Merge remote-tracking branch 'origin/main' into fix/audit-clipping-coverage

This commit is contained in:
FredApps
2026-12-02 18:27:28 +07:00
373 changed files with 29145 additions and 2181 deletions
+8 -1
View File
@@ -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 }
+117
View File
@@ -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"
}
}
}
}
+9 -4
View File
@@ -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
+8 -4
View File
@@ -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
+72
View File
@@ -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.')
+59
View File
@@ -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.
+35
View File
@@ -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"]'
+20
View File
@@ -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 }}
+1
View File
@@ -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 }}
+3 -1
View File
@@ -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
+5 -7
View File
@@ -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:
+1 -1
View File
@@ -81,7 +81,7 @@ For the crates you changed: `cargo fmt --check`, `cargo clippy -p <crate> -- -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 <PORT>`, 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.
+9 -1
View File
@@ -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) |
+88
View File
@@ -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)"
Generated
+150 -137
View File
File diff suppressed because it is too large Load Diff
+77 -75
View File
@@ -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" }
+6 -1
View File
@@ -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"
+2 -1
View File
@@ -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.
+1
View File
@@ -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)
+10
View File
@@ -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.
+20 -16
View File
@@ -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<f32, String> {
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);
+51
View File
@@ -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<Option<&'a str>, 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<String> {
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");
}
}
+1
View File
@@ -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;
@@ -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<u8> {
let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];
let kids: Vec<String> = (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<String> {
let mut names: Vec<String> = 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");
}
+2 -16
View File
@@ -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");
}
+2 -2
View File
@@ -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 }
+4 -1
View File
@@ -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);
+5 -1
View File
@@ -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.
+49 -7
View File
@@ -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}");
-1
View File
@@ -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<dyn Fn()> {
let wake = ctx.clone();
self.inbox.set_wake(move || wake.request_repaint());
+57
View File
@@ -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));
}
}
}
+49
View File
@@ -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)");
}
}
+197
View File
@@ -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<Item = OsString>) -> Result<Launch, ProfileError> {
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<OsString> {
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<OsString> {
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 <profile>/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 <profile>\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"]));
}
}
+274 -35
View File
@@ -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<Vec<std::ffi::OsString>> {
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::<Vec<_>>()) {
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<String>,
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<eframe::wgpu::Backends> {
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>) -> eframe::wgpu::Dx12SwapchainKind {
@@ -806,14 +1004,25 @@ fn linux_display_gpus(drm: &std::path::Path) -> Vec<DisplayGpu> {
/// 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<usize> {
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<usize> {
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));
}
}
+230
View File
@@ -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<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
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<Mutex<Option<Session>>>;
/// 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<Self>, 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<Option<Self>> {
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();
}
}
}
+65
View File
@@ -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<Result<(), String>> = 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());
}
}
+199
View File
@@ -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<PathBuf> {
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<PathBuf> {
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 { .. })));
}
}
+24 -10
View File
@@ -159,26 +159,29 @@ pub fn absolute(paths: &[String]) -> Vec<String> {
/// 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<std::path::PathBuf> {
fn socket_path(profile_root: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
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::path::PathBuf> {
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<std::path::PathBuf> {
fn socket_path(profile_root: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
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()));
}
}
+25
View File
@@ -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<Item = String>, nightly: bool) -> Self {
if nightly { Self::parse_impl(args, true) } else { Self::parse(args) }
}
pub fn parse(args: impl IntoIterator<Item = String>) -> Self {
Self::parse_impl(args, false)
}
fn parse_impl(args: impl IntoIterator<Item = String>, 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
+78 -5
View File
@@ -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.
+101
View File
@@ -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<RECT> {
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());
}
}
+106
View File
@@ -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::<serde_json::Value>(&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();
}
@@ -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"));
}
+24
View File
@@ -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."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

@@ -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/
+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v1.49.0 - ISC -->
<svg
class="lucide lucide-chevrons-down"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m7 6 5 5 5-5" />
<path d="m7 13 5 5 5-5" />
</svg>

