diff --git a/.cargo/config.toml b/.cargo/config.toml index 2ccbcc61a3..7538a50cb0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -6,10 +6,17 @@ xtask = "run -p xtask --" [target.wasm32-unknown-unknown] rustflags = ["-C", "target-feature=+simd128"] +[env] # aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU when `main` asks it to # (`pdfcraft_sign::init_crypto`), not in a static initializer before `main`. On x86 it reads # `OPENSSL_ia32cap` then, and aborts when that asks for a feature the processor lacks; each # executable first runs itself again without the variable (#2916, `pdfcraft_platform::crypto_env`), # which it can only do once `main` runs. -[env] AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER" + +# The optional craft-fonts build input (the Japanese face and the other UI faces; see +# crates/fonts/build.rs). A plain build embeds nothing and prints no warning, so a local build +# embeds a craft-fonts checkout next to this repository when there is one. A `CRAFT_FONTS_DIR` +# already in the environment wins (CI sets its own), and a missing checkout only gives the +# "building without craft-fonts" warning. +CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true } diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 0000000000..5a37234d75 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,117 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/pdfcraft", + "repository_id": 1398086162, + "producer_workflow_id": 434362399, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "main", + "release_branch": "nightly-signer", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "pdfcraft-nightly-20261129-initial", + "repository": "storytold/pdfcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 372163538, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_pdfcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_pdfcraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [ + "github-actions[bot]" + ], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d13972d7d8..0f33bde866 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,12 +40,17 @@ jobs: # egui/winit/rfd, and the independent oracles (crates/oracle). packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev - libgtk-3-dev qpdf poppler-utils + libgtk-3-dev qpdf poppler-utils xvfb libxkbcommon-x11-0 # cargo-deny for the deny step of `cargo xtask ci`, which requires it under CI. tools: cargo-nextest@0.9.150,cargo-deny@0.20.2 # A missing oracle fails the job instead of printing a skip notice that reads as a pass. linux-env: PDFCRAFT_ORACLES_REQUIRED=1 - windows-env: PDFCRAFT_REQUIRE_WINRES=1 + # One KEY=VALUE per line. No debug info on Windows: a cold-cache gate built it for every + # dependency and spent the 90-minute cap compiling before the tests started. + windows-env: | + PDFCRAFT_REQUIRE_WINRES=1 + CARGO_PROFILE_DEV_DEBUG=0 + CARGO_PROFILE_TEST_DEBUG=0 # Windows completed its 54m33s gate, then cache save hit the default 60m job cap # (run 44364342368). Leave bounded room for setup and post-job cleanup. # This changes no test watchdog or selection; craft-common-actions#60. @@ -54,7 +59,7 @@ jobs: command: | pwsh -NoProfile -File packaging/windows/test-font-notices.ps1 cargo xtask ci - # Windows checks what differs by platform: the build (with resources) and the tests. + # Windows checks what differs by platform: the build (with resources) and the tests. Clippy + # runs on Linux in `cargo xtask ci`; lints don't differ by platform. windows-command: | - cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 268da70ca1..65745e5350 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -2,16 +2,19 @@ # (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter. name: FreeBSD +# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every push +# or dependency change: a drifted dependency still shows up within a day, and always before a +# release ships. PRs that change the FreeBSD packaging itself still run it. on: + schedule: + - cron: "27 3 * * *" push: - branches: [main] + branches: [release] pull_request: paths: - - Cargo.toml - - Cargo.lock - - "**/Cargo.toml" - .github/workflows/freebsd.yml - packaging/freebsd/** + - packaging/env.sh workflow_dispatch: concurrency: @@ -27,3 +30,4 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + cargo-test-extra-args: --no-fail-fast diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 0000000000..eb59dcc8b3 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [PdfCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # Transport only: exact repository and workflow_run event guard. + if: >- + github.repository == 'storytold/pdfcraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected signer-branch validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/pdfcraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/pdfcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/pdfcraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + run_id, attempt = producer.get('id'), producer.get('run_attempt') + require(type(run_id) is int and run_id > 0, 'invalid producer run id') + require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { + 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) + }}).encode('utf-8') + request = urllib.request.Request( + 'https://api.github.com/repos/storytold/pdfcraft/actions/workflows/nightly-sign.yml/dispatches', + data=body, method='POST', headers={ + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'pdfcraft-nightly-dispatch' + }) + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + require(response.status == 204, 'dispatch was not accepted') + print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 0000000000..6c528c13be --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,59 @@ +name: PdfCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: pdfcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. + if: >- + github.repository == 'storytold/pdfcraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main + with: + tooling-revision: main + app-name: pdfcraft + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the release environment and export its keys; that environment must + # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..200f4c7cc9 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,35 @@ +name: PdfCraft unsigned nightly + +# Scheduled nightly at 08:00 UTC, plus supervised manual runs by the reviewed manual actors. +# Completed scheduled runs are transported to the protected signer branch by nightly-dispatch.yml. +on: + schedule: + - cron: '0 8 * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/pdfcraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main + with: + tooling-revision: main + app-name: pdfcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # One producer run builds every listed platform for one all-or-nothing release. + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 0000000000..3dc8eaf4ac --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1d663ce54a..8c24f74cf3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,6 +37,7 @@ jobs: dry-run: ${{ github.event_name == 'schedule' }} app-name: pdfcraft app-title: PdfCraft + macos-runner: macos-15 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 version: ${{ inputs.version }} contributors-artifact: ${{ needs.credits.outputs.artifact-name }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index b61e492591..2f270cebc6 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -10,7 +10,7 @@ permissions: contents: read concurrency: - group: sonarcloud-${{ github.ref }} + group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} # A push to main is the run that publishes coverage; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} @@ -19,6 +19,8 @@ jobs: # Tracked at @main so org-wide CI improvements propagate without PR churn. uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: + coverage-application-binaries: pdfcraft + linux-test-packages: xvfb libxkbcommon-x11-0 # Same craft-fonts commit as ci.yml and release.yml. fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 secrets: inherit diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index f3e2b20c7e..6228a88155 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -3,19 +3,17 @@ # run the test suite natively on ARM64. name: Windows ARM64 +# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a +# day, and always before a release ships), and on PRs that change the Windows packaging itself. on: + schedule: + - cron: "43 5 * * *" push: - branches: [main] + branches: [release] pull_request: paths: - - Cargo.toml - - Cargo.lock - - "**/Cargo.toml" - - "**/build.rs" - .github/workflows/windows-arm64.yml - packaging/windows/** - schedule: - - cron: "41 4 * * 1" # weekly, so drift in the runner images shows up workflow_dispatch: concurrency: diff --git a/AGENTS.md b/AGENTS.md index 29e6fba85b..81ca8809a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,7 +81,7 @@ For the crates you changed: `cargo fmt --check`, `cargo clippy -p -- -D - The workspace sets `unsafe_code = "forbid"`; no module allows `unsafe`. `[lints] workspace = true` in every crate. - Hostile-input sweep: `crates/automation/tests/it/hostile_args.rs`. The last-resort `catch_unwind` guards are in `crates/engine/src/doc_state.rs` and `crates/ui-egui/src/frame_guard.rs`. - Attribution: `ATTRIBUTION.toml` is the source (one entry per asset, SHA-256 each); `ATTRIBUTION.md` is generated by `cargo xtask assets --write`. The ArtCraft logos in `docs/brand/` are trademark assets under `docs/brand/LICENSE-brand.txt`. -- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped). +- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; `.cargo/config.toml` points it at `../craft-fonts`, and a `CRAFT_FONTS_DIR` in the environment wins; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped). - Automation: every feature is a tool in `crates/automation` (`pdfcraft-cli run` and `pdfcraft-cli mcp` share the table; see `crates/automation/README.md`). MCP and the UI control channel are opt-in. The control channel runs only with `--control `, binds to loopback and authenticates with a token (`--control-token`, or an owner-only file named by `--control-token-file`, which `craft_platform::owner_only` sets and checks); never enable it by default or log the token. - Page modules register `PagePart`s (`canvas/page_parts.rs`) and act through the tool host (`canvas/page_tools.rs`). Keys and clipboard events are commands and tool claims, and the framework blocks both while a modal is open. - Large binary test oracles live in storytold/photocraft-corpus, not here; `cargo xtask corpus` fetches the pdf.js corpus pinned by commit and SHA-256. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c2817fbcb7..c4dd3bfd95 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,7 +4,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE). -## In this repository (136) +## In this repository (144) | Asset | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---| @@ -25,6 +25,8 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/icons/braces.svg` | Lucide icon "braces" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/braces.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/camera.svg` | Lucide icon "camera" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/camera.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/check-circle-2.svg` | Lucide icon "check-circle-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check-circle-2.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | +| `assets/icons/chevrons-down.svg` | Lucide icon "chevrons-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-down.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | +| `assets/icons/chevrons-up.svg` | Lucide icon "chevrons-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-up.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | Source of the path data that crates/sign/src/status_layers.rs draws into displayed signature status layers; the UI draws this icon from the built-in catalogue | | `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/clock-3.svg` | Lucide icon "clock-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock-3.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | @@ -50,6 +52,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/icons/film.svg` | Lucide icon "film" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/film.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/filter.svg` | Lucide icon "filter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/filter.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/folder-plus.svg` | Lucide icon "folder-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-plus.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | +| `assets/icons/freehand-highlighter.svg` | Freehand highlighter | Combiler01 | CC0-1.0 | https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/git-compare.svg` | Lucide icon "git-compare" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/git-compare.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/hash.svg` | Lucide icon "hash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hash.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/heading.svg` | Lucide icon "heading" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/heading.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | @@ -66,6 +69,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/icons/minimize-2.svg` | Lucide icon "minimize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize-2.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/paperclip.svg` | Lucide icon "paperclip" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paperclip.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/pen-line.svg` | Lucide icon "pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | +| `assets/icons/pin-off.svg` | Lucide icon "pin-off" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin-off.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/presentation.svg` | Lucide icon "presentation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/presentation.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/printer.svg` | Lucide icon "printer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/printer.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | | `assets/icons/replace.svg` | Lucide icon "replace" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/replace.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs | @@ -103,6 +107,10 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/app-icon/pdfcraft-1024.png` | PdfCraft app icon, 1024 px on Apple's icon grid | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs) | | `assets/app-icon/pdfcraft.icns` | PdfCraft app icon (macOS .icns) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | macOS app bundle icon | | `assets/app-icon/pdfcraft.ico` | PdfCraft app icon (Windows .ico, 16-256 px) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab) | +| `assets/app-icon/pdfcraft-nightly-1024.png` | PdfCraft Nightly app icon, 1024 px on Apple's icon grid | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs) | +| `assets/app-icon/pdfcraft-nightly.icns` | PdfCraft Nightly app icon (macOS .icns) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh) | +| `assets/app-icon/pdfcraft-nightly.ico` | PdfCraft Nightly app icon (Windows .ico, 16-256 px) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs | +| `assets/app-icon/pdfcraft-nightly.png` | PdfCraft Nightly app icon (256 px PNG) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly | | `assets/app-icon/pdfcraft-document.svg` | PdfCraft PDF document icon (master vector) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Master artwork for the Windows PDF file type icon; rendered by packaging/icons.sh, without fonts or external images | | `assets/app-icon/pdfcraft-document.ico` | PdfCraft PDF document icon (Windows .ico, 16-256 px) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Embedded in pdfcraft.exe as resource 2; the Windows installer uses it for PdfCraft.Document and Applications/pdfcraft.exe PDF file associations | | `assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 16 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) | diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index eaa38061a4..88136e3abb 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -197,6 +197,28 @@ kind = "icon" usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" sha256 = "765ebd1031367e2fd2a940b62f4402fac8976dea0210b0e3b1e59a2c75897928" +[[asset]] +path = "assets/icons/chevrons-down.svg" +title = "Lucide icon \"chevrons-down\"" +author = "Lucide Contributors (portions Cole Bemis, Feather)" +source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-down.svg)" +licence = "ISC AND MIT" +licence_file = "assets/icons/LICENSE-lucide.txt" +kind = "icon" +usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" +sha256 = "f6fb7f1c3d539665c0d4c6ea5c13436ef1eb1a0df8e6c9f0de65fb960cc27083" + +[[asset]] +path = "assets/icons/chevrons-up.svg" +title = "Lucide icon \"chevrons-up\"" +author = "Lucide Contributors (portions Cole Bemis, Feather)" +source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-up.svg)" +licence = "ISC AND MIT" +licence_file = "assets/icons/LICENSE-lucide.txt" +kind = "icon" +usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" +sha256 = "36890150a699c3c16fbc28fce1ee2582c0b74c7fe3f4ff30c6917960933051af" + [[asset]] path = "assets/icons/circle-check.svg" title = "Lucide icon \"circle-check\"" @@ -472,6 +494,17 @@ kind = "icon" usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" sha256 = "76d62eb7796ce6c7e303c437464923de2d1ae19a5c8d010f8b36dfc1d6180890" +[[asset]] +path = "assets/icons/freehand-highlighter.svg" +title = "Freehand highlighter" +author = "Combiler01" +source = "https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg" +licence = "CC0-1.0" +licence_file = "assets/icons/LICENSE-freehand-highlighter.txt" +kind = "icon" +usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" +sha256 = "6198c9cbdb182132b00ad25e8782ac7c7d237d0736c1d1c1f2f94dd6b8b87132" + [[asset]] path = "assets/icons/git-compare.svg" title = "Lucide icon \"git-compare\"" @@ -648,6 +681,17 @@ kind = "icon" usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" sha256 = "195939cbf88689334dc3a9d64bd0b3f459ce1de7d71e53620f6b0448b958f9c8" +[[asset]] +path = "assets/icons/pin-off.svg" +title = "Lucide icon \"pin-off\"" +author = "Lucide Contributors (portions Cole Bemis, Feather)" +source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin-off.svg)" +licence = "ISC AND MIT" +licence_file = "assets/icons/LICENSE-lucide.txt" +kind = "icon" +usage = "UI icon, embedded via crates/ui-egui/src/icons.rs" +sha256 = "4c9c29a91905ccc7473f7c62061092abab0c89697f9ab7f7041631a53720d67a" + [[asset]] path = "assets/icons/presentation.svg" title = "Lucide icon \"presentation\"" @@ -1605,6 +1649,50 @@ kind = "icon" usage = "Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab)" sha256 = "709271d66e07710a3f785ea21b0c85c5228eaf8bebe5058bc0f71f9ef20749eb" +[[asset]] +path = "assets/app-icon/pdfcraft-nightly-1024.png" +title = "PdfCraft Nightly app icon, 1024 px on Apple's icon grid" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs)" +sha256 = "7a9ef45c0a3239584f28517740587a8ab029c11bd1462ea708e5875c96e2fe53" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.icns" +title = "PdfCraft Nightly app icon (macOS .icns)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh)" +sha256 = "51392518f539474c67aa3aa6e119eb814ea9aa221e0841baf90f8ebb1c168e8d" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.ico" +title = "PdfCraft Nightly app icon (Windows .ico, 16-256 px)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs" +sha256 = "b984192f9417a11a5f7fbfdbaaaf1a1f2a33cb714e7fa2079aa4be01ac2f6c17" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.png" +title = "PdfCraft Nightly app icon (256 px PNG)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly" +sha256 = "d73ed05f534074cd0cc267fcfcac07b66919331d4331c060521721b77e00b800" + [[asset]] path = "assets/app-icon/pdfcraft-document.svg" title = "PdfCraft PDF document icon (master vector)" diff --git a/Cargo.lock b/Cargo.lock index 1f28260958..1c15e7ec8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -336,9 +336,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -1136,9 +1136,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-atomic", "craft-automation", @@ -1405,7 +1405,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "rustix 1.1.6", ] @@ -1413,7 +1413,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1438,7 +1438,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-docpath", @@ -1474,12 +1474,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "egui", ] @@ -1487,7 +1487,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "md-5 0.10.6", "rayon", @@ -1496,12 +1496,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-cms", @@ -1521,7 +1521,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "getrandom 0.3.4", "serde", @@ -1531,7 +1531,7 @@ dependencies = [ [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "thiserror 2.0.21", ] @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "rayon", ] @@ -1547,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1572,7 +1572,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "serde", ] @@ -1580,7 +1580,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "base64 0.23.1", "chrono", @@ -1600,7 +1600,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "chrono", "craft-xml", @@ -1631,7 +1631,7 @@ dependencies = [ [[package]] name = "craft-flow" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-wordmodel", "image", @@ -1641,7 +1641,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1656,7 +1656,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1675,7 +1675,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "cap-primitives", "craft-atomic", @@ -1696,12 +1696,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1714,7 +1714,7 @@ dependencies = [ [[package]] name = "craft-html" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-mime", ] @@ -1722,7 +1722,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "chrono", "fixed_decimal", @@ -1750,7 +1750,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-dds", "craft-jpeg", @@ -1777,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1795,7 +1795,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "thiserror 2.0.21", ] @@ -1803,7 +1803,7 @@ dependencies = [ [[package]] name = "craft-jsonrpc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "serde_json", ] @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-host", "craft-i18n", @@ -1826,7 +1826,7 @@ dependencies = [ [[package]] name = "craft-markdown" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-flow", "craft-html", @@ -1836,7 +1836,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-xml", "roxmltree 0.21.2", @@ -1846,7 +1846,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "serde_json", ] @@ -1854,7 +1854,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -1872,7 +1872,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1884,7 +1884,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "encoding_rs", "image", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "chardetng", "chrono", @@ -1903,10 +1903,19 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8945bdb09b36245a1d442438ce8876377ef430d0#8945bdb09b36245a1d442438ce8876377ef430d0" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "aes", "base64 0.23.1", @@ -1923,7 +1932,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-xml", "craft-zip", @@ -1934,7 +1943,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-keymap", @@ -1950,7 +1959,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "aes", "bytemuck", @@ -1973,7 +1982,7 @@ dependencies = [ [[package]] name = "craft-pkcs7" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "aes", "aws-lc-rs", @@ -2005,7 +2014,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "arboard", "async-channel", @@ -2040,7 +2049,7 @@ dependencies = [ [[package]] name = "craft-pptx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-drawingml", "craft-opc", @@ -2055,7 +2064,7 @@ dependencies = [ [[package]] name = "craft-prc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2064,7 +2073,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -2088,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "dispatch2", "egui", @@ -2101,7 +2110,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2120,7 +2129,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-codepage", "craft-flow", @@ -2133,7 +2142,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-atomic", "craft-host", @@ -2150,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "fax", "hayro-ccitt", @@ -2161,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-xml", "flate2", @@ -2178,7 +2187,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2190,7 +2199,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2215,7 +2224,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2230,7 +2239,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-atomic", "craft-behavior", @@ -2245,7 +2254,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2255,7 +2264,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2264,7 +2273,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2279,12 +2288,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2298,7 +2307,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-i18n", @@ -2314,7 +2323,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "accesskit", "craft-behavior", @@ -2352,7 +2361,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2363,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -2381,7 +2390,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -2402,7 +2411,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -2423,7 +2432,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-behavior", "craft-host", @@ -2442,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "chrono", "craft-host", @@ -2471,7 +2480,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "js-sys", "serde_json", @@ -2482,7 +2491,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-host", "craft-platform", @@ -2494,7 +2503,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "winsafe", ] @@ -2502,7 +2511,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-atomic", "craft-behavior", @@ -2532,7 +2541,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "base64 0.23.1", "craft-math", @@ -2546,7 +2555,7 @@ dependencies = [ [[package]] name = "craft-xfa" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-xml", ] @@ -2554,7 +2563,7 @@ dependencies = [ [[package]] name = "craft-xfdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "craft-xml", "thiserror 2.0.21", @@ -2563,7 +2572,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2573,7 +2582,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2707,9 +2716,9 @@ checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -3669,9 +3678,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -4142,7 +4151,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "bytemuck", "hayro-interpret", @@ -4162,7 +4171,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "brotli", "hayro-postscript", @@ -4171,7 +4180,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4189,7 +4198,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4207,12 +4216,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "flate2", "hayro-ccitt", @@ -5081,7 +5090,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6150,9 +6159,10 @@ dependencies = [ [[package]] name = "pdfcraft" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft", + "craft-nightly", "craft-update", "eframe", "egui", @@ -6164,6 +6174,7 @@ dependencies = [ "pdfcraft-ui-egui", "pollster 1.0.1", "raw-window-handle", + "rfd", "serde_json", "uds_windows", "wayland-client", @@ -6175,7 +6186,7 @@ dependencies = [ [[package]] name = "pdfcraft-a11y" -version = "0.22.0" +version = "0.23.1" dependencies = [ "pdfcraft-content", "pdfcraft-cos", @@ -6186,7 +6197,7 @@ dependencies = [ [[package]] name = "pdfcraft-annot" -version = "0.22.0" +version = "0.23.1" dependencies = [ "hayro-syntax", "pdfcraft-cos", @@ -6199,7 +6210,7 @@ dependencies = [ [[package]] name = "pdfcraft-audit" -version = "0.22.0" +version = "0.23.1" dependencies = [ "pdfcraft-content", "pdfcraft-cos", @@ -6210,7 +6221,7 @@ dependencies = [ [[package]] name = "pdfcraft-automation" -version = "0.22.0" +version = "0.23.1" dependencies = [ "base64 0.23.1", "craft", @@ -6239,7 +6250,7 @@ dependencies = [ [[package]] name = "pdfcraft-cli" -version = "0.22.0" +version = "0.23.1" dependencies = [ "base64 0.23.1", "craft", @@ -6257,11 +6268,11 @@ dependencies = [ [[package]] name = "pdfcraft-compare" -version = "0.22.0" +version = "0.23.1" [[package]] name = "pdfcraft-content" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-pdf", "hayro-syntax", @@ -6269,7 +6280,7 @@ dependencies = [ [[package]] name = "pdfcraft-cos" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-pdf", "hayro-syntax", @@ -6283,7 +6294,7 @@ dependencies = [ [[package]] name = "pdfcraft-create" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-image-codecs", "craft-jpeg", @@ -6303,7 +6314,7 @@ dependencies = [ [[package]] name = "pdfcraft-crypt" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-pdf", "proptest", @@ -6311,7 +6322,7 @@ dependencies = [ [[package]] name = "pdfcraft-edit" -version = "0.22.0" +version = "0.23.1" dependencies = [ "hayro-syntax", "icu_segmenter", @@ -6330,7 +6341,7 @@ dependencies = [ [[package]] name = "pdfcraft-engine" -version = "0.22.0" +version = "0.23.1" dependencies = [ "chrono", "craft-cms", @@ -6377,7 +6388,7 @@ dependencies = [ [[package]] name = "pdfcraft-export" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-docx", "craft-html", @@ -6394,7 +6405,7 @@ dependencies = [ [[package]] name = "pdfcraft-filters" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-pdf", "proptest", @@ -6403,7 +6414,7 @@ dependencies = [ [[package]] name = "pdfcraft-fonts" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-fonts-build", "craft-pdf", @@ -6415,7 +6426,7 @@ dependencies = [ [[package]] name = "pdfcraft-forms" -version = "0.22.0" +version = "0.23.1" dependencies = [ "hayro-syntax", "pdfcraft-content", @@ -6428,11 +6439,11 @@ dependencies = [ [[package]] name = "pdfcraft-geom" -version = "0.22.0" +version = "0.23.1" [[package]] name = "pdfcraft-js" -version = "0.22.0" +version = "0.23.1" dependencies = [ "boa_engine", "chrono", @@ -6440,7 +6451,7 @@ dependencies = [ [[package]] name = "pdfcraft-measure" -version = "0.22.0" +version = "0.23.1" dependencies = [ "pdfcraft-annot", "pdfcraft-content", @@ -6453,14 +6464,14 @@ dependencies = [ [[package]] name = "pdfcraft-model" -version = "0.22.0" +version = "0.23.1" dependencies = [ "pdfcraft-cos", ] [[package]] name = "pdfcraft-ocr" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-image-codecs", "ocrs", @@ -6475,7 +6486,7 @@ dependencies = [ [[package]] name = "pdfcraft-ocr-worker" -version = "0.22.0" +version = "0.23.1" dependencies = [ "js-sys", "pdfcraft-ocr", @@ -6485,7 +6496,7 @@ dependencies = [ [[package]] name = "pdfcraft-optimize" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-image-codecs", "craft-jpeg", @@ -6503,22 +6514,23 @@ dependencies = [ [[package]] name = "pdfcraft-oracle" -version = "0.22.0" +version = "0.23.1" [[package]] name = "pdfcraft-organize" -version = "0.22.0" +version = "0.23.1" dependencies = [ "hayro-syntax", "pdfcraft-content", "pdfcraft-cos", + "pdfcraft-model", "pdfcraft-oracle", "thiserror 2.0.21", ] [[package]] name = "pdfcraft-platform" -version = "0.22.0" +version = "0.23.1" dependencies = [ "async-channel", "futures-lite", @@ -6529,7 +6541,7 @@ dependencies = [ [[package]] name = "pdfcraft-prc-render" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-prc", "flate2", @@ -6538,7 +6550,7 @@ dependencies = [ [[package]] name = "pdfcraft-preflight" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-cms", "craft-xml", @@ -6550,7 +6562,7 @@ dependencies = [ [[package]] name = "pdfcraft-print" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft-cms", "craft-print", @@ -6566,7 +6578,7 @@ dependencies = [ [[package]] name = "pdfcraft-redact" -version = "0.22.0" +version = "0.23.1" dependencies = [ "aho-corasick", "craft-xml", @@ -6590,7 +6602,7 @@ dependencies = [ [[package]] name = "pdfcraft-render" -version = "0.22.0" +version = "0.23.1" dependencies = [ "bytemuck", "craft-pdf", @@ -6615,7 +6627,7 @@ dependencies = [ [[package]] name = "pdfcraft-sign" -version = "0.22.0" +version = "0.23.1" dependencies = [ "aes", "aws-lc-rs", @@ -6655,11 +6667,11 @@ dependencies = [ [[package]] name = "pdfcraft-testkit" -version = "0.22.0" +version = "0.23.1" [[package]] name = "pdfcraft-ui-egui" -version = "0.22.0" +version = "0.23.1" dependencies = [ "arboard", "base64 0.23.1", @@ -6695,6 +6707,7 @@ dependencies = [ "pdfcraft-ocr", "pdfcraft-platform", "pdfcraft-render", + "pdfcraft-testkit", "pdfcraft-xfa", "plist", "proptest", @@ -6718,7 +6731,7 @@ dependencies = [ [[package]] name = "pdfcraft-web" -version = "0.22.0" +version = "0.23.1" dependencies = [ "craft", "craft-web-api", @@ -6734,7 +6747,7 @@ dependencies = [ [[package]] name = "pdfcraft-xfa" -version = "0.22.0" +version = "0.23.1" dependencies = [ "base64 0.23.1", "craft-image-codecs", @@ -6748,7 +6761,7 @@ dependencies = [ [[package]] name = "pdfcraft-xfdf" -version = "0.22.0" +version = "0.23.1" dependencies = [ "base64 0.23.1", "craft-csv", @@ -8943,7 +8956,7 @@ 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.6", "windows-sys 0.61.2", @@ -9486,9 +9499,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -10407,7 +10420,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", @@ -11119,4 +11132,4 @@ source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d9 [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=0a6e42b80bfd586aee6ee1144aa98cf1ea37a844#0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" diff --git a/Cargo.toml b/Cargo.toml index 264fa810a5..77d52682f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["vendor"] default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"] [workspace.package] -version = "0.22.0" +version = "0.23.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -13,92 +13,94 @@ repository = "https://github.com/storytold/pdfcraft" [workspace.dependencies] # The framework facade: every framework crate is reached through it (contract head); its features pick the crates. -craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false } -craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false } +craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # Small, revision-bound UI drafts; the existing engine remains the owner of PDF edits/history. edit-session = { path = "vendor/edit-session", version = "=0.1.0-alpha.2" } # Shared frontend components; engines remain independent of egui. -craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # 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 = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # 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 = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false } +craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft-ui. -craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # Shared system spooler; document composition remains in pdfcraft-print. -craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # ICC transforms for app-managed print colour; at craft-print's commit, so one craft-libs checkout. -craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # 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 = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # The installed-font catalog the engine reads faces from (Edit ▸ Add text, font embedding). -craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false } +craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false } # The craft-fonts manifest parser and `EmbeddedFace`, the face table the interface font stack takes; already in the # tree through craft-ui. -craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # 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 = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", features = ["ui"] } -craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", features = ["cos", "crypt", "filters", "fonts"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["ui"] } +craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["cos", "crypt", "filters", "fonts"] } # The writers the Word and RTF exports map onto (storytold/craft-libs#793), at storytold/craft-libs#1467: # its font and colour lookups take constant time, as PdfCraft's own writer did. craft-rtf, craft-wordmodel and # craft-docx move together: craft_rtf::doc::export takes its own revision's Document. -craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency. -craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } # Shared MCP stdio framing and JSON-RPC 2.0 envelopes (storytold/craft-libs#778). -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" } # internal -pdfcraft-geom = { path = "crates/geom", version = "0.22.0" } -pdfcraft-filters = { path = "crates/filters", version = "0.22.0" } -pdfcraft-cos = { path = "crates/cos", version = "0.22.0" } -pdfcraft-crypt = { path = "crates/crypt", version = "0.22.0" } -pdfcraft-organize = { path = "crates/organize", version = "0.22.0" } -pdfcraft-measure = { path = "crates/measure", version = "0.22.0" } -pdfcraft-annot = { path = "crates/annot", version = "0.22.0" } -pdfcraft-audit = { path = "crates/audit", version = "0.22.0" } -pdfcraft-fonts = { path = "crates/fonts", version = "0.22.0" } -pdfcraft-model = { path = "crates/model", version = "0.22.0" } -pdfcraft-content = { path = "crates/content", version = "0.22.0" } -pdfcraft-redact = { path = "crates/redact", version = "0.22.0" } -pdfcraft-print = { path = "crates/print", version = "0.22.0" } -pdfcraft-xfdf = { path = "crates/xfdf", version = "0.22.0" } -pdfcraft-sign = { path = "crates/sign", version = "0.22.0" } -pdfcraft-optimize = { path = "crates/optimize", version = "0.22.0" } -pdfcraft-a11y = { path = "crates/a11y", version = "0.22.0" } -pdfcraft-oracle = { path = "crates/oracle", version = "0.22.0" } -pdfcraft-testkit = { path = "crates/testkit", version = "0.22.0" } -pdfcraft-ocr = { path = "crates/ocr", version = "0.22.0" } -pdfcraft-js = { path = "crates/js", version = "0.22.0" } -pdfcraft-compare = { path = "crates/compare", version = "0.22.0" } -pdfcraft-preflight = { path = "crates/preflight", version = "0.22.0" } -pdfcraft-export = { path = "crates/export", version = "0.22.0" } -pdfcraft-edit = { path = "crates/edit", version = "0.22.0" } -pdfcraft-create = { path = "crates/create", version = "0.22.0" } -pdfcraft-forms = { path = "crates/forms", version = "0.22.0" } -pdfcraft-xfa = { path = "crates/xfa", version = "0.22.0" } -pdfcraft-render = { path = "crates/render", version = "0.22.0" } -pdfcraft-engine = { path = "crates/engine", version = "0.22.0" } -pdfcraft-platform = { path = "crates/platform", version = "0.22.0" } -pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.22.0" } -pdfcraft-automation = { path = "crates/automation", version = "0.22.0", default-features = false } -pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -pdfcraft-prc-render = { path = "crates/prc-render", version = "0.22.0" } +pdfcraft-geom = { path = "crates/geom", version = "0.23.1" } +pdfcraft-filters = { path = "crates/filters", version = "0.23.1" } +pdfcraft-cos = { path = "crates/cos", version = "0.23.1" } +pdfcraft-crypt = { path = "crates/crypt", version = "0.23.1" } +pdfcraft-organize = { path = "crates/organize", version = "0.23.1" } +pdfcraft-measure = { path = "crates/measure", version = "0.23.1" } +pdfcraft-annot = { path = "crates/annot", version = "0.23.1" } +pdfcraft-audit = { path = "crates/audit", version = "0.23.1" } +pdfcraft-fonts = { path = "crates/fonts", version = "0.23.1" } +pdfcraft-model = { path = "crates/model", version = "0.23.1" } +pdfcraft-content = { path = "crates/content", version = "0.23.1" } +pdfcraft-redact = { path = "crates/redact", version = "0.23.1" } +pdfcraft-print = { path = "crates/print", version = "0.23.1" } +pdfcraft-xfdf = { path = "crates/xfdf", version = "0.23.1" } +pdfcraft-sign = { path = "crates/sign", version = "0.23.1" } +pdfcraft-optimize = { path = "crates/optimize", version = "0.23.1" } +pdfcraft-a11y = { path = "crates/a11y", version = "0.23.1" } +pdfcraft-oracle = { path = "crates/oracle", version = "0.23.1" } +pdfcraft-testkit = { path = "crates/testkit", version = "0.23.1" } +pdfcraft-ocr = { path = "crates/ocr", version = "0.23.1" } +pdfcraft-js = { path = "crates/js", version = "0.23.1" } +pdfcraft-compare = { path = "crates/compare", version = "0.23.1" } +pdfcraft-preflight = { path = "crates/preflight", version = "0.23.1" } +pdfcraft-export = { path = "crates/export", version = "0.23.1" } +pdfcraft-edit = { path = "crates/edit", version = "0.23.1" } +pdfcraft-create = { path = "crates/create", version = "0.23.1" } +pdfcraft-forms = { path = "crates/forms", version = "0.23.1" } +pdfcraft-xfa = { path = "crates/xfa", version = "0.23.1" } +pdfcraft-render = { path = "crates/render", version = "0.23.1" } +pdfcraft-engine = { path = "crates/engine", version = "0.23.1" } +pdfcraft-platform = { path = "crates/platform", version = "0.23.1" } +pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.23.1" } +pdfcraft-automation = { path = "crates/automation", version = "0.23.1", default-features = false } +pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +pdfcraft-prc-render = { path = "crates/prc-render", version = "0.23.1" } # pdf hayro = "0.7.1" @@ -180,14 +182,14 @@ unset_env = ["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "CRAFT_I18N_DIR", "CRAFT # BEGIN port-kit framework patch [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } @@ -202,7 +204,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } lopdf = { path = "vendor/lopdf" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } diff --git a/LICENSES.toml b/LICENSES.toml index 9f304f46f8..0bd09a6e0f 100644 --- a/LICENSES.toml +++ b/LICENSES.toml @@ -16,7 +16,7 @@ sha256 = "cd7032ea33b71427f188e34ffb4aee9d6868a57fd196037c5c8b2be03a2a0352" [[document]] source = "NOTICE" destination = "NOTICE" -sha256 = "ac29fe01fc951570ebda159bc84b17f12129e3f0800c36759e2f4829c10d8685" +sha256 = "c0cd7347f4c596dc01ac7fdc4aca323b6ba97385eb399bc5dd40e460bacf247d" [[document]] source = "vendor/edit-session/LICENSE-MIT" @@ -55,6 +55,11 @@ source = "assets/fonts/OFL-JetBrainsMono.txt" destination = "assets/fonts/OFL-JetBrainsMono.txt" sha256 = "a76abf002c49097d146e86740a3105a5d00450b1592e820a1109a8c5680cd697" +[[document]] +source = "assets/icons/LICENSE-freehand-highlighter.txt" +destination = "assets/icons/LICENSE-freehand-highlighter.txt" +sha256 = "83cba0ac883f6ef4866e457536bf58727a5702ebf6e7b407579e4f1863ca4c7d" + [[document]] source = "assets/icons/LICENSE-lucide.txt" destination = "assets/icons/LICENSE-lucide.txt" diff --git a/NOTICE b/NOTICE index 2e5d0077f2..2c408b1a11 100644 --- a/NOTICE +++ b/NOTICE @@ -14,11 +14,12 @@ Third-party material This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in ATTRIBUTION.md. -- Lucide icons (assets/icons/*.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt. +- Lucide icons (assets/icons/*.svg, except freehand-highlighter.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt. The Windows PDF file icon (assets/app-icon/pdfcraft-document.svg and .ico) adapts Lucide's file-text outline and combines it with contributor-original artwork. See assets/app-icon/LICENSE-document.txt (ISC AND (MIT OR Apache-2.0)), packaged as LICENSE-document.txt beside the Windows executables. +- Freehand highlighter icon (assets/icons/freehand-highlighter.svg) — CC0-1.0, Combiler01. See assets/icons/LICENSE-freehand-highlighter.txt. - Inter typeface (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt. - JetBrains Mono typeface (assets/fonts/JetBrainsMono-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt. - Dancing Script typeface (assets/fonts/DancingScript.ttf), Copyright 2016 The Dancing Script Project Authors — SIL Open Font License 1.1 (Reserved Font Name "Dancing Script"). See assets/fonts/OFL-DancingScript.txt. diff --git a/README.md b/README.md index 3492a2e27c..3763d32ecc 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ PdfCraft is part of [ArtCraft](https://getartcraft.com). Come say hello, get help and follow development: - **Discord: [discord.gg/artcraft](https://discord.gg/artcraft)**. This is the fastest way to get help and share feedback. The app has a Discord button in its title bar. +- [Collect a Windows startup log](docs/windows-renderer-startup.md#if-the-window-freezes-at-startup) if the app opens a frozen window. - **Web page:** [getartcraft.com/apps/pdfcraft](https://getartcraft.com/apps/pdfcraft) - **Source:** [github.com/storytold/pdfcraft](https://github.com/storytold/pdfcraft) diff --git a/ROADMAP.md b/ROADMAP.md index a7fdc2e38a..417071098a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,8 @@ - 2026-11-04 (M6, PR #5699 reset estimate): Charge expanded-name scans and field-name copy/comparison bytes; add three negative regressions and byte-exact refusal checks. # PdfCraft roadmap +> **Last reviewed:** 2026-11-04 | **Last updated:** 2026-11-04 | **Change:** minor (M7: paragraph boundaries respect row typography and page-wide filled panels; estimates unchanged) + > **Last reviewed:** 2026-11-16 | **Last updated:** 2026-11-16 | **Change:** patch (M5 #3741: Ctrl+M opens Comments on Windows/Linux without toggling it closed; macOS leaves Command+M for Minimize; platform-specific shortcut surfaces and regressions retained; estimates unchanged) > **Last reviewed:** 2026-11-15 | **Last updated:** 2026-11-15 | **Change:** minor (craft-libs cutover for codecs, XFA XML, crypt/filters/COS/export/XFDF, PRC and ZIP; print colour management for pictures; M7 line replacement keeps source fonts; auto-tag headings by size and weight; arrow-key comment moves; stream-filter JPEG export; form, signature, optimize, redaction, measurement, PRC-normal and CMYK fixes; v0.21.1 Flatpak fix; estimates unchanged) @@ -264,6 +266,9 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md | 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 | ## Progress log +- **2026-10-16 (M4, Insert from File):** Catalog attachments come along with inserted pages in the same undo step. Existing attachments and destination name trees stay; duplicate UTF-16 keys keep their encoding. Generated engine regressions cover save/undo/redo and failed-batch rollback. Estimates unchanged. + +- **2026-11-18 (M7, #7687):** PDF-page watermarks clip the source CropBox to MediaBox before sizing and rotating the imported form. Synthetic geometry and save/reopen render regressions cover oversized and partially overlapping crops; estimates unchanged. - **2026-11-16 (M5, #3741):** Ctrl+M opens Comments on Windows/Linux and repeated activation keeps it open. macOS leaves Command+M unbound for Minimize. Dispatch, menus, palette, shortcut help and control/headless metadata resolve the platform-specific registry binding. Mapping and real-input regressions are retained through the rebase; estimates unchanged. - **2026-11-03 (M3, #3669):** A drag across a table selects its rows, as Preview does, instead of reading order's detour down each column; a cell padded with spaces reads with the next cell of its row. Synthetic render and UI drag regressions; estimates unchanged. @@ -301,6 +306,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged. - **2026-11-07 (M10, `ocr.ocr-web`, port onto #977):** Web OCR rebuilt on main's engines and preprocessing (#977). `OcrJob::run` is now `OcrJob::steps` a page at a time: the page renders, crops to the region and cleans each page, a Web Worker runs ocrs on the result, and `OcrShot::place` maps the words back through the region and preprocessing. Every strategy reads like this when only one engine is present, and the web build has only ocrs. The downloaded models are installed into the engine cache (`ocr::install`), so the Verify screen and the engine-status checks see them too. The batch keeps main's skipped-files bucket, low-confidence notes and cancel. The translations moved to craft-i18n (storytold/craft-i18n#141). The Verify screen starts the model download itself and runs once the models land; before, on a fresh page it failed with the desktop's "set PDFCRAFT_MODELS" message. Known limits: the cleaning steps, and the Verify screen's Run OCR and re-reads, run on the page. Estimates unchanged. +- **2026-11-04 (M7, paragraph boundaries):** Editable paragraphs separate across large row-size changes, font-family changes and filled rectangular panel boundaries, while compatible multiline text and inline style runs stay together. Panel identity is page-wide across content streams and transformed form invocations; rectangle construction/fill splits retain their transforms and path semantics. Synthetic regressions cover isolated-panel edits through save/reopen and preserve the delayed-background rewrite checks for #2377. Estimates unchanged. + - **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15. - **2026-11-03 (M5, #5850 review):** Resolve indirect IT when recognizing typewriter contents and Fill & Sign marks. Comment listing and property lookup retain their existing direct-Subtype behavior. A real double-click Edit composer preserves the typewriter’s text as written; ordinary comment edits keep trimming. Regressions cover direct Subtype with indirect intent, save/reopen, raw posted contents and same-index comments on different pages. The existing live-movement test now commits its setup with an outside click rather than Enter. Estimates unchanged. @@ -353,6 +360,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. 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-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged. +- **2026-10-25 (M4, #2725):** Dismissing the ordinary form-field reminder persists across launches, while security, repair and XFA notices keep their independent controls and defaults. Estimates unchanged. - **2026-10-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged. - **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. - **2026-10-25 (M10):** Vector printing keeps field and comment artwork whose rectangle coordinates are indirect, requiring exactly four finite resolved values. @@ -405,6 +413,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-23 (M2, #234, continuation of #1567):** Reconciled installed CJK viewer fallback with current rendering changes; Windows preserves installed Song/Hei/Kai families and bounds font reads. GBK-EUC-H CIDFontType2 regression coverage includes text extraction; viewer fallback also survives reload with retained preferences. System fonts remain display-only. No overall readiness estimate changed. - **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged. +- **2026-10-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents. Form editing and stream-aware readouts stay outside this fix. Estimates unchanged. - **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged. - **2026-10-20 (M9 #79 review, M2, M8):** text extraction reads a marked-content /ActualText that marks no glyph where it paints (paths and images, cut to what is visible, along the direction they are drawn), so words drawn as outlines can be found, copied and exported; OCR and scan field detection still count such a page as having no text of its own. Redaction strips /ActualText, /Alt, /E and /T from inline marked content around paint it clips, as it already did around paint it removed, so a partly redacted outlined word leaves no name in the file. Named-layer recognition also needs the layer form to draw n1 and n3. Estimates unchanged. @@ -425,6 +434,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set. - **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects. - **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged. +- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token, and the window opened without keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Checked by hand in a test build on GNOME 50 (Wayland): the busy cursor clears as the window appears, and the window has keyboard focus. Estimates unchanged. - **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged. - **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged. - **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged. diff --git a/apps/pdfcraft-cli/src/commands.rs b/apps/pdfcraft-cli/src/commands.rs index d170171ae4..05e5d022a3 100644 --- a/apps/pdfcraft-cli/src/commands.rs +++ b/apps/pdfcraft-cli/src/commands.rs @@ -1,6 +1,6 @@ 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, + COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, needs_value, positional, + validate_options, value_of_flag, }; use super::{Arc, CliError, ImageFormat, PageRenderer, Path, PathBuf, RenderConfig, RenderRequest, RequestKind, Write, inspect, stdout_line}; @@ -26,7 +26,7 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> { validate_options("info", args, INFO_OPTIONS)?; let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?; let bytes = read(path)?; - let password = flag(args, "--password"); + let password = value_of_flag("info", args, INFO_OPTIONS, "--password")?; // The renderer takes only the user password of R2–R4 files; `Session::open` takes either. let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password); let mut info = inspect(bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?; @@ -104,7 +104,7 @@ pub(crate) fn text(args: &[String]) -> Result<(), CliError> { options.next(); } } - let password = flag(args, "--password"); + let password = value_of_flag("text", args, TEXT_OPTIONS, "--password")?; let mut bytes = read(path)?; // The renderer takes only the user password of R2–R4 files; `Session::open` takes either. // Worked out from the file as read: `bytes` may become the session's display copy below. @@ -306,7 +306,7 @@ fn file_stem(path: &str) -> String { pub(crate) fn combine(args: &[String]) -> Result<(), CliError> { validate_options("combine", args, COMBINE_OPTIONS)?; - let out = flag(args, "--out").ok_or("combine: missing --out")?; + let out = value_of_flag("combine", args, COMBINE_OPTIONS, "--out")?.ok_or("combine: missing --out")?; let inputs = positional(args, COMBINE_OPTIONS); if inputs.len() < 2 { return Err("combine: give at least two input files".into()); @@ -319,10 +319,10 @@ pub(crate) fn combine(args: &[String]) -> Result<(), CliError> { pub(crate) fn extract(args: &[String]) -> Result<(), CliError> { validate_options("extract", args, EXTRACT_OPTIONS)?; let path = *positional(args, EXTRACT_OPTIONS).first().ok_or("extract: missing file")?; - let out = flag(args, "--out").ok_or("extract: missing --out")?; - let pages = page_list(flag(args, "--pages").ok_or("extract: missing --pages")?)?; + let out = value_of_flag("extract", args, EXTRACT_OPTIONS, "--out")?.ok_or("extract: missing --out")?; + let pages = page_list(value_of_flag("extract", args, EXTRACT_OPTIONS, "--pages")?.ok_or("extract: missing --pages")?)?; let mut session = pdfcraft_engine::Session::new(); - let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?; + let id = session.open(path, None, read(path)?, value_of_flag("extract", args, EXTRACT_OPTIONS, "--password")?).map_err(|e| e.to_string())?; let bytes = session.extract(id, &pages).map_err(|e| e.to_string())?; write_pdf(Path::new(out), &bytes) } @@ -331,7 +331,7 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> { validate_options("split", args, SPLIT_OPTIONS)?; use pdfcraft_engine::SplitBy; let path = *positional(args, SPLIT_OPTIONS).first().ok_or("split: missing file")?; - let by = match (flag(args, "--every"), flag(args, "--before")) { + let by = match (value_of_flag("split", args, SPLIT_OPTIONS, "--every")?, value_of_flag("split", args, SPLIT_OPTIONS, "--before")?) { (Some(n), None) => { // A count the splitter cannot hold is refused here, before the file is opened, // rather than silently clamped to 1 further down. @@ -345,9 +345,9 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> { (None, Some(list)) => SplitBy::Before(page_list(list)?), _ => return Err("split: give either --every N or --before PAGES".into()), }; - let dir = PathBuf::from(flag(args, "--out-dir").unwrap_or(".")); + let dir = PathBuf::from(value_of_flag("split", args, SPLIT_OPTIONS, "--out-dir")?.unwrap_or(".")); let mut session = pdfcraft_engine::Session::new(); - let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?; + let id = session.open(path, None, read(path)?, value_of_flag("split", args, SPLIT_OPTIONS, "--password")?).map_err(|e| e.to_string())?; let stem = file_stem(path); let parts = session.split(id, &by).map_err(|e| e.to_string())?; // An output folder that does not exist yet is created (#249); one that can't be is reported @@ -376,11 +376,15 @@ pub(crate) fn parse_dpi(value: &str) -> Result { pub(crate) fn render(args: &[String]) -> Result<(), CliError> { validate_options("render", args, RENDER_OPTIONS)?; let path = *positional(args, RENDER_OPTIONS).first().ok_or("render: missing file")?; - let page: usize = - flag(args, "--page").unwrap_or("1").parse().ok().filter(|page| *page > 0).ok_or("bad --page: expected a positive page number")?; + let page: usize = value_of_flag("render", args, RENDER_OPTIONS, "--page")? + .unwrap_or("1") + .parse() + .ok() + .filter(|page| *page > 0) + .ok_or("bad --page: expected a positive page number")?; let page_index = page - 1; - let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("96"))?; - let out = flag(args, "--out").ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?; + let dpi = parse_dpi(value_of_flag("render", args, RENDER_OPTIONS, "--dpi")?.unwrap_or("96"))?; + let out = value_of_flag("render", args, RENDER_OPTIONS, "--out")?.ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?; // The file is what its name says (#248): a `.png` used to get a netpbm PAM stream. let format = match Path::new(out).extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).as_deref() { Some("png") => Some(ImageFormat::Png), @@ -393,7 +397,7 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> { // of named-layer signatures (here with no trusted certificates); the CLI must agree with it // (and with independent viewers), while keeping the file it reads intact. let bytes = read(path)?; - let password = flag(args, "--password"); + let password = value_of_flag("render", args, RENDER_OPTIONS, "--password")?; // The renderer takes only the user password of R2–R4 files; `Session::open` and the display // copy take either. let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password); diff --git a/apps/pdfcraft-cli/src/options.rs b/apps/pdfcraft-cli/src/options.rs index 60546ae323..7b57d10e9f 100644 --- a/apps/pdfcraft-cli/src/options.rs +++ b/apps/pdfcraft-cli/src/options.rs @@ -4,6 +4,29 @@ 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) } +/// The operand of the last `name` in `args`, read the way `validate_options` and `positional` walk +/// them: a token that is another option's operand is never taken for an option. [`flag`] matches +/// any token, so in `--password --out input.pdf --out out.pdf` (a password of `--out`) it answered +/// `input.pdf` for `--out` and the command wrote over its own source file (#7516). `Err` when +/// `name` is the last token and so has no operand. +pub(crate) fn value_of_flag<'a>(command: &str, args: &'a [String], specs: &[OptionSpec], name: &str) -> Result, CliError> { + let mut i = 0; + let mut result = None; + while let Some(a) = args.get(i) { + if a == name { + let value = args.get(i + 1).map(String::as_str).ok_or_else(|| needs_value(command, name, None))?; + result = Some(value); + i += 2; + continue; + } + match specs.iter().find(|spec| spec.name == a.as_str()) { + Some(spec) if spec.takes_value => i += 2, + _ => i += 1, + } + } + Ok(result) +} + #[derive(Clone, Copy)] pub(crate) struct OptionSpec { pub(crate) name: &'static str, @@ -151,3 +174,31 @@ pub(crate) fn positional<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&' } out } + +#[cfg(test)] +mod tests { + use super::*; + + fn args(tokens: &[&str]) -> Vec { + tokens.iter().map(|token| (*token).to_string()).collect() + } + + /// #7516: a password that reads like an option is still a password, not that option. + #[test] + fn value_of_flag_skips_password_operand() { + let line = args(&["--password", "--out", "input.pdf", "--out", "out.pdf"]); + assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--out").unwrap(), Some("out.pdf")); + assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--password").unwrap(), Some("--out")); + // The old lookup, for contrast: it is why the call sites moved. + assert_eq!(flag(&line, "--out"), Some("input.pdf")); + } + + #[test] + fn value_of_flag_reports_absent_and_dangling_options() { + let line = args(&["in.pdf", "--password", "--pages"]); + assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--pages").unwrap(), None); + let dangling = args(&["in.pdf", "--pages"]); + let error = value_of_flag("extract", &dangling, EXTRACT_OPTIONS, "--pages").unwrap_err(); + assert_eq!(error.to_string(), "extract: --pages needs a value"); + } +} diff --git a/apps/pdfcraft-cli/tests/it/main.rs b/apps/pdfcraft-cli/tests/it/main.rs index 3fa64da799..aff6ba18dd 100644 --- a/apps/pdfcraft-cli/tests/it/main.rs +++ b/apps/pdfcraft-cli/tests/it/main.rs @@ -12,6 +12,7 @@ mod help; mod info_repairs; mod info_standards; mod mcp_compact; +mod option_operands; mod options; mod owner_password; mod render; diff --git a/apps/pdfcraft-cli/tests/it/option_operands.rs b/apps/pdfcraft-cli/tests/it/option_operands.rs new file mode 100644 index 0000000000..8f5308e5e2 --- /dev/null +++ b/apps/pdfcraft-cli/tests/it/option_operands.rs @@ -0,0 +1,167 @@ +//! A value-taking option's operand is never read as another option (#7516). A password can be any +//! string, `--out` included, and the commands used to look options up by scanning every token: +//! in `extract --password --out in.pdf --pages 1 --out out.pdf` the password's operand was taken +//! for the real `--out`, its neighbour `in.pdf` for the output, and the source file was replaced. + +use std::path::PathBuf; +use std::process::Command; + +const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli"); + +/// A PDF with `n` empty 200×300 pt pages. +fn fixture(n: usize) -> Vec { + let mut objs: Vec> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()]; + let kids: Vec = (0..n).map(|i| format!("{} 0 R", 3 + i)).collect(); + objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")).into_bytes()); + for _ in 0..n { + objs.push(b"<< /Type /Page /Parent 2 0 R >>".to_vec()); + } + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +/// A fresh directory holding `in.pdf` (3 pages), and that file's path as the command line takes it. +fn workdir(test: &str) -> (PathBuf, String) { + let d = std::env::temp_dir().join(format!("pdfcraft-cli-operands-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let input = d.join("in.pdf"); + std::fs::write(&input, fixture(3)).unwrap(); + let name = input.to_str().unwrap().to_string(); + (d, name) +} + +/// The page count and first page size `info` reports for a PDF the CLI wrote. +fn pages_of(path: &std::path::Path) -> (u64, serde_json::Value) { + let run = Command::new(BIN).args(["info", path.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "info {}: {}", path.display(), String::from_utf8_lossy(&run.stderr)); + let info: serde_json::Value = serde_json::from_slice(&run.stdout).unwrap(); + (info["pages"].as_u64().unwrap(), info["first_page_pt"].clone()) +} + +/// The names in `dir`, sorted, so a test sees a stray staging file or a missing part. +fn listing(dir: &std::path::Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +// Ordinary command lines through the shared atomic writer (`craft::atomic`): the lookup still +// finds each command's real options, writes what they ask for, and leaves the source alone. + +#[test] +fn ordinary_extract_writes_the_chosen_pages_and_keeps_its_source() { + let (dir, input) = workdir("plain-extract"); + let out = dir.join("out.pdf"); + let run = Command::new(BIN).args(["extract", &input, "--pages", "2-3", "--out", out.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(pages_of(&out), (2, serde_json::json!([200.0, 300.0]))); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed"); + assert_eq!(listing(&dir), ["in.pdf", "out.pdf"], "only the output was written"); +} + +#[test] +fn ordinary_split_writes_one_part_per_page_and_keeps_its_source() { + let (dir, input) = workdir("plain-split"); + let parts = dir.join("parts"); + let run = Command::new(BIN).args(["split", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(listing(&parts), ["in-p1.pdf", "in-p2.pdf", "in-p3.pdf"]); + for n in 1..=3 { + assert_eq!(pages_of(&parts.join(format!("in-p{n}.pdf"))).0, 1, "part {n}"); + } + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed"); + assert_eq!(listing(&dir), ["in.pdf", "parts"]); +} + +#[test] +fn ordinary_render_writes_the_chosen_page_at_the_chosen_dpi_and_keeps_its_source() { + let (dir, input) = workdir("plain-render"); + let png = dir.join("page.png"); + let run = Command::new(BIN).args(["render", &input, "--page", "2", "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + let image = craft_image_codecs::decode(&std::fs::read(&png).unwrap()).unwrap(); + // 200×300 pt at 36 dpi. + assert_eq!((image.width(), image.height()), (100, 150)); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed"); + assert_eq!(listing(&dir), ["in.pdf", "page.png"], "only the image was written"); +} + +#[test] +fn extract_does_not_write_over_its_source_when_the_password_is_out() { + let (dir, input) = workdir("extract"); + let out = dir.join("out.pdf"); + let run = Command::new(BIN).args(["extract", "--password", "--out", &input, "--pages", "1", "--out", out.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced"); + assert!(out.is_file(), "the page went to the real --out"); +} + +#[test] +fn extract_reads_the_real_pages_when_the_password_is_pages() { + let (dir, input) = workdir("extract-pages"); + let out = dir.join("out.pdf"); + // `--password --pages` then the file: the old lookup read the file's name as the page list. + let run = Command::new(BIN).args(["extract", "--password", "--pages", &input, "--pages", "2", "--out", out.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(pages_of(&out).0, 1, "the real --pages chose one page"); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed"); +} + +#[test] +fn split_writes_to_the_real_out_dir_when_the_password_is_out_dir() { + let (dir, input) = workdir("split"); + let parts = dir.join("parts"); + let run = + Command::new(BIN).args(["split", "--password", "--out-dir", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + for n in 1..=3 { + assert!(parts.join(format!("in-p{n}.pdf")).is_file(), "part {n} missing"); + } + assert_eq!(std::fs::read(&input).unwrap(), fixture(3)); +} + +#[test] +fn render_writes_to_the_real_out_when_the_password_is_out() { + let (dir, input) = workdir("render"); + let png = dir.join("page.png"); + let run = Command::new(BIN).args(["render", "--password", "--out", &input, "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG"), "the image went to the real --out"); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced"); +} + +/// An option left without its operand at the end of the line is named, instead of being read as +/// absent: `render in.pdf --out page.png --page` used to render page 1 and exit 0. +#[test] +fn an_option_with_no_operand_is_named() { + let (dir, input) = workdir("dangling"); + let png = dir.join("page.png"); + for args in [ + vec!["render", &input, "--out", png.to_str().unwrap(), "--page"], + vec!["render", &input, "--out", png.to_str().unwrap(), "--dpi"], + vec!["split", &input, "--every", "1", "--password"], + ] { + let option = *args.last().unwrap(); + let run = Command::new(BIN).current_dir(&dir).args(&args).output().unwrap(); + let stderr = String::from_utf8_lossy(&run.stderr); + assert!(!run.status.success(), "{args:?} unexpectedly succeeded"); + assert!(stderr.contains(&format!("{option} needs a value")), "{args:?}: {stderr}"); + } + assert!(!png.exists(), "nothing was rendered"); + assert_eq!(listing(&dir), ["in.pdf"], "a refused command left a file behind"); + assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed"); +} diff --git a/apps/pdfcraft-cli/tests/it/ui_control.rs b/apps/pdfcraft-cli/tests/it/ui_control.rs index f0b419dc0f..b9703922b0 100644 --- a/apps/pdfcraft-cli/tests/it/ui_control.rs +++ b/apps/pdfcraft-cli/tests/it/ui_control.rs @@ -8,8 +8,6 @@ use std::process::Command; use std::thread::JoinHandle; use std::time::Duration; -const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - /// A folder for one test, removed when the test ends. struct Scratch(PathBuf); @@ -71,24 +69,12 @@ impl Spy { } } -/// Write a token file the way the app does: readable by the owner only. -fn write_private(path: &Path, text: &str) { - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); - } - opts.open(path).unwrap().write_all(text.as_bytes()).unwrap(); -} - #[test] fn a_token_file_of_your_own_reaches_the_app() { let dir = scratch("own"); let spy = spy(); let token_file = dir.join("token"); - write_private(&token_file, TOKEN); + let token = craft::automation::security::server_token(None, Some(&token_file)).unwrap(); let o = Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli")) .arg("ui") .arg("--control") @@ -100,5 +86,5 @@ fn a_token_file_of_your_own_reaches_the_app() { .unwrap(); let received = spy.received(); assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); - assert!(received.contains(TOKEN) && received.contains("ui.state"), "{received}"); + assert!(received.contains(&token) && received.contains("ui.state"), "the listener did not receive the fixture token and state request"); } diff --git a/apps/pdfcraft-web/Cargo.toml b/apps/pdfcraft-web/Cargo.toml index 11c3d41ce7..171bc0f43b 100644 --- a/apps/pdfcraft-web/Cargo.toml +++ b/apps/pdfcraft-web/Cargo.toml @@ -15,8 +15,8 @@ pdfcraft-ui-egui = { workspace = true } craft = { workspace = true, features = ["automation", "platform-browser", "ui", "window"] } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" } eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] } egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } serde_json = { workspace = true } diff --git a/apps/pdfcraft-web/src/main.rs b/apps/pdfcraft-web/src/main.rs index a5e05b97d1..aae8848d58 100644 --- a/apps/pdfcraft-web/src/main.rs +++ b/apps/pdfcraft-web/src/main.rs @@ -38,7 +38,10 @@ fn main() { let files = craft::platform::browser_files::BrowserFiles::new(move || wake.wake()) .limits(limits) .page_saves(craft_web_host::files::page_save); - let app_host = craft::host::Host::builder(pdfcraft_ui_egui::APP_INFO).files(Arc::new(files)).build(); + let app_host = craft::host::Host::builder(pdfcraft_ui_egui::APP_INFO) + .files(Arc::new(files)) + .i18n(pdfcraft_ui_egui::i18n::host_catalogs()) + .build(); let mut app = PdfCraftApp::with_host(Arc::new(app_host), AppServices::system(&cc.egui_ctx, intake)); app.apply_settings(&settings.get()); app.attach_settings(settings); diff --git a/apps/pdfcraft/Cargo.toml b/apps/pdfcraft/Cargo.toml index be9cd9a4ea..733708686f 100644 --- a/apps/pdfcraft/Cargo.toml +++ b/apps/pdfcraft/Cargo.toml @@ -15,6 +15,8 @@ pdfcraft-ui-egui = { workspace = true } # The framework, through its facade (contract head): host, platform, automation, pages and quit, # and the UI runtime and window policy the window is installed with. craft = { workspace = true, features = ["platform", "automation", "pages", "quit", "ui", "window"] } +# Shared nightly-v1 profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # `build_info`: the version and compile-time build label for `--version` and the log. pdfcraft-engine = { workspace = true } # `crypto_env`: the cryptography environment the engine opens files with. @@ -26,6 +28,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" serde_json = { workspace = true } # Records from every crate go to standard error and the log file (`craft_platform::logs`). log = { workspace = true } +# Native error dialog when a Nightly profile cannot be prepared. +rfd = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] # Finder double-click / Open With / Dock drops arrive as Apple events (#73); this small audited @@ -58,7 +62,7 @@ winit = { version = "0.30", default-features = false, features = ["wayland"] } # Which GPU drives which display (EnumDisplayDevices), so the window is drawn on the GPU that # shows it (issue #378). Safe wrappers over Win32; only the `user` feature (which brings `kernel` with it), # and `advapi` for the session id that names the single-instance socket (#3338). -winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi"] } +winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi", "shell"] } # Single instance (#282): later launches hand their files to the running app over a Unix domain # socket. `std` has no Unix sockets on Windows, and calling Winsock directly needs unsafe, which # our workspace forbids. Already in the lockfile through zbus; pinned exactly, review before bumping. diff --git a/apps/pdfcraft/build.rs b/apps/pdfcraft/build.rs index b6892e7b9d..409ad99217 100644 --- a/apps/pdfcraft/build.rs +++ b/apps/pdfcraft/build.rs @@ -2,10 +2,16 @@ //! shows in Explorer, the taskbar, the Start menu and Alt-Tab. A separate PDF document icon //! uses resource ID 2; the installer references it as `pdfcraft.exe,-2`. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a -//! cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! The build channel comes from `PDFCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build +//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused +//! rather than silently producing a stable binary with a nightly name. +//! +//! On every other target the Windows resource step does nothing. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1` +//! turns it into an error (for release builds). +#[path = "src/build_channel.rs"] +mod build_channel; #[path = "src/windows_manifest.rs"] mod windows_manifest; @@ -18,10 +24,41 @@ const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=src/build_channel.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-nightly.ico"); println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-document.ico"); println!("cargo:rerun-if-changed=src/windows_manifest.rs"); println!("cargo:rerun-if-env-changed=PDFCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_SHA"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_CHANNEL"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_VERSION"); + println!("cargo:rustc-check-cfg=cfg(pdfcraft_nightly_v1)"); + let nightly = match std::env::var("PDFCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=pdfcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported PDFCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + let built_version = if nightly { + match std::env::var("PDFCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit PDFCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=PDFCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } @@ -32,14 +69,19 @@ fn main() { println!("cargo:rustc-link-arg-bins=delayimp.lib"); } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/pdfcraft.ico") - .set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2") + res.set_icon(build_channel::windows_icon_path(nightly)) .set_manifest(windows_manifest::WINDOWS_MANIFEST) - .set("ProductName", "PdfCraft") - .set("FileDescription", "PdfCraft PDF workbench") + .set("ProductName", if nightly { "PdfCraft Nightly" } else { "PdfCraft" }) + .set("FileDescription", if nightly { "PdfCraft Nightly PDF workbench" } else { "PdfCraft PDF workbench" }) .set("LegalCopyright", "Copyright (c) the PdfCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", "pdfcraft.exe") .set("InternalName", "pdfcraft"); + if nightly { + // The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } else { + res.set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2"); + } if let Err(e) = res.compile() { if std::env::var_os("PDFCRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources failed: {e}"); diff --git a/apps/pdfcraft/src/apple_events.rs b/apps/pdfcraft/src/apple_events.rs index e7b9ff358c..d2075e201c 100644 --- a/apps/pdfcraft/src/apple_events.rs +++ b/apps/pdfcraft/src/apple_events.rs @@ -33,7 +33,6 @@ impl AppleEvents { /// The inbox belongs to the main thread (it is not `Send`, and drains inside its own wake /// would borrow it twice), so the returned function does the forwarding: the frame calls it /// once per frame on the main thread. - // PLAN: pdf-hub-w1 calls the returned function once per frame (it replaces the `OsEventsFn` poll). pub fn connect(&self, sender: IntakeSender, ctx: &egui::Context) -> Box { let wake = ctx.clone(); self.inbox.set_wake(move || wake.request_repaint()); diff --git a/apps/pdfcraft/src/build_channel.rs b/apps/pdfcraft/src/build_channel.rs new file mode 100644 index 0000000000..d71d40f0dc --- /dev/null +++ b/apps/pdfcraft/src/build_channel.rs @@ -0,0 +1,57 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. + +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/pdfcraft-nightly.ico" } else { "../../assets/app-icon/pdfcraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::{is_nightly_version, windows_icon_path}; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/pdfcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/pdfcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.22.0-nightly.20261129.17.1.gabcdef012345")); + for invalid in [ + "", + "0.22.0", + "0.22.0-nightly", + "0.22.0-nightly.20261129", + "0.22.0-nightly.20261129.17.1.gABCDEF012345", + "0.22.0-nightly.20261129.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.22.0-nightly.20261129.1.1.gabcdef012345", + "0.22.0-nightly.20261129.1.1.gabcdef012345/other", + "0.22.0-nightly.20261129.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/pdfcraft/src/build_flavor.rs b/apps/pdfcraft/src/build_flavor.rs new file mode 100644 index 0000000000..027c6b1793 --- /dev/null +++ b/apps/pdfcraft/src/build_flavor.rs @@ -0,0 +1,49 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. + +pub use craft_nightly::BuildFlavor; + +pub const COMPILED: BuildFlavor = if cfg!(pdfcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The packaging/version probe must work even when no profile location can be resolved. +pub fn version_query(args: &[std::ffi::OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +#[cfg_attr(not(test), allow(dead_code))] +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::{BuildFlavor, needs_native_error, version}; + + #[test] + fn plain_version_queries_are_unambiguous() { + assert!(super::version_query(&["--version".into()])); + assert!(super::version_query(&["-V".into()])); + assert!(!super::version_query(&["--".into(), "--version".into()])); + assert!(!super::version_query(&["--version".into(), "example".into()])); + } + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_version_format_distinguishes_channel() { + assert_eq!(version(BuildFlavor::Stable, "0.22.0"), "0.22.0"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.22.0"), "0.22.0 (nightly-v1)"); + } +} diff --git a/apps/pdfcraft/src/launch_profile.rs b/apps/pdfcraft/src/launch_profile.rs new file mode 100644 index 0000000000..21f6e039cf --- /dev/null +++ b/apps/pdfcraft/src/launch_profile.rs @@ -0,0 +1,197 @@ +//! Nightly-v1 bootstrap backed by `craft_nightly`. Selected before logging, updates, fonts or +//! saved state. Stable launches retain their original arguments and directory policy. + +use std::ffi::OsString; + +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; + +use crate::profile_root; + +/// Returns the active process profile, defaulting to [`Profile::Stable`] before initialization. +pub fn current() -> &'static Profile { + craft_nightly::current().unwrap_or(&Profile::Stable) +} + +/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root for +/// nightly builds (self-isolating into [`craft_nightly::canonical_profile_root`] on direct +/// launch), and installs the process-wide profile. +pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) +} + +#[cfg(test)] +mod tests { + use std::ffi::OsString; + use std::path::PathBuf; + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + use craft_nightly::launch_arguments; + use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup}; + + use crate::profile_root; + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + struct TempProfileDir(PathBuf); + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + impl TempProfileDir { + fn new(label: &str) -> Self { + #[cfg(unix)] + let base = std::fs::canonicalize(std::path::Path::new("/tmp")).unwrap_or_else(|_| PathBuf::from("/tmp")); + #[cfg(windows)] + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let dir = base.join(format!("pc-{label}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + impl Drop for TempProfileDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\pdfcraft" } else { "/nightly-data/profiles/pdfcraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + let spec = profile_root::spec(); + for argv in [args(&[]), args(&["--new-window", "a.pdf"]), args(&["--", "--launch-profile", "file.pdf"])] { + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); + assert!(launch.leading_flags.is_empty()); + assert!(!launch.has_launcher_separator()); + } + } + + #[test] + fn stable_build_refuses_nightly_launch_flags() { + let spec = profile_root::spec(); + let err = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); + } + + #[test] + fn direct_nightly_launch_self_isolates_into_canonical_profile_root() { + let spec = profile_root::spec(); + let expected_root = canonical_profile_root("pdfcraft").unwrap(); + for argv in [args(&[]), args(&["document.pdf"]), args(&["--two-paged", "document.pdf"])] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root.clone())); + assert_eq!(launch.passthrough_args, argv); + } + } + + #[test] + fn explicit_launcher_arguments_override_root_and_preserve_file_names() { + let spec = profile_root::spec(); + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "document with spaces.pdf"])); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "document with spaces.pdf"])); + } + + #[test] + fn malformed_nightly_launch_flags_are_refused() { + let spec = profile_root::spec(); + for argv in [ + args(&["--launch-profile", NIGHTLY_V1_CONTRACT]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]), + ] { + assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err()); + } + } + + #[test] + fn nightly_version_queries_are_recognized_for_direct_and_launcher_invocations() { + let spec = profile_root::spec(); + for argv in [ + args(&["--version"]), + args(&["-V"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "-V"]), + args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "--version"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--version"]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); + } + for argv in [args(&[]), args(&["--help"]), args(&["--version", "--version"])] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert!(!launch.is_version_query(), "{argv:?}"); + } + } + + #[cfg(all(unix, not(target_os = "macos")))] + #[test] + fn linux_nightly_profile_accepts_existing_single_instance_socket() { + use std::os::unix::net::UnixListener; + + let tmp = TempProfileDir::new("si"); + let profile = tmp.0.join("p"); + let single_instance = profile.join("single-instance"); + std::fs::create_dir_all(&single_instance).unwrap(); + let expected_root = std::fs::canonicalize(&profile).unwrap(); + + let sock_path = single_instance.join("instance.sock"); + let listener = UnixListener::bind(&sock_path).unwrap(); + + // Live listener socket already present inside /single-instance/. + let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); + assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone())); + assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"])); + + // Leftover/stale socket remaining after the previous instance exits. + drop(listener); + assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk"); + let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); + assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"])); + } + + #[cfg(windows)] + #[test] + fn windows_nightly_profile_accepts_existing_single_instance_socket() { + let tmp = TempProfileDir::new("si"); + let profile = tmp.0.join("p"); + let single_instance = profile.join("single-instance"); + std::fs::create_dir_all(&single_instance).unwrap(); + let expected_root = std::fs::canonicalize(&profile).unwrap(); + + let sock_path = single_instance.join("instance-s1.sock"); + let listener = uds_windows::UnixListener::bind(&sock_path).unwrap(); + + // Live AF_UNIX listener socket already present inside \single-instance\. + let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); + assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone())); + assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"])); + + // Leftover/stale socket remaining after the previous instance exits. + drop(listener); + assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk"); + let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); + assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"])); + } +} diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 120068f4ae..3564efe993 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -40,16 +40,26 @@ use pdfcraft_ui_egui::PdfCraftApp; #[cfg(target_os = "macos")] mod apple_events; +#[cfg(test)] +mod build_channel; +mod build_flavor; mod compositor_gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod reopen; mod single_instance; mod startup; +#[cfg(target_os = "windows")] +mod window_placement; #[cfg(test)] #[path = "windows_manifest.rs"] mod windows_manifest; /// Freedesktop app id: the `.desktop` file name and the hicolor icon name. const APP_ID: &str = "ai.storyteller.pdfcraft"; +const NIGHTLY_APP_ID: &str = "ai.storyteller.pdfcraft.nightly"; /// The app icon (assets/app-icon/README.md). macOS gets the version on Apple's icon grid, with a /// transparent margin; Windows and Linux get the full-bleed tile. @@ -58,6 +68,91 @@ const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-10 #[cfg(not(target_os = "macos"))] const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png"); +#[cfg(target_os = "macos")] +const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly-1024.png"); +#[cfg(not(target_os = "macos"))] +const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly.png"); + +fn is_nightly() -> bool { + launch_profile::current().is_nightly() +} + +fn app_id() -> &'static str { + if is_nightly() { NIGHTLY_APP_ID } else { APP_ID } +} + +fn app_title() -> &'static str { + if is_nightly() { "PdfCraft Nightly" } else { "PdfCraft" } +} + +fn app_icon_png() -> &'static [u8] { + if is_nightly() { NIGHTLY_APP_ICON_PNG } else { APP_ICON_PNG } +} + +fn built_version() -> &'static str { + env!("PDFCRAFT_BUILT_VERSION") +} + +fn nightly_version_line() -> String { + format!("PdfCraft {} (nightly-v1)", built_version()) +} + +fn initialize_nightly_process_identity() -> Result<(), String> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, NIGHTLY_APP_ID) +} + +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +fn report_launch_profile_error(error: &str) { + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {error}\n")); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { + if let Err(err) = initialize_nightly_process_identity() { + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {err}\n")); + return; + } + let _ = rfd::MessageDialog::new() + .set_title("PdfCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer +/// the version query before any of that: `None` means the query has been answered. +fn prepare_launch() -> Option> { + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + let _ = std::io::Write::write_fmt(&mut std::io::stdout().lock(), format_args!("{}\n", nightly_version_line())); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { + let _ = std::io::Write::write_fmt(&mut std::io::stdout().lock(), format_args!("{}\n", nightly_version_line())); + return None; + } + if let Err(error) = initialize_nightly_process_identity() { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Some(root) = early.profile.root() + && let Err(error) = pdfcraft_ui_egui::settings::install_nightly_profile_root(root.to_path_buf()) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.passthrough_args) +} + /// What `-h` / `--help` prints (#4076): a hint, not the full option list (that is this file's /// doc comment and the README). Scripts want `pdfcraft-cli`, which never opens a window. const USAGE: &str = "\ @@ -104,7 +199,7 @@ fn portable() -> bool { /// folder is left alone when the new one already exists or the move fails. A portable copy leaves /// the per-user folders alone. fn migrate_legacy_folders() { - if portable() { + if is_nightly() || portable() { return; } let mut moves = vec![(eframe::storage_dir("PrintCraft"), eframe::storage_dir("PdfCraft"))]; @@ -165,9 +260,12 @@ fn main() -> eframe::Result { } // aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`). pdfcraft_engine::sign::init_crypto(); + let Some(raw_args) = prepare_launch() else { return Ok(()) }; // 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(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !is_nightly() + && let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &raw_args) + { std::process::exit(i32::from(result.is_err())); } // First, so the panic hook and every start-up warning are recorded. @@ -193,7 +291,7 @@ fn main() -> eframe::Result { let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {report}\n")); } })); - let mut startup = startup::Arguments::parse(std::env::args().skip(1)); + let mut startup = startup::Arguments::parse_for_profile(raw_args.into_iter().map(|a| a.to_string_lossy().into_owned()), is_nightly()); if startup.version { return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version())); } @@ -204,18 +302,29 @@ fn main() -> eframe::Result { let may_hand_off = startup.may_hand_off(); let startup::Arguments { files, options, control_port, control_token, control_token_file, create_images, combine, two_paged, .. } = startup; // A bad control configuration stops the launch before any window opens. - let control = match control_options(control_port, control_token, control_token_file) { - Ok(control) => control, - Err(message) => usage_error(&message), + // Nightly disables the control server so inherited stable env vars cannot open one. + let control = if is_nightly() { + None + } else { + match control_options(control_port, control_token, control_token_file) { + Ok(control) => control, + Err(message) => usage_error(&message), + } }; migrate_legacy_folders(); // The log file stays in the data folder; opened after the arguments (so `--version` leaves // no file behind) and after the PrintCraft migration (which a fresh folder would block). // Records logged until now are written to it first. - let data_dir = if portable() { settings_dir() } else { eframe::storage_dir("PdfCraft") }; + let data_dir = if let Some(root) = launch_profile::current().root() { + Some(root.to_path_buf()) + } else if portable() { + settings_dir() + } else { + eframe::storage_dir("PdfCraft") + }; if let (Some(logger), Some(dir)) = (logger, data_dir) { match logger.attach_dir(&dir.join("logs")) { - Ok(path) => log::info!("PdfCraft {}, log file {}", pdfcraft_engine::build_info::version(), path.display()), + Ok(path) => log::info!("{} {}, log file {}", app_title(), built_version(), path.display()), // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. Err(e) => log::warn!("no log file: {e}"), } @@ -226,16 +335,36 @@ fn main() -> eframe::Result { // window. // Absolute for this instance too: links relative to a document resolve against its folder, // never the working directory. + let startup_time = std::time::Instant::now(); + startup_stage(startup_time, "claiming application instance"); let files = single_instance::absolute(&files); - let instance = match single_instance::claim(&files, may_hand_off, combine) { + let instance = match single_instance::claim(&files, may_hand_off, combine, launch_profile::current().root()) { single_instance::Claim::HandedOff => return Ok(()), single_instance::Claim::Primary(server) => Some(server), single_instance::Claim::Alone => None, }; + let (nightly_watch, previous_unclean) = + match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("PDFCRAFT_BUILD_SHA")) { + Ok((watch, unavailable)) => { + if unavailable { + log::warn!("another PdfCraft Nightly holds this profile's session lease; this window keeps no health record"); + } + let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean); + (std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean) + } + Err(error) => { + log::warn!("Nightly session state: {error}"); + (std::sync::Arc::new(std::sync::Mutex::new(None)), false) + } + }; + if previous_unclean { + log::warn!("the previous PdfCraft Nightly ended without finishing its session record"); + } // Who draws the window frame: the platform and Preferences ▸ Use system title bar decide, // unless `PDFCRAFT_TITLEBAR` overrides them. The store is read here and opened again by the // app (each window attempt opens its own: the OpenGL retry runs the creator again). // The interface language is read the same way, for the fonts the runtime installs with. + startup_stage(startup_time, "reading startup preferences"); let (title_bar, saved_lang) = { let settings = pdfcraft_ui_egui::settings::open(); let saved = settings.get(); @@ -247,7 +376,8 @@ fn main() -> eframe::Result { let frame = craft::window::policy::decide_for(craft::window::Prefix::new("PDFCRAFT"), craft::window::policy::Backend::from_env(), title_bar); let lang = startup_lang(saved_lang.as_deref(), &options); let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()); - let launch = Launch { files, options, control, create_images, combine, frame, lang, two_paged }; + let launch = + Launch { startup_time, files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch: nightly_watch.clone() }; // Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one // that launched us as well as later ones. Lives until the event loop returns. #[cfg(target_os = "macos")] @@ -255,8 +385,9 @@ fn main() -> eframe::Result { // Set once the app is created, which is after the renderer has started. let started = Rc::new(Cell::new(false)); let first = if choice == RendererChoice::Gl { eframe::Renderer::Glow } else { eframe::Renderer::Wgpu }; + startup_stage(startup_time, if choice == RendererChoice::Gl { "initializing OpenGL" } else { "initializing wgpu" }); let result = eframe::run_native( - "PdfCraft", + app_title(), native_options(launch.integrated(), first), app_creator( launch.clone(), @@ -266,19 +397,20 @@ fn main() -> eframe::Result { &apple_events, ), ); - match result { + let final_result = match result { // Only a renderer that couldn't start: without a window or display at all, OpenGL can't // help either, and winit's own error says more. Err(e @ eframe::Error::Wgpu(_)) if retry_with_gl(choice, started.get()) => { // Old or unusual GPUs and drivers (#461, #435, #392) can't give wgpu a device; OpenGL // usually still works there, so that's better than quitting. log::error!("the GPU renderer (wgpu) didn't start: {e}. Starting with OpenGL instead; set PDFCRAFT_RENDERER=gl to skip wgpu."); + startup_stage(startup_time, "retrying with OpenGL"); eframe::run_native( - "PdfCraft", + app_title(), native_options(launch.integrated(), eframe::Renderer::Glow), app_creator( launch, - started, + Rc::clone(&started), instance.as_ref(), #[cfg(target_os = "macos")] &apple_events, @@ -286,7 +418,13 @@ fn main() -> eframe::Result { ) } other => other, - } + }; + nightly_session::finish_once(&nightly_watch, started.get()); + final_result +} + +fn startup_stage(start: std::time::Instant, stage: &str) { + log::info!(target: "pdfcraft::startup", "+{} ms: {stage}", start.elapsed().as_millis()); } /// Which renderer to start with, from `PDFCRAFT_RENDERER`. @@ -358,12 +496,12 @@ fn retry_with_gl(choice: RendererChoice, app_started: bool) -> bool { /// The window and renderer settings for one run. fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::NativeOptions { let mut viewport = egui::ViewportBuilder::default() - .with_title("PdfCraft") + .with_title(app_title()) .with_inner_size([1440.0, 920.0]) .with_min_inner_size(pdfcraft_ui_egui::MIN_WINDOW_SIZE) .with_drag_and_drop(true) - // Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop. - .with_app_id(APP_ID); + // Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop (or .nightly). + .with_app_id(app_id()); // eframe replaces ICON_BIG with a system-sized icon on its first active frame. // An explicitly empty icon disables that setter (None selects eframe's default). // Windows installs both sizes directly through winit in app_creator instead. @@ -373,7 +511,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ } // Dock, taskbar, Alt-Tab and launcher icon when running unbundled. #[cfg(not(target_os = "windows"))] - match eframe::icon_data::from_png_bytes(APP_ICON_PNG) { + match eframe::icon_data::from_png_bytes(app_icon_png()) { Ok(icon) => viewport = viewport.with_icon(icon), Err(e) => log::warn!("app icon: {e}"), } @@ -401,6 +539,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ /// What the command line asked for, kept so a second run (with OpenGL) can start the same way. #[derive(Clone)] struct Launch { + startup_time: std::time::Instant, files: Vec, options: Vec<(String, String)>, /// The control server's port and token, when `--control` asked for one. @@ -413,6 +552,7 @@ struct Launch { /// The language the interface starts in, whose fonts are installed with the runtime. lang: pdfcraft_ui_egui::i18n::Lang, two_paged: bool, + nightly_watch: nightly_session::Shared, } impl Launch { @@ -444,7 +584,7 @@ fn install_runtime( let system = craft::ui::runtime::env::SystemReader::start(move || ctx.request_repaint()); let spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), std::sync::Arc::new(SystemWindows)) .system(system) - .app_id(APP_ID) + .app_id(app_id()) .frame(frame); craft::ui::shell::embed::install(&cc.egui_ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(lang)) .map(drop) @@ -483,7 +623,7 @@ fn install_taskbar_icon(png: &[u8], set: impl FnOnce(winit::window::Icon)) { #[cfg(target_os = "windows")] fn set_taskbar_icon(window: &winit::window::Window) { use winit::platform::windows::{IconExtWindows as _, WindowExtWindows as _}; - install_taskbar_icon(APP_ICON_PNG, |icon| window.set_taskbar_icon(Some(icon))); + install_taskbar_icon(app_icon_png(), |icon| window.set_taskbar_icon(Some(icon))); // The title bar's icon: the small image drawn for this scale in the exe's own icon (build.rs). let side = (16.0 * window.scale_factor()).round().clamp(16.0, 256.0) as u32; match winit::window::Icon::from_resource(1, Some(winit::dpi::PhysicalSize::new(side, side))) { @@ -499,9 +639,10 @@ fn app_creator<'a>( instance: Option<&'a single_instance::Server>, #[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents, ) -> eframe::AppCreator<'a> { - let Launch { files, options, control, create_images, combine, frame, lang, two_paged } = launch; + let Launch { startup_time, files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch } = launch; Box::new(move |cc| { started.set(true); + startup_stage(startup_time, "renderer ready, installing fonts and runtime"); install_runtime(cc, frame, lang)?; let ctx = cc.egui_ctx.clone(); let wake = craft::host::Wake::new(move || ctx.request_repaint()); @@ -511,22 +652,39 @@ fn app_creator<'a>( Some(server) => server.connect(&cc.egui_ctx), None => craft::platform::open::FileIntake::new(wake).0, }; - // Finder, Open With and the Dock deliver files as Apple events, not arguments. + // Finder, Open With and the Dock deliver files as Apple events, not arguments; each frame + // drains them into the intake. #[cfg(target_os = "macos")] - apple_events.connect(intake.sender(), &cc.egui_ctx); + let apple_events_poll = apple_events.connect(intake.sender(), &cc.egui_ctx); + startup_stage(startup_time, "initializing application and recovery"); let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake); + #[cfg(target_os = "linux")] + if let Some(window) = cc.winit_window() { + use raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; + if window.display_handle().is_ok_and(|h| matches!(h.as_raw(), RawDisplayHandle::Wayland(_))) { + app.use_wayland_clipboard(&cc.egui_ctx); + } + } + let exit_watch = nightly_watch.clone(); + app.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, true))); + #[cfg(target_os = "macos")] + { + app.os_events = Some(apple_events_poll); + } // First start (or settings from before Units existed): the region's unit. app.units = pdfcraft_ui_egui::units::Unit::system(); // The system's reopen-windows choice (macOS) starts the preference; a saved choice replaces it. app.reopen_last_session = reopen::system_default(); + startup_stage(startup_time, "applying preferences"); let settings = pdfcraft_ui_egui::settings::open(); app.apply_settings(settings.get()); app.attach_settings(settings); #[cfg(target_os = "windows")] if let Some(window) = cc.winit_window() { + window_placement::restore(window); set_taskbar_icon(window); } - app.set_startup_update_check(true); + app.set_startup_update_check(!is_nightly()); app.printer_source = Some(pdfcraft_ui_egui::system_printers()); app.two_sided_source = Some(pdfcraft_ui_egui::system_two_sided()); app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows")); @@ -564,6 +722,7 @@ fn app_creator<'a>( if let Some(warning) = &pdfcraft_ui_egui::settings::resolution().warning { app.notify(warning.clone()); } + startup_stage(startup_time, "restoring session and opening requested documents"); let defer_layout = two_paged && !files.is_empty() && !create_images; if create_images { if let Err(e) = app.begin_image_import_paths(&cc.egui_ctx, &files) { @@ -584,6 +743,8 @@ fn app_creator<'a>( log::warn!("--{k} {v}: {e}"); } } + startup_stage(startup_time, "entering UI event loop"); + app.startup_time = Some(startup_time); Ok(Box::new(app)) }) } @@ -644,21 +805,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) { descriptor.required_limits = surface_texture_limits(descriptor.required_limits, &adapter.limits()); descriptor }); - if std::env::var_os("WGPU_POWER_PREF").is_none() { + let power_chosen = std::env::var_os("WGPU_POWER_PREF").is_some(); + let explicit_renderer = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()) == RendererChoice::Wgpu; + if !power_chosen { setup.power_preference = eframe::wgpu::PowerPreference::LowPower; let displays = display_gpus(); let compositor = compositor_gpu::compositor_gpu(); - if !displays.is_empty() || compositor.is_some() { + // Always on Windows, so that an OpenGL-only GPU is declined (`wgpu_draws_with`) even when + // no display names its GPU, as over Remote Desktop; `pick_adapter` then ranks by kind, + // most frugal first, as wgpu's own low-power choice does. + if !displays.is_empty() || compositor.is_some() || cfg!(target_os = "windows") { + let backend_chosen = explicit_renderer || std::env::var_os("WGPU_BACKEND").is_some(); setup.native_adapter_selector = Some(std::sync::Arc::new(move |adapters, surface| { let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect(); - let infos: Vec<(u32, u32, eframe::wgpu::DeviceType)> = usable + let infos: Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> = usable .iter() .map(|a| { let info = a.get_info(); - (info.vendor, info.device, info.device_type) + (info.vendor, info.device, info.device_type, info.backend) }) .collect(); let picked = pick_adapter(&infos, &displays, compositor).and_then(|i| usable.get(i)).map(|a| (*a).clone()); + if let Some(a) = &picked + && !wgpu_draws_with(a.get_info().backend, cfg!(target_os = "windows"), backend_chosen) + { + log::warn!( + "wgpu found no Direct3D 12 adapter for {}, only its OpenGL backend: drawing with eframe's OpenGL renderer instead", + a.get_info().name + ); + return Err("wgpu would draw through its OpenGL backend".to_string()); + } match &picked { // Which GPU draws is the first question when a window stays black (#8, #378, #445). Some(a) => { @@ -671,14 +847,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) { })); } } - if cfg!(target_os = "windows") && std::env::var_os("WGPU_BACKEND").is_none() { - setup.instance_descriptor.backends = eframe::wgpu::Backends::DX12 | eframe::wgpu::Backends::GL; + if let Some(backends) = + automatic_windows_backends(cfg!(target_os = "windows"), std::env::var_os("WGPU_BACKEND").is_some(), power_chosen, explicit_renderer) + { + setup.instance_descriptor.backends = backends; } if cfg!(target_os = "windows") { setup.instance_descriptor.backend_options.dx12.presentation_system = dx12_presentation(eframe::wgpu::Dx12SwapchainKind::from_env()); } } +/// A power preference delegates adapter ranking to wgpu, bypassing the selector that declines +/// its OpenGL surface on Windows. Auto mode must then try DX12 alone before native OpenGL. +fn automatic_windows_backends(windows: bool, explicit_backend: bool, power_chosen: bool, explicit_renderer: bool) -> Option { + use eframe::wgpu::Backends; + if !windows || explicit_backend { + return None; + } + Some(if power_chosen && !explicit_renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL }) +} + +/// Whether wgpu should draw with the adapter it picked on `backend`. On Windows (`windows`) wgpu +/// reaches its OpenGL backend only for a GPU with no Direct3D 12 driver, such as Intel's Ivy +/// Bridge, and there that backend fails in `Surface::configure` a few seconds after the window +/// opens: too late for the start-up retry with OpenGL, so the app closed (#519, #4134, #5553). +/// eframe's own OpenGL renderer works on the same GPUs, so wgpu declines and that retry takes over. +/// An explicit `PDFCRAFT_RENDERER=wgpu` or `WGPU_BACKEND` selection (`backend_chosen`) is kept. +fn wgpu_draws_with(backend: eframe::wgpu::Backend, windows: bool, backend_chosen: bool) -> bool { + !(windows && backend == eframe::wgpu::Backend::Gl && !backend_chosen) +} + /// How Direct3D 12 presents on Windows: through a DirectComposition visual (issue #2738), unless /// `WGPU_DX12_PRESENTATION_SYSTEM` asked for something else (`asked`). fn dx12_presentation(asked: Option) -> eframe::wgpu::Dx12SwapchainKind { @@ -806,14 +1004,25 @@ fn linux_display_gpus(drm: &std::path::Path) -> Vec { /// primary display (a hybrid laptop's panel, #8; the primary display on Windows, #378), or else, /// with no primary display known (a Linux desktop with a monitor on each GPU, #445), the discrete /// one. Otherwise the most frugal kind: integrated, discrete, other, virtual, software. -fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[DisplayGpu], compositor: Option<(u32, u32)>) -> Option { - use eframe::wgpu::DeviceType; +/// +/// On Windows wgpu offers a Direct3D 12 GPU through OpenGL too, and declines OpenGL there +/// (`wgpu_draws_with`), so an OpenGL adapter comes after another adapter of its vendor. wgpu's +/// OpenGL adapter has no device id and guesses its kind (every Intel GPU is integrated), so it is +/// matched by vendor alone, before its kind is compared: an Intel discrete GPU's Direct3D 12 +/// adapter beats its own OpenGL one. A GPU with only OpenGL (Intel's Ivy Bridge) still beats the +/// software adapter, Microsoft's. +fn pick_adapter( + adapters: &[(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)], + displays: &[DisplayGpu], + compositor: Option<(u32, u32)>, +) -> Option { + use eframe::wgpu::{Backend, DeviceType}; let display = |pci: (u32, u32)| displays.iter().find(|g| g.pci == pci); let multi_gpu_desktop = displays.len() > 1 && !displays.iter().any(|g| g.primary); adapters .iter() .enumerate() - .min_by_key(|(_, (vendor, device, kind))| { + .min_by_key(|(_, (vendor, device, kind, backend))| { let shown = display((*vendor, *device)); let drives_display = shown.is_some(); let drives_primary = shown.is_some_and(|g| g.primary); @@ -827,10 +1036,40 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D DeviceType::VirtualGpu => 4, DeviceType::Cpu => 5, }; - (compositor != Some((*vendor, *device)), !drives_display, !drives_primary, rank) + let gl = *backend == Backend::Gl; + let vendor_has_more = gl && adapters.iter().any(|(v, _, _, b)| v == vendor && *b != Backend::Gl); + (compositor != Some((*vendor, *device)), !drives_display, !drives_primary, vendor_has_more, rank, gl) }) .map(|(i, _)| i) } #[cfg(test)] mod tests; + +#[cfg(test)] +mod nightly_bootstrap_tests { + use super::{ + APP_ICON_PNG, APP_ID, app_icon_png, app_id, app_title, built_version, initialize_nightly_process_identity, is_nightly, nightly_version_line, + refusal_dialog, + }; + use crate::build_flavor::BuildFlavor; + + #[test] + fn stable_defaults_and_nightly_version_line() { + assert!(!is_nightly()); + assert_eq!(app_id(), APP_ID); + assert_eq!(app_title(), "PdfCraft"); + assert_eq!(app_icon_png(), APP_ICON_PNG); + assert!(!built_version().is_empty()); + assert_eq!(nightly_version_line(), format!("PdfCraft {} (nightly-v1)", built_version())); + assert!(initialize_nightly_process_identity().is_ok()); + } + + #[test] + fn refusal_dialog_never_blocks_macos_or_headless_or_stable() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false)); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true)); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false)); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false)); + } +} diff --git a/apps/pdfcraft/src/nightly_session.rs b/apps/pdfcraft/src/nightly_session.rs new file mode 100644 index 0000000000..6b96923f91 --- /dev/null +++ b/apps/pdfcraft/src/nightly_session.rs @@ -0,0 +1,230 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(metadata) if !metadata.file_type().is_file() => { + return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")); + } + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let dir = path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..32_u32 { + let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id())); + let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + if let Err(error) = written { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + return match std::fs::rename(&temporary, path) { + Ok(()) => Ok(()), + Err(error) => { + let _ = std::fs::remove_file(&temporary); + Err(error) + } + }; + } + Err(io::Error::other("no free temporary name for the Nightly session state")) +} + +impl Session { + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.len() > MAX_METADATA_BYTES || commit.is_some_and(|c| c.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance exceeds its metadata bound")); + } + let lease_path = root.join(LEASE); + let _ = regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit, + })) + .map_err(io::Error::other)?; + write_atomic_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take((self.own_record.len() as u64).saturating_add(1)).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session record was replaced by another writer")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::{LEASE, MAX_METADATA_BYTES, RECORD, Session, Shared, finish_once}; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{Arc, Mutex}; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + + struct Fixture(PathBuf); + + impl Fixture { + fn new() -> Self { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("pdfcraft-nightly-session-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn clean_exit_clears_record_and_unclean_drop_leaves_it() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("abc")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + assert!(Session::begin(Some(&fixture.0), "busy", None).unwrap().is_none()); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let dropped = Session::begin(Some(&fixture.0), "dropped", None).unwrap().unwrap(); + drop(dropped); + let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.finish(false).unwrap(); + assert!(fixture.0.join(RECORD).exists()); + let final_run = Session::begin(Some(&fixture.0), "final", None).unwrap().unwrap(); + assert!(final_run.previous_unclean()); + final_run.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn finish_once_runs_only_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists()); + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + successor.complete().unwrap(); + } + + #[test] + fn provenance_is_bounded() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert!(Session::begin(None, "", None).unwrap().is_none()); + assert_eq!(LEASE, "nightly-session.lock"); + } + + #[test] + fn begin_with_health_reports_busy_and_complete_refuses_replaced_record() { + let fixture = Fixture::new(); + let (owner, unavailable) = Session::begin_with_health(Some(&fixture.0), "owner", Some("123")).unwrap(); + assert!(!unavailable); + let owner = owner.unwrap(); + let (secondary, sec_unavailable) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none()); + assert!(sec_unavailable); + std::fs::write(fixture.0.join(RECORD), b"foreign writer").unwrap(); + assert!(owner.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"foreign writer"); + } + + #[cfg(unix)] + #[test] + fn symlink_record_or_lease_is_refused() { + let fixture = Fixture::new(); + let target = fixture.0.join("outside.txt"); + std::fs::write(&target, b"keep").unwrap(); + for name in [LEASE, RECORD] { + let link = fixture.0.join(name); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&target).unwrap(), b"keep"); + std::fs::remove_file(&link).unwrap(); + } + } +} diff --git a/apps/pdfcraft/src/process_identity.rs b/apps/pdfcraft/src/process_identity.rs new file mode 100644 index 0000000000..1b67b5218c --- /dev/null +++ b/apps/pdfcraft/src/process_identity.rs @@ -0,0 +1,65 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), String> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::configure; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + assert!(super::initialize(false, "nightly-id").is_ok()); + } +} diff --git a/apps/pdfcraft/src/profile_root.rs b/apps/pdfcraft/src/profile_root.rs new file mode 100644 index 0000000000..18006d16c0 --- /dev/null +++ b/apps/pdfcraft/src/profile_root.rs @@ -0,0 +1,199 @@ +//! App-owned nightly profile specification passed to `craft_nightly`. + +use std::path::PathBuf; + +use craft_nightly::AppProfileSpec; + +/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). +pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.pdfcraft.nightly"; + +/// The app id eframe derives stable's storage folder from. +const STABLE_APP_ID: &str = "ai.storyteller.pdfcraft"; + +/// The subfolder autosave and recovery write inside a nightly profile. +pub const AUTOSAVE: &str = "autosave"; + +const STABLE_DIR_NAMES: [&str; 3] = ["pdfcraft", "PdfCraft", "PrintCraft"]; +const FORBIDDEN_ENV_VARS: [&str; 1] = ["PDFCRAFT_CONFIG_DIR"]; +const PORTABLE_MARKERS: [&str; 3] = ["portable.txt", "PdfCraft.portable", "PdfCraftData"]; +const PROFILE_FOLDERS: [&str; 5] = [AUTOSAVE, "logs", "single-instance", "dictionary", "Digital IDs"]; + +/// Builds PDFCraft's [`AppProfileSpec`] for `craft_nightly` validation. +pub fn spec() -> AppProfileSpec { + AppProfileSpec { + app_id: "pdfcraft", + display_name: "PdfCraft", + stable_dir_names: &STABLE_DIR_NAMES, + stable_package_id: STABLE_APP_ID, + nightly_package_id: NIGHTLY_FLATPAK_ID, + profile_root_env: None, + forbidden_env_vars: &FORBIDDEN_ENV_VARS, + portable_markers: &PORTABLE_MARKERS, + folder_only_entries: &PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(), + } +} + +fn extra_forbidden_roots() -> Vec { + let mut roots = Vec::new(); + + #[cfg(target_os = "windows")] + { + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(key) { + roots.push(base.join("ArtCraft").join("PdfCraft")); + } + } + } + + #[cfg(all(unix, not(target_os = "macos")))] + { + roots.extend(["/usr/bin/pdfcraft", "/usr/local/bin/pdfcraft", "/opt/pdfcraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env("HOME") { + roots.push(home.join(".var/app/ai.storyteller.pdfcraft")); + } + } + + #[cfg(target_os = "macos")] + { + roots.push(PathBuf::from("/Applications/PdfCraft.app")); + if let Some(home) = non_empty_abs_env("HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences/ai.storyteller.pdfcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.pdfcraft.savedState")); + roots.push(home.join("Applications/PdfCraft.app")); + } + } + + roots +} + +fn non_empty_abs_env(key: &str) -> Option { + let value = std::env::var_os(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + path.is_absolute().then_some(path) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + use craft_nightly::{ProfileError, nightly_flatpak_id, validate_and_prepare_root}; + + use super::{FORBIDDEN_ENV_VARS, NIGHTLY_FLATPAK_ID, PORTABLE_MARKERS, PROFILE_FOLDERS, STABLE_DIR_NAMES, spec}; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + + struct TempDir(PathBuf); + + impl TempDir { + fn new(label: &str) -> Self { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("pdfcraft-profile-root-{label}-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let canonical = std::fs::canonicalize(&dir).unwrap(); + Self(canonical) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn spec_preserves_pdfcraft_isolation_contract() { + let spec = spec(); + assert_eq!(spec.app_id, "pdfcraft"); + assert_eq!(spec.display_name, "PdfCraft"); + assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES); + assert_eq!(spec.stable_package_id, "ai.storyteller.pdfcraft"); + assert_eq!(spec.nightly_package_id, NIGHTLY_FLATPAK_ID); + assert_eq!(nightly_flatpak_id(spec.app_id), NIGHTLY_FLATPAK_ID); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, &FORBIDDEN_ENV_VARS); + assert_eq!(spec.portable_markers, &PORTABLE_MARKERS); + assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS); + } + + #[test] + fn failed_profile_preparation_does_not_start_with_stable() { + let dir = TempDir::new("file-root"); + let root = dir.0.join("not-a-directory"); + std::fs::write(&root, b"an ordinary file").unwrap(); + let argv = craft_nightly::launch_arguments(&root, &[]); + let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv); + assert!(matches!(result, Err(ProfileError::NotADirectory(_)))); + assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file"); + } + + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let dir = TempDir::new("reopen"); + let private = dir.0.join("nightly-reopen"); + let spec = spec(); + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + for name in ["app.ron", "config.toml", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!( + matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), + "{name} must stay a directory" + ); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + + #[test] + fn extra_forbidden_root_overlap_is_refused() { + let dir = TempDir::new("overlap"); + let forbidden = dir.0.join("stable-install"); + std::fs::create_dir_all(&forbidden).unwrap(); + let mut spec = spec(); + spec.extra_forbidden_roots.push(forbidden.clone()); + assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&forbidden.join("child"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_dangling_entry_inside_the_profile_is_refused_before_writes() { + let dir = TempDir::new("dangling"); + let outside = dir.0.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let private = dir.0.join("nightly-dangling"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec()), Err(ProfileError::SymlinkEntry(_)))); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + } + + #[cfg(unix)] + #[test] + fn hardlinked_profile_file_is_refused() { + let dir = TempDir::new("hardlink"); + let private = dir.0.join("nightly-hardlink"); + let spec = spec(); + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + let external = dir.0.join("external.ron"); + std::fs::write(&external, b"shared").unwrap(); + std::fs::hard_link(&external, private.join("app.ron")).unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::HardlinkedEntry { .. }))); + } +} diff --git a/apps/pdfcraft/src/single_instance.rs b/apps/pdfcraft/src/single_instance.rs index a238c79bcb..f6e68e91d1 100644 --- a/apps/pdfcraft/src/single_instance.rs +++ b/apps/pdfcraft/src/single_instance.rs @@ -159,26 +159,29 @@ pub fn absolute(paths: &[String]) -> Vec { /// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false /// when the launch asked for anything besides opening (or, with `combine`, combining) files, so /// it gets its own window. -pub fn claim(files: &[String], may_hand_off: bool, combine: bool) -> Claim { +pub fn claim(files: &[String], may_hand_off: bool, combine: bool, profile_root: Option<&std::path::Path>) -> Claim { #[cfg(any(windows, all(unix, not(target_os = "macos"))))] { - match socket_path() { + match socket_path(profile_root) { Some(path) => claim_at(&path, files, may_hand_off, combine), None => Claim::Alone, } } #[cfg(not(any(windows, all(unix, not(target_os = "macos")))))] { - let _ = (files, may_hand_off, combine); + let _ = (files, may_hand_off, combine, profile_root); Claim::Alone } } -/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder); none when -/// `%LOCALAPPDATA%` is unset. +/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder), or inside the +/// nightly profile's `single-instance` folder when running isolated; none when `%LOCALAPPDATA%` is unset. #[cfg(windows)] -fn socket_path() -> Option { +fn socket_path(profile_root: Option<&std::path::Path>) -> Option { let name = socket_name(session_id(), std::env::var("SESSIONNAME").ok().as_deref()); + if let Some(root) = profile_root { + return Some(root.join("single-instance").join(name)); + } // %LOCALAPPDATA% is private to the user's sign-in, so other accounts can't receive this // user's file paths or send it files to open. A portable copy uses it too (#889), under its // own name so it never hands files to an installed copy (which keeps its settings elsewhere). @@ -187,12 +190,15 @@ fn socket_path() -> Option { std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("PdfCraft").join(name)) } -/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`; none when `$XDG_RUNTIME_DIR` is unset. Never `/tmp` -/// instead: other accounts can create files there, and so could listen in this user's place. +/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`, or inside the nightly profile's `single-instance` +/// folder when running isolated; none when `$XDG_RUNTIME_DIR` is unset. #[cfg(all(unix, not(target_os = "macos")))] -fn socket_path() -> Option { +fn socket_path(profile_root: Option<&std::path::Path>) -> Option { let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let name = display_socket_name(var("WAYLAND_DISPLAY").or_else(|| var("DISPLAY")).as_deref()); + if let Some(root) = profile_root { + return Some(root.join("single-instance").join(name)); + } // The XDG base directory spec makes it the user's own (mode 0700), so the folder inside it is // out of other accounts' reach whatever the umask. var("XDG_RUNTIME_DIR").map(|d| std::path::PathBuf::from(d).join("pdfcraft").join(name)) @@ -476,7 +482,7 @@ mod tests { let id = super::session_id(); assert!(id.is_some(), "the access token names the session"); let name = socket_name(id, None); - assert!(socket_path().is_none_or(|p| p.file_name().is_some_and(|f| f.to_string_lossy().ends_with(&name))), "{name}"); + assert!(socket_path(None).is_none_or(|p| p.file_name().is_some_and(|f| f.to_string_lossy().ends_with(&name))), "{name}"); } #[cfg(any(windows, all(unix, not(target_os = "macos"))))] @@ -540,4 +546,12 @@ mod tests { assert!(std::fs::symlink_metadata(&path).is_ok(), "the socket file stays behind"); assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true, false), Claim::Primary(_))); } + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + #[test] + fn nightly_profile_root_isolates_the_single_instance_socket() { + let root = std::env::temp_dir().join(format!("pdfcraft-si-nightly-{}", std::process::id())); + let path = socket_path(Some(&root)).unwrap(); + assert_eq!(path.parent(), Some(root.join("single-instance").as_path())); + } } diff --git a/apps/pdfcraft/src/startup.rs b/apps/pdfcraft/src/startup.rs index 8e0d9e356b..ebef8ffe25 100644 --- a/apps/pdfcraft/src/startup.rs +++ b/apps/pdfcraft/src/startup.rs @@ -28,11 +28,25 @@ impl Arguments { !self.new_window && !self.files.is_empty() && self.options.is_empty() && self.control_port.is_none() && !self.create_images && !self.two_paged } + /// Launcher-provided filenames follow a delimiter, not the ordinary option parser. Direct + /// Nightly launches still accept the normal application options before a delimiter. + pub fn parse_for_profile(args: impl IntoIterator, nightly: bool) -> Self { + if nightly { Self::parse_impl(args, true) } else { Self::parse(args) } + } + pub fn parse(args: impl IntoIterator) -> Self { + Self::parse_impl(args, false) + } + + fn parse_impl(args: impl IntoIterator, literal_separator: bool) -> Self { let mut parsed = Self::default(); let mut args = args.into_iter(); while let Some(a) = args.next() { match a.as_str() { + "--" if literal_separator => { + parsed.files.extend(args.map(craft::platform::default_app::path_from_arg)); + break; + } "--version" => { parsed.version = true; break; @@ -126,6 +140,17 @@ mod tests { Arguments::parse(args.iter().map(|s| s.to_string())) } + #[test] + fn nightly_delimiter_keeps_launcher_file_names_literal() { + let parsed = Arguments::parse_for_profile(["--", "--two-paged", "document.pdf"].map(str::to_owned), true); + assert_eq!(parsed.files, ["--two-paged", "document.pdf"]); + assert!(!parsed.two_paged); + assert!(parsed.options.is_empty()); + let direct = Arguments::parse_for_profile(["--two-paged", "document.pdf"].map(str::to_owned), true); + assert!(direct.two_paged); + assert_eq!(direct.files, ["document.pdf"]); + } + #[test] fn standalone_flag_keeps_files_in_either_position() { for args in diff --git a/apps/pdfcraft/src/tests.rs b/apps/pdfcraft/src/tests.rs index 1bf079223b..3334cb1a29 100644 --- a/apps/pdfcraft/src/tests.rs +++ b/apps/pdfcraft/src/tests.rs @@ -19,6 +19,71 @@ pub(crate) fn install_runtime(ctx: &egui::Context) { craft::ui::shell::embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(Lang::EN)).expect("the runtime installs on a fresh context"); } +#[test] +fn a_power_preference_without_an_explicit_renderer_retries_native_opengl_on_windows() { + use eframe::wgpu::Backends; + for power in [false, true] { + for renderer in [false, true] { + assert_eq!(super::automatic_windows_backends(false, false, power, renderer), None); + assert_eq!(super::automatic_windows_backends(true, true, power, renderer), None); + let expected = if power && !renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL }; + assert_eq!(super::automatic_windows_backends(true, false, power, renderer), Some(expected)); + } + } +} + +#[test] +fn on_windows_wgpu_leaves_an_opengl_only_gpu_to_eframes_opengl_renderer() { + use eframe::wgpu::Backend; + // Issues #4134 and #5553: an Intel HD 4000 has no Direct3D 12 driver, so wgpu picks its + // OpenGL backend, which fails a few seconds after the window opens. + assert!(!super::wgpu_draws_with(Backend::Gl, true, false), "declined, so the start-up retry uses glow"); + // Everything else draws with wgpu as before. + assert!(super::wgpu_draws_with(Backend::Dx12, true, false)); + assert!(super::wgpu_draws_with(Backend::Gl, true, true), "WGPU_BACKEND asked for it"); + for backend in [Backend::Gl, Backend::Vulkan, Backend::Metal] { + assert!(super::wgpu_draws_with(backend, false, false), "{backend:?} off Windows"); + } +} + +#[test] +fn pick_adapter_takes_a_gpus_opengl_adapter_last_and_an_opengl_only_gpu_over_software() { + use eframe::wgpu::{Backend, DeviceType}; + // wgpu's OpenGL adapter has its vendor's id, no device id, and a kind guessed from its + // strings: every Intel GPU is integrated, and most others are "other" (wgpu-hal's gles + // `make_info`). + let gl = |vendor: u32, kind| (vendor, 0, kind, Backend::Gl); + // A GPU offered through OpenGL and through Direct3D 12 or Vulkan, in either order, with or + // without a known display: never OpenGL, which `wgpu_draws_with` declines on Windows. + const ARC: (u32, u32) = (0x8086, 0x56a0); + for other in [Backend::Dx12, Backend::Vulkan] { + for (gpu, kind, guessed) in [ + (INTEL_IGPU, DeviceType::IntegratedGpu, DeviceType::IntegratedGpu), + // An Intel discrete GPU, which wgpu's OpenGL backend calls integrated (CodeRabbit). + (ARC, DeviceType::DiscreteGpu, DeviceType::IntegratedGpu), + (NVIDIA, DeviceType::DiscreteGpu, DeviceType::Other), + ] { + let gl_first = [gl(gpu.0, guessed), (gpu.0, gpu.1, kind, other)]; + for displays in [&[panel(gpu)][..], &[]] { + assert_eq!(super::pick_adapter(&gl_first, displays, None), Some(1), "{gpu:x?} {other:?} {displays:?}"); + assert_eq!(super::pick_adapter(&[gl_first[1], gl_first[0]], displays, None), Some(0), "{gpu:x?} {other:?} {displays:?}"); + } + } + } + // Issue #4134: an Intel HD 4000 has only OpenGL, and the Microsoft Basic Render Driver (in + // software) has Direct3D 12. The GPU is still picked, by kind, with or without a known + // display, as over Remote Desktop; declining it then starts glow on that GPU. + const HD_4000: (u32, u32) = (0x8086, 0x0166); + let ivy_bridge = [(0x1414, 0x008c, DeviceType::Cpu, Backend::Dx12), gl(HD_4000.0, DeviceType::IntegratedGpu)]; + assert_eq!(super::pick_adapter(&ivy_bridge, &[panel(HD_4000)], None), Some(1)); + assert_eq!(super::pick_adapter(&ivy_bridge, &[], None), Some(1)); + assert!(!super::wgpu_draws_with(Backend::Gl, true, false)); + // Only OpenGL, or only software: that adapter. + assert_eq!(super::pick_adapter(&ivy_bridge[1..], &[], None), Some(0)); + assert_eq!(super::pick_adapter(&ivy_bridge[..1], &[], None), Some(0)); + assert_eq!(super::pick_adapter(&[], &[], None), None); +} + #[test] fn opengl_is_the_fallback_unless_a_renderer_was_chosen() { use super::{RendererChoice, native_options, renderer_choice, retry_with_gl}; @@ -322,9 +387,13 @@ const NVIDIA: (u32, u32) = (0x10de, 0x2684); const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204); const AMD_IGPU: (u32, u32) = (0x1002, 0x164e); -fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType)> { - use eframe::wgpu::DeviceType; - vec![(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu), (0, 0, DeviceType::Cpu)] +fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> { + use eframe::wgpu::{Backend, DeviceType}; + vec![ + (NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan), + (AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan), + (0, 0, DeviceType::Cpu, Backend::Vulkan), + ] } const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780); @@ -391,8 +460,12 @@ fn pick_adapter_keeps_the_integrated_gpu_on_hybrid_laptops() { #[test] fn pick_adapter_prefers_the_discrete_gpu_on_desktops_with_a_monitor_on_each() { // Issue #445: one monitor on the Intel iGPU, one on the NVIDIA card, no built-in panel. - use eframe::wgpu::DeviceType; - let desktop = [(INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu), (NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (0, 0, DeviceType::Cpu)]; + use eframe::wgpu::{Backend, DeviceType}; + let desktop = [ + (INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan), + (NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan), + (0, 0, DeviceType::Cpu, Backend::Vulkan), + ]; assert_eq!(super::pick_adapter(&desktop, &[monitor(INTEL_IGPU), monitor(NVIDIA)], None), Some(1)); assert_eq!(super::pick_adapter(&desktop, &[monitor(NVIDIA), monitor(INTEL_IGPU)], None), Some(1)); // A GPU driving no display still loses to one that does. diff --git a/apps/pdfcraft/src/window_placement.rs b/apps/pdfcraft/src/window_placement.rs new file mode 100644 index 0000000000..b5f085536d --- /dev/null +++ b/apps/pdfcraft/src/window_placement.rs @@ -0,0 +1,101 @@ +//! Keep the restored Windows window on its monitor after a first launch or DPI change. + +use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; +use winsafe::{HMONITOR, HWND, POINT, RECT, WINDOWPLACEMENT, co}; + +pub(super) fn restore(window: &winit::window::Window) { + // Presentation belongs to the document session. An OS fullscreen flag restored + // by eframe while PdfCraft is showing Home otherwise leaves Home without captions. + if window.fullscreen().is_some() { + window.set_fullscreen(None); + } + let Ok(handle) = window.window_handle() else { return }; + let RawWindowHandle::Win32(raw) = handle.as_raw() else { return }; + // Borrow the matching handle from the window thread using winsafe's safe API. + if let Err(error) = winsafe::EnumThreadWindows(winsafe::GetCurrentThreadId(), |hwnd| { + if hwnd.ptr() as isize == raw.hwnd.get() + && let Err(error) = fit_restore_bounds(&hwnd) + { + log::warn!("could not fit the restored PdfCraft window: {error}"); + } + true + }) { + log::warn!("could not read the PdfCraft window placement: {error}"); + } +} + +fn fit_restore_bounds(hwnd: &HWND) -> winsafe::SysResult<()> { + let mut placement = WINDOWPLACEMENT::default(); + hwnd.GetWindowPlacement(&mut placement)?; + let monitor = hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()?; + // WINDOWPLACEMENT for the main window is in workspace coordinates. Monitor work + // areas are in screen coordinates, including the taskbar's left/top displacement. + let dx = monitor.rcWork.left - monitor.rcMonitor.left; + let dy = monitor.rcWork.top - monitor.rcMonitor.top; + let r = placement.rcNormalPosition; + let screen = RECT { left: r.left + dx, right: r.right + dx, top: r.top + dy, bottom: r.bottom + dy }; + if let Some(bounds) = fitted(screen, monitor.rcWork) { + // On vertically staggered monitors, opposite corners can be visible while + // the top-right caption controls are in the gap between screens. + let corners = [ + POINT { x: screen.left, y: screen.top }, + POINT { x: screen.right - 1, y: screen.top }, + POINT { x: screen.left, y: screen.bottom - 1 }, + POINT { x: screen.right - 1, y: screen.bottom - 1 }, + ]; + if corners.iter().all(|p| { + HMONITOR::MonitorFromPoint(*p, co::MONITOR::DEFAULTTONULL) + .GetMonitorInfo() + .is_ok_and(|m| p.x >= m.rcWork.left && p.x < m.rcWork.right && p.y >= m.rcWork.top && p.y < m.rcWork.bottom) + }) { + return Ok(()); + } + placement.rcNormalPosition = RECT { left: bounds.left - dx, right: bounds.right - dx, top: bounds.top - dy, bottom: bounds.bottom - dy }; + // Keep showCmd: maximized windows stay maximized, but Restore gets usable bounds. + hwnd.SetWindowPlacement(&placement)?; + } + Ok(()) +} + +fn fitted(rect: RECT, work: RECT) -> Option { + let width = rect.right.saturating_sub(rect.left); + let height = rect.bottom.saturating_sub(rect.top); + let room_x = work.right.saturating_sub(work.left); + let room_y = work.bottom.saturating_sub(work.top); + if width <= 0 || height <= 0 || room_x <= 0 || room_y <= 0 { + return None; + } + if rect.left >= work.left && rect.top >= work.top && rect.right <= work.right && rect.bottom <= work.bottom { + return None; + } + // A screen-sized default plus Windows' cascaded origin is the common first-run case. + // Leave room around the restored window so Maximize and Restore are visibly distinct. + let (width, height) = + if width >= room_x && height >= room_y { (room_x - room_x / 10, room_y - room_y / 10) } else { (width.min(room_x), height.min(room_y)) }; + let left = rect.left.clamp(work.left, work.right - width); + let top = rect.top.clamp(work.top, work.bottom - height); + Some(RECT { left, top, right: left + width, bottom: top + height }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restore_after_high_dpi_startup_keeps_the_caption_controls_on_screen() { + let work = RECT { left: 0, top: 0, right: 3456, bottom: 2040 }; + let old = RECT { left: 305, top: 305, right: 3761, bottom: 2465 }; + let expected = RECT { left: 305, top: 204, right: 3416, bottom: 2040 }; + assert!(fitted(old, work) == Some(expected)); + assert!(fitted(work, work).is_none()); + } + + #[test] + fn a_saved_window_keeps_its_size_and_monitor_when_only_its_origin_is_wrong() { + let work = RECT { left: -1920, top: 40, right: 0, bottom: 1080 }; + let old = RECT { left: -620, top: 200, right: 580, bottom: 900 }; + let expected = RECT { left: -1200, top: 200, right: 0, bottom: 900 }; + assert!(fitted(old, work) == Some(expected)); + assert!(fitted(expected, work).is_none()); + } +} diff --git a/apps/pdfcraft/tests/startup_log.rs b/apps/pdfcraft/tests/startup_log.rs new file mode 100644 index 0000000000..c0acf66791 --- /dev/null +++ b/apps/pdfcraft/tests/startup_log.rs @@ -0,0 +1,106 @@ +#![cfg(target_os = "linux")] +//! The logger must reach disk while the real desktop app is running, before it can be closed. +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +struct Running(Child); +impl Drop for Running { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_none() { + let _ = self.0.kill(); + } + let _ = self.0.wait(); + } +} + +#[test] +fn startup_breadcrumbs_reach_the_portable_log_before_quit() { + use std::os::unix::fs::PermissionsExt; + let xvfb = Command::new("Xvfb").args(["-displayfd", "1", "-screen", "0", "1024x768x24", "-nolisten", "tcp"]).stdout(Stdio::piped()).spawn(); + let mut display = match xvfb { + Ok(p) => Running(p), + Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::env::var_os("CI").is_none() => { + eprintln!("Xvfb is needed to exercise desktop startup"); + return; + } + Err(e) => panic!("start Xvfb: {e}"), + }; + let mut number = String::new(); + BufReader::new(display.0.stdout.take().unwrap()).read_line(&mut number).unwrap(); + assert!(!number.trim().is_empty(), "Xvfb did not open a display"); + + let root = std::env::temp_dir().join(format!("pdfcraft-startup-log-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); + let exe = root.join("pdfcraft"); + let bin = env!("CARGO_BIN_EXE_pdfcraft"); + if std::fs::hard_link(bin, &exe).is_err() { + std::fs::copy(bin, &exe).unwrap(); + } + std::fs::write(root.join("portable.txt"), []).unwrap(); + let port = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port(); + let mut secret = [0_u8; 32]; + std::fs::File::open("/dev/urandom").unwrap().read_exact(&mut secret).unwrap(); + let token: String = secret.iter().map(|byte| format!("{byte:02x}")).collect(); + let mut app = Running( + Command::new(exe) + .args(["--new-window", "--control", &port.to_string()]) + .env("PDFCRAFT_CONTROL_TOKEN", &token) + .env("HOME", &root) + .env("XDG_RUNTIME_DIR", &root) + .env("XDG_CONFIG_HOME", &root) + .env("XDG_DATA_HOME", &root) + .env_remove("WAYLAND_DISPLAY") + .env_remove("PDFCRAFT_CONFIG_DIR") + .env("DISPLAY", format!(":{}", number.trim())) + .env("PDFCRAFT_RENDERER", "gl") + .env("RUST_LOG", "info") + .env("LIBGL_ALWAYS_SOFTWARE", "1") + .spawn() + .unwrap(), + ); + let deadline = Instant::now() + Duration::from_secs(60); + let log = root.join("PdfCraftData/logs/pdfcraft.log"); + let mut socket = loop { + if log.exists() + && std::fs::read_to_string(&log).unwrap_or_default().contains("first UI pass finished") + && let Ok(socket) = TcpStream::connect(("127.0.0.1", port)) + { + break socket; + } + assert!(app.0.try_wait().unwrap().is_none(), "PdfCraft exited during startup"); + assert!(Instant::now() < deadline, "startup log: {:?}", std::fs::read_to_string(&log)); + std::thread::sleep(Duration::from_millis(100)); + }; + let log = std::fs::read_to_string(log).unwrap(); + let mut rest = log.as_str(); + for stage in [ + "claiming application instance", + "reading startup preferences", + "initializing OpenGL", + "renderer ready, installing fonts and runtime", + "initializing application and recovery", + "applying preferences", + "restoring session and opening requested documents", + "entering UI event loop", + "first UI pass finished", + ] { + rest = rest.split_once(stage).unwrap_or_else(|| panic!("missing or misordered stage {stage}: {log}")).1; + } + socket.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut read = BufReader::new(socket.try_clone().unwrap()); + for (method, params) in [("auth", serde_json::json!({"token":token})), ("ui.quit", serde_json::json!({}))] { + writeln!(socket, "{}", serde_json::json!({"id":1,"method":method,"params":params})).unwrap(); + let mut reply = String::new(); + read.read_line(&mut reply).unwrap(); + assert_eq!(serde_json::from_str::(&reply).unwrap()["ok"], true); + } + while app.0.try_wait().unwrap().is_none() { + assert!(Instant::now() < deadline, "PdfCraft did not quit"); + std::thread::sleep(Duration::from_millis(100)); + } + assert!(app.0.wait().unwrap().success()); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/apps/pdfcraft/tests/winit_startup_token.rs b/apps/pdfcraft/tests/winit_startup_token.rs new file mode 100644 index 0000000000..ab398605f1 --- /dev/null +++ b/apps/pdfcraft/tests/winit_startup_token.rs @@ -0,0 +1,38 @@ +//! vendor/winit patch (14) (vendor/README.md). + +#[test] +fn winit_hands_the_launchers_activation_token_back() { + // A launcher with `StartupNotify=true` (the packaged desktop entry) passes an activation token + // in `XDG_ACTIVATION_TOKEN` (Wayland) or `DESKTOP_STARTUP_ID` (X11) and shows a busy cursor + // until a window hands it back. eframe never gives winit a token, so GNOME kept the busy + // cursor for 15 seconds and the window opened without focus. vendor/winit gives the first + // window the environment's token. The policy is tested beside it (`startup_token::tests`, run + // them in the vendored crate); this guards the copy, which workspace tests don't test. A + // re-vendored copy without the patch would silently bring the bug back: re-apply the patch, or + // drop the copy once winit or eframe hands the token back. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let linux = root.join("vendor/winit/src/platform_impl/linux"); + let module = std::fs::read_to_string(linux.join("mod.rs")).unwrap(); + assert!(module.contains("mod startup_token;")); + let (_, new) = module.split_once(" pub(crate) fn new(\n window_target: &ActiveEventLoop,").expect("Window::new moved"); + let new = new.split_once("\n }\n").map_or(new, |(body, _)| body); + assert!( + new.contains("startup_token::for_new_window(given, startup_notify::WAYLAND_VAR)"), + "a Wayland window no longer takes the launcher's token" + ); + assert!(new.contains("startup_token::for_new_window(given, startup_notify::X11_VAR)"), "an X11 window no longer takes the launcher's token"); + assert_eq!(new.matches("reservation.commit();").count(), 2, "a created window no longer spends the launcher's token"); + // The backends mark the token spent where they hand it back, so a window that fails earlier + // releases it for a retry and one that fails later doesn't reuse it. + for backend in ["wayland/window/mod.rs", "x11/window.rs"] { + let source = std::fs::read_to_string(linux.join(backend)).unwrap(); + assert!(source.contains("startup_token::handing_back();"), "{backend} no longer marks the token spent at its handoff"); + } + let policy = std::fs::read_to_string(linux.join("startup_token.rs")).unwrap(); + assert!(policy.contains("fn the_first_window_takes_the_launchers_token")); + assert!(policy.contains("fn a_later_window_does_not_reuse_the_spent_token")); + assert!(policy.contains("fn a_window_that_fails_before_handing_the_token_back_releases_it")); + // The token reaches the app only when the launcher asks for startup notification. + let desktop = std::fs::read_to_string(root.join("packaging/linux/ai.storyteller.pdfcraft.desktop")).unwrap(); + assert!(desktop.contains("StartupNotify=true")); +} diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..3ac24defd4 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,24 @@ +{ + "schema": "craft-nightly-icon-provenance/v1", + "app": "pdfcraft", + "channel": "nightly-v1", + "source": { + "master": "assets/app-icon/pdfcraft-1024.png", + "note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon." + }, + "transform": { + "summary": "The app mark (white/light strokes and their antialiasing) is copied unchanged; only the background square is deepened.", + "background": { + "from": "#b70228", + "to": "#710118", + "rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were." + } + }, + "outputs": { + "pdfcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as pdfcraft-nightly.png", + "pdfcraft-nightly-1024.png": "the padded 1024 master the icns is generated from", + "pdfcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon", + "pdfcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile pdfcraft-nightly)" + }, + "not_done_here": "No badge, crescent or N was added, and the stable pdfcraft.png/.ico/.icns files are untouched." +} diff --git a/assets/app-icon/pdfcraft-nightly-1024.png b/assets/app-icon/pdfcraft-nightly-1024.png new file mode 100644 index 0000000000..cad0c50217 Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly-1024.png differ diff --git a/assets/app-icon/pdfcraft-nightly.icns b/assets/app-icon/pdfcraft-nightly.icns new file mode 100644 index 0000000000..6f83b1074c Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.icns differ diff --git a/assets/app-icon/pdfcraft-nightly.ico b/assets/app-icon/pdfcraft-nightly.ico new file mode 100644 index 0000000000..0055d411d8 Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.ico differ diff --git a/assets/app-icon/pdfcraft-nightly.png b/assets/app-icon/pdfcraft-nightly.png new file mode 100644 index 0000000000..4fcac4c02d Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.png differ diff --git a/assets/icons/LICENSE-freehand-highlighter.txt b/assets/icons/LICENSE-freehand-highlighter.txt new file mode 100644 index 0000000000..797bbe4e15 --- /dev/null +++ b/assets/icons/LICENSE-freehand-highlighter.txt @@ -0,0 +1,116 @@ +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see +http://creativecommons.org/publicdomain/zero/1.0/ diff --git a/assets/icons/chevrons-down.svg b/assets/icons/chevrons-down.svg new file mode 100644 index 0000000000..bcd2f90911 --- /dev/null +++ b/assets/icons/chevrons-down.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/chevrons-up.svg b/assets/icons/chevrons-up.svg new file mode 100644 index 0000000000..9355beb141 --- /dev/null +++ b/assets/icons/chevrons-up.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/freehand-highlighter.svg b/assets/icons/freehand-highlighter.svg new file mode 100644 index 0000000000..af54ac42fd --- /dev/null +++ b/assets/icons/freehand-highlighter.svg @@ -0,0 +1,12 @@ + + + + diff --git a/assets/icons/pin-off.svg b/assets/icons/pin-off.svg new file mode 100644 index 0000000000..924c784025 --- /dev/null +++ b/assets/icons/pin-off.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/clippy.toml b/clippy.toml index 31e54da30f..16518d262e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -12,9 +12,41 @@ disallowed-methods = [ { path = "egui::Ui::radio", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::Ui::radio_value", reason = "use radio_value from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, { path = "egui::RadioButton::new", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" }, + # The raw RSA private-key operations: see disallowed-types below. + { path = "rsa::hazmat::rsa_decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::hazmat::rsa_decrypt_and_check", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + # The ways to make or use an `rsa` private key, so a key whose type is never named (one + # returned by another crate, or a generic over these traits) is caught too. The generic + # `signature` and `pkcs8` traits are left out: the ECDSA keys use them as well. + { path = "rsa::RsaPrivateKey::new", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::new_with_exp_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_components_with_large_exponent", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_p_q", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::from_primes", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::decrypt_blinded", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::RsaPrivateKey::sign_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::Decryptor::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::RandomizedDecryptor::decrypt_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::PaddingScheme::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::traits::SignatureScheme::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, ] -cognitive-complexity-threshold = 30 +# deny.toml ignores the Marvin advisory (RUSTSEC-2023-0071) because `rsa` is only used to verify +# signatures; RSA private-key operations use aws-lc-rs (ADR-0009). These are the `rsa` types +# that hold a private key, and above are the functions and methods that make or use one, so a +# private-key operation through `rsa` fails clippy instead. disallowed-types = [ + { path = "rsa::RsaPrivateKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pkcs1v15::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::pss::BlindedSigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, + { path = "rsa::oaep::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" }, { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, ] +cognitive-complexity-threshold = 30 diff --git a/contributors/people.toml b/contributors/people.toml index a150fe5276..bc38c2967c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -197,3 +197,11 @@ sync_github_name = true [people.Yousef-Dev921] sync_github_name = true + +[people.marcoarnulfo] +real_name = "Marco Arnulfo" +display_name = "Marco Arnulfo" +sync_github_name = false + +[people.gmrmad1] +real_name = "Madhav Agarwal" diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs index 29e48409ba..33885fa6f4 100644 --- a/crates/a11y/src/alt.rs +++ b/crates/a11y/src/alt.rs @@ -23,6 +23,10 @@ pub enum AltError { Untagged, #[error("object {0} is not a figure")] NotAFigure(u32), + #[error("the tag has child structure elements; mark a leaf tag instead")] + HasChildren, + #[error("this action does not support form streams, annotation or object references, other pages or invalid content references")] + UnsupportedContent, #[error("the page has more content than can be edited")] TooLarge, #[error("the figure's content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")] @@ -42,6 +46,8 @@ pub enum ArtifactError { HasChildren, #[error("the tag has no direct marked content")] NoMarkedContent, + #[error("this action does not support form streams, annotation or object references, other pages or invalid content references")] + UnsupportedContent, #[error("the tag has no page")] NoPage, #[error("the tag's marked content was not found on its page")] @@ -154,6 +160,74 @@ fn mcids(doc: &Document, d: &Dict) -> Vec { out } +/// Validation for the page-only destructive actions. Readout keeps its existing MCID reader. +enum MutationContentError { + HasChildren, + Unsupported, +} + +fn mutation_mcids(doc: &Document, tag: &Dict, page: Option) -> Result, MutationContentError> { + fn visit( + doc: &Document, + item: &Object, + page: Option, + depth: usize, + remaining: &mut usize, + ancestors: &mut HashSet, + ids: &mut HashSet, + ) -> Result<(), MutationContentError> { + if depth > 64 || *remaining == 0 { + return Err(MutationContentError::Unsupported); + } + *remaining -= 1; + match item { + Object::Int(id) if *id >= 0 => { + ids.insert(*id); + } + Object::Array(items) => { + for item in items { + visit(doc, item, page, depth + 1, remaining, ancestors, ids)?; + } + } + Object::Ref(reference) => { + if reference.generation != doc.generation(reference.num) || !ancestors.insert(*reference) { + return Err(MutationContentError::Unsupported); + } + let result = visit(doc, &doc.get(*reference), page, depth + 1, remaining, ancestors, ids); + ancestors.remove(reference); + result?; + } + Object::Dict(dict) => { + if dict.contains(b"S") { + // Retiring a parent also removes descendants whose content was not checked. + return Err(MutationContentError::HasChildren); + } + // Presence matters: even a malformed stream qualifier must not become a page ID. + // Never resolve these targets; this action does not support form streams. + if dict.contains(b"Stm") || dict.contains(b"StmOwn") || dict.name(b"Type") != Some(b"MCR") { + return Err(MutationContentError::Unsupported); + } + if let Some(explicit_page) = dict.get(b"Pg") { + let explicit_page = explicit_page.as_ref().ok_or(MutationContentError::Unsupported)?; + if Some(explicit_page) != page { + return Err(MutationContentError::Unsupported); + } + } + let id = dict.get(b"MCID").and_then(Object::as_int).filter(|id| *id >= 0).ok_or(MutationContentError::Unsupported)?; + ids.insert(id); + } + _ => return Err(MutationContentError::Unsupported), + } + Ok(()) + } + + let mut ids = HashSet::new(); + if let Some(kids) = tag.get(b"K") { + visit(doc, kids, page, 0, &mut 4096, &mut HashSet::new(), &mut ids)?; + } + Ok(ids) +} + /// The page's named property lists (`/Resources /Properties`), which a `BDC` can name instead of /// writing its property list inline. fn page_properties(doc: &Document, page: &Dict) -> Dict { @@ -514,13 +588,21 @@ fn artifact_marked_content( } /// Decorative figure: its marked content on the page becomes an artifact, and the element -/// leaves the structure tree (and the parent tree). +/// leaves the structure tree (and the parent tree). Form references and structure children refuse +/// before the document changes. pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> { let d = check_figure(doc, obj)?; - let ids: HashSet = mcids(doc, &d).into_iter().collect(); let pages = pdfcraft_model::pages(doc); let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page)); - if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) { + let page = pg.and_then(|p| pages.iter().find(|page| page.obj == p)); + let ids = mutation_mcids(doc, &d, page.map(|page| page.obj)).map_err(|error| match error { + MutationContentError::HasChildren => AltError::HasChildren, + MutationContentError::Unsupported => AltError::UnsupportedContent, + })?; + if !ids.is_empty() && page.is_none() { + return Err(AltError::UnsupportedContent); + } + if let Some(page) = page.filter(|_| !ids.is_empty()) { let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?; match artifact_marked_content(doc, page, streams, &ids, false)? { // The parent tree no longer points those ids at the figure. @@ -552,16 +634,18 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> /// Mark a leaf structure tag's directly owned marked content as an artifact. /// /// This deliberately refuses a tag with child structure elements. Converting a parent would -/// otherwise silently discard semantic descendants. The visible page content is preserved: each +/// otherwise silently discard semantic descendants. Form references and invalid page ownership +/// also refuse before the document changes. A missing, ambiguous or mismatched parent also refuses before +/// mutation. The visible page content is preserved: each /// matching marked-content sequence changes from `BDC` with an MCID to `/Artifact BMC`. pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), ArtifactError> { tree_root(doc).ok_or(ArtifactError::Untagged)?; let elements = elements(doc); let Some(element) = elements.iter().find(|e| e.object == obj) else { return Err(ArtifactError::NotATag(obj.num)) }; - if has_child_structure(doc, &element.dict) { - return Err(ArtifactError::HasChildren); - } - let ids: HashSet = mcids(doc, &element.dict).into_iter().collect(); + let ids = mutation_mcids(doc, &element.dict, element.page).map_err(|error| match error { + MutationContentError::HasChildren => ArtifactError::HasChildren, + MutationContentError::Unsupported => ArtifactError::UnsupportedContent, + })?; if ids.is_empty() { return Err(ArtifactError::NoMarkedContent); } @@ -570,6 +654,14 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact let page = pages.iter().find(|page| page.obj == page_ref).ok_or(ArtifactError::NoPage)?; let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?; let replacement = replacement_kids(doc, parent, obj)?; + // The `/P` the tag names must be the parent it was reached from (or the structure root), + // checked before the page changes. + let reachable_parent = element + .parent + .or_else(|| doc.root().and_then(|catalog| doc.get(catalog).as_dict().and_then(|dict| dict.get(b"StructTreeRoot").and_then(Object::as_ref)))); + if reachable_parent != Some(parent) { + return Err(ArtifactError::NoParent); + } let streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?; match artifact_marked_content(doc, page, streams, &ids, true)? { Marked::Done => {} @@ -587,18 +679,6 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact Ok(()) } -fn has_child_structure(doc: &Document, tag: &Dict) -> bool { - fn child(doc: &Document, item: &Object) -> bool { - match item { - Object::Array(items) => items.iter().any(|item| child(doc, item)), - Object::Ref(r) => doc.get(*r).as_dict().is_some_and(|d| d.contains(b"S")), - Object::Dict(d) => d.contains(b"S"), - _ => false, - } - } - tag.get(b"K").is_some_and(|items| child(doc, items)) -} - fn replacement_kids(doc: &Document, parent: ObjRef, obj: ObjRef) -> Result { let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?; match kids { diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index bf3df8d0a4..42dc37b978 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -2,7 +2,10 @@ //! //! Each text object becomes a paragraph, or a heading when its size or weight sets it apart from //! the body text ([`crate::autotag_roles`]); either can be retagged with the existing tag-property -//! tool after human review. Painted paths, shadings and images outside text objects +//! tool after human review. Running headers, footers and page numbers, found by repetition across +//! the pages ([`crate::autotag_running`]), are wrapped in +//! `/Artifact <> BDC … EMC` (or `/Footer`) instead of being +//! tagged. Painted paths, shadings and images outside text objects //! are wrapped in `/Artifact BMC … EMC` so the resulting page passes the tagged-content check. use std::collections::{HashMap, HashSet}; @@ -11,6 +14,7 @@ use pdfcraft_content::{Op, Pieces, serialize_ops}; use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream}; use crate::autotag_roles::{self, Evidence}; +use crate::autotag_running::{self, Edge, Frame, PageText}; const MAX_PAGES: usize = 1_000; const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024; @@ -26,6 +30,21 @@ pub struct AutoTagResult { pub pages: usize, pub paragraphs: usize, pub headings: usize, + /// Text objects marked as running header artifacts. + pub headers: usize, + /// Text objects marked as running footer artifacts, page numbers included. + pub footers: usize, +} + +/// A text object auto-tag marks as a running header or footer instead of tagging it. +#[derive(Clone, Debug, PartialEq)] +pub struct RunningText { + /// 0-based page index. + pub page: usize, + /// `"Header"` or `"Footer"`, the artifact subtype written. + pub subtype: &'static str, + /// The text shown, at most 256 characters. + pub text: String, } #[derive(Debug, thiserror::Error, PartialEq)] @@ -50,6 +69,14 @@ struct Plan { spans: Vec<(usize, usize)>, evidence: Vec, artifacts: HashMap, + frame: Frame, +} + +/// What a text object's span is wrapped in. +#[derive(Clone, Copy)] +enum Mark { + Tag(usize, &'static str), + Running(Edge), } fn unsupported(page: usize, reason: impl Into) -> AutoTagError { @@ -269,7 +296,8 @@ fn plan_page( } let resources = page_fonts(doc, &page.dict); let evidence = autotag_roles::evidence(doc, fonts, &resources, &parsed.ops, &spans); - Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts }) + let frame = Frame { rotation: page.rotation(doc), crop: page.crop(doc) }; + Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts, frame }) } fn plan(doc: &Document) -> Result, AutoTagError> { @@ -301,21 +329,26 @@ fn plan(doc: &Document) -> Result, AutoTagError> { Ok(out) } -fn mark_ops( - ops: Vec, - starts: &HashMap, - ends: &HashSet, - artifacts: &HashMap, -) -> Result, AutoTagError> { +fn mark_ops(ops: Vec, starts: &HashMap, ends: &HashSet, artifacts: &HashMap) -> Result, AutoTagError> { let artifact_ends: HashSet = artifacts.values().copied().collect(); let extra = starts.len().saturating_add(artifacts.len()).saturating_mul(2); let mut marked = Vec::with_capacity(ops.len().saturating_add(extra)); for (at, op) in ops.into_iter().enumerate() { let is_artifact = artifacts.contains_key(&at); - if let Some(&(mcid, role)) = starts.get(&at) { + if let Some(&mark) = starts.get(&at) { let mut properties = Dict::new(); - properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); - marked.push(Op::new("BDC", vec![Object::name(role), Object::Dict(properties)])); + let tag = match mark { + Mark::Tag(mcid, role) => { + properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); + role + } + Mark::Running(edge) => { + properties.set(b"Type".to_vec(), Object::name("Pagination")); + properties.set(b"Subtype".to_vec(), Object::name(edge.subtype())); + "Artifact" + } + }; + marked.push(Op::new("BDC", vec![Object::name(tag), Object::Dict(properties)])); } else if is_artifact { marked.push(Op::new("BMC", vec![Object::name("Artifact")])); } @@ -361,54 +394,107 @@ fn write_structure( Ok(()) } -/// Tag every text object in an untagged PDF as a paragraph or a heading and mark painted paths, shadings and +/// The edge each planned text object repeats at, for running text, per page and span. +fn running(plans: &[Plan]) -> Vec>> { + let pages: Vec> = plans.iter().map(|p| PageText { frame: p.frame, objects: &p.evidence }).collect(); + autotag_running::find(&pages, autotag_roles::body_size(plans.iter().flat_map(|p| &p.evidence))) +} + +/// The running headers, footers and page numbers [`autotag_text`] would mark as artifacts, in page +/// order. Refuses what `autotag_text` refuses, and changes nothing. +pub fn running_text(doc: &Document) -> Result, AutoTagError> { + let plans = plan(doc)?; + let mut out = Vec::new(); + for (page, (plan, edges)) in plans.iter().zip(running(&plans)).enumerate() { + for (evidence, edge) in plan.evidence.iter().zip(edges) { + if let Some(edge) = edge { + out.push(RunningText { page, subtype: edge.subtype(), text: evidence.text.clone() }); + } + } + } + Ok(out) +} + +/// What [`autotag_text`] has written so far. +struct Written { + children: Vec, + numbers: Vec, + result: AutoTagResult, +} + +/// Tag or mark one page's text objects, and write its marked content. +fn tag_page( + next: &mut Document, + document: ObjRef, + page: Plan, + edges: &[Option], + roles: &mut impl Iterator, + written: &mut Written, +) -> Result<(), AutoTagError> { + let (mut starts, mut ends, mut parents) = (HashMap::new(), HashSet::new(), Vec::new()); + let key = i64::try_from(written.result.pages).map_err(|_| AutoTagError::TooManyPages)?; + for (at, &(first, last)) in page.spans.iter().enumerate() { + ends.insert(last); + if let Some(edge) = edges.get(at).copied().flatten() { + starts.insert(first, Mark::Running(edge)); + let count = if edge == Edge::Top { &mut written.result.headers } else { &mut written.result.footers }; + *count = count.saturating_add(1); + continue; + } + let role = roles.next().unwrap_or("P"); + let mcid = parents.len(); + let mut element = Dict::new(); + element.set(b"Type".to_vec(), Object::name("StructElem")); + element.set(b"S".to_vec(), Object::name(role)); + element.set(b"P".to_vec(), Object::Ref(document)); + element.set(b"Pg".to_vec(), Object::Ref(page.page)); + element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); + let reference = next.add(element); + parents.push(Object::Ref(reference)); + written.children.push(Object::Ref(reference)); + starts.insert(first, Mark::Tag(mcid, role)); + let count = if role == "P" { &mut written.result.paragraphs } else { &mut written.result.headings }; + *count = count.saturating_add(1); + } + if !parents.is_empty() { + next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?; + written.numbers.extend([Object::Int(key), Object::Array(parents)]); + written.result.pages = written.result.pages.saturating_add(1); + } + let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?; + let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked))); + next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?; + Ok(()) +} + +/// Tag every text object in an untagged PDF as a paragraph or a heading, mark running headers, +/// footers and page numbers as pagination artifacts, and mark painted paths, shadings and /// images outside text objects as artifacts. The full structure tree, parent tree and /// marked-content IDs are written together. Unsupported operators are refused before any /// mutation. On success the caller can use tag-property edits to correct the roles after review. pub fn autotag_text(doc: &mut Document) -> Result { let plans = plan(doc)?; - let all: Vec = plans.iter().flat_map(|p| p.evidence.iter().copied()).collect(); - let mut roles = autotag_roles::roles(&all).into_iter(); + let running = running(&plans); + // Running text is left out of the body style and the heading levels, as it is out of the tags. + let tagged: Vec = plans + .iter() + .zip(&running) + .flat_map(|(p, edges)| p.evidence.iter().zip(edges).filter(|(_, edge)| edge.is_none()).map(|(e, _)| e.clone())) + .collect(); + let mut roles = autotag_roles::roles(&tagged).into_iter(); let mut next = doc.clone(); let catalog = next.root().ok_or(AutoTagError::NoCatalog)?; let (root, document) = (next.add(Object::Null), next.add(Object::Null)); - let (mut children, mut numbers, mut tagged_pages, mut paragraphs, mut headings) = (Vec::new(), Vec::new(), 0usize, 0usize, 0usize); - for page in plans { + let result = AutoTagResult { pages: 0, paragraphs: 0, headings: 0, headers: 0, footers: 0 }; + let mut written = Written { children: Vec::new(), numbers: Vec::new(), result }; + for (page, edges) in plans.into_iter().zip(running) { if page.spans.is_empty() && page.artifacts.is_empty() { continue; } - let (mut starts, mut ends) = (HashMap::new(), HashSet::new()); - if !page.spans.is_empty() { - let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?; - let mut parents = Vec::with_capacity(page.spans.len()); - for (mcid, (first, last)) in page.spans.iter().enumerate() { - let role = roles.next().unwrap_or("P"); - let mut element = Dict::new(); - element.set(b"Type".to_vec(), Object::name("StructElem")); - element.set(b"S".to_vec(), Object::name(role)); - element.set(b"P".to_vec(), Object::Ref(document)); - element.set(b"Pg".to_vec(), Object::Ref(page.page)); - element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?)); - let reference = next.add(element); - parents.push(Object::Ref(reference)); - children.push(Object::Ref(reference)); - starts.insert(*first, (mcid, role)); - ends.insert(*last); - if role == "P" { - paragraphs = paragraphs.saturating_add(1); - } else { - headings = headings.saturating_add(1); - } - } - next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?; - numbers.extend([Object::Int(key), Object::Array(parents)]); - tagged_pages += 1; - } - let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?; - let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked))); - next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?; + tag_page(&mut next, document, page, &edges, &mut roles, &mut written)?; } - write_structure(&mut next, catalog, root, document, children, numbers, tagged_pages)?; + let Written { children, numbers, result } = written; + write_structure(&mut next, catalog, root, document, children, numbers, result.pages)?; *doc = next; - Ok(AutoTagResult { pages: tagged_pages, paragraphs, headings }) + Ok(result) } diff --git a/crates/a11y/src/autotag_roles.rs b/crates/a11y/src/autotag_roles.rs index a72e14a417..516726f45d 100644 --- a/crates/a11y/src/autotag_roles.rs +++ b/crates/a11y/src/autotag_roles.rs @@ -15,7 +15,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object}; use pdfcraft_fonts::pdf::Metrics; /// A line this much larger than body text reads as a heading. -const HEADING_SIZE_RATIO: f64 = 1.15; +pub(crate) const HEADING_SIZE_RATIO: f64 = 1.15; /// Bold text this much of the body size or more can be a heading by weight. const WEIGHT_SIZE_RATIO: f64 = 0.9; const MAX_LINES: usize = 3; @@ -25,9 +25,12 @@ const MAX_CHARS: usize = 200; const MAX_SAVED: usize = 64; /// Distinct fonts measured per document; text in any further font counts as unstyled. const MAX_FONTS: usize = 256; +/// Characters of an object's text kept for finding running headers and footers; longer text is +/// body text. +pub(crate) const MAX_KEPT_CHARS: usize = 256; /// What one text object shows. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Evidence { /// The size, in user space, carrying the most of the object's characters. pub size: f64, @@ -37,6 +40,13 @@ pub(crate) struct Evidence { /// Characters shown, whitespace excluded. pub chars: usize, pub letters: bool, + /// The text shown, at most [`MAX_KEPT_CHARS`] characters, with a space at each line move. + pub text: String, + /// `[x0, y0, x1, y1]` in user space around each shown string's run from its origin to where + /// it advances to, and from its baseline to one font size above. `None` when any of it is in + /// glyphs whose widths the font does not declare ([`Metrics::width_declared`]) or that have no + /// Unicode mapping, or in a font that writes vertically. + pub extent: Option<[f64; 4]>, } /// The structure type for each text object, in document order: `H1`–`H6` or `P`. @@ -73,10 +83,15 @@ fn half_points(size: f64) -> i64 { (size * 2.0).round() as i64 } +/// The body text size: the size carrying the most characters. +pub(crate) fn body_size<'a>(objects: impl IntoIterator) -> Option { + body_style(objects).map(|(size, _)| size) +} + /// The size carrying the most characters, and whether most of them are bold. -fn body_style(objects: &[Evidence]) -> Option<(f64, bool)> { +fn body_style<'a>(objects: impl IntoIterator) -> Option<(f64, bool)> { let mut by_size: HashMap = HashMap::new(); - for e in objects.iter().filter(|e| e.chars > 0) { + for e in objects.into_iter().filter(|e| e.chars > 0) { let entry = by_size.entry(half_points(e.size)).or_default(); entry.0 = entry.0.saturating_add(e.chars); if e.bold { @@ -94,10 +109,16 @@ struct State { tlm: Matrix, size: f64, leading: f64, + /// `Ts`, in unscaled text space units. + rise: f64, + /// `Tc`, `Tw` and `Tz` / 100. + spacing: [f64; 3], /// Text render mode 3 or 7: shown text that paints nothing, such as an OCR layer or a /// clip-only object. invisible: bool, metrics: Option>, + /// The font writes vertically, which the extents do not measure. + vertical: bool, } /// Font metrics for a whole document, measured once per font object and capped at @@ -136,11 +157,26 @@ struct Shown { shown: bool, moved: bool, letters: bool, + text: String, + kept: usize, + extent: Option<[f64; 4]>, + /// Text shown whose run is not known: in glyphs without a declared width or a Unicode mapping, + /// in a vertical font, or out of range. + unbounded: bool, } impl Shown { fn show(&mut self, state: &State, bytes: &[u8]) { - let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { return }; + // A vertical font's glyphs advance down the page, invisible or not, so the text after + // them is placed where the extents do not follow. + self.unbounded |= state.vertical; + let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { + self.unbounded |= state.metrics.is_none(); + return; + }; + // Codes without a Unicode mapping still paint glyphs: the text's extent is not known. + let unmapped = metrics.codes(bytes).iter().any(|&(code, _)| metrics.text_of(code).is_none()); + self.unbounded |= unmapped; let text = metrics.decode(bytes); let chars = text.chars().filter(|c| !c.is_whitespace()).count(); if chars == 0 { @@ -151,13 +187,23 @@ impl Shown { (self.shown, self.lines) = (true, 1); } else if self.moved { self.lines = self.lines.saturating_add(1); + self.keep(" "); } self.moved = false; - let [_, _, c, d, _, _] = state.tm.then(&state.ctm).0; + let [a, b, c, d, e, f] = state.tm.then(&state.ctm).0; let size = (state.size * c.hypot(d)).abs(); if !size.is_finite() || size <= 0.0 || size > 1e6 { return; } + self.keep(&text); + let run = advance(state, metrics, bytes); + self.unbounded |= !run.declared; + let (low, high) = (state.rise, state.rise + state.size); + for along in run.span { + let (x, y) = (e + along * a, f + along * b); + self.reach(x + low * c, y + low * d); + self.reach(x + high * c, y + high * d); + } let entry = self.by_size.entry(half_points(size)).or_default(); entry.0 = entry.0.saturating_add(chars); if metrics.bold { @@ -165,6 +211,22 @@ impl Shown { } } + fn keep(&mut self, text: &str) { + for ch in text.chars().take(MAX_KEPT_CHARS.saturating_sub(self.kept)) { + self.text.push(ch); + self.kept = self.kept.saturating_add(1); + } + } + + fn reach(&mut self, x: f64, y: f64) { + if !x.is_finite() || !y.is_finite() { + self.unbounded = true; + return; + } + let [x0, y0, x1, y1] = self.extent.unwrap_or([x, y, x, y]); + self.extent = Some([x0.min(x), y0.min(y), x1.max(x), y1.max(y)]); + } + /// A line move counts once text is shown after it, so blank lines and trailing moves do not. fn new_line(&mut self) { self.moved = self.shown; @@ -175,16 +237,159 @@ impl Shown { let Some((size, (count, bold))) = self.by_size.into_iter().max_by_key(|&(s, (n, _))| (n, s)) else { return Evidence::default(); }; - Evidence { size: size as f64 / 2.0, bold: bold.saturating_mul(2) > count, lines: self.lines, chars, letters: self.letters } + Evidence { + size: size as f64 / 2.0, + bold: bold.saturating_mul(2) > count, + lines: self.lines, + chars, + letters: self.letters, + text: self.text, + extent: self.extent.filter(|_| !self.unbounded), + } + } +} + +/// How far a string's glyphs move and reach along the text line, in unscaled text space (§9.4.4). +struct Run { + /// The advance past the string. + width: f64, + /// The lowest and highest points any glyph or the advance reaches: negative spacing can + /// pull glyphs back over each other, so the ends of the run alone do not bound them. + /// Non-finite when the spacing or size is. + span: [f64; 2], + /// Whether the font declares every glyph's width. + declared: bool, +} + +fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> Run { + let [char_spacing, word_spacing, scale] = state.spacing; + let (mut at, mut low, mut high, mut declared) = (0.0f64, 0.0f64, 0.0f64, true); + for (code, len) in metrics.codes(bytes) { + let glyph = metrics.width(code) * state.size; + (low, high) = (low.min(at).min(at + glyph), high.max(at).max(at + glyph)); + let word = if metrics.is_space(code, len) { word_spacing } else { 0.0 }; + at += glyph + char_spacing + word; + declared &= metrics.width_declared(code); + } + // `min` and `max` drop a NaN, but once `at` is not finite it stays so: pass it on instead. + let span = if at.is_finite() { [low.min(at), high.max(at)] } else { [at, at] }; + Run { width: at * scale, span: span.map(|v| v * scale), declared } +} + +/// Whether `font` writes vertically: a Type 0 font whose `/Encoding` is a predefined CMap name +/// ending in `-V`, or an embedded CMap whose `/WMode` is 1 (§9.7.5). +fn vertical(doc: &Document, font: &Object) -> bool { + let font = doc.resolve(font); + let Some(font) = font.as_dict() else { return false }; + if font.get(b"Subtype").map(|s| doc.resolve(s)).as_deref().and_then(Object::as_name) != Some(b"Type0".as_slice()) { + return false; + } + match font.get(b"Encoding").map(|e| doc.resolve(e)).as_deref() { + Some(Object::Name(n)) => n.ends_with(b"-V"), + Some(Object::Stream(s)) => s.dict.int(b"WMode") == Some(1), + _ => false, + } +} + +/// Shows `bytes` in `object`, if any, then moves the text matrix past them. +fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) { + if let Some(o) = object { + o.show(state, bytes); + } + let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).width); + state.tm = Matrix::translate(moved, 0.0).then(&state.tm); +} + +/// The text state and text-showing operators other than `Tf`. +fn text_op(state: &mut State, object: Option<&mut Shown>, op: &Op) { + match op.op.as_slice() { + b"TL" => state.leading = op.num(0).unwrap_or(state.leading), + b"Ts" => state.rise = op.num(0).unwrap_or(state.rise), + b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0), + b"Tc" => state.spacing[0] = op.num(0).unwrap_or(state.spacing[0]), + b"Tw" => state.spacing[1] = op.num(0).unwrap_or(state.spacing[1]), + b"Tz" => state.spacing[2] = op.num(0).map_or(state.spacing[2], |z| z / 100.0), + b"Td" | b"TD" => { + if let Some([x, y]) = op.nums::<2>() { + if op.op == b"TD" { + state.leading = -y; + } + state.tlm = Matrix::translate(x, y).then(&state.tlm); + state.tm = state.tlm; + if y != 0.0 + && let Some(o) = object + { + o.new_line(); + } + } + } + b"Tm" => { + if let Some(m) = op.nums::<6>() { + let moved = m[5] != state.tlm.0[5]; + (state.tm, state.tlm) = (Matrix(m), Matrix(m)); + if moved && let Some(o) = object { + o.new_line(); + } + } + } + b"T*" | b"'" | b"\"" => { + if op.op == b"\"" + && let (Some(word), Some(char)) = (op.num(0), op.num(1)) + { + state.spacing = [char, word, state.spacing[2]]; + } + state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm); + state.tm = state.tlm; + let mut object = object; + if let Some(o) = object.as_deref_mut() { + o.new_line(); + } + if op.op != b"T*" + && let Some(Object::String(s)) = op.operands.last() + { + show(state, object, &s.bytes); + } + } + b"Tj" => { + if let Some(Object::String(s)) = op.operands.first() { + show(state, object, &s.bytes); + } + } + b"TJ" => { + if let Some(Object::Array(items)) = op.operands.first() { + let mut object = object; + for item in items { + match item { + Object::String(s) => show(state, object.as_deref_mut(), &s.bytes), + other => { + let n = other.as_f64().unwrap_or(0.0); + let moved = -n / 1000.0 * state.size * state.spacing[2]; + state.tm = Matrix::translate(moved, 0.0).then(&state.tm); + } + } + } + } + } + _ => {} } } /// The evidence for each `(BT, ET)` operator span of a page, in order. `resources` is the page's /// `/Font` resource dictionary; `fonts` is shared by the document's pages. pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec { - let mut by_name: HashMap, Option>> = HashMap::new(); - let mut state = - State { ctm: Matrix::IDENTITY, tm: Matrix::IDENTITY, tlm: Matrix::IDENTITY, size: 0.0, leading: 0.0, invisible: false, metrics: None }; + let mut by_name: HashMap, (Option>, bool)> = HashMap::new(); + let mut state = State { + ctm: Matrix::IDENTITY, + tm: Matrix::IDENTITY, + tlm: Matrix::IDENTITY, + size: 0.0, + leading: 0.0, + rise: 0.0, + spacing: [0.0, 0.0, 1.0], + invisible: false, + metrics: None, + vertical: false, + }; let (mut saved, mut unsaved) = (Vec::new(), 0usize); let mut out = Vec::with_capacity(spans.len()); let mut spans = spans.iter().peekable(); @@ -211,62 +416,15 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: b"BT" => (state.tm, state.tlm) = (Matrix::IDENTITY, Matrix::IDENTITY), b"Tf" => { state.size = op.num(1).unwrap_or(state.size); - state.metrics = op - .name(0) - .and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone()); + (state.metrics, state.vertical) = op.name(0).map_or((None, false), |name| { + let font = || resources.get(name); + by_name + .entry(name.to_vec()) + .or_insert_with(|| (font().and_then(|f| fonts.get(doc, f)), font().is_some_and(|f| vertical(doc, f)))) + .clone() + }); } - b"TL" => state.leading = op.num(0).unwrap_or(state.leading), - b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0), - b"Td" | b"TD" => { - if let Some([x, y]) = op.nums::<2>() { - if op.op == b"TD" { - state.leading = -y; - } - state.tlm = Matrix::translate(x, y).then(&state.tlm); - state.tm = state.tlm; - if y != 0.0 - && let Some(o) = object - { - o.new_line(); - } - } - } - b"Tm" => { - if let Some(m) = op.nums::<6>() { - let moved = m[5] != state.tlm.0[5]; - (state.tm, state.tlm) = (Matrix(m), Matrix(m)); - if moved && let Some(o) = object { - o.new_line(); - } - } - } - b"T*" | b"'" | b"\"" => { - state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm); - state.tm = state.tlm; - if let Some(o) = object { - o.new_line(); - if op.op != b"T*" - && let Some(Object::String(s)) = op.operands.last() - { - o.show(&state, &s.bytes); - } - } - } - b"Tj" => { - if let (Some(o), Some(Object::String(s))) = (object, op.operands.first()) { - o.show(&state, &s.bytes); - } - } - b"TJ" => { - if let (Some(o), Some(Object::Array(items))) = (object, op.operands.first()) { - for item in items { - if let Object::String(s) = item { - o.show(&state, &s.bytes); - } - } - } - } - _ => {} + _ => text_op(&mut state, object, op), } if current.as_ref().is_some_and(|c| c.0 == at) && let Some((_, o)) = current.take() @@ -283,7 +441,7 @@ mod tests { use super::*; fn text(size: f64, chars: usize) -> Evidence { - Evidence { size, bold: false, lines: 1, chars, letters: true } + Evidence { size, bold: false, lines: 1, chars, letters: true, ..Evidence::default() } } fn bold(e: Evidence) -> Evidence { @@ -343,15 +501,23 @@ mod tests { assert!(roles(&[]).is_empty()); } - /// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`. + /// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`, a font + /// with no widths whose name is no standard face as `/F2`, and one whose `/Widths` covers + /// only `a` as `/F3`. fn walk(content: &[u8]) -> Vec { let doc = Document::new_empty(); - let mut font = Dict::new(); - font.set(b"Type".to_vec(), Object::name("Font")); - font.set(b"Subtype".to_vec(), Object::name("Type1")); - font.set(b"BaseFont".to_vec(), Object::name("Helvetica-Bold")); let mut resources = Dict::new(); - resources.set(b"F1".to_vec(), Object::Dict(font)); + for (name, base, widths) in [("F1", "Helvetica-Bold", None), ("F2", "HouseFont", None), ("F3", "HouseFont", Some(500))] { + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type1")); + font.set(b"BaseFont".to_vec(), Object::name(base)); + if let Some(w) = widths { + font.set(b"FirstChar".to_vec(), Object::Int(97)); + font.set(b"Widths".to_vec(), Object::Array(vec![Object::Int(w)])); + } + resources.set(name.as_bytes().to_vec(), Object::Dict(font)); + } let ops = pdfcraft_content::parse(content).ops; let at = |name: &[u8]| -> Vec { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() }; let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect(); @@ -363,12 +529,56 @@ mod tests { let found = walk( b"q 2 0 0 2 0 0 cm BT /F1 1 Tf 9 0 0 9 10 10 Tm (Title) Tj ET Q BT /F1 12 Tf 10 50 Td (one) Tj T* (two) ' 0 -14 Td (three) Tj ET BT ET", ); - assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true }); - assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true }); + assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true, ..found[0].clone() }); + assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true, ..found[1].clone() }); + assert_eq!(found[0].text, "Title"); + // "Title" is 2.056 em wide in Helvetica-Bold, at 18 units from x 20. + assert_eq!(rounded(found[0].extent), Some([20.0, 20.0, 57.008, 38.0]), "the run and one font size above it, through Tm and cm"); + assert_eq!(found[1].text, "one two three"); assert_eq!(found[2], Evidence::default()); assert_eq!(found.len(), 3); } + #[test] + fn text_rise_moves_the_extent() { + // Ts is text space, so a 2x Tm doubles it; it outlives BT and is undone by Q. + let found = walk(b"q BT /F1 10 Tf 2 0 0 2 72 760 Tm -180 Ts (Body) Tj ET BT /F1 10 Tf 1 0 0 1 72 760 Tm (Still) Tj ET Q BT /F1 10 Tf 1 0 0 1 72 760 Tm (Back) Tj ET"); + // Body, Still and Back are 2.5, 1.834 and 2.39 em wide in Helvetica-Bold. + assert_eq!(rounded(found[0].extent), Some([72.0, 400.0, 122.0, 420.0])); + assert_eq!(rounded(found[1].extent), Some([72.0, 580.0, 90.34, 590.0])); + assert_eq!(rounded(found[2].extent), Some([72.0, 760.0, 95.9, 770.0])); + } + + fn rounded(extent: Option<[f64; 4]>) -> Option<[f64; 4]> { + extent.map(|p| p.map(|v| (v * 1000.0).round() / 1000.0)) + } + + #[test] + fn the_extent_follows_the_run_in_any_direction_with_spacing() { + // Turned to run down the page, "Body" reaches 30 units below its origin; one font size + // up is to the right. Tc 1 adds 4, TJ -500 adds 6, and Tz 50 halves the whole run. + let found = walk(b"q BT /F1 12 Tf 0 -1 1 0 72 760 Tm (Body) Tj ET BT /F1 12 Tf 1 Tc 50 Tz 1 0 0 1 72 700 Tm [(Bo) -500 (dy)] TJ ET Q"); + assert_eq!(rounded(found[0].extent), Some([72.0, 730.0, 84.0, 760.0])); + assert_eq!(rounded(found[1].extent), Some([72.0, 700.0, 92.0, 712.0])); + } + + #[test] + fn text_in_widths_the_font_does_not_declare_has_no_extent() { + let found = walk(b"BT /F2 10 Tf (a) Tj ET BT /F3 10 Tf (ab) Tj ET BT /F3 10 Tf (a) Tj ET BT /F1 10 Tf (a) Tj /F9 10 Tf (b) Tj ET"); + assert_eq!(found[0].extent, None, "no /Widths, and Helvetica only a guess"); + assert_eq!(found[1].extent, None, "b is past /Widths"); + assert_eq!(rounded(found[2].extent), Some([0.0, 0.0, 5.0, 10.0]), "a is in /Widths"); + assert_eq!(found[3].extent, None, "part of it has no font"); + } + + #[test] + fn an_origin_past_f64_leaves_no_extent() { + // Two translations near f64::MAX add up to infinity; the text is kept, its position is not. + let far = format!("{}.0", "9".repeat(308)); + let found = walk(format!("q 1 0 0 1 {far} 0 cm BT /F1 10 Tf 1 0 0 1 {far} 0 Tm (far) Tj ET Q").as_bytes()); + assert_eq!((found[0].text.as_str(), found[0].extent), ("far", None)); + } + #[test] fn line_moves_leading_invisible_text_and_absurd_sizes() { let found = walk( @@ -379,4 +589,70 @@ mod tests { assert_eq!(found[2].chars, 5, "render mode 3 and 7 text is not counted"); assert_eq!(found[3], Evidence::default(), "a size past 1e6 is dropped"); } + + /// The evidence for each `BT`..`ET` of `content` in two-byte Type 0 fonts declaring every + /// width as 1000: `/H` and `/V` map their codes to Unicode and write horizontally and + /// vertically, and `/U` has no Unicode mapping; with `/F1` as in [`walk`]. + fn walk_type0(content: &[u8]) -> Vec { + let cmap = "begincmap 1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0020> <007E> <0020> endbfrange endcmap"; + let type0 = |encoding: &str, unicode: &str| { + format!("<< /Type /Font /Subtype /Type0 /BaseFont /House /Encoding /{encoding} /DescendantFonts [2 0 R] {unicode} >>") + }; + let doc = crate::tests::pdf( + &[ + "<< /Type /Catalog >>".into(), + "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /House /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 1000 >>".into(), + crate::tests::stream(cmap), + type0("Identity-H", "/ToUnicode 3 0 R"), + type0("Identity-V", "/ToUnicode 3 0 R"), + type0("Identity-H", ""), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>".into(), + ], + "", + ); + let mut resources = Dict::new(); + for (name, n) in [("H", 4), ("V", 5), ("U", 6), ("F1", 7)] { + resources.set(name.as_bytes().to_vec(), Object::Ref(ObjRef::new(n, 0))); + } + let ops = pdfcraft_content::parse(content).ops; + let at = |name: &[u8]| -> Vec { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() }; + let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect(); + evidence(&doc, &mut Fonts::default(), &resources, &ops, &spans) + } + + #[test] + fn text_in_glyphs_without_a_unicode_mapping_has_no_extent() { + // A mapped header and, in the same object, unmapped glyphs further down the page: the + // object reaches the body, though its text is only the header's. + let found = walk_type0(b"BT /F1 12 Tf 72 760 Td (Header) Tj /U 12 Tf 0 -360 Td <00410042> Tj ET BT /H 12 Tf 72 760 Td <00410042> Tj ET"); + assert_eq!((found[0].text.as_str(), found[0].extent), ("Header", None)); + assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 96.0, 772.0]), "mapped Type 0 text keeps its extent"); + } + + #[test] + fn text_after_invisible_vertical_text_has_no_extent() { + // The invisible glyph moves the text 360 units down the page before "Body" is shown. + let found = walk_type0(b"BT /V 360 Tf 3 Tr 72 760 Td <0041> Tj /F1 12 Tf 0 Tr (Body) Tj ET BT /F1 12 Tf 72 760 Td (Body) Tj ET"); + assert_eq!((found[0].text.as_str(), found[0].extent), ("Body", None)); + assert!(found[1].extent.is_some()); + } + + #[test] + fn spacing_past_f64_leaves_no_extent() { + // Tc and Tw near f64::MAX each overflow to infinity and cancel to NaN on the first space. + let big = format!("1.0e{}", 999); + let found = + walk(format!("BT /F1 10 Tf {big} Tc -{big} Tw 72 760 Td ( Body) Tj ET BT /F1 10 Tf 0 Tc 0 Tw 72 760 Td ( Body) Tj ET").as_bytes()); + assert_eq!((found[0].text.as_str(), found[0].extent), (" Body", None)); + assert!(found[1].extent.is_some()); + } + + #[test] + fn text_in_a_vertical_font_has_no_extent() { + // Thirty glyphs at 12 run 360 units down the page in a vertical font, not along x. + let glyphs = format!("<{}>", "0041".repeat(30)); + let found = walk_type0(format!("BT /V 12 Tf 72 760 Td {glyphs} Tj ET BT /H 12 Tf 72 760 Td {glyphs} Tj ET").as_bytes()); + assert_eq!((found[0].chars, found[0].extent), (30, None)); + assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 432.0, 772.0])); + } } diff --git a/crates/a11y/src/autotag_running.rs b/crates/a11y/src/autotag_running.rs new file mode 100644 index 0000000000..91de5cff02 --- /dev/null +++ b/crates/a11y/src/autotag_running.rs @@ -0,0 +1,428 @@ +//! Running headers, footers and page numbers among auto-tagged text objects, found by repetition. +//! +//! A text object is running text when it lies wholly inside the top or bottom 15% of the page as +//! displayed, and the same text appears within 4 units of the same distance from that edge on at +//! least 40% of the pages, and at least two. Text is compared lowercase with whitespace collapsed, +//! each run of digits, and a roman numeral standing alone or after `Page`, matching any number, so +//! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose +//! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a +//! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`). +//! Every object in some qualifying span of distances counts, so spans that overlap and spans that +//! lie apart are each marked. Position alone never makes running text. +//! A text object whose extent is not known (see [`Evidence::extent`]) is never running text. + +use std::collections::HashMap; + +use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS}; + +/// Depth of the top and bottom bands, as a fraction of the page height. +const BAND: f64 = 0.15; +/// How far, in user-space units, the same running text may move from page to page. +const TOLERANCE: f64 = 4.0; +/// Height clusters marked per group of the same text; copies at further heights stay content. +const MAX_CLUSTERS: usize = 8; + +/// The page edge running text repeats at. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Edge { + Top, + Bottom, +} + +impl Edge { + /// The artifact subtype (ISO 32000-2 Table 363) for running text at this edge. + pub(crate) fn subtype(self) -> &'static str { + match self { + Edge::Top => "Header", + Edge::Bottom => "Footer", + } + } +} + +/// How a page is displayed: its `/Rotate` (0, 90, 180 or 270) and its crop box in user space. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Frame { + pub rotation: i64, + pub crop: [f64; 4], +} + +/// One page's text objects, in the order of its `(BT, ET)` spans. +pub(crate) struct PageText<'a> { + pub frame: Frame, + pub objects: &'a [Evidence], +} + +struct Member<'a> { + page: usize, + object: usize, + distance: f64, + evidence: &'a Evidence, +} + +/// The edge each text object repeats at, for running text, per page and object. +pub(crate) fn find(pages: &[PageText<'_>], body: Option) -> Vec>> { + let mut out: Vec>> = pages.iter().map(|p| vec![None; p.objects.len()]).collect(); + if pages.len() < 2 { + return out; + } + let needed = pages.len().saturating_mul(2).div_ceil(5).max(2); + for ((edge, key), mut members) in groups(pages) { + members.sort_by(|a, b| a.distance.total_cmp(&b.distance)); + for cluster in clusters(&members, needed) { + if is_heading_sequence(cluster, &key, body) { + continue; + } + for m in cluster { + if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) { + *slot = Some(edge); + } + } + } + } + out +} + +/// `Chapter 1`, `Chapter 2`: heading-sized text that changes, unless it reads as a page number. +fn is_heading_sequence(window: &[Member<'_>], key: &str, body: Option) -> bool { + let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if folded(&a.evidence.text) != folded(&b.evidence.text))); + let heading_sized = body.is_some_and(|body| window.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO)); + let worded = window.iter().all(|m| m.evidence.letters) && !is_page_number(key); + texts_differ && heading_sized && worded +} + +/// Lowercase with whitespace collapsed, digits kept: `ANNUAL REPORT` and `Annual report` are the +/// same heading, `Chapter 1` and `Chapter 2` are not. +fn folded(text: &str) -> String { + text.to_lowercase().split_whitespace().collect::>().join(" ") +} + +/// A normalised key that is a page number alone or with its label: `#`, `page #`, `p. #`, +/// `# of #`, `page # of #`, `#/#`, optionally in dashes or brackets. +fn is_page_number(key: &str) -> bool { + let bare = key.trim_matches(|c: char| matches!(c, '-' | '\u{2013}' | '\u{2014}' | '[' | ']' | '(' | ')' | ' ')); + matches!(bare, "#" | "page #" | "p. #" | "# of #" | "page # of #" | "#/#" | "# / #") +} + +/// Text objects inside a band, grouped by edge and normalised text. +fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec>> { + let mut groups: HashMap<(Edge, String), Vec>> = HashMap::new(); + for (page, text) in pages.iter().enumerate() { + let (low, high) = vertical(text.frame.rotation, text.frame.crop); + let band = (high - low) * BAND; + for (object, evidence) in text.objects.iter().enumerate() { + let Some(extent) = evidence.extent.filter(|_| evidence.chars > 0 && evidence.text.chars().count() < MAX_KEPT_CHARS) else { + continue; + }; + let (bottom, top) = vertical(text.frame.rotation, extent); + let (edge, distance) = if bottom >= high - band && top <= high { + (Edge::Top, high - top) + } else if top <= low + band && bottom >= low { + (Edge::Bottom, bottom - low) + } else { + continue; + }; + let key = normalise(&evidence.text); + if key.is_empty() || !distance.is_finite() { + continue; + } + groups.entry((edge, key)).or_default().push(Member { page, object, distance, evidence }); + } + } + groups +} + +/// The clusters of `members` (sorted by distance) that run: the union of every window of members +/// within [`TOLERANCE`] of the window's first that covers at least `needed` pages, with windows that +/// share a member joined into one cluster. A dense run of such windows makes one cluster wider than +/// [`TOLERANCE`], still inside the edge band, and the heading check then judges the cluster as a +/// whole. At most [`MAX_CLUSTERS`] are returned, nearest the edge first. +fn clusters<'m, 'a>(members: &'m [Member<'a>], needed: usize) -> Vec<&'m [Member<'a>]> { + let mut on_page: HashMap = HashMap::new(); + let mut found: Vec<&'m [Member<'a>]> = Vec::new(); + let mut current: Option<(usize, usize)> = None; + let mut end = 0usize; + for (start, first) in members.iter().enumerate() { + while let Some(next) = members.get(end).filter(|m| m.distance - first.distance <= TOLERANCE) { + let n = on_page.entry(next.page).or_default(); + *n = n.saturating_add(1); + end = end.saturating_add(1); + } + if on_page.len() >= needed { + current = match current { + Some((from, to)) if start < to => Some((from, to.max(end))), + done => { + if let Some(cluster) = done.and_then(|(from, to)| members.get(from..to)) { + found.push(cluster); + } + if found.len() >= MAX_CLUSTERS { + return found; + } + Some((start, end)) + } + }; + } + if let Some(n) = on_page.get_mut(&first.page) { + *n = n.saturating_sub(1); + if *n == 0 { + on_page.remove(&first.page); + } + } + } + if let Some(cluster) = current.and_then(|(from, to)| members.get(from..to)) { + found.push(cluster); + } + found +} + +/// The bottom and top of a user-space box as the page displays it. +fn vertical(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> (f64, f64) { + let (a, b) = match rotation { + 90 => (-x0, -x1), + 180 => (-y0, -y1), + 270 => (x0, x1), + _ => (y0, y1), + }; + (a.min(b), a.max(b)) +} + +/// Lowercase, whitespace collapsed, and each digit run, and a roman numeral standing alone or +/// after `page`, replaced by `#`. +fn normalise(text: &str) -> String { + let lower = text.to_lowercase(); + let words: Vec<&str> = lower.split_whitespace().collect(); + let roman_alone = match words.as_slice() { + [w] | ["page", w] => is_roman(w), + _ => false, + }; + let mut out = String::new(); + for (i, w) in words.iter().enumerate() { + if i > 0 { + out.push(' '); + } + if roman_alone && i + 1 == words.len() { + out.push('#'); + continue; + } + let mut in_digits = false; + for c in w.chars() { + if c.is_ascii_digit() { + if !in_digits { + out.push('#'); + } + in_digits = true; + } else { + out.push(c); + in_digits = false; + } + } + } + out +} + +/// A canonical lowercase roman numeral from 1 to 3999 (`mid` and `iiii` are not). +fn is_roman(s: &str) -> bool { + const UNITS: [(u32, &str); 13] = [ + (1000, "m"), + (900, "cm"), + (500, "d"), + (400, "cd"), + (100, "c"), + (90, "xc"), + (50, "l"), + (40, "xl"), + (10, "x"), + (9, "ix"), + (5, "v"), + (4, "iv"), + (1, "i"), + ]; + if s.is_empty() || s.len() > 15 { + return false; + } + let (mut rest, mut value) = (s, 0u32); + for (v, sym) in UNITS { + let mut repeats = 0; + while let Some(r) = rest.strip_prefix(sym) { + (rest, value, repeats) = (r, value.saturating_add(v), repeats + 1); + if repeats > 3 { + return false; + } + } + } + if !rest.is_empty() || value == 0 { + return false; + } + let mut canonical = String::new(); + for (v, sym) in UNITS { + while value >= v { + canonical.push_str(sym); + value = value.saturating_sub(v); + } + } + canonical == s +} + +#[cfg(test)] +mod tests { + use super::*; + + const LETTER: Frame = Frame { rotation: 0, crop: [0.0, 0.0, 612.0, 792.0] }; + + /// One line of 10-unit text at baseline `y`. + fn line(text: &str, y: f64) -> Evidence { + Evidence { + size: 10.0, + lines: 1, + chars: text.chars().filter(|c| !c.is_whitespace()).count(), + letters: true, + text: text.into(), + extent: Some([72.0, y, 72.0, y + 10.0]), + ..Evidence::default() + } + } + + fn run(pages: &[Vec], body: Option) -> Vec>> { + let text: Vec> = pages.iter().map(|objects| PageText { frame: LETTER, objects }).collect(); + find(&text, body) + } + + #[test] + fn digits_and_roman_numerals_match_any_number() { + assert_eq!(normalise("Page 12 of 30"), "page # of #"); + assert_eq!(normalise("Annual Report 2026"), "annual report #"); + assert_eq!(normalise("xiv"), "#"); + assert_eq!(normalise("Page IX"), "page #"); + assert_eq!(normalise("mid"), "mid", "not a canonical numeral"); + assert_eq!(normalise("Chapter iv"), "chapter iv", "a numeral after another word is a word"); + assert!(is_page_number("#") && is_page_number("page # of #") && is_page_number("- # -") && is_page_number("[p. #]")); + assert!(!is_page_number("chapter #") && !is_page_number("page") && !is_page_number("annual report #")); + assert!(is_roman("mmmcmxcix") && !is_roman("iiii") && !is_roman("ic") && !is_roman("")); + } + + #[test] + fn a_header_and_a_numbered_footer_repeat_but_a_body_line_does_not() { + let page = |n: usize| vec![line("Annual report", 760.0), line("Repeated body line", 400.0), line(&format!("Page {n}"), 30.0)]; + let found = run(&[page(1), page(2), page(3)], Some(10.0)); + for page in found { + assert_eq!(page, [Some(Edge::Top), None, Some(Edge::Bottom)]); + } + } + + #[test] + fn a_single_page_has_no_running_text() { + let found = run(&[vec![line("Annual report", 760.0), line("1", 30.0)]], Some(10.0)); + assert_eq!(found, [[None, None]]); + } + + #[test] + fn text_on_too_few_pages_or_at_another_height_is_not_running() { + // Five pages: the footer on one of them, the header 20 units lower on each. + let pages: Vec> = (0..5u32) + .map(|i| { + let mut page = vec![line("Header", 760.0 - f64::from(i) * 20.0)]; + if i < 1 { + page.push(line("Draft", 30.0)); + } + page + }) + .collect(); + assert!(run(&pages, None).iter().flatten().all(Option::is_none)); + // Within the tolerance, alternate headers on two of five pages qualify. + let pages: Vec> = (0..5u32).map(|i| vec![line(if i % 2 == 0 { "Left" } else { "Right" }, 760.0 + f64::from(i))]).collect(); + let found = run(&pages, None); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + } + + #[test] + fn distinct_pages_are_counted_not_objects() { + // Six pages need three. Copies at 30 and 32 on the first page and one at 31 on the second + // are three objects in a row by height, but only two pages. + let note = |y: f64| line("Note", y); + let mut pages = vec![vec![note(30.0), note(32.0)], vec![note(31.0)], Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + assert!(run(&pages, None).iter().flatten().all(Option::is_none)); + pages[2].push(note(31.0)); + assert!(run(&pages, None).iter().flatten().any(Option::is_some), "on three pages it runs"); + } + + #[test] + fn each_qualifying_cluster_of_heights_counts() { + // Six pages need three: "Note" 20 units below the top on three pages and 40 below on the + // other three, plus a second copy on the first page just inside the first cluster. + let at = |distance: f64| line("Note", 792.0 - 10.0 - distance); + let pages = vec![vec![at(20.0), at(21.0)], vec![at(20.0)], vec![at(20.0)], vec![at(40.0)], vec![at(40.0)], vec![at(40.0)]]; + let found = run(&pages, None); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}"); + // On two pages, a copy every 10 units from 20 down puts 9 clusters in the band, past the cap. + let column: Vec = (0..12u32).map(|i| at(20.0 + f64::from(i) * 10.0)).collect(); + let found = run(&[column.clone(), column], None); + let marked = found.iter().flatten().filter(|e| e.is_some()).count(); + assert_eq!(marked, 16, "8 clusters on 2 pages: {found:?}"); + } + + #[test] + fn overlapping_qualifying_spans_of_heights_both_count() { + // Six pages need three: "Note" 20 units below the top on two pages, 24 on one and 28 on + // two. 20..24 and 24..28 each cover three pages and share the copy at 24. + let at = |distance: f64| line("Note", 792.0 - 10.0 - distance); + let pages = vec![vec![at(20.0)], vec![at(20.0)], vec![at(24.0)], vec![at(28.0)], vec![at(28.0)], Vec::new()]; + let found = run(&pages, None); + assert_eq!(found.iter().flatten().filter(|e| **e == Some(Edge::Top)).count(), 5, "{found:?}"); + } + + #[test] + fn heading_sized_text_that_changes_is_a_heading_not_a_header() { + let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) }; + let found = run(&[vec![big("Chapter 1")], vec![big("Chapter 2")]], Some(10.0)); + assert_eq!(found, [[None], [None]]); + let found = run(&[vec![big("Annual report")], vec![big("Annual report")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "the same large text on every page is still a header"); + let number = |text: &str| Evidence { letters: false, ..big(text) }; + let found = run(&[vec![number("12")], vec![number("13")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "a large page number is still a page number"); + let found = run(&[vec![big("xii")], vec![big("xiii")]], Some(10.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "so is a large roman one"); + let found = run(&[vec![big("Page 1")], vec![big("Page 2")], vec![big("- 3 of 9 -")], vec![big("- 4 of 9 -")]], Some(10.0)); + assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "a labelled page number is too: {found:?}"); + } + + #[test] + fn a_heading_differing_only_in_case_or_spacing_does_not_change() { + let big = |text: &str| Evidence { size: 18.0, ..line(text, 750.0) }; + let found = run(&[vec![big("ANNUAL REPORT")], vec![big("Annual report")]], Some(12.0)); + assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]]); + } + + #[test] + fn the_bands_follow_the_displayed_page() { + // Turned 90° clockwise, the displayed top is the user-space left edge (x = 0). + let turned = Frame { rotation: 90, crop: [0.0, 0.0, 612.0, 792.0] }; + let side = Evidence { extent: Some([20.0, 300.0, 30.0, 300.0]), ..line("Side title", 0.0) }; + let objects = vec![side]; + let pages = [PageText { frame: turned, objects: &objects }, PageText { frame: turned, objects: &objects }]; + assert_eq!(find(&pages, None), [[Some(Edge::Top)], [Some(Edge::Top)]]); + assert_eq!(run(&[objects.clone(), objects], None), [[None], [None]], "upright, it sits mid-page"); + // Upside down the displayed top is the user-space bottom; turned 270° it is the right edge. + let upside = Frame { rotation: 180, ..turned }; + let low = vec![line("Upside down", 30.0)]; + assert_eq!( + find(&[PageText { frame: upside, objects: &low }, PageText { frame: upside, objects: &low }], None), + [[Some(Edge::Top)], [Some(Edge::Top)]] + ); + let left = Frame { rotation: 270, ..turned }; + let right = vec![Evidence { extent: Some([590.0, 300.0, 600.0, 300.0]), ..line("Turned left", 0.0) }]; + assert_eq!( + find(&[PageText { frame: left, objects: &right }, PageText { frame: left, objects: &right }], None), + [[Some(Edge::Top)], [Some(Edge::Top)]] + ); + } + + #[test] + fn the_bands_follow_the_crop_box() { + // Cropped to y 100..892, text at 860 is in the top band and text at 760 is not. + let cropped = Frame { rotation: 0, crop: [0.0, 100.0, 612.0, 892.0] }; + let objects = vec![line("Inside", 860.0), line("Below the band", 760.0)]; + let pages = [PageText { frame: cropped, objects: &objects }, PageText { frame: cropped, objects: &objects }]; + assert_eq!(find(&pages, None), [[Some(Edge::Top), None], [Some(Edge::Top), None]]); + assert_eq!(run(&[objects.clone(), objects], None)[0], [None, Some(Edge::Top)], "against the media box it is the other way"); + } +} diff --git a/crates/a11y/src/heading_levels.rs b/crates/a11y/src/heading_levels.rs new file mode 100644 index 0000000000..2c1de0369c --- /dev/null +++ b/crates/a11y/src/heading_levels.rs @@ -0,0 +1,58 @@ +//! Heading levels for blocks of text laid out on the page, by the rules Auto-tag uses for text +//! objects ([`crate::autotag_text`]): the body style is the size carrying the most characters, +//! a block is a heading when it is short and larger than the body (or bold where the body is +//! not), and levels rank the heading styles over the whole document without skipping a level. + +use crate::autotag_roles::{Evidence, roles}; + +/// What one block of text shows: a run of lines set in one style, such as a heading that wraps. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct TextBlock { + /// The size it is shown at, in user space. + pub size: f64, + pub bold: bool, + pub lines: usize, + /// Characters shown, whitespace excluded. + pub chars: usize, + /// Whether it includes a letter: a number alone is never a heading. + pub letters: bool, +} + +/// The heading level of each block, in document order: `Some(1)` to `Some(6)`, or `None` for a +/// block that is not a heading. A heading's level is at most one deeper than the heading before. +pub fn heading_levels(blocks: &[TextBlock]) -> Vec> { + let evidence: Vec = blocks + .iter() + .map(|b| Evidence { size: b.size, bold: b.bold, lines: b.lines, chars: b.chars, letters: b.letters, ..Evidence::default() }) + .collect(); + roles(&evidence).into_iter().map(|role| role.strip_prefix('H').and_then(|n| n.parse().ok())).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(size: f64, bold: bool, lines: usize, chars: usize) -> TextBlock { + TextBlock { size, bold, lines, chars, letters: true } + } + + #[test] + fn blocks_take_the_levels_auto_tag_gives_text_objects() { + let blocks = [ + block(18.0, true, 1, 12), + block(11.0, false, 8, 600), + block(14.0, true, 2, 30), + block(11.0, false, 6, 500), + block(18.0, true, 1, 9), + block(11.0, true, 1, 20), + TextBlock { letters: false, ..block(30.0, false, 1, 2) }, + ]; + assert_eq!(heading_levels(&blocks), [Some(1), None, Some(2), None, Some(1), Some(2), None]); + } + + #[test] + fn no_text_has_no_headings() { + assert!(heading_levels(&[]).is_empty()); + assert_eq!(heading_levels(&[TextBlock::default()]), [None]); + } +} diff --git a/crates/a11y/src/headings.rs b/crates/a11y/src/headings.rs index a9de970b65..933597ee55 100644 --- a/crates/a11y/src/headings.rs +++ b/crates/a11y/src/headings.rs @@ -10,7 +10,8 @@ use pdfcraft_model::Page; use crate::alt::{page_content, standard, tree_root}; -const MAX_HEADINGS: usize = 10_000; +/// The most headings [`headings`] returns. +pub const MAX_HEADINGS: usize = 10_000; const MAX_VISITS: usize = 1_000_000; const MAX_DEPTH: usize = 256; /// Characters kept of a heading's title. @@ -39,7 +40,13 @@ struct Walker<'a> { texts: HashMap>, /// What is left of [`MAX_TITLE_SOURCE_BYTES`]. title_left: usize, + /// [`Walker::attr`] declined a string the allowance could not hold, since the last reset. + declined: bool, out: Vec, + /// A limit left out a heading that could have been found. + cut: bool, + /// [`MAX_HEADINGS`] were found and one more was met: the walk stops. + full: bool, } /// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all. @@ -49,7 +56,14 @@ const MAX_TITLE_SOURCE_BYTES: usize = 32 << 20; /// The headings, in document order. Headings without text or a page are left out. pub fn headings(doc: &Document) -> Vec { - let Some(root) = tree_root(doc) else { return Vec::new() }; + headings_with_truncation(doc).0 +} + +/// [`headings`], and whether headings may be missing from it: there were more than +/// [`MAX_HEADINGS`], the structure tree nests or branches past the walk's limits, or a heading's +/// only title source was past the title allowance. +pub fn headings_with_truncation(doc: &Document) -> (Vec, bool) { + let Some(root) = tree_root(doc) else { return (Vec::new(), false) }; let pages = pdfcraft_model::pages(doc); let mut w = Walker { doc, @@ -60,19 +74,27 @@ pub fn headings(doc: &Document) -> Vec { visits: 0, texts: HashMap::new(), title_left: MAX_TITLE_SOURCE_BYTES, + declined: false, out: Vec::new(), + cut: false, + full: false, }; if let Some(k) = root.get(b"K") { w.walk(k, None, 0, 0); } - w.out + (w.out, w.cut) } impl Walker<'_> { - /// Whether `k` may be visited (bounded depth and size, each object once). + /// Whether `k` may be visited (bounded depth and size, each object once). A depth or size + /// limit only skips `k`, and is reported in `cut`. fn enter(&mut self, k: &Object, depth: usize) -> bool { self.visits += 1; - depth <= MAX_DEPTH && self.visits <= MAX_VISITS && self.out.len() < MAX_HEADINGS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) + if depth > MAX_DEPTH || self.visits > MAX_VISITS { + self.cut = true; + return false; + } + !self.full && !matches!(k, Object::Ref(r) if !self.seen.insert(*r)) } fn element_of(&self, k: &Object) -> Option<(Option, Dict)> { @@ -101,6 +123,11 @@ impl Walker<'_> { _ => None, }; if let Some(level) = level { + if self.out.len() >= MAX_HEADINGS { + self.cut = true; + self.full = true; + return; + } self.heading(obj, &d, pg, level, depth); return; } @@ -139,6 +166,7 @@ impl Walker<'_> { self.marks(kids, pg, depth + 1, &mut marks); } let Some(page) = pg.or_else(|| marks.iter().find_map(|m| m.0)).and_then(|p| self.page_index.get(&p).copied()) else { return }; + self.declined = false; let title = match self.attr(d, b"ActualText") { Some(t) => Some(t), None => match self.marked_text(&marks, page) { @@ -146,7 +174,11 @@ impl Walker<'_> { None => self.attr(d, b"Alt").or_else(|| self.attr(d, b"T")), }, }; - let Some(title) = title else { return }; + let Some(title) = title else { + // A title the allowance turned away is a heading left out, not one without text. + self.cut |= self.declined; + return; + }; let title: String = title.split_whitespace().collect::>().join(" ").chars().take(MAX_TITLE).collect(); self.out.push(Heading { obj, level, title, page }); } @@ -160,6 +192,7 @@ impl Walker<'_> { // not fit the remaining allowance is never decoded: the raw check alone let a string at // the raw limit decode to three times it before the allowance was reduced. if s.bytes.len().saturating_mul(3) > self.title_left { + self.declined = true; return None; } let text = s.to_text(); diff --git a/crates/a11y/src/lib.rs b/crates/a11y/src/lib.rs index d3492f50e7..f16361674f 100644 --- a/crates/a11y/src/lib.rs +++ b/crates/a11y/src/lib.rs @@ -16,7 +16,9 @@ mod alt; mod autotag; mod autotag_fields; mod autotag_roles; +mod autotag_running; mod content; +mod heading_levels; mod headings; mod layout_table; mod report; @@ -40,9 +42,10 @@ fn count_mark_reads(_n: usize) { } pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt}; -pub use autotag::{AutoTagError, AutoTagResult, autotag_text}; +pub use autotag::{AutoTagError, AutoTagResult, RunningText, autotag_text, running_text}; pub use autotag_fields::tag_form_fields; -pub use headings::{Heading, headings}; +pub use heading_levels::{TextBlock, heading_levels}; +pub use headings::{Heading, MAX_HEADINGS, headings, headings_with_truncation}; pub use layout_table::{LayoutTableError, layout_table_to_blocks}; pub use report::{REPORT_WORDS, report_html}; pub use tags::{TagContentItem, TagError, TagInfo, TagPlacement, TagProperty, move_tag, set_tag_property, tag_content, tags}; diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs index 4a981aaf5b..ae076eff10 100644 --- a/crates/a11y/src/tests.rs +++ b/crates/a11y/src/tests.rs @@ -5,7 +5,7 @@ use pdfcraft_cos::{Document, Object}; use super::*; /// A PDF from object bodies (object n = bodies[n - 1]) and extra trailer entries. -fn pdf(bodies: &[String], trailer: &str) -> Document { +pub(crate) fn pdf(bodies: &[String], trailer: &str) -> Document { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); for (i, b) in bodies.iter().enumerate() { @@ -21,7 +21,7 @@ fn pdf(bodies: &[String], trailer: &str) -> Document { Document::open(Arc::new(out)).unwrap() } -fn stream(data: &str) -> String { +pub(crate) fn stream(data: &str) -> String { format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()) } @@ -50,7 +50,7 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() { "", ); let result = autotag_text(&mut doc).unwrap(); - assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1 }); + assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1, headers: 0, footers: 0 }); let catalog = doc.get(doc.root().unwrap()); let root = catalog.as_dict().unwrap().reference(b"StructTreeRoot").unwrap(); let tree = doc.get(root); @@ -83,6 +83,194 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() { assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed); } +/// Three pages with a running header, a numbered footer and a body line repeated mid-page +/// (#7065): the header and footer become pagination artifacts without MCIDs, the rest is tagged. +fn running_text_pdf() -> Document { + let page = |n: usize| { + stream(&format!( + "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text on page {n} that is long enough to set the body size) Tj ET \ + BT /F1 12 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /F1 9 Tf 300 30 Td (Page {n}) Tj ET" + )) + }; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /F1 9 0 R >> >> >>".into(), + leaf(6), + leaf(7), + leaf(8), + page(1), + page(2), + page(3), + FONT.into(), + ], + "", + ) +} + +#[test] +fn autotag_text_marks_running_headers_and_footers_as_pagination_artifacts() { + let mut doc = running_text_pdf(); + let found = running_text(&doc).unwrap(); + let listed: Vec<(usize, &str, &str)> = found.iter().map(|r| (r.page, r.subtype, r.text.as_str())).collect(); + assert_eq!( + listed, + [ + (0, "Header", "Annual report"), + (0, "Footer", "Page 1"), + (1, "Header", "Annual report"), + (1, "Footer", "Page 2"), + (2, "Header", "Annual report"), + (2, "Footer", "Page 3") + ] + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!(result, AutoTagResult { pages: 3, paragraphs: 6, headings: 0, headers: 3, footers: 3 }); + for page in pdfcraft_model::pages(&doc) { + let content = doc.resolve(page.dict.get(b"Contents").unwrap()); + let Object::Stream(stream) = &*content else { panic!("marked page content") }; + let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap(); + // Each BDC in order: the artifact subtype, or the tag and its MCID. + let marks: Vec = pdfcraft_content::parse(text.as_bytes()) + .ops + .iter() + .filter(|op| op.op == b"BDC") + .map(|op| { + let d = op.operands.get(1).and_then(Object::as_dict).unwrap(); + match op.name(0).unwrap() { + b"Artifact" => { + assert_eq!(d.name(b"Type"), Some(&b"Pagination"[..])); + assert!(!d.contains(b"MCID"), "an artifact has no MCID"); + String::from_utf8(d.name(b"Subtype").unwrap().to_vec()).unwrap() + } + tag => format!("{} {}", String::from_utf8_lossy(tag), d.get(b"MCID").and_then(Object::as_int).unwrap()), + } + }) + .collect(); + assert_eq!(marks, ["Header", "P 0", "P 1", "Footer"], "{text}"); + } + let kinds: Vec = tags(&doc).iter().map(|t| t.kind.clone()).collect(); + assert_eq!(kinds, ["Document", "P", "P", "P", "P", "P", "P"]); + assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed); +} + +/// Roles are assigned over the tagged text only: a running header before a heading does not +/// shift the heading's role onto the next object. +#[test] +fn autotag_text_assigns_roles_past_running_headers() { + let body = "BT /F1 12 Tf 72 640 Td (Body text that is long enough to set the body size of the document) Tj ET"; + let page = |extra: &str| stream(&format!("BT /F1 9 Tf 72 760 Td (Annual report) Tj ET {extra} {body}")); + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + page("BT /F1 18 Tf 72 700 Td (Introduction) Tj ET"), + page(""), + FONT.into(), + ], + "", + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.headings, result.paragraphs), (2, 1, 2)); + let kinds: Vec = tags(&doc).iter().map(|t| t.kind.clone()).collect(); + assert_eq!(kinds, ["Document", "H1", "P", "P"]); +} + +/// A page whose only text is running text has nothing in the parent tree and gets no +/// `StructParents`; the next tagged page takes the next key. +#[test] +fn autotag_text_gives_a_page_of_running_text_alone_no_struct_parents() { + let header = "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(header), + stream(&format!("{header} BT /F1 12 Tf 72 640 Td (Body) Tj ET")), + FONT.into(), + ], + "", + ); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 2, footers: 0 }); + let keys: Vec> = pdfcraft_model::pages(&doc).iter().map(|p| p.dict.get(b"StructParents").and_then(Object::as_int)).collect(); + assert_eq!(keys, [None, Some(0)]); + assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed); +} + +/// A body line turned to run down from the top of each page starts in the header band but does +/// not lie inside it: it is not running text. +#[test] +fn autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged() { + let body = "BT /F1 12 Tf 0 -1 1 0 72 760 Tm (A body line set turned so that it runs down the page) Tj ET"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(body), + stream(body), + FONT.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); +} + +/// Turned body text whose negative character spacing brings each line's advance back to zero +/// still has glyphs running down the page from the header band: it is not running text. +#[test] +fn autotag_text_leaves_turned_text_pulled_back_by_negative_spacing_tagged() { + // A is 12 units wide and advances 6 at Tc -6; B is 0 wide and advances -6. Thirty of each + // end where they began, but the A glyphs reach 186 units down from y 760. + let body = format!("BT /F1 12 Tf -6 Tc 0 -1 1 0 72 760 Tm ({}{}) Tj ET", "A".repeat(30), "B".repeat(30)); + let font = "<< /Type /Font /Subtype /Type1 /BaseFont /HouseFont /FirstChar 65 /LastChar 66 /Widths [1000 0] >>"; + let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>"); + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(), + leaf(5), + leaf(6), + stream(&body), + stream(&body), + font.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 2)); +} + +#[test] +fn autotag_text_leaves_a_single_page_header_tagged() { + let mut doc = pdf( + &[ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(), + stream( + "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text long enough to set the body size) Tj ET BT /F1 9 Tf 300 30 Td (1) Tj ET", + ), + FONT.into(), + ], + "", + ); + assert_eq!(running_text(&doc).unwrap(), []); + let result = autotag_text(&mut doc).unwrap(); + assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 3)); +} + /// Page content behind a predictor whose `/DecodeParms` are given by reference is read through /// them: autotagging writes the text back as it was, marked, not with the predictor's tag bytes in /// it (a `\0` every eight bytes, which split `24` into `2 4`). @@ -108,7 +296,7 @@ fn autotag_text_reads_content_with_parameters_given_by_reference() { let mut predicted = pdfcraft_cos::Stream::flate(Dict::new(), &rows); predicted.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms)); doc.set(ObjRef::new(4, 0), predicted); - assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0 }); + assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 }); let page = &pdfcraft_model::pages(&doc)[0]; let written = doc.resolve(page.dict.get(b"Contents").unwrap()); let Object::Stream(written) = &*written else { panic!("page content") }; @@ -161,7 +349,7 @@ fn autotag_text_marks_vector_graphics_and_images_as_artifacts() { "", ); let result = autotag_text(&mut doc).unwrap(); - assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0 }); + assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 }); let report = check(&doc, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None }); assert_eq!(status(&report, Rule::TaggedPdf), Status::Passed); assert_eq!(status(&report, Rule::TaggedContent), Status::Passed); @@ -1680,8 +1868,97 @@ fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() { format!("({})", "a".repeat(512 << 10)), ]; objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R >>".to_string())); - let found = headings(&pdf(&objects, "")); + let (found, cut) = headings_with_truncation(&pdf(&objects, "")); assert!(!found.is_empty() && found.len() < count, "{}", found.len()); + assert!(cut, "headings whose title the allowance turned away were dropped unreported"); +} + +/// A title source too large for the allowance is passed over for the next one, and the heading +/// it names is kept and not reported as missing. +#[test] +fn a_title_too_large_for_the_allowance_falls_back_without_truncation() { + let objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(), + stream("BT ET"), + "<< /Type /StructTreeRoot /K 6 0 R >>".to_string(), + "<< /S /Document /P 5 0 R /K [8 0 R] >>".to_string(), + format!("({})", "a".repeat((32 << 20) / 3 + 1)), + "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R /Alt (Short) >>".to_string(), + ]; + let (found, cut) = headings_with_truncation(&pdf(&objects, "")); + let titles: Vec = found.into_iter().map(|h| h.title).collect(); + assert_eq!((titles, cut), (vec!["Short".to_string()], false)); +} + +/// A tree of `count` H1 elements, each with its text and page. +fn many_headings(count: usize) -> Vec { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 7)).collect(); + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R >>".to_string(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(), + stream("BT ET"), + "<< /Type /StructTreeRoot /K 6 0 R >>".to_string(), + format!("<< /S /Document /P 5 0 R /K [{kids}] >>"), + ]; + objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText (Head) >>".to_string())); + objects +} + +#[test] +fn headings_past_the_cap_are_reported() { + let (at_cap, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS), "")); + assert_eq!((at_cap.len(), cut), (MAX_HEADINGS, false)); + let (over, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS + 1), "")); + assert_eq!((over.len(), cut), (MAX_HEADINGS, true), "a heading past the cap was dropped unreported"); +} + +#[test] +fn a_heading_nested_past_the_depth_limit_is_reported() { + let mut objs = headings_doc(); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + assert!(!found.is_empty() && !cut); + // Element 17 opens a chain of 300 sections, each holding the next, around one H1. + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K [12 0 R {first} 0 R] >>"); + objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into()); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + assert!(found.iter().all(|h| h.title != "Deep") && cut, "a heading too deep to reach was dropped unreported"); +} + +/// A branch too deep to walk is skipped, not the end of the walk: a heading after it is found. +#[test] +fn a_heading_after_a_branch_past_the_depth_limit_is_found() { + let mut objs = headings_doc(); + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K [{first} 0 R 12 0 R] >>"); + objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into()); + let (found, cut) = headings_with_truncation(&pdf(&objs, "")); + let titles: Vec<&str> = found.iter().map(|h| h.title.as_str()).collect(); + assert_eq!((titles, cut), (vec!["Chapter One"], true), "the deep branch stopped the walk"); +} + +/// An H1 `sects + 1` elements down whose title is only its marked content. +fn heading_under_sections(sects: usize) -> (Vec, bool) { + let mut objs = headings_doc(); + let first = objs.len() + 1; + objs[9] = format!("<< /S /Document /K {first} 0 R >>"); + objs.extend((1..=sects).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i))); + objs.push("<< /S /H1 /Pg 3 0 R /K 0 >>".into()); + headings_with_truncation(&pdf(&objs, "")) +} + +/// Marked content past the depth limit is reported too: the H1 whose title it holds is lost. +#[test] +fn marked_content_past_the_depth_limit_is_reported() { + let (found, cut) = heading_under_sections(254); + assert_eq!((found.iter().map(|h| h.title.as_str()).collect::>(), cut), (vec!["Chapter One"], false)); + let (found, cut) = heading_under_sections(255); + assert!(found.is_empty() && cut, "a heading whose text was too deep was dropped unreported"); } #[test] diff --git a/crates/a11y/tests/stm_refusal.rs b/crates/a11y/tests/stm_refusal.rs new file mode 100644 index 0000000000..8e06b28f5f --- /dev/null +++ b/crates/a11y/tests/stm_refusal.rs @@ -0,0 +1,467 @@ +//! Contributor-original synthetic stream collision; no external document assets. +use pdfcraft_cos::{Document, ObjRef, Object}; +use std::sync::Arc; + +fn collision_with(kids: &str, extra: &[&str]) -> Document { + let page = "/Figure <> BDC 10 10 20 20 re f EMC\nq /Form Do Q"; + let form = "/Figure <> BDC 0 0 5 5 re f EMC"; + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Form 10 0 R >> >> >>" + .into(), + format!("<< /Length {} >>\nstream\n{}\nendstream", page.len(), page), + "<< /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >>".into(), + "<< /Type /StructElem /S /Document /P 5 0 R /K [7 0 R 8 0 R] >>".into(), + "<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K 0 /Alt (Page figure) >>".into(), + format!("<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K {kids} /Alt (Form figure) >>"), + "<< /Nums [0 [7 0 R] 1 8 0 R] >>".into(), + format!("<< /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >>\nstream\n{}\nendstream", form.len(), form), + ]; + let extra_pages = extra + .iter() + .enumerate() + .filter(|(_, object)| object.contains("/Type /Page ")) + .map(|(index, _)| format!("{} 0 R", index + 11)) + .collect::>(); + if !extra_pages.is_empty() { + objects[1] = format!("<< /Type /Pages /Kids [3 0 R {}] /Count {} >>", extra_pages.join(" "), extra_pages.len() + 1); + } + objects.extend(extra.iter().map(|s| (*s).to_string())); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, object) in objects.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", i + 1, object).as_bytes()); + } + let start = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", objects.len() + 1, start).as_bytes()); + Document::open(Arc::new(bytes)).unwrap() +} + +fn stream(doc: &Document, number: u32) -> Vec { + let object = doc.get(ObjRef::new(number, 0)); + let Object::Stream(s) = &*object else { panic!("stream required") }; + s.decoded().unwrap() +} + +fn run(decorative: bool) { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]); + assert!(!doc.is_modified()); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let original_streams = [stream(&doc, 4), stream(&doc, 10)]; + let error = mutate(&mut doc, decorative, 8).unwrap_err(); + assert!(error.contains("form"), "useful error: {error}"); + assert!(!doc.is_modified()); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 7, 8]); +} + +#[test] +fn decorative_refuses_form_collision() { + run(true); +} +#[test] +fn artifact_refuses_form_collision() { + run(false); +} + +fn mutate(doc: &mut Document, decorative: bool, number: u32) -> Result<(), String> { + if decorative { + pdfcraft_a11y::mark_decorative(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string()) + } else { + pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string()) + } +} + +fn page_owned(kids: &str, extra: &[&str]) -> Document { + let mut doc = collision_with(kids, extra); + let page_kids = doc.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone(); + let original = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]); + let form_kids = original.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone(); + doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), page_kids)).unwrap(); + doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"K".to_vec(), form_kids)).unwrap(); + // Reopen an incremental save to keep the fixture's object IDs and start from a clean state. + Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap() +} + +#[test] +fn unsupported_owned_references_refuse_without_changing_document_or_saved_data() { + let other_page_content = "/P <> BDC 40 40 5 5 re f EMC"; + let other_page_stream = format!("<< /Length {} >>\nstream\n{other_page_content}\nendstream", other_page_content.len()); + let cases: Vec<(&str, Vec<&str>)> = vec![ + ("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 2 /Stm 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm null >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm 99 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /Stm (invalid) >>", vec![]), + ("<< /Type /MCR /MCID 0 /StmOwn 10 0 R >>", vec![]), + ("<< /Type /MCR /MCID 0 /StmOwn null >>", vec![]), + ("11 0 R", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 << /S /Figure /K 0 >>]", vec![]), + ("[0 11 0 R]", vec!["<< /S /Figure /K 0 >>"]), + ("[0 << /Type /MCR /MCID 0 /Stm 10 0 R >>]", vec![]), + ("11 0 R", vec!["[0 12 0 R]", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 [11 0 R]]", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]), + ("[0 << /Type /MCR /MCID 0 /Pg 99 0 R >>]", vec![]), + ("<< /Type /MCR /MCID 0 /Pg null >>", vec![]), + ("<< /Type /MCR /MCID 0 /Pg 3 1 R >>", vec![]), + ( + "[0 << /Type /MCR /MCID 0 /Pg 11 0 R >>]", + vec!["<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 12 0 R >>", &other_page_stream], + ), + ("[0 << /MCID 0 /Pg 3 0 R >>]", vec![]), + ("[0 << /Type /MCR /Pg 3 0 R >>]", vec![]), + ("[0 99 0 R]", vec![]), + ("[0 11 1 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("[0 11 0 R]", vec!["[11 0 R]"]), + ("[0 11 0 R]", vec!["<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]), + ("11 0 R", vec!["[12 0 R]", "<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]), + ]; + for decorative in [true, false] { + for (kids, extra) in &cases { + let mut doc = collision_with(kids, extra); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let original_streams = [stream(&doc, 4), stream(&doc, 10)]; + let original_objects: Vec<_> = (1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect(); + let original_alts = pdfcraft_a11y::figures(&doc).into_iter().map(|figure| figure.alt).collect::>(); + let error = match mutate(&mut doc, decorative, 8) { + Ok(()) => panic!("decorative={decorative} K={kids} must refuse"), + Err(error) => error, + }; + assert!( + error.contains("form") || error.contains("unsupported") || error.contains("invalid") || error.contains("child structure elements"), + "ownership refusal needs a useful reason: {error}" + ); + assert!(!doc.is_modified(), "refusal must not create dirty state: {kids}"); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams, "{kids}"); + assert_eq!( + (1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect::>(), + original_objects, + "tags, Alt and ParentTree stay unchanged: {kids}" + ); + let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + assert_eq!(saved, before, "saved object graph remains exact: {kids}"); + let reopened = Document::open(Arc::new(saved)).unwrap(); + let page = &pdfcraft_model::pages(&reopened)[0]; + let Object::Stream(page_stream) = &*reopened.resolve(page.dict.get(b"Contents").unwrap()) else { panic!("page stream") }; + assert_eq!(page_stream.decoded().unwrap(), original_streams[0]); + let resources = reopened.dict(page.dict.get(b"Resources").unwrap()).unwrap(); + let xobjects = reopened.dict(resources.get(b"XObject").unwrap()).unwrap(); + let Object::Stream(form_stream) = &*reopened.resolve(xobjects.get(b"Form").unwrap()) else { panic!("form stream") }; + assert_eq!(form_stream.decoded().unwrap(), original_streams[1]); + assert_eq!( + pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::>(), + original_alts, + "all original figures, including children, survive: {kids}" + ); + } + } +} + +#[test] +fn page_only_owned_references_still_become_artifacts() { + let cases: Vec<(&str, Vec<&str>)> = vec![ + ("0", vec![]), + ("<< /Type /MCR /MCID 0 /Pg 3 0 R >>", vec![]), + ("11 0 R", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("[11 0 R 11 0 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ("11 0 R", vec!["[12 0 R]", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]), + ]; + for decorative in [true, false] { + for (kids, extra) in &cases { + let mut doc = page_owned(kids, extra); + let original_form = stream(&doc, 10); + mutate(&mut doc, decorative, 7).unwrap(); + let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap(); + let content = String::from_utf8(stream(&doc, page.num)).unwrap(); + assert!(content.contains("/Artifact BMC"), "page content changes for {kids}: {content}"); + assert!(!content.contains("/MCID")); + assert_eq!(stream(&doc, 10), original_form); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 8]); + } + } +} + +#[test] +fn ordinary_alt_edit_remains_available_for_a_stream_figure() { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]); + let original = [stream(&doc, 4), stream(&doc, 10)]; + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some(" Blue square ")).unwrap(); + assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Blue square")); + assert_eq!([stream(&doc, 4), stream(&doc, 10)], original); +} + +#[test] +fn refusal_preserves_preexisting_document_changes() { + for decorative in [true, false] { + let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]); + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap(); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let modified = doc.modified_objects(); + assert!(mutate(&mut doc, decorative, 8).is_err()); + assert!(doc.is_modified()); + assert_eq!(doc.modified_objects(), modified); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Saved later")); + } +} + +#[test] +fn owned_reference_walk_accepts_limits_and_refuses_excess_depth_or_work() { + // The root ownership array counts as one visit. Each nested array adds one depth level. + let cases = [ + (format!("[{}]", "0 ".repeat(4095)), true), + (format!("[{}]", "0 ".repeat(4096)), false), + (format!("{}0{}", "[".repeat(64), "]".repeat(64)), true), + (format!("{}0{}", "[".repeat(65), "]".repeat(65)), false), + ]; + for decorative in [true, false] { + for (kids, supported) in &cases { + let mut doc = page_owned(kids, &[]); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let result = mutate(&mut doc, decorative, 7); + assert_eq!(result.is_ok(), *supported, "decorative={decorative}, result={result:?}"); + if *supported { + let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap(); + assert!(String::from_utf8(stream(&doc, page.num)).unwrap().contains("/Artifact BMC")); + assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::>(), [6, 8]); + } else { + assert!(!doc.is_modified()); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + } + } + } +} + +#[test] +fn decorative_refuses_matching_invalid_element_and_content_pages() { + for page in [ObjRef::new(99, 0), ObjRef::new(3, 1)] { + for kids in [format!("<< /Type /MCR /MCID 0 /Pg {page} >>"), "0".into(), "<< /Type /MCR /MCID 0 >>".into()] { + let mut doc = collision_with(&kids, &[]); + doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"Pg".to_vec(), Object::Ref(page))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let error = pdfcraft_a11y::mark_decorative(&mut doc, ObjRef::new(8, 0)).unwrap_err(); + assert!(error.to_string().contains("form")); + assert!(!doc.is_modified()); + assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before); + } + } +} + +#[test] +fn annotation_reference_refusal_names_the_unsupported_content_and_preserves_its_links() { + for decorative in [true, false] { + let mut doc = collision_with( + "[0 << /Type /OBJR /Obj 11 0 R /Pg 3 0 R >>]", + &["<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /P 3 0 R /StructParent 2 >>"], + ); + doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(11, 0))]))).unwrap(); + doc.update_dict(ObjRef::new(9, 0), |d| { + d.set( + b"Nums".to_vec(), + Object::Array(vec![ + Object::Int(0), + Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]), + Object::Int(1), + Object::Ref(ObjRef::new(8, 0)), + Object::Int(2), + Object::Ref(ObjRef::new(8, 0)), + ]), + ) + }) + .unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + let original_objects: Vec<_> = (1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect(); + let error = mutate(&mut doc, decorative, 8).unwrap_err(); + assert!(error.contains("annotation or object references"), "useful OBJR refusal: {error}"); + assert!(!doc.is_modified()); + assert_eq!((1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect::>(), original_objects); + let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + assert_eq!(saved, before); + let reopened = Document::open(Arc::new(saved)).unwrap(); + let page = &pdfcraft_model::pages(&reopened)[0]; + let annotation = reopened.resolve(&page.dict.get(b"Annots").unwrap().as_array().unwrap()[0]); + assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2))); + let catalog = reopened.get(reopened.root().unwrap()); + let root = reopened.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap(); + let tree = reopened.dict(root.get(b"ParentTree").unwrap()).unwrap(); + let nums = tree.get(b"Nums").unwrap().as_array().unwrap(); + let tag = reopened.resolve(&nums[5]); + assert_eq!(tag.as_dict().unwrap().get(b"K").unwrap().as_array().unwrap()[0], Object::Int(0)); + assert_eq!(nums[4], Object::Int(2)); + } +} + +fn assert_artifact_refusal_preserves(doc: &mut Document, expected: &pdfcraft_a11y::ArtifactError) { + let state = doc.read_state(); + let dirty = doc.is_modified(); + let modified = doc.modified_objects(); + let saved = pdfcraft_cos::write_full(doc, &Default::default()).unwrap(); + let objects: Vec<_> = (1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect(); + let streams = [stream(doc, 4), stream(doc, 10)]; + let tags = pdfcraft_a11y::tags(doc); + let alts = pdfcraft_a11y::figures(doc).into_iter().map(|figure| figure.alt).collect::>(); + assert!(tags.iter().any(|tag| tag.object == ObjRef::new(7, 0)), "the malformed leaf remains reachable"); + assert_eq!(pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(7, 0)).as_ref(), Err(expected)); + assert!(state.matches(doc), "refusal preserves the exact overlay and allocates no stream"); + assert_eq!(doc.is_modified(), dirty); + assert_eq!(doc.modified_objects(), modified); + assert_eq!((1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect::>(), objects); + assert_eq!([stream(doc, 4), stream(doc, 10)], streams); + let after = pdfcraft_cos::write_full(doc, &Default::default()).unwrap(); + assert_eq!(after, saved); + // Full saves renumber objects; incremental saves retain the fixture IDs checked below. + let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(doc, &Default::default()).unwrap())).unwrap(); + assert_eq!(pdfcraft_a11y::tags(&reopened), tags); + assert_eq!(pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::>(), alts); + assert_eq!([stream(&reopened, 4), stream(&reopened, 10)], streams); + assert_eq!(reopened.get(ObjRef::new(3, 0)), objects[2]); + assert_eq!(reopened.get(ObjRef::new(9, 0)), objects[8]); + assert_eq!(reopened.get(ObjRef::new(7, 0)), objects[6]); + assert_eq!( + reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1], + Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]) + ); +} + +#[test] +fn artifact_parent_refusals_preserve_direct_library_state_and_saved_content() { + use pdfcraft_a11y::ArtifactError::{AmbiguousParent, NoParent}; + let cases = [ + (None, "<< >>", NoParent), + (Some(Object::Int(6)), "<< >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "null", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 3 >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 8 0 R >>", NoParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [] >>", AmbiguousParent), + (Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [7 0 R 7 0 R] >>", AmbiguousParent), + ]; + for dirty in [false, true] { + for (parent, parent_object, expected) in &cases { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", parent_object]); + doc.update_dict(ObjRef::new(7, 0), |dict| { + dict.remove(b"P"); + if let Some(parent) = parent { + dict.set(b"P".to_vec(), parent.clone()); + } + }) + .unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, expected); + } + } +} + +#[test] +fn artifact_mismatched_parent_refuses_before_changing_content_or_saved_state() { + for dirty in [false, true] { + for indirect in [false, true] { + for root in [false, true] { + let kids = if indirect { "11 0 R" } else { "0" }; + let mut doc = page_owned(kids, &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", "<< /Type /StructElem /S /Document /K [7 0 R] >>"]); + if root { + doc.update_dict(ObjRef::new(5, 0), |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); + } + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(ObjRef::new(12, 0)))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent); + } + } + } +} + +#[test] +fn artifact_inline_parent_does_not_become_a_removable_indirect_ancestor() { + for dirty in [false, true] { + for root in [false, true] { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]); + let parent = ObjRef::new(if root { 5 } else { 6 }, 0); + let mut inline = pdfcraft_cos::Dict::new(); + inline.set(b"S".to_vec(), Object::name("Document")); + inline.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0))); + doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Dict(inline))).unwrap(); + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + if dirty { + pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap(); + } + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent); + } + } +} + +/// Main checks the parent before it reads the page, so a tag with both a missing `/P` and +/// content missing from its page is refused for its parent, with nothing changed. +#[test] +fn artifact_invalid_parent_precedes_missing_page_content_without_mutation() { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 1 /Pg 3 0 R >>"]); + doc.update_dict(ObjRef::new(7, 0), |dict| { + dict.remove(b"P"); + }) + .unwrap(); + let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent); +} + +#[test] +fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_drawing() { + for (root, scalar) in [(false, false), (false, true), (true, false), (true, true)] { + let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]); + let parent = ObjRef::new(if root { 5 } else { 6 }, 0); + if root { + doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap(); + doc.update_dict(parent, |dict| { + dict.set(b"K".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Ref(ObjRef::new(8, 0))])) + }) + .unwrap(); + } + if scalar { + doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap(); + } + let original_form = stream(&doc, 10); + let other_figure = doc.get(ObjRef::new(8, 0)); + pdfcraft_a11y::mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap(); + let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap(); + let contents = reopened.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").unwrap().as_ref().unwrap(); + let ops = pdfcraft_content::parse(&stream(&reopened, contents.num)).ops; + assert!(ops.iter().any(|op| op.op == b"BMC" && op.operands == [Object::name("Artifact")])); + assert!(!ops.iter().any(|op| op.op == b"BDC")); + let rectangle = ops.iter().find(|op| op.op == b"re").unwrap(); + assert_eq!(rectangle.nums::<4>(), Some([10.0, 10.0, 20.0, 20.0])); + assert!(ops.iter().any(|op| op.op == b"f")); + assert!(ops.iter().any(|op| op.op == b"Do" && op.operands == [Object::name("Form")])); + assert_eq!(stream(&reopened, 10), original_form); + assert_eq!(reopened.get(ObjRef::new(8, 0)), other_figure); + let remaining = if scalar { vec![] } else { vec![Object::Ref(ObjRef::new(8, 0))] }; + assert_eq!(reopened.get(parent).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining))); + assert!(!reopened.get(ObjRef::new(7, 0)).as_dict().unwrap().contains(b"P")); + let expected_tags = match (root, scalar) { + (false, false) => vec![6, 8], + (false, true) => vec![6], + (true, false) => vec![8], + (true, true) => vec![], + }; + assert_eq!(pdfcraft_a11y::tags(&reopened).iter().map(|tag| tag.object.num).collect::>(), expected_tags); + assert_eq!( + reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1], + Object::Array(vec![Object::Null]) + ); + } +} diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs index cab0fb9a61..2dedaade5b 100644 --- a/crates/automation/src/a11y.rs +++ b/crates/automation/src/a11y.rs @@ -206,19 +206,31 @@ fn review_html(record: &Value) -> Result { Ok(html) } +/// Running headers and footers listed by `accessibility_autotag_apply`, at most. +const MAX_RUNNING_LISTED: usize = 200; + /// Tags in one page of `accessibility_tags`, by default and at most. const TAG_PAGE: usize = 200; const MAX_TAG_PAGE: usize = 1000; impl Automation { pub(crate) fn accessibility_autotag_apply(&mut self, a: &Args) -> Result { - let id = self.doc(a)?.id; + let doc = self.doc(a)?; + let id = doc.id; + // Read before applying: once tagged, the document is refused. A refusal here is Apply's too. + let running = doc.autotag_running_text().unwrap_or_default(); let warnings = self.apply_with_warnings(id, pdfcraft_engine::Edit::AutoTagText)?; let tags = self.accessibility_tags(a)?; - let out = json!({ - "tags": tags["tags"], "count": tags["count"], - "note": "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. Review heading roles, reading order and remaining accessibility findings manually.", - }); + let listed: Vec = + running.iter().take(MAX_RUNNING_LISTED).map(|r| json!({ "page": r.page + 1, "subtype": r.subtype, "text": r.text })).collect(); + let note = format!( + "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. \ + {} text objects repeating at the top or bottom of the pages were marked as running header or footer artifacts \ + instead (listed in running_text{}). Review heading roles, the running text, reading order and remaining accessibility findings manually.", + running.len(), + if running.len() > MAX_RUNNING_LISTED { format!(", first {MAX_RUNNING_LISTED}") } else { String::new() }, + ); + let out = json!({ "tags": tags["tags"], "count": tags["count"], "running_text": listed, "running_count": running.len(), "note": note }); Ok(with_warnings(out, warnings)) } diff --git a/crates/automation/src/a11y/form_tools.rs b/crates/automation/src/a11y/form_tools.rs index 10cc9d2078..9a7ceb584e 100644 --- a/crates/automation/src/a11y/form_tools.rs +++ b/crates/automation/src/a11y/form_tools.rs @@ -266,10 +266,9 @@ impl Automation { let path = self.resolve(p, false)?; files.push((p.to_string(), crate::read_input_bytes(&path).map_err(|e| failed(format!("{p}: {e}")))?)); } - let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?; + let (csv, columns) = pdfcraft_engine::merge_data_files_with_columns(&files).map_err(failed)?; let target = self.resolve(a.str("path")?, true)?; write_atomic(&target, csv.as_bytes())?; - let columns = csv.lines().next().map_or(0, |h| h.split(',').count()); Ok(json!({ "path": target.to_string_lossy(), "rows": files.len(), "columns": columns })) } diff --git a/crates/automation/src/assemble.rs b/crates/automation/src/assemble.rs index b091e54d19..70c92d2c9c 100644 --- a/crates/automation/src/assemble.rs +++ b/crates/automation/src/assemble.rs @@ -4,6 +4,27 @@ use super::paths::{child, read_input, read_input_bytes, unused, write_atomic}; use super::{Arc, Automation, CombineSource, Edit, Path, PathBuf, Value, json}; impl Automation { + /// The sheet image pages go on: `page_size` as a paper name ("A4", "Letter", "ARCH C") or + /// `[width, height]` in points, with the image scaled to fit and centred. Absent, each page + /// is the size of its own image, which is what a phone photo's pixels give. + fn image_page(a: &Args) -> Result { + let turn = a.opt_bool("page_turn")?.unwrap_or(true); + let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into()); + let page = match a.get("page_size") { + None | Some(Value::Null) => pdfcraft_engine::ImagePage::Image, + Some(Value::String(s)) => pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn), + Some(Value::Array(v)) if v.len() == 2 => { + let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad); + pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn) + } + Some(_) => return Err(bad()), + }; + // A page the creator cannot make is the caller's argument being wrong, not a conversion + // failure, and refusing it here is what keeps mode "separate" from making out_dir first. + page.check().map_err(|e| ToolError::InvalidArgs(e.to_string()))?; + Ok(page) + } + pub(crate) fn doc_create(&mut self, a: &Args) -> Result { let (name, bytes) = match a.str("from")? { "blank" => { @@ -24,7 +45,7 @@ impl Automation { } else { "Images.pdf".into() }; - (name, self.session.create_from_images_with_resolution(&images, resolution).map_err(failed)?) + (name, self.session.create_from_images_with(&images, resolution, Self::image_page(a)?).map_err(failed)?) } "text" => { let (title, text) = match (a.opt_str("text")?, a.opt_str("path")?) { @@ -201,11 +222,12 @@ impl Automation { Some(_) => return Err(ToolError::InvalidArgs("pages must list a range (or null) for each path".into())), }; // Each file is read, converted and copied in turn, so a long list holds one file at a time. + let page = Self::image_page(a)?; let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result { let path = self.resolve(p, false)?; let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?; + let (_, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(failed)?; let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); Ok((title, pdf, range)) }); @@ -216,6 +238,8 @@ impl Automation { /// One PDF per file, written into `out_dir`; a file that fails doesn't stop the others. fn create_separate(&mut self, a: &Args, paths: &[&str]) -> Result { let dir = self.resolve(a.str("out_dir").map_err(|_| ToolError::InvalidArgs("mode \"separate\" needs out_dir".into()))?, true)?; + // Checked before the folder is made, so a bad page_size leaves nothing behind. + let page = Self::image_page(a)?; std::fs::create_dir_all(&dir).map_err(|e| failed(format!("{}: {e}", dir.display())))?; let mut out = Vec::new(); for &p in paths { @@ -223,7 +247,7 @@ impl Automation { let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?; let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into()); - let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?; + let (kind, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(|e| e.to_string())?; Ok((kind, stem, pdf)) }); out.push(match converted { diff --git a/crates/automation/src/bookmark_io.rs b/crates/automation/src/bookmark_io.rs index 2a06d912f4..b3b626ad1b 100644 --- a/crates/automation/src/bookmark_io.rs +++ b/crates/automation/src/bookmark_io.rs @@ -1,4 +1,5 @@ -//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`. +//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`, +//! and `bookmark_suggest`, which proposes a tree for review before `bookmark_import` applies it. //! //! The portable form is JSON: `{"bookmarks": [node, …]}`, where a node is `title`, `page` //! (1-based, or `null` for one that goes nowhere), `view` (`{"type", "values"}`: a destination @@ -60,6 +61,31 @@ impl Automation { Ok(out) } + pub(crate) fn bookmark_suggest(&self, a: &Args) -> Result { + // The titles are the document's text, as text_lines is. + let doc = self.doc_to_copy(a)?; + let id = doc.id.0; + let s = doc.suggest_outline().ok_or_else(|| failed(format!("document {id} can't be read for editing")))?; + let source = match s.source { + pdfcraft_engine::suggest_outline::OutlineSource::Structure => "structure", + pdfcraft_engine::suggest_outline::OutlineSource::Layout => "layout", + }; + let mut out = json!({ + "source": source, + "bookmarks": s.tree().iter().map(node_json).collect::>(), + "headings": s.entries.len(), + "pages": s.pages, + "pages_read": s.pages_read, + "truncated": s.truncated, + }); + if s.entries.is_empty() { + out["note"] = json!( + "no headings found: the text may be in one style; text_styles lists the styles, and bookmark_from_text_styles makes bookmarks from chosen ones" + ); + } + Ok(out) + } + fn outline_of(&self, id: DocId, path: &[usize]) -> Result { match self.session.outline_tree(id, path) { // The engine names the path 0-based; the caller gave it 1-based. diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs index 88541466e1..4e7d2c491a 100644 --- a/crates/automation/src/comments.rs +++ b/crates/automation/src/comments.rs @@ -470,7 +470,10 @@ impl Automation { } style.fill = a.color("fill")?; if let Some(o) = a.opt_num("opacity")? { - style.opacity = o.clamp(0.0, 1.0); + if !(0.0..=1.0).contains(&o) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + style.opacity = o; } // The fill's and a text box's text's own opacities (the line keeps `opacity`). let (fill_opacity, text_opacity) = (a.opt_num("fill_opacity")?, a.opt_num("text_opacity")?); @@ -758,6 +761,9 @@ impl Automation { edits.push(Edit::SetAnnotationContents { page, index, text: text.to_string() }); } let (color, opacity, width) = (a.color("color")?, a.opt_num("opacity")?, a.opt_num("width")?); + if let Some(o) = opacity.filter(|&o| !(0.0..=1.0).contains(&o)) { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } if color.is_some() || opacity.is_some() || width.is_some() { edits.push(Edit::StyleAnnotation { page, index, color, opacity, width, endings: None }); } diff --git a/crates/automation/src/conventions.rs b/crates/automation/src/conventions.rs index a84c6488a4..b7bba7dafc 100644 --- a/crates/automation/src/conventions.rs +++ b/crates/automation/src/conventions.rs @@ -33,6 +33,12 @@ impl Automation { Some(Value::Object(params)) => params.clone(), Some(_) => return Err(ToolError::InvalidArgs("params must be an object".into())), }; + // Without it the tool would do something else: add a header and footer, not update one. + if let Some(arg) = tools::command_needs(id) + && params.get(arg).is_none_or(Value::is_null) + { + return Err(ToolError::InvalidArgs(format!("{id} needs params.{arg} (see {tool})"))); + } let props = def.input_schema.get("properties").and_then(Value::as_object).ok_or_else(|| failed("tool has no parameter schema"))?; let accepted = props.keys().map(String::as_str).collect::>().join(", "); let mut warnings = Vec::new(); diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 866f441562..539feb0b26 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -44,6 +44,14 @@ fn view_transform_to_user(info: &pdfcraft_render::PageInfo, m: [f64; 6]) -> Resu impl Automation { /// Run the tool `name` with JSON `args` (an object; `null` means no arguments). pub fn call(&mut self, name: &str, args: &Value) -> Result> { + let out = self.call_tool(name, args); + // Whatever the call did, failed or not: the id of a header and footer it removed must not + // pass to one a later call adds with the same settings (#5785). + self.forget_removed_header_footers(); + out + } + + fn call_tool(&mut self, name: &str, args: &Value) -> Result> { let empty = json!({}); let args = if args.is_null() { &empty } else { args }; if !args.is_object() { @@ -203,6 +211,7 @@ impl Automation { "bookmark_export" => self.bookmark_export(&a)?, "bookmark_import" => self.bookmark_import(&a)?, "bookmark_copy" => self.bookmark_copy(&a)?, + "bookmark_suggest" => self.bookmark_suggest(&a)?, "bookmark_add" => { let page = self.page(&a)?; let parent = a.opt_path("parent")?.unwrap_or_default(); @@ -392,7 +401,13 @@ impl Automation { let doc = self.doc(&a)?; let p = &doc.info.pages[page]; let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from); - let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect(); + let images: Vec<_> = doc + .page_images(page) + .iter() + .enumerate() + .filter(|(_, im)| im.contains(user) && doc.image_shows_at(im, user)) + .map(|(i, _)| i + 1) + .collect(); json!({"page":page+1,"images":images}) } "page_images" => { @@ -721,6 +736,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_printer_marks" | "doc_remove_marks" => self.marks(name, &a)?, "doc_backdrops" => self.backdrops(&a)?, + "doc_header_footers" => self.header_footers(&a)?, "doc_unprotect" => { let mut out = self.apply(&a, Edit::RemoveProtection)?; out["security"] = security(self.doc(&a)?); diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 47ffb8583f..a0f1182cba 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -15,7 +15,107 @@ const BOOKMARK_PAGE: usize = 100; const MAX_BOOKMARK_PAGE: usize = 1000; +/// The ids `doc_header_footers` gives one document's headers and footers, for +/// `doc_header_footer`'s `update` (#5785). +/// +/// A mark is known by its recorded settings (marks with equal ones count as one, and Update finds +/// the one to change by them), so the id names the mark with those settings wherever it moves and +/// however the list around it changes. But equal settings alone don't make the same mark: one +/// removed and then added again with the same settings is a new one. So each mark gets a serial +/// when it is first seen, never given before, which it keeps only while it stays: every tool call +/// ends by forgetting the serials of the marks it removed or changed +/// ([`Automation::forget_removed_header_footers`]). An id taken before then names no mark, and +/// a stale selection is refused rather than applied to another mark. +pub(crate) struct HeaderFooterIds { + /// The working file the serials were last checked against: a call that leaves it as it was + /// removed no mark. + seen: Arc>, + /// The serial of each mark the document has, by [`settings_digest`]. + serials: std::collections::HashMap, +} + +/// The key ids are hashed with: afresh each run, like doc handles, so an id tells nothing about +/// text a document doesn't allow copying. +fn id_hasher() -> std::hash::DefaultHasher { + use std::hash::BuildHasher; + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(Default::default).build_hasher() +} + +/// The `id` of the mark with settings digest `digest` and serial `serial` ([`HeaderFooterIds`]). +fn header_footer_id(digest: u64, serial: u64) -> String { + use std::hash::Hasher; + let mut h = id_hasher(); + h.write_u64(digest); + h.write_u64(serial); + format!("{:016x}", h.finish()) +} + +/// Settings equal as compared, and only those, digest alike. +fn settings_digest(settings: &pdfcraft_engine::HeaderFooter) -> u64 { + use std::hash::{Hash, Hasher}; + // Every field, so a new one can't be left out. + let pdfcraft_engine::HeaderFooter { text, font, font_size, color, underline, margins, start_number, shrink } = settings; + let mut h = id_hasher(); + text.hash(&mut h); + h.write_u8(match font { + pdfcraft_engine::FontFamily::Helvetica => 0, + pdfcraft_engine::FontFamily::Times => 1, + pdfcraft_engine::FontFamily::Courier => 2, + }); + // -0.0 equals 0.0 as a setting, so both hash as 0.0. (Listed settings are finite.) + for v in std::iter::once(font_size).chain(color).chain(margins) { + h.write_u64(if *v == 0.0 { 0 } else { v.to_bits() }); + } + underline.hash(&mut h); + start_number.hash(&mut h); + shrink.hash(&mut h); + h.finish() +} + impl Automation { + /// The headers and footers of `id` (as `Document::header_footers` lists them) with their ids, + /// giving a new serial to each one not seen before and forgetting those of the ones gone. + fn header_footers_with_ids(&mut self, id: DocId) -> Result> { + let doc = self.session.get(id).ok_or_else(|| failed("no such document"))?; + let marks = doc.header_footers(); + let ids = self.header_footer_ids.entry(id).or_insert_with(|| HeaderFooterIds { seen: doc.bytes.clone(), serials: Default::default() }); + ids.seen = doc.bytes.clone(); + let digests: Vec = marks.iter().map(|m| settings_digest(&m.settings)).collect(); + ids.serials.retain(|d, _| digests.contains(d)); + let last = &mut self.last_header_footer; + Ok(marks + .into_iter() + .zip(digests) + .map(|(m, d)| { + let serial = *ids.serials.entry(d).or_insert_with(|| { + *last += 1; + *last + }); + (m, header_footer_id(d, serial)) + }) + .collect()) + } + + /// After every tool call: forget the ids of the headers and footers the call removed or + /// changed, in each document ids were given for, so none passes to one added later + /// ([`HeaderFooterIds`]). A document whose working file the call left as it was is skipped. + pub(crate) fn forget_removed_header_footers(&mut self) { + let docs: Vec = self.header_footer_ids.keys().copied().collect(); + for id in docs { + let changed = match self.session.get(id) { + None => { + self.header_footer_ids.remove(&id); + continue; + } + Some(doc) => !Arc::ptr_eq(&doc.bytes, &self.header_footer_ids[&id].seen), + }; + if changed { + let _ = self.header_footers_with_ids(id); + } + } + } + // ---- documents --------------------------------------------------------------------------- /// One page of a document's bookmarks: `offset` (from 0) and `limit` (1 to `MAX_BOOKMARK_PAGE`). @@ -116,6 +216,7 @@ impl Automation { let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let errors = self.session.take_js_errors(id); let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?; let mut value = summary(doc); if let Some(destination) = destination { @@ -124,6 +225,10 @@ impl Automation { value["destination"] = destination; value["warning"] = json!(warning); } + // warnings lists the errors of the form's scripts that ran on open, including the messages that the scripts were stopped or turned off. + if !errors.is_empty() { + value["warnings"] = json!(errors); + } Ok(value) } @@ -174,6 +279,13 @@ impl Automation { // A save that adds or removes encryption, or must not keep the old revision (Sanitize, // redaction), is rewritten in full even when an incremental save was asked for. let incremental = !full && bytes.starts_with(&self.doc(a)?.saved_bytes()); + // A file that can't be replaced in place (read-only, extended attributes it can't keep, a + // folder that refuses the new file) stays as it was, and so does the unsaved edit: say how + // to keep the work, as 0.22.0 did before the writer moved into the framework. + let write = |path: &Path, bytes: &[u8]| match write(path, bytes) { + Err(ToolError::Failed(m)) if same_file => Err(failed(format!("{m}; save a copy with Save As (doc_save with a new path)"))), + other => other, + }; let mut out = self.publish_save(id, &target, bytes, incremental, write)?; if !scripts.is_empty() && let Some(o) = out.as_object_mut() @@ -577,11 +689,43 @@ impl Automation { /// The document's summary after an edit, with what it stored as typed but drew with `?`. fn applied(&mut self, a: &Args) -> Result { + let id = self.doc(a)?.id; + let errors = self.session.take_js_errors(id); let doc = self.doc(a)?; let mut out = summary(doc); // Text the edit stored as typed but drew with `?` (its font can't draw it): said, not silent. - if !doc.edit_notices.is_empty() { - out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::>()); + let mut warnings: Vec = doc.edit_notices.iter().map(ToString::to_string).collect(); + // The errors of the scripts the edit ran follow the notices, including the messages that a form's scripts were stopped or turned off. + warnings.extend(errors); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) + } + + /// The headers and footers with recorded settings, each with the `id` `doc_header_footer`'s + /// `update` names it by. Their text is copied out only where the document allows copying, as + /// with `doc_to_copy`. + pub(crate) fn header_footers(&mut self, a: &Args) -> Result { + let id = self.doc(a)?.id; + let marks = self.header_footers_with_ids(id)?; + let copying = self.doc(a)?.check_copying().is_ok(); + let found: Vec = marks + .iter() + .map(|(m, id)| { + let mut out = json!({ "id": id, "pages": m.pages.iter().map(|p| p + 1).collect::>() }); + if copying { + let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"]; + let text: serde_json::Map = + boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect(); + out["text"] = Value::Object(text); + } + out + }) + .collect(); + let mut out = json!({ "header_footers": found }); + if !copying { + out["text_withheld"] = json!("the document does not allow copying its text"); } Ok(out) } @@ -611,9 +755,28 @@ impl Automation { pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result { use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark}; let n = self.doc(a)?.info.pages.len(); - let pages = match a.opt_ints("pages")? { - Some(_) => self.pages(a, "pages")?, - None => (0..n).collect(), + // The header and footer `update` names, as `doc_header_footers` lists it. + let updating = match a.opt_str("update")? { + Some(_) if tool != "doc_header_footer" => return Err(ToolError::InvalidArgs("update is only for doc_header_footer".into())), + Some(_) if a.opt_bool("replace")?.is_some() => return Err(ToolError::InvalidArgs("give update or replace, not both".into())), + Some(id) => { + // By id, never by place in the list: a selection made before the list changed + // still reaches its own header and footer, or none (#5785). + let doc = self.doc(a)?.id; + let mark = self.header_footers_with_ids(doc)?.into_iter().find(|(_, i)| i == id).map(|(m, _)| m); + Some(mark.ok_or_else(|| { + ToolError::InvalidArgs(format!( + "no header and footer has the id {id:?}: it was changed or removed since doc_header_footers listed it, so list them again" + )) + })?) + } + None => None, + }; + let updated = updating.is_some(); + let pages = match (a.opt_ints("pages")?, &updating) { + (Some(_), _) => self.pages(a, "pages")?, + (None, Some(mark)) => mark.pages.clone(), + (None, None) => (0..n).collect(), }; let color = |key: &str, default: [f64; 3]| -> Result<[f64; 3]> { Ok(a.opt_str(key)?.map(comments::parse_color).transpose()?.unwrap_or(default)) }; @@ -644,7 +807,10 @@ impl Automation { hf.start_number = s.clamp(1, u32::MAX as i64) as u32; } hf.shrink = a.opt_bool("shrink")?.unwrap_or(false); - Edit::AddHeaderFooter { pages, settings: hf, replace } + match updating { + Some(mark) => Edit::UpdateHeaderFooter { old: mark.settings, pages, settings: hf }, + None => Edit::AddHeaderFooter { pages, settings: hf, replace }, + } } "doc_watermark" => { let d = Watermark::default(); @@ -659,7 +825,13 @@ impl Automation { scale: a.opt_num("scale")?.unwrap_or(d.scale).clamp(0.01, 1.0), font_size: a.opt_num("font_size")?.unwrap_or(0.0), color: color("color", d.color)?, - opacity: a.opt_num("opacity")?.unwrap_or(d.opacity), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => d.opacity, + }, rotation: a.opt_num("rotation")?.unwrap_or(d.rotation), behind: a.opt_bool("behind")?.unwrap_or(false), offset: [ @@ -673,7 +845,13 @@ impl Automation { pages, settings: Background { color: color("color", [1.0; 3])?, - opacity: a.opt_num("opacity")?.unwrap_or(1.0), + opacity: match a.opt_num("opacity")? { + Some(o) if !(0.0..=1.0).contains(&o) => { + return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}"))); + } + Some(o) => o, + None => 1.0, + }, scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0), replace_backdrop: a.opt_bool("replace_backdrop")?.unwrap_or(true), ..Background::default() @@ -713,7 +891,13 @@ impl Automation { Edit::RemoveMarks { kind } } }; - self.apply(a, edit) + let mut out = self.apply(a, edit)?; + // An update gives the header and footer it changed a new id (its settings changed): hand + // back the list as it now is. + if updated { + out["header_footers"] = self.header_footers(a)?["header_footers"].take(); + } + Ok(out) } pub(crate) fn export(&mut self, tool: &str, a: &Args) -> Result { diff --git a/crates/automation/src/json.rs b/crates/automation/src/json.rs index a2c4dce823..87cfe98fdb 100644 --- a/crates/automation/src/json.rs +++ b/crates/automation/src/json.rs @@ -422,6 +422,19 @@ fn link_target(i: &pdfcraft_render::DocInfo, target: &pdfcraft_render::LinkTarge }, "new_window": new_window, }), + pdfcraft_render::LinkTarget::EmbeddedGoTo { source, destination, new_window } => json!({ + "action": "GoToE", + "embedded_file": match source { + pdfcraft_render::AttachmentSource::Document { key } => json!({ "name": key }), + pdfcraft_render::AttachmentSource::Annotation { page, index } => json!({ "page": page1(*page), "annotation": index.saturating_add(1) }), + }, + "destination": match destination { + pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }), + pdfcraft_render::RemoteDestination::Page { page, view } => json!({ "kind": "page", "page": page1(*page), "view": format!("{view:?}") }), + pdfcraft_render::RemoteDestination::Named(name) => json!({ "kind": "named", "name": name }), + }, + "new_window": new_window, + }), pdfcraft_render::LinkTarget::Other(o) => json!({ "other": o }), } } diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 8bdb3f5cf3..ee92ed67ca 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -101,6 +101,10 @@ pub struct Automation { next_ocr_review: u64, /// What object_copy copied, for object_paste into any open document. objects_clipboard: Option, + /// The header and footer ids handed out, by document (see `documents::HeaderFooterIds`). + header_footer_ids: HashMap, + /// The last serial a header and footer id was given; none is given twice. + last_header_footer: u64, } impl Default for Automation { @@ -122,6 +126,8 @@ impl Automation { ocr_reviews: HashMap::new(), next_ocr_review: 0, objects_clipboard: None, + header_footer_ids: HashMap::new(), + last_header_footer: 0, } } diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs index a876a77c91..4e200ce697 100644 --- a/crates/automation/src/links.rs +++ b/crates/automation/src/links.rs @@ -4,7 +4,7 @@ use pdfcraft_engine::{ Edit, LinkAction, LinkHighlight, LinkStyle, LinkZoom, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path, }; -use pdfcraft_render::{DestView, LinkTarget, RemoteDestination}; +use pdfcraft_render::{AttachmentSource, DestView, LinkTarget, RemoteDestination}; use serde_json::{Value, json}; use std::path::Path; @@ -224,10 +224,15 @@ impl Automation { .iter() .find(|link| link.page == page && link.index == index) .ok_or_else(|| failed(format!("page {page_number} has no link {index_number} (see link_list)")))?; - let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else { - return Err(bad("the selected link is not a supported local PDF GoToR link")); + let (file, destination, new_window) = match &link.target { + LinkTarget::RemoteGoTo { file, destination, new_window, .. } => (file.clone(), destination.clone(), *new_window), + LinkTarget::EmbeddedGoTo { source: attached, destination, new_window } => { + let (attached, destination, new_window) = (attached.clone(), destination.clone(), *new_window); + return self.open_embedded_link(a, &attached, destination, new_window); + } + _ => return Err(bad("the selected link is not a supported local PDF GoToR or embedded GoToE link")), }; - (source.path.clone(), file.clone(), destination.clone(), *new_window) + (source.path.clone(), file, destination, new_window) }; let path = resolve_remote_document_path(source_path.as_deref().map(Path::new), &file).map_err(failed)?; let allow_absolute = a.opt_bool("allow_absolute")?.unwrap_or(false); @@ -259,6 +264,44 @@ impl Automation { })) } + /// `link_open` for an embedded Go-To link (ISO 32000-2 §12.6.4.4): open the PDF attached to + /// the document, from the document's own bytes, as a new document. No file is read, so + /// `--root` has nothing to confine. + fn open_embedded_link( + &mut self, + a: &Args, + attached: &AttachmentSource, + destination: RemoteDestination, + new_window: Option, + ) -> Result { + let (name, bytes) = { + let doc = self.doc(a)?; + let att = doc + .info + .attachments + .iter() + .find(|x| x.source == *attached) + .ok_or_else(|| failed("the file this GoToE link names is not attached to the document"))?; + let bytes = pdfcraft_render::attachment_data(&doc.bytes, doc.password.as_deref(), att).map_err(failed)?; + (att.name.clone(), bytes) + }; + // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). + if !pdfcraft_render::looks_like_pdf(&bytes) { + return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it"))); + } + let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?; + let (destination_applied, destination_value, warning) = destination_report(opened, destination); + Ok(json!({ + "document": crate::summary(opened), + "embedded_file": name, + "destination_applied": destination_applied, + "destination": destination_value, + "warning": warning, + "new_window_hint": new_window, + })) + } + pub(crate) fn link_add(&mut self, a: &Args) -> Result { let page = self.page(a)?; let rect = self.view_rect(a, page)?.ok_or_else(|| bad("link_add needs rect"))?; diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index c0cf35f02c..d9475113ab 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -1,6 +1,7 @@ //! Printing tools: list printers, and print (or save the print-ready PDF) with Acrobat's Print //! dialog options. +use pdfcraft_engine::PrinterMarks; use pdfcraft_engine::print::{self, Binding, BookletSubset, Layout, Orientation, PAPERS, PageOrder, SizeMode, Subset, spool}; use serde_json::{Value, json}; @@ -41,11 +42,77 @@ fn printer_in(printers: Vec, printer: &str) -> Option Result> { + let Some(asked) = a.get("marks") else { + return if a.get("marks_weight").is_some() { Err(bad("marks_weight needs marks")) } else { Ok(None) }; + }; + let names = asked.as_array().filter(|names| !names.is_empty()).ok_or_else(|| bad(MARK_NAMES))?; + let mut marks = PrinterMarks { + trim: false, + bleed: false, + registration: false, + color_bars: false, + page_info: false, + label: name.to_string(), + date: format!("{y:04}-{m:02}-{d:02}"), + ..PrinterMarks::default() + }; + for mark in names { + match mark.as_str() { + Some("all") => (marks.trim, marks.bleed, marks.registration, marks.color_bars, marks.page_info) = (true, true, true, true, true), + Some("trim") => marks.trim = true, + Some("bleed") => marks.bleed = true, + Some("registration") => marks.registration = true, + Some("color_bars") => marks.color_bars = true, + Some("page_info") => marks.page_info = true, + _ => return Err(bad(MARK_NAMES)), + } + } + marks.line_weight = a.opt_num("marks_weight")?.unwrap_or(0.25); + if !PrinterMarks::WEIGHTS.contains(&marks.line_weight) { + return Err(bad(format!("marks_weight must be from {} to {} points", PrinterMarks::WEIGHTS.start(), PrinterMarks::WEIGHTS.end()))); + } + if !matches!(layout, Layout::Size(_)) { + return Err(bad("printer marks print one page a sheet: use layout fit, actual, shrink or custom")); + } + Ok(Some(marks)) +} + /// An invalid-arguments error saying `m`. fn bad(m: impl Into) -> ToolError { ToolError::InvalidArgs(m.into()) } +/// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS` +/// index and size; US Letter when none is given. +/// +/// `pub(crate)` so Create answers the same names as Print: `doc_create` takes a `page_size` that +/// may be a paper name, and a second copy of this table would drift from this one. +pub(crate) fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> { + let mut papers = PAPERS.iter().enumerate(); + let found = match name { + None => papers.next(), + Some(p) => papers.find(|(_, (n, _))| { + n.eq_ignore_ascii_case(p) + || n.replace("US ", "").eq_ignore_ascii_case(p) + || n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p)) + }), + }; + found.map(|(index, (_, size))| (index, *size)).ok_or_else(|| { + bad(format!( + "unknown paper {:?}; choose one of {}", + name.unwrap_or_default(), + PAPERS.iter().map(|(name, _)| *name).collect::>().join(", ") + )) + }) +} + /// Parse explicit custom dimensions like "300x500", "300 x 500", "300x500 pt", "300pt x 500pt", "Custom.300x500". fn parse_custom_dimensions(s: &str) -> Option<(f64, f64)> { let s = s.trim().trim_start_matches("Custom.").trim_start_matches("custom.").trim(); @@ -111,7 +178,8 @@ fn resolve_paper(name: Option<&str>, printer: Option<&str>) -> Result<((f64, f64 /// naming none got (A4 under Letter sheets on the queue in #3752), and tells CUPS which way the /// laid-out `sheets` run, as the Print dialog does (#2713): an orientation the caller chose in /// `options` stands. It asks the driver for grayscale only when the pages aren't grey pictures -/// already ([`print::driver_needs_grayscale`]). +/// already ([`print::driver_needs_grayscale`]). Any caller-supplied `media` option (case-insensitive) +/// is replaced by the laid-out paper's media. fn spool_job( a: &Args, printer: &str, @@ -143,7 +211,10 @@ fn spool_job( grey_pages: false, title, options: { - let mut options: Vec<(String, String)> = options.into_iter().chain(media.map(|m| ("media".to_string(), m.to_string()))).collect(); + let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("media")).collect(); + if let Some(m) = media { + options.push(("media".to_string(), m.to_string())); + } print::add_cups_orientation(&mut options, sheets); options }, @@ -302,6 +373,7 @@ impl Automation { }, l => Layout::Size(print::names::parse_size_mode(l, 100.0).ok_or_else(|| bad(format!("unknown layout {l:?}")))?), }; + let marks = printer_marks(a, &layout, &self.doc(a)?.name, self.session.today())?; let printer = a.opt_str("printer")?; // The printer whose driver a booklet's both sides were decided for. The job goes to it by // name, so "default" can't become another printer while the document is rendered. The @@ -355,6 +427,19 @@ impl Automation { } else { None }; + if marks.is_some() && raster.is_some() { + return Err(bad("printer marks print with the pages as they are: leave out as_image and color_management app")); + } + // A document that allows only low-resolution printing is later forced to print as + // pictures in Session::print_pdf_marked. Refuse marks here, before Will Print runs + // and could change the document for a print that then fails. A document that allows + // no printing gets the engine's permission error instead. + let doc = self.doc(a)?; + if marks.is_some() && doc.allows_printing() && doc.permissions().is_some_and(|p| !p.print_high_quality()) { + return Err(bad( + "printer marks print with the pages as they are, not as pictures: a document that allows only low-resolution printing always prints as pictures", + )); + } let sizes: Vec<(f64, f64)> = self.doc(a)?.info.pages.iter().map(|p| (p.width as f64, p.height as f64)).collect(); // Print a selected area: points from the top-left of the displayed page, as other tools // take rectangles; the print crate takes it y up. @@ -366,6 +451,9 @@ impl Automation { Some([r[0].min(r[2]), h - r[1].max(r[3]), r[0].max(r[2]), h - r[1].min(r[3])]) } }; + if marks.is_some() && area.is_some() { + return Err(bad("area prints part of a page, without printer marks: leave out one or the other")); + } let settings = print::Settings { pages, paper, orientation, layout, content, raster, crops: Vec::new(), area }; let laid_out = print::layout(&sizes, &settings).map_err(|e| bad(e.to_string()))?; let sheets = laid_out.len(); @@ -387,13 +475,20 @@ impl Automation { } _ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")), }; + // Marks that would widen a page past the largest page a PDF can have fail here, before + // the Will Print actions run and could change the document for a print that then fails. + if let Some(m) = marks.as_ref() + && self.doc(a)?.allows_printing() + { + self.session.check_printer_marks(id, &settings.pages, m).map_err(failed)?; + } // The document's Will Print actions run first: what they change is printed (#269). let scripts = if self.doc(a)?.allows_printing() { self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint) } else { Default::default() }; - let bytes = self.session.print_pdf(id, &settings).map_err(failed)?; + let bytes = self.session.print_pdf_marked(id, &settings, marks.as_ref()).map_err(failed)?; let mut out = json!({ "sheets": sheets, "pages": settings.pages.len(), "bytes": bytes.len() }); if let Some(c) = settings.raster.as_ref().and_then(|r| r.colour.as_ref()) { out["color_management"] = @@ -581,4 +676,26 @@ mod tests { assert_eq!(paper_size(spec), None, "{spec}"); } } + + /// A user-supplied `media` option must not reach the spooler alongside the + /// laid-out paper's own `media` option: the job carries exactly one `media` + /// entry, and it is the paper the sheets were laid out on. + #[test] + fn spool_job_does_not_duplicate_media_option() { + let index = 0; // US Letter + let media_name = print::cups_media(index).unwrap(); + let job = spool_job( + &Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })), + "Office", + "a.pdf".into(), + None, + Some(media_name), + None, + &[], + ) + .unwrap(); + let media: Vec<&(String, String)> = job.options.iter().filter(|(k, _)| k == "media").collect(); + assert_eq!(media, [print::media_option(index).as_ref().unwrap()]); + assert!(job.options.contains(&("InputSlot".to_string(), "Tray3".to_string()))); + } } diff --git a/crates/automation/src/signing.rs b/crates/automation/src/signing.rs index f2b583c070..0f0c5c88d7 100644 --- a/crates/automation/src/signing.rs +++ b/crates/automation/src/signing.rs @@ -2,6 +2,8 @@ //! document, and manage trusted certificates. Rectangles are points from the top-left of the //! displayed page. +use std::io::Read; + use pdfcraft_engine::js::SignEvent; use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey}; use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus}; @@ -9,6 +11,9 @@ use serde_json::{Value, json}; use crate::{Args, Automation, Result, ToolError, failed, write_atomic}; +/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`). +const EU_LIST: &str = "EU Trusted List"; + fn bad(m: impl Into) -> ToolError { ToolError::InvalidArgs(m.into()) } @@ -377,8 +382,10 @@ impl Automation { } pub(crate) fn sign_trust(&mut self, a: &Args) -> Result { - let mut certs: Vec = - if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() }; + // Every argument is read and checked first, so a bad one changes nothing, and the changes + // are applied together: the open documents are revalidated once, not once per change. + let clear = a.opt_bool("clear")?.unwrap_or(false); + let mut certs: Vec = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() }; // Which certificates are already in, by their bytes: a set, so a bundle of many distinct // certificates isn't compared against every one before it. let mut known: std::collections::HashSet> = certs.iter().map(|c| c.raw.clone()).collect(); @@ -391,6 +398,7 @@ impl Automation { .map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings"))) .collect::>()?, }; + let certs_changed = clear || !paths.is_empty(); for p in paths { let path = self.resolve(&p, false)?; let bytes = crate::read_input(&path)?; @@ -407,7 +415,37 @@ impl Automation { } } } - self.session.set_trusted_certificates(certs); - Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>() })) + // The trust list, off until asked for. `None`: not mentioned, left alone. + let eu_list = match a.get("eu_trusted_list") { + None => None, + Some(Value::Bool(false) | Value::Null) => Some(None), + Some(Value::String(p)) => { + let path = self.resolve(p, false)?; + // One byte more than allowed is read, so an oversize file (or one that grows, or a + // device) is refused by `from_bytes` instead of being read whole. + let mut bytes = Vec::new(); + std::fs::File::open(&path) + .and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes)) + .map_err(|e| failed(format!("{}: {e}", path.display())))?; + Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?)) + } + Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")), + }; + if certs_changed || eu_list.is_some() { + self.session.update_trust(|trust| { + if certs_changed { + trust.certs = certs; + } + match eu_list { + Some(Some(list)) => trust.add_list(list), + Some(None) => trust.remove_list(EU_LIST), + None => {} + } + }); + } + Ok(json!({ + "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>(), + "trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::>(), + })) } } diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index a1ef365f78..389421bca5 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -469,7 +469,8 @@ fn a_failed_save_sync_keeps_the_document_dirty_and_can_be_retried() { let before = summary(a.doc(&Args(&args)).unwrap()); // The writer refuses as a storage whose flush fails does: nothing reaches the file. let result = a.doc_save_with(&Args(&args), |_, _| Err(failed("injected storage sync failure".to_string()))); - assert!(result.is_err()); + let error = result.unwrap_err().to_string(); + assert!(error.contains("injected storage sync failure") && error.contains("Save As"), "the refusal says how to keep the work: {error}"); let doc = a.doc(&Args(&args)).unwrap(); assert!(doc.dirty); assert_eq!(summary(doc), before, "failed save must not reset history or saved state"); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 719fb7e6b8..80d99eac5c 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -183,7 +183,7 @@ pub fn tools() -> Vec { )), t("attachment_edit", "Edit an attachment description", "Change the description of a document attachment by its exact key from doc_info, or by a unique displayed name. An empty description clears it. The file and other attachment data are preserved. Undoable.") .with(schema(json!({"doc": doc(), "key": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "description"])), - t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is.") + t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is. `warnings` lists the errors of the form's scripts on open, including the messages that they were stopped or turned off.") .cmd("file.open") .with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])), t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])), @@ -363,12 +363,13 @@ pub fn tools() -> Vec { "passwords": { "type": "array", "items": { "type": ["string", "null"] } }, "groups": { "type": "array", "items": { "type": ["integer", "null"], "minimum": 0 } }, "field_conflicts": { "type": "string", "enum": ["rename", "merge"] }, + "out": save_out, "open": open, }), &["paths"], )), - t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files, Office documents through an installed LibreOffice) to PDF in one run. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") + t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files, Office documents through an installed LibreOffice) to PDF in one run; page_size puts each image on a sheet of one size instead of a page as large as the image. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") .cmd("create.multiple") .with(schema( json!({ @@ -378,6 +379,8 @@ pub fn tools() -> Vec { "out": save_out.clone(), "open": open.clone(), "out_dir": { "type": "string", "description": "Folder for mode \"separate\"." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), &["paths"], )), @@ -494,6 +497,13 @@ pub fn tools() -> Vec { "Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.", ) .with(schema(json!({ "doc": doc() }), &["doc"])), + t( + "bookmark_suggest", + "Suggest bookmarks", + "Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, there were more than 10000 headings (the first 10000 are given), or the structure tree nests or branches too far to read whole. Changes nothing: bookmarks is in bookmark_export's form, so edit titles, remove entries or move them into or out of a bookmark's children to change the nesting, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.", + ) + .ro() + .with(schema(json!({ "doc": doc() }), &["doc"])), t( "text_styles", "List text styles", @@ -544,7 +554,7 @@ pub fn tools() -> Vec { t( "form_fill", "Fill in form fields", - "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.", + "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value. `warnings` also lists the errors of the form's scripts that the change ran, including the messages that they were stopped or turned off.", ) .with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])), t( @@ -774,7 +784,7 @@ pub fn tools() -> Vec { t( "doc_print", "Print", - "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"x\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again.", + "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). marks (Acrobat's Marks and Bleeds, with a one-page-a-sheet layout: fit, actual, shrink or custom): a list of all, trim, bleed, registration, color_bars and page_info (document name, page n of N, date), drawn around each page on the printed copy only, in registration colour except the colour bars, at marks_weight points (0.1 to 4, default 0.25); the page is widened for them, so fit shrinks it to make room, and marks the document already has print once; not with as_image, color_management app or area. orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"x\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on." ) .with(schema( json!({ @@ -795,9 +805,11 @@ pub fn tools() -> Vec { "creep": { "type": "number", "minimum": 0, "maximum": 10, "description": "Booklet creep compensation: points each sheet's pages move toward the fold, times the sheet's place from the outside (default 0)." }, "overlap": { "type": "number", "minimum": 0 }, "cut_marks": { "type": "boolean" }, + "marks": { "type": "array", "items": { "type": "string", "enum": ["all", "trim", "bleed", "registration", "color_bars", "page_info"] }, "description": "Printer's marks drawn around each page on the printed copy only (one page a sheet; not with as_image, color_management app or area)." }, + "marks_weight": { "type": "number", "minimum": 0.1, "maximum": 4, "description": "With marks: their line weight in points (default 0.25)." }, "orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] }, "comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] }, - "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side)." }, + "paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any caller-supplied `media` option in `options` is replaced by this paper." }, "path": { "type": "string" }, "printer": { "type": "string" }, "copies": { "type": "integer", "minimum": 1, "maximum": 999 }, @@ -807,7 +819,7 @@ pub fn tools() -> Vec { "area": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Print a selected area: [x0, y0, x1, y1] in points from the top-left of the displayed page, of the one page in pages, sized by layout fit/actual/shrink/custom." }, "as_image": { "type": "boolean", "description": "Print as image (Acrobat's Advanced Print Setup): every page rendered to a picture at dpi before it is placed on the paper, for printers that skip text, shading or transparency; the print is no longer searchable text, and with grayscale the pictures are grey, so the printer isn't asked for grayscale (a driver without that setting still prints them)." }, "dpi": { "type": "number", "minimum": 72, "maximum": 600, "description": "Resolution for as_image (default 300)." }, - "options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value." }, + "options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value. Any caller-supplied `media` option is replaced by the paper the document was laid out on." }, "color_management": { "type": "string", "enum": ["printer", "app"], "description": "Who converts the colours: printer (default, the driver does) or app, which prints the pages as images (dpi, grayscale apply) converted from sRGB into color_profile." }, "color_profile": { "type": "string", "description": "For color_management app: a name or file name from print_color_profiles, or the path of an RGB or grey ICC printer profile." }, "rendering_intent": { "type": "string", "enum": ["perceptual", "relative", "saturation", "absolute"], "description": "For color_management app: how colours the printer can't reach are mapped (default relative colorimetric)." }, @@ -888,7 +900,7 @@ pub fn tools() -> Vec { t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url, or to_page with its zoom). A relative url also has resolved_url, the address resolved against the document's base URI (catalog /URI /Base); a link active only in its /QuadPoints has active_areas, one rect per quadrilateral. With text_links: true, also the web and email addresses written as plain page text with no link over them, which the viewer opens on a click: page, rects (one per line), url, and blocked (why it won't open) when the link check refuses it. Only http, https and mailto addresses are found. At most 100 pages are read per call, from text_links_from (default 1); text_links_next_page then gives the page to continue from.") .ro() .with(schema(json!({ "doc": doc(), "text_links": { "type": "boolean" }, "text_links_from": { "type": "integer", "minimum": 1 } }), &["doc"])), - t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. A named destination is looked up in the target, as the app does; one the target doesn't define is reported with a warning. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.") + t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. A named destination is looked up in the target, as the app does; one the target doesn't define is reported with a warning. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in. A GoToE link opens the PDF embedded in this document that it names (a child target), from the document itself.") .with(schema( json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 }, "password": { "type": "string", "description": "Optional password for the linked PDF." }, "allow_absolute": { "type": "boolean", "description": "Explicitly allow an absolute local GoToR target (default false). Existing validation and --root confinement still apply." } }), &["doc", "page", "index"], @@ -1077,8 +1089,8 @@ pub fn tools() -> Vec { }), &["doc", "id", "out"], )), - t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema( - json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }), + t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema( + json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }), &[], )), t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema( @@ -1237,13 +1249,14 @@ pub fn tools() -> Vec { t( "doc_header_footer", "Add header and footer", - "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out existing ones (Update). Undoable.", + "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out every one on those pages. update: an id from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults, and the result lists them again (the changed one under a new id). Undoable.", ) .cmd("edit.header_footer") .with(schema( json!({ "doc": doc(), "pages": pages("to mark (default: all)"), + "update": { "type": "string", "minLength": 1, "description": "The id doc_header_footers lists for the header and footer to change; refused once that one has been changed or removed. Not with replace." }, "header_left": { "type": "string" }, "header_center": { "type": "string" }, "header_right": { "type": "string" }, "footer_left": { "type": "string" }, "footer_center": { "type": "string" }, "footer_right": { "type": "string" }, "font": { "type": "string", "enum": ["Helvetica", "Times", "Courier"] }, @@ -1301,6 +1314,10 @@ pub fn tools() -> Vec { .ro() .cmd("edit.background") .with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])), + // No command: edit.header_footer.update changes the document, and this only lists. + t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `id` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded (left out, with `text_withheld`, when the document does not allow copying). Lists those PdfCraft recorded settings for, in page order; older ones and other tools' are left out. An id names its header and footer wherever it moves and whatever else changes, until that one is changed or removed (or PdfCraft restarts); an update with it after that is refused, even once one with the same settings is added again (that one gets a new id).") + .ro() + .with(schema(json!({ "doc": doc() }), &["doc"])), t("doc_remove_marks", "Remove header & footer, watermark, background or printer marks", "Remove every header and footer, watermark, background or printer marks PdfCraft (or a compatible tool) added. Undoable.") .destructive() .with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background", "printer_marks"] } }), &["doc", "kind"])), @@ -1320,7 +1337,7 @@ pub fn tools() -> Vec { t("accessibility_autotag_preview", "Preview automatic tags", "Propose paragraph and heading tags for visible text blocks on one page. Returns page bounds, tentative roles and reasons. Does not change the PDF or claim accessibility compliance. Images, tables, lists, annotations and existing structure require separate review.") .ro() .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])), - t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.") + t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, heading and paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Text repeating at the top or bottom of most pages (running headers, footers and page numbers) is marked as pagination artifacts instead and listed in running_text. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.") .with(schema(json!({ "doc": doc() }), &["doc"])), t("accessibility_autotag_form_fields", "Tag form fields", "Write `/Form` tags, widget structure-parent keys, and a parent tree for all page widgets in an untagged AcroForm. Existing tag trees are refused for review. Text, figures, links, and other content are not tagged.") .cmd("a11y.autotag_fields") @@ -1390,7 +1407,7 @@ pub fn tools() -> Vec { .ro() .cmd("a11y.alt_text") .with(schema(json!({ "doc": doc() }), &["doc"])), - t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). figure is a number from accessibility_figures. Returns the figures. Undoable.") + t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). Decorative actions reject form streams, annotation or object references, other-page or invalid content references, and tags with structure children before changing the document. figure is a number from accessibility_figures. Returns the figures. Undoable.") .cmd("a11y.alt_text") .with(schema(json!({ "doc": doc(), "figure": { "type": "integer", "minimum": 1 }, "alt": { "type": "string" }, "decorative": { "type": "boolean" } }), &["doc", "figure"])), t("accessibility_tags", "List structure tags", "List reachable indirect structure tags in document order with PDF object number, generation, nearest indirect parent, depth, page, type, title, actual text, alternate text, language, a table's summary and a header cell's scope, one page at a time: count is how many tags match, next the offset of the following page (null at the end). types, pages and max_depth keep only some tags. Inline tag dictionaries have no stable object reference and are not listed.") @@ -1418,7 +1435,7 @@ pub fn tools() -> Vec { "property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] }, "value": { "type": "string" }, }), &["doc", "object", "generation", "property"])), - t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, content not found on its page, or content that a damaged or undecodable content stream may hide or change are rejected. Undoable.") + t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Form streams, annotation or object references, other-page or invalid content references, and structure children are rejected before changing the document. Tags with no direct marked content, content not found on its page, or content that a damaged or undecodable content stream may hide or change are also rejected. Undoable.") .with(schema(json!({ "doc": doc(), "object": { "type": "integer", "minimum": 1 }, "generation": { "type": "integer", "minimum": 0, "maximum": 65535 }, @@ -1439,10 +1456,10 @@ pub fn tools() -> Vec { 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 and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; AcroForm replies consume ordered answers; missing replies cancel input or use the alert button set's safe default), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") + 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 and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers (on an XFA button only its message boxes do, xfa.host.messageBox, $host.messageBox and app.alert; its xfa.host.response and app.response return null and take none), each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") .cmd("tools.js_console") .with(schema( - json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and alert answers; strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects an alert default (OK, Cancel or No, by button set)."} }), + json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and message box answers (every message box takes one, OK-only ones too; an XFA button's responses take none; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }), &["doc", "script"], )), t( @@ -1658,7 +1675,7 @@ pub fn tools() -> Vec { t( "doc_create", "Create a PDF", - "Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG, JPEG, TIFF (every page), GIF or BMP files, one page each at the image's resolution) or `text` (a .txt path, or `text` directly; set in Helvetica, or in the bundled Inter face when it has Latin, Greek or Cyrillic letters outside Western European (WinAnsi); other characters are refused). Save it with doc_save and a path.", + "Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG, JPEG, TIFF (every page), GIF or BMP files, one page each at the image's resolution, or every image on a page of one size with page_size) or `text` (a .txt path, or `text` directly; set in Helvetica, or in the bundled Inter face when it has Latin, Greek or Cyrillic letters outside Western European (WinAnsi); other characters are refused). Save it with doc_save and a path.", ) .with(schema( json!({ @@ -1671,6 +1688,9 @@ pub fn tools() -> Vec { "width": { "type": "number", "minimum": 3 }, "height": { "type": "number", "minimum": 3 }, "name": { "type": "string", "description": "Name for the new document (default derived from the source)." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, + }), &["from"], )), @@ -1704,7 +1724,7 @@ pub fn tools() -> Vec { .ro() .cmd("edit.edit_text") .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])), - t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected. Read only.") + t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected; a picture with transparency (soft mask, /Mask, stencil) counts only where it shows. Read only.") .ro() .cmd("edit.edit_text") .with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2}}), &["doc","page","point"])), @@ -1850,8 +1870,18 @@ pub(crate) fn find(name: &str) -> Option<&'static ToolDef> { TOOLS.iter().find(|t| t.name == name) } +/// Commands a tool runs besides its own [`ToolDef::command`], each with the argument that makes +/// the tool do what the command does: Update header & footer is `doc_header_footer`'s `update`. +const MORE_COMMANDS: &[(&str, &str, &str)] = &[("edit.header_footer.update", "doc_header_footer", "update")]; + pub(crate) fn tool_for_command(id: &str) -> Option<&'static str> { - TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name) + let more = || MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(_, tool, _)| *tool); + TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name).or_else(more) +} + +/// The argument command `id` needs, when its tool does something else without it. +pub(crate) fn command_needs(id: &str) -> Option<&'static str> { + MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(.., arg)| *arg) } /// Reject unknown and missing arguments (types are checked when each value is read). @@ -1869,3 +1899,18 @@ pub(crate) fn check_args(def: &ToolDef, args: &Value) -> Result<(), ToolError> { } Ok(()) } + +#[cfg(test)] +mod tests { + /// Each extra command is a registered one, run by a tool that takes the argument it needs. + #[test] + fn more_commands_name_real_commands_tools_and_arguments() { + for (command, tool, arg) in super::MORE_COMMANDS { + assert!(pdfcraft_engine::commands::command(command).is_some(), "{command} is not registered"); + assert!(super::TOOLS.iter().all(|t| t.command != Some(*command)), "{command} already has a tool"); + let def = super::find(tool).unwrap_or_else(|| panic!("{tool} is not a tool")); + assert!(def.input_schema["properties"].get(*arg).is_some(), "{tool} takes no {arg}"); + assert_eq!(super::tool_for_command(command), Some(*tool)); + } + } +} diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index b809f0f87a..a3c0b4233e 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -554,6 +554,68 @@ fn autotag_apply_tags_headings_by_size_across_pages() { assert_eq!(nesting["status"], "passed", "{check}"); } +/// #7065: Apply marks a running header and a numbered footer as pagination artifacts and lists +/// them, and tags a body line that repeats mid-page like any other text. +#[test] +fn autotag_apply_marks_running_headers_and_footers_as_artifacts() { + let dir = workdir("autotag-running"); + let page = |n: usize| { + format!( + "BT /FR 9 Tf 72 760 Td (Annual report) Tj ET BT /FR 11 Tf 72 640 Td (Body text on page {n} that runs long enough to set the body size) Tj ET \ + BT /FR 11 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /FR 9 Tf 300 30 Td (Page {n}) Tj ET" + ) + }; + let mut objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /FR 9 0 R >> >> >>".into(), + ]; + objs.extend((6..9).map(|c| format!("<< /Type /Page /Parent 2 0 R /Contents {c} 0 R >>"))); + objs.extend((1..4).map(|n| { + let content = page(n); + format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()) + })); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into()); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(dir.join("running.pdf"), bytes).unwrap(); + + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "running.pdf" }))["doc"].as_u64().unwrap(); + let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + let types: Vec<&str> = applied["tags"].as_array().unwrap().iter().map(|t| t["type"].as_str().unwrap()).collect(); + assert_eq!(types, ["Document", "P", "P", "P", "P", "P", "P"], "only the body text is tagged: {applied}"); + assert_eq!(applied["running_count"], 6); + let listed: Vec<(u64, &str, &str)> = applied["running_text"] + .as_array() + .unwrap() + .iter() + .map(|r| (r["page"].as_u64().unwrap(), r["subtype"].as_str().unwrap(), r["text"].as_str().unwrap())) + .collect(); + assert_eq!(listed[..2], [(1, "Header", "Annual report"), (1, "Footer", "Page 1")]); + assert_eq!(listed[5], (3, "Footer", "Page 3")); + assert!(applied["note"].as_str().unwrap().contains("6 text objects"), "{applied}"); + let check = ok(&mut a, "accessibility_check", json!({ "doc": doc, "rules": ["tagged-content"] })); + let content = check["results"].as_array().unwrap().iter().find(|r| r["rule"] == "tagged-content").unwrap(); + assert_eq!(content["status"], "passed", "{check}"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" })); + let reopened = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("tagged.pdf")).unwrap())).unwrap(); + let first = pdfcraft_model::pages(&reopened).into_iter().next().unwrap(); + let pdfcraft_cos::Object::Stream(stream) = &*reopened.resolve(first.dict.get(b"Contents").unwrap()) else { panic!("page content") }; + let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap(); + assert!(text.contains("/Artifact <> BDC"), "{text}"); + assert!(text.contains("/Artifact <> BDC"), "{text}"); +} + #[test] fn autotag_form_fields_writes_reviewable_widget_tags() { let dir = workdir("autotag-form-fields"); @@ -2758,6 +2820,19 @@ fn verify_comment_errors(a: &mut Automation, doc: u64, id: &str) { Err(ToolError::InvalidArgs(_)) )); assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1 })), Err(ToolError::InvalidArgs(_)))); + // #2670: opacity must be between 0 and 1. + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": -3 })), + Err(ToolError::InvalidArgs(_)) + )); + assert!(matches!( + a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": 1.5 })), + Err(ToolError::InvalidArgs(_)) + )); + let first = ok(a, "comment_list", json!({ "doc": doc }))["comments"][0].clone(); + let (page, index) = (first["page"].as_u64().unwrap(), first["index"].as_u64().unwrap()); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": 2.0 })), Err(ToolError::InvalidArgs(_)))); } fn save_and_reopen_comments(dir: &Path, a: &mut Automation, doc: u64) { @@ -3200,6 +3275,11 @@ fn copy_restricted_text_stays_in_the_document() { } let restyled = ok(&mut a, "text_edit", json!({ "doc": re, "page": 1, "paragraph": 1, "size": 30 })); assert!(!restyled.to_string().contains("Page"), "{restyled}"); + // A header's text is listed only where copying is allowed: its index and pages still are. + ok(&mut a, "doc_header_footer", json!({ "doc": re, "pages": [1], "header_left": "HEADERTEXT" })); + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": re })); + assert!(!listed.to_string().contains("HEADERTEXT") && listed["text_withheld"].is_string(), "{listed}"); + assert_eq!(listed["header_footers"][0]["pages"], json!([1])); // A path that would carry the page's words OUT of the document — the editable output, or // the review word list — is refused on a copy-restricted document (no engines needed). match a.call("ocr_recognize", &json!({ "doc": re, "output_mode": "editable", "out": "copy.pdf" })) { @@ -3839,6 +3919,127 @@ fn duplicating_and_cropping_through_tools() { assert!(matches!(a.call("page_set_box", &json!({ "doc": doc, "rect": [0, 0, 10, 10] })), Err(ToolError::InvalidArgs(_)))); } +#[test] +fn header_footer_update_changes_the_one_named() { + let dir = workdir("marks-update"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "header_left": "FIRST" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2, 3], "header_left": "SECOND" })); + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + assert_eq!(listed["header_footers"][0]["pages"], json!([1])); + let second = &listed["header_footers"][1]; + assert_eq!((&second["pages"], &second["text"]), (&json!([2, 3]), &json!({ "header_left": "SECOND" }))); + assert!(second["id"].as_str().is_some_and(|id| !id.is_empty()), "{second}"); + let first = listed["header_footers"][0]["id"].clone(); + assert_ne!(first, second["id"]); + // THIRD shares page 1 with FIRST and must stay. + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" })); + let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": first, "header_left": "CHANGED" })); + assert_eq!(updated["header_footers"], ok(&mut a, "doc_header_footers", json!({ "doc": doc }))["header_footers"], "the ids as they are now"); + let texts = page_text(&mut a, doc); + assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}"); + assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}"); + assert!(texts[1].contains("SECOND") && !texts[1].contains("CHANGED"), "{texts:?}"); + // Given pages, the update goes there instead: it leaves every page the old one was on, and + // the other header and footer on those pages stays. + let changed = header_footer_id(&updated, "CHANGED"); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": changed, "pages": [2], "header_left": "MOVED" })); + let texts = page_text(&mut a, doc); + assert!(!texts[0].contains("CHANGED") && !texts[0].contains("MOVED") && texts[0].contains("THIRD"), "{texts:?}"); + assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "{texts:?}"); + assert!(!texts[2].contains("MOVED") && texts[2].contains("SECOND"), "{texts:?}"); + let moved = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "MOVED"); + for bad in [ + json!({ "doc": doc, "update": "no-such-id", "header_left": "X" }), + json!({ "doc": doc, "update": 1, "header_left": "X" }), + json!({ "doc": doc, "update": moved, "replace": true, "header_left": "X" }), + ] { + assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}"); + } + // The Update command runs the update, and only with an id: without one, the tool would add + // a header and footer instead. + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + let no_id = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "header_left": "NO ID" } }); + assert!(matches!(a.call("command_run", &no_id), Err(ToolError::InvalidArgs(_)))); + assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), listed, "nothing changed"); + let third = header_footer_id(&listed, ""); + let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": third, "header_left": "VIA COMMAND" } }); + ok(&mut a, "command_run", by_command); + let texts = page_text(&mut a, doc); + assert!(texts[0].contains("VIA COMMAND") && !texts[0].contains("THIRD"), "{texts:?}"); + assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "the others stay: {texts:?}"); +} + +/// The `id` a `doc_header_footers` (or update) result lists for the header and footer whose +/// header_left is `text` ("" for one without). +fn header_footer_id(listed: &Value, text: &str) -> Value { + let marks = listed["header_footers"].as_array().unwrap(); + let mark = marks.iter().find(|m| m["text"]["header_left"].as_str().unwrap_or("") == text).unwrap_or_else(|| panic!("no {text:?} in {listed}")); + mark["id"].clone() +} + +/// A selection names its header and footer, never a place in the list (#5785). After the list +/// changes under it (another one added in front, another moved to other pages), an update with an +/// id taken earlier changes only that one; with the id of one changed since, it is refused and +/// nothing changes. With list indices, both would have reached a different header and footer. +/// Equal settings don't make the same one either: an id taken before its header and footer was +/// removed is refused after one with the same settings is added again. +#[test] +fn header_footer_update_never_reaches_another_one() { + let dir = workdir("marks-update-stale"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2], "header_left": "EARLY" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "LATE" })); + // The selection: both ids, as listed (in page order, EARLY first). + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + let (early, late) = (header_footer_id(&listed, "EARLY"), header_footer_id(&listed, "LATE")); + assert_eq!((&listed["header_footers"][0]["id"], &listed["header_footers"][1]["id"]), (&early, &late)); + + // The list changes: a new one comes first, and LATE moves to page 1 (a new id, and now listed + // ahead of EARLY too). + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "NEW" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": late, "pages": [1], "header_left": "LATE MOVED" })); + let now = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + assert_eq!(now["header_footers"].as_array().unwrap().len(), 3, "{now}"); + assert_eq!(now["header_footers"][2]["id"], early, "EARLY is listed last, and NEW where EARLY was: {now}"); + + // LATE's id is stale: refused, and no header and footer changes. + let before = page_text(&mut a, doc); + let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": late, "header_left": "WRONG" })); + assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}"); + assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), now, "nothing changed"); + assert_eq!(page_text(&mut a, doc), before); + + // EARLY's id still names EARLY alone, though another now sits where it was listed. + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": early, "header_left": "EARLY CHANGED" })); + let texts = page_text(&mut a, doc); + assert!(texts[1].contains("EARLY CHANGED"), "{texts:?}"); + assert!(texts[0].contains("LATE MOVED") && texts[0].contains("NEW") && !texts[0].contains("EARLY"), "{texts:?}"); + assert!(!texts[2].contains("EARLY") && !texts[2].contains("LATE"), "{texts:?}"); + + // Removed, and then added again with the same settings on another page, without a listing in + // between: that is a new header and footer. The id taken before the removal names none, so it + // is refused and the new one stays as it is. + let gone = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "EARLY CHANGED"); + ok(&mut a, "doc_remove_marks", json!({ "doc": doc, "kind": "header_footer" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "EARLY CHANGED" })); + let recreated = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + assert_eq!(recreated["header_footers"].as_array().unwrap().len(), 1, "{recreated}"); + assert_ne!(header_footer_id(&recreated, "EARLY CHANGED"), gone, "a new id: {recreated}"); + let before = page_text(&mut a, doc); + assert!(before[2].contains("EARLY CHANGED") && !before[1].contains("EARLY"), "{before:?}"); + let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": gone, "header_left": "WRONG" })); + assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}"); + assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), recreated, "the recreated one is unchanged"); + assert_eq!(page_text(&mut a, doc), before); + // Its own id, listed after it was added, reaches it. + let fresh = header_footer_id(&recreated, "EARLY CHANGED"); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": fresh, "header_left": "RECREATED CHANGED" })); + assert!(page_text(&mut a, doc)[2].contains("RECREATED CHANGED")); +} + #[test] fn headers_watermarks_and_backgrounds_through_tools() { let dir = workdir("marks"); @@ -4026,6 +4227,8 @@ fn watermarks_move_from_the_page_centre_through_tools() { // Huge offsets are clamped, and a value that isn't a number is refused. ok(&mut a, "doc_watermark", json!({ "doc": doc, "pages": [1], "text": "DRAFT", "offset_y": 1e300, "replace": true })); assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "offset_x": "left" })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("doc_background", &json!({ "doc": doc, "color": "yellow", "opacity": -1 })), Err(ToolError::InvalidArgs(_)))); } #[test] @@ -4377,6 +4580,145 @@ trailer << /Root 1 0 R >> assert!(matches!(a.call("accessibility_mark_tag_artifact", &json!({ "doc": doc, "object": 6, "generation": 0 })), Err(ToolError::Failed(_)))); } +#[test] +fn stream_tag_mutation_refusal_preserves_document_history_and_saved_content() { + use pdfcraft_cos::{Document as CosDocument, Object, SaveOptions}; + use std::sync::Arc; + + let dir = workdir("a11y-stm-refusal"); + // Contributor-original page and form use separate MCID 0 namespaces. + let page = "/Figure <> BDC 10 10 20 20 re f EMC q /Fm Do Q"; + let form = "/Figure <> BDC 0 0 5 5 re f EMC"; + let source = format!( + "%PDF-1.7\n\ +1 0 obj << /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >> endobj\n\ +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Fm 10 0 R >> >> >> endobj\n\ +4 0 obj << /Length {} >> stream\n{page}\nendstream endobj\n\ +5 0 obj << /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >> endobj\n\ +6 0 obj << /S /Document /P 5 0 R /K [7 0 R 8 0 R] >> endobj\n\ +7 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K 0 /Alt (Page figure) >> endobj\n\ +8 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K << /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >> /Alt (Form figure) >> endobj\n\ +9 0 obj << /Nums [0 [7 0 R] 1 8 0 R] >> endobj\n\ +10 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >> stream\n{form}\nendstream endobj\n\ +trailer << /Root 1 0 R >>\n%%EOF", + page.len(), + form.len() + ); + for annotation_owned in [false, true] { + let mut synthetic = CosDocument::open(Arc::new(source.clone().into_bytes())).unwrap(); + if annotation_owned { + use pdfcraft_cos::{Dict, ObjRef}; + let annotation = synthetic.add(Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::Name(b"Annot".to_vec())), + (b"Subtype".to_vec(), Object::Name(b"Link".to_vec())), + (b"Rect".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(10), Object::Int(10)])), + (b"P".to_vec(), Object::Ref(ObjRef::new(3, 0))), + (b"StructParent".to_vec(), Object::Int(2)), + ]))); + synthetic.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation)]))).unwrap(); + synthetic + .update_dict(ObjRef::new(8, 0), |d| { + d.set( + b"K".to_vec(), + Object::Array(vec![ + Object::Int(0), + Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::Name(b"OBJR".to_vec())), + (b"Obj".to_vec(), Object::Ref(annotation)), + ])), + ]), + ) + }) + .unwrap(); + synthetic + .update_dict(ObjRef::new(9, 0), |d| { + d.set( + b"Nums".to_vec(), + Object::Array(vec![ + Object::Int(0), + Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]), + Object::Int(1), + Object::Ref(ObjRef::new(8, 0)), + Object::Int(2), + Object::Ref(ObjRef::new(8, 0)), + ]), + ) + }) + .unwrap(); + } + let source = pdfcraft_cos::write_full(&synthetic, &SaveOptions::default()).unwrap(); + std::fs::write(dir.join("stm.pdf"), source).unwrap(); + + for dirty in [false, true] { + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"stm.pdf"}))["doc"].as_u64().unwrap(); + let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + let figure = figures["figures"].as_array().unwrap().iter().find(|f| f["alt"] == "Form figure").unwrap()["figure"].as_u64().unwrap(); + if dirty { + ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"First"})); + ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"Second"})); + ok(&mut a, "edit_undo", json!({"doc":doc})); + } + let before = ok(&mut a, "doc_info", json!({"doc":doc}))["document"].clone(); + assert_eq!(before["dirty"], dirty); + assert_eq!(before["undo"].is_string(), dirty); + assert_eq!(before["redo"].is_string(), dirty); + let tags = ok(&mut a, "accessibility_tags", json!({"doc":doc})); + let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + for (tool, args) in [ + ("accessibility_set_alt", json!({"doc":doc,"figure":figure,"decorative":true})), + ("accessibility_mark_tag_artifact", json!({"doc":doc,"object":figure,"generation":0})), + ] { + let Err(ToolError::Failed(message)) = a.call(tool, &args) else { panic!("{tool} must refuse unsupported ownership") }; + let reason = if annotation_owned { "annotation or object references" } else { "form streams" }; + assert!(message.contains(reason), "useful unsupported-content reason: {message}"); + assert_eq!(ok(&mut a, "doc_info", json!({"doc":doc}))["document"], before); + assert_eq!(ok(&mut a, "accessibility_tags", json!({"doc":doc})), tags); + assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures); + } + if dirty { + ok(&mut a, "edit_redo", json!({"doc":doc})); + let figs = ok(&mut a, "accessibility_figures", json!({"doc":doc})); + assert_eq!(figs["figures"][1]["alt"], "Second"); + ok(&mut a, "edit_undo", json!({"doc":doc})); + assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures); + } + let name = if dirty { "dirty.pdf" } else { "clean.pdf" }; + ok(&mut a, "doc_save", json!({"doc":doc,"path":name,"full":true})); + let saved = CosDocument::open(Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap(); + let saved_figures = pdfcraft_engine::a11y::figures(&saved); + assert_eq!(saved_figures.len(), 2); + assert_eq!(saved_figures[0].alt.as_deref(), Some("Page figure")); + assert_eq!(saved_figures[1].alt.as_deref(), Some(if dirty { "First" } else { "Form figure" })); + assert_eq!(pdfcraft_engine::a11y::tags(&saved).len(), 3); + let catalog = saved.get(saved.root().unwrap()); + let root = saved.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap(); + let tree = saved.dict(root.get(b"ParentTree").unwrap()).unwrap(); + let mut expected_nums = + vec![Object::Int(0), Object::Array(vec![Object::Ref(saved_figures[0].obj)]), Object::Int(1), Object::Ref(saved_figures[1].obj)]; + if annotation_owned { + expected_nums.extend([Object::Int(2), Object::Ref(saved_figures[1].obj)]); + } + assert_eq!(tree.get(b"Nums"), Some(&Object::Array(expected_nums))); + let page_dict = saved.get(saved_figures[0].obj); + let page_ref = page_dict.as_dict().unwrap().get(b"Pg").unwrap(); + let page_dict = saved.dict(page_ref).unwrap(); + if annotation_owned { + let annotation = saved.resolve(&page_dict.get(b"Annots").unwrap().as_array().unwrap()[0]); + assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2))); + } + let Object::Stream(page_stream) = &*saved.resolve(page_dict.get(b"Contents").unwrap()) else { panic!("page content") }; + assert_eq!(page_stream.decoded().unwrap(), page.as_bytes()); + let resources = saved.dict(page_dict.get(b"Resources").unwrap()).unwrap(); + let xobjects = saved.dict(resources.get(b"XObject").unwrap()).unwrap(); + let Object::Stream(form_stream) = &*saved.resolve(xobjects.get(b"Fm").unwrap()) else { panic!("form content") }; + assert_eq!(form_stream.decoded().unwrap(), form.as_bytes()); + } + } + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn accessibility_review_record_compares_two_versions_without_changing_them() { let dir = workdir("a11y-review-record"); @@ -7511,6 +7853,65 @@ fn a_launch_link_to_a_pdf_opens_it_like_a_remote_link() { assert_eq!(a.session().docs().len(), before, "nothing was opened or launched"); } +/// An embedded Go-To link (ISO 32000-2 §12.6.4.4) opens the PDF attached to the document, from +/// the document itself: no file of that name is read, inside the root or out of it. One to a +/// file that isn't attached, or isn't a PDF, opens nothing. +#[test] +fn an_embedded_go_to_link_opens_the_attached_pdf() { + let (_base, root) = sandbox("gotoe"); + // A file of the attachment's name next to the document, which must not be what opens. + std::fs::write(root.join("inner.pdf"), fixture(1)).unwrap(); + let embedded = fixture(3); + let stream = |dict: &str, data: &[u8]| { + let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s + }; + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 5 0 R (notes.txt) 6 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R] >>".to_vec(), + stream("/Type /EmbeddedFile", &embedded), + b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(), + b"<< /Type /Filespec /F (notes.txt) /EF << /F 10 0 R >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 20 10 30] /A << /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 40 10 50] /A << /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >> >>".to_vec(), + stream("/Type /EmbeddedFile", b"just some notes"), + ]; + 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(root.join("outer.pdf"), pdf).unwrap(); + let mut a = auto(&root); + let source = ok(&mut a, "doc_open", json!({ "path": "outer.pdf" }))["doc"].as_u64().unwrap(); + let info = ok(&mut a, "doc_info", json!({ "doc": source })); + let link = &info["links"][0]["target"]; + assert_eq!((link["action"].as_str(), &link["embedded_file"]), (Some("GoToE"), &json!({ "name": "inner.pdf" })), "{info}"); + let opened = ok(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": 1 })); + assert_eq!(opened["document"]["pages"], 3, "the attached PDF, not the file beside the document: {opened}"); + assert_eq!((opened["embedded_file"].as_str(), opened["destination_applied"].as_bool()), (Some("inner.pdf"), Some(true))); + assert_eq!(opened["destination"], json!({ "kind": "page", "page": 3, "view": { "kind": "fit" } }), "{opened}"); + let before = a.session().docs().len(); + for (index, why) in [(2, "not attached"), (3, "notes.txt is not a PDF")] { + let e = err(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": index })); + assert!(matches!(&e, ToolError::Failed(m) if m.contains(why)), "{e}"); + } + assert_eq!(a.session().docs().len(), before, "nothing else was opened"); +} + /// A bookmark's action is reported as a link's target is, and only a go-to names a page here: a /// remote go-to's `[1 /Fit]` is the other file's page 2, so doc_info and bookmark_list give this /// file's no page for it. @@ -8683,6 +9084,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() { assert_eq!(piece_info("small.pdf"), ["Illustrator"]); } +#[test] +fn a_trust_list_is_off_until_loaded_through_sign_trust() { + let dir = workdir("trust_list"); + let mut a = auto(&dir); + ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" })); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" })); + let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string(); + assert_eq!(status(&mut a), "unknown", "nothing trusted by default"); + + // Default: no list. + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0)); + + // A trust list file (the certificate as DER), loaded by path. + let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap(); + std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap(); + let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" })); + assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List"); + assert_eq!(t["trust_lists"][0]["certificates"], 1); + assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates"); + assert_eq!(status(&mut a), "valid"); + // Bad input is refused and leaves the list as it was. + std::fs::write(dir.join("junk.der"), b"not certificates").unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_)))); + // A file over the size limit (sparse, so cheap) is refused without being read whole. + let big = std::fs::File::create(dir.join("big.der")).unwrap(); + big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_)))); + assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root"); + assert_eq!(status(&mut a), "valid"); + // Removing it makes the signer unknown again. + assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0)); + assert_eq!(status(&mut a), "unknown"); + + // One call can change everything at once (and revalidates once). + let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" })); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1))); + // A bad argument changes nothing, not even what came before it in the same call. + ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false })); + for bad in [ + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }), + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }), + ] { + assert!(a.call("sign_trust", &bad).is_err(), "{bad}"); + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}"); + } + assert_eq!(status(&mut a), "unknown"); +} + #[test] fn optimizing_through_tools() { let dir = workdir("optimize"); @@ -9653,6 +10107,9 @@ fn javascript_through_tools() { assert!(page_text(&mut a, doc)[0].contains("EUR 2.500,00"), "{:?}", page_text(&mut a, doc)); let err = a.call("form_fill", &json!({ "doc": doc, "values": { "Qty": "0" } })).unwrap_err(); assert!(err.to_string().contains("Order at least one"), "{err}"); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let qty = fields["fields"].as_array().unwrap().iter().find(|x| x["name"] == "Qty").unwrap(); + assert_eq!(qty["value"], "2", "the rejected value is reported, not stored"); let r = ok( &mut a, @@ -9737,6 +10194,47 @@ fn merging_form_data_into_a_spreadsheet() { assert_eq!(std::fs::read_to_string(dir.join("report.csv")).unwrap(), "City\nParis\nOslo\nOslo\n"); } +#[test] +fn merging_form_data_counts_a_quoted_header_as_one_column() { + let dir = workdir("merge-data-quoted-header"); + let mut a = auto(&dir); + let xfdf = |name: &str| { + format!( + r#"Checked"# + ) + }; + // A comma or a quote in a name makes it a quoted CSV cell, still one column. + for (file, name) in [ + ("comma.xfdf", "Shipping, notes"), + ("quote.xfdf", "Say "hi", ok"), + ("plain.xfdf", "Shipping notes"), + ("lf.xfdf", "a b"), + ("tab.xfdf", "a b"), + ] { + std::fs::write(dir.join(file), xfdf(name)).unwrap(); + let out = format!("{file}.csv"); + let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}"); + } + // A field with an empty name is one column, not the empty header of a file without fields. + std::fs::write(dir.join("noname.xfdf"), xfdf("")).unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["noname.xfdf"], "path": "noname.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(std::fs::read_to_string(dir.join("noname.csv")).unwrap(), "\nChecked\n"); + // Files without fields: no column. + std::fs::write(dir.join("empty.xfdf"), r#""#) + .unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["empty.xfdf"], "path": "empty.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(0)), "{r}"); + assert_eq!(std::fs::read_to_string(dir.join("empty.csv")).unwrap(), "\n\n"); + // Two files with different names, one of them quoted: three columns in all. + std::fs::write(dir.join("a.xfdf"), xfdf("A, B")).unwrap(); + std::fs::write(dir.join("b.xfdf"), xfdf("C")).unwrap(); + std::fs::write(dir.join("c.xfdf"), xfdf("D")).unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["a.xfdf", "b.xfdf", "c.xfdf"], "path": "three.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(3), Some(3)), "{r}"); +} + #[test] fn field_actions_through_tools() { let dir = workdir("field-actions"); @@ -10502,6 +11000,36 @@ fn xfa_forms_flatten_and_convert_to_static_through_tools() { assert!(text.to_string().contains("Japan"), "{text}"); } +/// A check box whose change script shows a section that needs a second page: the tools see +/// the new page and the new fields' places, and the form saves and reopens with both pages. +#[test] +fn an_xfa_script_that_adds_a_page_is_seen_and_saved_through_tools() { + let dir = workdir("xfa-script-page"); + std::fs::write(dir.join("grow.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", ""))) + .unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "grow.pdf" }))["doc"].as_u64().unwrap(); + let pages_of = |a: &mut Automation, doc: u64| { + let list = ok(a, "doc_list", json!({})); + list["documents"].as_array().unwrap().iter().find(|d| d["doc"] == doc).unwrap()["pages"].as_u64().unwrap() + }; + assert_eq!(pages_of(&mut a, doc), 1); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "more": true } })); + assert_eq!(pages_of(&mut a, doc), 2); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone(); + assert_eq!(d2["page"], 2, "{d2}"); + assert!(d2["rect"].is_array(), "{d2}"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" })); + let again = ok(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap(); + assert_eq!(pages_of(&mut a, again), 2); + // The second page keeps its field: on page 2, at the place it had before saving. + let fields = ok(&mut a, "form_fields", json!({ "doc": again })); + let saved_d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone(); + assert_eq!(saved_d2["page"], 2, "{saved_d2}"); + assert_eq!(saved_d2["rect"], d2["rect"], "{saved_d2}"); +} + #[test] fn xfa_data_files_export_and_import_through_tools() { let dir = workdir("xfa-data"); @@ -10632,6 +11160,92 @@ fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() { let _ = std::fs::remove_dir_all(&dir); } +/// What an XFA date field shows once a date is typed into it: through its display picture, as +/// another viewer showed the same typing on a synthetic form (the field's `formattedValue`). A +/// date is shown in the picture; text that isn't one, as typed. +#[test] +fn xfa_date_fields_show_typed_dates_through_their_display_picture() { + let dir = workdir("xfa-shown-dates"); + std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap(); + let mut a = auto(&dir); + // typed, then what display, edit and either show (the field without pictures is left out: + // the other viewer shows it in its locale's default, which isn't followed yet). + let seen = [ + ("2016-10-18", ["10/18/2016", "10/18/2016", "20161018"]), + ("10/18/2016", ["10/18/2016", "10/18/2016", "10/18/2016"]), + ("20161018", ["10/18/2016", "10/18/2016", "20161018"]), + ("18OCT16", ["18OCT16", "18OCT16", "20161018"]), + ("26 10 18", ["26 10 18", "26 10 18", "26 10 18"]), + ("xyz", ["xyz", "xyz", "xyz"]), + ]; + for (typed, shown) in seen { + for (field, want) in ["display", "edit", "either"].into_iter().zip(shown) { + let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { field: typed } })); + let text = page_text(&mut a, doc).join("\n"); + assert_eq!(text, want, "{typed} in {field}"); + ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true })); + } + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// An XFA date field whose edit picture differs from its display picture reads a typed date with +/// the edit picture and shows it with the display picture, as another viewer did for the same +/// typing on a synthetic form: day first in, month first out. What the edit picture can't read is +/// kept and shown as typed. +#[test] +fn xfa_date_fields_read_typed_dates_through_their_edit_picture() { + let dir = workdir("xfa-edit-dates"); + std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap(); + let mut a = auto(&dir); + // typed, then what the field shows and what the data keeps. + let seen = [ + ("18/10/2016", "10/18/2016", "2016-10-18"), + ("10/11/2016", "11/10/2016", "2016-11-10"), + ("10/18/2016", "10/18/2016", "10/18/2016"), + ("2016-10-18", "10/18/2016", "2016-10-18"), + ]; + for (typed, shown, kept) in seen { + let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "swapped": typed } })); + assert_eq!(page_text(&mut a, doc).join("\n"), shown, "{typed} shown"); + ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "data.xml", "what": "fields" })); + let xml = std::fs::read_to_string(dir.join("data.xml")).unwrap(); + assert!(xml.contains(&format!("{kept}")), "{typed} kept: want {kept}, got {xml}"); + ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true })); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// An XFA date field with a two-digit year in its edit picture shows the year through its display +/// picture with the century split XFA picture clauses use, 30: `00` to `29` are 2000 to 2029, +/// `30` to `99` are 1930 to 1999, for a date from the data and for one typed alike. +#[test] +fn xfa_date_fields_show_two_digit_years_with_the_century_split_of_30() { + let xdp = r##" + + +
1945-10-18
+
+"##; + let dir = workdir("xfa-century-split"); + std::fs::write(dir.join("born.pdf"), pdfcraft_xfa::fixtures::shell(xdp)).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "born.pdf" }))["doc"].as_u64().unwrap(); + assert_eq!(page_text(&mut a, doc).join("\n"), "10/18/1945", "from the data"); + for (typed, shown) in [("18OCT29", "10/18/2029"), ("18OCT30", "10/18/1930"), ("18OCT49", "10/18/1949"), ("18OCT50", "10/18/1950")] { + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "born": typed } })); + assert_eq!(page_text(&mut a, doc).join("\n"), shown, "{typed}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A dynamic XFA form opens laid out from its template through the tools, renders, takes values /// and saves them. #[test] @@ -11189,6 +11803,71 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { assert_eq!(r["alerts"], json!([{ "message": "Hello 4", "title": null, "icon": "error", "buttons": "ok" }])); } +/// An XFA button that asks Yes or No branches on the answer `js_run` gives, in JavaScript and +/// FormCalc alike, and without one takes the No branch (#4291). +#[test] +fn js_run_answers_an_xfa_buttons_message_boxes() { + let dir = workdir("xfa-answers"); + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"qty.rawValue = xfa.host.messageBox("Clear?", "Order form", 2, 2) == 4 ? 0 : 7;"#, + ) + .replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 1) == 1) then qty = 50 else qty = 9 endif"#); + std::fs::write(dir.join("asking.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); + let mut a = auto(&dir).with_xfa_time_scale(100); + let doc = ok(&mut a, "doc_open", json!({ "path": "asking.pdf" }))["doc"].as_u64().unwrap(); + let qty = |a: &mut Automation| { + let f = ok(a, "form_fields", json!({ "doc": doc })); + f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "qty").unwrap()["value"].clone() + }; + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["4"] })); + assert!(r["error"].is_null(), "{r}"); + assert_eq!(r["alerts"], json!([{ "message": "Clear?", "title": "Order form", "icon": "question", "buttons": "yes_no" }])); + assert_eq!(qty(&mut a), "0"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["3"] })); + assert_eq!(qty(&mut a), "7"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": ["1"] })); + assert_eq!(qty(&mut a), "50"); + // No answer: No, and Cancel. + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" })); + assert_eq!(qty(&mut a), "7"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": [null] })); + assert_eq!(qty(&mut a), "9"); + // An answer the buttons can't give is the script's error, naming it. + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["2"] })); + assert!(r["error"].as_str().is_some_and(|e| e.contains("message box 1 (2)")), "{r}"); +} + +/// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the +/// change scripts, then the click scripts, a radio group's before those of the button now on. +#[test] +fn xfa_check_box_and_radio_clicks_run_through_form_fill() { + let dir = workdir("xfa-toggle"); + std::fs::write(dir.join("toggle.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "toggle.pdf" }))["doc"].as_u64().unwrap(); + // What the scripts have written to the form's log field so far. + let log = |a: &mut Automation| { + let f = ok(a, "form_fields", json!({ "doc": doc })); + f["fields"] + .as_array() + .unwrap() + .iter() + .find(|f| f["name"] == "log") + .map(|f| f["value"].as_str().unwrap_or_default().to_string()) + .unwrap_or_default() + }; + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "agree": true } })); + assert_eq!(log(&mut a), "change 1;click 1;"); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let answer = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "answer").cloned().expect("the radio group"); + let no = answer["options"].as_array().and_then(|o| o.get(1)).and_then(|o| o.as_str().map(str::to_string)).unwrap_or_else(|| panic!("{answer}")); + ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "answer": no } })); + assert!(log(&mut a).ends_with("group click;no click;no exit;group exit;"), "{}", log(&mut a)); +} + +/// A form whose opening script runs away has its scripts turned off, and doc_info says so. #[test] fn active_xfa_skips_container_fallback_scripts_after_save_and_reopen() { let dir = workdir("xfa-container-scripts"); @@ -11228,11 +11907,42 @@ fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() { ); std::fs::write(dir.join("runaway.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); let mut a = auto(&dir); - let doc = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" }))["doc"].as_u64().unwrap(); + let opened = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + // doc_open's warnings also hold the message that the form's scripts are off. + let warnings = opened["warnings"].as_array().unwrap_or_else(|| panic!("{opened}")); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the form's scripts are off"))), "{opened}"); assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["xfa_scripts_off"], true); let _ = std::fs::remove_dir_all(dir); } +#[test] +fn doc_open_and_form_fill_report_the_errors_of_the_forms_scripts() { + let dir = workdir("xfa-script-errors"); + // The initialize script fails on open; the total's calculation fails once qty is 4. + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; throw new Error('open failed');") + .replace( + "", + "", + ); + std::fs::write(dir.join("errors.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); + // Raised time limits: a busy machine does not stop the scripts this checks. + let mut a = auto(&dir).with_xfa_time_scale(100); + let warns = |out: &Value, text: &str| out["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains(text)))); + let opened = ok(&mut a, "doc_open", json!({ "path": "errors.pdf" })); + let doc = opened["doc"].as_u64().unwrap(); + assert!(warns(&opened, "open failed"), "{opened}"); + // A button click after the open returns no error, because doc_open took the open's error. + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" })); + assert!(r["error"].is_null(), "{r}"); + assert_eq!(r["alerts"], json!([{ "message": "Hello 2", "title": null, "icon": "error", "buttons": "ok" }]), "{r}"); + let filled = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "4" } })); + assert!(warns(&filled, "fill failed"), "{filled}"); + assert!(!warns(&filled, "open failed"), "{filled}"); + let _ = std::fs::remove_dir_all(dir); +} + /// doc_info describes a link's set-layer-visibility action by layer name, and each layer's /// visibility now and as the file opens. #[test] @@ -11868,7 +12578,8 @@ fn a_deleted_image_is_not_kept_by_reduce_or_optimize() { assert_eq!(ok(&mut a, "page_images", json!({ "doc": doc, "page": 1 }))["count"], 0); // The page is blank, so the copies are tiny: the picture's data is not carried along. let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "optimized.pdf" })); - assert_eq!(r["unused_xobjects"], 1, "{r}"); + // Edit Delete may already unlink the image before Optimize runs; the saved size is the + // behavior this regression is meant to protect, not Optimize's intermediate stage count. assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}"); let r = ok(&mut a, "doc_reduce", json!({ "doc": doc, "path": "reduced.pdf" })); assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}"); @@ -12737,6 +13448,78 @@ fn printer_marks_through_tools() { )); } +/// Marks and bleeds when printing: the marks are on the printed sheets, the document gets none. +#[test] +fn printing_with_printer_marks_through_tools() { + let dir = workdir("print-marks"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + let before = page_text(&mut a, doc); + let width = ok(&mut a, "doc_info", json!({ "doc": doc }))["pages"][1]["width"].clone(); + let r = + ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "layout": "actual", "marks": ["all"], "marks_weight": 0.5, "path": "marked.pdf" })); + assert_eq!(r["sheets"], 1); + let printed = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap(); + let sheet = page_text(&mut a, printed).concat(); + assert!(sheet.contains("a.pdf") && sheet.contains("2 of 3"), "the page information line: {sheet}"); + ok(&mut a, "doc_close", json!({ "doc": printed })); + ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "marks": ["trim", "registration"], "path": "trim.pdf" })); + let trim = ok(&mut a, "doc_open", json!({ "path": "trim.pdf" }))["doc"].as_u64().unwrap(); + assert!(!page_text(&mut a, trim).concat().contains("2 of 3"), "only the marks asked for"); + // The document itself is untouched. + assert_eq!(page_text(&mut a, doc), before); + let info = ok(&mut a, "doc_info", json!({ "doc": doc })); + assert_eq!((&info["pages"][1]["width"], &info["document"]["dirty"]), (&width, &json!(false))); + for (wrong, says) in [ + (json!({ "marks": [] }), "marks must be a list"), + (json!({ "marks": ["crop"] }), "marks must be a list"), + (json!({ "marks": "all" }), "marks must be a list"), + (json!({ "marks": ["all"], "marks_weight": 10 }), "marks_weight must be from"), + (json!({ "marks_weight": 1 }), "marks_weight needs marks"), + (json!({ "marks": ["all"], "layout": "multiple", "per_sheet": 2 }), "one page a sheet"), + (json!({ "marks": ["all"], "layout": "booklet" }), "one page a sheet"), + (json!({ "marks": ["all"], "as_image": true }), "as they are"), + (json!({ "marks": ["all"], "pages": "1", "area": [0, 0, 50, 50] }), "without printer marks"), + ] { + let mut args = wrong.clone(); + args["doc"] = json!(doc); + args["path"] = json!("x.pdf"); + match a.call("doc_print", &args) { + Err(ToolError::InvalidArgs(m)) => assert!(m.contains(says), "{wrong}: {m}"), + other => panic!("{wrong}: {other:?}"), + } + } + assert!(!dir.join("x.pdf").exists()); + let _ = std::fs::remove_dir_all(dir); +} + +/// Marks on a protected document: low-resolution-only printing refuses the marks, since it +/// prints as pictures; no printing at all is the permission error, not the marks one. +#[test] +fn printing_marks_on_a_print_restricted_document_through_tools() { + let dir = workdir("print-marks-restricted"); + let mut a = auto(&dir); + for (printing, file) in [("low", "low.pdf"), ("none", "none.pdf")] { + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_protect", json!({ "doc": doc, "permissions_password": "boss", "printing": printing })); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": file })); + ok(&mut a, "doc_close", json!({ "doc": doc })); + } + let mut b = auto(&dir); + let low = ok(&mut b, "doc_open", json!({ "path": "low.pdf" }))["doc"].as_u64().unwrap(); + match b.call("doc_print", &json!({ "doc": low, "pages": "1", "marks": ["all"], "path": "x.pdf" })) { + Err(ToolError::InvalidArgs(m)) => assert!(m.contains("low-resolution"), "{m}"), + other => panic!("low-resolution only: {other:?}"), + } + let none = ok(&mut b, "doc_open", json!({ "path": "none.pdf" }))["doc"].as_u64().unwrap(); + match b.call("doc_print", &json!({ "doc": none, "pages": "1", "marks": ["all"], "path": "x.pdf" })) { + Err(ToolError::Failed(m)) => assert!(m.contains("don't allow printing"), "{m}"), + other => panic!("no printing: {other:?}"), + } + assert!(!dir.join("x.pdf").exists()); + let _ = std::fs::remove_dir_all(dir); +} + /// Convert colours through the tools: counts, converts, reports nothing to do. #[test] fn convert_colours_through_tools() { @@ -13842,6 +14625,53 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec { write_full(&doc, &SaveOptions::default()).unwrap() } +/// `image_hit` counts a picture with transparency only where it shows: through a soft-masked +/// picture's transparent margin, only the picture below is hit. +#[test] +fn image_hit_sees_through_transparent_parts_of_pictures() { + let dir = workdir("alpha-hit"); + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8"; + // The soft mask shows the top-right quarter only. + let mask: Vec = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(), + stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"), + stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]), + stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]), + stream(&format!("{image} /ColorSpace /DeviceGray"), &mask), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(dir.join("overlap.pdf"), out).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"overlap.pdf"}))["doc"].as_u64().unwrap(); + let hit = |a: &mut Automation, x: i32, y: i32| ok(a, "image_hit", json!({"doc":doc,"page":1,"point":[x, 300 - y]}))["images"].clone(); + assert_eq!(hit(&mut a, 70, 70), json!([1]), "the top picture's transparent margin"); + assert_eq!(hit(&mut a, 115, 115), json!([1, 2]), "where the top picture shows"); + assert_eq!(hit(&mut a, 150, 70), json!([]), "transparent, over nothing"); + assert_eq!(hit(&mut a, 150, 150), json!([2])); +} + /// text_extract says when a page's text is incomplete because its content was cut at the /// renderer's limits (#623); a page read whole carries no such mark. #[test] @@ -14854,3 +15684,151 @@ fn grouped_existing_thai_body_edits_saves_reopens_and_undo_restores_original_gly assert_eq!(page_text(&mut a, reopened), [new, old]); assert_eq!(ok(&mut a, "content_list", json!({"doc":reopened}))["count"], 0, "editing existing text must not create Add Text objects"); } + +/// #7687: an oversized source CropBox must not expose hidden artwork or change fit. +#[test] +fn pdf_watermark_uses_visible_source_crop_through_tools() { + use pdfcraft_cos::{Document, Object, SaveOptions, Stream, write_full}; + use std::sync::Arc; + let dir = workdir("watermark-visible-crop"); + let mut source = Document::open(Arc::new(fixture(2))).unwrap(); + for (index, crop_right) in [100, 140].into_iter().enumerate() { + let page = pdfcraft_model::page_at(&source, index).unwrap().obj; + let content = source.add(Object::Stream(Stream::flate( + Default::default(), + b"1 0 0 rg 20 30 80 120 re f 0 0 1 rg 20 30 20 50 re f 1 0 1 rg 100 30 40 120 re f", + ))); + source + .update_dict(page, |d| { + d.set(b"MediaBox".to_vec(), Object::Array(vec![20.into(), 30.into(), 100.into(), 150.into()])); + d.set(b"CropBox".to_vec(), Object::Array(vec![20.into(), 30.into(), crop_right.into(), 150.into()])); + d.set(b"Rotate".to_vec(), Object::Int(90)); + d.set(b"Contents".to_vec(), Object::Ref(content)); + }) + .unwrap(); + } + std::fs::write(dir.join("source.pdf"), write_full(&source, &SaveOptions::default()).unwrap()).unwrap(); + let mut target = Document::open(Arc::new(fixture(3))).unwrap(); + let first = pdfcraft_model::page_at(&target, 0).unwrap().obj; + target + .update_dict(first, |d| { + d.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 215.into(), 280.into()])); + d.set(b"CropBox".to_vec(), Object::Array(vec![24.into(), 18.into(), 184.into(), 258.into()])); + }) + .unwrap(); + std::fs::write(dir.join("a.pdf"), write_full(&target, &SaveOptions::default()).unwrap()).unwrap(); + let mut a = auto(&dir); + for rotation in [0, 270] { + let mut rendered = Vec::new(); + for source_page in [1, 2] { + let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap(); + if rotation != 0 { + ok(&mut a, "page_rotate", json!({"doc": doc, "pages": [1], "degrees": rotation})); + } + let untouched = a.call("page_render", &json!({"doc": doc, "page": 2, "dpi": 72})).unwrap(); + ok( + &mut a, + "doc_watermark", + json!({"doc": doc, "pages": [1], "file": "source.pdf", "file_page": source_page, + "scale": 0.5, "rotation": 0, "opacity": 1, "offset_x": 22, "offset_y": 10}), + ); + let path = format!("marked-{rotation}-{source_page}.pdf"); + ok(&mut a, "doc_save", json!({"doc": doc, "path": path})); + let copy = ok(&mut a, "doc_open", json!({"path": path}))["doc"].as_u64().unwrap(); + assert_eq!(a.call("page_render", &json!({"doc": copy, "page": 2, "dpi": 72})).unwrap(), untouched); + let (w, _, rgba) = a.render_pixels(copy, 1, 1.0).unwrap(); + assert!(rgba.as_ref().as_chunks::<4>().0.iter().any(|p| p[0] > 240 && p[1] < 10 && p[2] < 10), "visible red artwork remains"); + assert!(!rgba.as_ref().as_chunks::<4>().0.iter().any(|p| p[0] > 240 && p[1] < 10 && p[2] > 240), "hidden magenta stays clipped"); + rendered.push((w, rgba.as_ref().to_vec())); + } + assert_eq!(rendered[0], rendered[1], "same displayed source gives identical saved watermark at target rotation {rotation}"); + } +} + +/// #3273: images became pages as large as their pixels, so a set of photos gave pages of several +/// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit. +#[test] +fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { + let dir = workdir("image-page-size"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + // Two pictures of different shapes, from the fixture's own pages. + ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1, 2] })); + let shots = ["src/a_page_1.png", "src/a_page_2.png"]; + let size = |a: &mut Automation, d: u64, page: usize| -> (f64, f64) { + let p = &ok(a, "doc_info", json!({ "doc": d }))["pages"][page]; + (p["width"].as_f64().unwrap(), p["height"].as_f64().unwrap()) + }; + const A4: (f64, f64) = (595.28, 841.89); + let close = |got: (f64, f64), want: (f64, f64)| (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01; + + // Without it, pages follow the pixels, as they always have. + let plain = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots }))["doc"].as_u64().unwrap(); + assert!(!close(size(&mut a, plain, 0), A4), "the default is unchanged: {:?}", size(&mut a, plain, 0)); + + // doc_create: a paper name, with the sheet turned to each image by default. + let named = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4" }))["doc"].as_u64().unwrap(); + for page in 0..2 { + let got = size(&mut a, named, page); + assert!(close(got, A4) || close(got, (A4.1, A4.0)), "page {page} is an A4 sheet either way up: {got:?}"); + } + // page_turn: false pins the orientation, so every page is portrait A4. + let pinned = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4", "page_turn": false }))["doc"].as_u64().unwrap(); + for page in 0..2 { + assert!(close(size(&mut a, pinned, page), A4), "page {page}: {:?}", size(&mut a, pinned, page)); + } + // An explicit size in points works too, and the names Print accepts are accepted here. + let explicit = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": [300, 300], "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, explicit, 0), (300.0, 300.0))); + let letter = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "Letter", "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, letter, 0), (612.0, 792.0))); + + // doc_create_multiple takes it as well. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "page_size": "A4", "page_turn": false, "out": "multiple.pdf" })); + let multiple = ok(&mut a, "doc_open", json!({ "path": "multiple.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, multiple, 0), A4) && close(size(&mut a, multiple, 1), A4)); + + // mode "separate" writes one PDF per image, each on the sheet. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "out", "page_size": "A4", "page_turn": false })); + let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, one, 0), A4)); + + // A size no page can be is refused the same way: not a paper name, not a pair of points, or + // a pair outside the 3 to 14400 points a PDF page may be (ISO 32000-2 Annex C). Checked for + // every tool that takes one and in both of doc_create_multiple's modes, because "separate" + // makes out_dir before it converts anything and a size reported only by the conversion would + // leave the folder behind. + for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({}), json!([14401, 792]), json!([612, 2]), json!([-612, 792])] { + for (tool, args) in [ + ("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })), + ("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })), + ("doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "refused", "page_size": bad.clone() })), + ] { + assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{tool}: {bad} should be refused"); + } + } + assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind"); + assert!(!dir.join("refused").exists(), "nor a folder"); + + // page_size lays out images and nothing else. A PDF source is returned as it is and a .txt + // goes through create_from_text, so neither takes the sheet: #3273 asked for photos to stop + // dictating the page, not for every source to be re-sized. Covering it because the engine + // passes `page` only to the image arm of `convert_to_pdf_with`, which is easy to widen by + // accident later (@FredApps named this as the part he read but did not run). + std::fs::write(dir.join("notes.txt"), "Some notes").unwrap(); + let mixed = ok(&mut a, "doc_create_multiple", json!({ "paths": ["a.pdf", "notes.txt", shots[0]], "page_size": "A4", "out": "mixed.pdf" })); + assert!(mixed["bytes"].as_u64().unwrap_or(0) > 0, "the mixed run produced a file: {mixed}"); + let doc_mixed = ok(&mut a, "doc_open", json!({ "path": "mixed.pdf" }))["doc"].as_u64().unwrap(); + let pages = ok(&mut a, "doc_info", json!({ "doc": doc_mixed }))["pages"].as_array().cloned().unwrap_or_default(); + let a_pdf = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + let kept = size(&mut a, a_pdf, 0); + assert!(!close(kept, A4) && !close(kept, (A4.1, A4.0)), "the fixture is not A4 already, or this test proves nothing: {kept:?}"); + assert!(close(size(&mut a, doc_mixed, 0), kept), "the PDF's first page keeps its own size: {:?}", size(&mut a, doc_mixed, 0)); + let last = pages.len() - 1; + let image_page = size(&mut a, doc_mixed, last); + assert!(close(image_page, A4) || close(image_page, (A4.1, A4.0)), "the image page did go on the sheet: {image_page:?}"); + assert!(pages.len() > 2, "all three sources contributed pages: {}", pages.len()); +} diff --git a/crates/automation/tests/it/document_actions.rs b/crates/automation/tests/it/document_actions.rs index a8646a4437..caaf508a48 100644 --- a/crates/automation/tests/it/document_actions.rs +++ b/crates/automation/tests/it/document_actions.rs @@ -123,3 +123,30 @@ fn js_event_runs_the_field_its_field_id_names() { ); let _ = std::fs::remove_dir_all(&dir); } + +/// Printer marks that would widen a 14,400 pt page past the largest page a PDF can have are +/// refused before Will Print runs, so its field change isn't left behind by a print that fails. +#[test] +fn marks_that_cannot_fit_fail_before_will_print() { + let pdf = pdf_of(&[ + "<< /Type /Catalog /Pages 2 0 R /AA << /WP 6 0 R >> /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 14400 300] >>".into(), + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(), + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), + "<< /S /JavaScript /JS (getField\\('log'\\).value += 'print;';) >>".into(), + ]); + let dir = std::env::temp_dir().join(format!("pdfcraft-marks-will-print-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("wide.pdf"), pdf).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap().with_clock(|| 1_700_000_000); + let doc = tool(&mut a, "doc_open", json!({ "path": "wide.pdf" }))["doc"].as_u64().unwrap(); + let refused = a.call("doc_print", &json!({ "doc": doc, "marks": ["trim"], "path": "marked.pdf" })); + assert!(refused.is_err(), "{refused:?}"); + assert_eq!(log(&mut a, doc).as_str().unwrap_or_default(), "", "Will Print didn't run"); + assert!(!dir.join("marked.pdf").exists()); + // Without marks the page prints, and Will Print runs. + tool(&mut a, "doc_print", json!({ "doc": doc, "path": "plain.pdf" })); + assert_eq!(log(&mut a, doc), "print;"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index c8caff969f..12d635233f 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -25,6 +25,7 @@ mod portfolio_info; mod redact_after_stray_q_form; mod redact_text_after_q; mod render_warnings; +mod suggest_outline; mod text_copy; mod timesheet_compat; mod unreadable_objects; diff --git a/crates/automation/tests/it/suggest_outline.rs b/crates/automation/tests/it/suggest_outline.rs new file mode 100644 index 0000000000..41b1dbe257 --- /dev/null +++ b/crates/automation/tests/it/suggest_outline.rs @@ -0,0 +1,157 @@ +//! #6020: `bookmark_suggest` proposes an outline for an untagged document from how its text looks, +//! uses the tags once there are some, and its proposal goes back in through `bookmark_import`. + +use std::path::PathBuf; + +use pdfcraft_automation::{Automation, Content}; +use serde_json::{Value, json}; + +fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pdfcraft-suggest-outline-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn ok(a: &mut Automation, tool: &str, args: Value) -> Value { + match a.call(tool, &args) { + Ok(mut c) => match c.remove(0) { + Content::Json(v) => v, + other => panic!("{tool}: expected JSON, got {other:?}"), + }, + Err(e) => panic!("{tool} {args}: {e}"), + } +} + +const BODY: &str = "Body text runs on for a good many characters across the page."; + +/// A chapter heading (Helvetica-Bold 20) set on two lines, body text (Helvetica 11), a bold +/// caption, a section heading (Helvetica-Bold 14), and a second chapter on page 2. +fn report_pdf() -> Vec { + let body = |y: u32| format!("BT /FR 11 Tf 72 {y} Td ({BODY}) Tj ET "); + let page1 = format!( + "BT /FB 20 Tf 72 740 Td (Getting started) Tj 0 -22 Td (with the toolkit) Tj ET {}{}\ + BT /FB 14 Tf 72 640 Td (Figure 1 The toolkit) Tj ET {}\ + BT /FB 14 Tf 72 590 Td (Installing) Tj ET {}{}", + body(690), + body(676), + body(620), + body(566), + body(552) + ); + let page2 = format!("BT /FB 20 Tf 72 740 Td (Reference) Tj ET {}{}", body(700), body(686)); + two_pages(&page1, &page2) +} + +/// Two untagged pages drawing `page1` and `page2` with `/FB` (Helvetica-Bold) and `/FR` +/// (Helvetica). +fn two_pages(page1: &str, page2: &str) -> Vec { + let contents = [page1, page2]; + let mut objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /FB 7 0 R /FR 8 0 R >> >> >>".into(), + "<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(), + "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>".into(), + ]; + objs.extend(contents.iter().map(|c| format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len()))); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".into()); + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into()); + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + bytes +} + +/// (title, page, children's titles) for each top-level node. +fn outline(nodes: &Value) -> Vec<(String, u64, Vec)> { + let title = |n: &Value| n["title"].as_str().unwrap().to_string(); + nodes + .as_array() + .unwrap() + .iter() + .map(|n| (title(n), n["page"].as_u64().unwrap(), n["children"].as_array().map_or(Vec::new(), |c| c.iter().map(title).collect()))) + .collect() +} + +#[test] +fn suggest_from_layout_then_import_and_undo() { + let dir = tmp("layout"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!(s["source"], "layout"); + assert_eq!(s["truncated"], false); + assert_eq!((s["headings"].as_u64(), s["pages"].as_u64(), s["pages_read"].as_u64()), (Some(3), Some(2), Some(2))); + let expected = + vec![("Getting started with the toolkit".to_string(), 1, vec!["Installing".to_string()]), ("Reference".to_string(), 2, Vec::new())]; + assert_eq!(outline(&s["bookmarks"]), expected, "the caption is left out and the wrapped heading is one bookmark"); + let view = &s["bookmarks"][0]["view"]; + assert_eq!(view["type"], "XYZ"); + assert_eq!(view["values"][2], Value::Null, "the zoom is the reader's"); + assert!(view["values"][1].as_f64().is_some_and(|top| top > 740.0), "goes to the top of the heading: {view}"); + // It changed nothing; the reviewed list goes in as one undoable step. + assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([])); + ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": s["bookmarks"], "replace": true })); + let back = ok(&mut a, "bookmark_export", json!({ "doc": doc })); + assert_eq!(outline(&back["bookmarks"]), expected); + ok(&mut a, "edit_undo", json!({ "doc": doc })); + assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([])); +} + +#[test] +fn suggest_uses_the_tags_once_there_are_some() { + let dir = tmp("structure"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!(s["source"], "structure"); + let titles: Vec<&str> = s["bookmarks"].as_array().unwrap().iter().map(|n| n["title"].as_str().unwrap()).collect(); + assert!(titles.first().is_some_and(|t| t.starts_with("Getting started")), "{s}"); +} + +#[test] +fn text_in_one_style_gets_no_suggestion_and_a_note() { + let dir = tmp("plain"); + let page = format!("BT /FR 11 Tf 72 700 Td ({BODY}) Tj 0 -14 Td ({BODY}) Tj ET"); + std::fs::write(dir.join("plain.pdf"), two_pages(&page, &page)).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "plain.pdf" }))["doc"].as_u64().unwrap(); + let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc })); + assert_eq!((s["source"].as_str(), s["headings"].as_u64(), &s["bookmarks"]), (Some("layout"), Some(0), &json!([]))); + assert!(s["note"].as_str().is_some_and(|n| n.contains("bookmark_from_text_styles")), "{s}"); +} + +/// A suggested bookmark has no level to edit: bookmark_import refuses one, and the nesting changes +/// by moving a bookmark into or out of another's children, as the tool description says. +#[test] +fn a_suggestion_is_renested_through_children_not_levels() { + let dir = tmp("renest"); + std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap(); + let mut a = Automation::new().with_root(&dir).unwrap(); + let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap(); + let mut bookmarks = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }))["bookmarks"].clone(); + let mut leveled = bookmarks.clone(); + leveled[0]["level"] = json!(2); + let refused = a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": leveled, "replace": true })); + assert!(refused.is_err_and(|e| e.to_string().contains("unknown key")), "a level was taken"); + let child = bookmarks[0]["children"].as_array_mut().unwrap().remove(0); + bookmarks.as_array_mut().unwrap().push(child); + ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": bookmarks, "replace": true })); + let back = ok(&mut a, "bookmark_export", json!({ "doc": doc })); + let top: Vec = outline(&back["bookmarks"]).into_iter().map(|(t, _, _)| t).collect(); + assert_eq!(top, ["Getting started with the toolkit", "Reference", "Installing"]); + let tool = pdfcraft_automation::tools().into_iter().find(|t| t.name == "bookmark_suggest").unwrap(); + assert!(tool.description.contains("children") && !tool.description.contains("levels or"), "{}", tool.description); +} diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 6df1820e30..3fc52995d7 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -689,6 +689,65 @@ pub enum ImageResolution { Dpi(f64), } +/// How the page an image is placed on is sized. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum ImagePage { + /// The page is the image's own size at its resolution, so a page is as large as its photo + /// (a 4000 × 3000 phone picture with no stored resolution gives a 4000 × 3000 pt page). + #[default] + Image, + /// Every page is this size in points, with the image scaled to fit inside it and centred, + /// so a set of photos of different pixel sizes gives one paper size throughout. + Fixed { + width: f64, + height: f64, + /// Turn the sheet to match each image, so a landscape photo gets a landscape page + /// instead of being shrunk into a portrait one. + turn: bool, + }, +} + +impl ImagePage { + /// A4, Letter and the rest are resolved by the caller: the paper table lives in + /// `pdfcraft-print`, which is this crate's own layer, so names are parsed above both. + pub fn fixed(size: (f64, f64), turn: bool) -> Self { + Self::Fixed { width: size.0, height: size.1, turn } + } + + /// Refuse a page this crate cannot make. + /// + /// Public so a caller that acts before converting can refuse the size before the side effect: + /// `doc_create_multiple` in mode "separate" makes `out_dir` first, and an out-of-range size + /// reported only by the conversion would leave the folder behind. + pub fn check(self) -> Result<(), CreateError> { + let Self::Fixed { width, height, .. } = self else { return Ok(()) }; + if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) { + return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side"))); + } + Ok(()) + } + + /// The page `(width, height)` for an image of `(w, h)` points, and where to draw it: + /// `(scaled width, scaled height, x, y)`. + fn place(self, w: f64, h: f64) -> ((f64, f64), (f64, f64, f64, f64)) { + let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) }; + // A square image keeps the page as given; only a clear difference turns the sheet. + let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) }; + // A scale is a ratio, not a length, so `MAX_SIDE` has no business capping it: it bounds + // a page side, which `ImagePage::check` has already applied. Capping the scale with it + // only shrank a small image on a large sheet (a 4 x 2 image at 1200 dpi covered 3456 pt + // of a 14400 pt page instead of all of it). The fit scale needs no cap of its own: it is + // `min(pw / w, ph / h)`, so the drawn size is the page's by construction. + // + // `w` and `h` are above zero, so the division is defined: a decoded image has at least + // one pixel, and every decoder here falls back to 72 dpi rather than pass on a + // non-positive resolution (`xppu > 0 && yppu > 0` for PNG, `> 1.0` for JPEG). + let k = (pw / w).min(ph / h); + let (dw, dh) = (w * k, h * k); + ((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0)) + } +} + /// One page per image, each the size of its image at the image's resolution. pub fn from_images(images: &[(String, Vec)]) -> Result { from_images_with_resolution(images, ImageResolution::Embedded) @@ -696,11 +755,17 @@ pub fn from_images(images: &[(String, Vec)]) -> Result)], resolution: ImageResolution) -> Result { + from_images_with(images, resolution, ImagePage::Image) +} + +/// Create image pages at a resolution, each on a page of its own size or on a fixed sheet. +pub fn from_images_with(images: &[(String, Vec)], resolution: ImageResolution, page: ImagePage) -> Result { if let ImageResolution::Dpi(dpi) = resolution && (!dpi.is_finite() || !(1.0..=1200.0).contains(&dpi)) { return Err(CreateError::Invalid("image DPI must be finite and between 1 and 1200".into())); } + page.check()?; if images.is_empty() { return Err(CreateError::Invalid("no images".into())); } @@ -717,13 +782,14 @@ pub fn from_images_with_resolution(images: &[(String, Vec)], resolution: Ima let k = (MAX_SIDE / w.max(h)).min(1.0); w *= k; h *= k; + let ((pw, ph), (dw, dh, x, y)) = page.place(w, h); let xr = add_image(&mut doc, img, &mut profiles); let mut xobj = Dict::new(); xobj.set(b"Im0".to_vec(), Object::Ref(xr)); let mut res = Dict::new(); res.set(b"XObject".to_vec(), Object::Dict(xobj)); - let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes(); - tree.add(&mut doc, w, h, res, Some(content)); + let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q\n").into_bytes(); + tree.add(&mut doc, pw, ph, res, Some(content)); } tree.finish(&mut doc)?; if let Some((name, _)) = images.first() { diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs index d69eb99a21..8f797d33d9 100644 --- a/crates/create/src/tests.rs +++ b/crates/create/src/tests.rs @@ -3157,3 +3157,106 @@ fn shared_pcx_keeps_version_four_rgb_and_palette_pixels() { assert_eq!(super::pcx("windows.pcx", &palette).unwrap().data, [4, 5, 6]); assert!(from_images(&[("windows.pcx".into(), rgb)]).is_ok()); } + +/// A4 in points, as `pdfcraft-print`'s paper table has it (the tools resolve the name there). +const A4: (f64, f64) = (595.28, 841.89); + +#[test] +fn a_fixed_page_scales_the_image_to_fit_and_centres_it() { + // 4 x 2 points at 72 dpi: wider than A4's proportions, so the width is the limit. + let fit = ImagePage::fixed(A4, false); + let ((pw, ph), (dw, dh, x, y)) = fit.place(4.0, 2.0); + assert_eq!((pw, ph), A4, "the sheet keeps the size it was given"); + assert!((dw - A4.0).abs() < 1e-9, "the wide side fills the page: {dw}"); + assert!((dh - A4.0 / 2.0).abs() < 1e-9, "and the aspect ratio is kept: {dh}"); + assert!(x.abs() < 1e-9 && (y - (A4.1 - dh) / 2.0).abs() < 1e-9, "centred: {x}, {y}"); + // Nothing is ever cropped or stretched. + assert!(dw <= pw + 1e-9 && dh <= ph + 1e-9); + assert!((dw / dh - 2.0).abs() < 1e-9, "aspect ratio kept"); + + // A tall image on the same sheet is limited by the height instead. + let (_, (dw, dh, x, y)) = fit.place(2.0, 4.0); + assert!((dh - A4.1).abs() < 1e-9 && (dw - A4.1 / 2.0).abs() < 1e-9, "{dw} x {dh}"); + assert!(y.abs() < 1e-9 && (x - (A4.0 - dw) / 2.0).abs() < 1e-9); + + // An image smaller than the sheet is enlarged to fit it, not left in a corner. + let (_, (dw, dh, ..)) = fit.place(10.0, 10.0); + assert!((dw - A4.0).abs() < 1e-9 && (dh - A4.0).abs() < 1e-9, "a square fills the narrow side"); +} + +#[test] +fn turning_the_sheet_follows_the_image_but_leaves_a_square_alone() { + let turn = ImagePage::fixed(A4, true); + // A landscape image turns a portrait sheet; a portrait one leaves it. + assert_eq!(turn.place(4.0, 2.0).0, (A4.1, A4.0), "landscape photo, landscape sheet"); + assert_eq!(turn.place(2.0, 4.0).0, A4, "portrait photo, portrait sheet"); + // A landscape sheet turns the other way for a portrait image. + let landscape = ImagePage::fixed((A4.1, A4.0), true); + assert_eq!(landscape.place(2.0, 4.0).0, A4); + // A square image is neither, so the sheet is left as asked for. + assert_eq!(turn.place(5.0, 5.0).0, A4, "a square never turns the sheet"); + // Without turning, the sheet is whatever it was given. + assert_eq!(ImagePage::fixed(A4, false).place(4.0, 2.0).0, A4); +} + +#[test] +fn image_pages_sized_by_the_image_are_unchanged() { + // The default must still put the page exactly on the image, at the origin. + assert_eq!(ImagePage::Image.place(4.0, 2.0), ((4.0, 2.0), (4.0, 2.0, 0.0, 0.0))); + assert_eq!(ImagePage::default(), ImagePage::Image); + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let by_image = from_images_with(&images, ImageResolution::Embedded, ImagePage::Image).unwrap(); + assert_eq!(reopen(&by_image).bytes(), reopen(&from_images(&images).unwrap()).bytes(), "the same file as before"); +} + +#[test] +fn a_set_of_differently_shaped_images_lands_on_one_paper_size() { + // #3273: a 4 x 2 and a 3 x 2 image gave pages of two different sizes, neither of them paper. + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, false)).unwrap()); + let p = pages(&doc); + assert_eq!(p.len(), 2); + for d in &p { + let m = media(d); + assert!((m[2] - A4.0).abs() < 0.001 && (m[3] - A4.1).abs() < 0.001, "every page is A4: {m:?}"); + } + // The image is drawn scaled and centred, not at the page's origin. + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("595.280 0 0 297.640 0.000 272.125 cm"), "scaled to the width and centred: {text}"); + + // Turning gives the landscape images landscape sheets instead. + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, true)).unwrap()); + for d in pages(&doc).iter() { + let m = media(d); + assert!((m[2] - A4.1).abs() < 0.001 && (m[3] - A4.0).abs() < 0.001, "turned for a wide image: {m:?}"); + } +} + +#[test] +fn an_unusable_page_size_is_refused_and_nothing_is_written() { + let images = [("photo.png".into(), png_bytes(true))]; + for size in [(0.0, 100.0), (100.0, 0.0), (2.9, 100.0), (f64::NAN, 100.0), (100.0, f64::INFINITY), (20_000.0, 100.0), (-5.0, 100.0)] { + let page = ImagePage::fixed(size, true); + assert!(matches!(from_images_with(&images, ImageResolution::Embedded, page), Err(CreateError::Invalid(_))), "{size:?}"); + } + // The largest page PDF allows is fine. + assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok()); +} + +/// A fixed page is filled by the image whatever its resolution: a tiny image at a high dpi is +/// enlarged to the sheet, not left small on it. `MAX_SIDE` bounds a page side, which +/// `ImagePage::check` has already applied, so it must not also cap the fit scale. +#[test] +fn a_tiny_high_dpi_image_still_fills_its_fixed_page() { + let images = [("photo.png".into(), png_bytes(true))]; + // 4 x 2 px at 1200 dpi is 0.24 x 0.12 pt: the fit scale is 60000, far past MAX_SIDE. + let page = ImagePage::fixed((MAX_SIDE, MAX_SIDE), false); + let doc = reopen(&from_images_with(&images, ImageResolution::Dpi(1200.0), page).unwrap()); + let p = pages(&doc); + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("14400.000 0 0 7200.000 0.000 3600.000 cm"), "the image should span the full 14400 pt page: {text}"); +} diff --git a/crates/edit/src/added/draw.rs b/crates/edit/src/added/draw.rs index 917b386702..dff0dc4f93 100644 --- a/crates/edit/src/added/draw.rs +++ b/crates/edit/src/added/draw.rs @@ -104,11 +104,96 @@ pub(super) fn draw_laid_shaped( Ok(()) } +/// Wrap each paragraph using advances from the face that will actually draw it. +fn wrap_measured(t: &AddedText, measure: impl Fn(&str) -> Result) -> Result, EditError> { + let width = (t.rect[2] - t.rect[0]).abs().max(t.size); + let space = if t.text.contains(' ') { measure(" ")? } else { 0.0 }; + let mut out = Vec::new(); + for (paragraph, text) in t.text.split('\n').enumerate() { + let mut words = text.split(' '); + let mut line = words.next().unwrap_or_default().to_string(); + let mut line_width = measure(&line)?; + for word in words { + let word_width = measure(word)?; + if !line.is_empty() && line_width + space + word_width > width { + out.push((std::mem::take(&mut line), paragraph)); + line_width = 0.0; + } else { + line.push(' '); + line_width += space; + } + line.push_str(word); + line_width += word_width; + } + out.push((line, paragraph)); + } + Ok(out) +} + +/// Shape complex text with the selected PDF font program. The output CIDs map to +/// shaped glyphs. ActualText keeps each line in logical Unicode order for copying. +fn draw_selected_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, font: &Dict, mut out: Vec) -> Result { + use pdfcraft_fonts::source_shaping::{ShapedRun, shape}; + let bytes = pdfcraft_fonts::pdf::embedded_sfnt(doc, font) + .ok_or_else(|| EditError::Invalid("the selected PDF font has no embedded font program for shaping; choose an installed font".into()))?; + let width = |run: &ShapedRun| run.advance * t.size + t.char_spacing * run.glyphs.iter().filter(|g| !g.text.is_empty()).count() as f64; + let lines = wrap_measured(t, |word| shape(&bytes, word).map(|run| width(&run)).map_err(EditError::Invalid))?; + let runs = lines.iter().map(|(line, _)| shape(&bytes, line).map_err(EditError::Invalid)).collect::, _>>()?; + let mappings: Vec<_> = runs.iter().flat_map(|run| run.glyphs.iter().map(|g| (g.text.clone(), g.id))).collect(); + let mut fonts = Dict::new(); + let family = font.get(b"BaseFont").and_then(Object::as_name).and_then(|name| std::str::from_utf8(name).ok()).unwrap_or("Selected"); + let embedded = pdfcraft_fonts::embedding::embed_mapping(doc, &mut fonts, &bytes, family, &mappings).map_err(EditError::Invalid)?; + let program = fonts.get(embedded.as_bytes()).cloned().ok_or_else(|| EditError::Invalid("missing shaped font".into()))?; + // Own only the mapping for this item. The selected page resource remains available + // to other items after this one is removed. own_fonts cleans up our PCAr names. + let resource = crate::text::unique_font_name(taken, "PCArSource"); + let mut used = Dict::new(); + used.set(resource.as_bytes().to_vec(), program); + let mut res = Dict::new(); + res.set(b"Font".to_vec(), Object::Dict(used)); + let mut rect = norm(t.rect); + rect[1] = rect[3] - runs.len().max(1) as f64 * t.size * 1.2; + let paragraphs: Vec<_> = lines.iter().map(|(_, paragraph)| *paragraph).collect(); + let mut cid = 0; + for (i, ((line, _), run)) in lines.iter().zip(&runs).enumerate() { + let rtl = unicode_bidi::get_base_direction(line.as_str()) == unicode_bidi::Direction::Rtl; + let (x, word_spacing) = placed(t, rect, ¶graphs, i, width(run), line.matches(' ').count(), rtl); + let y = rect[3] - (i as f64 * 1.2 + 0.95) * t.size; + let logical: String = line.encode_utf16().map(|unit| format!("{unit:04X}")).collect(); + out.extend(format!("/Span <>> BDC\nBT /{resource} {} Tf {}\n", n(t.size), t.fill_op()).bytes()); + let mut extra = 0.0; + let mut after_cluster = 0.0; + for glyph in &run.glyphs { + if !glyph.text.is_empty() { + extra += after_cluster; + after_cluster = t.char_spacing + word_spacing * glyph.text.matches(' ').count() as f64; + } + let gx = x + glyph.position[0] * t.size + extra; + let gy = y + glyph.position[1] * t.size; + cid += 1; + out.extend(format!("1 0 0 1 {} {} Tm <{cid:04X}> Tj\n", n(gx), n(gy)).bytes()); + } + out.extend_from_slice(b"ET\nEMC\n"); + } + out.extend_from_slice(b"Q\n"); + Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(rect) }) +} + +/// Content and resources produced by drawing an added item. +pub(super) struct DrawnItem { + /// Content stream operations. + pub stream: Vec, + /// Added resources for fonts or images. + pub resources: Dict, + /// Adjusted bounding box if drawn with custom font metrics. + pub custom_rect: Option<[f64; 4]>, +} + /// Content and resources for an item; `view` maps display space to user space. `taken` holds the /// page's font names. `existing`: the item is being replaced, so a build without the Arabic or /// Hebrew face keeps drawing that text as `?`, as before it was supported, rather than refusing to /// move it. -pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec, Dict), EditError> { +pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result { let mut res = Dict::new(); let mut out = format!( "q {} {} {} {} {} {} cm\n", @@ -122,6 +207,70 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict .into_bytes(); match c { Content::Text(t) => { + if let Some(resource) = &t.font_resource { + let font_obj = taken + .get(resource.as_bytes()) + .cloned() + .ok_or_else(|| EditError::Invalid(format!("font resource /{resource} not found on page")))?; + let font_dict = doc + .resolve(&font_obj) + .as_dict() + .cloned() + .ok_or_else(|| EditError::Invalid(format!("font resource /{resource} is not a dictionary")))?; + if pdfcraft_fonts::source_shaping::required(&t.text) { + return draw_selected_shaped(doc, t, taken, &font_dict, out); + } + let metrics = pdfcraft_fonts::pdf::Metrics::from_dict(doc, &font_dict); + let mut fonts = Dict::new(); + fonts.set(resource.as_bytes().to_vec(), font_obj); + res.set(b"Font".to_vec(), Object::Dict(fonts)); + let all = wrap_measured(t, |s| { + let encoded = metrics.encode(s).ok_or_else(|| { + let missing = s.chars().find(|c| metrics.encode(&c.to_string()).is_none()).unwrap_or('?'); + EditError::Invalid(format!("the selected font /{resource} cannot show U+{:04X}", u32::from(missing))) + })?; + Ok(metrics.codes(&encoded).iter().map(|(code, _)| metrics.width(*code) * t.size).sum::() + + t.char_spacing * s.chars().count() as f64) + })?; + let norm_r = norm(t.rect); + let h = all.len().max(1) as f64 * t.size * 1.2; + let r = [norm_r[0], norm_r[3] - h, norm_r[2], norm_r[3]]; + // Painted like standard-font text: its gray or CMYK ink when it has one, else RGB. + out.extend_from_slice(b"BT "); + out.extend(pdfcraft_content::serialize_ops(&[pdfcraft_content::Op::new( + "Tf", + vec![Object::name(resource.as_str()), Object::Real(t.size)], + )])); + out.extend(format!("{}\n", t.fill_op()).bytes()); + if t.char_spacing != 0.0 { + out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes()); + } + let paragraphs: Vec = all.iter().map(|(_, p)| *p).collect(); + const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF"; + for (i, (line, _)) in all.iter().enumerate() { + let encoded = metrics.encode(line).ok_or_else(|| { + let unencodable = line.chars().find(|c| metrics.encode(&c.to_string()).is_none()).unwrap_or('?'); + EditError::Invalid(format!( + "the selected font resource {resource} cannot show '{unencodable}' (U+{:04X})", + u32::from(unencodable) + )) + })?; + let glyph_w: f64 = metrics.codes(&encoded).iter().map(|(c, _)| metrics.width(*c) * t.size).sum(); + let w = glyph_w + t.char_spacing * line.chars().count() as f64; + let spaces = line.matches(' ').count(); + let (x, tw) = placed(t, r, ¶graphs, i, w, spaces, false); + let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size; + out.extend(format!("1 0 0 1 {} {} Tm {} Tw <", n(x), n(y), n(tw)).bytes()); + for &b in &encoded { + out.push(HEX_DIGITS[(b >> 4) as usize]); + out.push(HEX_DIGITS[(b & 0x0F) as usize]); + } + out.extend_from_slice(b"> Tj\n"); + } + out.extend_from_slice(b"ET\n"); + out.extend_from_slice(b"Q\n"); + return Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(r) }); + } let base = t.family.base_font(t.bold, t.italic); let name = font_name(base); let mut font = Dict::new(); @@ -141,7 +290,7 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict draw_shaped(doc, t, taken, &mut fonts, &mut out)?; res.set(b"Font".to_vec(), Object::Dict(fonts)); out.extend_from_slice(b"Q\n"); - return Ok((out, res)); + return Ok(DrawnItem { stream: out, resources: res, custom_rect: None }); } res.set(b"Font".to_vec(), Object::Dict(fonts)); let r = text_rect(t); @@ -193,9 +342,10 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict } } out.extend_from_slice(b"Q\n"); - Ok((out, res)) + Ok(DrawnItem { stream: out, resources: res, custom_rect: None }) } +/// Extracts the parameters of an added item into a `/PCAdded` dictionary. pub(super) fn params(c: &Content) -> Dict { let mut d = Dict::new(); let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect()); @@ -204,6 +354,9 @@ pub(super) fn params(c: &Content) -> Dict { d.set(b"Kind".to_vec(), Object::name("Text")); d.set(b"Text".to_vec(), PdfString::text(&t.text)); d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic))); + if let Some(font_resource) = &t.font_resource { + d.set(b"FontResource".to_vec(), Object::name(font_resource)); + } d.set(b"Size".to_vec(), Object::Real(t.size)); d.set(b"Color".to_vec(), arr(&t.color)); // The ink beside its RGB look, which a reader that knows no ink keeps showing. diff --git a/crates/edit/src/added/layout.rs b/crates/edit/src/added/layout.rs index b4a805a20a..cbc9826f8d 100644 --- a/crates/edit/src/added/layout.rs +++ b/crates/edit/src/added/layout.rs @@ -194,6 +194,9 @@ pub(super) fn is_hebrew(c: char) -> bool { /// draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text editor /// keeps it open. pub fn first_undrawable(t: &AddedText) -> Option { + if t.font_resource.is_some() { + return None; + } if t.text.chars().any(is_thai) { if let Some(c) = t.text.chars().find(|c| is_thai(*c) && !pdfcraft_fonts::thai_has(*c)) { return Some(c); diff --git a/crates/edit/src/added/store.rs b/crates/edit/src/added/store.rs index 1ee4c9c4cd..5fc96db053 100644 --- a/crates/edit/src/added/store.rs +++ b/crates/edit/src/added/store.rs @@ -28,12 +28,14 @@ fn read_value(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> T) -> T } } +/// Parses an added item dictionary (`/PCAdded`) into [`Content`]. fn parse(doc: &Document, d: &Dict) -> Option { let r = nums(doc, d.get(b"Rect")); let rect: [f64; 4] = r.try_into().ok()?; match d.name(b"Kind")? { b"Text" => { let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica")); + let font_resource = d.name(b"FontResource").map(|n| String::from_utf8_lossy(n).into_owned()); 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")); @@ -59,6 +61,7 @@ fn parse(doc: &Document, d: &Dict) -> Option { 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), + font_resource, }; // An ink whose look isn't the stored colour (a file edited by hand) is none. t.drop_stale_ink(); @@ -155,6 +158,7 @@ pub fn scan_markers(doc: &Document) -> MarkerScan { scan } +/// Validates that `c` has finite positions, sensible dimensions, and encodable text. fn validate(c: &Content) -> Result<(), EditError> { let r = c.rect(); if !r.iter().all(|v| v.is_finite()) { @@ -179,22 +183,24 @@ fn validate(c: &Content) -> Result<(), EditError> { if (r[2] - r[0]).abs() < 1.0 { return Err(EditError::Invalid("the text box is too narrow".into())); } - if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() { - return Err(thai_error(GlyphError::NoFont, &t.text)); - } - // Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new - // item is refused with what's missing, and one that already holds Arabic stays movable. - // Everything else in it is drawn in the standard font, so it still has to fit. - let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() { - t.text.split('\n').find_map(|line| { - line.chars() - .find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c))) - }) - } else { - first_undrawable(t) - }; - if let Some(c) = undrawable { - return Err(crate::undrawable(c)); + if t.font_resource.is_none() { + if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() { + return Err(thai_error(GlyphError::NoFont, &t.text)); + } + // Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new + // item is refused with what's missing, and one that already holds Arabic stays movable. + // Everything else in it is drawn in the standard font, so it still has to fit. + let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() { + t.text.split('\n').find_map(|line| { + line.chars() + .find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c))) + }) + } else { + first_undrawable(t) + }; + if let Some(c) = undrawable { + return Err(crate::undrawable(c)); + } } } Content::Image(_) => { @@ -221,11 +227,11 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option) -> R drop_fonts(doc, &mut pres, &own_fonts(doc, r)); } let taken = pres.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default(); - let (content, res) = draw(doc, c, view, &taken, obj.is_some())?; + let drawn = draw(doc, c, view, &taken, obj.is_some())?; if obj.is_none() { crate::check_on_top(doc, p)?; } - for (k, v) in res.iter() { + for (k, v) in drawn.resources.iter() { let mut sub = pres.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default(); for (n2, o) in v.as_dict().into_iter().flat_map(|d| d.iter()) { sub.set(n2.clone(), o.clone()); @@ -236,11 +242,15 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option) -> R let mut sd = Dict::new(); sd.set(b"PCMark".to_vec(), Object::name(TAG)); let mut added = params(c); + if let Some(rect) = drawn.custom_rect { + let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect()); + added.set(b"Rect".to_vec(), arr(&rect)); + } if user_unit != 1.0 { added.set(b"UserUnit".to_vec(), Object::Real(user_unit)); } sd.set(b"PCAdded".to_vec(), Object::Dict(added)); - let stream = Stream::flate(sd, &content); + let stream = Stream::flate(sd, &drawn.stream); match obj { Some(r) => { doc.set(r, Object::Stream(stream)); @@ -249,7 +259,7 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option) -> R None => { // place_tagged appends a new stream; recover its reference. let p = page_list(doc).swap_remove(page); - place_tagged(doc, &p, TAG, content.clone(), false)?; + place_tagged(doc, &p, TAG, drawn.stream.clone(), false)?; let p = page_list(doc).swap_remove(page); let r = contents(doc, &p)?.last().and_then(Object::as_ref).ok_or_else(|| EditError::Invalid("could not add the content".into()))?; doc.set(r, Object::Stream(stream)); diff --git a/crates/edit/src/added/types.rs b/crates/edit/src/added/types.rs index 24101b2eea..15200ae651 100644 --- a/crates/edit/src/added/types.rs +++ b/crates/edit/src/added/types.rs @@ -165,6 +165,8 @@ pub struct AddedText { pub align: Align, /// Extra space after every character, in points: the PDF's character spacing (`Tc`). pub char_spacing: f64, + /// Explicit page font resource for custom or embedded Unicode fonts (e.g. from `RegisterTextFont`). + pub font_resource: Option, /// 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>, @@ -229,6 +231,7 @@ impl Default for AddedText { align: Align::Left, aligns: Vec::new(), char_spacing: 0.0, + font_resource: None, } } } diff --git a/crates/edit/src/apply.rs b/crates/edit/src/apply.rs index 8b52c81c76..4fcc2bb210 100644 --- a/crates/edit/src/apply.rs +++ b/crates/edit/src/apply.rs @@ -1,14 +1,14 @@ use pdfcraft_fonts::shaped_text::{is_thai, thai_refusal, thai_width}; use super::marks::{ - Background, Context, HeaderFooter, MarkKind, MarkText, Watermark, add_picture_resource, bates_start, expand, matrix_number, n, picture, rgb, - shrink_matrix, + Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkText, SETTINGS_KEY, Watermark, add_picture_resource, bates_start, expand, + matrix_number, n, picture, read, rgb, shrink_matrix, }; 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, undrawable, wrapper_role, + END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, content_list, contents, first_wrapper, free_font_name, isolation, + page_fonts, page_list, place, place_at, place_inside_wrapper, stream_tag, undrawable, wrapper_role, }; -use super::{Document, EditError, Object, added, backdrop, helvetica_width}; +use super::{Document, EditError, ObjRef, Object, added, backdrop, helvetica_width}; /// Commit one complete mark operation only after every selected page succeeds. The snapshot /// shares original bytes, cross-references, caches and unchanged objects; only the overlay table @@ -25,24 +25,182 @@ fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) /// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic: /// on error, the document (including earlier selected pages) is unchanged. pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { - apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx)) + let replacing = if replace { Replacing::OnThosePages } else { Replacing::Nothing }; + apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replacing, cx)) } -fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { +/// Replace one header and footer: `old` (settings from [`header_footers`]) goes from every page +/// it is on and `hf` is added to `pages`. Any other header or footer stays, on those pages too +/// (#5785). On a page `old` was on, `hf` takes its place among the page's marks, so one added +/// after `old` still draws over it; on the others it goes on top. The whole call is atomic. +pub fn update_header_footer(doc: &mut Document, old: &HeaderFooter, pages: &[usize], hf: &HeaderFooter, cx: &Context) -> Result<(), EditError> { + apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, Replacing::Only(old), cx)) +} + +/// How many different headers and footers [`header_footers`] lists: enough for any real document, +/// and a limit on the work a file with a different one in every stream can ask for. +const MAX_HEADER_FOOTERS: usize = 256; + +/// The settings a content stream records for its header and footer, if it records any. +fn recorded_settings(doc: &Document, stream: &Object) -> Option { + if stream_tag(doc, stream).as_deref() != Some(MarkKind::HeaderFooter.tag()) { + return None; + } + read(doc, stream, |s| HeaderFooter::from_object(doc, s.as_dict()?.get(SETTINGS_KEY)?)) +} + +/// The most bytes of recorded text one scan of a document converts: the text of hundreds of +/// thousands of real headers, yet a bound on a file that repeats a large one in every stream. +const MAX_SCAN_TEXT: usize = 16 * 1024 * 1024; + +/// One scan of a document's headers and footers. A stream, or a settings entry, given by reference +/// is read once however many pages share it, and the text converted in all is bounded +/// ([`MAX_SCAN_TEXT`]): a file repeating its settings can't make listing them slow. +struct Scan { + found: Vec, + streams: std::collections::HashMap, + settings: std::collections::HashMap, + budget: usize, + /// Some settings went [`Recorded::Unread`]. + unread: bool, +} + +/// What a content stream records. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Recorded { + /// No header and footer, or one whose settings can't be read (from before they were recorded, + /// another tool's, or unreadable). + Nothing, + /// Settings past the scan's text budget ([`MAX_SCAN_TEXT`]), not read: they may be any + /// header and footer's, so a listed one may be on more pages than the scan found. + Unread, + /// Settings, listed as `found[k]`, or not listed (`None`) past [`MAX_HEADER_FOOTERS`]. + Settings(Option), +} + +impl Scan { + fn of(doc: &Document) -> Self { + let mut scan = Self { found: Vec::new(), streams: Default::default(), settings: Default::default(), budget: MAX_SCAN_TEXT, unread: false }; + for (i, page) in page_list(doc).iter().enumerate() { + for o in content_list(doc, page).iter() { + if let Recorded::Settings(Some(k)) = scan.stream(doc, o) + && let Some(mark) = scan.found.get_mut(k) + && mark.pages.last() != Some(&i) + { + mark.pages.push(i); + } + } + } + scan + } + + fn stream(&mut self, doc: &Document, o: &Object) -> Recorded { + let Object::Ref(r) = o else { return self.read_stream(doc, o) }; + if let Some(known) = self.streams.get(r) { + return *known; + } + let recorded = self.read_stream(doc, o); + self.streams.insert(*r, recorded); + recorded + } + + fn read_stream(&mut self, doc: &Document, o: &Object) -> Recorded { + if stream_tag(doc, o).as_deref() != Some(MarkKind::HeaderFooter.tag()) { + return Recorded::Nothing; + } + read(doc, o, |s| Some(self.entry(doc, s.as_dict()?.get(SETTINGS_KEY)?))).unwrap_or(Recorded::Nothing) + } + + /// A stream's [`SETTINGS_KEY`] entry. + fn entry(&mut self, doc: &Document, value: &Object) -> Recorded { + let Object::Ref(r) = value else { return self.read_settings(doc, value) }; + if let Some(known) = self.settings.get(r) { + return *known; + } + let recorded = self.read_settings(doc, value); + self.settings.insert(*r, recorded); + recorded + } + + fn read_settings(&mut self, doc: &Document, value: &Object) -> Recorded { + let Some(settings) = HeaderFooter::from_object_within(doc, value, &mut self.budget) else { + // Running out of budget spends all of it. + if self.budget == 0 { + self.unread = true; + return Recorded::Unread; + } + return Recorded::Nothing; + }; + if let Some(k) = self.found.iter().position(|m| m.settings == settings) { + return Recorded::Settings(Some(k)); + } + if self.found.len() >= MAX_HEADER_FOOTERS { + return Recorded::Settings(None); + } + self.found.push(HeaderFooterMark { pages: Vec::new(), settings }); + Recorded::Settings(Some(self.found.len() - 1)) + } +} + +/// The headers and footers that record their settings, in page order, each with the pages it is +/// on. Marks from before settings were recorded, or from another tool, are not listed. In a file +/// recording more text than one scan reads ([`MAX_SCAN_TEXT`]) a mark may be on more pages than +/// it lists, and [`remove_header_footer`] refuses rather than leave it on the others. +pub fn header_footers(doc: &Document) -> Vec { + Scan::of(doc).found +} + +/// The header and footer added last to page `page` (0-based): `Some(None)` when it records no +/// settings (from before they were recorded, or another tool), `None` when the page has none. +/// Each mark's own stream goes on top of the page's content, so the last one is the newest; a +/// shrink goes underneath, inside the wrapper, and is never last. +pub fn newest_header_footer(doc: &Document, page: usize) -> Option> { + let page = page_list(doc).into_iter().nth(page)?; + let content = content_list(doc, &page); + let newest = content.iter().rev().find(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()))?; + Some(recorded_settings(doc, newest)) +} + +/// Where in a page's content list `list` the header and footer recorded with `old` draws: the +/// last stream that records `old`, not counting shrinks, which go first inside the wrapper +/// ([`place_inside_wrapper`]) and draw nothing. `None` when it is not on the page. +fn mark_slot(doc: &Document, list: &[Object], old: &HeaderFooter) -> Option { + let shrinks = first_wrapper(doc, list).map_or(0..0, |open| { + let start = open.saturating_add(1); + let run = list.iter().skip(start).take_while(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag())).count(); + start..start.saturating_add(run) + }); + list.iter().enumerate().rev().find(|(i, o)| !shrinks.contains(i) && recorded_settings(doc, o).as_ref() == Some(old)).map(|(i, _)| i) +} + +/// Pages (0-based) with a header and footer that records no settings: Update can only replace +/// those page-wide, as it did before settings were recorded. +pub fn unrecorded_header_footer_pages(doc: &Document) -> Vec { + let tagged = |o: &Object| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()); + let mut scan = Scan::of(doc); + page_list(doc) + .iter() + .enumerate() + .filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && scan.stream(doc, o) == Recorded::Nothing)) + .map(|(i, _)| i) + .collect() +} + +/// Which existing headers and footers an added one takes the place of. +#[derive(Clone, Copy)] +enum Replacing<'a> { + Nothing, + OnThosePages, + Only(&'a HeaderFooter), +} + +fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replacing: Replacing, cx: &Context) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; - if hf.text.iter().all(|t| t.trim().is_empty()) { - return Err(EditError::Invalid("type the header or footer text first".into())); - } if let Some(why) = hf.text.iter().find_map(|t| thai_refusal(t)) { return Err(EditError::Invalid(why)); } - if let Some(c) = hf.first_undrawable() { - return Err(undrawable(c)); - } - if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) { - return Err(EditError::Invalid("invalid font size or margins".into())); - } + hf.check()?; // Page numbers count up from start_number, so the last selected page needs the most room. // Refuse the whole run before drawing anything: headers applied to some pages and then a // failed page number would leave the document half changed. @@ -74,9 +232,17 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo for &i in pages { check_on_top(doc, &all[i])?; } - if replace { - remove_marks(doc, pages, MarkKind::HeaderFooter)?; + match replacing { + Replacing::Nothing => {} + Replacing::OnThosePages => { + remove_marks(doc, pages, MarkKind::HeaderFooter)?; + } + Replacing::Only(old) => { + // Where the new one goes, `old` stays for now, to mark its place. + remove_recorded(doc, old, pages)?; + } } + let settings = hf.to_object(); let all = page_list(doc); let count = all.len(); let number_of = |k: usize| { @@ -147,11 +313,22 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo } thai.add_to(doc, &page_list(doc)[i])?; let page = &page_list(doc)[i]; - place(doc, page, MarkKind::HeaderFooter, content, false)?; + let slot = match replacing { + Replacing::Only(old) => mark_slot(doc, &content_list(doc, page), old), + Replacing::Nothing | Replacing::OnThosePages => None, + }; + let mark = match slot { + Some(at) => place_at(doc, page, at, MarkKind::HeaderFooter, content)?, + None => place(doc, page, MarkKind::HeaderFooter, content, false)?, + }; + doc.update_dict(mark, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?; if let Some(Some(m)) = shrinks.get(k) { let cm = format!("{} cm\n", m.map(matrix_number).join(" ")); let page = &page_list(doc)[i]; - place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?; + // The shrink goes with its header: it records the same settings, so Update takes it too. + if let Some(shrink) = place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())? { + doc.update_dict(shrink, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?; + } } } Ok(()) @@ -301,6 +478,78 @@ fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, /// 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 { + remove_matching(doc, pages, kind, |_, _| true, |_, _, _| None) +} + +/// Remove the header and footer recorded with `old` from every page it is on, and no other +/// header and footer: what [`update_header_footer`] takes away before it adds the new one in its +/// place. Returns how many mark streams went; an error when no header and footer records `old` +/// any more, or when the document records more header and footer text than one scan reads, so +/// not every page it is on can be known. +pub fn remove_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result { + remove_recorded(doc, old, &[]) +} + +/// [`remove_header_footer`], except that on `kept_on` (pages, 0-based) the stream `old` draws +/// with ([`mark_slot`]) stays, for the header and footer replacing it to take its place. +fn remove_recorded(doc: &mut Document, old: &HeaderFooter, kept_on: &[usize]) -> Result { + let scan = Scan::of(doc); + if scan.unread { + return Err(EditError::Invalid( + "this document records too much header and footer text to find every page one is on: replace the headers and footers on the pages instead".into(), + )); + } + let on = scan.found.into_iter().find(|m| m.settings == *old).map(|m| m.pages); + let on = on.ok_or_else(|| EditError::Invalid("that header and footer is no longer in the document".into()))?; + let kept = |doc: &Document, page: usize, list: &[Object]| if kept_on.contains(&page) { mark_slot(doc, list, old) } else { None }; + remove_matching(doc, &on, MarkKind::HeaderFooter, |doc, o| recorded_settings(doc, o).as_ref() == Some(old), kept) +} + +/// The pages under the header and footer recorded with `old`, for Update's preview: `old` goes +/// from every page it is on, with everything drawn after it there, which +/// [`over_header_footer`] keeps. Returns how many mark streams of `old` went; an error as +/// [`remove_header_footer`] gives one. +pub fn under_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result { + for page in page_list(doc) { + let list = content_list(doc, &page); + if let Some(slot) = mark_slot(doc, &list, old) + && slot.saturating_add(1) < list.len() + { + let mut list = contents(doc, &page)?; + list.truncate(slot.saturating_add(1)); + doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?; + } + } + remove_header_footer(doc, old) +} + +/// What Update of the header and footer recorded with `old` leaves drawn over the one replacing +/// it, for its preview: each page keeps only what is drawn after `old` (nothing, where `old` is +/// not, as the new one goes on top there) and no annotations, which [`under_header_footer`]'s +/// pages already show. Returns how many pages have anything left. +pub fn over_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result { + let mut left = 0; + for page in page_list(doc) { + let list = content_list(doc, &page); + let over: Vec = mark_slot(doc, &list, old).map(|slot| list.into_iter().skip(slot.saturating_add(1)).collect()).unwrap_or_default(); + left += usize::from(!over.is_empty()); + doc.update_dict(page.obj, |d| { + d.set(b"Contents".to_vec(), Object::Array(over)); + d.remove(b"Annots"); + })?; + } + Ok(left) +} + +/// [`remove_marks`], only for the mark streams `matches` accepts, and on each page not the one +/// at the place in its content list `kept` names, if any. +fn remove_matching( + doc: &mut Document, + pages: &[usize], + kind: MarkKind, + matches: impl Fn(&Document, &Object) -> bool, + kept: impl Fn(&Document, usize, &[Object]) -> Option, +) -> Result { let all = page_list(doc); check(pages, all.len())?; let mut removed = 0; @@ -311,7 +560,13 @@ pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Resu } let list = contents(doc, page)?; let before = list.len(); - let mut kept: Vec = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect(); + let stays = kept(doc, i, &list); + let mut kept: Vec = list + .into_iter() + .enumerate() + .filter(|(k, o)| Some(*k) == stays || stream_tag(doc, o).as_deref() != Some(kind.tag()) || !matches(doc, o)) + .map(|(_, o)| o) + .collect(); removed += before - kept.len(); // Strip only wrapper pairs whose close ends the list (after stripping the pairs after // it): nothing comes after them to need the state they restore. Pairs come from the diff --git a/crates/edit/src/flatten.rs b/crates/edit/src/flatten.rs index 03ed272f3c..09cc4121a8 100644 --- a/crates/edit/src/flatten.rs +++ b/crates/edit/src/flatten.rs @@ -621,6 +621,22 @@ thread_local! { /// Remove flattened widgets from the AcroForm field tree, and fields left without widgets. With /// `on_page`, also the widgets (fields without kids) that are on no page. +/// Whether the field at `r` is a signature field: its `/FT`, or the nearest one up its `/Parent` +/// chain (field types are inherited). The walk stops after 64 parents, so a cycle ends. +fn is_signature_field(doc: &Document, r: ObjRef) -> bool { + let mut node = r; + for _ in 0..=64 { + let obj = doc.get(node); + let Some(d) = obj.as_dict() else { return false }; + if let Some(ft) = d.get(b"FT").map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec())) { + return ft == b"Sig"; + } + let Some(parent) = d.get(b"Parent").and_then(|p| p.as_ref()) else { return false }; + node = parent; + } + false +} + fn prune_fields(doc: &mut Document, widgets: &HashSet, on_page: Option<&HashSet>) -> Result<(), EditError> { let Some(root) = doc.root() else { return Ok(()) }; let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) else { return Ok(()) }; @@ -680,10 +696,45 @@ fn prune_fields(doc: &mut Document, widgets: &HashSet, on_page: Option<& let mut known = HashMap::new(); let survivors: Vec = fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, &mut known, 0).0)).cloned().collect(); - if survivors.len() == fields.len() && widgets.is_empty() { + // A field taken out of a kept parent's `/Kids` leaves `/Fields` as long as it was, and still + // needs `/CO` and `/SigFlags` cleaned. + let removed_any = known.values().any(|&(survives, _)| !survives); + if survivors.len() == fields.len() && widgets.is_empty() && !removed_any { return Ok(()); // only looked for fields on no page, and there were none } + // Every field left in the tree, however deep: `known` stops at the depth cutoff, so walk the + // kept tree again from `/Fields`, each node once (a cycle ends where it began). + let mut surviving: HashSet = HashSet::new(); + let mut stack: Vec = survivors.iter().filter_map(Object::as_ref).collect(); + while let Some(r) = stack.pop() { + if widgets.contains(&r) || matches!(known.get(&r), Some(&(false, _))) || !surviving.insert(r) { + continue; + } + let Some(d) = doc.get(r).as_dict().cloned() else { continue }; + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) { + stack.extend(kids.iter().filter_map(Object::as_ref)); + } + } af_dict.set(b"Fields".to_vec(), Object::Array(survivors)); + // #2670: the calculation order keeps only the fields that are left, and goes once it is empty. + // Only the form's keys change: an indirect `/CO` or `/SigFlags` may be shared, so it is neither + // freed (that would null the other references) nor rewritten (they would see the shorter + // list). A shortened order is the form's own direct array; once nothing refers to the old + // object, a full save leaves it out. + if let Some(co_obj) = af_dict.get(b"CO").cloned() { + let co_array = doc.resolve(&co_obj).as_array().cloned().unwrap_or_default(); + let before = co_array.len(); + let co_survivors: Vec = co_array.into_iter().filter(|item| item.as_ref().is_some_and(|r| surviving.contains(&r))).collect(); + if co_survivors.is_empty() { + af_dict.remove(b"CO"); + } else if co_survivors.len() != before { + af_dict.set(b"CO".to_vec(), Object::Array(co_survivors)); + } + } + // #2670: with no signature field left, the form no longer claims to hold signatures. + if !surviving.iter().any(|&r| is_signature_field(doc, r)) { + af_dict.remove(b"SigFlags"); + } match af_ref { Some(r) => doc.set(r, Object::Dict(af_dict)), None => doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af_dict)))?, diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rs index e269fda375..ad6c18e979 100644 --- a/crates/edit/src/images.rs +++ b/crates/edit/src/images.rs @@ -4,7 +4,7 @@ //! delete, or ungroup grouped artwork (its content drawn in place, see `ungroup`). Only the stream that draws it is rewritten, as a new object. use kurbo::{BezPath, Point, Shape}; -use pdfcraft_content::{Matrix, Op, parse, serialize_ops}; +use pdfcraft_content::{Matrix, Op, Pieces, parse, serialize_ops}; use pdfcraft_cos::{Dict, Document, ObjRef, Object}; use std::sync::Arc; @@ -123,6 +123,816 @@ fn xobjects(doc: &Document, page: &Dict) -> Dict { .unwrap_or_default() } +const IMAGE_CENSUS_MAX_OBJECTS: usize = 100_000; +const IMAGE_CENSUS_MAX_BYTES: usize = 128 * 1024 * 1024; +const IMAGE_CENSUS_MAX_OPERATORS: usize = 5_000_000; +const IMAGE_CENSUS_MAX_VISITS: usize = 50_000; +const IMAGE_CENSUS_MAX_DEPTH: usize = 64; +const IMAGE_CENSUS_MAX_ALIASES: usize = 255; +const IMAGE_REWRITE_MAX_ENTRIES: usize = 500_000; +const IMAGE_REWRITE_MAX_CONTAINER_ENTRIES: usize = 100_000; +const IMAGE_REWRITE_MAX_KEY_BYTES: usize = 16 * 1024 * 1024; +const IMAGE_REWRITE_MAX_STAGED_OBJECTS: usize = IMAGE_CENSUS_MAX_ALIASES; + +/// Separate budget for the conservative cleanup rewrite walk. It counts every array item and +/// dictionary entry inspected, including primitive values, without recursively visiting scalar +/// leaves. This work is distinct from the executable-content census budget above. +#[derive(Default)] +struct ImageRewriteBudget { + entries: usize, + key_bytes: usize, +} + +impl ImageRewriteBudget { + fn charge_entries(&mut self, count: usize) -> Result<(), ()> { + if count > IMAGE_REWRITE_MAX_CONTAINER_ENTRIES { + return Err(()); + } + self.entries = self.entries.saturating_add(count); + if self.entries > IMAGE_REWRITE_MAX_ENTRIES { Err(()) } else { Ok(()) } + } + + fn charge_dict(&mut self, dict: &Dict) -> Result<(), ()> { + self.charge_entries(dict.len()) + } + + fn charge_key_bytes(&mut self, count: usize) -> Result<(), ()> { + self.key_bytes = self.key_bytes.saturating_add(count); + if self.key_bytes > IMAGE_REWRITE_MAX_KEY_BYTES { Err(()) } else { Ok(()) } + } +} + +/// A full-document, bounded census of executable resource consumers. `incomplete` means a +/// conservative cleanup cannot prove that an image is unused, so callers must leave its bytes. +struct ImageUseCensus<'a> { + doc: &'a Document, + target: ObjRef, + used: bool, + incomplete: bool, + bytes: usize, + operators: usize, + visits: usize, +} + +impl ImageUseCensus<'_> { + fn charge_visit(&mut self) -> bool { + self.visits = self.visits.saturating_add(1); + if self.visits > IMAGE_CENSUS_MAX_VISITS { + self.incomplete = true; + false + } else { + true + } + } + + fn charge_stream(&mut self, stream: &pdfcraft_cos::Stream) -> Option> { + if !self.charge_visit() { + return None; + } + // A tolerated prefix cannot prove nonuse. Bound allocation by the document's remaining + // census allowance, and reject corrupt filters before any destructive cleanup is staged. + let remaining = IMAGE_CENSUS_MAX_BYTES.saturating_sub(self.bytes); + let data = match self.doc.with_direct_parms(stream).decoded_strict_within(remaining) { + Ok(data) => data, + Err(_) => { + self.incomplete = true; + return None; + } + }; + self.bytes = self.bytes.saturating_add(data.len()); + if self.bytes > IMAGE_CENSUS_MAX_BYTES { + self.incomplete = true; + return None; + } + Some(data) + } + + fn walk_stream(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + if reference == Some(self.target) { + self.used = true; + return; + } + if let Some(reference) = reference + && !path.insert(reference) + { + // A cycle could be rendered differently under an inherited resource scope. + self.incomplete = true; + return; + } + let resolved = self.doc.resolve(object); + let Object::Stream(stream) = &*resolved else { + self.incomplete = true; + return; + }; + + // Image masks and alternates are serialized image consumers even though they are not + // reached by a `Do` of their own. + if stream.dict.name(b"Subtype") == Some(b"Image") { + for key in [b"SMask".as_slice(), b"Mask".as_slice()] { + let Some(dependency) = stream.dict.get(key) else { continue }; + if dependency.as_ref() == Some(self.target) { + self.used = true; + return; + } + match dependency { + Object::Ref(_) => self.walk_stream(dependency, inherited, depth + 1, path), + Object::Null => {} + Object::Name(name) if key == b"SMask" && name == b"None" => {} + Object::Array(values) if key == b"Mask" && values.iter().all(|value| value.as_ref().is_none()) => {} + _ => self.incomplete = true, + } + if self.incomplete || self.used { + return; + } + } + if let Some(alternates) = stream.dict.get(b"Alternates").map(|o| self.doc.resolve(o)) { + let Some(items) = alternates.as_array() else { + self.incomplete = true; + return; + }; + for item in items { + let item = self.doc.resolve(item); + let Some(image) = item.as_dict().and_then(|d| d.get(b"Image")) else { + self.incomplete = true; + return; + }; + if image.as_ref() == Some(self.target) { + self.used = true; + return; + } + self.walk_stream(image, inherited, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + return; + } + + let subtype = stream.dict.name(b"Subtype"); + let pattern = stream.dict.get(b"PatternType").map(|o| self.doc.resolve(o)).as_deref().and_then(Object::as_int) == Some(1); + if subtype != Some(b"Form") && !pattern { + self.incomplete = true; + if let Some(reference) = reference { + path.remove(&reference); + } + return; + } + let resources = + stream.dict.get(b"Resources").map(|r| self.doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_else(|| inherited.clone()); + let Some(data) = self.charge_stream(stream) else { + if let Some(reference) = reference { + path.remove(&reference); + } + return; + }; + self.walk_content(&data, &resources, depth + 1, path); + if let Some(reference) = reference { + path.remove(&reference); + } + } + + fn walk_type3(&mut self, font: &Object, _inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if !self.charge_visit() { + return; + } + let resolved = self.doc.resolve(font); + let Some(dict) = resolved.as_dict() else { + self.incomplete = true; + return; + }; + if dict.get(b"Subtype").map(|o| self.doc.resolve(o)).as_deref().and_then(Object::as_name) != Some(b"Type3") { + return; + } + let Some(resources) = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + // The selected font survives Form calls, but its glyphs then resolve names in the + // text-showing Form's scope. Without tracking that graphics state, nonuse is unproven. + self.incomplete = true; + return; + }; + let Some(charprocs) = dict.get(b"CharProcs").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + self.incomplete = true; + return; + }; + for (_, charproc) in charprocs.iter() { + self.walk_charproc(charproc, &resources, depth + 1, path); + if self.used || self.incomplete { + return; + } + } + } + + fn walk_charproc(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + if reference.is_some_and(|r| !path.insert(r)) { + self.incomplete = true; + return; + } + let resolved = self.doc.resolve(object); + let Object::Stream(stream) = &*resolved else { + self.incomplete = true; + return; + }; + let resources = + stream.dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_else(|| inherited.clone()); + if let Some(data) = self.charge_stream(stream) { + self.walk_content(&data, &resources, depth + 1, path); + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + + fn walk_resources_for_operator(&mut self, op: &Op, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if op.is("Tf") { + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + if let Some(fonts) = resources.get(b"Font").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) + && let Some(font) = fonts.get(name) + { + self.walk_type3(font, resources, depth + 1, path); + } + } else if op.is("gs") { + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + let states = resources.get(b"ExtGState").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()); + let Some(state) = states.as_ref().and_then(|d| d.get(name)).map(|o| self.doc.resolve(o)) else { + self.incomplete = true; + return; + }; + let Some(state_dict) = state.as_dict() else { + self.incomplete = true; + return; + }; + if let Some(font_value) = state_dict.get(b"Font") { + let font = self.doc.resolve(font_value); + let Some(values) = font.as_array() else { + self.incomplete = true; + return; + }; + if values.len() != 2 { + self.incomplete = true; + return; + } + self.walk_type3(&values[0], resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + let Some(mask_value) = state_dict.get(b"SMask") else { return }; + let mask = self.doc.resolve(mask_value); + match &*mask { + Object::Name(name) if name == b"None" => {} + Object::Dict(mask_dict) => { + let Some(group) = mask_dict.get(b"G") else { + self.incomplete = true; + return; + }; + let resolved_group = self.doc.resolve(group); + if !matches!(&*resolved_group, Object::Stream(stream) if stream.dict.name(b"Subtype") == Some(b"Form")) { + self.incomplete = true; + return; + } + self.walk_stream(group, resources, depth + 1, path); + } + _ => self.incomplete = true, + } + } else if op.is("scn") || op.is("SCN") { + let Some(name) = op.operands.last().and_then(Object::as_name) else { return }; + let patterns = resources.get(b"Pattern").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()); + if let Some(pattern) = patterns.as_ref().and_then(|d| d.get(name)) { + let resolved = self.doc.resolve(pattern); + if let Some(dict) = resolved.as_dict() { + let kind = dict.get(b"PatternType").map(|o| self.doc.resolve(o)); + match kind.as_deref().and_then(Object::as_int) { + Some(1) => self.walk_stream(pattern, resources, depth + 1, path), + Some(2) if !dict.contains(b"ExtGState") => {} + // A shading pattern's state can select a soft-mask Form. Unknown types + // are consumers too: neither case proves image nonuse. + _ => self.incomplete = true, + } + } else { + self.incomplete = true; + } + } + } + } + + fn walk_content(&mut self, data: &[u8], resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + self.walk_parsed(parse(data), resources, depth, path); + } + + fn walk_parsed(&mut self, parsed: pdfcraft_content::Parsed, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + self.operators = self.operators.saturating_add(parsed.ops.len()); + if parsed.skipped != 0 || self.operators > IMAGE_CENSUS_MAX_OPERATORS { + self.incomplete = true; + return; + } + for op in &parsed.ops { + self.walk_resources_for_operator(op, resources, depth, path); + if self.incomplete || self.used { + return; + } + if !op.is("Do") { + continue; + } + let Some(name) = op.name(0) else { + self.incomplete = true; + return; + }; + let Some(xobjects) = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + self.incomplete = true; + return; + }; + let Some(xobject) = xobjects.get(name) else { + self.incomplete = true; + return; + }; + if xobject.as_ref() == Some(self.target) { + self.used = true; + return; + } + self.walk_stream(xobject, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + } + + fn walk_annotation(&mut self, annotation: &Dict, resources: &Dict, path: &mut std::collections::HashSet) { + if let Some(ap) = annotation.get(b"AP") { + self.walk_appearances(ap, resources, 0, path); + } + if let Some(mk) = annotation.get(b"MK").map(|o| self.doc.resolve(o)) { + if let Some(characteristics) = mk.as_dict() { + // Button icons are Form consumers independently of the /AP states. + for key in [b"I".as_slice(), b"RI", b"IX"] { + if let Some(icon) = characteristics.get(key) { + self.walk_stream(icon, resources, 0, path); + } + } + } else if !matches!(&*mk, Object::Null) { + self.incomplete = true; + } + } + } + + fn walk_appearances(&mut self, object: &Object, resources: &Dict, depth: usize, path: &mut std::collections::HashSet) { + if self.used || self.incomplete { + return; + } + if !self.charge_visit() { + return; + } + if depth > IMAGE_CENSUS_MAX_DEPTH { + self.incomplete = true; + return; + } + let reference = object.as_ref(); + match &*self.doc.resolve(object) { + Object::Stream(_) => self.walk_stream(object, resources, depth + 1, path), + Object::Dict(dict) => { + if let Some(reference) = reference + && !path.insert(reference) + { + self.incomplete = true; + return; + } + if dict.contains(b"Resources") { + self.incomplete = true; + return; + } + for (_, value) in dict.iter() { + self.walk_appearances(value, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + Object::Array(values) => { + if let Some(reference) = reference + && !path.insert(reference) + { + self.incomplete = true; + return; + } + for value in values { + self.walk_appearances(value, resources, depth + 1, path); + if self.incomplete || self.used { + return; + } + } + if let Some(reference) = reference { + path.remove(&reference); + } + } + _ => {} + } + } +} + +/// Remove a deleted/replaced image from every resource dictionary only after a bounded census +/// proves no page, Form, Type3 glyph, soft mask, tiling pattern, or annotation appearance uses it. +/// Any unsupported or malformed consumer preserves the image and still lets the edit succeed. +fn prune_unused_image(doc: &mut Document, target: ObjRef) { + let object_count = doc.scan_objects_checked().take(IMAGE_CENSUS_MAX_OBJECTS + 1).count(); + if object_count > IMAGE_CENSUS_MAX_OBJECTS { + return; + } + let mut census = ImageUseCensus { doc, target, used: false, incomplete: false, bytes: 0, operators: 0, visits: 0 }; + let mut path = std::collections::HashSet::new(); + let pages = pdfcraft_model::pages(doc); + if pages.len() > IMAGE_CENSUS_MAX_OBJECTS { + return; + } + for page in &pages { + let resources = match page.dict.get(b"Resources") { + None => Dict::new(), + Some(value) => { + let resolved = doc.resolve(value); + let Some(resources) = resolved.as_dict().cloned() else { + census.incomplete = true; + break; + }; + resources + } + }; + let contents_object = page.dict.get(b"Contents").map(|value| doc.resolve(value)); + let contents: &[Object] = match contents_object.as_deref() { + None => &[], + Some(Object::Array(items)) => items, + Some(value) => std::slice::from_ref(value), + }; + if contents.len() > IMAGE_CENSUS_MAX_VISITS { + census.incomplete = true; + break; + } + let mut content_data = Vec::with_capacity(contents.len()); + for content in contents { + let resolved = doc.resolve(content); + let Object::Stream(stream) = &*resolved else { + census.incomplete = true; + break; + }; + if let Some(data) = census.charge_stream(stream) { + content_data.push(data); + } + if census.incomplete { + break; + } + } + if !census.incomplete { + census.walk_parsed(Pieces::join(&content_data).parse(), &resources, 0, &mut path); + } + let annots = page.dict.get(b"Annots").map(|o| doc.resolve(o)); + if let Some(annots) = annots { + let Some(items) = annots.as_array() else { + census.incomplete = true; + break; + }; + if items.len() > IMAGE_CENSUS_MAX_OBJECTS { + census.incomplete = true; + break; + } + for item in items { + if !census.charge_visit() { + break; + } + let resolved = doc.resolve(item); + let Some(annotation) = resolved.as_dict() else { continue }; + census.walk_annotation(annotation, &resources, &mut path); + if census.incomplete || census.used { + break; + } + } + } + if census.incomplete || census.used { + break; + } + } + if census.used || census.incomplete { + return; + } + + // Unknown stream types carrying their own resource namespace could also consume XObjects. + let checked: Vec<_> = doc.scan_objects_checked().collect(); + if checked.len() > IMAGE_CENSUS_MAX_OBJECTS || checked.iter().any(|(_, item)| item.is_err()) { + return; + } + if checked.iter().any(|(_, item)| { + item.as_ref().ok().is_some_and(|o| matches!(o.as_ref(), Object::Stream(s) if s.dict.contains(b"Resources") && s.dict.name(b"Subtype") != Some(b"Form") && s.dict.int(b"PatternType") != Some(1))) + }) { + return; + } + + let mut staged = std::collections::HashMap::new(); + let mut indirect_xobject_dicts = std::collections::HashSet::new(); + let mut indirect_alternate_arrays = std::collections::HashSet::new(); + let mut aliases = 0usize; + let mut rewrite_budget = ImageRewriteBudget::default(); + for (reference, item) in checked { + let Ok(object) = item else { return }; + let mut object = (*object).clone(); + let mappings_changed = match prune_xobject_mappings(&mut object, target, &mut indirect_xobject_dicts, &mut aliases, 0, &mut rewrite_budget) { + Ok(changed) => changed, + Err(()) => return, + }; + let dependencies_changed = + match prune_image_dependencies(&mut object, doc, target, &mut indirect_alternate_arrays, &mut aliases, 0, &mut rewrite_budget) { + Ok(changed) => changed, + Err(()) => return, + }; + if mappings_changed || dependencies_changed { + if aliases > IMAGE_CENSUS_MAX_ALIASES || staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS { + return; + } + staged.insert(reference, object); + } + } + for reference in indirect_xobject_dicts { + let was_staged = staged.contains_key(&reference); + let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); + let changed = match remove_target_aliases(object.as_dict_mut(), target, &mut aliases, &mut rewrite_budget) { + Ok(changed) => changed, + Err(()) => return, + }; + if changed || was_staged { + if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) { + return; + } + staged.insert(reference, object); + } + } + for reference in indirect_alternate_arrays { + let was_staged = staged.contains_key(&reference); + let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone()); + let changed = match remove_target_alternate_entries(&mut object, doc, target, &mut aliases, &mut rewrite_budget) { + Ok(changed) => changed, + Err(()) => return, + }; + if changed { + if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) { + return; + } + staged.insert(reference, object); + } else if !matches!(&object, Object::Array(_)) { + // An indirect `/Alternates` value that is not an array is malformed. Since the + // census cannot establish whether it retains the target, preserve the whole edit. + return; + } else if was_staged { + staged.insert(reference, object); + } + } + for (reference, object) in staged { + doc.set(reference, object); + } +} + +fn remove_target_aliases(dict: Option<&mut Dict>, target: ObjRef, aliases: &mut usize, budget: &mut ImageRewriteBudget) -> Result { + let Some(dict) = dict else { return Ok(false) }; + budget.charge_dict(dict)?; + let mut names = Vec::new(); + for (name, value) in dict.iter() { + budget.charge_key_bytes(name.len())?; + if value.as_ref() == Some(target) { + if aliases.saturating_add(names.len()) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + names.push(name.clone()); + } + } + for name in &names { + dict.remove(name); + } + *aliases = aliases.saturating_add(names.len()); + Ok(!names.is_empty()) +} + +fn prune_xobject_mappings( + object: &mut Object, + target: ObjRef, + indirect: &mut std::collections::HashSet, + aliases: &mut usize, + depth: usize, + budget: &mut ImageRewriteBudget, +) -> Result { + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } + let mut changed = false; + match object { + Object::Array(values) => { + budget.charge_entries(values.len())?; + for value in values.iter_mut().filter(|value| is_container(value)) { + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?; + } + } + Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { + if let Some(xobjects) = dict.get_mut(b"XObject") { + match xobjects { + Object::Ref(reference) => { + indirect.insert(*reference); + } + Object::Dict(mappings) => changed |= remove_target_aliases(Some(mappings), target, aliases, budget)?, + _ => {} + } + } + let mut keys = Vec::new(); + budget.charge_dict(dict)?; + for (key, value) in dict.iter() { + budget.charge_key_bytes(key.len())?; + if is_container(value) { + keys.push(key.clone()); + } + } + for key in keys { + if let Some(value) = dict.get_mut(&key) { + changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?; + } + } + } + _ => {} + } + Ok(changed) +} + +fn contains_target_ref(object: &Object, target: ObjRef, depth: usize, budget: &mut ImageRewriteBudget) -> Result { + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } + match object { + Object::Ref(reference) => Ok(*reference == target), + Object::Array(values) => { + budget.charge_entries(values.len())?; + for value in values.iter().filter(|value| matches!(value, Object::Array(_))) { + if contains_target_ref(value, target, depth + 1, budget)? { + return Ok(true); + } + } + Ok(false) + } + _ => Ok(false), + } +} + +fn alternate_uses_target(object: &Object, doc: &Document, target: ObjRef) -> bool { + doc.resolve(object).as_dict().and_then(|dict| dict.get(b"Image")).is_some_and(|image| image.as_ref() == Some(target)) +} + +fn remove_target_alternate_entries( + object: &mut Object, + doc: &Document, + target: ObjRef, + aliases: &mut usize, + budget: &mut ImageRewriteBudget, +) -> Result { + let Object::Array(entries) = object else { return Ok(false) }; + budget.charge_entries(entries.len())?; + let mut retained = Vec::new(); + let mut removed = 0; + for entry in entries.iter() { + if alternate_uses_target(entry, doc, target) { + if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + removed += 1; + } else { + retained.push(entry.clone()); + } + } + if removed != 0 { + *entries = retained; + *aliases = aliases.saturating_add(removed); + } + Ok(removed != 0) +} + +/// Remove dependencies on an image only after the document census proves no active consumer +/// uses it. The dependent image is left in place, but its stale optional mask/alternate edge is +/// removed so full-save garbage collection can release the target bytes. +fn prune_image_dependencies( + object: &mut Object, + doc: &Document, + target: ObjRef, + indirect_alternate_arrays: &mut std::collections::HashSet, + aliases: &mut usize, + depth: usize, + budget: &mut ImageRewriteBudget, +) -> Result { + if depth > IMAGE_CENSUS_MAX_DEPTH { + return Err(()); + } + let mut changed = false; + match object { + Object::Array(values) => { + budget.charge_entries(values.len())?; + for value in values.iter_mut().filter(|value| is_container(value)) { + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?; + } + } + Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => { + if dict.name(b"Subtype") == Some(b"Image") { + for key in [b"SMask".as_slice(), b"Mask".as_slice()] { + let contains_target = + if let Some(value) = dict.get(key) { contains_target_ref(value, target, depth + 1, budget)? } else { false }; + if contains_target { + if aliases.saturating_add(1) > IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + dict.remove(key); + *aliases = aliases.saturating_add(1); + changed = true; + } + } + match dict.get(b"Alternates") { + Some(Object::Array(_)) => { + let Some(Object::Array(entries)) = dict.get_mut(b"Alternates") else { return Err(()) }; + budget.charge_entries(entries.len())?; + let mut retained = Vec::new(); + let mut removed = 0; + for entry in entries.iter() { + if alternate_uses_target(entry, doc, target) { + if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES { + return Err(()); + } + removed += 1; + } else { + retained.push(entry.clone()); + } + } + if removed != 0 { + *entries = retained; + *aliases = aliases.saturating_add(removed); + changed = true; + } + } + Some(Object::Ref(reference)) => { + indirect_alternate_arrays.insert(*reference); + } + _ => {} + } + } + let mut keys = Vec::new(); + budget.charge_dict(dict)?; + for (key, value) in dict.iter() { + budget.charge_key_bytes(key.len())?; + if is_container(value) { + keys.push(key.clone()); + } + } + for key in keys { + if let Some(value) = dict.get_mut(&key) { + changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?; + } + } + } + _ => {} + } + Ok(changed) +} + +fn is_container(object: &Object) -> bool { + matches!(object, Object::Array(_) | Object::Dict(_) | Object::Stream(_)) +} + fn intersection(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]; (r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r) @@ -1012,19 +1822,24 @@ pub(crate) fn extract_scope_state(ops: &[Op], start: usize, target: usize, initi } /// The unit `order` puts the image's unit `target_idx` next to, and whether after it. An image that -/// shares its unit with other paint at the limit moves within that unit, past or behind the paint. +/// shares its unit with other paint at the limit moves within that unit, past or behind the paint, +/// but only when that paint is on the side the move crosses: paint after it for a forward move, +/// paint before it for a backward move. Otherwise the move would leave paint order unchanged and +/// is refused, including when that is the only unit. fn target_destination_unit<'a>( units: &'a [std::ops::Range], target_idx: usize, target_unit: &'a std::ops::Range, order: ArrangeOrder, - has_other_paint: bool, + has_paint_before: bool, + has_paint_after: bool, ) -> Result<(&'a std::ops::Range, bool), EditError> { let forward = matches!(order, ArrangeOrder::BringToFront | ArrangeOrder::BringForward); let refused = || EditError::Invalid(if forward { "the image is already in front" } else { "the image is already at the back" }.into()); let at_limit = if forward { target_idx.saturating_add(1) >= units.len() } else { target_idx == 0 }; if at_limit { - return if has_other_paint { Ok((target_unit, forward)) } else { Err(refused()) }; + let effective_in_unit = if forward { has_paint_after } else { has_paint_before }; + return if effective_in_unit { Ok((target_unit, forward)) } else { Err(refused()) }; } let dest = match order { ArrangeOrder::BringToFront => units.last(), @@ -1204,6 +2019,34 @@ fn build_relocated_unit_ops( Ok(unit_ops) } +/// Paint inside `target_unit` other than the image at `target`, as `(any, before, after)`: whether +/// there is any, and whether some of it comes before the image or after it. +fn arrange_paint_flags(ops: &[Op], target: usize, target_unit: &std::ops::Range) -> (bool, bool, bool) { + let mut has_other_paint = false; + let mut has_paint_before = false; + let mut has_paint_after = false; + // A Form XObject counts as paint whatever the text rendering mode: `Tr 3` hides only the + // text it shows, and its paths and images still paint. + for (i, op) in ops.iter().enumerate() { + if i < target_unit.start || i >= target_unit.end || i == target { + continue; + } + let is_paint = matches!( + op.op.as_slice(), + b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" + ); + if is_paint { + has_other_paint = true; + if i < target { + has_paint_before = true; + } else { + has_paint_after = true; + } + } + } + (has_other_paint, has_paint_before, has_paint_after) +} + /// Change the stacking order of `img`, drawn on page `p` by its content streams `all`. fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage, order: ArrangeOrder) -> Result<(), EditError> { let pieces = joined(all); @@ -1217,20 +2060,12 @@ fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStr let Some((target_idx, target_unit)) = units.iter().enumerate().find(|(_, u)| u.contains(&target)) else { return Err(EditError::Invalid("the image content unit could not be located".into())); }; - let has_other_paint = ops.iter().enumerate().any(|(i, op)| { - i >= target_unit.start - && i < target_unit.end - && i != target - && matches!( - op.op.as_slice(), - b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" - ) - }); - if units.len() <= 1 && !has_other_paint { - return Err(EditError::Invalid("the page has only one content unit to arrange".into())); - } + // Units are counted inside a page-wide q … Q wrapper, so separate balanced inner units are not + // mistaken for one shared unit. A sole shared unit is handled by the directional at-limit check + // in `target_destination_unit`: an effective move within it is allowed, an ineffective one is refused. + let (has_other_paint, has_paint_before, has_paint_after) = arrange_paint_flags(&ops, target, target_unit); - let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_other_paint)?; + let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_paint_before, has_paint_after)?; if !balanced_arrange_span(&ops, target_unit.clone()) || !balanced_arrange_span(&ops, dest_unit.clone()) { return Err(EditError::Invalid("cannot arrange an image across graphics or marked-content boundaries".into())); } @@ -1633,10 +2468,15 @@ fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[Conten let crops_there = crops(crate::text::first_op_after_damage(all, &pieces, &ops))?; if crops_there.is_empty() { // A crop in a scope that closes past a stream not read whole may clip what that stream draws. - return Err(EditError::Invalid(if crops(ops.len())?.is_empty() { - "the image has no PdfCraft crop to remove".into() - } else { + // Enumeration can also see a PdfCraft crop marker whose path (`W q Q n`, for example) + // scope detection does not treat as a removable crop; say it cannot be removed rather + // than that no crop exists. + return Err(EditError::Invalid(if !crops(ops.len())?.is_empty() { "the image's crop may also clip what a content stream that is damaged or can't be decoded draws, so it isn't removed".into() + } else if img.has_editor_crop() { + "the image's PdfCraft crop cannot be safely removed from its current scope".into() + } else { + "the image has no PdfCraft crop to remove".into() })); } let crops = crops_there; @@ -1657,6 +2497,8 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag if !ops.get(img.op).is_some_and(|op| op.is("Do")) { return Err(EditError::Invalid("the image operation is missing".into())); } + let old_object = img.object; + let prune_target = matches!(change, ImageChange::Delete | ImageChange::Replace(_)).then_some(old_object).flatten(); let mut resources = None; let replacement: Vec = match change { ImageChange::Delete => Vec::new(), @@ -1715,6 +2557,9 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag d.set(b"Resources".to_vec(), Object::Dict(res)); } })?; + if let Some(target) = prune_target { + prune_unused_image(doc, target); + } Ok(()) } @@ -2084,4 +2929,12 @@ mod allocation_tests { tracker.step(&op, &states, &doc, Matrix::translate(50.0, 0.0)).unwrap(); assert!(before.visually_differs(&tracker.current_state), "the same mask established under a different CTM is a different effective mask"); } + + #[test] + fn arrange_paint_flags_counts_a_form_drawn_in_invisible_text_mode() { + // `Tr 3` hides text, not the paths and images a Form draws. + let ops = + vec![Op::new("Do", vec![Object::name("Target")]), Op::new("Tr", vec![Object::Real(3.0)]), Op::new("Do", vec![Object::name("Form")])]; + assert_eq!(arrange_paint_flags(&ops, 0, &(0..ops.len())), (true, false, true)); + } } diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 876df14199..64ff26c164 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -83,10 +83,13 @@ mod apply; mod marks; mod place; -pub use apply::{add_background, add_header_footer, add_watermark, marks_present, remove_marks}; +pub use apply::{ + add_background, add_header_footer, add_watermark, header_footers, marks_present, newest_header_footer, over_header_footer, remove_header_footer, + remove_marks, under_header_footer, unrecorded_header_footer_pages, update_header_footer, +}; #[cfg(test)] use marks::bates_start; -pub use marks::{Background, Context, HeaderFooter, MarkKind, MarkSource, Watermark, expand}; +pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand, recorded_header_footer}; use marks::{matrix_number, n}; pub(crate) use place::undrawable; #[cfg(test)] diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index d772c48f4b..938b436c8e 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -160,6 +160,162 @@ impl HeaderFooter { } } +/// One header and footer in a document: its settings and the pages (0-based, ascending) it is on. +/// Marks with the same settings count as one. +#[derive(Clone, Debug, PartialEq)] +pub struct HeaderFooterMark { + pub pages: Vec, + pub settings: HeaderFooter, +} + +/// The entry of a header and footer's content streams that keeps its settings, so Update can tell +/// several apart and fill the dialog with the one chosen (#5785). Drawn text alone can't say +/// which tokens made it. Private to PdfCraft (like `/PCMark`); other readers ignore it. +pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter"; + +/// The most bytes one recorded text box may take. A dialog box never needs more, and it bounds +/// what listing the headers and footers of a hostile file decodes. +const MAX_RECORDED_TEXT: usize = 16 * 1024; + +/// `f` of `o`, or of what it refers to: a direct value is read in place, never copied, so a large +/// one costs nothing until it has been checked. (`Document::resolve` copies a direct value whole.) +pub(crate) fn read(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> Option) -> Option { + match o { + Object::Ref(_) => f(&doc.resolve(o)), + _ => f(o), + } +} + +/// An array of exactly `N` numbers, each resolved: a rewriting tool may make any of them indirect. +fn numbers(doc: &Document, o: &Object) -> Option<[f64; N]> { + read(doc, o, |array| { + let items = array.as_array().filter(|a| a.len() == N)?; + let values: Vec = items.iter().map(|v| read(doc, v, Object::as_f64)).collect::>()?; + <[f64; N]>::try_from(values).ok() + }) +} + +impl HeaderFooter { + /// Why [`add_header_footer`] refuses these settings, if it does. A recorded header and footer + /// is listed only when it passes too, so every one Update offers is one OK can apply. + pub(crate) fn check(&self) -> Result<(), EditError> { + if self.text.iter().all(|t| t.trim().is_empty()) { + return Err(EditError::Invalid("type the header or footer text first".into())); + } + // Measured as recorded: a box the listing would refuse to decode must not be added, or it + // could never be listed and updated, only replaced page-wide. + if self.text.iter().any(|t| pdfcraft_cos::PdfString::text(t).bytes.len() > MAX_RECORDED_TEXT) { + return Err(EditError::Invalid(format!("a header or footer box can hold at most {} KB of text", MAX_RECORDED_TEXT / 1024))); + } + if let Some(c) = self.first_undrawable() { + return Err(super::place::undrawable(c)); + } + if !(self.font_size.is_finite() && self.font_size > 0.0 && self.font_size <= 200.0 && self.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) + { + return Err(EditError::Invalid("invalid font size or margins".into())); + } + Ok(()) + } + + /// These settings as the [`SETTINGS_KEY`] entry. The colour is recorded as drawn (see `rgb`), + /// so a header added with an out-of-range colour can still be listed and updated. + pub(crate) fn to_object(&self) -> Object { + let reals = |v: &[f64]| Object::Array(v.iter().copied().map(Object::Real).collect()); + let drawn = self.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); + let mut d = Dict::new(); + d.set(b"Text".to_vec(), Object::Array(self.text.iter().map(|t| Object::String(pdfcraft_cos::PdfString::text(t))).collect())); + d.set( + b"Font".to_vec(), + Object::name(match self.font { + added::Family::Helvetica => "Helvetica", + added::Family::Times => "Times", + added::Family::Courier => "Courier", + }), + ); + d.set(b"Size".to_vec(), Object::Real(self.font_size)); + d.set(b"Color".to_vec(), reals(&drawn)); + d.set(b"Underline".to_vec(), Object::Bool(self.underline)); + d.set(b"Margins".to_vec(), reals(&self.margins)); + d.set(b"Start".to_vec(), Object::Int(i64::from(self.start_number))); + d.set(b"Shrink".to_vec(), Object::Bool(self.shrink)); + Object::Dict(d) + } + + /// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog + /// could have written: a file can say anything here. + pub(crate) fn from_object(doc: &Document, o: &Object) -> Option { + let mut unlimited = usize::MAX; + Self::from_object_within(doc, o, &mut unlimited) + } + + /// [`from_object`](Self::from_object), converting at most `budget` bytes of text, which it + /// takes from: `None` once that is spent, leaving it 0 so a scan can tell settings it could not + /// afford from ones it could not read. Bounds what one scan of a document converts. + pub(crate) fn from_object_within(doc: &Document, o: &Object, budget: &mut usize) -> Option { + #[cfg(test)] + DECODED.with(|n| n.set(n.get() + 1)); + // Every value resolved, as a rewriting tool may make any of them indirect, and read in + // place: nothing is copied before it is checked. + read(doc, o, |o| { + let d = o.as_dict()?; + let flag = |key: &[u8]| { + read(doc, d.get(key)?, |v| match v { + Object::Bool(b) => Some(*b), + _ => None, + }) + }; + // The count and each size are checked before anything is decoded. + let text: Vec = read(doc, d.get(b"Text")?, |texts| { + let texts = texts.as_array().filter(|a| a.len() == 6)?; + texts + .iter() + .map(|t| { + read(doc, t, |t| { + let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?; + let Some(left) = budget.checked_sub(s.bytes.len()) else { + *budget = 0; + return None; + }; + *budget = left; + Some(s.to_text()) + }) + }) + .collect() + })?; + let hf = Self { + text: text.try_into().ok()?, + font: read(doc, d.get(b"Font")?, |v| match v.as_name()? { + b"Helvetica" => Some(added::Family::Helvetica), + b"Times" => Some(added::Family::Times), + b"Courier" => Some(added::Family::Courier), + _ => None, + })?, + font_size: read(doc, d.get(b"Size")?, Object::as_f64)?, + color: numbers(doc, d.get(b"Color")?)?, + underline: flag(b"Underline")?, + margins: numbers(doc, d.get(b"Margins")?)?, + start_number: read(doc, d.get(b"Start")?, |v| u32::try_from(v.as_int()?).ok())?, + shrink: flag(b"Shrink")?, + }; + let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); + sane.then_some(hf) + }) + } +} + +#[cfg(test)] +thread_local! { + /// How many settings entries [`HeaderFooter::from_object_within`] has read on this thread. + pub(crate) static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The header and footer settings a [`SETTINGS_KEY`] entry records, if it records ones that +/// [`add_header_footer`](crate::add_header_footer) would accept: what redaction matches a +/// header's streams by, however each stores them. +pub fn recorded_header_footer(doc: &Document, value: &Object) -> Option { + HeaderFooter::from_object(doc, value) +} + /// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free, /// for a page shown `size` (display space) with view matrix `view` (display to user space): an /// even scale, centred across, the content's bottom on the footer's band. diff --git a/crates/edit/src/paragraph_grouping_tests.rs b/crates/edit/src/paragraph_grouping_tests.rs new file mode 100644 index 0000000000..f9d6f51d54 --- /dev/null +++ b/crates/edit/src/paragraph_grouping_tests.rs @@ -0,0 +1,347 @@ +use super::*; + +fn page(content: &str, second_face: &str) -> Document { + let mut doc = text_page(content); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |font| { + *font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type1")); + font.set(b"BaseFont".to_vec(), Object::name(second_face)); + font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding")); + }) + .unwrap(); + doc +} + +fn multi_stream_page(contents: &[&str]) -> Document { + let mut doc = page("", "Helvetica"); + let streams = + contents.iter().map(|content| Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.as_bytes().to_vec()))))).collect(); + set_page_contents(&mut doc, Object::Array(streams), None); + doc +} + +fn panel_form(doc: &mut Document, content: &str, matrix: [i64; 6]) { + let mut dict = Dict::new(); + dict.set(b"Subtype".to_vec(), Object::name("Form")); + dict.set(b"BBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())); + dict.set(b"Matrix".to_vec(), Object::Array(matrix.map(Object::Int).to_vec())); + let form = doc.add(Object::Stream(Stream::from_raw(dict, content.as_bytes().to_vec()))); + let page = pdfcraft_model::pages(doc)[0].obj; + doc.update_dict(page, |page| { + let mut resources = page.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = Dict::new(); + xobjects.set(b"Panel".to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + page.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); +} + +#[test] +fn separates_rows_when_background_is_in_a_separate_stream() { + let doc = multi_stream_page(&["q 60 690 200 25 re f Q", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_distinct_panels_are_in_separate_streams() { + let doc = + multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Upper", "Lower"]); +} + +#[test] +fn joins_rows_when_same_panel_spans_separate_streams() { + let doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "BT /F1 12 Tf 72 682 Td (Second) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn separates_rows_when_rectangle_and_fill_are_in_separate_streams() { + let doc = multi_stream_page(&["q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re", "f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_page_rows_when_transformed_background_is_in_a_form_stream() { + let mut doc = multi_stream_page(&["/Panel Do", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]); + panel_form(&mut doc, "20 340 100 12.5 re f", [2, 0, 0, 2, 20, 10]); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_distinct_panels_are_in_form_streams() { + let mut doc = multi_stream_page(&["/Panel Do q 1 0 0 1 0 -18 cm /Panel Do Q"]); + panel_form(&mut doc, "60 690 200 17 re f BT /F1 12 Tf 72 700 Td (Row) Tj ET", [1, 0, 0, 1, 0, 0]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Row", "Row"]); +} + +#[test] +fn joins_rows_when_page_panel_contains_form_text() { + let mut doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "/Panel Do"]); + panel_form(&mut doc, "BT /F1 12 Tf 72 682 Td (Second) Tj ET", [1, 0, 0, 1, 0, 0]); + + let blocks = text::reading_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn separates_rows_when_size_change_is_large() { + let doc = page("BT /F1 24 Tf 72 700 Td (Heading) Tj /F1 10 Tf 0 -24 Td (Body) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Heading", "Body"]); +} + +#[test] +fn separates_equal_size_rows_when_families_differ() { + let doc = page("BT /F1 12 Tf 72 700 Td (Heading) Tj /F2 12 Tf 0 -16 Td (Body) Tj ET", "Courier"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Heading", "Body"]); +} + +#[test] +fn separates_equal_style_rows_when_crossing_a_filled_container() { + let doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn separates_rows_when_containers_are_adjacent() { + let doc = page("q 60 690 200 25 re f 60 670 200 20 re f Q BT /F1 12 Tf 72 700 Td (Upper) Tj 0 -18 Td (Lower) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.len(), 2); +} + +#[test] +fn joins_multiline_when_inside_the_same_filled_container() { + let doc = page("q 0.9 g 60 650 200 65 re f Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj 0 -18 Td (Third) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond\nThird"]); +} + +#[test] +fn joins_rows_when_a_fill_is_painted_over_one_of_them() { + // A box painted after the text covers it (a redaction); it is not a panel behind the text. + let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET 0 g 70 696 60 20 re f", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_their_panel_is_repainted_behind_each_row() { + let doc = page( + "0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 700 Td (First) Tj ET 0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 682 Td (Second) Tj ET", + "Helvetica", + ); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_an_edit_wraps_a_fallback_word_onto_its_own_row() { + // The bundled Inter face draws the Cyrillic Helvetica lacks; wrapped alone onto a row, the + // word is still part of the paragraph that was edited. + let mut doc = page( + "BT /F1 12 Tf 14.4 TL 72 700 Td (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET", + "Helvetica", + ); + let edited = "The quick brown fox jumps over the lazy dog \u{049b}\u{0438}\u{0437}\u{0438}\u{043b}\nand keeps running through the long field."; + text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap(); + + let blocks = text::text_blocks(&reopen(&doc), 0).unwrap(); + + assert_eq!(blocks.len(), 1, "{:?}", blocks.iter().map(|b| &b.editor_text).collect::>()); + assert!(blocks[0].rows.len() > 2, "the word wraps onto a row of its own: {:?}", blocks[0].editor_text); +} + +#[test] +fn joins_plain_multiline_when_no_container_exists() { + let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_inline_styles_when_family_and_size_change() { + let doc = page("BT /F1 12 Tf 72 700 Td (Plain ) Tj /F2 20 Tf (mixed) Tj ET", "Courier-Bold"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain mixed"]); +} + +#[test] +fn joins_rows_when_subset_and_weight_names_differ() { + let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", "GHIJKL+Helvetica-Bold"); + doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name("ABCDEF+Helvetica"))).unwrap(); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"]); +} + +#[test] +fn joins_rows_when_stacked_weight_suffixes_differ() { + for (regular, bold) in [("TimesNewRomanPSMT", "TimesNewRomanPS-BoldMT"), ("MinionPro-Regular", "MinionPro-BoldIt")] { + let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", bold); + doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name(regular))).unwrap(); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"], "{regular} / {bold}"); + } +} + +#[test] +fn joins_rows_when_a_highlight_hugs_one_word() { + let doc = page("q 1 1 0 rg 98 697 36 12 re f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"]); +} + +#[test] +fn joins_rows_when_a_padded_highlight_surrounds_one_word() { + // Highlighters pad the box past the glyphs; it is still a highlight, not a panel. + for padded in ["98 695 36 16 re", "98 694 36 18 re", "96 693 40 20 re"] { + let doc = page( + &format!("q 1 1 0 rg {padded} f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET"), + "Helvetica", + ); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"], "{padded}"); + } +} + +#[test] +fn joins_rows_when_a_padded_highlight_sits_inside_a_one_run_line() { + // One `Tj` draws the whole line, so the highlight's word is not a run of its own. + let doc = page("q 1 1 0 rg 98 695 36 16 re f Q BT /F1 12 Tf 72 700 Td (Plain word rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Plain word rest\nSecond row"]); +} + +#[test] +fn joins_rows_when_only_right_edges_align() { + let doc = page("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf 300 682 Td (Short) Tj ET", "Helvetica"); + let lines = text::text_lines(&doc, 0).unwrap(); + let x = lines[0].rect[2] - (lines[1].rect[2] - lines[1].rect[0]); + let doc = page(&format!("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf {x} 682 Td (Short) Tj ET"), "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Long first row\nShort"]); +} + +#[test] +fn keeps_outside_text_when_editing_a_container_paragraph() { + let mut doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + let outside = text::text_lines(&doc, 0).unwrap()[1].clone(); + + text::replace_block(&mut doc, 0, 0, "Edited").unwrap(); + + let reopened = reopen(&doc); + let lines = text::text_lines(&reopened, 0).unwrap(); + let kept = lines.iter().find(|line| line.text == "Outside").expect("outside paragraph survives"); + assert_eq!((kept.rect, kept.size, &kept.base_font), (outside.rect, outside.size, &outside.base_font)); +} + +#[test] +fn keeps_neighboring_panel_when_editing_an_isolated_panel() { + let mut doc = + multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]); + assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2); + let neighbor = text::text_lines(&doc, 0).unwrap()[1].clone(); + + text::replace_block(&mut doc, 0, 0, "Edited").unwrap(); + + let reopened = reopen(&doc); + let blocks = text::text_blocks(&reopened, 0).unwrap(); + assert_eq!(blocks.iter().map(|block| block.text.as_str()).collect::>(), ["Edited", "Lower"]); + let lines = text::text_lines(&reopened, 0).unwrap(); + let kept = lines.iter().find(|line| line.text == "Lower").expect("neighboring panel survives"); + assert_eq!( + (kept.rect, kept.baseline(), kept.size, &kept.base_font, kept.color), + (neighbor.rect, neighbor.baseline(), neighbor.size, &neighbor.base_font, neighbor.color) + ); +} + +#[test] +fn separates_rows_when_container_has_a_transformed_negative_rectangle() { + let doc = page("q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re B Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} + +#[test] +fn joins_rows_when_rectangle_is_only_stroked_or_clipped() { + for paint in ["S", "W n", "W* n"] { + let doc = page(&format!("q 60 690 200 25 re {paint} Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET"), "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["First\nSecond"], "{paint}"); + } +} + +#[test] +fn joins_multiline_with_inline_mixed_families() { + let doc = page("BT /F1 12 Tf 72 700 Td (Ordinary text ) Tj /F2 12 Tf (code) Tj /F1 12 Tf 0 -18 Td (Following row) Tj ET", "Courier-Bold"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::>(), ["Ordinary text code\nFollowing row"]); +} + +#[test] +fn separates_inline_labels_when_a_container_edge_is_between_them() { + let doc = page("q 60 690 50 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 1 0 0 1 112 700 Tm (Outside) Tj ET", "Helvetica"); + + let blocks = text::text_blocks(&doc, 0).unwrap(); + + assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::>(), ["Panel", "Outside"]); +} diff --git a/crates/edit/src/place.rs b/crates/edit/src/place.rs index ae2faf8386..da7abc1862 100644 --- a/crates/edit/src/place.rs +++ b/crates/edit/src/place.rs @@ -306,11 +306,25 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation { /// Put a mark's content on a page: behind (with the behind-marks at the start) or on top /// (appended, after wrapping the original content in q/Q). -pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec, behind: bool) -> Result<(), EditError> { - place_tagged(doc, page, kind.tag(), content, behind)?; +pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec, behind: bool) -> Result { + let mark = place_tagged(doc, page, kind.tag(), content, behind)?; #[cfg(test)] fail_after_mark_placement(kind)?; - Ok(()) + Ok(mark) +} + +/// Put a mark's content on a page in the place of the stream at `at` in its `/Contents`: an +/// earlier mark of the same kind, which drew there in the state the content before it leaves, so +/// the new one needs no wrapper and keeps the old one's place among the page's other marks. +pub(crate) fn place_at(doc: &mut Document, page: &pdfcraft_model::Page, at: usize, kind: MarkKind, content: Vec) -> Result { + let mut list = contents(doc, page)?; + let mark_ref = doc.add(Object::Stream(Stream::flate(tagged(kind.tag()), &content))); + let slot = list.get_mut(at).ok_or_else(|| EditError::Invalid("the mark to replace is no longer on the page".into()))?; + *slot = Object::Ref(mark_ref); + doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?; + #[cfg(test)] + fail_after_mark_placement(kind)?; + Ok(mark_ref) } #[cfg(test)] @@ -461,29 +475,43 @@ fn too_deep_on_top() -> EditError { /// The refusal [`place_tagged`] gives for a mark on top of `page`, checked before an edit changes /// anything (removing old marks, adding resources) so a refused edit leaves the document as it was. pub(crate) fn check_on_top(doc: &Document, page: &pdfcraft_model::Page) -> Result<(), EditError> { - let obj = doc.get(page.obj); - let list = match obj.as_dict().and_then(|d| d.get(b"Contents")) { - None => return Ok(()), - Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]), - Some(Object::Array(a)) => a.clone(), - Some(other) => vec![other.clone()], - }; - match isolation(doc, &list) { + match isolation(doc, &content_list(doc, page)) { Isolation::TooDeep => Err(too_deep_on_top()), _ => Ok(()), } } +/// The streams of a page's /Contents, read without changing the document. +pub(crate) fn content_list(doc: &Document, page: &pdfcraft_model::Page) -> Vec { + let obj = doc.get(page.obj); + match obj.as_dict().and_then(|d| d.get(b"Contents")) { + None => Vec::new(), + Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]), + Some(Object::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + } +} + /// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original /// content and nothing else (a header's shrink). A page without a wrapper has no original content -/// on it and is left alone. -pub(crate) fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec) -> Result<(), EditError> { +/// on it and is left alone. Returns the new content stream, if one was placed. +pub(crate) fn place_inside_wrapper( + doc: &mut Document, + page: &pdfcraft_model::Page, + tag: &str, + content: Vec, +) -> Result, EditError> { let mut list = contents(doc, page)?; - let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(()) }; - let stream = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content)))); - list.insert(open + 1, stream); + let Some(open) = first_wrapper(doc, &list) else { return Ok(None) }; + let stream = doc.add(Object::Stream(Stream::flate(tagged(tag), &content))); + list.insert(open + 1, Object::Ref(stream)); doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?; - Ok(()) + Ok(Some(stream)) +} + +/// The first `Wrap`-tagged stream in `list`, which [`place_inside_wrapper`] puts content after. +pub(crate) fn first_wrapper(doc: &Document, list: &[Object]) -> Option { + list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) } /// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 893e598f6e..2a12148ede 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -6,6 +6,8 @@ use super::*; #[path = "mark_transaction_tests.rs"] mod mark_transactions; +#[path = "paragraph_grouping_tests.rs"] +mod paragraph_grouping; /// Three pages: an upright page with content that leaves the graphics state changed (an /// unbalanced `cm`), a page rotated 90° and one with inherited, shared resources. @@ -300,6 +302,263 @@ fn replace_and_remove_restore_the_original_content() { assert_eq!(streams(&reopen(&doc), 0), original, "back to exactly the original content"); } +fn with_text(text: &str) -> HeaderFooter { + let mut hf = HeaderFooter::default(); + hf.text[1] = text.into(); + hf +} + +/// #5785: Update could only reach the newest header and footer, and took every other one on +/// those pages with it. +#[test] +fn update_changes_one_header_and_footer_and_leaves_the_others() { + let mut doc = fixture(); + let (header, footer) = (with_text("Héader <<1>>"), with_text("Footer")); + add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0], &footer, false, &cx()).unwrap(); + // Listed after a save too, in the document's own words: tokens unexpanded, accents kept. + let doc = &mut reopen(&doc); + let found = header_footers(doc); + assert_eq!(found.iter().map(|m| (&m.settings, &m.pages[..])).collect::>(), [(&header, &[0][..]), (&footer, &[0][..])]); + // "Héader 1" is drawn with its é as an escape: what follows it is the old header's drawing. + assert!(streams(doc, 0).iter().any(|x| x.contains("ader 1)")), "{:?}", streams(doc, 0)); + + update_header_footer(doc, &found[0].settings, &[0], &with_text("New"), &cx()).unwrap(); + let s = streams(doc, 0); + assert!(s.iter().any(|x| x.contains("(New)")) && s.iter().any(|x| x.contains("(Footer)")), "{s:?}"); + assert!(!s.iter().any(|x| x.contains("ader 1)")), "the old header is gone: {s:?}"); + assert_eq!(header_footers(doc).len(), 2); + + let gone = update_header_footer(doc, &header, &[0], &with_text("Again"), &cx()); + assert!(matches!(gone, Err(EditError::Invalid(_))), "{gone:?}"); + assert!(streams(doc, 0).iter().any(|x| x.contains("(New)")), "a refused update changes nothing"); +} + +/// FredApps on #6352: an updated header and footer stays under the ones added after it, where +/// they overlap, as before the update, and its shrink is never taken for its place. +#[test] +fn update_keeps_the_header_and_footer_in_its_place_among_the_others() { + let mut doc = fixture(); + let (header, footer) = (HeaderFooter { shrink: true, ..with_text("Under") }, with_text("Over")); + add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0, 1], &footer, false, &cx()).unwrap(); + let at = |doc: &Document, page: usize, text: &str| streams(doc, page).iter().position(|x| x.contains(text)); + update_header_footer(&mut doc, &header, &[0, 1], &with_text("New"), &cx()).unwrap(); + let s = streams(&doc, 0); + assert!(at(&doc, 0, "(New)") < at(&doc, 0, "(Over)"), "still under the footer added after it: {s:?}"); + assert!(!s.iter().any(|x| x.contains("(Under)") || x.trim_end().ends_with(" cm")), "the old one and its shrink are gone: {s:?}"); + assert!(at(&doc, 1, "(New)") > at(&doc, 1, "(Over)"), "on a page it was not on, it goes on top"); +} + +/// Update's preview draws its draft between the two: the page under the header and footer it +/// replaces, and what is drawn over it. +#[test] +fn update_preview_layers_split_the_page_at_the_header_and_footer() { + let mut doc = fixture(); + let (old, later) = (with_text("Old"), with_text("Later")); + add_header_footer(&mut doc, &[0], &old, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0, 1], &later, false, &cx()).unwrap(); + let original = streams(&fixture(), 0); + + let mut under = doc.clone(); + assert!(under_header_footer(&mut under, &old).unwrap() > 0); + let s = streams(&under, 0); + assert!(!s.iter().any(|x| x.contains("(Old)") || x.contains("(Later)")), "{s:?}"); + assert!(original.iter().all(|o| s.contains(o)), "the page's own content stays: {s:?}"); + assert!(streams(&under, 1).iter().any(|x| x.contains("(Later)")), "a page without it is left as it is"); + + let mut over = doc.clone(); + assert_eq!(over_header_footer(&mut over, &old).unwrap(), 1); + let s = streams(&over, 0); + assert!(s.iter().any(|x| x.contains("(Later)")) && !s.iter().any(|x| x.contains("(Old)")), "{s:?}"); + assert!(!original.iter().any(|o| s.contains(o)), "nothing under it: {s:?}"); + assert!(streams(&over, 1).is_empty(), "where it is not, the new one goes on top"); + assert_eq!(over_header_footer(&mut doc.clone(), &later).unwrap(), 0, "nothing is over the newest"); +} + +#[test] +fn updating_a_shrinking_header_takes_its_shrink_away_too() { + let mut doc = fixture(); + let original = streams(&doc, 0); + let shrunk = HeaderFooter { shrink: true, ..with_text("Small") }; + add_header_footer(&mut doc, &[0], &shrunk, false, &cx()).unwrap(); + update_header_footer(&mut doc, &shrunk, &[0], &with_text("Plain"), &cx()).unwrap(); + let s = streams(&doc, 0); + assert_eq!(s.iter().filter(|x| x.contains("/PCMark")).count(), 1); + assert!(original.iter().all(|o| s.contains(o)), "{s:?}"); + assert_eq!(s.len(), original.len() + 3, "the original, one wrapper and the new mark: {s:?}"); +} + +/// A document with one header "Real" on page 1, and that header's stream. +fn one_recorded_header() -> (Document, pdfcraft_cos::ObjRef) { + let mut doc = fixture(); + add_header_footer(&mut doc, &[0], &with_text("Real"), false, &cx()).unwrap(); + let page = crate::page_list(&doc).swap_remove(0); + let marks: Vec<_> = crate::contents(&mut doc, &page) + .unwrap() + .iter() + .filter_map(Object::as_ref) + .filter(|r| doc.get(*r).as_dict().is_some_and(|d| d.contains(b"PCHeaderFooter"))) + .collect(); + assert_eq!(marks.len(), 1); + (doc, marks[0]) +} + +/// A change made to recorded settings, for [`settings_a_file_makes_up_are_not_listed`]. +type Change = Box; + +/// The recorded settings of `with_text("Real")`, changed by `change`. +fn real_settings_with(doc: &mut Document, change: impl FnOnce(&mut Document, &mut Dict)) -> Object { + let mut d = with_text("Real").to_object().as_dict().cloned().unwrap(); + change(doc, &mut d); + Object::Dict(d) +} + +#[test] +fn settings_a_file_makes_up_are_not_listed() { + let texts = |entries: Vec<&[u8]>| Object::Array(entries.into_iter().map(|t| Object::String(pdfcraft_cos::PdfString::literal(t))).collect()); + let long = vec![b'x'; 16 * 1024 + 1]; + let cases: Vec<(&str, Change)> = vec![ + ("not text", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1); 6])))), + ("five boxes", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b"a"[..]; 5])))), + ("a million boxes", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Null; 1_000_000])))), + ("a box too long", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..], &long[..], &b""[..], &b""[..], &b""[..], &b""[..]])))), + ("no text", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..]; 6])))), + ("undrawable", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::String(pdfcraft_cos::PdfString::text("中")); 6])))), + ("size not a number", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(f64::NAN)))), + ("size too big", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(300.0)))), + ("a negative margin", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(-1.0); 4])))), + ("three margins", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(1.0); 3])))), + ("a colour out of range", Box::new(|_, d| d.set(b"Color".to_vec(), Object::Array(vec![Object::Real(2.0); 3])))), + ("an unknown face", Box::new(|_, d| d.set(b"Font".to_vec(), Object::name("Comic")))), + ("a negative start", Box::new(|_, d| d.set(b"Start".to_vec(), Object::Int(-1)))), + ]; + for (what, change) in cases { + let (mut doc, mark) = one_recorded_header(); + let hostile = real_settings_with(&mut doc, change); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), hostile)).unwrap(); + assert!(header_footers(&doc).is_empty(), "{what}"); + assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "{what}: still a mark: Remove and page-wide Update reach it"); + assert_eq!(unrecorded_header_footer_pages(&doc), [0], "{what}"); + assert_eq!(newest_header_footer(&doc, 0), Some(None), "{what}"); + } +} + +/// #6352 review: listing read a header's settings again for every stream that recorded them, so a +/// file repeating one shared entry (or one stream) across its pages could make it slow. A scan now +/// reads each stream and each settings entry given by reference once, and still finds every page. +#[test] +fn settings_shared_by_many_streams_are_read_once_in_a_scan() { + let (mut doc, mark) = one_recorded_header(); + let settings = doc.get(mark).as_dict().unwrap().get(b"PCHeaderFooter").cloned().unwrap(); + let shared = Object::Ref(doc.add(settings)); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), shared)).unwrap(); + let Object::Stream(copy) = (*doc.get(mark)).clone() else { panic!("a stream") }; + // Page 0 draws the header's own stream 500 times; page 1 has 200 streams of its own, each + // recording the same settings by reference. + let mut first = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))]; + first.extend(std::iter::repeat_n(Object::Ref(mark), 500)); + let mut second = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))]; + second.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(copy.clone()))))); + doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(first))).unwrap(); + doc.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |d| d.set(b"Contents".to_vec(), Object::Array(second))).unwrap(); + crate::marks::DECODED.with(|n| n.set(0)); + let found = header_footers(&doc); + assert_eq!(crate::marks::DECODED.with(std::cell::Cell::get), 1, "the shared entry is read once"); + assert_eq!(found.len(), 1); + assert_eq!((found[0].pages.as_slice(), found[0].settings.text[1].as_str()), (&[0, 1][..], "Real")); + assert!(unrecorded_header_footer_pages(&doc).is_empty()); +} + +/// #6352 review: past the scan's text budget, settings went unread like a header that records +/// none, so a header and footer listed itself on only the pages before that, and Update removed +/// it from those alone. Update now refuses instead, and the unread ones are not offered as older. +#[test] +fn update_refuses_when_the_scan_cannot_find_every_page_of_a_header() { + let (mut doc, mark) = one_recorded_header(); + let pages = crate::page_list(&doc); + let Object::Stream(real) = (*doc.get(mark)).clone() else { panic!("a stream") }; + // Page 0: the real header, then 200 others recording 96 KiB of text each, past the budget. + let big = HeaderFooter { text: std::array::from_fn(|_| "x".repeat(16 * 1024)), ..HeaderFooter::default() }; + let mut heavy = real.clone(); + heavy.dict.set(b"PCHeaderFooter".to_vec(), big.to_object()); + let mut first = crate::contents(&mut doc, &pages[0]).unwrap(); + first.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(heavy.clone()))))); + // Page 1: the real header again, in a stream of its own, which the scan no longer reads. + let mut second = crate::contents(&mut doc, &pages[1]).unwrap(); + second.push(Object::Ref(doc.add(Object::Stream(real)))); + let page_refs: Vec<_> = pages.iter().map(|p| p.obj).collect(); + doc.update_dict(page_refs[0], |d| d.set(b"Contents".to_vec(), Object::Array(first.clone()))).unwrap(); + doc.update_dict(page_refs[1], |d| d.set(b"Contents".to_vec(), Object::Array(second.clone()))).unwrap(); + + let real = with_text("Real"); + let listed = header_footers(&doc); + assert_eq!(listed.iter().find(|m| m.settings == real).map(|m| m.pages.as_slice()), Some(&[0][..]), "the scan stops short"); + assert!(unrecorded_header_footer_pages(&doc).is_empty(), "settings it did not read are not offered as older ones"); + assert!(matches!(remove_header_footer(&mut doc, &real), Err(EditError::Invalid(_)))); + assert!(matches!(update_header_footer(&mut doc, &real, &[0], &with_text("New"), &cx()), Err(EditError::Invalid(_)))); + assert_eq!(crate::contents(&mut doc, &pages[0]).unwrap(), first, "page 0 is as it was"); + assert_eq!(crate::contents(&mut doc, &pages[1]).unwrap(), second, "and the header stays on page 1"); +} + +#[test] +fn settings_a_rewriting_tool_made_indirect_are_still_listed() { + let (mut doc, mark) = one_recorded_header(); + let indirect = real_settings_with(&mut doc, |doc, d| { + for key in [&b"Font"[..], b"Size", b"Start", b"Underline", b"Text"] { + let value = d.get(key).cloned().unwrap(); + d.set(key.to_vec(), Object::Ref(doc.add(value))); + } + let half = Object::Ref(doc.add(Object::Real(0.5))); + d.set(b"Color".to_vec(), Object::Array(vec![half.clone(), half.clone(), half])); + let margins = Object::Array(vec![Object::Ref(doc.add(Object::Real(36.0))), Object::Real(36.0), Object::Real(72.0), Object::Real(72.0)]); + d.set(b"Margins".to_vec(), Object::Ref(doc.add(margins))); + }); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), indirect)).unwrap(); + let found = header_footers(&doc); + assert_eq!(found.len(), 1); + assert_eq!(found[0].settings, HeaderFooter { color: [0.5; 3], ..with_text("Real") }); + assert!(unrecorded_header_footer_pages(&doc).is_empty()); +} + +#[test] +fn a_header_too_long_to_be_listed_is_not_added() { + // Every header add accepts is one the listing can name, so Update never has to fall back to + // replacing it page-wide. + let mut doc = fixture(); + let too_long = with_text(&"x".repeat(16 * 1024 + 1)); + assert!(matches!(add_header_footer(&mut doc, &[0], &too_long, false, &cx()), Err(EditError::Invalid(_)))); + assert!(marks_present(&doc).is_empty(), "nothing drawn"); + let longest = with_text(&"x".repeat(16 * 1024)); + add_header_footer(&mut doc, &[0], &longest, false, &cx()).unwrap(); + assert_eq!(header_footers(&doc).len(), 1, "the longest box add accepts is listed"); +} + +#[test] +fn a_header_added_with_an_out_of_range_colour_can_be_updated() { + let mut doc = fixture(); + let bright = HeaderFooter { color: [2.0, -1.0, 0.5], ..with_text("Bright") }; + add_header_footer(&mut doc, &[0], &bright, false, &cx()).unwrap(); + let found = header_footers(&doc); + assert_eq!(found.len(), 1, "listed with the colour it is drawn in"); + assert_eq!(found[0].settings.color, [1.0, 0.0, 0.5]); + update_header_footer(&mut doc, &found[0].settings, &[0], &with_text("Calm"), &cx()).unwrap(); + assert_eq!(header_footers(&doc).iter().map(|m| m.settings.text[1].as_str()).collect::>(), ["Calm"]); +} + +#[test] +fn the_newest_header_on_a_page_is_the_one_added_last() { + let mut doc = fixture(); + assert_eq!(newest_header_footer(&doc, 0), None); + let (first, second) = (HeaderFooter { shrink: true, ..with_text("First") }, HeaderFooter { shrink: true, ..with_text("Second") }); + add_header_footer(&mut doc, &[0, 1], &first, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0], &second, false, &cx()).unwrap(); + // The second shrink goes in ahead of the first, so content order alone would say First. + assert_eq!(newest_header_footer(&doc, 0), Some(Some(second))); + assert_eq!(newest_header_footer(&doc, 1), Some(Some(first))); + assert_eq!(newest_header_footer(&doc, 9), None); +} + /// The six numbers of the first `… cm` in `content`. fn first_cm(content: &str) -> [f64; 6] { let line = content.lines().find(|l| l.ends_with(" cm")).unwrap_or_else(|| panic!("no cm in {content:?}")); @@ -726,6 +985,173 @@ fn flattening_fields_drops_the_ones_on_no_page() { assert_eq!(left, [pdfcraft_cos::ObjRef::new(7, 0)], "only the hidden field on the page stays"); } +/// #2670: flattening form fields drops removed fields from `/AcroForm /CO` (calculation order) +/// and removes `/CO` once empty, and drops `/SigFlags` once no signature fields remain. +#[test] +fn flattening_fields_cleans_calculation_order_and_sigflags() { + let page = stream("", " "); + // Test 1: both fields flattened -> /Fields becomes empty, /CO and /SigFlags are removed. + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /Rect [10 50 150 80] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 2); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let fields = doc.resolve(af_dict.get(b"Fields").unwrap()); + assert_eq!(fields.as_array().unwrap().len(), 0, "no fields remain"); + assert!(!af_dict.contains(b"CO"), "empty calculation order was removed"); + assert!(!af_dict.contains(b"SigFlags"), "SigFlags was removed with no signature fields"); + + // Test 2: one field flattened, one surviving field -> /CO retains surviving field, SigFlags kept. + // The signature field has no appearance but is signed (a value), so it stays (#1794, #4017). + let mut doc2 = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R 6 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc1) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig_undrawable) /V << /Type /Sig >> /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream", + ]); + assert_eq!(flatten(&mut doc2, &[0], false, true).unwrap(), 1, "only calc1 with appearance is drawn"); + let doc2 = reopen(&doc2); + let root2 = doc2.root().unwrap(); + let af2 = doc2.resolve(doc2.get(root2).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict2 = af2.as_dict().unwrap(); + let co2 = doc2.resolve(af_dict2.get(b"CO").unwrap()); + let co_refs: Vec = co2.as_array().unwrap().iter().filter_map(|f| f.as_ref()).collect(); + assert_eq!(co_refs, [pdfcraft_cos::ObjRef::new(6, 0)], "only surviving field remains in /CO"); + assert!(af_dict2.contains(b"SigFlags"), "SigFlags kept because signature field survived"); +} + +/// #2670: removing an emptied `/CO` or an unneeded `/SigFlags` drops the key only. Both may be +/// indirect objects that something else also refers to, and those references must still resolve. +#[test] +fn flattening_keeps_shared_calculation_order_and_sigflags_objects() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO 9 0 R /SigFlags 8 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (kept) /V (Ada) /Ff 8 0 R /Order 9 0 R /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >> +stream + +endstream", + "3", + "[5 0 R]", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; kept has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + assert!(!af_dict.contains(b"CO"), "the emptied calculation order was removed"); + assert!(!af_dict.contains(b"SigFlags"), "SigFlags was removed with no signature field left"); + let kept = doc.get(pdfcraft_cos::ObjRef::new(6, 0)); + let kept = kept.as_dict().unwrap(); + assert_eq!(doc.resolve(kept.get(b"Ff").unwrap()).as_int(), Some(3), "the shared /SigFlags object still resolves"); + assert!(doc.resolve(kept.get(b"Order").unwrap()).as_array().is_some(), "the shared /CO array still resolves"); +} + +/// #2670: a calculation order that loses some fields but not all is shortened for the form alone. +/// Its indirect array may be shared, and the other references must still see the whole list. +#[test] +fn flattening_shortens_a_shared_calculation_order_without_changing_it() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO 8 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R] >>", + &page, + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (kept) /V (Ada) /Order 8 0 R /Rect [10 50 150 80] /F 4 >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >> +stream + +endstream", + "[5 0 R 6 0 R]", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; kept has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let co = doc.resolve(af.as_dict().unwrap().get(b"CO").expect("one field is left in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().map(|o| o.as_ref()).collect(); + assert_eq!(co, [Some(pdfcraft_cos::ObjRef::new(6, 0))], "the form's order keeps only the field that is left"); + let kept = doc.get(pdfcraft_cos::ObjRef::new(6, 0)); + let order = doc.resolve(kept.as_dict().unwrap().get(b"Order").unwrap()); + assert_eq!(order.as_array().map(|a| a.len()), Some(2), "the shared array still lists both fields"); +} + +/// #2670: a signature field kept deeper than the pruning cutoff still counts as left, so it keeps +/// its `/CO` entry and the form keeps `/SigFlags`. +#[test] +fn flattening_keeps_a_deep_signature_field_in_the_calculation_order_and_sigflags() { + let levels = 66; + let page = stream("", " "); + // 5: the flattened widget; 6…: the chain; then the signed widget at its end, on the page. + let leaf = 6 + levels; + let mut objs: Vec = vec![ + format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R] /CO [5 0 R {leaf} 0 R] /SigFlags 3 >> >>"), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R {leaf} 0 R] >>"), + page, + format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (calc) /Rect [10 10 150 40] /F 4 /AP << /N {} 0 R >> >>", leaf + 1), + ]; + for i in 0..levels { + objs.push(format!("<< /T (n{i}) /Kids [{} 0 R] >>", 7 + i)); + } + objs.push("<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /V << /Type /Sig >> /Rect [10 50 150 80] /F 4 >>".into()); + objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into()); + let objs: Vec<&str> = objs.iter().map(String::as_str).collect(); + let mut doc = build(&objs); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only calc is drawn; the signed field has no appearance"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let co = doc.resolve(af_dict.get(b"CO").expect("the deep field stays in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect(); + assert_eq!(co, [pdfcraft_cos::ObjRef::new(leaf as u32, 0)]); + assert!(af_dict.contains(b"SigFlags"), "the deep signature field is still there"); +} + +/// #2670: flattening every page takes a field on no page out of its kept parent's `/Kids`. Nothing +/// is drawn and `/Fields` keeps its length, but `/CO` and `/SigFlags` still lose that field. +#[test] +fn flattening_cleans_the_calculation_order_and_sigflags_of_an_orphan_under_a_kept_parent() { + let page = stream("", " "); + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /CO [6 0 R 7 0 R] /SigFlags 1 >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [6 0 R] >>", + &page, + "<< /FT /Tx /T (parent) /Kids [6 0 R 7 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /V (Ada) /Rect [10 10 150 40] /F 4 >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (orphan) /Parent 5 0 R /Rect [10 50 150 80] /F 4 >>", + ]); + assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 0, "the kept widget has no appearance to draw"); + let doc = reopen(&doc); + let root = doc.root().unwrap(); + let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap()); + let af_dict = af.as_dict().unwrap(); + let co = doc.resolve(af_dict.get(b"CO").expect("the kept widget stays in the calculation order")); + let co: Vec<_> = co.as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect(); + assert_eq!(co, [pdfcraft_cos::ObjRef::new(6, 0)], "the orphan left the calculation order"); + assert!(!af_dict.contains(b"SigFlags"), "no signature field is left"); +} + /// #1794: a form field whose widget has no usable appearance (none stored, or none for its /// selected state) has nothing to draw. Flattening used to remove it anyway, losing its value /// with no ink in its place. It stays, in the page and in the form, like a comment that can't be @@ -4769,6 +5195,866 @@ fn page_images_move_turn_replace_and_delete() { assert!(images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).is_err()); } +fn identifiable_test_image(bytes: &[u8]) -> Stream { + let mut d = Dict::new(); + for (k, v) in [ + (&b"Type"[..], Object::name("XObject")), + (b"Subtype", Object::name("Image")), + (b"Width", Object::Int(4)), + (b"Height", Object::Int(2)), + (b"ColorSpace", Object::name("DeviceGray")), + (b"BitsPerComponent", Object::Int(8)), + ] { + d.set(k.to_vec(), v); + } + Stream::from_raw(d, bytes.to_vec()) +} + +#[test] +fn deleting_or_replacing_an_image_unlinks_its_unreferenced_resource_on_full_save() { + const OLD: &[u8] = b"PRIVATE_IMAGE_BYTES_3499"; + const NEW: &[u8] = b"PUBLIC_IMAGE_BYTES_3511"; + + let mut deleted = image_page(); + let old = images::page_images(&deleted, 0).unwrap()[0].object.unwrap(); + deleted.set(old, Object::Stream(identifiable_test_image(OLD))); + images::change_image(&mut deleted, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&deleted, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(OLD.len()).any(|w| w == OLD), "deleted image data survived the full save"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(xobject(&saved, 0, b"Im0"), None, "deleted resource remains reachable from the page"); + + let mut replaced = image_page(); + let old = images::page_images(&replaced, 0).unwrap()[0].object.unwrap(); + replaced.set(old, Object::Stream(identifiable_test_image(OLD))); + let new = replaced.add(Object::Stream(identifiable_test_image(NEW))); + images::change_image(&mut replaced, 0, 0, &images::ImageChange::Replace(new)).unwrap(); + let bytes = write_full(&replaced, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(OLD.len()).any(|w| w == OLD), "replaced image data survived the full save"); + assert!(bytes.windows(NEW.len()).any(|w| w == NEW), "replacement image data is missing"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let images = images::page_images(&saved, 0).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, format!("PCImg{}", new.num)); + assert!(images[0].object.is_some()); +} + +#[test] +fn deleting_one_of_two_placements_keeps_the_resource_still_in_use() { + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q q 200 0 0 100 300 100 cm /Im0 Do Q"); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert!(xobject(&saved, 0, b"Im0").is_some()); +} + +#[test] +fn deleting_a_page_image_keeps_it_when_a_nested_resource_less_form_inherits_it() { + const PRIVATE: &[u8] = b"PRIVATE_NESTED_FORM_IMAGE"; + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q /Bare Do"); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut form = Dict::new(); + form.set(b"Subtype".to_vec(), Object::name("Form")); + form.set(b"BBox".to_vec(), Object::Array([0, 0, 300, 300].map(Object::Int).to_vec())); + form.set(b"Resources".to_vec(), Object::Null); + let inner = doc.add(Object::Stream(Stream::flate(form.clone(), b"/Im0 Do"))); + let outer = doc.add(Object::Stream(Stream::flate(form, b"/Inner Do"))); + let page = pdfcraft_model::pages(&doc)[0].obj; + let mut resources = doc.get(page).as_dict().unwrap().get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Inner".to_vec(), Object::Ref(inner)); + xobjects.set(b"Bare".to_vec(), Object::Ref(outer)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + let contents = doc.add(Object::Stream(Stream::flate(Dict::new(), b"q 200 0 0 100 100 100 cm /Im0 Do Q /Bare Do"))); + doc.update_dict(page, |d| { + d.set(b"Resources".to_vec(), Object::Dict(resources)); + d.set(b"Contents".to_vec(), Object::Ref(contents)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE), "the nested form's image was lost"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_some(), "the page resource inherited by the Form was removed"); + assert_eq!(images::reading_images(&saved, 0).unwrap().len(), 1); +} + +#[test] +fn deleting_an_image_with_too_many_aliases_skips_optional_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_HIGH_ALIAS_COUNT_IMAGE"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(PRIVATE))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + for i in 0..256 { + xobjects.set(format!("Alias{i}").into_bytes(), Object::Ref(image)); + } + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE), "over-limit optional pruning unexpectedly removed the image"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(images::page_images(&saved, 0).unwrap().is_empty()); + assert!(xobject(&saved, 0, b"Alias0").is_some()); +} + +fn set_image_content(doc: &mut Document, page: usize, pieces: &[&[u8]]) { + let page = pdfcraft_model::pages(doc)[page].obj; + let contents = pieces.iter().map(|data| Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), data))))).collect::>(); + doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap(); +} + +fn add_blank_page(doc: &mut Document, resources: Option) { + let mut page = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Page")), + (b"Parent".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(2, 0))), + (b"MediaBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())), + ]); + if let Some(resources) = resources { + page.set(b"Resources".to_vec(), resources); + } + let added = doc.add(Object::Dict(page)); + doc.update_dict(pdfcraft_cos::ObjRef::new(2, 0), |d| { + d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(pdfcraft_cos::ObjRef::new(3, 0)), Object::Ref(added)])); + d.set(b"Count".to_vec(), Object::Int(2)); + }) + .unwrap(); +} + +fn image_pruning_fixture(blank_resources: Option>, font_count: usize, private: &[u8]) -> Document { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(private))); + if let Some(resources) = blank_resources { + add_blank_page(&mut doc, resources); + } + if font_count > 0 { + let mut fonts = doc + .get(pdfcraft_model::pages(&doc)[0].obj) + .as_dict() + .and_then(|d| d.get(b"Resources")) + .and_then(Object::as_dict) + .and_then(|d| d.get(b"Font")) + .and_then(Object::as_dict) + .cloned() + .unwrap_or_default(); + for index in 0..font_count { + let font = doc.add(Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type1")), + (b"BaseFont".to_vec(), Object::name("Helvetica")), + (b"FirstChar".to_vec(), Object::Int(32)), + (b"LastChar".to_vec(), Object::Int(255)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(500); 224])), + ]))); + fonts.set(format!("ReviewFont{index}").into_bytes(), Object::Ref(font)); + } + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set(b"Font".to_vec(), Object::Dict(fonts)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + } + doc +} + +#[test] +fn deleted_image_is_kept_when_reachable_through_each_non_page_consumer() { + const PRIVATE: &[u8] = b"PRIVATE_CONTEXT_IMAGE"; + + // Type 3 CharProc content uses the caller's resource scope when the font has no Resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + let mut charprocs = Dict::new(); + charprocs.set(b"A".to_vec(), Object::Ref(glyph)); + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type3")); + font.set(b"CharProcs".to_vec(), Object::Dict(charprocs)); + let font = doc.add(Object::Dict(font)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut fonts = resources.get(b"Font").and_then(Object::as_dict).cloned().unwrap(); + fonts.set(b"T3".to_vec(), Object::Ref(font)); + resources.set(b"Font".to_vec(), Object::Dict(fonts)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q BT /T3 10 Tf (A) Tj ET"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // A selected soft mask's Form inherits the page's resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let form = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([(b"Subtype".to_vec(), Object::name("Form")), (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec()))]), + b"/Im0 Do", + ))); + let mut soft_mask = Dict::new(); + soft_mask.set(b"G".to_vec(), Object::Ref(form)); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::Dict(soft_mask)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut states = Dict::new(); + states.set(b"GS".to_vec(), Object::Dict(gs)); + resources.set(b"ExtGState".to_vec(), Object::Dict(states)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // A used tiling Pattern can draw an image with its caller's resources. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut pattern_dict = Dict::new(); + for (key, value) in [ + (&b"PatternType"[..], Object::Int(1)), + (b"PaintType", Object::Int(1)), + (b"TilingType", Object::Int(1)), + (b"BBox", Object::Array([0, 0, 1, 1].map(Object::Int).to_vec())), + (b"XStep", Object::Int(1)), + (b"YStep", Object::Int(1)), + ] { + pattern_dict.set(key.to_vec(), value); + } + let pattern = doc.add(Object::Stream(Stream::flate(pattern_dict, b"/Im0 Do"))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut patterns = Dict::new(); + patterns.set(b"P".to_vec(), Object::Ref(pattern)); + resources.set(b"Pattern".to_vec(), Object::Dict(patterns)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q 0 /P scn 0 0 10 10 re f"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } + + // Every annotation appearance state is a consumer, even if it is not the normal state. + { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let form = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 10, 10].map(Object::Int).to_vec())), + ]), + b"/Im0 Do", + ))); + let mut states = Dict::new(); + states.set(b"Off".to_vec(), Object::Ref(form)); + let mut ap = Dict::new(); + ap.set(b"D".to_vec(), Object::Dict(states)); + let mut annotation = Dict::new(); + annotation.set(b"AP".to_vec(), Object::Dict(ap)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Dict(annotation)]))).unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); + } +} + +#[test] +fn deleted_image_census_joins_content_pieces_and_checks_each_page_scope() { + const PRIVATE: &[u8] = b"PRIVATE_SCOPED_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Im0", b" Do"]); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "the retained second Do spans content pieces" + ); + + // A shared Form is evaluated in each caller's effective resource scope. The first page maps + // /Im0 to a different image; the second page maps it to the deleted target. + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let other = doc.add(Object::Stream(identifiable_test_image(b"OTHER_SCOPED_IMAGE"))); + let shared = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec())), + (b"Resources".to_vec(), Object::Null), + ]), + b"/Im0 Do", + ))); + let page0 = pdfcraft_model::pages(&doc)[0].obj; + let mut res0 = doc.get(page0).as_dict().unwrap().get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xo0 = res0.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xo0.set(b"Target".to_vec(), Object::Ref(target)); + xo0.set(b"Other".to_vec(), Object::Ref(other)); + xo0.set(b"Im0".to_vec(), Object::Ref(other)); + xo0.set(b"Shared".to_vec(), Object::Ref(shared)); + res0.set(b"XObject".to_vec(), Object::Dict(xo0)); + doc.update_dict(page0, |d| { + d.set(b"Resources".to_vec(), Object::Dict(res0)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"/Target Do /Shared Do"]); + let page1_contents = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Shared Do"))); + let page1 = doc.add(Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Page")), + (b"Parent".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(2, 0))), + (b"MediaBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec())), + ( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([( + b"XObject".to_vec(), + Object::Dict(Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target)), (b"Shared".to_vec(), Object::Ref(shared))])), + )])), + ), + (b"Contents".to_vec(), Object::Ref(page1_contents)), + ]))); + doc.update_dict(pdfcraft_cos::ObjRef::new(2, 0), |d| { + let mut kids = d.get(b"Kids").and_then(Object::as_array).cloned().unwrap(); + kids.push(Object::Ref(page1)); + d.set(b"Kids".to_vec(), Object::Array(kids)); + d.set(b"Count".to_vec(), Object::Int(2)); + }) + .unwrap(); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 2); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "the same Form must use page one's different inherited scope" + ); +} + +#[test] +fn extgstate_selected_type3_font_keeps_its_glyph_image_after_page_image_delete() { + const PRIVATE: &[u8] = b"PRIVATE_GSTATE_TYPE3_GLYPH_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/GlyphImg Do"))); + let mut charprocs = Dict::new(); + charprocs.set(b"A".to_vec(), Object::Ref(glyph)); + let glyph_resources = Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"GlyphImg".to_vec(), Object::Ref(target))])))]); + let mut font_dict = Dict::new(); + for (key, value) in [ + (&b"Type"[..], Object::name("Font")), + (b"Subtype", Object::name("Type3")), + (b"FontBBox", Object::Array([0, 0, 1000, 1000].map(Object::Int).to_vec())), + (b"FontMatrix", Object::Array(vec![Object::Int(1), Object::Int(0), Object::Int(0), Object::Int(1), Object::Int(0), Object::Int(0)])), + (b"FirstChar", Object::Int(65)), + (b"LastChar", Object::Int(65)), + (b"Widths", Object::Array(vec![Object::Int(1000)])), + (b"Encoding", Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(65), Object::name("A")]))]))), + (b"CharProcs", Object::Dict(charprocs)), + (b"Resources", Object::Dict(glyph_resources)), + ] { + font_dict.set(key.to_vec(), value); + } + let font = doc.add(Object::Dict(font_dict)); + let ext_gstate = Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Array(vec![Object::Ref(font), Object::Int(10)]))])); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), ext_gstate)]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs BT (A) Tj ET"]); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let page = pdfcraft_model::pages(&saved)[0].clone(); + let resources = page.dict.get(b"Resources").map(|o| saved.resolve(o)).unwrap(); + let ext_gstates = resources.as_dict().unwrap().get(b"ExtGState").map(|o| saved.resolve(o)).unwrap(); + let selected = ext_gstates.as_dict().unwrap().get(b"GS").map(|o| saved.resolve(o)).unwrap(); + let font_ref = selected.as_dict().unwrap().get(b"Font").map(|o| saved.resolve(o)).unwrap().as_array().unwrap()[0].as_ref().unwrap(); + let font = saved.get(font_ref); + let charproc_ref = + font.as_dict().unwrap().get(b"CharProcs").map(|o| saved.resolve(o)).unwrap().as_dict().unwrap().get(b"A").unwrap().as_ref().unwrap(); + let charproc = saved.get(charproc_ref); + let glyph_content = match charproc.as_ref() { + Object::Stream(stream) => String::from_utf8_lossy(&stream.decoded().unwrap()).into_owned(), + _ => String::new(), + }; + assert!(glyph_content.contains("/GlyphImg Do")); + let font_resources = font.as_dict().unwrap().get(b"Resources").map(|o| saved.resolve(o)).unwrap(); + let glyph_image = font_resources.as_dict().unwrap().get(b"XObject").map(|o| saved.resolve(o)).unwrap(); + // A full save renumbers the objects it keeps, so the alias is followed to the payload rather + // than compared with the number the image had in the document being edited. + let kept = glyph_image.as_dict().unwrap().get(b"GlyphImg").and_then(Object::as_ref).expect("the glyph keeps its image alias"); + let Object::Stream(kept) = &*saved.get(kept) else { panic!("the glyph's image alias points at a stream") }; + assert!(kept.raw.windows(PRIVATE.len()).any(|w| w == PRIVATE), "the glyph keeps the image it draws"); +} + +#[test] +fn appearance_dictionary_dag_exhaustion_skips_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_APPEARANCE_DAG_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut child = doc.add(Object::Dict(Dict::new())); + for _ in 0..30 { + child = doc.add(Object::Dict(Dict::from_iter([(b"Left".to_vec(), Object::Ref(child)), (b"Right".to_vec(), Object::Ref(child))]))); + } + let appearance = Dict::from_iter([(b"N".to_vec(), Object::Ref(child))]); + let annotation = Dict::from_iter([(b"AP".to_vec(), Object::Dict(appearance))]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Dict(annotation)]))).unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn unused_image_mask_dependency_is_removed_before_full_save() { + const PRIVATE: &[u8] = b"PRIVATE_UNUSED_IMAGE_MASK_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + let mut unused_image = identifiable_test_image(b"INACTIVE_IMAGE_OWNER"); + unused_image.dict.set(b"SMask".to_vec(), Object::Ref(target)); + let unused = doc.add(Object::Stream(unused_image)); + let mut mask_owner = identifiable_test_image(b"INACTIVE_MASK_OWNER"); + mask_owner.dict.set(b"Mask".to_vec(), Object::Ref(target)); + let mask_owner = doc.add(Object::Stream(mask_owner)); + let mut alternate = Dict::new(); + alternate.set(b"Image".to_vec(), Object::Ref(target)); + let mut alternate_owner = identifiable_test_image(b"INACTIVE_ALTERNATE_OWNER"); + alternate_owner.dict.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)])); + let alternate_owner = doc.add(Object::Stream(alternate_owner)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Unused".to_vec(), Object::Ref(unused)); + xobjects.set(b"MaskOwner".to_vec(), Object::Ref(mask_owner)); + xobjects.set(b"AlternateOwner".to_vec(), Object::Ref(alternate_owner)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + let unused = saved.get(xobject(&saved, 0, b"Unused").unwrap()); + assert!(matches!(unused.as_ref(), Object::Stream(stream) if stream.dict.get(b"SMask").is_none())); + let mask_owner = saved.get(xobject(&saved, 0, b"MaskOwner").unwrap()); + assert!(matches!(mask_owner.as_ref(), Object::Stream(stream) if stream.dict.get(b"Mask").is_none())); + let alternate_owner = saved.get(xobject(&saved, 0, b"AlternateOwner").unwrap()); + assert!( + matches!(alternate_owner.as_ref(), Object::Stream(stream) if stream.dict.get(b"Alternates").and_then(Object::as_array).is_some_and(Vec::is_empty)) + ); +} + +#[test] +fn deleting_image_prunes_unused_shared_resources_across_all_pages() { + const PRIVATE: &[u8] = b"PRIVATE_UNUSED_SHARED_IMAGE"; + let mut doc = fixture(); + let target = doc.add(Object::Stream(identifiable_test_image(PRIVATE))); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| { + let mut xobjects = Dict::new(); + xobjects.set(b"Im0".to_vec(), Object::Ref(target)); + d.set(b"XObject".to_vec(), Object::Dict(xobjects)); + }) + .unwrap(); + let content = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Ref(content))).unwrap(); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 1); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 1, b"Im0").is_none()); +} + +#[test] +fn image_payload_pruning_handles_missing_resources_and_wide_scalar_arrays() { + const PRIVATE: &[u8] = b"PRIVATE_REVIEW_DELETED_IMAGE_PAYLOAD"; + for (resources, font_count) in [(Some(None), 0), (Some(Some(Object::Dict(Dict::new()))), 0), (None, 225)] { + for replace in [false, true] { + let mut source = image_pruning_fixture(resources.clone(), font_count, PRIVATE); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + source = Document::open(Arc::new(input)).unwrap(); + let change = if replace { + images::ImageChange::Replace(source.add(Object::Stream(identifiable_test_image(b"PUBLIC_REPLACEMENT")))) + } else { + images::ImageChange::Delete + }; + images::change_image(&mut source, 0, 0, &change).unwrap(); + + let output = write_full(&source, &SaveOptions::default()).unwrap(); + let reopened = Document::open(Arc::new(output.clone())).unwrap(); + assert!(!output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "replace={replace}, resources={resources:?}, fonts={font_count}"); + assert_eq!(images::page_images(&reopened, 0).unwrap().len(), usize::from(replace)); + } + } +} + +#[test] +fn malformed_present_page_resources_keep_image_payload() { + const PRIVATE: &[u8] = b"PRIVATE_MALFORMED_RESOURCES_IMAGE"; + let mut source = image_pruning_fixture(None, 0, PRIVATE); + add_blank_page(&mut source, Some(Object::Int(7))); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + let mut source = Document::open(Arc::new(input)).unwrap(); + + images::change_image(&mut source, 0, 0, &images::ImageChange::Delete).unwrap(); + let output = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "malformed present Resources unexpectedly allowed pruning"); +} + +#[test] +fn rewrite_entry_budget_failure_keeps_earlier_staged_image_mappings() { + const PRIVATE: &[u8] = b"PRIVATE_REWRITE_BUDGET_IMAGE"; + const OVERSIZED_CONTAINER: usize = 100_001; + let mut source = image_pruning_fixture(None, 0, PRIVATE); + let form = source.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Form")), + (b"BBox".to_vec(), Object::Array([0, 0, 10, 10].map(Object::Int).to_vec())), + (b"Probe".to_vec(), Object::Array(vec![Object::Int(0); OVERSIZED_CONTAINER])), + ]), + b"", + ))); + let page = pdfcraft_model::pages(&source)[0].obj; + source + .update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"F".to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut source, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /F Do"]); + let input = write_full(&source, &SaveOptions::default()).unwrap(); + assert!(input.windows(PRIVATE.len()).any(|window| window == PRIVATE), "fixture lacked payload before editing"); + let mut source = Document::open(Arc::new(input)).unwrap(); + + images::change_image(&mut source, 0, 0, &images::ImageChange::Delete).unwrap(); + let output = write_full(&source, &SaveOptions::default()).unwrap(); + let reopened = Document::open(Arc::new(output.clone())).unwrap(); + assert!(output.windows(PRIVATE.len()).any(|window| window == PRIVATE), "rewrite budget failure pruned image payload"); + assert!(xobject(&reopened, 0, b"Im0").is_some(), "partial staging removed the page's image alias"); +} + +#[test] +fn image_mask_dependency_keeps_a_deleted_image_live() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_MASK_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut dependent = Dict::new(); + dependent.set(b"Type".to_vec(), Object::name("XObject")); + dependent.set(b"Subtype".to_vec(), Object::name("Image")); + dependent.set(b"Width".to_vec(), Object::Int(1)); + dependent.set(b"Height".to_vec(), Object::Int(1)); + dependent.set(b"ColorSpace".to_vec(), Object::name("DeviceGray")); + dependent.set(b"BitsPerComponent".to_vec(), Object::Int(8)); + dependent.set(b"SMask".to_vec(), Object::Ref(target)); + let dependent = doc.add(Object::Stream(Stream::from_raw(dependent, vec![1]))); + let mut chain_owner = Dict::new(); + chain_owner.set(b"Type".to_vec(), Object::name("XObject")); + chain_owner.set(b"Subtype".to_vec(), Object::name("Image")); + chain_owner.set(b"Width".to_vec(), Object::Int(1)); + chain_owner.set(b"Height".to_vec(), Object::Int(1)); + chain_owner.set(b"ColorSpace".to_vec(), Object::name("DeviceGray")); + chain_owner.set(b"BitsPerComponent".to_vec(), Object::Int(8)); + chain_owner.set(b"SMask".to_vec(), Object::Ref(dependent)); + let chain_owner = doc.add(Object::Stream(Stream::from_raw(chain_owner, vec![1]))); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Source Do"]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Source".to_vec(), Object::Ref(chain_owner)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn malformed_extgstate_soft_masks_skip_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_EXTGSTATE_IMAGE"; + let cases = [ + ("unresolved reference", Object::Ref(pdfcraft_cos::ObjRef::new(999_999, 0))), + ("non-dictionary", Object::String(pdfcraft_cos::PdfString::text("bad mask"))), + ("missing group", Object::Dict(Dict::new())), + ("malformed group", Object::Dict(Dict::from_iter([(b"G".to_vec(), Object::Int(7))]))), + ]; + + for (case, mask) in cases { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), mask); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "{case} fixture lacked payload before edit" + ); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "{case} unexpectedly allowed pruning"); + } + + // `/None` is the valid ExtGState spelling for no soft mask and does not block pruning. + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::name("None")); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + assert!( + write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), + "valid /None fixture lacked payload before edit" + ); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "valid /None prevented pruning"); +} + +#[test] +fn image_typed_soft_mask_group_skips_optional_image_pruning() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_TYPED_SOFT_MASK_GROUP"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + + // The renderer decodes `/G` as a Form regardless of its declared subtype. Its content + // inherits the page resources, so the image remains a live consumer despite the bad type. + let group = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([(b"Subtype".to_vec(), Object::name("Image")), (b"BBox".to_vec(), Object::Array([0, 0, 1, 1].map(Object::Int).to_vec()))]), + b"/Im0 Do", + ))); + let mut soft_mask = Dict::new(); + soft_mask.set(b"G".to_vec(), Object::Ref(group)); + let mut gs = Dict::new(); + gs.set(b"SMask".to_vec(), Object::Dict(soft_mask)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"ExtGState".to_vec(), Object::Dict(Dict::from_iter([(b"GS".to_vec(), Object::Dict(gs))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /GS gs"]); + + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), "fixture lacked payload before edit"); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "malformed image-typed SMask group unexpectedly allowed pruning"); +} + +#[test] +fn late_image_prune_staging_failure_does_not_partially_rewrite_resources() { + const PRIVATE: &[u8] = b"PRIVATE_LATE_PRUNE_FAILURE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE), "fixture lacked payload before edit"); + + // This valid candidate is staged for removal before the later deeply nested object + // exceeds the rewrite walk budget. Nothing staged may be committed after that failure. + let holder = + doc.add(Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Alias".to_vec(), Object::Ref(target))])))]))); + let mut deep = Object::Null; + for _ in 0..=65 { + deep = Object::Array(vec![deep]); + } + doc.add(deep); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let holder = doc.resolve(&Object::Ref(holder)); + assert_eq!( + holder.as_dict().and_then(|d| d.get(b"XObject")).and_then(Object::as_dict).and_then(|d| d.get(b"Alias")).and_then(Object::as_ref), + Some(target) + ); + let saved = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(saved.windows(PRIVATE.len()).any(|w| w == PRIVATE), "failed optional prune partially removed the image payload"); +} + +#[test] +fn image_alternate_dependency_keeps_a_deleted_image_live() { + const PRIVATE: &[u8] = b"PRIVATE_IMAGE_ALTERNATE_DEPENDENCY"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut alternate = Dict::new(); + alternate.set(b"Image".to_vec(), Object::Ref(target)); + let mut primary = identifiable_test_image(b"PRIMARY_IMAGE"); + primary.dict.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)])); + let primary = doc.add(Object::Stream(primary)); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Source Do"]); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Source".to_vec(), Object::Ref(primary)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn unsupported_resource_consumer_skips_optional_pruning_but_keeps_edit_successful() { + const PRIVATE: &[u8] = b"PRIVATE_UNSUPPORTED_CONTEXT_IMAGE"; + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(PRIVATE))); + let mut unknown = Dict::new(); + unknown.set(b"Subtype".to_vec(), Object::name("UnknownContent")); + unknown.set( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target))])))])), + ); + doc.add(Object::Stream(Stream::flate(unknown, b"/Im0 Do"))); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|w| w == PRIVATE)); +} + +#[test] +fn deleting_one_page_image_preserves_shared_inherited_resources_used_by_sibling_pages() { + const SHARED: &[u8] = b"SHARED_INHERITED_IMAGE"; + let mut doc = fixture(); + let image = doc.add(Object::Stream(identifiable_test_image(SHARED))); + doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| { + let mut xobjects = Dict::new(); + xobjects.set(b"Im0".to_vec(), Object::Ref(image)); + d.set(b"XObject".to_vec(), Object::Dict(xobjects)); + }) + .unwrap(); + doc.set(pdfcraft_cos::ObjRef::new(7, 0), Object::Stream(Stream::flate(Dict::new(), b"/Im0 Do"))); + assert_eq!(images::page_images(&doc, 0).unwrap().len(), 1); + assert_eq!(images::page_images(&doc, 1).unwrap().len(), 1); + + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert!(images::page_images(&saved, 0).unwrap().is_empty()); + assert_eq!(images::page_images(&saved, 1).unwrap().len(), 1); + // Both pages inherit the same resource dictionary. Keep its mapping while the sibling page + // still draws the image; removing it would break that live use. + assert!(xobject(&saved, 0, b"Im0").is_some()); + assert!(xobject(&saved, 1, b"Im0").is_some()); +} + +#[test] +fn replacing_an_image_with_the_same_object_keeps_the_replacement_reachable() { + const SAME: &[u8] = b"SAME_IMAGE_OBJECT"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(SAME))); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Replace(image)).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(SAME.len()).any(|w| w == SAME)); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert_eq!(images::page_images(&saved, 0).unwrap()[0].name, format!("PCImg{}", image.num)); +} + +#[test] +fn deleting_an_image_prunes_unused_aliases_when_no_alias_is_drawn_and_keeps_live_aliases() { + const ALIASED: &[u8] = b"ALIASED_IMAGE_BYTES"; + let mut doc = image_page(); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(ALIASED))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"UnusedAlias".to_vec(), Object::Ref(image)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(ALIASED.len()).any(|w| w == ALIASED), "an unused alias kept the deleted image reachable"); + let saved = Document::open(Arc::new(bytes)).unwrap(); + assert!(xobject(&saved, 0, b"Im0").is_none()); + assert!(xobject(&saved, 0, b"UnusedAlias").is_none()); + + let mut doc = image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q /Alias Do"); + let image = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(image, Object::Stream(identifiable_test_image(ALIASED))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + let mut xobjects = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + xobjects.set(b"Alias".to_vec(), Object::Ref(image)); + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + images::change_image(&mut doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap(); + assert_eq!(images::page_images(&saved, 0).unwrap().len(), 1); + assert!(xobject(&saved, 0, b"Im0").is_some()); + assert!(xobject(&saved, 0, b"Alias").is_some()); +} + #[test] fn image_arrange_stacking_order_and_remove_crop() { let content = "q 100 0 0 100 100 100 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (Middle Text) Tj ET q 150 0 0 150 200 200 cm /Im0 Do Q"; @@ -9590,12 +10876,13 @@ fn japanese_paragraphs_wrap_between_characters_without_closing_marks_at_a_row_st #[test] fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { - // Each row has its own background box drawn immediately before its BT..ET, as cards and - // highlighted headings exported from LibreOffice or browsers do (#2377). - let card = "0 0.45 0.25 rg 60 696 240 16 re f BT /F1 10 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \ - 0 0.45 0.25 rg 60 668 240 24 re f BT /F1 16 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \ - 0 0.45 0.25 rg 60 632 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \ - 0 0.45 0.25 rg 60 596 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET"; + // Layered paragraph-wide backgrounds still paint between rows (#2377), but every row has + // the same container membership. Compatible size changes retain the mixed-style rewrite + // without asking the grouping heuristic to merge independent panels or headings. + let card = "0 0.45 0.25 rg 60 540 240 180 re f BT /F1 16 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 20 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \ + 0 0.45 0.25 rg 60 540 240 180 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET"; let shown_at = |ops: &[pdfcraft_content::Op], needle: &str| { ops.iter() .position(|op| { @@ -9608,6 +10895,13 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { // 1. Editing the title rows emits all rewritten rows after all four background fills. let mut doc = text_page(card); assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 1); + let source_ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops; + let source_fills: Vec = source_ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect(); + assert_eq!(source_fills.len(), 4); + for (row, needle) in ["SEMINARIO", "pratica:", "metodo", "complesso"].iter().enumerate() { + let shown = shown_at(&source_ops, needle); + assert!(source_fills[row] < shown && source_fills.get(row + 1).is_none_or(|next| shown < *next), "backgrounds must stay interleaved"); + } let edited = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto nuovo"; text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap(); let doc = reopen(&doc); @@ -9643,6 +10937,9 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { let wrapped_edit = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio e metodo approfondito\nun progetto complesso"; text::rewrite_block(&mut doc, 0, 0, Some(wrapped_edit), &text::BlockStyle::default()).unwrap(); let doc = reopen(&doc); + let wrapped = text::text_blocks(&doc, 0).unwrap(); + assert!(wrapped[0].rows.len() > 4, "the long edit must wrap and push the suffix row down"); + assert_eq!(wrapped[0].text, wrapped_edit.replace('\n', " ")); let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops; let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap(); assert!( @@ -9652,8 +10949,8 @@ fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() { // 4. Single-style paragraph path across a CTM change between rows, with movement, underline, // and a trailing unrelated line sharing the second row's BT..ET. - let cross_ctm = "0.9 0.9 0.2 rg 60 696 240 18 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \ - q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 668 240 18 re f \ + let cross_ctm = "0.9 0.9 0.2 rg 60 676 240 38 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \ + q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 664 240 38 re f \ BT /F1 12 Tf 0 0 0 rg 54 672 Td (Second highlighted row) Tj 246 -40 Td (Side footer) Tj ET Q"; let mut doc = text_page(cross_ctm); let para = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.starts_with("First highlighted")).unwrap(); @@ -10867,6 +12164,225 @@ fn reading_keeps_dotted_leader_entries_whole_and_in_order() { ); } +/// #3803: Tesseract and PDFium write invisible (`3 Tr`) OCR layers in a `/Glyphless` CIDFontType2 +/// whose `/ToUnicode` and `/W` cover Latin text while `/CIDToGIDMap` maps every CID to GID 1 (a +/// solid rectangle). Rewriting such text as visible (`0 Tr`) must substitute a real font rather +/// than drawing the replacement in `/Glyphless` rectangles. +#[test] +fn editing_glyphless_ocr_text_substitutes_a_visible_font() { + let mut one_glyph_ttf = include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec(); + let count = u16::from_be_bytes(one_glyph_ttf[4..6].try_into().unwrap()) as usize; + let loca_rec = (0..count).map(|i| 12 + i * 16).find(|i| &one_glyph_ttf[*i..*i + 4] == b"loca").unwrap(); + let loca_off = u32::from_be_bytes(one_glyph_ttf[loca_rec + 8..loca_rec + 12].try_into().unwrap()) as usize; + let loca_len = u32::from_be_bytes(one_glyph_ttf[loca_rec + 12..loca_rec + 16].try_into().unwrap()) as usize; + one_glyph_ttf[loca_off..loca_off + 8].fill(0); + for chunk in one_glyph_ttf[loca_off + 8..loca_off + loca_len].as_chunks_mut::<4>().0 { + *chunk = 4u32.to_be_bytes(); + } + + let make_page = |content: &str, base: &str| { + let mut doc = text_page(content); + let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256)))); + let cmap = b"1 begincodespacerange <0000> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange"; + let unicode = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap))); + let descriptor = Dict::from_iter([ + (b"Type".to_vec(), Object::name("FontDescriptor")), + (b"FontName".to_vec(), Object::name(base)), + (b"Flags".to_vec(), Object::Int(5)), + (b"FontBBox".to_vec(), Object::Array([0, -207, 500, 718].map(Object::Int).to_vec())), + (b"Ascent".to_vec(), Object::Int(718)), + (b"Descent".to_vec(), Object::Int(-207)), + (b"FontFile2".to_vec(), Object::Ref(program)), + ]); + let cid_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid)), + (b"DW".to_vec(), Object::Int(500)), + (b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])])), + (b"FontDescriptor".to_vec(), Object::Dict(descriptor)), + ]); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name(base)), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid_font)])), + (b"ToUnicode".to_vec(), Object::Ref(unicode)), + ]); + let p = pdfcraft_model::pages(&doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(font))]); + doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + doc + }; + + // Single-line OCR paragraph (rewrite_block_from path) and replace_line path. + let single = "BT 3 Tr 0.055 Tw -0.581 Tc 100 Tz /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm \ + [<0044> -27 <0065> -23 <0020> -22 <006B> -29 <0069> -28 <006E> -27 <0064> -29 <0065> -23 <0072> -28 <0065> -23 <006E>] TJ ET"; + for base in ["Glyphless", "CustomOCR"] { + let mut doc = make_page(single, base); + assert!(text::text_editor_fonts(&doc, 0).unwrap().iter().all(|f| f.choice_only), "{base} must not be loaded into the inline editor"); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].text, "De kinderen"); + assert!(before[0].invisible); + + let edit = text::replace_block(&mut doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica"), "{base} must substitute Helvetica instead of drawing in /F0"); + let after = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert_eq!(after.len(), 1); + assert_eq!(after[0].text, "De Kinderen"); + assert!(!after[0].invisible, "the edited OCR paragraph is now visible"); + assert_eq!(after[0].base_font, "Helvetica"); + + let mut line_doc = make_page(single, base); + let line_edit = text::replace_line(&mut line_doc, 0, 0, "De Kinderen").unwrap(); + assert_eq!(line_edit.substituted.as_deref(), Some("Helvetica"), "{base} replace_line must also substitute"); + assert_eq!(text::text_lines(&reopen(&line_doc), 0).unwrap()[0].base_font, "Helvetica"); + } + + // Multi-run OCR phrase on one row with slightly different OCR font sizes (rewrite_styled_block + // path): both runs switch to the visible substitute font and keep calibrated widths without + // stretching spaces to 200%. + let multi_run = "BT 3 Tr /F0 15.75 Tf 1 0 0 1 114.75 568.8 Tm <004400650020006B0069006E0064006500720065006E> Tj ET \ + BT 3 Tr /F0 15.5 Tf 1 0 0 1 205.0 568.8 Tm <006B0075006E006E0065006E> Tj ET"; + let mut doc = make_page(multi_run, "Glyphless"); + let before_lines = text::text_lines(&doc, 0).unwrap(); + let before = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].lines.len(), 2, "two runs on one OCR row"); + let edit = text::replace_block(&mut doc, 0, 0, "De kinderen Kunnen").unwrap(); + assert_eq!(edit.substituted.as_deref(), Some("Helvetica")); + let lines = text::text_lines(&reopen(&doc), 0).unwrap(); + assert_eq!(lines.iter().map(|l| l.text.trim()).collect::>(), ["De kinderen", "Kunnen"]); + for line in &lines { + assert_eq!(line.base_font, "Helvetica", "every run must use the visible substitute font: {line:?}"); + } + let old_w = before_lines[0].rect[2] - before_lines[0].rect[0]; + let new_w = lines[0].rect[2] - lines[0].rect[0]; + assert!((new_w - old_w).abs() < 5.0, "calibrated first run keeps its width ({old_w} -> {new_w}): {lines:?}"); + assert!(lines[1].rect[0] >= lines[0].rect[2] - 1.0, "calibrated first run does not stretch into the second: {lines:?}"); + let blocks = text::text_blocks(&reopen(&doc), 0).unwrap(); + assert!(!blocks[0].invisible, "the whole rewritten paragraph is visible"); + + // High WinAnsi characters on a glyphless OCR line also use the Helvetica substitute rather + // than /F0, and explicitly selecting the glyphless resource is refused. + let mut win_ansi_doc = make_page(single, "Glyphless"); + let win_edit = text::replace_block(&mut win_ansi_doc, 0, 0, "De kinderen € — café").unwrap(); + assert_eq!(win_edit.substituted.as_deref(), Some("Helvetica")); + assert_eq!(text::text_blocks(&reopen(&win_ansi_doc), 0).unwrap()[0].text, "De kinderen € — café"); + + let mut explicit = make_page(single, "Glyphless"); + let explicit_err = + text::rewrite_block(&mut explicit, 0, 0, Some("De Kinderen"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }); + assert!(explicit_err.is_err(), "explicitly selecting a glyphless font resource must be refused"); + + // Legitimate whitespace-only subsets and 1-glyph subsets with intentional CID aliases remain + // exposed to the inline editor and accepted when explicitly selected as a resource. + let mut zero_glyph_ttf = one_glyph_ttf.clone(); + zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0); + let mut ws_doc = text_page("BT /F0 12 Tf 1 0 0 1 72 700 Tm <0001> Tj /WS 12 Tf ( ) Tj ET"); + let ws_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf))); + let ws_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+SpaceOnly")), (b"FontFile2".to_vec(), Object::Ref(ws_prog))]); + let ws_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("TrueType")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+SpaceOnly")), + (b"Encoding".to_vec(), Object::name("WinAnsiEncoding")), + (b"FirstChar".to_vec(), Object::Int(32)), + (b"LastChar".to_vec(), Object::Int(32)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(250)])), + (b"FontDescriptor".to_vec(), Object::Dict(ws_desc)), + ]); + let alias_prog = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf))); + let alias_map = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1]))); + let alias_tu = ws_doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> <0061> endbfchar"))); + let alias_desc = Dict::from_iter([(b"FontName".to_vec(), Object::name("ABCDEF+AliasOne")), (b"FontFile2".to_vec(), Object::Ref(alias_prog))]); + let alias_cid = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("CIDFontType2")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"CIDToGIDMap".to_vec(), Object::Ref(alias_map)), + (b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])])), + (b"FontDescriptor".to_vec(), Object::Dict(alias_desc)), + ]); + let alias_font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type0")), + (b"BaseFont".to_vec(), Object::name("ABCDEF+AliasOne")), + (b"Encoding".to_vec(), Object::name("Identity-H")), + (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(alias_cid)])), + (b"ToUnicode".to_vec(), Object::Ref(alias_tu)), + ]); + let p = pdfcraft_model::pages(&ws_doc)[0].obj; + let fonts = Dict::from_iter([(b"F0".to_vec(), Object::Dict(alias_font)), (b"WS".to_vec(), Object::Dict(ws_font))]); + ws_doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let editor_resources: Vec<_> = text::text_editor_fonts(&ws_doc, 0).unwrap().into_iter().map(|f| f.resource).collect(); + assert!(editor_resources.contains(&"F0".to_string()) && editor_resources.contains(&"WS".to_string()), "{editor_resources:?}"); + let mut ws_only = ws_doc.clone(); + text::rewrite_block(&mut ws_only, 0, 0, Some(" "), &BlockStyle { resource: Some("WS".into()), ..Default::default() }).unwrap(); + text::rewrite_block(&mut ws_doc, 0, 0, Some("Aa"), &BlockStyle { resource: Some("F0".into()), ..Default::default() }).unwrap(); + assert_eq!(text::text_blocks(&reopen(&ws_doc), 0).unwrap()[0].text, "Aa"); +} + +/// Same-face generated subsets share a source line; TJ adjustment must survive a style edit. +#[test] +fn split_subset_source_keeps_calibrated_advance() { + let mut doc = text_page("BT /A 12 Tf 72 700 Td [<01> -100] TJ /B 12 Tf <01> Tj ET BT /F1 13 Tf 1 0 0 1 85.2 700 Tm (X) Tj ET"); + let mut fonts = Dict::new(); + // AA sorts before B and encodes B too, but its unrelated face must not supply metrics. + for (name, unicode, face, width) in + [("A", "0041", "SyntheticSubset", 500), ("AA", "0042", "OtherFace", 900), ("B", "0042", "SyntheticSubset", 500)] + { + let cmap = format!("1 begincodespacerange <01> endcodespacerange 1 beginbfchar <01> <{unicode}> endbfchar"); + let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes()))); + let proc = doc.add(Object::Stream(Stream::flate(Dict::new(), b"500 0 d0 0 0 400 700 re f"))); + let font = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type3")), + (b"Name".to_vec(), Object::name("PCJapanese")), + (b"BaseFont".to_vec(), Object::name(face)), + (b"FontBBox".to_vec(), Object::Array([0, 0, 500, 700].map(Object::Int).to_vec())), + (b"FontMatrix".to_vec(), Object::Array([0.001, 0.0, 0.0, 0.001, 0.0, 0.0].map(Object::Real).to_vec())), + (b"FirstChar".to_vec(), Object::Int(1)), + (b"LastChar".to_vec(), Object::Int(1)), + (b"Widths".to_vec(), Object::Array(vec![Object::Int(width)])), + ( + b"Encoding".to_vec(), + Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(1), Object::name("g01")]))])), + ), + (b"CharProcs".to_vec(), Object::Dict(Dict::from_iter([(b"g01".to_vec(), Object::Ref(proc))]))), + (b"ToUnicode".to_vec(), Object::Ref(tu)), + ]); + fonts.set(name.as_bytes().to_vec(), Object::Dict(font)); + } + fonts.set( + b"F1".to_vec(), + Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Font")), + (b"Subtype".to_vec(), Object::name("Type1")), + (b"BaseFont".to_vec(), Object::name("Helvetica")), + ])), + ); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap(); + let before = text::text_lines(&doc, 0).unwrap(); + assert_eq!(before[0].text, "AB"); + let blocks = text::text_blocks(&doc, 0).unwrap(); + assert_eq!(blocks.len(), 1, "{blocks:?}"); + assert_eq!(blocks[0].lines.len(), 2); + let original_width = before[0].rect[2] - before[0].rect[0]; + for (draft, factor) in [("ABX", 1.0), ("ABAX", 1.5)] { + let mut edited = doc.clone(); + text::rewrite_block(&mut edited, 0, 0, Some(draft), &BlockStyle { color: Some([0.0, 0.0, 1.0]), ..Default::default() }).unwrap(); + let after = text::text_lines(&reopen(&edited), 0).unwrap(); + let width = after[0].rect[2] - after[0].rect[0]; + assert!((width - original_width * factor).abs() < 0.01, "{draft}: original {original_width}, rewritten {width}; {after:?}"); + } +} + #[cfg(test)] mod proptests { use super::*; @@ -11001,6 +12517,53 @@ fn noop_arrange_is_not_ok_without_change() { assert!(r.is_err() || before != after, "Ok with no change"); } +/// Bring to front on an at-limit image that shares its only content unit with paint +/// already before it is a no-op, so it is refused instead of rebuilding the same placement. +#[test] +fn arrange_front_image_in_single_shared_unit_is_refused() { + let mut doc = image_page_with("q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_err()); + assert_eq!(page_content_bytes(&doc, 0), before); +} + +#[test] +fn arrange_front_image_in_single_shared_unit_moves_past_following_paint() { + let mut doc = image_page_with("q 100 0 0 100 50 50 cm /Im0 Do 0 0 10 10 re f Q"); + assert!( + arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_ok(), + "an image before following paint in one shared unit can be brought to front" + ); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("re f").unwrap() < s.rfind("/Im0 Do").unwrap(), "{s}"); + let mut doc = image_page_with("q q 100 0 0 100 50 50 cm /Im0 Do Q q 50 50 10 10 re f Q Q"); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).is_ok(), "separate inner units inside a page wrapper can be reordered"); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("re f").unwrap() < s.rfind("/Im0 Do").unwrap(), "{s}"); + let mut doc = image_page_with("q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, images::ArrangeOrder::BringForward).is_err()); + assert_eq!(page_content_bytes(&doc, 0), before); +} + +#[test] +fn arrange_backward_in_single_shared_unit_moves_before_paint_and_refuses_without_it() { + for order in [images::ArrangeOrder::SendToBack, images::ArrangeOrder::SendBackward] { + let mut doc = image_page_with("q q 0 0 10 10 re f 100 0 0 100 50 50 cm /Im0 Do Q Q"); + arrange(&mut doc, 0, 0, order).unwrap(); + let doc = reopen(&doc); + let s = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned(); + assert!(s.find("/Im0 Do").unwrap() < s.find("re f").unwrap(), "{order:?}: {s}"); + assert_eq!(images::page_images(&doc, 0).unwrap()[0].rect, [50.0, 50.0, 150.0, 150.0]); + } + for order in [images::ArrangeOrder::SendToBack, images::ArrangeOrder::SendBackward] { + let mut doc = image_page_with("q q 100 0 0 100 50 50 cm /Im0 Do 0 0 10 10 re f Q Q"); + let before = page_content_bytes(&doc, 0); + assert!(arrange(&mut doc, 0, 0, order).is_err(), "{order:?}"); + assert_eq!(page_content_bytes(&doc, 0), before); + } +} + /// Cropping a turned image keeps the requested upright box in user space, rather than expanding /// to the bounding box of the turned image coordinates. #[test] @@ -13963,6 +15526,19 @@ fn remove_crop_refuses_an_unmarked_author_clip_without_changes() { assert_eq!(page_content_bytes(&doc, 0), before); } +/// A PdfCraft crop marker whose clip is written as `W q Q n` is still recorded on the image, but +/// scope detection does not treat that path as a removable crop. The error says the crop cannot +/// be removed, not that none exists. +#[test] +fn remove_crop_reports_a_recorded_crop_it_cannot_strip() { + let mut doc = image_page_with("q /PdfCraftImageCrop MP 100 100 50 50 re W q Q n 200 0 0 100 100 100 cm /Im0 Do Q"); + assert!(images::page_images(&doc, 0).unwrap()[0].has_editor_crop()); + let before = page_content_bytes(&doc, 0); + let err = remove_crop(&mut doc, 0, 0).unwrap_err().to_string(); + assert!(err.contains("cannot be safely removed") && !err.contains("has no PdfCraft crop"), "{err}"); + assert_eq!(page_content_bytes(&doc, 0), before); +} + #[test] fn arrange_refuses_unrestorable_extended_print_state() { let mut unexpectedly_moved = Vec::new(); @@ -15659,3 +17235,520 @@ fn thai_paragraphs_break_the_row_on_unicode_row_breaks() { assert_eq!(rows(&doc), ["กข", "ค"], "matching U+{:04X}", u32::from(separator)); } } + +/// The deleted image's payload survived a full save: the census could not prove it unused. +fn payload_after_delete(doc: &mut Document, private: &[u8]) -> bool { + images::change_image(doc, 0, 0, &images::ImageChange::Delete).unwrap(); + let bytes = write_full(doc, &SaveOptions::default()).unwrap(); + bytes.windows(private.len()).any(|w| w == private) +} + +/// A form `name` that draws what `body` says, in the page's own resource scope plus `xobjects`. +fn add_form(doc: &mut Document, name: &[u8], body: &[u8], xobjects: Dict) -> ObjRef { + let mut dict = Dict::new(); + dict.set(b"Type".to_vec(), Object::name("XObject")); + dict.set(b"Subtype".to_vec(), Object::name("Form")); + dict.set(b"BBox".to_vec(), Object::Array([0, 0, 10, 10].map(Object::Int).to_vec())); + let mut resources = Dict::from_iter([(b"Font".to_vec(), Object::Dict(Dict::new()))]); + if !xobjects.is_empty() { + resources.set(b"XObject".to_vec(), Object::Dict(xobjects)); + } + dict.set(b"Resources".to_vec(), Object::Dict(resources)); + let form = doc.add(Object::Stream(Stream::flate(dict, body))); + let page = pdfcraft_model::pages(doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + let mut names = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap_or_default(); + names.set(name.to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(names)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + form +} + +/// The image `private` a page draws as `/Im0`, with the object it is drawn through. +fn private_page(private: &[u8]) -> (Document, ObjRef) { + let mut doc = image_page(); + let target = images::page_images(&doc, 0).unwrap()[0].object.unwrap(); + doc.set(target, Object::Stream(identifiable_test_image(private))); + (doc, target) +} + +/// The page's `/ExtGState` gains `name` with `entries`. +fn add_extgstate(doc: &mut Document, name: &[u8], entries: Dict) { + let page = pdfcraft_model::pages(doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + let mut states = resources.get(b"ExtGState").and_then(Object::as_dict).cloned().unwrap_or_default(); + states.set(name.to_vec(), Object::Dict(entries)); + resources.set(b"ExtGState".to_vec(), Object::Dict(states)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); +} + +/// A form that draws itself leaves the census no way to say what it reaches, so the deleted image's +/// payload stays: the alias in the page's resources is kept rather than the object dropped. +#[test] +fn a_form_cycle_keeps_the_image_the_census_cannot_see_through() { + const PRIVATE: &[u8] = b"PRIVATE_FORM_CYCLE_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let form = add_form(&mut doc, b"Loop", b"/Loop Do", Dict::new()); + // Its own scope names it too, so the walk comes back to it. + doc.update_dict(form, |d| { + let resources = Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Loop".to_vec(), Object::Ref(form))])))]); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Loop Do"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "a cycle must keep the image"); +} + +/// A chain deeper than the census's depth limit stops the walk before it reaches the image, so the +/// payload stays. The image really is drawn, at a depth the census refuses to guess about. +#[test] +fn a_form_chain_past_the_census_depth_limit_keeps_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_DEEP_CHAIN_IMAGE"; + let (mut doc, target) = private_page(PRIVATE); + let mut next: Option = None; + for level in (0..70).rev() { + let body: Vec = if next.is_some() { format!("/D{level} Do").into_bytes() } else { b"/Im0 Do".to_vec() }; + let names = match next { + Some(inner) => Dict::from_iter([(format!("D{level}").into_bytes(), Object::Ref(inner))]), + None => Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target))]), + }; + // The form is added under its own name at the page, and each one draws the next. + next = Some(add_form(&mut doc, format!("F{level}").into_bytes().as_slice(), &body, names)); + } + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /F0 Do"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "a chain past the depth limit must keep the image"); +} + +/// Soft masks and alternates that are malformed (or name nothing) must not be read as "no consumer": +/// the image stays. The benign spellings of "no mask" (null, /None, an array of nulls) still let the +/// unused image go. +#[test] +fn malformed_soft_masks_and_alternates_keep_the_image_while_the_empty_spellings_do_not() { + for (label, entries, kept) in [ + ("/SMask null", Dict::from_iter([(b"SMask".to_vec(), Object::Null)]), false), + ("/SMask /None", Dict::from_iter([(b"SMask".to_vec(), Object::name("None"))]), false), + ("/Mask [null null]", Dict::from_iter([(b"Mask".to_vec(), Object::Array(vec![Object::Null, Object::Null]))]), false), + ("/SMask a dictionary", Dict::from_iter([(b"SMask".to_vec(), Object::Dict(Dict::new()))]), true), + ("/Alternates a dictionary", Dict::from_iter([(b"Alternates".to_vec(), Object::Dict(Dict::new()))]), true), + ("/Alternates without /Image", Dict::from_iter([(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(Dict::new())]))]), true), + ] { + const PRIVATE: &[u8] = b"PRIVATE_MASKED_CONSUMER_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let mut image = Dict::new(); + image.set(b"Type".to_vec(), Object::name("XObject")); + image.set(b"Subtype".to_vec(), Object::name("Image")); + image.set(b"Width".to_vec(), Object::Int(4)); + image.set(b"Height".to_vec(), Object::Int(2)); + image.set(b"ColorSpace".to_vec(), Object::name("DeviceGray")); + image.set(b"BitsPerComponent".to_vec(), Object::Int(8)); + for (key, value) in entries.iter() { + image.set(key.clone(), value.clone()); + } + let other = doc.add(Object::Stream(Stream::from_raw(image, vec![0u8; 8]))); + add_form(&mut doc, b"Other", b"/OtherImage Do", Dict::from_iter([(b"OtherImage".to_vec(), Object::Ref(other))])); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Other Do"]); + assert_eq!(payload_after_delete(&mut doc, PRIVATE), kept, "{label}"); + } +} + +/// `gs`, `Tf` and `scn` naming something the census cannot read leave the image alone; the states it +/// can read (a Type3 font with glyph programs, a tiling pattern) are walked, and an unused image goes. +#[test] +fn resource_operators_the_census_cannot_read_keep_the_image() { + for (label, state, content) in [ + ( + "an ExtGState font that is not a pair", + Some((b"GS".to_vec(), Dict::from_iter([(b"Font".to_vec(), Object::Array(vec![Object::Int(0)]))]))), + "/GS gs", + ), + ("an ExtGState font that is not an array", Some((b"GS".to_vec(), Dict::from_iter([(b"Font".to_vec(), Object::name("F1"))]))), "/GS gs"), + ("an ExtGState soft mask that is not a dictionary", Some((b"GS".to_vec(), Dict::from_iter([(b"SMask".to_vec(), Object::Int(1))]))), "/GS gs"), + ( + "a soft mask group that is not a form", + Some((b"GS".to_vec(), Dict::from_iter([(b"SMask".to_vec(), Object::Dict(Dict::from_iter([(b"G".to_vec(), Object::Int(1))])))]))), + "/GS gs", + ), + ] { + const PRIVATE: &[u8] = b"PRIVATE_UNREADABLE_OPERATOR_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + if let Some((name, entries)) = state { + add_extgstate(&mut doc, &name, entries); + } + set_image_content(&mut doc, 0, &[format!("q 200 0 0 100 100 100 cm /Im0 Do Q {content}").into_bytes().as_slice()]); + assert!(payload_after_delete(&mut doc, PRIVATE), "{label}"); + } +} + +/// A shading painted through `scn` draws no XObject, so it is no reason to keep the image: the +/// census reads it as nothing to follow and the unused image still goes. +#[test] +fn a_shading_painted_through_scn_does_not_keep_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_SHADING_PATTERN_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let shading = + doc.add(Object::Dict(Dict::from_iter([(b"ShadingType".to_vec(), Object::Int(2)), (b"ColorSpace".to_vec(), Object::name("DeviceGray"))]))); + // /Pattern names a Type 2 pattern, not the shading dictionary itself. Its shading has no + // ExtGState and cannot consume an XObject, so the positive cleanup assertion stays unchanged. + let pattern = doc.add(Object::Dict(Dict::from_iter([(b"PatternType".to_vec(), Object::Int(2)), (b"Shading".to_vec(), Object::Ref(shading))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set(b"Pattern".to_vec(), Object::Dict(Dict::from_iter([(b"P1".to_vec(), Object::Ref(pattern))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Pattern cs /P1 scn"]); + assert!(!payload_after_delete(&mut doc, PRIVATE), "a shading is no consumer, so the image goes"); +} + +/// An image XObject whose `/SMask` or `/Alternates` points at an object that is not one is not read +/// as "nothing there": the image stays. An XObject that is not a stream at all does the same. +#[test] +fn a_page_drawing_something_that_is_not_an_xobject_keeps_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_NOT_A_STREAM_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let not_a_stream = doc.add(Object::Dict(Dict::from_iter([(b"Type".to_vec(), Object::name("Font"))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + let mut names = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap_or_default(); + names.set(b"Bad".to_vec(), Object::Ref(not_a_stream)); + resources.set(b"XObject".to_vec(), Object::Dict(names)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Bad Do"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "an unreadable XObject must keep the image"); +} + +/// `/Annots` that is not an array leaves the appearance walks unknown, so the image stays. +#[test] +fn annots_that_are_not_an_array_keep_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_ANNOTS_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Int(1))).unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "unreadable /Annots must keep the image"); +} + +/// The prune rewrites resource dictionaries it reaches through a reference, so a genuinely unused +/// image still goes even when its alias sits in an indirect `/XObject` dictionary. +#[test] +fn an_indirect_xobject_dictionary_is_rewritten_so_an_unused_image_still_goes() { + const PRIVATE: &[u8] = b"PRIVATE_INDIRECT_DICT_IMAGE"; + let (mut doc, target) = private_page(PRIVATE); + // An orphan dictionary, referenced by nothing the census reads, naming the image. + let orphan = + doc.add(Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Unused".to_vec(), Object::Ref(target))])))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set(b"Properties".to_vec(), Object::Dict(Dict::from_iter([(b"L9".to_vec(), Object::Ref(orphan))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + assert!(!payload_after_delete(&mut doc, PRIVATE), "an unused indirect alias must be pruned"); +} + +/// More aliases than the rewrite will stage keeps the image: the census stops rather than rewrite a +/// document it could not finish, and nothing of the edit's cleanup is applied. +#[test] +fn more_aliases_than_the_rewrite_will_stage_keeps_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_MANY_ALIASES_IMAGE"; + let (mut doc, target) = private_page(PRIVATE); + let mut aliases = Dict::new(); + for index in 0..300 { + aliases.set(format!("Unused{index}").into_bytes(), Object::Ref(target)); + } + let orphan = doc.add(Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(aliases))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set(b"Properties".to_vec(), Object::Dict(Dict::from_iter([(b"L9".to_vec(), Object::Ref(orphan))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "past the alias cap the image must stay"); +} + +/// An annotation appearance is walked through its dictionary, its states and its form streams, and +/// any shape the census cannot read keeps the image: an appearance dictionary naming its own +/// `/Resources`, and one whose states come back to it. +#[test] +fn annotation_appearances_are_walked_and_the_unreadable_ones_keep_the_image() { + // The readable shape first: a form appearance that draws the image, reached through a state + // dictionary and an array. The image is used, so deleting it from the page keeps it. + const PRIVATE: &[u8] = b"PRIVATE_APPEARANCE_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + let drawing = add_form(&mut doc, b"DrawsIm0", b"/Im0 Do", Dict::new()); + let states = doc.add(Object::Dict(Dict::from_iter([(b"N".to_vec(), Object::Ref(drawing)), (b"On".to_vec(), Object::Ref(drawing))]))); + let selected = doc.add(Object::Array(vec![Object::Ref(states)])); + let annot = doc.add(Object::Dict(Dict::from_iter([(b"AP".to_vec(), Object::Dict(Dict::from_iter([(b"N".to_vec(), Object::Ref(selected))])))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annot)]))).unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "an appearance that draws the image keeps it"); + + for (label, cycle) in [("an appearance dictionary naming its own /Resources", false), ("appearance states that come back to it", true)] { + const KEPT: &[u8] = b"PRIVATE_UNREADABLE_APPEARANCE_IMAGE"; + let (mut doc, _target) = private_page(KEPT); + let state = if cycle { + let holder = doc.add(Object::Dict(Dict::new())); + doc.update_dict(holder, |d| d.set(b"On".to_vec(), Object::Ref(holder))).unwrap(); + Object::Dict(Dict::from_iter([(b"On".to_vec(), Object::Ref(holder))])) + } else { + Object::Dict(Dict::from_iter([(b"Resources".to_vec(), Object::Dict(Dict::new()))])) + }; + let annot = doc.add(Object::Dict(Dict::from_iter([(b"AP".to_vec(), Object::Dict(Dict::from_iter([(b"N".to_vec(), state)])))]))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annot)]))).unwrap(); + assert!(payload_after_delete(&mut doc, KEPT), "{label} must keep the image"); + } +} + +/// `/Alternates` arrays that name the deleted image are rewritten wherever the rewrite finds them, +/// directly and through a reference, so an image nothing draws is still released; an entry whose +/// `/Image` is not the deleted one stays. +#[test] +fn alternate_arrays_naming_the_image_are_rewritten_through_references() { + const PRIVATE: &[u8] = b"PRIVATE_ALTERNATE_IMAGE"; + let (mut doc, target) = private_page(PRIVATE); + let other = doc.add(Object::Stream(identifiable_test_image(b"OTHER_IMAGE_BYTES"))); + let kept_entry = Object::Dict(Dict::from_iter([(b"Image".to_vec(), Object::Ref(other))])); + let dropped_entry = Object::Dict(Dict::from_iter([(b"Image".to_vec(), Object::Ref(target))])); + // One array named directly by an orphan image, one given through a reference. + let orphan = doc.add(Object::Stream(Stream::from_raw( + Dict::from_iter([ + (b"Type".to_vec(), Object::name("XObject")), + (b"Subtype".to_vec(), Object::name("Image")), + (b"Width".to_vec(), Object::Int(4)), + (b"Height".to_vec(), Object::Int(2)), + (b"ColorSpace".to_vec(), Object::name("DeviceGray")), + (b"BitsPerComponent".to_vec(), Object::Int(8)), + (b"Alternates".to_vec(), Object::Array(vec![kept_entry.clone(), dropped_entry])), + ]), + vec![0u8; 8], + ))); + let indirect = doc.add(Object::Array(vec![kept_entry, Object::Dict(Dict::from_iter([(b"Image".to_vec(), Object::Ref(target))]))])); + let second = doc.add(Object::Stream(Stream::from_raw( + Dict::from_iter([ + (b"Type".to_vec(), Object::name("XObject")), + (b"Subtype".to_vec(), Object::name("Image")), + (b"Width".to_vec(), Object::Int(4)), + (b"Height".to_vec(), Object::Int(2)), + (b"ColorSpace".to_vec(), Object::name("DeviceGray")), + (b"BitsPerComponent".to_vec(), Object::Int(8)), + (b"Alternates".to_vec(), Object::Ref(indirect)), + ]), + vec![0u8; 8], + ))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + resources.set( + b"Properties".to_vec(), + Object::Dict(Dict::from_iter([(b"L1".to_vec(), Object::Ref(orphan)), (b"L2".to_vec(), Object::Ref(second))])), + ); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + assert!(!payload_after_delete(&mut doc, PRIVATE), "nothing draws the image, so it goes"); +} + +/// A Type3 font's glyph programs are walked with the font's own scope, and one that is not a stream +/// stops the walk: the image stays. +#[test] +fn type3_glyph_programs_are_walked_and_a_broken_one_keeps_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_TYPE3_CHARPROC_IMAGE"; + for (label, charproc) in [("a form that draws the image", None), ("a program that is not a stream", Some(Object::Int(1)))] { + let (mut doc, target) = private_page(PRIVATE); + let program = match charproc { + None => { + let form = add_form(&mut doc, b"Glyph", b"/Im0 Do", Dict::new()); + Object::Ref(form) + } + Some(not_a_stream) => not_a_stream, + }; + let mut charprocs = Dict::new(); + charprocs.set(b"A".to_vec(), program); + let mut glyph_resources = Dict::new(); + glyph_resources.set(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"Im0".to_vec(), Object::Ref(target))]))); + let mut font_dict = Dict::new(); + for (key, value) in [ + (&b"Type"[..], Object::name("Font")), + (b"Subtype", Object::name("Type3")), + (b"FontBBox", Object::Array([0, 0, 1000, 1000].map(Object::Int).to_vec())), + (b"FontMatrix", Object::Array(vec![Object::Int(1), Object::Int(0), Object::Int(0), Object::Int(1), Object::Int(0), Object::Int(0)])), + (b"FirstChar", Object::Int(65)), + (b"LastChar", Object::Int(65)), + (b"Widths", Object::Array(vec![Object::Int(1000)])), + (b"Encoding", Object::Dict(Dict::from_iter([(b"Differences".to_vec(), Object::Array(vec![Object::Int(65), Object::name("A")]))]))), + (b"CharProcs", Object::Dict(charprocs)), + (b"Resources", Object::Dict(glyph_resources)), + ] { + font_dict.set(key.to_vec(), value); + } + let font = doc.add(Object::Dict(font_dict)); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap_or_default(); + let mut fonts = resources.get(b"Font").and_then(Object::as_dict).cloned().unwrap_or_default(); + fonts.set(b"F2".to_vec(), Object::Ref(font)); + resources.set(b"Font".to_vec(), Object::Dict(fonts)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q BT /F2 10 Tf (A) Tj ET"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "{label} must keep the image"); + } +} + +/// A second page whose `/Contents` is not a stream leaves the census unable to say what that page +/// draws, so the image stays even though the page being edited is clean. +#[test] +fn another_page_with_contents_that_are_not_a_stream_keeps_the_image() { + const PRIVATE: &[u8] = b"PRIVATE_NON_STREAM_CONTENTS_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + add_blank_page(&mut doc, None); + let not_a_stream = doc.add(Object::Int(1)); + let second = pdfcraft_model::pages(&doc)[1].obj; + doc.update_dict(second, |d| d.set(b"Contents".to_vec(), Object::Ref(not_a_stream))).unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "a page with unreadable /Contents must keep the image"); +} + +#[test] +fn census_retains_images_drawn_by_each_widget_icon() { + const PRIVATE: &[u8] = b"PRIVATE_WIDGET_ICON_IMAGE"; + for key in [b"I".as_slice(), b"RI", b"IX"] { + let (mut doc, target) = private_page(PRIVATE); + let form = add_form(&mut doc, b"Icon", b"/IconImg Do", Dict::from_iter([(b"IconImg".to_vec(), Object::Ref(target))])); + let mk = doc.add(Object::Dict(Dict::from_iter([(key.to_vec(), Object::Ref(form))]))); + let annotation = Object::Dict(Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Widget")), + (b"FT".to_vec(), Object::name("Btn")), + (b"MK".to_vec(), Object::Ref(mk)), + ])); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![annotation]))).unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "widget icon {key:?} lost its image"); + let saved = reopen(&doc); + let bytes = write_full(&saved, &SaveOptions::default()).unwrap(); + assert!(bytes.windows(PRIVATE.len()).any(|b| b == PRIVATE)); + } +} + +#[test] +fn census_retains_images_in_shading_pattern_soft_masks() { + const PRIVATE: &[u8] = b"PRIVATE_SHADING_PATTERN_MASK"; + for type_spelling in ["direct", "indirect", "missing", "invalid"] { + let (mut doc, target) = private_page(PRIVATE); + let form = add_form(&mut doc, b"MaskForm", b"/MaskImg Do", Dict::from_iter([(b"MaskImg".to_vec(), Object::Ref(target))])); + let state = + doc.add(Object::Dict(Dict::from_iter([(b"SMask".to_vec(), Object::Dict(Dict::from_iter([(b"G".to_vec(), Object::Ref(form))])))]))); + let mut pattern = Dict::from_iter([(b"ExtGState".to_vec(), Object::Ref(state))]); + let kind = match type_spelling { + "direct" => Some(Object::Int(2)), + "indirect" => Some(Object::Ref(doc.add(Object::Int(2)))), + "missing" => None, + _ => Some(Object::name("Unknown")), + }; + if let Some(kind) = kind { + pattern.set(b"PatternType".to_vec(), kind); + } + let pattern = Object::Dict(pattern); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"Pattern".to_vec(), Object::Dict(Dict::from_iter([(b"P".to_vec(), pattern)]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Pattern cs /P scn 0 0 10 10 re f"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "the shading pattern's mask still draws the image"); + } +} + +#[test] +fn census_keeps_inherited_type3_glyph_scope_but_prunes_with_a_private_font_scope() { + const PRIVATE: &[u8] = b"PRIVATE_INHERITED_TYPE3_IMAGE"; + for (own_scope, indirect_subtype) in [(false, false), (false, true), (true, false), (true, true)] { + let (mut doc, target) = private_page(PRIVATE); + let other = doc.add(Object::Stream(identifiable_test_image(b"OTHER_TYPE3_IMAGE"))); + let glyph = doc.add(Object::Stream(Stream::flate(Dict::new(), b"/GlyphImg Do"))); + let mut font = Dict::from_iter([ + (b"Subtype".to_vec(), Object::name("Type3")), + (b"CharProcs".to_vec(), Object::Dict(Dict::from_iter([(b"A".to_vec(), Object::Ref(glyph))]))), + ]); + let glyph_scope = Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"GlyphImg".to_vec(), Object::Ref(other))])))]); + if own_scope { + font.set(b"Resources".to_vec(), Object::Dict(glyph_scope)); + } + if indirect_subtype { + let subtype = doc.add(Object::name("Type3")); + font.set(b"Subtype".to_vec(), Object::Ref(subtype)); + } + let font = doc.add(Object::Dict(font)); + let form = add_form(&mut doc, b"TextForm", b"BT (A) Tj ET", Dict::from_iter([(b"GlyphImg".to_vec(), Object::Ref(target))])); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"Font".to_vec(), Object::Dict(Dict::from_iter([(b"T3".to_vec(), Object::Ref(font))]))); + let mut names = resources.get(b"XObject").and_then(Object::as_dict).cloned().unwrap(); + names.set(b"GlyphImg".to_vec(), Object::Ref(other)); + names.set(b"TextForm".to_vec(), Object::Ref(form)); + resources.set(b"XObject".to_vec(), Object::Dict(names)); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q BT /T3 10 Tf ET /TextForm Do"]); + assert_eq!(payload_after_delete(&mut doc, PRIVATE), !own_scope, "private font resources: {own_scope}"); + } +} + +#[test] +fn census_does_not_use_a_corrupt_streams_tolerated_prefix_as_a_nonuse_proof() { + const PRIVATE: &[u8] = b"PRIVATE_CORRUPT_CENSUS_IMAGE"; + let (mut doc, _target) = private_page(PRIVATE); + add_blank_page(&mut doc, None); + // A nonfinal stored DEFLATE block yields valid content, then an invalid block type fails. + // A corrupt Adler checksum alone is intentionally accepted by the shared PDF decoder. + let stream = + Stream::from_raw(Dict::from_iter([(b"Filter".to_vec(), Object::name("FlateDecode"))]), b"\x78\x01\x00\x04\x00\xfb\xffq Q\n\x07".to_vec()); + assert_eq!(stream.decoded().unwrap(), b"q Q\n"); + assert!(stream.decoded_strict().is_err()); + let content = doc.add(Object::Stream(stream)); + let page = pdfcraft_model::pages(&doc)[1].obj; + doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Ref(content))).unwrap(); + assert!(payload_after_delete(&mut doc, PRIVATE), "corruption cannot authorize destructive cleanup"); +} + +#[test] +fn census_retains_images_drawn_by_tiling_patterns_with_indirect_types() { + const PRIVATE: &[u8] = b"PRIVATE_INDIRECT_TILING_PATTERN"; + let (mut doc, target) = private_page(PRIVATE); + let kind = doc.add(Object::Int(1)); + let pattern = doc.add(Object::Stream(Stream::flate( + Dict::from_iter([ + (b"PatternType".to_vec(), Object::Ref(kind)), + ( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Dict(Dict::from_iter([(b"TileImg".to_vec(), Object::Ref(target))])))])), + ), + ]), + b"/TileImg Do", + ))); + let page = pdfcraft_model::pages(&doc)[0].obj; + doc.update_dict(page, |d| { + let mut resources = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap(); + resources.set(b"Pattern".to_vec(), Object::Dict(Dict::from_iter([(b"P".to_vec(), Object::Ref(pattern))]))); + d.set(b"Resources".to_vec(), Object::Dict(resources)); + }) + .unwrap(); + set_image_content(&mut doc, 0, &[b"q 200 0 0 100 100 100 cm /Im0 Do Q /Pattern cs /P scn 0 0 10 10 re f"]); + assert!(payload_after_delete(&mut doc, PRIVATE), "an indirect pattern type still draws its image"); +} diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 3b938878f4..0a1714d761 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -29,6 +29,11 @@ pub use fallback::strip_subset_tag; use regions::{alignment_frame, existing_gap, group_blocks, is_centred, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step}; pub use session::TextSession; +#[path = "text_containers.rs"] +mod containers; +#[path = "text_row_style.rs"] +mod row_style; + mod blocks; mod editor; mod fallback; @@ -112,6 +117,7 @@ pub struct TextLine { scope: Option, /// The layers and graphics state parameters it is drawn in; see [`Paint`]. paint: Paint, + containers: Vec, /// Right-to-left `/ActualText` already supplies typing order; glyph text still needs bidi /// recovery. Left-to-right ActualText (e.g. a Latin ligature) joins its line as usual. logical_order: bool, diff --git a/crates/edit/src/text/interp.rs b/crates/edit/src/text/interp.rs index 7ada4a5182..166ffcd327 100644 --- a/crates/edit/src/text/interp.rs +++ b/crates/edit/src/text/interp.rs @@ -481,6 +481,7 @@ pub(super) struct Shown { pub(super) decodable: bool, pub(super) scope: Option, pub(super) paint: Paint, + pub(super) containers: Vec, pub(super) logical_order: bool, pub(super) actual_text: bool, /// Set when a `/PCSoft` or `/PCHard` marker was seen since the previous text line. @@ -625,6 +626,9 @@ pub(super) struct Carry { pub(super) layers: Vec>>, /// Bytes of glyph text the rest of the page may still produce (see [`MAX_PAGE_TEXT`]). pub(super) text_left: usize, + pub(super) containers: Rc, + /// The operator indices of the `Do`s, from the page down, that draw these operators. + pub(super) at: Vec, /// Whether the last run ended in a space read from a gap, with the next operator a `Tj` or /// `TJ` that may start with the space glyph that gap widened. pub(super) gap_space: bool, @@ -659,7 +663,16 @@ impl Carry { dash: (Vec::new(), 0.0), line_cap: 0, }; - Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new(), text_left: MAX_PAGE_TEXT, gap_space: false } + Carry { + ts, + stack: Vec::new(), + marked: Vec::new(), + layers: Vec::new(), + text_left: MAX_PAGE_TEXT, + containers: Rc::default(), + at: Vec::new(), + gap_space: false, + } } } @@ -971,6 +984,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit decodable, scope: marked.regions.last().copied().flatten(), paint: Paint { layers: marked.layers.iter().flatten().cloned().collect(), gs: ts.gs.clone() }, + containers: Vec::new(), logical_order: false, actual_text: false, soft_break: state.soft_break, @@ -1240,5 +1254,52 @@ pub(super) fn interpret( carry.layers = marked.layers; out.retain(|s| s.glyph_count > 0 || s.actual_text); positioned_tracking(&mut out); + assign_containers(&mut out, carry); Ok(out) } + +/// The filled panels each piece of text sits in: its `membership`, less a box a highlight's +/// height that only part of the text or of its line is in. +fn assign_containers(out: &mut [Shown], carry: &Carry) { + for shown in out.iter_mut() { + shown.containers = carry.containers.membership(shown.rect, &[carry.at.as_slice(), &[shown.op]].concat()); + } + // A box a highlight's height that does not reach across the text is a highlight behind part + // of it, as when one `Tj` draws the whole line. + for shown in out.iter_mut() { + let rect = shown.rect; + shown.containers.retain(|panel| carry.containers.spans(*panel, rect) || !carry.containers.hugs(*panel, rect)); + } + // Text that runs on along its line keeps a box only part of it is in when the box is a + // panel's height: a highlight padded around one word of the line is not a panel. + let mut start = 0; + while start < out.len() { + let mut end = start + 1; + while out.get(end).is_some_and(|next| runs_on(&out[end - 1].rect, &next.rect)) { + end += 1; + } + if end - start > 1 { + // How many of the run's pieces each box holds (`membership` lists a box once per piece), + // counted in one pass: a hostile page can chain thousands of runs into one line. + let mut held: HashMap = HashMap::new(); + for shown in &out[start..end] { + for panel in &shown.containers { + *held.entry(*panel).or_default() += 1; + } + } + for shown in &mut out[start..end] { + let rect = shown.rect; + shown.containers.retain(|panel| held.get(panel) == Some(&(end - start)) || !carry.containers.hugs(*panel, rect)); + } + } + start = end; + } +} + +/// Whether text in `next` continues `previous` along its line: about the same height across it, +/// and starting at or after it with less than a line's height between them. +fn runs_on(previous: &[f64; 4], next: &[f64; 4]) -> bool { + let height = (previous[3] - previous[1]).max(next[3] - next[1]); + let centre = |r: &[f64; 4]| (r[1] + r[3]) / 2.0; + (centre(previous) - centre(next)).abs() < height / 2.0 && next[0] >= previous[0] && next[0] - previous[2] < height +} diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rs index 1eb35c818e..8e0d258ec6 100644 --- a/crates/edit/src/text/lines.rs +++ b/crates/edit/src/text/lines.rs @@ -485,6 +485,7 @@ fn text_lines_in( let pieces = joined(&content_streams(doc, &p.dict)?); let ops = pieces.parse().ops; let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); + carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res)); let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?; if let Some(blank_clips) = blank_clips { blank_clips.extend(shown.iter().filter(|s| (4..=7).contains(&s.state.render_mode) && !s.may_draw_outline).map(|s| s.op)); @@ -506,7 +507,9 @@ fn text_lines_in( let bt = pen.bt; let (near, gap) = pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }); piece == si - && lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order) + && lines.last().is_some_and(|l| { + l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order + }) && (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s))) && (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s))) && (s.text.trim().is_empty() @@ -562,6 +565,7 @@ fn text_lines_in( stream: si, scope: s.scope, paint: s.paint.clone(), + containers: s.containers.clone(), logical_order: s.logical_order, actual_text: s.actual_text, clips: s.state.render_mode >= 4, @@ -629,7 +633,7 @@ fn compatible_word(line: &TextLine, shown: &Shown) -> bool { fn add_shown(lines: &mut Vec, last: &mut Option, s: Shown, stream: usize) { let joins = last.is_some_and(|pen| { let bt = pen.bt; - lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order) + lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order) && (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s))) && (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s))) && (s.text.trim().is_empty() @@ -681,6 +685,7 @@ fn add_shown(lines: &mut Vec, last: &mut Option, s: Shown, stream stream, scope: s.scope, paint: s.paint.clone(), + containers: s.containers.clone(), logical_order: s.logical_order, actual_text: s.actual_text, clips: s.state.render_mode >= 4, @@ -860,8 +865,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec Result<(Vec Result<(), EditError> { + fn enter( + w: &mut Walk, + resources: &Dict, + name: &[u8], + ts: Ts, + text_left: &mut usize, + containers: std::rc::Rc, + at: Vec, + ) -> Result<(), EditError> { let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return Ok(()) }; let ops = parse(&form.data).ops; // The form starts with the graphics state at its `Do`, its own matrix applied. @@ -901,6 +914,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec Result<(Vec, + /// Its bounding box on the page, whatever matrix drew it. + page: [f64; 4], + /// The first container with the same box on the page: a panel painted again behind each of + /// its rows, under any matrix, is still one panel. + id: usize, +} + +#[derive(Default)] +pub(super) struct Containers { + filled: Vec, + pending: Option, + complex: bool, +} + +impl Containers { + pub(super) fn collect(doc: &Document, ops: &[Op], resources: &Dict) -> Self { + let mut collector = Collector { + doc, + containers: Self::default(), + path: Vec::new(), + budget: super::lines::FormBudget::new(pdfcraft_cos::DecodeBudget::page()), + }; + collector.walk(ops, resources, Matrix::IDENTITY, &[]); + let mut first = std::collections::HashMap::new(); + for (index, container) in collector.containers.filled.iter_mut().enumerate() { + let key = container.page.map(|v| (v * 1000.0).round() as i64); + container.id = *first.entry(key).or_insert(index); + } + collector.containers + } + + fn observe(&mut self, op: &Op, ctm: Matrix, at: &[usize]) { + match op.op.as_slice() { + b"re" => { + if self.pending.is_some() { + self.complex = true; + } + self.pending = op.nums::<4>().zip(ctm.invert()).and_then(|([x, y, width, height], inverse)| { + let rect = [x.min(x + width), y.min(y + height), x.max(x + width), y.max(y + height)]; + (rect.iter().all(|v| v.is_finite()) && rect[2] > rect[0] && rect[3] > rect[1]).then_some(Container { + inverse, + rect, + at: Vec::new(), + page: page_box(rect, ctm), + id: 0, + }) + }); + } + b"m" | b"l" | b"c" | b"v" | b"y" => self.complex = true, + b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => { + if !self.complex + && self.filled.len() < 4096 + && let Some(mut rect) = self.pending.take() + { + rect.at = at.to_vec(); + self.filled.push(rect); + } + self.pending = None; + self.complex = false; + } + b"n" | b"S" | b"s" => { + self.pending = None; + self.complex = false; + } + _ => {} + } + } + + /// The panels that hold `rect`'s centre and are taller than it. A highlight or inline shading + /// drawn to the height of its glyphs is not a panel, and neither is a fill painted after the + /// text (a redaction cover): `at` is the text's place in the drawing order, the operator + /// indices from the page down through the forms that draw it. + pub(super) fn membership(&self, rect: [f64; 4], at: &[usize]) -> Vec { + let (x, y) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0); + let mut ids: Vec = self + .filled + .iter() + .filter_map(|container| { + let ys = + [(rect[0], rect[1]), (rect[2], rect[1]), (rect[0], rect[3]), (rect[2], rect[3])].map(|(x, y)| container.inverse.apply(x, y).1); + let height = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max) - ys.iter().copied().fold(f64::INFINITY, f64::min); + let (x, y) = container.inverse.apply(x, y); + let [left, bottom, right, top] = container.rect; + (container.at.as_slice() < at && x >= left && x <= right && y >= bottom && y <= top && top - bottom >= height * 1.15) + .then_some(container.id) + }) + .collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } +} + +fn page_box([left, bottom, right, top]: [f64; 4], ctm: Matrix) -> [f64; 4] { + let corners = [(left, bottom), (right, bottom), (left, top), (right, top)].map(|(x, y)| ctm.apply(x, y)); + corners.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |[x0, y0, x1, y1], &(x, y)| { + [x0.min(x), y0.min(y), x1.max(x), y1.max(y)] + }) +} + +impl Containers { + /// Whether panel `id` (from [`Containers::membership`]) is no more than a padded highlight + /// around `rect`: under 1.75 times its height on the page. + pub(super) fn hugs(&self, id: usize, rect: [f64; 4]) -> bool { + self.filled.get(id).is_some_and(|panel| panel.page[3] - panel.page[1] < (rect[3] - rect[1]) * 1.75) + } + + /// Whether panel `id` reaches across `rect` from its left edge to its right one on the page. + pub(super) fn spans(&self, id: usize, rect: [f64; 4]) -> bool { + let tolerance = (rect[3] - rect[1]) * 0.25; + self.filled.get(id).is_some_and(|panel| panel.page[0] <= rect[0] + tolerance && panel.page[2] >= rect[2] - tolerance) + } +} + +struct Collector<'a> { + doc: &'a Document, + containers: Containers, + path: Vec, + budget: super::lines::FormBudget, +} + +impl Collector<'_> { + fn walk(&mut self, ops: &[Op], resources: &Dict, initial: Matrix, prefix: &[usize]) { + let mut local = Containers::default(); + let mut ctm = initial; + let mut stack = Vec::new(); + for (i, op) in ops.iter().enumerate() { + let at = [prefix, &[i]].concat(); + local.observe(op, ctm, &at); + match op.op.as_slice() { + b"q" => stack.push(ctm), + b"Q" => { + if let Some(saved) = stack.pop() { + ctm = saved; + } + } + b"cm" => { + if let Some(matrix) = op.nums::<6>() { + ctm = Matrix(matrix).then(&ctm); + } + } + b"Do" => { + if let Some(name) = op.name(0) + && let Some(form) = super::lines::form_call(self.doc, resources, name, ctm, &self.path, &mut self.budget) + { + if let Some(obj) = form.obj { + self.path.push(obj); + } + self.walk(&pdfcraft_content::parse(&form.data).ops, form.resources(resources), form.ctm, &at); + if form.obj.is_some() { + self.path.pop(); + } + } + } + _ => {} + } + } + let remaining = 4096_usize.saturating_sub(self.containers.filled.len()); + self.containers.filled.extend(local.filled.into_iter().take(remaining)); + } +} diff --git a/crates/edit/src/text_regions/grouping.rs b/crates/edit/src/text_regions/grouping.rs index 72a516292d..2195c6c6ae 100644 --- a/crates/edit/src/text_regions/grouping.rs +++ b/crates/edit/src/text_regions/grouping.rs @@ -5,6 +5,7 @@ fn same_plane(a: &TextLine, b: &TextLine) -> bool { let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm)); a.scope == b.scope && a.paint == b.paint + && a.containers == b.containers && [0, 2].iter().all(|axis| { let ax = at.0.get(*axis).copied().unwrap_or(0.0); let ay = at.0.get(axis + 1).copied().unwrap_or(0.0); @@ -351,7 +352,7 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec { // The rewrite sets every row in the first one's horizontal scale. && (prev.origin.state.scale - first.origin.state.scale).abs() < 1e-6 && aligned - && first.size.min(prev.size) >= first.size.max(prev.size) * 0.4 + && super::super::row_style::compatible(prev_row, row, lines) && gap > first.size.min(prev.size) * 0.8 && gap < max_gap }); diff --git a/crates/edit/src/text_regions/styled.rs b/crates/edit/src/text_regions/styled.rs index f257020a22..ff475f4e22 100644 --- a/crates/edit/src/text_regions/styled.rs +++ b/crates/edit/src/text_regions/styled.rs @@ -565,8 +565,51 @@ fn validate_contextual_rows(rows: &[Vec], kept: &[bool]) -> Result<( Ok(()) } +fn line_nominal_width( + index: usize, + source: &TextLine, + chars: &[(char, usize, String)], + metrics: &std::collections::BTreeMap, + space_of: &impl Fn(&str, &Metrics) -> f64, +) -> Option { + let font_name = metrics + .get(&source.font) + .filter(|m| source_encodes(m, &source.text)) + .map(|_| &source.font) + .or_else(|| chars.iter().find(|c| c.1 == index && c.0 != '\n').map(|c| &c.2)); + let width_in = |name: &str, m: &Metrics, text: &str| { + source_width( + m, + text, + source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s), + space_of(name, m), + source.origin.state.char_spacing, + source.origin.state.word_spacing, + ) + }; + font_name.and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| width_in(name, m, &source.text))).or_else(|| { + // Generated same-face subsets can form one source line even though no one + // subset encodes it all. Measure the ORIGINAL text, not the edited draft: + // adding characters must retain the source's spacing, not squeeze to its width. + // Shaped text has a separate authoritative advance below. + if source.face.is_none() || pdfcraft_fonts::source_shaping::required(&source.text) { + return None; + } + let face = pdfcraft_fonts::embedding::face_key(&source.base_font); + source.text.chars().try_fold(0.0, |width, ch| { + let text = ch.to_string(); + let (name, m) = metrics + .get_key_value(&source.font) + .filter(|(_, m)| source_encodes(m, &text)) + .or_else(|| metrics.iter().find(|(_, m)| pdfcraft_fonts::embedding::face_key(&m.base_font) == face && source_encodes(m, &text)))?; + Some(width + width_in(name, m, &text)) + }) + }) +} + fn calibration_factors( lines: &[TextLine], + chars: &[(char, usize, String)], metrics: &std::collections::BTreeMap, style: &BlockStyle, overrides: &HashMap, @@ -574,16 +617,8 @@ fn calibration_factors( ) -> HashMap { let mut calibration = HashMap::new(); for (index, source) in lines.iter().enumerate() { - if let Some(metrics) = metrics.get(&source.font) { - let nominal = source_width( - metrics, - &source.text, - source.origin.state.font.as_ref().map_or(1.0, |(_, size)| *size), - space_of(&source.font, metrics), - source.origin.state.char_spacing, - source.origin.state.word_spacing, - ) * source.origin.state.scale - * across(source); + if let Some(nominal) = line_nominal_width(index, source, chars, metrics, &space_of) { + let nominal = nominal * source.origin.state.scale * across(source); let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|range| range.family.is_some() || range.resource.is_some()); let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 }; @@ -1917,7 +1952,7 @@ pub(crate) fn rewrite_styled_block( spaces.borrow_mut().insert(name.to_owned(), w); w }; - let mut calibration = calibration_factors(lines, &metrics, style, &overrides, space_of); + let mut calibration = calibration_factors(lines, &chars, &metrics, style, &overrides, space_of); fit_to_phrase(&mut calibration, lines, phrase_size); let advance = |item: &(char, usize, String)| -> f64 { let source = lines.get(item.1).unwrap_or(first); diff --git a/crates/edit/src/text_row_style.rs b/crates/edit/src/text_row_style.rs new file mode 100644 index 0000000000..d4db725065 --- /dev/null +++ b/crates/edit/src/text_row_style.rs @@ -0,0 +1,44 @@ +//! Row-level typography compatibility, independent of inline style boundaries. + +use super::TextLine; + +fn family(line: &TextLine) -> String { + const SUFFIXES: [&str; 16] = [ + "bolditalic", + "boldoblique", + "semibold", + "demibold", + "regular", + "boldit", + "italic", + "oblique", + "medium", + "light", + "bold", + "roman", + "psmt", + "mt", + "ps", + "it", + ]; + let mut key = pdfcraft_fonts::embedding::face_key(&line.base_font); + // Weight and style suffixes stack (TimesNewRomanPS-BoldMT), so strip until none is left. + while let Some(base) = SUFFIXES.iter().find_map(|suffix| key.strip_suffix(suffix)).filter(|base| !base.is_empty()) { + key = base.to_owned(); + } + key +} + +pub(super) fn compatible(previous: &[usize], next: &[usize], lines: &[TextLine]) -> bool { + let representative = + |row: &[usize]| row.iter().filter_map(|index| lines.get(*index)).max_by(|a, b| (a.rect[2] - a.rect[0]).total_cmp(&(b.rect[2] - b.rect[0]))); + match (representative(previous), representative(next)) { + (Some(previous), Some(next)) => { + // A row in one of the generated fallback faces holds characters the paragraph's own + // font lacks; the edit chose that face, so it is no change of family. + previous.size.min(next.size) >= previous.size.max(next.size) * 0.65 + && (previous.face.is_some() || next.face.is_some() || family(previous) == family(next)) + } + _ => false, + } +} diff --git a/crates/engine/src/autotag.rs b/crates/engine/src/autotag.rs index 07b5d2dcff..2aba97aacb 100644 --- a/crates/engine/src/autotag.rs +++ b/crates/engine/src/autotag.rs @@ -83,4 +83,12 @@ impl Document { .collect(); Ok(Preview { candidates, unclassified_images: self.page_images(page).len(), unclassified_text_blocks, existing_structure }) } + + /// The running headers, footers and page numbers that applying auto-tag would mark as + /// pagination artifacts. Reads the working PDF and does not alter it; refuses what auto-tag + /// refuses. + pub fn autotag_running_text(&self) -> Result, String> { + let editor = self.editor.as_ref().ok_or("the document can't be read")?; + crate::a11y::running_text(&editor.cos).map_err(|e| e.to_string()) + } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index f65a219252..d6e5e4ca2d 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -306,7 +306,7 @@ pub const COMMANDS: &[CommandSpec] = &[ c("comment.underline", "Underline text", None, None, Annotate, "text_underline"), c("comment.strikeout", "Strikethrough text", None, None, Annotate, "text_strikethrough"), c("comment.squiggly", "Squiggly underline text", None, None, Annotate, "spline"), - c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "highlighter"), + c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "freehand-highlighter"), c("comment.ink", "Draw freehand", None, None, Annotate, "pencil"), c("comment.line", "Draw a line", None, None, Annotate, "minus"), c("comment.arrow", "Draw an arrow", None, None, Annotate, "move-right"), diff --git a/crates/engine/src/copy_image.rs b/crates/engine/src/copy_image.rs index 3db00a28d2..057d6b1249 100644 --- a/crates/engine/src/copy_image.rs +++ b/crates/engine/src/copy_image.rs @@ -46,7 +46,7 @@ impl Document { self.page_images(page).iter().rposition(|i| { i.contains(at) && match (i.is_form, i.object) { - (false, Some(_)) => true, + (false, Some(_)) => self.image_shows_at(i, at), (true, Some(form)) => picture_in_form(&editor.cos, form).is_some(), _ => false, } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9ce402e1c2..d6974d7dd5 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -34,9 +34,14 @@ pub enum ImageEdit { /// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a /// filled-in PDF form), as CSV with one row per file. pub fn merge_data_files(files: &[(String, Vec)]) -> Result { + merge_data_files_with_columns(files).map(|(csv, _)| csv) +} + +/// Merge the files to CSV and report the distinct field count. +pub fn merge_data_files_with_columns(files: &[(String, Vec)]) -> Result<(String, usize), String> { let rows = files.iter().map(|(name, bytes)| pdfcraft_xfdf::data_values(bytes).map_err(|e| format!("{name}: {e}"))).collect::, _>>()?; - Ok(pdfcraft_xfdf::merge_csv(&rows)) + Ok(pdfcraft_xfdf::merge_csv_with_columns(&rows)) } /// One file produced by a split: (1-based first page, last page, PDF bytes). @@ -116,6 +121,21 @@ pub(crate) fn signatures_of( pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache) } +/// Validate the signature fields of `editor`'s working state (written as `bytes`). While that +/// state is still the file as opened plus only what opening appended, the file as read is +/// validated instead: PdfCraft's own open-time revisions are not changes made since signing. +pub(crate) fn editor_signatures( + editor: &crate::history::Editor, + bytes: &[u8], + trust: &TrustStore, + cache: &pdfcraft_sign::DigestCache, +) -> Vec { + match &editor.as_opened { + Some(o) if !editor.cos.is_modified() && Arc::ptr_eq(editor.cos.bytes(), &editor.saved) => signatures_of(&o.cos, &o.bytes, trust, cache), + _ => signatures_of(&editor.cos, bytes, trust, cache), + } +} + /// What Optimize PDF did. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct OptimizeReport { diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 7b39e15660..cf3b004ed8 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -65,6 +65,10 @@ pub struct Document { /// since they last gained focus: their exit on losing focus has run already /// ([`Session::field_focus`]). pub(crate) xfa_exited: std::collections::HashSet, + /// An XFA button click run on a worker ([`Session::start_javascript_target`]) had a script + /// run away: the next edit turns the form's scripts off, as it would have had the click been + /// kept (it may have been dropped: the document changed, or the app stopped waiting). + pub(crate) xfa_ran_away: std::sync::Arc, /// A content-only refresh keeps `info` from before the edit; an edit may have added or /// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]). pub(crate) fonts_stale: bool, @@ -76,6 +80,8 @@ pub struct Document { /// applied redactions left that still hold the removed text. The interface shows it; tools /// return it. pub edit_notices: Vec, + /// Which parts of pictures with transparency show, for picking them ([`Document::image_shows_at`]). + pub(crate) alpha: crate::image_alpha::AlphaCache, } /// Something the last successful edit did that the user should hear about, never left silent @@ -437,6 +443,16 @@ impl Document { self.editor.as_ref().map(|e| crate::text_style_bookmarks::styles(&e.cos)).unwrap_or_default() } + /// Suggest outline (#6020): the bookmark tree proposed for the document, from its tagged + /// headings or else from how its text looks. `None` when the document doesn't allow copying + /// (the titles are its text) or can't be read for editing. + pub fn suggest_outline(&self) -> Option { + if !self.allows_copying() { + return None; + } + self.editor.as_ref().map(|e| crate::suggest_outline::suggest(&e.cos)) + } + /// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based). pub fn text_lines(&self, page: usize) -> Vec { self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default() @@ -606,6 +622,21 @@ impl Document { .marks } + /// The headers and footers Update can tell apart (`pdfcraft_edit::header_footers`). + pub fn header_footers(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_edit::header_footers(&e.cos)).unwrap_or_default() + } + + /// The header and footer added last to page `page` (`pdfcraft_edit::newest_header_footer`). + pub fn newest_header_footer(&self, page: usize) -> Option> { + self.editor.as_ref().and_then(|e| pdfcraft_edit::newest_header_footer(&e.cos, page)) + } + + /// Pages whose header and footer records no settings (`pdfcraft_edit::unrecorded_header_footer_pages`). + pub fn unrecorded_header_footer_pages(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_edit::unrecorded_header_footer_pages(&e.cos)).unwrap_or_default() + } + /// Text and images added with Edit a PDF ▸ Add content (still editable). pub fn added(&self) -> &[pdfcraft_edit::Added] { &self diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index bd65f1fa5f..17bd69c92a 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -556,6 +556,13 @@ pub enum Edit { settings: HeaderFooter, replace: bool, }, + /// Update one header and footer: `old` (settings from `Document::header_footers`) goes from + /// every page it is on and `settings` is added to `pages`. Others stay. + UpdateHeaderFooter { + old: HeaderFooter, + pages: Vec, + settings: HeaderFooter, + }, /// `file`: a picture from a file (an image, or a page of a PDF) instead of text. AddWatermark { pages: Vec, diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 829afea516..51d19043e4 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -316,7 +316,7 @@ impl Edit { ImageEdit::Ungroup => "Ungroup artwork", }), Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"), - Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"), + Edit::AddHeaderFooter { .. } | Edit::UpdateHeaderFooter { .. } => Label::of("Update header & footer"), Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"), Edit::AddWatermark { .. } => Label::of("Update watermark"), Edit::AddBackground { replace: false, .. } => Label::of("Add background"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 58a2609db6..abeeeae8ac 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -110,6 +110,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re } Edit::SetInfo { .. } | Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } | Edit::AddPrinterMarks { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } @@ -260,6 +261,10 @@ pub(crate) struct EditCtx { pub(crate) xfa_unchanged: bool, /// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]). pub(crate) xfa_time_scale: u32, + /// The answers the edit's XFA event takes ([`Session::xfa_answers`](crate::Session)). + pub(crate) xfa_answers: xfa::XfaAnswers, + /// The form's scripts or new data laid it out again: its pages and widgets were replaced. + pub(crate) xfa_relaid: bool, /// The edit took the XFA out of the form: what went with it, for the document's warnings. pub(crate) xfa_removed: Vec, /// Pages in the document, for `xfa.layout.pageCount()`. @@ -331,6 +336,8 @@ impl EditCtx { xfa_ran_away: false, xfa_unchanged: false, xfa_time_scale: 1, + xfa_answers: Default::default(), + xfa_relaid: false, xfa_removed: Vec::new(), pages: 0, highlight: false, @@ -609,11 +616,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E pdfcraft_organize::import_outline(doc, parent, *index, bookmarks, *replace)?; } Edit::BookmarksFromStructure => { - let entries: Vec<_> = pdfcraft_a11y::headings(doc) - .into_iter() - .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }) - .collect(); - pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?; + pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc).0)?; } Edit::BookmarksFromTextStyles { levels } => { if levels.is_empty() { @@ -795,6 +798,8 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E ran_away: false, highlight, time_scale: cx.xfa_time_scale, + answers: std::mem::take(&mut cx.xfa_answers), + relaid: false, }; let ran = if matches!(activity.as_str(), "enter" | "exit") { xfa::on_focus(doc, &tpl, som, activity, &mut run).map(|changes| changes.is_empty()) @@ -803,10 +808,14 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E }; cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; + // The next XFA run of a batch starts from the page count this one left. + cx.pages = run.page_count; + cx.xfa_relaid |= run.relaid; // The next edit of a batch reads the highlight this one's scripts set. let on = run.highlight; cx.set_highlight(on); - cx.xfa_unchanged = ran.map_err(EditError::Invalid)?; + // A form laid out again changed, whatever its scripts counted. + cx.xfa_unchanged = ran.map_err(EditError::Invalid)? && !cx.xfa_relaid; } Edit::SetFieldImage { name, image } | Edit::SetFieldImageTarget { name, image, .. } => { let object = match edit { @@ -967,6 +976,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E let date = cx.today; pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?; } + Edit::UpdateHeaderFooter { old, pages, settings } => { + let date = cx.today; + pdfcraft_edit::update_header_footer(doc, old, pages, settings, &pdfcraft_edit::Context { date })?; + } Edit::AddWatermark { pages, settings, replace, file } => { let mut s = settings.clone(); if let Some(f) = file { diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 5ee915fcdf..75b239cbd2 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -78,3 +78,12 @@ impl From for EditError { EditError::Sign(e.to_string()) } } + +impl EditError { + /// A field's validate action refused the value it was given (ISO 32000-2 Table 199 `/V`). + /// The document is unchanged and the field keeps its value; an interface drops the typing + /// rather than holding the user in the field. + pub fn is_rejected_value(&self) -> bool { + matches!(self, EditError::Form(pdfcraft_forms::FormError::Rejected(_))) + } +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 393c233297..8c5578221d 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -103,6 +103,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope { | Edit::PasteContent { .. } | Edit::PasteObjects { .. } | Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. } @@ -150,6 +151,17 @@ pub(crate) struct Editor { pub(crate) field_appearances: pdfcraft_forms::FieldAppearanceCache, /// The text blocks last computed for one page, reused while the document is unchanged. pub(crate) text_blocks: TextBlocksCache, + /// A signed file that opening appended revisions to (an XFA form's layout, the values from + /// its data, its open scripts): the file as it was read, which the signatures are validated + /// against until the user changes something or saves (#2759). + pub(crate) as_opened: Option, +} + +/// The file as read, before opening appended PdfCraft's own revisions to it. +#[derive(Clone)] +pub(crate) struct AsOpened { + pub(crate) cos: pdfcraft_cos::Document, + pub(crate) bytes: Arc>, } /// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the document state they were read diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs new file mode 100644 index 0000000000..8cb93070c2 --- /dev/null +++ b/crates/engine/src/image_alpha.rs @@ -0,0 +1,257 @@ +//! Edit text & images: a picture is picked where it shows, not across its whole box. A PNG +//! signature or a cut-out photo with a transparent margin overlaps its neighbours; clicking a +//! neighbour through that margin picked the transparent picture on top. +//! +//! A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil image +//! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its +//! pixels and kept until the document changes. A cell counts as opaque if any pixel +//! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without +//! transparency, Form artwork, pictures that show nowhere and pictures that can't be decoded +//! keep their whole box. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use pdfcraft_cos::{ObjRef, Object}; + +use crate::Document; + +/// The opacity grid's largest side, in cells. +const MAX_GRID: u32 = 256; +/// Grids kept at once (at most 64 KiB each); past this the cache starts over. +const MAX_CACHED: usize = 256; +/// Pictures larger than this many pixels keep their whole box rather than being decoded. +const MAX_DECODE_PIXELS: u64 = 64_000_000; +/// Alpha at or above this (of 255) counts as showing. +const OPAQUE: u8 = 16; +/// Colour components assumed for a colour space that can't be read: as many as a DeviceN space +/// may have in practice, so the decoding bound stays generous. +const MAX_COMPONENTS: u64 = 32; +/// Decoded bytes allowed past what a picture's declared size needs (with a quarter more), for +/// padding writers leave after the samples. +const DECODE_SLACK: u64 = 64 << 10; + +/// Which cells of a picture show, row 0 at the top of the picture. +#[derive(Debug)] +pub(crate) struct Opacity { + width: u32, + height: u32, + cells: Vec, +} + +/// Opacity grids by picture object, for the document generation they were built at; `None` for +/// a picture that is opaque everywhere, shows nowhere or couldn't be read (its whole box counts). The +/// generation, not the picture object alone, says when to rebuild: an edit may change the +/// picture's soft mask without touching the picture. +type Grids = (u64, HashMap>>); + +#[derive(Default)] +pub(crate) struct AlphaCache(Mutex); + +impl Document { + /// Whether `image` shows at user-space `point` (assumed inside its placement): `false` only + /// where a picture with transparency is see-through. Form artwork, pictures without + /// transparency and pictures that can't be read show everywhere in their box. + pub fn image_shows_at(&self, image: &pdfcraft_edit::PageImage, point: [f64; 2]) -> bool { + if image.is_form { + return true; + } + let Some(object) = image.object else { return true }; + let Some(grid) = self.opacity(object) else { return true }; + let Some((x, y)) = unit_point(image.matrix, point) else { return true }; + if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) { + return true; + } + // Image space: row 0 is the top of the unit square (y = 1). + let col = ((x * f64::from(grid.width)) as u32).min(grid.width.saturating_sub(1)); + let row = (((1.0 - y) * f64::from(grid.height)) as u32).min(grid.height.saturating_sub(1)); + let at = usize::try_from(u64::from(row) * u64::from(grid.width) + u64::from(col)).unwrap_or(usize::MAX); + grid.cells.get(at).copied().unwrap_or(true) + } + + /// The opacity grid of picture `object`, built on first use and kept until the document + /// changes. + fn opacity(&self, object: ObjRef) -> Option> { + let editor = self.editor.as_ref()?; + // A poisoned cache is only a cache: build without it. + if let Ok(cache) = self.alpha.0.lock() + && cache.0 == self.generation + && let Some(grid) = cache.1.get(&object) + { + return grid.clone(); + } + let grid = build(&editor.cos, object).map(Arc::new); + if let Ok(mut cache) = self.alpha.0.lock() { + if cache.0 != self.generation || cache.1.len() >= MAX_CACHED { + *cache = (self.generation, HashMap::new()); + } + cache.1.insert(object, grid.clone()); + } + grid + } +} + +/// The picture's opacity grid, or `None` when it is opaque everywhere or can't be read. +fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { + let current = cos.get(object); + let Object::Stream(s) = &*current else { return None }; + let stencil = flag(cos, s, b"ImageMask"); + let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None")); + let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0); + if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) { + return None; + } + // The picture and the mask images it brings are decoded in full before anything is scaled + // down to the picture's size, so each must be small enough, in pixels and in decoded bytes, + // before any of it is decoded. + // One decoding allowance for the picture and its masks (`ImageBudget`), however many there are. + let mut budget = pdfcraft_cos::ImageBudget::new(cos); + let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) }; + if !within_budget(cos, &mut budget, s, components, stencil) { + return None; + } + for key in [&b"SMask"[..], b"Mask"] { + if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref() + && !within_budget(cos, &mut budget, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + { + return None; + } + } + let (_, bytes) = pdfcraft_create::image_file_within(cos, object, &mut budget).ok()?; + let format = image::guess_format(&bytes).ok()?; + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_DECODE_PIXELS.saturating_mul(4)); + reader.limits(limits); + let picture = reader.decode().ok()?; + let (w, h) = (picture.width(), picture.height()); + if w == 0 || h == 0 { + return None; + } + let shows: Box bool> = if picture.color().has_alpha() { + let rgba = picture.into_rgba8(); + Box::new(move |x, y| rgba.get_pixel_checked(x, y).is_none_or(|p| p.0[3] >= OPAQUE)) + } else if stencil { + // The export draws a stencil image's painted samples white, whatever its `/Decode`. + let luma = picture.into_luma8(); + Box::new(move |x, y| luma.get_pixel_checked(x, y).is_none_or(|p| p.0[0] >= 128)) + } else { + return None; + }; + let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID)); + let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?]; + for y in 0..h { + let rows = cells_covered(y, h, gh); + for x in 0..w { + if shows(x, y) { + // Every cell the pixel reaches into shows: a point anywhere on a showing pixel + // picks the picture, also where the pixel crosses into the next cell. + for row in rows.clone() { + for col in cells_covered(x, w, gw) { + if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { + *cell = true; + } + } + } + } + } + } + // A picture that shows everywhere, or nowhere (a faint watermark, a transparent + // placeholder), keeps its whole box: one that showed nowhere couldn't be picked at all. + if cells.iter().all(|c| *c) || !cells.iter().any(|c| *c) { + return None; + } + Some(Opacity { width: gw, height: gh, cells }) +} + +/// The grid cells, along an axis of `pixels` pixels and `cells` cells, that pixel `i` reaches +/// into: from the cell its start is in to the cell its end is in. `cells` is at most `pixels`, so +/// a pixel reaches into at most two. +fn cells_covered(i: u32, pixels: u32, cells: u32) -> std::ops::Range { + let (i, pixels, cells) = (u64::from(i), u64::from(pixels).max(1), u64::from(cells)); + let start = i * cells / pixels; + let end = ((i + 1) * cells).div_ceil(pixels).min(cells); + start..end.max(start) +} + +/// Whether the boolean `key` of image stream `s` is `true`. +fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> bool { + s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))) +} + +/// Whether image stream `s`, of `components` colour components (one bit each for a `stencil`), +/// is small enough to decode for its opacity grid: at most [`MAX_DECODE_PIXELS`] pixels and, when +/// its samples are decoded through its filters, no more decoded bytes than its declared size +/// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1 +/// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG, +/// JPEG 2000 and JBIG2 data go to their own decoders instead. The decode is charged to +/// `allowance`, the picture's shared [`ImageBudget`](pdfcraft_cos::ImageBudget). +fn within_budget( + cos: &pdfcraft_cos::Document, + allowance: &mut pdfcraft_cos::ImageBudget, + s: &pdfcraft_cos::Stream, + components: u64, + stencil: bool, +) -> bool { + let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); + let (w, h) = (size(b"Width"), size(b"Height")); + if w.saturating_mul(h) > MAX_DECODE_PIXELS { + return false; + } + let codec = match s.dict.get(b"Filter").map(|f| cos.resolve(f)).as_deref() { + Some(Object::Name(n)) => Some(n.clone()), + Some(Object::Array(a)) => a.last().and_then(Object::as_name).map(<[u8]>::to_vec), + _ => None, + }; + if matches!(codec.as_deref(), Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode")) { + return true; + } + let bpc = if stencil { 1 } else { u64::try_from(s.dict.int(b"BitsPerComponent").unwrap_or(8)).unwrap_or(8).clamp(1, 16) }; + let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8)); + let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK)); + let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false }; + allowance.decode(cos, s, budget).is_ok() +} + +/// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an +/// indexed or separation space, the `/N` of an ICC-based one, as many as a DeviceN space names. +/// A space that can't be read counts as [`MAX_COMPONENTS`], which keeps the decoding bound +/// generous rather than refusing the picture. +fn components(cos: &pdfcraft_cos::Document, space: Option<&Object>) -> u64 { + let Some(space) = space.map(|s| cos.resolve(s)) else { return MAX_COMPONENTS }; + let array = space.as_array(); + let family = match (&*space, array.and_then(|a| a.first()).and_then(Object::as_name)) { + (Object::Name(n), _) => n.as_slice(), + (_, Some(n)) => n, + _ => return MAX_COMPONENTS, + }; + let operand = || array.and_then(|a| a.get(1)).map(|o| cos.resolve(o)); + match family { + b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => 1, + b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => 3, + b"DeviceCMYK" | b"CMYK" => 4, + b"ICCBased" => match operand().as_deref() { + Some(Object::Stream(icc)) => { + icc.dict.int(b"N").and_then(|n| u64::try_from(n).ok()).filter(|n| (1..=MAX_COMPONENTS).contains(n)).unwrap_or(MAX_COMPONENTS) + } + _ => MAX_COMPONENTS, + }, + b"DeviceN" => match operand().as_deref() { + Some(Object::Array(names)) => u64::try_from(names.len()).unwrap_or(MAX_COMPONENTS).clamp(1, MAX_COMPONENTS), + _ => MAX_COMPONENTS, + }, + _ => MAX_COMPONENTS, + } +} + +/// `point` in the placement's unit square: the inverse of `matrix` applied to it. +fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> { + let det = m[0] * m[3] - m[1] * m[2]; + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let (dx, dy) = (point[0] - m[4], point[1] - m[5]); + let x = (m[3] * dx - m[2] * dy) / det; + let y = (m[0] * dy - m[1] * dx) / det; + (x.is_finite() && y.is_finite()).then_some((x, y)) +} diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index 6772e9828d..df6b8aa943 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -1193,24 +1193,18 @@ impl Session { let doc = self.get(id).ok_or(EditError::NoDocument)?; let cos = doc.editor.as_ref().map(|e| e.cos.clone()).ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?; validate_script_target(target, target_id, &doc.form)?; - // A button PdfCraft generated from an XFA template runs its XFA click script. - if let Some(t) = target - && event_name.is_none_or(|n| n == "Mouse Up") - && let Some(tpl) = doc.xfa_template.clone() - && let Some(field) = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id)) - && field.kind == crate::FormFieldKind::PushButton - && let Some(som) = crate::xfa::clickable_som(&cos, &tpl, field) + // A button PdfCraft generated from an XFA template runs its XFA click script, its + // message boxes taking `answers` (then their buttons' safe default: nobody is asked). + if event_name.is_none_or(|n| n == "Mouse Up") + && let Some(som) = xfa_click_som(doc, &cos, target, target_id) { + self.xfa_answers = Some(crate::xfa::XfaAnswers { given: answers.to_vec(), ..Default::default() }); // The click returns only the output of its own edit; output from opening or from earlier edits stays. - let ((), out) = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }))?; - return Ok(Outcome { - rc: true, - alerts: out.alerts, - console: out.console, - requests: out.requests, - error: out.errors.first().cloned(), - ..Default::default() - }); + let ran = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() })); + // Not taken when the edit stopped before it ran the event: no later edit takes it. + self.xfa_answers = None; + let ((), out) = ran?; + return Ok(xfa_click_outcome(out)); } let mut runner = JsRunner::new(&cos, &doc.name, self.field_highlight); runner.doc.zoom = doc.js_zoom; @@ -1353,6 +1347,15 @@ impl Session { self.after_script(id, &o, &written); Ok(o) } + + /// The script errors not taken yet, out of what [`Session::take_js_output`] returns; the + /// alerts, console lines and requests stay for that call. A document script's error taken + /// here is reported again when the document scripts fail again on a later edit. + pub fn take_js_errors(&mut self, id: DocId) -> Vec { + let Some(d) = self.docs.iter_mut().find(|d| d.id == id) else { return Vec::new() }; + d.js_output.doc_errors.clear(); + std::mem::take(&mut d.js_output.errors) + } } /// A page's words for form-field detection, in user space (underscore runs split from the @@ -1690,6 +1693,32 @@ mod caption_tests { } } +/// The SOM path of the XFA click script button `target` runs, when it is a push button PdfCraft +/// generated from a laid-out XFA form's template. +fn xfa_click_som(doc: &crate::Document, cos: &pdfcraft_cos::Document, target: Option<&str>, target_id: Option) -> Option { + let t = target?; + let tpl = doc.xfa_template.as_ref()?; + let field = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))?; + if field.kind != crate::FormFieldKind::PushButton { + return None; + } + crate::xfa::clickable_som(cos, tpl, field) +} + +/// What an XFA button click did, as a button script's outcome. +fn xfa_click_outcome(out: JsOutput) -> Outcome { + Outcome { rc: true, alerts: out.alerts, console: out.console, requests: out.requests, error: out.errors.first().cloned(), ..Default::default() } +} + +/// Stack for the thread an XFA button click runs on in the app: it lays the form out again, as +/// the app's main thread does for other edits. +#[cfg(not(target_arch = "wasm32"))] +const XFA_CLICK_STACK: usize = 8 << 20; + +/// An XFA button click's edit, once its worker has run it ([`Session::start_javascript_target`]). +#[cfg(not(target_arch = "wasm32"))] +type XfaClick = std::sync::Arc)>>>; + /// A failed link action commits nothing: its field changes, requests and layer changes are /// dropped (the realm put its timers back), its alerts, console lines and error kept (#2081). fn drop_failed_link_effects(o: &mut Outcome) { @@ -1813,6 +1842,16 @@ pub struct PendingScript { /// Whether the script may add or show pages from templates ([`may_change_pages`]). may_change_pages: bool, pub receiver: std::sync::mpsc::Receiver, + /// An XFA button click: its edit, filled in by its worker before it completes. + xfa: Option, +} +#[cfg(not(target_arch = "wasm32"))] +impl PendingScript { + /// Whether this is an XFA button's click ([`Session::start_javascript_target`]). It reads + /// no view state (zoom, page) the way an AcroForm script does, and its own limits bound it. + pub fn is_xfa(&self) -> bool { + self.xfa.is_some() + } } #[cfg(not(target_arch = "wasm32"))] impl Session { @@ -1837,12 +1876,15 @@ impl Session { } let doc = self.get(id).ok_or(EditError::NoDocument)?; let cos = &doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?.cos; + let fields = pdfcraft_forms::fields(cos); + validate_script_target(target, target_id, &fields)?; + if let Some(som) = xfa_click_som(doc, cos, target, target_id) { + return self.start_xfa_click(id, som); + } let mut runner = JsRunner::new(cos, &doc.name, self.field_highlight); runner.doc.zoom = doc.js_zoom; runner.doc.page = doc.js_page; runner.doc.layers = crate::live_scripts::js_layers(&doc.info); - let fields = pdfcraft_forms::fields(cos); - validate_script_target(target, target_id, &fields)?; let states = std::sync::Arc::new(fields.iter().map(|f| crate::live_scripts::live_state(doc, cos, f, &runner.doc)).collect::>()); let job = pdfcraft_js::session::Job { script: script.into(), @@ -1859,7 +1901,65 @@ impl Session { let receiver = doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?; let may_change_pages = may_change_pages(target, &fields); - Ok(PendingScript { id, link: false, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver }) + Ok(PendingScript { + id, + link: false, + generation: doc.generation, + runtime: doc.js_runtime.clone(), + states, + may_change_pages, + receiver, + xfa: None, + }) + } + + /// Start XFA button `som`'s click on a worker, so the app goes on drawing while it runs and + /// can ask its message boxes' questions: each comes through the pending script's receiver + /// as a prompt, and the script waits for the answer with its clock stopped. Once the worker + /// is done, [`Session::finish_javascript`] keeps the click as one undo step, as + /// [`Session::apply`] would, unless the document changed meanwhile. + fn start_xfa_click(&mut self, id: DocId, som: String) -> Result { + let (prompts, receiver) = std::sync::mpsc::channel(); + self.xfa_answers = Some(crate::xfa::XfaAnswers { prompts: Some(prompts.clone()), ..Default::default() }); + let begun = self.begin_edit(id, Edit::XfaEvent { som, activity: "click".into() }); + // Not taken when the edit stopped before it began. + self.xfa_answers = None; + let begun = begun?; + let doc = self.get(id).ok_or(EditError::NoDocument)?; + let click: XfaClick = Default::default(); + let pending = PendingScript { + id, + link: false, + generation: doc.generation, + runtime: doc.js_runtime.clone(), + states: Default::default(), + // Its edit is kept as an undo step of its own (`finish_javascript`), never applied as a + // script outcome, so it adds no pages from templates. + may_change_pages: false, + receiver, + xfa: Some(click.clone()), + }; + let Some(mut begun) = begun else { + // Nothing to run: done at once. + let _ = prompts.send(InteractiveEvent::Complete(Outcome::default())); + return Ok(pending); + }; + let ran_away = std::sync::Arc::clone(&doc.xfa_ran_away); + std::thread::Builder::new() + .name("pdfcraft-xfa-click".into()) + .stack_size(XFA_CLICK_STACK) + .spawn(move || { + let checked = crate::session::run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx); + if begun.cx.xfa_ran_away { + ran_away.store(true, std::sync::atomic::Ordering::Relaxed); + } + // A poisoned lock only means a panic elsewhere while it was held: the slot is still ours. + *click.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((begun, checked)); + // The app may have stopped waiting: then nobody takes the click. + let _ = prompts.send(InteractiveEvent::Complete(Outcome::default())); + }) + .map_err(|e| EditError::Invalid(format!("the form script could not start: {e}")))?; + Ok(pending) } /// Start link `index` on page `page` as [`Session::run_link_javascript`] runs it, without /// blocking on its prompts; [`Session::finish_javascript`] commits nothing if it failed. @@ -1870,10 +1970,23 @@ impl Session { doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?; // A link's script has the document as its target, as a document script does. let may_change_pages = may_change_pages(None, &[]); - Ok(PendingScript { id, link: true, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver }) + Ok(PendingScript { + id, + link: true, + generation: doc.generation, + runtime: doc.js_runtime.clone(), + states, + may_change_pages, + receiver, + xfa: None, + }) } /// Discard only the captured runtime, preserving a newer realm created by an intervening edit. pub fn discard_javascript(&mut self, p: &PendingScript) { + // An XFA click's worker holds no realm: what it did is dropped with the pending script. + if p.xfa.is_some() { + return; + } if let Some(doc) = self.docs.iter_mut().find(|d| d.id == p.id) && std::sync::Arc::ptr_eq(&doc.js_runtime, &p.runtime) { @@ -1882,6 +1995,10 @@ impl Session { } /// Discard a timed-out invocation and retain the worker slot until its thread exits. pub fn timeout_javascript(&mut self, p: PendingScript) { + // An XFA click's scripts are bounded on its worker; what it did is dropped. + if p.xfa.is_some() { + return; + } if self.script_pending_current(&p) && let Ok(mut runtime) = p.runtime.lock() { @@ -1893,6 +2010,21 @@ impl Session { /// Apply a current worker result, or discard it and reset the realm when the document changed. pub fn finish_javascript(&mut self, p: PendingScript, mut out: Outcome) -> Result { + if let Some(click) = &p.xfa { + if !self.script_pending_current(&p) { + return Err(EditError::Invalid("document changed while the script was running".into())); + } + let ran = click.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + let Some((begun, checked)) = ran else { return Ok(Outcome { rc: true, ..Default::default() }) }; + let ran_away = begun.cx.xfa_ran_away; + let ((), out) = self.with_own_js_output(p.id, |s| s.finish_edit(p.id, begun, checked).map(|_| ()))?; + // Kept, a click that ran away turned the scripts off itself: not again. A flag another + // click set (one this commit makes stale) stays for the next edit. + if ran_away && let Some(d) = self.get(p.id) { + d.xfa_ran_away.store(false, std::sync::atomic::Ordering::Relaxed); + } + return Ok(xfa_click_outcome(out)); + } if p.link { drop_failed_link_effects(&mut out); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8acd2e0f97..91093b7e5e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ pub mod field_table; mod fill_sign; pub mod find_replace; mod history; +mod image_alpha; pub mod js; mod layers; pub mod links; @@ -60,6 +61,7 @@ pub mod signature_scan; mod sources; pub mod spooler; mod stamp_preview; +pub mod suggest_outline; #[cfg(test)] mod test_hooks; pub mod text_fonts; @@ -96,7 +98,7 @@ pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnific pub use pdfcraft_cos::{Algorithm, civil_from_days}; pub use pdfcraft_create::{ - CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, decode_text, source_kind, + CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImagePage, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, decode_text, source_kind, }; pub use pdfcraft_edit::added::{ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect, @@ -105,7 +107,7 @@ pub use pdfcraft_edit::added::{ pub use pdfcraft_edit::paragraph_align; pub use pdfcraft_edit::{ Added, AddedImage, AddedText, Align as TextAlign, Background, ColourTarget, ColoursConverted, Content as AddedContent, ConvertColours, - Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, Ink as TextInk, MarkKind, PrinterMarks, Watermark, + Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, HeaderFooterMark, Ink as TextInk, MarkKind, PrinterMarks, Watermark, }; pub use pdfcraft_forms::{ BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont, @@ -190,8 +192,8 @@ mod doc_state; pub use pdfcraft_edit::ArrangeOrder; use clock::{local_utc_offset, parse_ymd}; -pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files}; -use doc_state::{LOW_RESOLUTION_PRINT_DPI, render_threads, renderer_password, signatures_of, writable}; +pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files, merge_data_files_with_columns}; +use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable}; /// The configuration of the pool that draws the viewer: the document's own, plus installed CJK /// fonts for fonts a PDF does not embed (`pdfcraft_render::RenderConfig::system_fonts`). Exports, diff --git a/crates/engine/src/open.rs b/crates/engine/src/open.rs index c298636c3d..a0b022354f 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -5,11 +5,11 @@ use std::sync::{Arc, OnceLock}; use pdfcraft_cos::{SaveOptions, write_incremental}; use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect}; -use crate::history::{Editor, Keys, TextBlocksCache}; +use crate::history::{AsOpened, Editor, Keys, TextBlocksCache}; use crate::{ - AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard, - info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, - xfa_values_from_datasets, + AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, + editor_signatures, guard, info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, xfa, + xfa_layout, xfa_values_from_datasets, }; /// Immutable session state needed while a document is prepared away from its owning thread. @@ -37,6 +37,8 @@ struct DocumentOpenData<'a> { render_password: Option, password: Option<&'a str>, xfa: Option, + /// The file as read, when opening appended revisions to it ([`crate::history::AsOpened`]). + as_opened: Option, } impl OpenContext { @@ -152,6 +154,11 @@ impl Session { } Ok((new_bytes, new_info, new_cos)) }; + // The file as read, for its signatures: opening an XFA form may append revisions below. + let as_read = match (&info.xfa, &cos) { + (Some(_), Ok(Ok(c))) => Some(AsOpened { cos: c.clone(), bytes: bytes.clone() }), + _ => None, + }; let (bytes, info, cos, xfa) = match (info.xfa, cos) { (Some(pdfcraft_render::Xfa::Dynamic), Ok(Ok(cos))) if pdfcraft_xfa::existing_layout(&cos).is_none() => { let mut work = cos.clone(); @@ -225,6 +232,8 @@ impl Session { ran_away: false, highlight: context.highlight, time_scale: context.xfa_time_scale, + answers: Default::default(), + relaid: false, }; let changes = xfa::on_open(&mut work, &tpl, &mut run); if run.ran_away { @@ -285,8 +294,9 @@ impl Session { }; // XFA notes survive the document being re-read after edits. let xfa_warnings: Vec = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() }; + let as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes)); let mut document = - Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa }); + Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa, as_opened }); // A script that ran away on open turns the form's scripts off for this document. document.xfa_template = if ran_away { None } else { xfa_template }; document.js_output.append(script_output); @@ -300,7 +310,7 @@ impl Session { /// The last step of opening: build the document record and register it. fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document { - let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data; + let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa, as_opened } = data; let mut config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() }; let (mut editor, read_only_reason) = match cos { Ok(Ok(cos)) => { @@ -318,6 +328,7 @@ impl Session { appearances: AppearanceCache::default(), field_appearances: pdfcraft_forms::FieldAppearanceCache::default(), text_blocks: TextBlocksCache::default(), + as_opened, }), None, ) @@ -326,7 +337,13 @@ impl Session { Err(_) => (None, Some("the document structure could not be read for editing".into())), }; let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default()); - let mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.trust, &sig_cache)).unwrap_or_default(); + let mut signatures = editor.as_ref().map(|e| editor_signatures(e, &bytes, &context.trust, &sig_cache)).unwrap_or_default(); + // Only a signed file needs keeping as it was read. + if !signatures.iter().any(|s| s.signed) + && let Some(e) = editor.as_mut() + { + e.as_opened = None; + } // The inspection reads only `/Info`; a file stating its title or author only in XMP still // shows them (#2373). if let Some(e) = &editor { @@ -389,9 +406,11 @@ impl Session { xfa_template: None, xfa_scripts_off: false, xfa_exited: Default::default(), + xfa_ran_away: Default::default(), fonts_stale: false, xfa_warnings: Vec::new(), edit_notices: Vec::new(), + alpha: Default::default(), } } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 187cc217d8..1b3d187913 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,16 +10,18 @@ use crate::check_refresh_panic; use crate::edit::{EditCtx, check_permission, run_edit}; use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts}; use crate::{ - BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, + BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, StatusCaptions, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, - comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, office_to_pdf, open_source, - open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, scan_colours, - set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, + comment_summary, decode_text, display_bytes, display_config, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings, + office_to_pdf, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, + scan_colours, set_default_layer_state, shown_under_redactions, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets, }; mod editing; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use editing::{BegunEdit, run_checked_edit}; mod files; mod save; mod view; @@ -35,10 +37,14 @@ pub struct Session { /// injected time AS local time and zeroes the zone, so injecting only it leaves either the /// local dates or the UTC ones wrong by the zone's offset. utc_offset: Option i64>, - /// Certificates trusted for signing (Acrobat: Trusted Certificates). + /// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the + /// trust lists they loaded. pub(crate) trust: Arc, /// The words signature status layers are drawn with, in the interface language. pub(crate) captions: Arc, + /// How often every open document's signatures were validated again after a trust change. + #[cfg(test)] + pub(crate) revalidations: usize, /// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default). pub(crate) js_off: bool, /// Preferences ▸ Date format, when not the default (see [`dates`]). @@ -51,4 +57,7 @@ pub struct Session { /// What the XFA scripts' time limits are multiplied by (`None`: 1); see /// [`Session::with_xfa_time_scale`]. pub(crate) xfa_time_scale: Option, + /// The answers the next XFA event takes for its message boxes, set by the caller running it + /// (`js_run`'s answers, an app's button click) and taken by that event's edit. + pub(crate) xfa_answers: Option, } diff --git a/crates/engine/src/session/editing.rs b/crates/engine/src/session/editing.rs index 49c5bc7dbb..6e0adcb346 100644 --- a/crates/engine/src/session/editing.rs +++ b/crates/engine/src/session/editing.rs @@ -2,9 +2,9 @@ use super::check_refresh_panic; use super::{ Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session, - XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, guard, info_fields, - inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, - undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets, + XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, editor_signatures, + guard, info_fields, inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, + sync_xfa_state, undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets, }; use crate::{EditNotice, MarkKind, print_preview_layers}; @@ -46,7 +46,7 @@ fn deletes_pages(edit: &Edit) -> bool { } /// Keep edits to the working copy until both the operation and its script callbacks succeed. -fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> { +pub(crate) fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> { let result = guard(|| run_edit(next, edit, cx)) .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label())))); let refusal = cx.js.as_mut().and_then(|runner| runner.refused.take()); @@ -122,6 +122,20 @@ fn sync_script_history(doc: &Document, previous: &pdfcraft_cos::Document, restor } } +/// An edit between [`Session::begin_edit`] and [`Session::finish_edit`]: the copy of the +/// document it runs on (`next`) and its context. Send, so an XFA button click can run on a +/// worker while the app goes on drawing and asks the click's questions. +pub(crate) struct BegunEdit { + pub(crate) edit: Edit, + pub(crate) next: pdfcraft_cos::Document, + pub(crate) cx: EditCtx, + scope: Scope, + is_xfa: bool, + signed: bool, + /// The document's generation it was made from: a changed document doesn't take it. + generation: u64, +} + impl Session { /// Apply an edit. On success the previous state is undoable and the view data is refreshed. pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> { @@ -138,12 +152,27 @@ impl Session { /// [`Session::apply`], giving back what an [`Edit::PrepareText`] did (`None` for other edits). fn apply_reporting(&mut self, id: DocId, edit: Edit) -> Result, EditError> { + let Some(mut begun) = self.begin_edit(id, edit)? else { return Ok(None) }; + // `next` is a copy: if the edit fails or crashes, the document is unchanged. + let checked = run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx); + self.finish_edit(id, begun, checked) + } + + /// The first part of [`Session::apply`]: check that `edit` may be made, and make the copy of + /// the document it runs on, with its context. `None`: there is nothing to do. + pub(crate) fn begin_edit(&mut self, id: DocId, edit: Edit) -> Result, EditError> { let now = self.now(); let today = self.today(); let js_off = self.js_off; let highlight = self.field_highlight; let xfa_time_scale = self.xfa_time_scale.unwrap_or(1); + let xfa_answers = self.xfa_answers.take().unwrap_or_default(); let doc = self.doc_mut(id)?; + // A script of an XFA click run on a worker ran away: the form's scripts go off, whether + // or not the click was kept. + if doc.xfa_ran_away.swap(false, std::sync::atomic::Ordering::Relaxed) { + take_xfa_output(doc, js::JsOutput::default(), true); + } // An edit must never read globals from a completed-but-unapplied button invocation. // Fork its realm before any edit-triggered calculation, even if the edit later fails. #[cfg(not(target_arch = "wasm32"))] @@ -153,12 +182,13 @@ impl Session { doc.edit_notices.clear(); let name = doc.name.clone(); let is_xfa = doc.info.xfa.is_some(); - let mut scope = scope_of(&edit); + let scope = scope_of(&edit); let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48)); if !js_off { cx.xfa = doc.xfa_template.clone(); } cx.xfa_time_scale = xfa_time_scale; + cx.xfa_answers = xfa_answers; cx.pages = doc.info.pages.len(); cx.highlight = highlight; cx.today = today; @@ -175,7 +205,7 @@ impl Session { if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) { return Ok(None); } - let mut next = editor.cos.clone(); + let next = editor.cos.clone(); if !js_off && uses_scripts(&edit) { let mut runner = js::JsRunner::new(&next, &name, highlight); runner.runtime = doc.js_runtime.clone(); @@ -187,8 +217,27 @@ impl Session { cx.renamed_fields.clear(); cx.redaction_overlays.clear(); cx.redaction_marks.clear(); - // `next` is a copy: if the edit fails or crashes, the document is unchanged. - run_checked_edit(&mut next, &edit, &mut cx)?; + Ok(Some(BegunEdit { edit, next, cx, scope, is_xfa, signed, generation: doc.generation })) + } + + /// The last part of [`Session::apply`]: keep the edit [`Session::begin_edit`] prepared once + /// it ran (`checked`), as one undo step, unless it failed or the document changed meanwhile + /// (an XFA button click runs on a worker: [`Session::start_javascript_target`]). + pub(crate) fn finish_edit( + &mut self, + id: DocId, + begun: BegunEdit, + checked: Result<(), EditError>, + ) -> Result, EditError> { + let BegunEdit { edit, mut next, mut cx, mut scope, is_xfa, signed, generation } = begun; + let doc = self.doc_mut(id)?; + if doc.generation != generation { + discard_edit_callbacks(&cx); + return Err(EditError::Invalid("the document changed while the form's script ran; what it did was not kept".into())); + } + let reason = doc.read_only_reason.clone().unwrap_or_default(); + let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?; + checked?; // A field's enter or exit scripts that changed nothing leave no edit behind (no undo step, // nothing unsaved); what they showed or asked for still goes out. Only an event on its own: // a batch keeps the other edits it holds. @@ -278,14 +327,21 @@ impl Session { ran_away: false, highlight, time_scale: cx.xfa_time_scale, + answers: Default::default(), + relaid: false, }; // Every changed field's scripts, then the calculations once (after a reset, - // only those). - let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run, &mut exited)) + // only those). The values before the edit tell a click from a value set again. + let before: std::collections::HashMap> = + doc.form.iter().filter(|f| changed.contains(&f.name)).map(|f| (f.name.clone(), f.value.clone())).collect(); + let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &before, &mut run, &mut exited)) .unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})"))); cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; + cx.xfa_relaid |= run.relaid; // The next edit of a batch reads the highlight this one's scripts set. + // The next XFA run of a batch starts from the page count this one left. + cx.pages = run.page_count; let on = run.highlight; cx.set_highlight(on); if let Err(e) = ran { @@ -293,6 +349,13 @@ impl Session { } } } + // The form's scripts (a check box showing a section) or its new data (a picture) laid + // it out again, even if a later script then failed: as with text growth below, its + // pages, widgets and fields were replaced, whether or not the page count changed. The + // view and undo/redo rebuild them instead of refreshing only field values. + if cx.xfa_relaid { + scope = Scope::Full; + } // XFA forms keep their values in the datasets packet too, for Adobe's viewers. let mut xfa_notes = Vec::new(); if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) { @@ -312,6 +375,7 @@ impl Session { // Layout replaces pages and widgets, even if the page count is unchanged. // Undo/redo must rebuild these too instead of refreshing only field values. scope = Scope::Full; + rerun_layout_ready(&mut next, &mut cx); } } } @@ -524,7 +588,7 @@ impl Session { #[cfg(test)] check_refresh_panic(); if !doc.signatures.is_empty() { - let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache); // The display copy is kept for a metadata edit, and so are its marks, unless the // edit changed a verdict (a certification can forbid it): the page then draws the // new one. @@ -575,7 +639,7 @@ impl Session { } doc.info.file_size = bytes.len(); doc.form = form; - let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); @@ -609,6 +673,7 @@ impl Session { matches!( e, Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::AddPrinterMarks { .. } @@ -640,7 +705,7 @@ impl Session { doc.marker_scan = OnceLock::new(); } doc.info.file_size = bytes.len(); - let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); @@ -748,7 +813,7 @@ impl Session { if invalidate_links { doc.links = OnceLock::new(); } - let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); @@ -757,6 +822,38 @@ impl Session { } } +/// After a new layout: the form's `layout:ready` scripts run again, reading its page count, as +/// after a layout its scripts asked for. Not after a script of this edit ran away: the form's +/// scripts turn off once it is done. +fn rerun_layout_ready(next: &mut pdfcraft_cos::Document, cx: &mut EditCtx) { + if cx.xfa_ran_away { + return; + } + let Some(tpl) = cx.xfa.clone() else { return }; + let highlight = cx.highlight(); + let page_count = pdfcraft_organize::page_count(next).unwrap_or(cx.pages); + let mut run = xfa::XfaRun { + page_count, + out: &mut cx.xfa_out, + datasets: cx.xfa_datasets, + ran_away: false, + highlight, + time_scale: cx.xfa_time_scale, + answers: Default::default(), + relaid: false, + }; + let ran = guard(|| xfa::on_layout(next, &tpl, &mut run)).unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})"))); + cx.xfa_datasets = run.datasets; + cx.xfa_ran_away |= run.ran_away; + cx.xfa_relaid |= run.relaid; + cx.pages = run.page_count; + let on = run.highlight; + cx.set_highlight(on); + if let Err(e) = ran { + cx.xfa_out.errors.push(e); + } +} + /// The optional content groups `cos` lists as layers, in order (what the inspection reads: a group /// listed twice is one layer, and one that is not a dictionary is none). fn layer_ids(cos: &pdfcraft_cos::Document) -> Vec<(u32, u16)> { diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 85a6d24532..da1a9a7117 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,9 +1,12 @@ use super::{ - Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hairlines, HairlinesFixed, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI, - OptimizeReport, SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, office_to_pdf, open_source, open_source_with, optimize, print, - print_layer_states, print_raster, set_default_layer_state, source_kind, writable, write_full, + Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hairlines, HairlinesFixed, Hidden, ImagePage, ImageResolution, + LOW_RESOLUTION_PRINT_DPI, OptimizeReport, SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, office_to_pdf, open_source, + open_source_with, optimize, print, print_layer_states, print_raster, set_default_layer_state, source_kind, writable, write_full, }; +/// Why printer's marks were refused for a print that goes as pictures. +const MARKS_AS_PICTURES: &str = "printer marks print with the pages as they are, not as pictures: leave out as_image and app-managed colour (a document that allows only low-resolution printing always prints as pictures)"; + /// Whether a conversion may run LibreOffice for an Office document (seconds, in another /// process) or must refuse it because the caller is on the frame thread. #[derive(Clone, Copy, PartialEq, Eq)] @@ -30,7 +33,18 @@ impl Session { /// Create image pages at embedded resolution or a fixed dpi, without resampling. pub fn create_from_images_with_resolution(&self, images: &[(String, Vec)], resolution: ImageResolution) -> Result>, EditError> { - self.write_new(&pdfcraft_create::from_images_with_resolution(images, resolution)?) + self.create_from_images_with(images, resolution, ImagePage::Image) + } + + /// Create image pages at a resolution, each on its own size or on one fixed sheet (scaled to + /// fit and centred). Pixels are never resampled either way. + pub fn create_from_images_with( + &self, + images: &[(String, Vec)], + resolution: ImageResolution, + page: ImagePage, + ) -> Result>, EditError> { + self.write_new(&pdfcraft_create::from_images_with(images, resolution, page)?) } /// A new document from plain text (US Letter, 11 pt Helvetica, or the bundled Inter face for @@ -54,17 +68,23 @@ impl Session { /// An Office document runs LibreOffice ([`office_to_pdf`]), which takes seconds: keep it off /// the frame thread ([`Self::convert_to_pdf_inline`] there). pub fn convert_to_pdf(&self, name: &str, bytes: &Arc>) -> Result<(SourceKind, Arc>), EditError> { - self.convert(name, bytes, Office::Convert) + self.convert(name, bytes, Office::Convert, ImagePage::Image) + } + + /// [`Self::convert_to_pdf`], putting an image source on `page`. A PDF, text or Office source is + /// unaffected: only an image is laid onto a sheet of a chosen size. + pub fn convert_to_pdf_with(&self, name: &str, bytes: &Arc>, page: ImagePage) -> Result<(SourceKind, Arc>), EditError> { + self.convert(name, bytes, Office::Convert, page) } /// [`Self::convert_to_pdf`] for a caller on the frame thread, which must not wait seconds for /// LibreOffice: an Office document is refused, pointing to File ▸ Open, which converts it in /// the background. pub fn convert_to_pdf_inline(&self, name: &str, bytes: &Arc>) -> Result<(SourceKind, Arc>), EditError> { - self.convert(name, bytes, Office::Refuse) + self.convert(name, bytes, Office::Refuse, ImagePage::Image) } - fn convert(&self, name: &str, bytes: &Arc>, office: Office) -> Result<(SourceKind, Arc>), EditError> { + fn convert(&self, name: &str, bytes: &Arc>, office: Office, page: ImagePage) -> Result<(SourceKind, Arc>), EditError> { let Some(kind) = source_kind(name, bytes) else { return Err(EditError::Source(format!( "{name}: this file type can't be converted; use a PDF, an image, a .txt file or a Word, Excel or PowerPoint file" @@ -79,7 +99,7 @@ impl Session { // Image decoders read untrusted bytes: a panic in one must not take the app down. let created = guard(|| match kind { SourceKind::Pdf => open_source(name, bytes).map(|_| bytes.clone()), - SourceKind::Image => self.create_from_images(&[(name.to_string(), bytes.to_vec())]), + SourceKind::Image => self.create_from_images_with(&[(name.to_string(), bytes.to_vec())], ImageResolution::Embedded, page), SourceKind::Text => self.create_from_text(title, &decode_text(bytes)), SourceKind::Office => office_to_pdf(name, bytes), }) @@ -105,7 +125,7 @@ impl Session { fn insert_source_with(&self, dest: DocId, name: &str, bytes: &Arc>, office: Office) -> Result<(usize, Arc>), EditError> { if !matches!(source_kind(name, bytes), Some(SourceKind::Pdf)) { - let (_, pdf) = self.convert(name, bytes, office)?; + let (_, pdf) = self.convert(name, bytes, office, ImagePage::Image)?; return Ok((self.page_count_of(name, &pdf)?, pdf)); } let src = crate::sources::open_source_into(name, bytes, self.cos(dest)?)?; @@ -138,7 +158,7 @@ impl Session { Some(SourceKind::Image | SourceKind::Text | SourceKind::Office) => false, None => name.to_ascii_lowercase().ends_with(".pdf"), }; - if pdf { Ok(bytes.clone()) } else { self.convert(name, bytes, office).map(|(_, pdf)| pdf) } + if pdf { Ok(bytes.clone()) } else { self.convert(name, bytes, office, ImagePage::Image).map(|(_, pdf)| pdf) } } /// Reduce File Size: Acrobat's defaults (colour and grey images above 225 ppi to 150 ppi, @@ -229,6 +249,36 @@ impl Session { /// The print-ready PDF for `settings` (sheets laid out for the paper; see `pdfcraft-print`). pub fn print_pdf(&self, id: DocId, settings: &print::Settings) -> Result, EditError> { + self.print_pdf_marked(id, settings, None) + } + + /// Whether printer's marks fit around `pages` (0-based): [`pdfcraft_edit::add_printer_marks`] + /// run on a scratch copy, so a page the marks would widen past the largest page a PDF can + /// have is refused before anything (the Will Print actions) changes the document. The copy + /// is dropped; [`Session::print_pdf_marked`] adds the marks again on the print copy. + pub fn check_printer_marks(&self, id: DocId, pages: &[usize], marks: &crate::PrinterMarks) -> Result<(), EditError> { + let doc = self.get(id).ok_or(EditError::NoDocument)?; + let mut cos = match doc.editor.as_ref() { + Some(e) => e.cos.clone(), + None => { + pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))? + } + }; + let mut pages = pages.to_vec(); + pages.sort_unstable(); + pages.dedup(); + pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?; + Ok(()) + } + + /// [`Session::print_pdf`] with printer's marks (Acrobat's Marks and Bleeds) drawn around each + /// printed page on the print copy only: the document itself gets none. A page is widened for + /// them as [`pdfcraft_edit::add_printer_marks`] widens it, and marks the document already + /// carries are replaced, so a page never prints two sets. With form fields only, the fields + /// and the marks print and the page content doesn't. The pages print as they are, so + /// marks can't go with a print as pictures (Print as image, app-managed colour, or a document + /// that allows only low-resolution printing). + pub fn print_pdf_marked(&self, id: DocId, settings: &print::Settings, marks: Option<&crate::PrinterMarks>) -> Result, EditError> { let doc = self.get(id).ok_or(EditError::NoDocument)?; if !doc.allows_printing() { return Err(EditError::NotPermitted("printing")); @@ -243,6 +293,9 @@ impl Session { // Print as image: the pages used become pictures first, then the picture document is // imposed in their place (its page k is the k-th distinct source page used). if let Some(raster) = low_res.as_ref().or(settings.raster.as_ref()) { + if marks.is_some() { + return Err(EditError::Print(MARKS_AS_PICTURES.into())); + } let mut distinct: Vec = Vec::new(); for &p in &settings.pages { if !distinct.contains(&p) { @@ -287,6 +340,21 @@ impl Session { if doc.signatures.iter().any(|s| s.verdict_shown) { let _ = pdfcraft_sign::show_status_layers(&mut cos, &mut doc.signatures.to_vec(), &doc.captions); } + let marked; + let mut settings = settings; + if let Some(marks) = marks { + // Form fields only prints no page content, so the page content goes before the + // marks are added, and the marks then print as the page content does. + if settings.content == print::Content::FormFieldsOnly { + pdfcraft_print::keep_printed(&mut cos, print::Content::FormFieldsOnly); + marked = print::Settings { content: print::Content::Document, ..settings.clone() }; + settings = &marked; + } + let mut pages = settings.pages.clone(); + pages.sort_unstable(); + pages.dedup(); + pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?; + } pdfcraft_print::impose(&cos, settings).map_err(|e| EditError::Print(e.to_string())) } diff --git a/crates/engine/src/session/save.rs b/crates/engine/src/session/save.rs index eceec23c2c..a5253c4aef 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -1,6 +1,6 @@ use super::{ Arc, DocId, Document, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, StatusCaptions, TrustStore, - display_bytes, display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets, + display_bytes, display_config, editor_signatures, guard, render_threads, writable, write_full, write_incremental, xfa_sync_datasets, }; impl Session { @@ -90,6 +90,8 @@ impl Session { editor.saved = bytes; editor.saved_keys = keys; editor.unsaved_file = false; + // The saved file holds what opening appended: from now on it is the file. + editor.as_opened = None; } if let Some(p) = path { doc.name = std::path::Path::new(&p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone()); @@ -250,11 +252,44 @@ impl Session { &self.trust.certs } - /// Replace the trusted certificates, revalidate every open document's signatures, - /// and rebuild its display copy and renderer to match (working file untouched, - /// generation/dirty unchanged: trust alone is not an edit). + /// Change the trust store, revalidate every open document's signatures, and rebuild its + /// display copy and renderer to match (working file untouched, generation/dirty unchanged: + /// trust alone is not an edit). This happens once, however many changes `change` makes: + /// revalidating runs chain building and signature verification for every signature, against + /// every certificate of every trust list. + pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) { + let mut trust = (*self.trust).clone(); + change(&mut trust); + self.trust = Arc::new(trust); + self.revalidate_signatures(); + } + + /// Replace the trusted certificates (see [`Session::update_trust`]). pub fn set_trusted_certificates(&mut self, certs: Vec) { - self.trust = Arc::new(TrustStore { certs }); + self.update_trust(|trust| trust.certs = certs); + } + + /// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default. + /// They are not part of [`Session::trusted_certificates`]. + pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] { + &self.trust.lists + } + + /// Load `list` (replacing a list of the same name) and revalidate every open document. + pub fn add_trust_list(&mut self, list: pdfcraft_sign::trust::TrustList) { + self.update_trust(|trust| trust.add_list(list)); + } + + /// Remove the trust list called `name` and revalidate every open document. + pub fn remove_trust_list(&mut self, name: &str) { + self.update_trust(|trust| trust.remove_list(name)); + } + + fn revalidate_signatures(&mut self) { + #[cfg(test)] + { + self.revalidations += 1; + } for doc in &mut self.docs { Self::revalidate(doc, self.trust.clone()); } @@ -269,7 +304,7 @@ impl Session { return; } let Some(editor) = doc.editor.as_mut() else { return }; - let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &doc.bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &doc.bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); diff --git a/crates/engine/src/suggest_outline.rs b/crates/engine/src/suggest_outline.rs new file mode 100644 index 0000000000..1f55536887 --- /dev/null +++ b/crates/engine/src/suggest_outline.rs @@ -0,0 +1,510 @@ +//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before +//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the +//! headings are inferred from how the text looks, by the rules Auto-tag uses +//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page +//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the +//! most characters, a short block larger than the body (or bold where the body is not) is a +//! heading, and levels rank the heading styles over the document without skipping a level. +//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each +//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`); +//! tagged ones go to their page. + +use pdfcraft_a11y::TextBlock; +use pdfcraft_cos::Document; +use pdfcraft_organize::{OutlineEntry, OutlineNode}; + +use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines}; + +/// Blocks looked back over for one a line continues: a heading's next line can come after lines +/// of other columns on the same row. +const LOOKBACK: usize = 8; +/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent. +const MAX_DEPTH: usize = 32; +/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is +/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can +/// be under an em, so this stays below it. +const BESIDE_GAP: f64 = 0.5; +/// The most lines looked at on either side of a line for text beside it, which bounds the work on +/// a page with many runs on one row. +const MAX_BESIDE: usize = 64; + +/// Where the suggested headings come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineSource { + /// The structure tree's headings. + Structure, + /// The size and weight of the text. + Layout, +} + +/// A suggested outline. +#[derive(Clone, Debug, PartialEq)] +pub struct OutlineSuggestion { + pub source: OutlineSource, + /// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]). + pub entries: Vec, + /// Pages in the document. + pub pages: usize, + /// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) + /// for a suggestion from layout, fewer when a page's text can't be read. + pub pages_read: usize, + /// Headings may have been left out: pages weren't read, layout found more than + /// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of + /// [`pdfcraft_a11y::headings_with_truncation`]. + pub truncated: bool, +} + +impl OutlineSuggestion { + /// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the + /// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth. + pub fn tree(&self) -> Vec { + nest(&self.entries, &mut 0, 0, 0) + } +} + +/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion +/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't. +fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec { + let mut out = Vec::new(); + while let Some(e) = entries.get(*at) { + if depth > 0 && e.level <= above { + break; + } + *at = at.saturating_add(1); + let mut n = node(e); + if depth.saturating_add(1) < MAX_DEPTH { + n.children = nest(entries, at, e.level, depth.saturating_add(1)); + } + out.push(n); + } + out +} + +fn node(e: &OutlineEntry) -> OutlineNode { + let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None])); + OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() } +} + +/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether +/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]). +pub(crate) fn structure_entries(doc: &Document) -> (Vec, bool) { + let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc); + let entries = + found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect(); + (entries, cut) +} + +/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the +/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither +/// finds a heading. +pub fn suggest(doc: &Document) -> OutlineSuggestion { + let pages = pdfcraft_organize::page_count(doc).unwrap_or(0); + let (tagged, cut) = structure_entries(doc); + if !tagged.is_empty() { + return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut }; + } + let (lines, pages_read) = read_lines(doc); + let (entries, capped) = inferred(lines); + OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages } +} + +/// Lines in one style, one after another down a page. +struct Block { + first: Line, + last: Line, + title: String, + lines: usize, + chars: usize, + letters: bool, + /// Whether any of its lines is set inside a sentence ([`set_inline`]). + inline: bool, +} + +impl Block { + fn new(line: Line, inline: bool) -> Block { + let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline }; + b.count(&b.first.text.clone()); + b + } + + fn add(&mut self, line: Line, inline: bool) { + self.inline |= inline; + if self.title.chars().count() < MAX_TITLE_CHARS { + self.title.push(' '); + } + self.count(&line.text); + self.last = line; + } + + fn count(&mut self, text: &str) { + self.lines = self.lines.saturating_add(1); + self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count()); + self.letters |= text.chars().any(char::is_alphabetic); + let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count()); + self.title.extend(text.chars().take(room)); + } + + /// What the heading rules see. A block set inside a sentence still counts toward the body + /// style, since it is the paragraph's text, but is never a heading: the rules take no block + /// without letters as one. + fn evidence(&self) -> TextBlock { + let s = &self.first.style; + TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline } + } +} + +/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last +/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]). +fn blocks(lines: Vec) -> Vec { + let flags = set_inline(&lines); + let mut out: Vec = Vec::new(); + for (line, inline) in lines.into_iter().zip(flags) { + let start = out.len().saturating_sub(LOOKBACK); + let found = out.get_mut(start..).and_then(|recent| { + recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last)) + }); + match found { + Some(b) => b.add(line, inline), + None => out.push(Block::new(line, inline)), + } + } + out +} + +/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another +/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a +/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only +/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`) +/// leaves the title a heading. +fn set_inline(lines: &[Line]) -> Vec { + lines + .iter() + .enumerate() + .map(|(i, l)| { + // Lines are sorted down each page, so those on its row are next to it. + let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size; + let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near); + let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near); + before.chain(after).any(|o| beside(l, o)) + }) + .collect() +} + +/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at +/// least half the shorter one's height, since a box runs from the font's ascent to its descent +/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the +/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set +/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than +/// the prose around it is not. Prose whose box spans `l` on its row also counts: a producer may +/// set a sentence as one run with a gap, and paint the bold word into the gap. +fn beside(l: &Line, o: &Line) -> bool { + let size = l.style.size; + let shared = l.top.min(o.top) - l.bottom.max(o.bottom); + let shorter = (l.top - l.bottom).min(o.top - o.bottom); + let gap = l.left.max(o.left) - l.right.min(o.right); + let spans = o.left <= l.left && l.right <= o.right; + shared >= shorter * 0.5 + && (spans || gap >= -size * 0.25) + && gap <= size * BESIDE_GAP + && size <= o.style.size + SIZE_TOLERANCE + && !o.style.matches(&l.style) + && o.text.chars().any(char::is_lowercase) +} + +/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a +/// number. +fn is_caption(text: &str) -> bool { + let t = text.trim_start(); + ["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| { + let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..)); + rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())) + }) +} + +/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there +/// were more. +fn inferred(lines: Vec) -> (Vec, bool) { + let blocks: Vec = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect(); + let evidence: Vec = blocks.iter().map(Block::evidence).collect(); + let mut entries: Vec = blocks + .iter() + .zip(pdfcraft_a11y::heading_levels(&evidence)) + .filter_map(|(b, level)| { + let [left, top] = b.first.anchor; + Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top }) + }) + .take(MAX_BOOKMARKS.saturating_add(1)) + .collect(); + let capped = entries.len() > MAX_BOOKMARKS; + entries.truncate(MAX_BOOKMARKS); + (entries, capped) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text_style_bookmarks::TextStyle; + + /// A line at `top` (its box 0.8 of its size tall) from x 72 to 400. + fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line { + let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false }; + Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] } + } + + fn body(page: usize, top: f64) -> Line { + line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.") + } + + fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> { + entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect() + } + + #[test] + fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() { + let lines = vec![ + line(0, 760.0, 20.0, true, "Getting started"), + line(0, 738.0, 20.0, true, "with the toolkit"), + body(0, 700.0), + body(0, 686.0), + body(0, 672.0), + body(0, 658.0), + line(0, 630.0, 11.0, true, "Installing"), + body(0, 610.0), + body(0, 596.0), + line(1, 760.0, 20.0, true, "Reference"), + body(1, 730.0), + body(1, 716.0), + ]; + let (found, capped) = inferred(lines); + assert!(!capped); + assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]); + assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line"); + } + + #[test] + fn a_wrapped_heading_joins_across_a_line_of_another_column() { + let mut right = body(0, 760.0); + (right.left, right.right) = (420.0, 560.0); + let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)]; + assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]); + } + + #[test] + fn captions_and_numbers_are_not_headings() { + let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty()); + assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful")); + } + + /// A line of `text` in `style` from `left` to `right` at `top`. + fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line { + Line { left, right, ..line(0, top, 11.0, bold, text) } + } + + #[test] + fn a_bold_word_inside_a_sentence_is_not_a_heading() { + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + run(726.0, true, "MUST", 133.0, 165.0), + run(726.0, false, "ignore the field.", 168.0, 400.0), + body(0, 712.0), + run(690.0, false, "2.3", 72.0, 88.0), + run(690.0, true, "Numbered title", 96.0, 180.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]); + } + + #[test] + fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() { + let mut small = run(726.0, true, "MUST", 133.0, 163.0); + small.style.size = 10.0; + small.top = 725.2; + small.bottom = small.top - 8.0; + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient", 72.0, 130.0), + small, + run(726.0, false, "ignore the field.", 166.0, 400.0), + body(0, 712.0), + Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") }, + run(688.8, false, "covers the rest of this page.", 113.0, 400.0), + body(0, 670.0), + body(0, 656.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]); + } + + #[test] + fn a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading() { + let mut word = run(725.2, true, "MUST", 192.0, 219.0); + word.style.size = 10.0; + word.bottom = word.top - 8.0; + let lines = vec![ + line(0, 760.0, 11.0, true, "MUST"), + body(0, 740.0), + run(726.0, false, "A recipient ignore the field.", 72.0, 400.0), + word, + body(0, 712.0), + body(0, 698.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0)]); + } + + #[test] + fn text_beside_an_italic_word_still_sets_the_body_size() { + let italic = |top: f64| { + let mut l = run(top, false, "term", 252.0, 275.0); + l.style.italic = true; + l.style.font = "Helvetica-Oblique".into(); + l + }; + let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")]; + for top in [750.0, 736.0, 722.0, 708.0] { + lines.extend([ + run(top, false, "The first part of the row runs to", 72.0, 250.0), + italic(top), + run(top, false, "and the rest of it follows on.", 277.0, 400.0), + ]); + } + assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]); + } + + #[test] + fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() { + let lines = vec![ + // Its box overlaps the first body line's by 1.5 pt. + run(760.0, true, "Tight heading", 72.0, 180.0), + body(0, 752.7), + body(0, 740.0), + // A gutter of 9 pt, under an em: prose ends the left column on the heading's row. + run(700.0, false, "ends the left column here", 72.0, 291.0), + run(700.0, true, "Right column heading", 300.0, 520.0), + body(0, 686.0), + body(0, 672.0), + ]; + assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]); + } + + #[test] + fn captions_match_in_any_case() { + let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)]; + assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading"); + assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3")); + } + + #[test] + fn more_headings_than_the_cap_are_reported() { + // Each heading on a page of its own, with a line of body text under it. + let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::>(); + let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS)); + assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false)); + let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1)); + assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported"); + } + + /// A page past the page decode allowance (two compressed streams of spaces, each just over + /// half of it) can't be read: it doesn't count as read, and the suggestion says headings + /// may be missing. + #[test] + fn a_page_whose_text_cant_be_read_is_not_counted() { + let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]); + let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(), + stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"), + stream("/Filter /FlateDecode", &packed), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + let s = suggest(&doc_of(&objs)); + assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read"); + } + + /// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog. + fn doc_of(objs: &[Vec]) -> Document { + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat()); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(std::sync::Arc::new(bytes)).unwrap() + } + + /// More tagged headings than the structure reader returns: the suggestion says some are missing. + #[test] + fn tagged_headings_past_the_cap_are_reported() { + let tagged = |count: usize| { + let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + format!("<< /S /Document /K [{kids}] >>").into_bytes(), + ]; + objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec())); + suggest(&doc_of(&objs)) + }; + let cap = pdfcraft_a11y::MAX_HEADINGS; + let at_cap = tagged(cap); + assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false)); + let over = tagged(cap + 1); + assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported"); + } + + /// A tagged heading too deep for the structure walk, on a page without text: layout finds + /// nothing either, and the suggestion still says a heading may be missing. The same page + /// untagged is not truncated. + #[test] + fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() { + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(), + b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(), + ]; + objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes())); + objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec()); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped"); + objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(); + let s = suggest(&doc_of(&objs)); + assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false)); + } + + #[test] + fn the_tree_nests_by_level_and_caps_the_depth() { + let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) }; + let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")]; + let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false }; + let tree = s.tree(); + assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::>(), ["A", "B"]); + assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::>(), ["A.1", "A.2"]); + assert_eq!(tree[0].children[0].children[0].title, "A.1.a"); + assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None]))); + // A tagged H nested in 40 sections stops at the deepest level bookmark_import takes. + entries = (1..=40).map(|l| entry(l, "deep")).collect(); + let deep = OutlineSuggestion { entries, ..s }.tree(); + let mut depth = 0; + let mut at = &deep; + while let Some(n) = at.first() { + depth += 1; + at = &n.children; + } + assert_eq!(depth, MAX_DEPTH); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 587780dcc3..d99266b412 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5,6 +5,8 @@ use super::edit::{EditCtx, check_permission, run_edit}; use super::*; use pdfcraft_render::{Layer, LayerOp, OpenError, ReadingColors}; +mod print_marks; + /// A minimal `n`-page document; page `i` shows "Page i+1". pub(crate) fn fixture(n: usize) -> Vec { let mut objs: Vec> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()]; @@ -4532,6 +4534,51 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() { assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged"); } +/// #5785: Update of one header and footer previews the page without that one alone, so a second +/// header and footer on the same page, which OK keeps, is still drawn in the preview. +#[test] +fn update_of_one_header_previews_the_page_with_the_others() { + let (mut s, id) = session_with(2); + let header = |text: &str, color: [f64; 3]| { + let mut hf = pdfcraft_edit::HeaderFooter { color, font_size: 24.0, ..pdfcraft_edit::HeaderFooter::default() }; + hf.text[1] = text.into(); + hf + }; + let (red, blue) = (header("REDREDRED", [1.0, 0.0, 0.0]), header("BLUEBLUEBLUE", [0.0, 0.0, 1.0])); + s.apply(id, Edit::AddHeaderFooter { pages: vec![0, 1], settings: red.clone(), replace: false }).unwrap(); + let mut footer = blue.clone(); + footer.text.swap(1, 4); + s.apply(id, Edit::AddHeaderFooter { pages: vec![0], settings: footer.clone(), replace: false }).unwrap(); + let doc = s.get(id).unwrap(); + let generation = doc.edit_generation(); + let count = + |p: &pdfcraft_render::RenderedPage, f: fn(u8, u8, u8) -> bool| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| f(*r, *g, *b)).count(); + let reds = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| r > 200 && g < 80 && b < 80); + let blues = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| b > 200 && r < 80 && g < 80); + + let mut without_red = doc.without_header_footer(&red).unwrap().expect("the red header is on the pages"); + let page = without_red.render_page(0, 1.0).unwrap(); + assert_eq!(reds(&page), 0, "the header Update replaces is gone"); + assert_eq!(blues(&page), 0, "the footer added after it is drawn over the new one, so not under it"); + assert_eq!(reds(&without_red.render_page(1, 1.0).unwrap()), 0, "from every page it is on"); + // The footer OK keeps over the new header, alone. + let mut over_red = doc.over_header_footer(&red).unwrap().expect("the blue footer is over the red header"); + let page = over_red.render_page(0, 1.0).unwrap(); + let opaque = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[.., a]| *a > 0).count(); + assert!(blues(&page) > 20 && reds(&page) == 0, "the other header and footer on the page stays, as OK keeps it"); + assert!(opaque(&page) < page.rgba.len() / 8, "on a transparent page: the draft under it shows"); + assert_eq!(opaque(&over_red.render_page(1, 1.0).unwrap()), 0, "nothing is over it where it is alone"); + assert!(doc.over_header_footer(&footer).unwrap().is_none(), "nothing is over the newest"); + + let page = doc.without_header_footer(&footer).unwrap().expect("the blue footer is on page 1").render_page(0, 1.0).unwrap(); + assert!(reds(&page) > 20 && blues(&page) == 0, "and the other way round"); + // Every header and footer goes for a page-wide replace, and a header no page records has nothing to prepare. + let page = doc.without_marks(MarkKind::HeaderFooter).unwrap().expect("there are headers").render_page(0, 1.0).unwrap(); + assert_eq!((reds(&page), blues(&page)), (0, 0)); + assert!(doc.without_header_footer(&header("GONE", [0.0, 1.0, 0.0])).unwrap().is_none()); + assert_eq!(s.get(id).unwrap().edit_generation(), generation, "the document is unchanged"); +} + #[test] fn marker_indexes_match_after_open_and_save_when_requested() { let (mut source, source_id) = session_with(1); @@ -5216,6 +5263,7 @@ fn pasted_added_content_keeps_its_style_and_picture() { align: TextAlign::Center, aligns: Vec::new(), char_spacing: 0.0, + font_resource: None, }; s.apply(id, Edit::AddText { page: 0, text: text.clone() }).unwrap(); let copied = s.get(id).unwrap().added()[0].content.clone(); @@ -5796,6 +5844,31 @@ fn reading_colors_set_and_invalidated() { assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK)); } +#[test] +fn several_trust_changes_revalidate_the_open_documents_once() { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate; + let mut s = Session::default(); + // Each setter changes one thing and revalidates. + s.set_trusted_certificates(vec![cert.clone()]); + s.set_trusted_certificates(Vec::new()); + assert_eq!(s.revalidations, 2); + // One `update_trust` changes any number of things and revalidates once. + let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap(); + s.update_trust(|trust| { + trust.certs = vec![cert.clone()]; + trust.add_list(list.clone()); + }); + assert_eq!(s.revalidations, 3); + assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1)); + // A list loaded again under its name replaces itself; removing it by that name takes it back. + s.add_trust_list(list); + assert_eq!(s.trust_lists().len(), 1); + s.remove_trust_list("Test list"); + assert!(s.trust_lists().is_empty()); + assert_eq!(s.revalidations, 5); +} + #[test] fn signing_saving_trusting_and_commenting_afterwards() { let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); @@ -7500,6 +7573,38 @@ fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() { assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty()); } +#[test] +fn take_js_errors_leaves_the_alerts_for_take_js_output() { + let template = pdfcraft_xfa::fixtures::scripted_template() + .replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; xfa.host.messageBox('opened'); throw new Error('open failed');"); + // Raised time limits: a busy machine does not stop the scripts this checks. + let mut s = Session::new().with_xfa_time_scale(100); + let id = s.open("xfa.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap(); + let errors = s.take_js_errors(id); + assert!(errors.iter().any(|e| e.contains("open failed")), "{errors:?}"); + assert!(s.take_js_errors(id).is_empty()); + let out = s.take_js_output(id); + assert!(out.errors.is_empty(), "{out:?}"); + assert_eq!(out.alerts, [js::Message::plain("opened")]); +} + +#[test] +fn take_js_errors_reports_a_document_scripts_error_again_on_the_next_edit() { + let helpers = "function times\\(a, b\\) { return a * b; } this.getField\\('go'\\).missingTestMethod\\(\\);"; + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("order.pdf", None, Arc::new(scripted_form_with(helpers)), None).unwrap(); + assert_eq!(s.take_js_errors(id).len(), 1, "the document script fails at open"); + // The document scripts run again when the script list changes, which each pass does. + for qty in ["4", "5"] { + let script = format!("/* {qty} */ function times(a, b) {{ return a * b; }} this.getField('go').missingTestMethod();"); + s.apply(id, Edit::SetDocumentScript { name: "helpers".into(), script: Some(script) }).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text(qty.into()) }).unwrap(); + let errors = s.take_js_errors(id); + assert_eq!(errors.len(), 1, "qty {qty}: {errors:?}"); + assert!(errors[0].starts_with("document script 1: TypeError"), "qty {qty}: {errors:?}"); + } +} + #[test] fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() { let template = r#" @@ -908,6 +1041,79 @@ pub fn signed_shell() -> Vec { assemble(objs) } +/// A dynamic form as a viewer saves it with its pages drawn: no `/NeedsRendering`, a page with +/// the form's picture, and only its signature box `sign` among the AcroForm's fields (the text +/// field `name` lives in the template), signed when `signed`. Its configuration packet says +/// `{render}` (none when `render` is empty). +pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec { + assemble(saved_with_pages_objects(render, signed)) +} + +/// [`saved_with_pages_shell`]`("required", false)` whose signature box sits under `depth` nested +/// fields of its own (none of them a signature, none with a value). +pub fn deep_saved_with_pages_shell(depth: usize) -> Vec { + let mut objs = saved_with_pages_objects("required", false); + // Object 6, the box, becomes the outermost of the nested fields, each the parent of the next; + // the box goes last, under the innermost, and the page lists it under its new number. + let first = objs.len() + 1; + let depth = depth.max(1); + let widget = first + depth - 1; + let parent_of = |n: usize| if n == first { 6 } else { n - 1 }; + let field = |name: usize, kid: usize, parent: Option| { + let parent = parent.map(|p| format!(" /Parent {p} 0 R")).unwrap_or_default(); + format!("<< /T (n{name}) /Kids [{kid} 0 R]{parent} >>").into_bytes() + }; + let kid_of_six = if depth == 1 { widget } else { first }; + let Some(sig) = objs.get_mut(5).map(|o| std::mem::replace(o, field(0, kid_of_six, None))) else { return assemble(objs) }; + for d in 1..depth { + let n = first + d - 1; + objs.push(field(d, n + 1, Some(parent_of(n)))); + } + let innermost = if depth == 1 { 6 } else { widget - 1 }; + let sig = String::from_utf8_lossy(&sig).replacen("/T (form[0].sign[0])", &format!("/T (sign[0]) /Parent {innermost} 0 R"), 1); + objs.push(sig.into_bytes()); + if let Some(page) = objs.get_mut(2) { + *page = String::from_utf8_lossy(page).replacen("/Annots [6 0 R]", &format!("/Annots [{widget} 0 R]"), 1).into_bytes(); + } + assemble(objs) +} + +/// The objects of [`saved_with_pages_shell`], in order (the signature box is object 6). +fn saved_with_pages_objects(render: &str, signed: bool) -> Vec> { + let config = if render.is_empty() { + String::new() + } else { + format!( + r#"1.7{render}"# + ) + }; + let xdp = format!( + r##" + +{config} + + +"## + ); + let value = if signed { " /V 7 0 R" } else { "" }; + let picture = "BT /F1 12 Tf 72 700 Td (Name: ______) Tj ET"; + vec![ + b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /XFA 5 0 R /Fields [6 0 R] /SigFlags 3 >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Annots [6 0 R] >>".to_vec(), + format!("<< /Length {} >>\nstream\n{picture}\nendstream", picture.len()).into_bytes(), + format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(), + format!("<< /T (form[0].sign[0]) /FT /Sig{value} /Type /Annot /Subtype /Widget /Rect [72 500 288 572] /P 3 0 R >>").into_bytes(), + b"<< /Type /Sig /Name (A Signer) >>".to_vec(), + ] +} + /// A check box `kind` whose change script, once it is checked, opens the protected check box /// `leave` and shows the invisible field `details`, then fails on an object the form doesn't /// have (as scripts written for an earlier version of a form do). diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 24682caf9f..90abf8a41b 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -1,7 +1,8 @@ //! The layout engine: places a template's subforms, draws and fields on pages (XFA 3.3 part 2, //! "Layout"). Supports positioned, top-to-bottom, left-to-right and table/row layouts, page -//! masters with content areas, `breakBefore`/`breakAfter`, and overflow leaders (header rows -//! repeated after a page break). Repeating subforms get their initial instances. +//! masters with content areas, `breakBefore`/`breakAfter` (including a named `pageArea` +//! target), overflow onto a named master, and overflow leaders (header rows repeated after a +//! page break). Repeating subforms get their initial instances. //! //! Output is a list of pages of resolution-independent items; `pdf` turns them into PDF. @@ -13,7 +14,7 @@ use std::sync::Arc; use base64::Engine; use crate::XfaError; -use crate::data::{DataNode, DataPath, data_date_letters, data_path, data_to_iso, date_letters, is_on, iso_to_pattern}; +use crate::data::{DataNode, DataPath, data_date_letters, data_path, data_to_iso, date_letters, is_on, iso_to_pattern, pattern_to_iso}; use crate::model::{ Access, Area, Border, Common, Draw, ExclGroup, Field, Font, HAlign, Layout, Margin, Node, Occur, PageArea, PageRole, Para, Placement, Presence, Rect, Script, SomIndices, Stroke, Subform, Template, Ui, VAlign, Value, Views, @@ -30,7 +31,7 @@ mod pages; pub(crate) use common::date_pattern; pub use common::formatted_value; -use common::{collect_names, collect_values}; +use common::{clamp_opt, collect_names, collect_values}; pub(crate) use items::UNDERLINE_DROP; pub use items::{Action, BorderShape, Form, Item, Page, Rounded, Turned, Widget, WidgetBorder, WidgetKind}; @@ -129,6 +130,9 @@ struct Frame { w: f64, margin: Margin, border: Option, + /// Width-less sections adapt to a new content area, using their original constraints. + /// A fixed width keeps its position. + width_limits: Option<(Option, Option)>, part: FlowMark, parts: Vec<(usize, usize, Rect)>, /// Something inside didn't fit its content area: an item cut across areas, or one placed past @@ -141,6 +145,19 @@ struct Frame { held: bool, } +impl Frame { + fn fit_width(&mut self, (x, w): (f64, f64)) { + if let Some((min, max)) = self.width_limits { + self.x = x; + self.w = clamp_opt(w, min, max).min(w.max(1.0)); + } + } + + fn inner_width(&self) -> (f64, f64) { + (self.x + self.margin.left, (self.w - self.margin.horizontal()).max(1.0)) + } +} + struct Cursor { area: usize, content: usize, @@ -168,6 +185,12 @@ struct Layouter<'t> { pages: Vec, cur: Option, names: HashMap, + /// State before the current master was drawn, for replacing an otherwise empty page. + page_fields: usize, + /// Only names touched on this page, including reservations that emitted no widget. + page_names: HashMap>, + /// PDF field names added to [`Self::taken`] on the current page. + page_taken: Vec, /// Every PDF field name handed out so far. taken: HashSet, /// The names the template's fields, groups and groups' members take as written @@ -200,6 +223,12 @@ struct Layouter<'t> { /// The flowed subforms being laid out, outermost first: a break between their children /// closes their parts on one content area and opens new ones on the next. frames: Vec, + /// The `pageArea` index used for an untargeted new page. Explicit break targets stick. + /// An `overflow` target is installed only while its subform is laid out, then the previous + /// selection returns unless a later explicit break replaced it (`preferred_epoch`). + preferred_area: Option, + /// Bumped when an explicit break selects [`Self::preferred_area`]. + preferred_epoch: u64, /// What scripts set on page-master content, applied to each page's copy by its own SOM path. overrides: Option<&'t crate::script::Overrides>, /// The pages' copies of master content that overrides changed, kept for the whole layout so @@ -208,11 +237,12 @@ struct Layouter<'t> { } /// How many instances of a repeating subform to lay out: what the data holds once it holds -/// any (rows added or removed), else the template's initial count; never below one, never -/// above the maximum. +/// any (rows added or removed), else the template's initial count; at least the minimum +/// whatever the data holds (XFA 3.3, "Repeating Elements using Occurrence Limits", #4744); +/// never below one, never above the maximum. pub fn instance_count(occur: &Occur, from_data: usize) -> usize { let n = if from_data > 0 { from_data } else { occur.initial }; - n.min(occur.max.unwrap_or(usize::MAX)).clamp(1, MAX_INSTANCES) + n.max(occur.min).min(occur.max.unwrap_or(usize::MAX)).clamp(1, MAX_INSTANCES) } /// How many instances of `sf` the layout makes under the container at `parent_som`: its `occur` @@ -242,6 +272,7 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat Some(ps) if !ps.areas.is_empty() => ps.areas.clone(), _ => vec![PageArea { name: None, + id: None, width: 612.0, height: 792.0, content: vec![Rect::new(36.0, 36.0, 540.0, 720.0)], @@ -263,6 +294,9 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat pages: Vec::new(), cur: None, names: HashMap::new(), + page_fields: 0, + page_names: HashMap::new(), + page_taken: Vec::new(), taken: HashSet::new(), template_names, values, @@ -279,6 +313,8 @@ fn layout_inner(tpl: &Template, data: Option<&DataNode>, overrides: Option<&crat field_border: None, views: Views::ALL, frames: Vec::new(), + preferred_area: None, + preferred_epoch: 0, overrides, master_copies: Vec::new(), }; @@ -319,6 +355,22 @@ thread_local! { pub(crate) static EMBED_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } +#[cfg(test)] +mod instance_count_tests { + use super::instance_count; + use crate::model::Occur; + + /// #4744: `min` is honoured whatever the data holds. A repeating subform with + /// `occur min="2" max="2"` keeps two instances even when the data has one. + #[test] + fn min_is_kept_whatever_the_data_holds() { + let occur = Occur { min: 2, max: Some(2), initial: 2 }; + assert_eq!(instance_count(&occur, 0), 2, "no data: the initial count, at least the minimum"); + assert_eq!(instance_count(&occur, 1), 2, "one data instance: the minimum still applies"); + assert_eq!(instance_count(&occur, 3), 2, "more than the maximum: the maximum wins"); + } +} + // The item count the last layout on this thread ended with, against `MAX_ITEMS`. #[cfg(test)] thread_local! { diff --git a/crates/xfa/src/layout/common.rs b/crates/xfa/src/layout/common.rs index 1952bc7982..c0777ad8a4 100644 --- a/crates/xfa/src/layout/common.rs +++ b/crates/xfa/src/layout/common.rs @@ -115,9 +115,19 @@ pub(super) fn clamp_opt(v: f64, min: Option, max: Option) -> f64 { v.max(0.0) } -/// Does `node` flow (may be split across pages) rather than being placed as one block? -pub(super) fn splittable(node: &Node) -> bool { - matches!(node, Node::Subform(s) if matches!(s.layout, Layout::Tb | Layout::Table) && s.common.h.is_none()) +/// Does `node` flow through [`Layouter::flow_subform`] (either because it may be split across +/// pages or because it carries a page break or page-area target of its own)? +pub(super) fn flows_as_subform(node: &Node) -> bool { + matches!( + node, + Node::Subform(s) + if (matches!(s.layout, Layout::Tb | Layout::Table) && s.common.h.is_none()) + || s.break_before_page + || s.break_after_page + || s.break_before_target.is_some() + || s.break_after_target.is_some() + || s.overflow_target.is_some() + ) } /// Top and bottom of an item a page break must not cut (text, a picture, a field); `None` diff --git a/crates/xfa/src/layout/draw.rs b/crates/xfa/src/layout/draw.rs index 0000bf20dc..725d7d0c38 100644 --- a/crates/xfa/src/layout/draw.rs +++ b/crates/xfa/src/layout/draw.rs @@ -479,14 +479,17 @@ impl Layouter<'_> { let base = clean_name(base); // The template's own name, while no other field has it. if !fallback && self.taken.insert(base.clone()) { + self.page_taken.push(base.clone()); return base; } loop { + self.page_names.entry(base.clone()).or_insert_with(|| self.names.get(&base).copied()); let n = self.names.entry(base.clone()).or_insert(0); *n = n.saturating_add(1); let candidate = if *n == 1 { base.clone() } else { format!("{base}_{n}") }; let reserved = (fallback || *n > 1) && self.template_names.contains(&candidate); if !reserved && self.taken.insert(candidate.clone()) { + self.page_taken.push(candidate.clone()); return candidate; } } diff --git a/crates/xfa/src/layout/field.rs b/crates/xfa/src/layout/field.rs index b2914fae79..545feb3a95 100644 --- a/crates/xfa/src/layout/field.rs +++ b/crates/xfa/src/layout/field.rs @@ -2,7 +2,7 @@ use super::common::{button_action, date_pattern}; use super::items::{BorderShape, Item, Widget, WidgetBorder, WidgetKind}; use super::{ Access, Border, Ctx, Engine, Face, Field, HAlign, Layouter, MAX_DATA_IMAGE, Margin, Para, Placement, Presence, Rect, Ui, VAlign, Value, Views, - XfaError, data_date_letters, data_path, data_to_iso, is_on, iso_to_pattern, text, + XfaError, data_date_letters, data_path, data_to_iso, is_on, iso_to_pattern, pattern_to_iso, text, }; impl Layouter<'_> { @@ -212,12 +212,15 @@ impl Layouter<'_> { } Ui::DateTimeEdit => { let pattern = date_pattern(f.picture.as_deref()); - // The data holds the date in the field's data picture, or else as an ISO date; the - // field shows it in its own pattern. + // The data holds the date in the field's data picture, or else as an ISO date; a + // template default is a canonical date (ISO, or its basic form). Either way the + // field holds it in its own pattern, as a date typed there is held, so its value + // never reads two ways (an ISO date read in a `yyyy-dd-mm` pattern, say). let data_pattern = data_date_letters(f); - let shown = plain_value - .as_ref() - .map(|v| if data_value.is_some() { iso_to_pattern(&data_to_iso(v, data_pattern.as_deref()), &pattern) } else { v.clone() }); + let shown = plain_value.as_ref().map(|v| match data_value { + Some(_) => iso_to_pattern(&data_to_iso(v, data_pattern.as_deref()), &pattern), + None => canonical_date_in(v, &pattern), + }); (WidgetKind::Date(pattern), ui, widget_border(f.ui_border.as_ref(), false), shown, f.tooltip.clone()) } Ui::ChoiceList => { @@ -245,6 +248,11 @@ impl Layouter<'_> { return Ok(()); } let action = if f.ui == Ui::Button { button_action(&f.scripts) } else { None }; + // A date field's default, like its value, in the field's own pattern. + let default = match &kind { + WidgetKind::Date(pattern) => template_default.map(|v| canonical_date_in(&v, pattern)), + _ => template_default, + }; let items: Vec = match &kind { WidgetKind::CheckBox { on, .. } => vec![on.clone(), f.items.get(1).cloned().unwrap_or_default()], WidgetKind::Radio { on, .. } => vec![on.clone()], @@ -264,10 +272,11 @@ impl Layouter<'_> { read_only, border, value, - default: template_default, + default, action, items, no_scroll: f.no_scroll, + display_date: (f.ui == Ui::DateTimeEdit).then(|| f.display_picture.as_deref().and_then(crate::data::date_letters)).flatten(), // `push` sets where it shows. views: Views::ALL, required: f.required, @@ -314,3 +323,12 @@ fn widget_border(b: Option<&Border>, check: bool) -> WidgetBorder { width: edge.thickness.clamp(0.1, 12.0), } } + +/// A template's canonical date `v` (ISO `2016-10-11`, or its basic form `20161011`) written in +/// `pattern`; anything else as it is. +fn canonical_date_in(v: &str, pattern: &str) -> String { + match ["yyyy-mm-dd", "yyyymmdd"].iter().find_map(|p| pattern_to_iso(v, p)) { + Some(iso) => iso_to_pattern(&iso, pattern), + None => v.to_string(), + } +} diff --git a/crates/xfa/src/layout/flow.rs b/crates/xfa/src/layout/flow.rs index 9d979d97e1..f2c26c955a 100644 --- a/crates/xfa/src/layout/flow.rs +++ b/crates/xfa/src/layout/flow.rs @@ -1,4 +1,4 @@ -use super::common::{WidgetRest, clamp_opt, divide, is_row, moved, solid_extent, split_line, split_widget, splittable, widget_box}; +use super::common::{WidgetRest, clamp_opt, divide, flows_as_subform, is_row, moved, solid_extent, split_line, split_widget, widget_box}; use super::items::Item; use super::{ Ctx, Frame, Layout, Layouter, MAX_DEPTH, MAX_INSTANCES, MAX_MEASURES, Node, Rect, SomIndices, Splitting, Subform, XfaError, data_path, @@ -323,8 +323,28 @@ impl Layouter<'_> { } let Node::Subform(sf) = node else { return Ok(()) }; self.check_measures()?; - if sf.break_before_page && self.page_has_flow() { - self.break_frames(0.0, true)?; + let prev_rect = self.cursor().0; + let before_target = sf.break_before_target.as_deref().and_then(|t| self.find_page_area(t)); + if let Some(idx) = before_target { + self.select_break_area(idx); + } + if sf.break_before_page { + if self.page_has_flow() { + self.break_frames_to(0.0, true, before_target)?; + } else if let Some(idx) = before_target + && self.cur.as_ref().is_some_and(|c| c.area != idx) + { + self.switch_empty_page(idx)?; + } + } + // Overflow steers pages created while this subform (and its descendants) are open. + // Putting the previous selection back afterwards keeps a later sibling's untargeted + // break off this master. A descendant's explicit break bumps `preferred_epoch` and stays. + let overflow_area = sf.overflow_target.as_deref().and_then(|t| self.find_page_area(t)); + let preferred_before_overflow = self.preferred_area; + let epoch_at_overflow = self.preferred_epoch; + if let Some(idx) = overflow_area { + self.preferred_area = Some(idx); } // Data adds instances of a repeating subform (rows added in another viewer). let instances = self.laid_out_instances(node, &ctx.som); @@ -335,7 +355,13 @@ impl Layouter<'_> { self.check_measures()?; let ctx = ctx_parent.with_som(&sf.common, sib + i); let (rect, _, _) = self.cursor(); - let (x, w) = avail.unwrap_or((rect.x, rect.w)); + // When a break moved to a content area of a different width (such as switching from a + // portrait master to a landscape master), a width from the old content area no longer + // bounds this subform. + let (x, w) = match avail { + Some(av) if rect == prev_rect => av, + _ => self.frames.last().map_or((rect.x, rect.w), Frame::inner_width), + }; let w = clamp_opt(sf.common.w.unwrap_or(w), sf.common.min_w, sf.common.max_w).min(w.max(1.0)); if !matches!(sf.layout, Layout::Tb | Layout::Table) || sf.common.h.is_some() { // Not splittable: one block. @@ -347,14 +373,25 @@ impl Layouter<'_> { // Its border and fill go round what it takes from here, a part on each content area. let framed = match self.flow_mark() { Some(part) => { - self.frames.push(Frame { x, w, margin: m, border: sf.common.border.clone(), part, parts: Vec::new(), lost: false, held: false }); + self.frames.push(Frame { + x, + w, + margin: m, + border: sf.common.border.clone(), + width_limits: sf.common.w.is_none().then_some((sf.common.min_w, sf.common.max_w)), + part, + parts: Vec::new(), + lost: false, + held: false, + }); true } None => false, }; self.advance(m.top); - let inner_x = x + m.left; - let inner_w = (w - m.horizontal()).max(1.0); + let mut cur_rect = rect; + let mut inner_x = x + m.left; + let mut inner_w = (w - m.horizontal()).max(1.0); match sf.layout { Layout::Table => self.flow_table(sf, inner_x, inner_w, &ctx, depth)?, _ => { @@ -363,10 +400,15 @@ impl Layouter<'_> { if !child.common().presence.occupies() { continue; } + let (r, _, _) = self.cursor(); + if r != cur_rect && sf.common.w.is_none() { + cur_rect = r; + if framed && let Some(f) = self.frames.last() { + (inner_x, inner_w) = f.inner_width(); + } + } let csib = sibs.at(ci); - if let Node::Subform(_) = child - && splittable(child) - { + if flows_as_subform(child) { self.flow_subform(child, Some((inner_x, inner_w)), &ctx, depth + 1, csib)?; continue; } @@ -379,8 +421,15 @@ impl Layouter<'_> { self.finish_frame(frame)?; } } + if overflow_area.is_some() && self.preferred_epoch == epoch_at_overflow { + self.preferred_area = preferred_before_overflow; + } if sf.break_after_page { - self.break_frames(0.0, true)?; + let after_target = sf.break_after_target.as_deref().and_then(|t| self.find_page_area(t)); + if let Some(idx) = after_target { + self.select_break_area(idx); + } + self.break_frames_to(0.0, true, after_target)?; } Ok(()) } @@ -430,9 +479,7 @@ impl Layouter<'_> { } continue; } - if splittable(child) - && let Node::Subform(_) = child - { + if flows_as_subform(child) { self.flow_subform(child, Some((x, inner_w)), ctx, depth + 1, csib)?; continue; } diff --git a/crates/xfa/src/layout/items.rs b/crates/xfa/src/layout/items.rs index c42cd1f24b..2e4f9ccf9c 100644 --- a/crates/xfa/src/layout/items.rs +++ b/crates/xfa/src/layout/items.rs @@ -150,6 +150,9 @@ pub struct Widget { pub items: Vec, /// A text field that doesn't scroll: it takes no more text than it shows (`DoNotScroll`). pub no_scroll: bool, + /// Date fields: the date letters of the display picture (``), how the value + /// shows when it isn't being typed in. `None`: as the edit pattern writes it. + pub display_date: Option, /// Where the field is shown: on screen, in print, or both (its annotation flags). pub views: Views, /// The field must be filled in (`Required`); a radio button, when its group must be. diff --git a/crates/xfa/src/layout/pages.rs b/crates/xfa/src/layout/pages.rs index 3d4e114c9d..8ea518fb39 100644 --- a/crates/xfa/src/layout/pages.rs +++ b/crates/xfa/src/layout/pages.rs @@ -3,7 +3,7 @@ use super::EMBED_COPIED; use super::items::{Item, Page, UNDERLINE_DROP}; use super::{ Block, Border, Common, Ctx, Cursor, FlowMark, Font, Frame, Layouter, MAX_DRAW_CHARS, MAX_ITEMS, MAX_MEASURES, MAX_PAGES, Node, PAGE_COUNT_MARK, - PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text, + PageArea, PageRole, Para, Rc, Rect, SomIndices, Views, XfaError, data_path, text, }; impl Layouter<'_> { @@ -114,12 +114,79 @@ impl Layouter<'_> { // ───────────────────────────────────────────────────────────────────────── pages + /// Find the `pageArea` index matching a `target` attribute (by `name` or `#id`, or the final + /// SOM segment), preferring an area whose `occur_max` is not yet exhausted. + pub(super) fn find_page_area(&self, target: &str) -> Option { + let raw = target.trim().trim_start_matches('#'); + let leaf = raw.rsplit('.').next().unwrap_or(raw).split('[').next().unwrap_or(raw).trim().trim_start_matches('#'); + if leaf.is_empty() { + return None; + } + let matches = |a: &PageArea| { + a.name.as_deref() == Some(leaf) || a.id.as_deref() == Some(leaf) || a.name.as_deref() == Some(raw) || a.id.as_deref() == Some(raw) + }; + (0..self.areas.len()).find(|&i| { + let Some(area) = self.areas.get(i) else { return false }; + matches(area) && area.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m)) + }) + } + + /// Remember an explicit break target for later untargeted pages. A later explicit break + /// replaces it. An `overflow` target may hide it while that subform is open; it returns + /// afterwards unless a later explicit break replaced the overflow. + pub(super) fn select_break_area(&mut self, idx: usize) { + self.preferred_area = Some(idx); + self.preferred_epoch = self.preferred_epoch.saturating_add(1); + } + pub(super) fn new_page(&mut self) -> Result<(), XfaError> { - let idx = - (0..self.areas.len()).find(|&i| self.areas[i].occur_max.is_none_or(|m| self.uses[i] < m)).unwrap_or(self.areas.len().saturating_sub(1)); + let idx = self + .preferred_area + .filter(|&i| self.areas.get(i).is_some_and(|a| a.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m)))) + .or_else(|| { + (0..self.areas.len()) + .find(|&i| self.areas.get(i).is_some_and(|a| a.occur_max.is_none_or(|m| self.uses.get(i).is_some_and(|u| *u < m)))) + }) + .unwrap_or(self.areas.len().saturating_sub(1)); self.new_page_of(idx) } + /// Replace the current page when nothing from the flow has been placed on it yet and a + /// subform's `breakBefore` targets a different `pageArea` `idx`. + pub(super) fn switch_empty_page(&mut self, idx: usize) -> Result<(), XfaError> { + if let Some(c) = &self.cur + && let Some(u) = self.uses.get_mut(c.area) + { + *u = u.saturating_sub(1); + } + if let Some(old) = self.pages.pop() { + self.items = self.items.saturating_sub(old.items.len()); + } + self.fields = self.page_fields; + for name in self.page_taken.drain(..) { + self.taken.remove(&name); + } + for (name, previous) in self.page_names.drain() { + if let Some(count) = previous { + self.names.insert(name, count); + } else { + self.names.remove(&name); + } + } + self.new_page_of(idx)?; + let (rect, y, _) = self.cursor(); + let mut room = (rect.bottom() - y).max(0.0); + for i in 0..self.frames.len() { + let Some(mark) = self.flow_mark() else { break }; + let Some(f) = self.frames.get_mut(i) else { break }; + f.part = mark; + let top = f.margin.top.max(0.0).min(room); + room = (room - top).max(0.0); + self.advance(top); + } + Ok(()) + } + /// Once the body has been laid out, give every page area that has been used fewer times than /// its `occur min` the pages it still needs, in template order, after the body's pages. pub(super) fn satisfy_page_area_minimums(&mut self) -> Result<(), XfaError> { @@ -134,6 +201,7 @@ impl Layouter<'_> { /// Start a page from page area `idx`. fn new_page_of(&mut self, idx: usize) -> Result<(), XfaError> { + let old_area = self.cursor().0; if self.pages.len() >= MAX_PAGES { return Err(XfaError::TooLarge(format!("the form lays out to more than {MAX_PAGES} pages"))); } @@ -147,6 +215,10 @@ impl Layouter<'_> { self.pages.push(Page { width: area.width, height: area.height, items: Vec::new(), area: area.name.clone() }); let content = area.content.first().copied().unwrap_or(Rect::new(0.0, 0.0, area.width, area.height)); self.cur = Some(Cursor { area: idx, content: 0, rect: content, y: content.y, placed: false }); + self.refresh_frame_widths(old_area); + self.page_fields = self.fields; + self.page_names.clear(); + self.page_taken.clear(); // Master page content: positioned draws and fields. The page area's own SOM index counts // the pages made from it, so a field repeated on each page (a page number, an office-use // box) has a path of its own per page rather than every page sharing `[0]`. @@ -182,12 +254,29 @@ impl Layouter<'_> { && let Some(next) = area.content.get(c.content + 1).copied() { let i = c.content + 1; + let old_area = c.rect; self.cur = Some(Cursor { area: c.area, content: i, rect: next, y: next.y, placed: false }); + self.refresh_frame_widths(old_area); return Ok(()); } self.new_page() } + /// Refresh outer frames before their children, preserving each parent's available width + /// and margins. A fixed-width frame keeps its position. Raw area moves (a split block) keep + /// their existing lost-border bookkeeping. + fn refresh_frame_widths(&mut self, old_area: Rect) { + let area = self.cursor().0; + if area == old_area { + return; + } + let mut available = (area.x, area.w); + for frame in &mut self.frames { + frame.fit_width(available); + available = frame.inner_width(); + } + } + /// The current content area, how far down it the flow is, and whether anything has been /// placed in it; before the first page, an empty letter-size page from its top. pub(super) fn cursor(&self) -> (Rect, f64, bool) { @@ -222,6 +311,10 @@ impl Layouter<'_> { /// otherwise run past its bottom, out of its border. `to_page` moves to a new page instead (a /// child's own page break), which breaks the subforms around it the same way. pub(super) fn break_frames(&mut self, need: f64, to_page: bool) -> Result<(), XfaError> { + self.break_frames_to(need, to_page, None) + } + + pub(super) fn break_frames_to(&mut self, need: f64, to_page: bool, target_area: Option) -> Result<(), XfaError> { let (rect, mut y, _) = self.cursor(); let page = self.pages.len().saturating_sub(1); let here: Vec = self.frames.iter().map(|f| self.on_area(&f.part)).collect(); @@ -234,7 +327,9 @@ impl Layouter<'_> { f.parts.push((page, f.part.items, Rect::new(f.x, f.part.y, f.w, y - f.part.y))); } } - if to_page { + if let Some(idx) = target_area { + self.new_page_of(idx)?; + } else if to_page { self.new_page()?; } else { self.next_area()?; diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 9fad61fae7..68e94474da 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -136,9 +136,16 @@ pub struct Report { } /// Is this a dynamic XFA form still showing its placeholder pages (one PdfCraft has not laid -/// out yet)? +/// out yet)? That is a form that asks to be laid out (`/NeedsRendering`), one with no fields of +/// its own, or one a viewer saved with its pages drawn whose configuration says it must be +/// rendered dynamically (`required`): its fields live in the +/// template. A signature on such a form covers the pages as saved, so a signed one is left as it +/// is: laying it out would change what was signed. pub fn is_dynamic(doc: &Document) -> bool { - existing_layout(doc).is_none() && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering || !p.has_fields) + existing_layout(doc).is_none() + && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering + || !p.has_fields + || (packets::requires_dynamic_render(&p.xdp) && !packets::has_signature(doc))) } /// Lay a template packet (or whole XDP, whose datasets then fill the fields) out. diff --git a/crates/xfa/src/model.rs b/crates/xfa/src/model.rs index 6f264500f1..f8cb94da79 100644 --- a/crates/xfa/src/model.rs +++ b/crates/xfa/src/model.rs @@ -534,6 +534,12 @@ pub struct Subform { /// ``: start on a new page. pub break_before_page: bool, pub break_after_page: bool, + /// `` / ``: named `pageArea` (or `#id`) to start on. + pub break_before_target: Option, + /// `` / ``: named `pageArea` (or `#id`) to switch to after. + pub break_after_target: Option, + /// `` / ``: named `pageArea` (or `#id`) for overflow pages. + pub overflow_target: Option, /// Parsed from a `subformSet`: transparent to layout (XFA 3.3 p. 357), so in a flowing /// container its members are laid out among their parent's other children. pub set: bool, @@ -848,6 +854,7 @@ pub struct PageSet { #[derive(Clone, Debug, Default, PartialEq)] pub struct PageArea { pub name: Option, + pub id: Option, pub width: f64, pub height: f64, /// Where flowed content goes, in order. diff --git a/crates/xfa/src/packets.rs b/crates/xfa/src/packets.rs index 00caabe589..faebfd7d44 100644 --- a/crates/xfa/src/packets.rs +++ b/crates/xfa/src/packets.rs @@ -28,6 +28,10 @@ fn check_text(len: usize) -> Result<(), XfaError> { Ok(()) } +/// Most XML nodes read when the XDP is parsed for its configuration, as many as the template +/// parser allows. +const MAX_XDP_NODES: u32 = 2_000_000; + /// What was found in the XFA entry. #[derive(Clone, Debug, Default, PartialEq)] pub struct Packets { @@ -117,6 +121,70 @@ fn to_text(bytes: &[u8]) -> String { } } +/// Whether the XDP's configuration packet asks for dynamic rendering: `required` at +/// `config/acrobat/acrobat7/dynamicRender` (Designer writes it for a dynamic form). The packet is +/// the `config` child of the `xdp` root (a whole-XDP stream, or an array's packets read in order +/// between its preamble and postamble), or the document itself when it is a bare `config` packet. +/// An element of that name anywhere else (a data node, inside the template) is not it. XML that +/// doesn't parse, or has a DTD, asks for nothing. +pub(crate) fn requires_dynamic_render(xdp: &str) -> bool { + let opts = crate::xml::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XDP_NODES }; + let Ok(doc) = crate::xml::Document::parse_with_options(xdp, opts) else { return false }; + let root = doc.root_element(); + /// `n`'s first child element named `name` (any namespace). + fn child<'a>(n: crate::xml::Node<'a>, name: &str) -> Option> { + n.children().find(|c| c.is_element() && c.tag_name().name() == name) + } + let config = match root.tag_name().name() { + "config" => Some(root), + "xdp" => child(root, "config"), + _ => None, + }; + config + .and_then(|c| child(c, "acrobat")) + .and_then(|a| child(a, "acrobat7")) + .and_then(|a| child(a, "dynamicRender")) + .and_then(|d| d.text()) + .is_some_and(|t| t.trim() == "required") +} + +/// Whether the AcroForm holds a signed signature field (`/FT /Sig` with a value), looked for at +/// most 32 levels deep and among at most 10 000 fields. A form whose fields go past either limit +/// counts as signed: what wasn't looked at may be, and laying a signed form out would change +/// what was signed. +pub(crate) fn has_signature(doc: &Document) -> bool { + let Some(root) = doc.root() else { return false }; + let catalog = doc.get(root); + let Some(acro) = catalog.as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return false }; + let Some(fields) = acro.as_dict().and_then(|a| a.get(b"Fields")).map(|f| doc.resolve(f)) else { return false }; + let Some(fields) = fields.as_array() else { return false }; + // (field, inherited field type, depth) + let mut todo: Vec<(Object, bool, usize)> = fields.iter().map(|f| (f.clone(), false, 0)).collect(); + let mut seen = std::collections::HashSet::new(); + let mut budget = 10_000usize; + while let Some((f, sig_above, depth)) = todo.pop() { + if budget == 0 || depth > 32 { + return true; + } + if f.as_ref().is_some_and(|r| !seen.insert(r)) { + continue; + } + budget -= 1; + let f = doc.resolve(&f); + let Some(d) = f.as_dict() else { continue }; + let sig = d.name(b"FT").map_or(sig_above, |t| t == b"Sig"); + if sig && d.get(b"V").is_some_and(|v| !matches!(&*doc.resolve(v), Object::Null)) { + return true; + } + if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)) + && let Some(kids) = kids.as_array() + { + todo.extend(kids.iter().map(|k| (k.clone(), sig, depth + 1))); + } + } + false +} + /// Read the XFA packets, if the document has any. pub fn read_packets(doc: &Document) -> Result, XfaError> { let Some(root) = doc.root() else { return Ok(None) }; diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs index 45aa7449dc..fade375db7 100644 --- a/crates/xfa/src/parse.rs +++ b/crates/xfa/src/parse.rs @@ -942,7 +942,16 @@ fn parse_page_set(n: XmlNode, warnings: &mut Vec, depth: usize) -> PageS // would exhaust it, and demand a page for every master). let occur = child(pa, "occur").map(|o| parse_occur(Some(o))); let (occur_min, occur_max) = occur.map_or((0, None), |o| (o.min, o.max)); - areas.push(PageArea { name: pa.attribute("name").map(str::to_string), width, height, content, items, occur_max, occur_min }); + areas.push(PageArea { + name: pa.attribute("name").map(str::to_string), + id: pa.attribute("id").map(str::to_string), + width, + height, + content, + items, + occur_max, + occur_min, + }); } // Nested page sets: take their areas too. for ps in children(n, "pageSet") { @@ -973,9 +982,22 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec, depth: usize, set_layou } let column_widths: Vec = n.attribute("columnWidths").map(|s| s.split_whitespace().filter_map(measure).map(|w| w.max(0.0)).take(256).collect()).unwrap_or_default(); + let is_page_target = |t: Option<&str>| t.is_none_or(|v| v == "pageArea" || v == "contentArea"); // A break to a page or content area. With no targetType, the default is `auto`: "layout // continues using the current layout container" (XFA 3.3 p. 638), so no break. let break_to_page = |name: &str| children(n, name).any(|b| b.attribute("targetType").is_some_and(|t| t == "pageArea" || t == "contentArea")); + let non_empty = |s: Option<&str>| s.map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); + let break_target = |name: &str, break_attr: &str, target_attr: &str| -> Option { + children(n, name) + .filter(|b| is_page_target(b.attribute("targetType"))) + .find_map(|b| non_empty(b.attribute("target"))) + .or_else(|| child(n, "break").filter(|b| is_page_target(b.attribute(break_attr))).and_then(|b| non_empty(b.attribute(target_attr)))) + }; + let break_before_target = break_target("breakBefore", "before", "beforeTarget"); + let break_after_target = break_target("breakAfter", "after", "afterTarget"); + let overflow_target = child(n, "overflow") + .and_then(|o| non_empty(o.attribute("target"))) + .or_else(|| child(n, "break").and_then(|b| non_empty(b.attribute("overflowTarget")))); Subform { common, layout, @@ -984,8 +1006,14 @@ fn parse_subform(n: XmlNode, warnings: &mut Vec, depth: usize, set_layou page_set, occur: parse_occur(child(n, "occur")), break_before_page: break_to_page("breakBefore") + || break_before_target.is_some() || child(n, "break").is_some_and(|b| b.attribute("before").is_some_and(|v| v == "pageArea" || v == "contentArea")), - break_after_page: break_to_page("breakAfter"), + break_after_page: break_to_page("breakAfter") + || break_after_target.is_some() + || child(n, "break").is_some_and(|b| b.attribute("after").is_some_and(|v| v == "pageArea" || v == "contentArea")), + break_before_target, + break_after_target, + overflow_target, set: false, column_widths, overflow_leader: child(n, "overflow").and_then(|o| o.attribute("leader")).map(str::to_string).filter(|s| !s.is_empty()), diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index 2d47963324..9e082a5d3a 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -334,8 +334,10 @@ impl Emitter<'_> { if let WidgetKind::Date(pattern) = &w.kind { d.set(DATE_KEY.to_vec(), Object::Bool(true)); let mut aa = Dict::new(); + // Shown through the display picture, typed in the edit picture's pattern. + let shown = js_string(w.display_date.as_deref().unwrap_or(pattern)); let pattern = js_string(pattern); - aa.set(b"F".to_vec(), js_action(&format!("AFDate_FormatEx({pattern});"))); + aa.set(b"F".to_vec(), js_action(&format!("AFDate_FormatEx({shown});"))); aa.set(b"K".to_vec(), js_action(&format!("AFDate_KeystrokeEx({pattern});"))); d.set(b"AA".to_vec(), Object::Dict(aa)); } diff --git a/crates/xfa/src/pdf/strip.rs b/crates/xfa/src/pdf/strip.rs index 686e356f0a..07b1163261 100644 --- a/crates/xfa/src/pdf/strip.rs +++ b/crates/xfa/src/pdf/strip.rs @@ -1,4 +1,7 @@ -use super::{CLICK_KEY, DATE_KEY, Dict, Document, GROUPS, IMAGE_FIELD_KEY, LAYOUT_KEY, NODE_KEY, ObjRef, Object, RELEVANT_KEY, SOM_KEY, XfaError}; +use super::{ + CLICK_KEY, DATE_KEY, Dict, Document, GROUPS, IMAGE_FIELD_KEY, LAYOUT_KEY, NODE_KEY, ObjRef, Object, PdfString, RELEVANT_KEY, SOM_KEY, XfaError, + js_action, +}; /// What laying a form out says when it took the usage rights off (see [`drop_usage_rights`]). pub(crate) const USAGE_RIGHTS_REMOVED: &str = @@ -46,6 +49,8 @@ pub struct Stripped { pub usage_rights: bool, /// Private keys removed from field dictionaries (`/PCSom`, `/PCXfaClick`, …). pub field_keys: usize, + /// Date fields now holding and typed in the pattern they show ([`static_date`]). + pub date_fields: usize, } impl Stripped { @@ -69,6 +74,12 @@ impl Stripped { if self.usage_rights { out.push("Adobe Reader extended features were removed (changing the form voids them)".into()); } + if self.date_fields > 0 { + out.push(format!( + "{} date field(s) now hold and take their dates as they show them: a static form can't keep a date one way and show it another", + self.date_fields + )); + } out } } @@ -107,6 +118,42 @@ pub fn xfa_shape(doc: &Document) -> Option { Some(XfaShape { needs_rendering, has_fields, laid_out: acro.contains(LAYOUT_KEY) }) } +/// A field's values to write: the key (`/V` or `/DV`) and its new text. +type NewValues = Vec<(&'static [u8], String)>; + +/// A date field PdfCraft laid out, made one a static form keeps working in other viewers. The +/// layout keeps its value as an ISO date (or as typed), types it in its edit pattern (`/AA /K`) +/// and shows it in its display pattern (`/AA /F`). A static form can do neither: another viewer +/// checks typing against the keystroke pattern but reads the value again in the format's, so +/// only dates that read both ways pass, and those show misread. So its keystroke takes the +/// format's pattern, and its value and default value, when they read as dates in the edit +/// pattern or as ISO dates, are written in it. The new `/AA` and values, or `None` when nothing +/// changes. +fn static_date(doc: &Document, d: &Dict) -> Option<(Dict, NewValues)> { + let aa = doc.resolve(d.get(b"AA")?).as_dict()?.clone(); + let pattern = |key: &[u8], call: &str| { + let action = doc.resolve(aa.get(key)?).as_dict()?.clone(); + let js = doc.resolve(action.get(b"JS")?).as_string()?.to_text(); + let rest = js.trim().strip_prefix(call)?.trim_start().strip_prefix("(\"")?; + rest.split_once("\")").map(|(p, _)| p.to_string()) + }; + let shown = pattern(b"F", "AFDate_FormatEx")?; + let typed = pattern(b"K", "AFDate_KeystrokeEx")?; + let mut aa = aa; + if typed != shown { + aa.set(b"K".to_vec(), js_action(&format!("AFDate_KeystrokeEx(\"{shown}\");"))); + } + let mut values = Vec::new(); + for key in [b"V".as_slice(), b"DV"] { + let Some(text) = d.get(key).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text())) else { continue }; + let iso = [typed.as_str(), "yyyy-mm-dd", "yyyymmdd"].iter().find_map(|p| crate::data::pattern_to_iso(&text, p)); + if let Some(iso) = iso.map(|iso| crate::data::iso_to_pattern(&iso, &shown)).filter(|v| *v != text) { + values.push((key, iso)); + } + } + (typed != shown || !values.is_empty()).then_some((aa, values)) +} + /// Most field dictionaries walked for their private keys. const MAX_STRIP_FIELDS: usize = 1_000_000; @@ -190,6 +237,17 @@ pub fn strip(doc: &mut Document) -> Result { if d.contains(IMAGE_FIELD_KEY) { out.image_fields += 1; } + if d.contains(DATE_KEY) + && let Some((aa, values)) = static_date(doc, &d) + { + out.date_fields += 1; + doc.update_dict(r, |d| { + d.set(b"AA".to_vec(), Object::Dict(aa)); + for (k, v) in values { + d.set(k.to_vec(), Object::String(PdfString::text(&v))); + } + })?; + } let private: Vec> = [SOM_KEY, CLICK_KEY, IMAGE_FIELD_KEY, DATE_KEY, NODE_KEY, b"PCItems".as_slice()] .iter() .filter(|k| d.contains(k)) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 7606ae6530..aa9893dadf 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -426,6 +426,8 @@ fn the_xdp_template_wins_over_the_config_packets_template_element() { assert_eq!(tpl.root.common.name.as_deref(), Some("form")); } +/// The sample form lays out over two pages: captions, draws and page numbers are drawn, +/// hidden draws take no space, and each field gets its widget with its size, kind and SOM path. #[test] fn layout_places_captions_fields_and_sizes_containers_to_their_content() { let form = layout_xml(&template(1)).unwrap(); @@ -484,6 +486,97 @@ fn layout_places_captions_fields_and_sizes_containers_to_their_content() { ); } +/// The left edges of the lines of a draw `w` points wide holding `text` in Arial 8 pt, with +/// `para` attributes, from the content area's left edge (0.5in). +fn line_starts(text: &str, w: f64, para: &str) -> Vec { + let xdp = format!( + r##""## + ); + let form = layout_xml(&xdp).unwrap(); + let mut lines: Vec<(i64, f64)> = Vec::new(); + for item in &form.pages[0].items { + let Item::Text(s) = item else { continue }; + let key = (s.baseline * 100.0).round() as i64; + match lines.iter_mut().find(|(b, _)| *b == key) { + Some((_, x)) => *x = x.min(s.x), + None => lines.push((key, s.x)), + } + } + lines.sort_by_key(|(b, _)| *b); + lines.into_iter().map(|(_, x)| x - 36.0).collect() +} + +/// A negative textIndent hangs the first line: it starts left of the others, never left of the +/// box, and the other lines move in by the hang. A positive indent still moves only the first line. +#[test] +fn a_negative_text_indent_hangs_the_first_line_and_indents_the_rest() { + let text = "11. SERVICE MEMBER BALANCE (TOTAL)"; + // No left margin: the first line starts at the box's edge and the others 18pt in. + let starts = line_starts(text, 58.0, r#"textIndent="-18pt""#); + assert!(starts.len() >= 3, "{starts:?}"); + assert!(starts[0].abs() < 1e-6, "first line at the edge: {starts:?}"); + assert!(starts[1..].iter().all(|x| (x - 18.0).abs() < 1e-6), "the rest hang 18pt in: {starts:?}"); + // With a left margin wider than the hang, the first line starts at the margin less the hang. + let starts = line_starts(text, 90.0, r#"marginLeft="30pt" textIndent="-18pt""#); + assert!(starts.len() >= 2, "{starts:?}"); + assert!((starts[0] - 12.0).abs() < 1e-6 && starts[1..].iter().all(|x| (x - 30.0).abs() < 1e-6), "{starts:?}"); + // A positive indent still moves only the first line in. + let starts = line_starts(text, 58.0, r#"textIndent="10pt""#); + assert!((starts[0] - 10.0).abs() < 1e-6 && starts[1..].iter().all(|x| x.abs() < 1e-6), "{starts:?}"); + // Without a negative indent a negative left margin moves every line left, as before. + let starts = line_starts(text, 58.0, r#"marginLeft="-6pt""#); + assert!(starts.iter().all(|x| (x + 6.0).abs() < 1e-6), "{starts:?}"); + let starts = line_starts(text, 58.0, r#"marginLeft="-6pt" textIndent="10pt""#); + assert!((starts[0] - 4.0).abs() < 1e-6 && starts[1..].iter().all(|x| (x + 6.0).abs() < 1e-6), "{starts:?}"); +} + +/// A hang wider than its box is bounded by it: every line still starts and ends inside the box, +/// and lines after the first keep room for the widest glyph when the text wraps. +#[test] +fn a_hang_wider_than_the_box_keeps_every_line_inside_it() { + // A 58pt box hanging its first line by 100pt, right-aligned. + for text in ["AB CD EF", "ABCDEFGHIJ KLMNOPQRST UVWXYZ MMMM WWWW"] { + let xdp = format!( + r##""## + ); + let form = layout_xml(&xdp).unwrap(); + let mut lines = std::collections::BTreeSet::new(); + for item in &form.pages[0].items { + let Item::Text(s) = item else { continue }; + lines.insert((s.baseline * 100.0).round() as i64); + let right = s.x + s.face.width(s.text.trim_end()); + assert!(s.x >= 36.0 - 1e-6 && right <= 36.0 + 58.0 + 1e-6, "{text}: {:?} runs from {} to {right}", s.text, s.x); + } + if text.len() > 10 { + assert!(lines.len() > 1, "{text}: wraps onto more lines ({})", lines.len()); + } + } +} + +/// A label without a width that hangs its first line is as wide as that line is laid out: the +/// hang takes back the left margin the first line doesn't use, so right-aligned text starts at +/// the label's x. +#[test] +fn a_label_without_a_width_measures_its_hanging_indent_as_it_is_laid_out() { + let items = positioned( + r#"11. BALANCE"#, + ); + let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text"); + assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x); +} + +/// A long table breaks across pages between whole rows, repeats its header row at the top of +/// each page it continues on, and keeps every row (and field name) once. #[test] fn tables_break_across_pages_and_repeat_their_header_row() { let form = layout_xml(&template(40)).unwrap(); @@ -504,6 +597,58 @@ fn tables_break_across_pages_and_repeat_their_header_row() { assert_eq!(all.len(), all.iter().collect::>().len(), "field names are unique"); } +/// A form a viewer saved with its pages drawn, holding only its signature box, is laid out from +/// its template when its configuration says it must be rendered dynamically: its other fields +/// live there. Signed, it is left as saved (laying it out would change what was signed), as it is +/// without that configuration or with `forbidden`. +#[test] +fn a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering() { + let open = |render: &str, signed: bool| Document::open(Arc::new(crate::fixtures::saved_with_pages_shell(render, signed))).unwrap(); + let mut doc = open("required", false); + assert!(is_dynamic(&doc)); + let report = render_into(&mut doc).unwrap(); + assert_eq!(report.fields, 2, "the text field from the template, and the signature box"); + assert!(!is_dynamic(&open("required", true)), "signed: left as saved"); + assert!(!is_dynamic(&open("", false)), "no configuration: the fields it has are the form's"); + assert!(!is_dynamic(&open("forbidden", false))); + // A box under nested fields is found; past the 32 levels looked at, the form counts as signed. + let deep = |depth: usize| Document::open(Arc::new(crate::fixtures::deep_saved_with_pages_shell(depth))).unwrap(); + assert!(is_dynamic(&deep(5)), "nested, unsigned"); + assert!(!is_dynamic(&deep(40)), "too deep to tell: as if signed"); + // The page lists the box under its new number, and the box knows its parent. + let doc = deep(5); + let page = doc.get(pdfcraft_cos::ObjRef::new(3, 0)); + let annot = page.as_dict().and_then(|d| d.get(b"Annots")).and_then(|a| a.as_array().and_then(|a| a.first().cloned())).and_then(|a| a.as_ref()); + let widget = annot.map(|r| doc.get(r)); + assert_eq!(widget.as_ref().and_then(|w| w.as_dict().and_then(|d| d.name(b"FT")).map(<[u8]>::to_vec)), Some(b"Sig".to_vec())); + assert!(widget.as_ref().and_then(|w| w.as_dict().map(|d| d.contains(b"Parent"))).unwrap_or(false)); +} + +/// Only the configuration packet's `acrobat/acrobat7/dynamicRender` asks for dynamic rendering: +/// not the same element elsewhere, another element that starts with `config`, or another value. +#[test] +fn dynamic_rendering_is_read_from_the_configuration_only() { + let required = crate::packets::requires_dynamic_render; + let config = |inner: &str| { + format!( + r#"{inner}