After

Width:  |  Height:  |  Size: 349 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v1.49.0 - ISC -->
<svg
class="lucide lucide-chevrons-up"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m17 11-5-5-5 5" />
<path d="m17 18-5-5-5 5" />
</svg>

After

Width:  |  Height:  |  Size: 350 B

+12
View File
@@ -0,0 +1,12 @@
<!-- Original artwork by Combiler01, CC0-1.0 -->
<svg xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="0.75"
stroke-linejoin="round"
>
<path d="M 10.4588 22.4944 c -0.4792 -0.043 -0.768 -0.3686 -0.768 -0.8663 c 0 -0.4178 0.1659 -0.8601 0.5959 -1.5974 c 0.5468 -0.9277 0.768 -1.4438 0.7127 -1.665 c -0.0491 -0.1966 -1.0076 0.0737 -2.7893 0.7803 c -3.3914 1.3455 -5.001 1.4622 -6.0516 0.4546 c -1.4622 -1.4069 0.5959 -3.2255 4.0487 -3.5818 l 0.2027 -0.0184 l 0.0983 0.0491 c 0.3256 0.1597 0.2396 0.6267 -0.1229 0.6697 c -3.1517 0.3379 -5.1116 1.9291 -3.2931 2.6725 c 0.9646 0.3932 2.1073 0.172 5.0563 -0.9769 c 2.1933 -0.854 2.9183 -0.983 3.3483 -0.5775 c 0.4239 0.3993 0.2826 1.0444 -0.5222 2.4391 c -0.4239 0.7311 -0.5714 1.0752 -0.5714 1.3516 l 0 0.1536 l 0.0676 0.0246 c 0.4423 0.1474 1.3086 -0.3932 2.5804 -1.6097 c 1.3762 -1.3148 2.095 -1.7633 2.7831 -1.7325 c 0.7311 0.0369 0.8847 0.6758 0.3993 1.7141 c -0.2888 0.6205 -0.301 0.6512 -0.2335 0.6328 c 0.2519 -0.0799 0.4608 -0.2212 0.897 -0.5959 c 0.725 -0.6328 1.0444 -0.8171 1.4991 -0.854 c 0.8786 -0.0737 1.9107 0.9154 1.3209 1.2595 c -0.172 0.0983 -0.3379 0.0553 -0.4976 -0.1352 c -0.2519 -0.301 -0.4423 -0.4055 -0.7311 -0.4055 h -0.1966 l -0.1413 0.0737 c -0.2089 0.1044 -0.4116 0.258 -0.9277 0.725 c -0.7127 0.6451 -1.3946 0.8294 -1.7694 0.4854 c -0.2765 -0.258 -0.258 -0.6144 0.0553 -1.2902 c 0.4055 -0.8663 0.4116 -0.9707 0.0553 -0.854 c -0.5284 0.172 -0.9646 0.4915 -1.8984 1.3823 c -1.5974 1.5236 -2.3715 1.9844 -3.207 1.9168 z m -0.9918 -5.8111 c -0.0123 -0.0061 -0.3318 -0.0983 -0.7188 -0.215 c -0.3871 -0.1167 -0.7618 -0.2273 -0.8417 -0.2519 c -0.2949 -0.086 -0.4423 -0.301 -0.3993 -0.5837 c 0.0246 -0.172 0.0307 -0.1782 1.2165 -1.4561 l 0.1659 -0.1782 l 0.0061 -0.1044 c 0.0123 -0.1843 0.0614 -0.2765 0.2642 -0.4976 c 0.6267 -0.682 0.7987 -1.1366 0.9154 -2.4083 c 0.129 -1.4315 -0.0614 -1.1182 1.7878 -2.906 c 0.4854 -0.4669 1.0321 -1.0014 1.2165 -1.1796 c 0.1843 -0.1782 0.6144 -0.6021 0.9584 -0.9338 c 0.3441 -0.3318 1.069 -1.0383 1.6035 -1.5605 c 2.777 -2.7032 2.648 -2.5804 2.777 -2.6602 c 0.5345 -0.3502 1.2165 -0.3441 1.7018 0.0246 c 0.1659 0.1229 1.7141 1.665 1.8308 1.8247 c 0.4854 0.6451 0.4546 1.4929 -0.0737 2.1073 c -0.1413 0.1659 -0.9154 1.0936 -1.4991 1.8001 c -0.5407 0.6574 -1.4499 1.7571 -2.3838 2.8876 c -0.4485 0.5407 -1.6035 1.9414 -2.3776 2.8814 c -0.7188 0.8724 -0.725 0.8786 -1.5175 0.9953 c -1.7325 0.258 -2.0459 0.3809 -2.7708 1.0874 c -0.2949 0.2888 -0.3502 0.3256 -0.5345 0.3441 l -0.1044 0.0123 l -0.2396 0.2642 c -0.4423 0.4915 -0.639 0.682 -0.7188 0.7004 c -0.0676 0.0184 -0.2335 0.0246 -0.2703 0.0123 z m 0.3748 -1.0752 m 0.3133 -0.3379 m -0.1413 -0.129 c -0.0737 -0.0737 -0.2457 -0.2335 -0.3809 -0.3625 c -0.1352 -0.129 -0.2519 -0.2335 -0.258 -0.2335 c -0.0307 0 -1.0076 1.069 -0.9891 1.0813 c 0.0123 0.0061 0.2396 0.0799 0.5099 0.1597 c 0.2703 0.0799 0.5038 0.1536 0.5284 0.1659 c 0.0799 0.0307 0.0983 0.0123 0.4178 -0.3318 z m 1.1304 -0.8847 c 0.6942 -0.6451 1.4315 -0.9523 2.6787 -1.0997 c 0.1229 -0.0123 0.1474 0.0184 -0.2273 -0.3318 c -0.4546 -0.4301 -1.5482 -1.4684 -2.1196 -2.009 c -0.3748 -0.3563 -0.4915 -0.4608 -0.4976 -0.4362 c -0.0061 0.0184 -0.0184 0.1044 -0.0246 0.1905 c -0.0922 1.2779 -0.3502 1.9721 -1.0137 2.7524 l -0.0737 0.086 l 0.5345 0.5038 c 0.6144 0.5837 0.5345 0.5468 0.7434 0.3502 z m 3.9627 -1.7325 c 0.3563 -0.4301 0.7188 -0.8663 1.3823 -1.6711 c 0.2396 -0.2888 0.6082 -0.7372 0.8171 -0.9891 c 0.2089 -0.258 0.6635 -0.8048 1.0076 -1.2165 c 0.8171 -0.983 1.1612 -1.4008 1.794 -2.1687 c 0.2826 -0.3502 0.7065 -0.8601 0.94 -1.1366 c 0.6942 -0.8294 0.7004 -0.8355 0.7127 -1.155 c 0.0184 -0.4116 0 -0.4362 -0.8233 -1.2718 c -1.1857 -1.198 -1.2595 -1.2472 -1.6097 -1.1857 c -0.2888 0.0553 -0.1229 -0.0922 -2.1319 1.8677 c -3.9197 3.8153 -4.2515 4.1409 -5.3389 5.1853 c -0.3686 0.3563 -0.6758 0.6574 -0.6881 0.6758 c -0.0369 0.0737 -0.043 0.0676 2.1933 2.1872 c 0.6021 0.5714 1.1489 1.0936 1.2226 1.1612 c 0.172 0.1659 0.1413 0.1782 0.5222 -0.2765 z" />
</svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+18
View File
@@ -0,0 +1,18 @@
<!-- @license lucide-static v1.49.0 - ISC -->
<svg
class="lucide lucide-pin-off"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 17v5" />
<path d="M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" />
<path d="m2 2 20 20" />
<path d="M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11" />
</svg>

After

Width:  |  Height:  |  Size: 486 B

+33 -1
View File
@@ -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
+8
View File
@@ -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"
+100 -20
View File
@@ -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<i64> {
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<ObjRef>) -> Result<HashSet<i64>, MutationContentError> {
fn visit(
doc: &Document,
item: &Object,
page: Option<ObjRef>,
depth: usize,
remaining: &mut usize,
ancestors: &mut HashSet<ObjRef>,
ids: &mut HashSet<i64>,
) -> 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<i64> = mcids(doc, &d).into_iter().collect();
let pages = pdfcraft_model::pages(doc);
let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page));
if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) {
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<i64> = 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<Object, ArtifactError> {
let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?;
match kids {
+134 -48
View File
@@ -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 <</Type /Pagination /Subtype /Header>> 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<Evidence>,
artifacts: HashMap<usize, usize>,
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<String>) -> 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<Vec<Plan>, AutoTagError> {
@@ -301,21 +329,26 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
Ok(out)
}
fn mark_ops(
ops: Vec<Op>,
starts: &HashMap<usize, (usize, &'static str)>,
ends: &HashSet<usize>,
artifacts: &HashMap<usize, usize>,
) -> Result<Vec<Op>, AutoTagError> {
fn mark_ops(ops: Vec<Op>, starts: &HashMap<usize, Mark>, ends: &HashSet<usize>, artifacts: &HashMap<usize, usize>) -> Result<Vec<Op>, AutoTagError> {
let artifact_ends: HashSet<usize> = 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<Vec<Option<Edge>>> {
let pages: Vec<PageText<'_>> = 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<Vec<RunningText>, 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<Object>,
numbers: Vec<Object>,
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<Edge>],
roles: &mut impl Iterator<Item = &'static str>,
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<AutoTagResult, AutoTagError> {
let plans = plan(doc)?;
let all: Vec<Evidence> = 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<Evidence> = 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)
}
+350 -74
View File
@@ -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<Item = &'a Evidence>) -> Option<f64> {
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<Item = &'a Evidence>) -> Option<(f64, bool)> {
let mut by_size: HashMap<i64, (usize, usize)> = 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<Rc<Metrics>>,
/// 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<Evidence> {
let mut by_name: HashMap<Vec<u8>, Option<Rc<Metrics>>> = 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<Vec<u8>, (Option<Rc<Metrics>>, 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<Evidence> {
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<usize> { 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<Evidence> {
let cmap = "begincmap 1 begincodespacerange <0000> <FFFF> 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<usize> { 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]));
}
}
+428
View File
@@ -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<f64>) -> Vec<Vec<Option<Edge>>> {
let mut out: Vec<Vec<Option<Edge>>> = 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<f64>) -> 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::<Vec<_>>().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<Member<'a>>> {
let mut groups: HashMap<(Edge, String), Vec<Member<'a>>> = 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<usize, usize> = 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<Evidence>], body: Option<f64>) -> Vec<Vec<Option<Edge>>> {
let text: Vec<PageText<'_>> = 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<Vec<Evidence>> = (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<Vec<Evidence>> = (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<Evidence> = (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");
}
}
+58
View File
@@ -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<Option<u8>> {
let evidence: Vec<Evidence> = 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]);
}
}
+39 -6
View File
@@ -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<usize, HashMap<i64, String>>,
/// 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<Heading>,
/// 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<Heading> {
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<Heading>, 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<Heading> {
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<ObjRef>, 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::<Vec<_>>().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();
+5 -2
View File
@@ -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};
+283 -6
View File
@@ -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<String> = 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<String> = 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<String> = 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<Option<i64>> = 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<String> = 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<String> {
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<Heading>, 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::<Vec<_>>(), 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]
+467
View File
@@ -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 <</MCID 0>> BDC 10 10 20 20 re f EMC\nq /Form Do Q";
let form = "/Figure <</MCID 0>> 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::<Vec<_>>();
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<u8> {
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::<Vec<_>>(), [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 <</MCID 0>> 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::<Vec<_>>();
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::<Vec<_>>(),
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::<Vec<_>>(),
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::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), 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::<Vec<_>>();
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::<Vec<_>>(), 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::<Vec<_>>(), 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::<Vec<_>>(), 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])
);
}
}
+17 -5
View File
@@ -206,19 +206,31 @@ fn review_html(record: &Value) -> Result<String> {
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<Value> {
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<Value> =
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))
}
+1 -2
View File
@@ -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 }))
}
+27 -3
View File
@@ -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<pdfcraft_engine::ImagePage> {
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<Value> {
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<pdfcraft_engine::CombineSource, ToolError> {
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<Value> {
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 {
+27 -1
View File
@@ -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<Value> {
// 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::<Vec<_>>(),
"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<pdfcraft_engine::OutlineTree> {
match self.session.outline_tree(id, path) {
// The engine names the path 0-based; the caller gave it 1-based.
+7 -1
View File
@@ -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 });
}
+6
View File
@@ -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::<Vec<_>>().join(", ");
let mut warnings = Vec::new();
+17 -1
View File
@@ -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<Vec<Content>> {
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<Vec<Content>> {
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)?);
+193 -9
View File
@@ -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<Vec<u8>>,
/// The serial of each mark the document has, by [`settings_digest`].
serials: std::collections::HashMap<u64, u64>,
}
/// 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::collections::hash_map::RandomState> = 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<Vec<(pdfcraft_engine::HeaderFooterMark, String)>> {
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<u64> = 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<DocId> = 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<Value> {
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::<Vec<_>>());
let mut warnings: Vec<String> = 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<Value> {
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<Value> = marks
.iter()
.map(|(m, id)| {
let mut out = json!({ "id": id, "pages": m.pages.iter().map(|p| p + 1).collect::<Vec<_>>() });
if copying {
let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"];
let text: serde_json::Map<String, Value> =
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<Value> {
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<Value> {
+13
View File
@@ -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 }),
}
}
+6
View File
@@ -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<pdfcraft_engine::ObjectClipboard>,
/// The header and footer ids handed out, by document (see `documents::HeaderFooterIds`).
header_footer_ids: HashMap<DocId, documents::HeaderFooterIds>,
/// 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,
}
}
+47 -4
View File
@@ -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<bool>,
) -> Result<Value> {
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<Value> {
let page = self.page(a)?;
let rect = self.view_rect(a, page)?.ok_or_else(|| bad("link_add needs rect"))?;
+120 -3
View File
@@ -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<spool::Printer>, printer: &str) -> Option<spool::Pri
printers.into_iter().find(|p| if printer == "default" { p.default } else { p.name == printer })
}
/// What `doc_print`'s `marks` may name.
const MARK_NAMES: &str = "marks must be a list of all, trim, bleed, registration, color_bars and page_info";
/// `doc_print`'s `marks` and `marks_weight`: the printer's marks to print around each page, or
/// `None` when none are asked for. The information line names the document (`name`) and the
/// date (`today`, year, month, day).
fn printer_marks(a: &Args, layout: &Layout, name: &str, (y, m, d): (i64, u32, u32)) -> Result<Option<PrinterMarks>> {
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<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
/// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS`
/// index and size; US Letter when none is given.
///
/// `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::<Vec<_>>().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())));
}
}
+42 -4
View File
@@ -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<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
@@ -377,8 +382,10 @@ impl Automation {
}
pub(crate) fn sign_trust(&mut self, a: &Args) -> Result<Value> {
let mut certs: Vec<Certificate> =
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<Certificate> = 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<Vec<u8>> = 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::<Result<_>>()?,
};
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::<Vec<_>>() }))
// 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::<Vec<_>>(),
"trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::<Vec<_>>(),
}))
}
}
+2 -1
View File
@@ -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");
+63 -18
View File
@@ -183,7 +183,7 @@ pub fn tools() -> Vec<ToolDef> {
)),
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<ToolDef> {
"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<ToolDef> {
"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<ToolDef> {
"Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.",
)
.with(schema(json!({ "doc": doc() }), &["doc"])),
t(
"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<ToolDef> {
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<ToolDef> {
t(
"doc_print",
"Print",
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(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 \"<w>x<h>\"; 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 \"<w>x<h>\"; 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<ToolDef> {
"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<ToolDef> {
"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<ToolDef> {
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<ToolDef> {
}),
&["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<ToolDef> {
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, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. 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, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. 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<ToolDef> {
.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<ToolDef> {
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<ToolDef> {
.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<ToolDef> {
"property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] },
"value": { "type": "string" },
}), &["doc", "object", "generation", "property"])),
t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, 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<ToolDef> {
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
.cmd("form.merge_data")
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's 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<ToolDef> {
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<ToolDef> {
"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<ToolDef> {
.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));
}
}
}
File diff suppressed because it is too large Load Diff
@@ -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);
}
+1
View File
@@ -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;
@@ -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<u8> {
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<u8> {
let contents = [page1, page2];
let mut objs: Vec<String> = 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<String>)> {
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<String> = 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);
}
+68 -2
View File
@@ -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<u8>)]) -> Result<Document, CreateError> {
from_images_with_resolution(images, ImageResolution::Embedded)
@@ -696,11 +755,17 @@ pub fn from_images(images: &[(String, Vec<u8>)]) -> Result<Document, CreateError
/// Create image pages with embedded resolution or a fixed dpi (72 gives one point per pixel).
pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: ImageResolution) -> Result<Document, CreateError> {
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<u8>)], resolution: ImageResolution, page: ImagePage) -> Result<Document, CreateError> {
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<u8>)], 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() {
+103
View File
@@ -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}");
}
+156 -3
View File
@@ -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<f64, EditError>) -> Result<Vec<(String, usize)>, 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<u8>) -> Result<DrawnItem, EditError> {
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::<Result<Vec<_>, _>>()?;
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, &paragraphs, 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 <</ActualText <FEFF{logical}>>> 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<u8>,
/// 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<u8>, Dict), EditError> {
pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<DrawnItem, EditError> {
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::<f64>()
+ 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<usize> = 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, &paragraphs, 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.
+3
View File
@@ -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<char> {
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);
+30 -20
View File
@@ -28,12 +28,14 @@ fn read_value<T>(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<Content> {
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<Content> {
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<ObjRef>) -> 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<ObjRef>) -> 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<ObjRef>) -> 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));
+3
View File
@@ -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<String>,
/// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;
/// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).
pub aligns: Vec<Option<Align>>,
@@ -229,6 +231,7 @@ impl Default for AddedText {
align: Align::Left,
aligns: Vec::new(),
char_spacing: 0.0,
font_resource: None,
}
}
}
+276 -21
View File
@@ -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<HeaderFooter> {
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<HeaderFooterMark>,
streams: std::collections::HashMap<ObjRef, Recorded>,
settings: std::collections::HashMap<ObjRef, Recorded>,
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<usize>),
}
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<HeaderFooterMark> {
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<Option<HeaderFooter>> {
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<usize> {
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<usize> {
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<usize, EditError> {
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<usize, EditError> {
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<usize, EditError> {
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<usize, EditError> {
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<usize, EditError> {
let mut left = 0;
for page in page_list(doc) {
let list = content_list(doc, &page);
let over: Vec<Object> = 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<usize>,
) -> Result<usize, EditError> {
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<Object> = 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<Object> = 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
+52 -1
View File
@@ -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<ObjRef>, on_page: Option<&HashSet<ObjRef>>) -> 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<ObjRef>, on_page: Option<&
let mut known = HashMap::new();
let survivors: Vec<Object> =
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<ObjRef> = HashSet::new();
let mut stack: Vec<ObjRef> = 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<Object> = 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)))?,
+873 -20
View File
@@ -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<Vec<u8>> {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<ObjRef>) {
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<bool, ()> {
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<ObjRef>,
aliases: &mut usize,
depth: usize,
budget: &mut ImageRewriteBudget,
) -> Result<bool, ()> {
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<bool, ()> {
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<bool, ()> {
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<ObjRef>,
aliases: &mut usize,
depth: usize,
budget: &mut ImageRewriteBudget,
) -> Result<bool, ()> {
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<usize>],
target_idx: usize,
target_unit: &'a std::ops::Range<usize>,
order: ArrangeOrder,
has_other_paint: bool,
has_paint_before: bool,
has_paint_after: bool,
) -> Result<(&'a std::ops::Range<usize>, 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<usize>) -> (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<Op> = 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));
}
}
+5 -2
View File
@@ -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)]
+156
View File
@@ -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<usize>,
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<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> Option<T>) -> Option<T> {
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<const N: usize>(doc: &Document, o: &Object) -> Option<[f64; N]> {
read(doc, o, |array| {
let items = array.as_array().filter(|a| a.len() == N)?;
let values: Vec<f64> = items.iter().map(|v| read(doc, v, Object::as_f64)).collect::<Option<_>>()?;
<[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<Self> {
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<Self> {
#[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<String> = 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<usize> = 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> {
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.
+347
View File
@@ -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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>());
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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["Panel", "Outside"]);
}
+45 -17
View File
@@ -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<u8>, 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<u8>, behind: bool) -> Result<ObjRef, EditError> {
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<u8>) -> Result<ObjRef, EditError> {
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<Object> {
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<u8>) -> 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<u8>,
) -> Result<Option<ObjRef>, 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<usize> {
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
+2101 -8
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -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<usize>,
/// The layers and graphics state parameters it is drawn in; see [`Paint`].
paint: Paint,
containers: Vec<usize>,
/// 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,
+62 -1
View File
@@ -481,6 +481,7 @@ pub(super) struct Shown {
pub(super) decodable: bool,
pub(super) scope: Option<usize>,
pub(super) paint: Paint,
pub(super) containers: Vec<usize>,
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<Option<Vec<u8>>>,
/// 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<super::containers::Containers>,
/// The operator indices of the `Do`s, from the page down, that draw these operators.
pub(super) at: Vec<usize>,
/// 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<usize, usize> = 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
}
+23 -7
View File
@@ -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<TextLine>, last: &mut Option<Pen>, 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<TextLine>, last: &mut Option<Pen>, 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<TextLine
let mut last_stream = None;
let mut forms = invoked.into_iter().peekable();
for s in shown {
while let Some((_, name, ts)) = forms.next_if(|f| f.0 < s.op) {
enter(w, resources, &name, ts, &mut carry.text_left)?;
while let Some((i, name, ts)) = forms.next_if(|f| f.0 < s.op) {
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
// Text after a form starts a new line.
last = None;
}
@@ -878,13 +883,21 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
}
add_shown(&mut w.lines, &mut last, s, si);
}
for (_, name, ts) in forms {
enter(w, resources, &name, ts, &mut carry.text_left)?;
for (i, name, ts) in forms {
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
}
Ok(())
}
/// `text_left`: the page's text budget, shared with the forms the page draws.
fn enter(w: &mut Walk, resources: &Dict, name: &[u8], ts: Ts, text_left: &mut usize) -> Result<(), EditError> {
fn enter(
w: &mut Walk,
resources: &Dict,
name: &[u8],
ts: Ts,
text_left: &mut usize,
containers: std::rc::Rc<super::containers::Containers>,
at: Vec<usize>,
) -> 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<TextLine
layers: Vec::new(),
text_left: *text_left,
gap_space: false,
containers,
at,
};
let stream = w.next_stream;
w.next_stream = w.next_stream.saturating_add(1);
@@ -927,6 +942,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let stream_of = |i: usize| ops.get(i).map_or(0, |op| pieces.pieces_of(op).0);
carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res));
walk(&mut w, &ops, &res, &mut carry, &stream_of)?;
let mut lines = w.lines;
// A visual-order Indic font draws pre-base vowel signs before their consonant.

Some files were not shown because too many files have changed in this diff Show More