mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-10-31 21:48:09 -06:00
Merge upstream main into prep/4013-merge-main
The only content conflict was crates/engine/src/lib.rs: main moved EditCtx and run_edit into edit.rs, while this branch taught Protect to draw keys and salts from getrandom and fail closed. Keep main's module split and apply that CSPRNG behaviour on EditCtx in edit.rs. The regression test imports EditCtx and run_edit from the edit module. Co-authored-by: jonathanwxh-cell <jonathanwxh-cell@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI
|
||||
# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET).
|
||||
nextest-version = "0.9.150"
|
||||
+75
-135
@@ -1,152 +1,92 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
|
||||
# suite's shared gate workflow in craft-common-actions. Nightly fuzzing is in fuzz.yml.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
# `labeled` so that adding `full-ci` to an open PR starts a run with Windows in it.
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "17 3 * * *" # nightly fuzzing
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
# The token is only used to check out the code: no job writes to the repository.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding
|
||||
# any label but `full-ci` gets a group of its own, so it neither runs the gate nor cancels a run.
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: test (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
CARGO_PROFILE_TEST_DEBUG: line-tables-only
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# No macOS on PRs, main or nightly: the org's 5 macOS slots are kept for release builds,
|
||||
# and release.yml builds macOS (a failing release is fixed and rebuilt).
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
# The shared gate doesn't check where git dependencies come from; release.yml runs the same job.
|
||||
git-sources:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
# The optional craft-fonts build input (Japanese fonts), so the Japanese font tests run on
|
||||
# Linux; Windows tests the build without it. See craftrules standards/fonts.md.
|
||||
- name: Check out craft-fonts (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
|
||||
path: craft-fonts
|
||||
|
||||
- name: Configure craft-fonts (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts" >> "$GITHUB_ENV"
|
||||
echo "CRAFT_FONTS_REQUIRED=1" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install Linux system dependencies (egui/winit/rfd) and the oracles
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \
|
||||
libgl1-mesa-dev libgtk-3-dev \
|
||||
qpdf poppler-utils
|
||||
|
||||
# The independent oracles (crates/oracle) are only worth having when they run. With this
|
||||
# set, a missing one fails the job instead of printing a skip notice that reads as a pass.
|
||||
# Only the tools the job actually uses are installed above.
|
||||
- name: Require the oracles (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: echo "PDFCRAFT_ORACLES_REQUIRED=1" >> "$GITHUB_ENV"
|
||||
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy, rustfmt
|
||||
|
||||
- name: Require Windows executable resources
|
||||
if: runner.os == 'Windows'
|
||||
run: Add-Content -Path $env:GITHUB_ENV -Value 'PDFCRAFT_REQUIRE_WINRES=1'
|
||||
persist-credentials: false
|
||||
- name: Windows font notice regressions
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-font-notices.ps1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
|
||||
- name: Format
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
- name: Test
|
||||
if: runner.os != 'Linux'
|
||||
run: cargo test --workspace
|
||||
|
||||
- name: Test (with craft-fonts)
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo test --workspace
|
||||
|
||||
- name: Layering
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo xtask layers
|
||||
|
||||
- name: Assets (licences and attribution)
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo xtask assets
|
||||
|
||||
- name: CLI without the MCP server still builds
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo check -p pdfcraft-cli --no-default-features
|
||||
|
||||
wasm:
|
||||
name: wasm32 check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: wasm32
|
||||
- name: Check library crates for wasm32
|
||||
run: cargo xtask wasm
|
||||
|
||||
deny:
|
||||
name: dependency licences and advisories
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
|
||||
with:
|
||||
command: check
|
||||
|
||||
fuzz:
|
||||
name: fuzz (mutation, 15 min)
|
||||
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: fuzz
|
||||
- name: Fetch the pdf.js corpus (seeds)
|
||||
run: cargo xtask corpus
|
||||
- name: Fuzz
|
||||
run: cargo xtask fuzz --time 900 --seed ${{ github.run_number }}
|
||||
- name: Upload findings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: fuzz-findings
|
||||
path: fuzz-out/findings
|
||||
if-no-files-found: ignore
|
||||
gate:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Windows on main, manual runs and pull requests labelled `full-ci`. No macOS on PRs or main:
|
||||
# the org's 5 macOS slots are kept for release builds, and release.yml builds macOS.
|
||||
os: ${{ (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'full-ci')) && '["ubuntu-24.04","windows-latest"]' || '["ubuntu-24.04"]' }}
|
||||
# Same craft-fonts commit as release.yml and freebsd.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# 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
|
||||
# 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
|
||||
# Windows checks what differs by platform: the build (with resources) and the tests.
|
||||
windows-command: |
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
cargo test --workspace --locked
|
||||
|
||||
@@ -26,4 +26,4 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
name: Fuzz
|
||||
|
||||
# Mutation fuzzing of open/render/edit/save (`cargo xtask fuzz`), nightly and on demand. Findings
|
||||
# are uploaded as an artifact; each real one becomes a synthetic regression test.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
# The token is only used to check out the code: no job writes to the repository.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
concurrency:
|
||||
group: fuzz-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fuzz:
|
||||
name: fuzz (mutation, 15 min)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
key: fuzz
|
||||
- name: Fetch the pdf.js corpus (seeds)
|
||||
run: cargo xtask corpus
|
||||
- name: Fuzz
|
||||
run: cargo xtask fuzz --time 900 --seed ${{ github.run_number }}
|
||||
- name: Upload findings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: fuzz-findings
|
||||
path: fuzz-out/findings
|
||||
if-no-files-found: ignore
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
with:
|
||||
app-name: pdfcraft
|
||||
app-title: PdfCraft
|
||||
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
version: ${{ inputs.version }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
|
||||
@@ -11,7 +11,8 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
|
||||
@@ -20,10 +20,10 @@ An **asset** is any non-code material that the project includes, ships, embeds,
|
||||
|
||||
- **Never** use icons, images, artwork, logos, UI graphics, fonts, stamps, cursors, sample documents or any other asset taken from an Adobe product, installer, website, document or package.
|
||||
- "Adobe product" includes Acrobat, Reader, Photoshop, Illustrator, Premiere, Lightroom and Creative Cloud, including the fonts they install (for example Minion, Myriad, Kozuka and the Adobe CJK families).
|
||||
- This holds even when Adobe publishes the material under an open licence, if it is **visual design**. For example, **do not** use Source Han, Source Serif or Source Sans, or Noto CJK, which is Source Han rebranded.
|
||||
- Typefaces released under the SIL Open Font License are allowed like any other OFL font, with an `ATTRIBUTION.toml` entry, whoever designed them: for example Noto CJK and Source Han, taken from their open-source releases. The copies an Adobe product installs stay banned.
|
||||
- **Never** recreate, trace, redraw or closely imitate an Adobe icon or graphic. Our icons come from Lucide, and our visual design is our own.
|
||||
- Screenshots of Adobe software exist only as private, local observation notes under `plan/acrobat/`, which is gitignored. They must **never** be committed, published, linked, shown in docs, used as a design source to trace, or placed anywhere else in the repository or its outputs.
|
||||
- The only Adobe-authored material allowed is **non-visual technical data** that is openly licensed and required for PDF compatibility. Each item needs its own entry in `ATTRIBUTION.toml` with `adobe_data = true`, and the list below is closed:
|
||||
- Apart from those OFL typefaces, the only Adobe-authored material allowed is **non-visual technical data** that is openly licensed and required for PDF compatibility. Each item needs its own entry in `ATTRIBUTION.toml` with `adobe_data = true`, and the list below is closed:
|
||||
- The CMap resources (BSD-3-Clause), bundled inside the `hayro-cmap` dependency.
|
||||
- The standard-14 font metrics and encoding tables in the PDF specification. They are data, not typefaces. They are embedded as code in hayro, and as our own generated table in `crates/fonts/src/std14_metrics.rs` (approved by the owner, 2026-10-08; that file holds the data alone, so the code reading it can change without re-attesting the table), which is what generated appearances measure with and what survives hayro being retired.
|
||||
|
||||
@@ -54,16 +54,17 @@ Anything else is forbidden, including assets whose licence you cannot prove from
|
||||
- path or URL, title, author;
|
||||
- source (URL, with version or commit);
|
||||
- SPDX licence, and the licence file in the repo;
|
||||
- SHA-256;
|
||||
- SHA-256, except for translation catalogs (see below);
|
||||
- how it is used.
|
||||
- **Translation catalogs** (`crates/ui-egui/src/i18n/*.tsv`, `kind = "translation"`) are project files under the project licence. Their entries carry no `sha256`: git history records every change and who made it. Every other kind (fonts, images, data) is hashed.
|
||||
- **`ATTRIBUTION.md`** is generated from it (`cargo xtask assets --write`). Never edit it by hand.
|
||||
- **`NOTICE`** keeps the licence notices that the licences require.
|
||||
- **`cargo xtask assets`** runs in `cargo xtask ci`. It fails if:
|
||||
- an asset file in the repository has no entry;
|
||||
- an entry's hash does not match;
|
||||
- an entry's hash is missing or does not match (translation catalogs carry none);
|
||||
- a licence is not on the allowlist;
|
||||
- a licence file is missing;
|
||||
- an image, icon or font names Adobe as author or source.
|
||||
- an image, icon or font names Adobe as author or source, except a font licensed under OFL-1.1 alone.
|
||||
- **`cargo xtask demo-pdf`** downloads its fonts only from `ATTRIBUTION.toml` entries, pinned by SHA-256. Afterwards it **fails if the PDF embeds any font not in its allowlist**, which catches the browser silently falling back to a system font.
|
||||
|
||||
### 1.4 Fonts live in craft-fonts
|
||||
|
||||
+46
-44
@@ -2,39 +2,40 @@
|
||||
|
||||
<!-- Generated from ATTRIBUTION.toml by `cargo xtask assets --write`. Do not edit by hand. -->
|
||||
|
||||
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
|
||||
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset but the translation catalogs, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
|
||||
|
||||
## In this repository (288)
|
||||
## In this repository (289)
|
||||
|
||||
| Asset | Title | Author | Licence | Source | Used for |
|
||||
|---|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/fa.tsv` | Persian (Farsi) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-25 initial catalog covering the current 2,776-entry key union, AI-assisted translations from English, not separately native-reviewed | Persian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/accessibility.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/align-left.svg` | Lucide icon "align-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/align-center.svg` | Lucide icon "align-center" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-center.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
@@ -275,36 +276,37 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/forms.rs, commands.rs) |
|
||||
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs) |
|
||||
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `crates/sign/tests/data/openssl-signed.pdf` | One-page PDF signed with OpenSSL CMS (adbe.pkcs7.detached) by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl cms -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/pdf.rs): a signature PdfCraft did not make |
|
||||
| `crates/sign/tests/data/openssl-signed.pdf` | One-page PDF signed with OpenSSL CMS (adbe.pkcs7.detached) by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl cms -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/it/pdf.rs): a signature PdfCraft did not make |
|
||||
| `assets/icons/clipboard-paste.svg` | Lucide icon "clipboard-paste" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clipboard-paste.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/fonts/DancingScript.ttf` | Dancing Script (variable) | The Dancing Script Project Authors (Pablo Impallari) | OFL-1.1 | https://github.com/google/fonts/blob/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/dancingscript/DancingScript%5Bwght%5D.ttf | Fill & Sign typed signatures and initials: the typed name's glyph outlines, drawn as filled paths (the font file itself is not embedded in PDFs) |
|
||||
| `packaging/macos/dmg/background.svg` | PdfCraft macOS DMG window background | @XusBadia | MIT OR Apache-2.0 | Original work for this repository, derived from the PdfCraft app icon (assets/app-icon/pdfcraft.svg, referenced via an SVG image element, not copied) | Finder window of the macOS DMG; rendered to background.tiff by packaging/macos/dmg/generate.py |
|
||||
| `packaging/macos/dmg/background.tiff` | PdfCraft macOS DMG window background (rendered) | @XusBadia | MIT OR Apache-2.0 | Rendered from packaging/macos/dmg/background.svg by packaging/macos/dmg/generate.py | 1x + 2x HiDPI 16-colour palette TIFF copied into the macOS DMG by packaging/macos/package.sh; includes the app icon and the free LittleCMS built-in sRGB profile |
|
||||
| `crates/sign/tests/data/x509-rsa-sha1.pdf` | One-page PDF with a legacy adbe.x509.rsa_sha1 signature by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl dgst -sha1 -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/pdf.rs): the legacy adbe.x509.rsa_sha1 format |
|
||||
| `crates/sign/tests/data/x509-rsa-sha1.pdf` | One-page PDF with a legacy adbe.x509.rsa_sha1 signature by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl dgst -sha1 -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/it/pdf.rs): the legacy adbe.x509.rsa_sha1 format |
|
||||
| `assets/icons/monitor.svg` | Lucide icon "monitor" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/monitor.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `vendor/vello_common/assets/probe.png` | vello_common probe reference image (rendered from probe.rgba) | Linebender vello contributors | MIT OR Apache-2.0 | vello_common 0.0.8 (crates.io), vendored in vendor/vello_common; regenerated by its vello_sparse_tests regenerate_probe_reference binary | Reference picture of the vendored vello_common probe module, for people only; the build reads probe.rgba, not this file |
|
||||
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `assets/icons/superscript.svg` | Lucide icon "superscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/superscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/subscript.svg` | Lucide icon "subscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/subscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
|
||||
|
||||
## Compiled in through dependencies (5)
|
||||
## Compiled in through dependencies (6)
|
||||
|
||||
| Crate | File | Title | Author | Licence | Source | Used for |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `epaint_default_fonts` 0.36.2 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.36.2 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.36.2 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.36.2 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.37.0 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.37.0 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) |
|
||||
| `epaint_default_fonts` 0.37.0 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui monochrome fallback font (egui feature monochrome_emoji_fonts) |
|
||||
| `epaint_default_fonts` 0.37.0 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui monochrome fallback font (egui feature monochrome_emoji_fonts) |
|
||||
| `epaint_default_fonts` 0.37.0 | `fonts/egui-icons.ttf` | egui icons (monochrome emoji-icon-font subset) | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | Small special-icon subset embedded by egui default_fonts; retained in FontDefinitions::default(). Provenance: https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; complete MIT copyright and permission text in NOTICE. |
|
||||
| `hayro-interpret` 0.7.0 | `src/font/generated/metrics.rs` | Standard-14 font metrics and encodings (as Rust tables) (non-visual data, AGENTS.md §1.1) | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | MIT OR Apache-2.0 | ISO 32000-2 Annex D; Adobe Core14 AFM files (via vendored hayro-interpret) | Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1 |
|
||||
|
||||
## Downloaded at build time (22)
|
||||
@@ -342,4 +344,4 @@ Not in this repository and never downloaded by it: compiled in only when the bui
|
||||
|
||||
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs never embeds (AGENTS.md §1.1) |
|
||||
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
|
||||
|
||||
+70
-79
@@ -2,17 +2,18 @@
|
||||
path = "crates/ui-egui/src/i18n/el.tsv"
|
||||
title = "Greek interface translation catalog"
|
||||
author = "Camthalion77 and contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "1902f1c31698e6adfdaf65b35b1fe1628f5cd2bd0182dd3b99bcf5e21720f394"
|
||||
|
||||
# ATTRIBUTION.toml: one entry per asset (AGENTS.md §1). The source of truth for provenance and licences.
|
||||
# ATTRIBUTION.md is generated from this file: `cargo xtask assets --write`. Checked by `cargo xtask assets` (part of `xtask ci`).
|
||||
#
|
||||
# [[asset]] a file in this repository (committed or vendored); `sha256` must match the file.
|
||||
# Translation catalogs (kind = "translation", crates/ui-egui/src/i18n/*.tsv) are project files
|
||||
# under the project licence and carry no `sha256`: git history records their provenance.
|
||||
# [[bundled]] a file compiled into PdfCraft by a Cargo dependency (its crate version must match Cargo.lock).
|
||||
# [[fetched]] downloaded at build time by xtask (never committed), pinned by `sha256`.
|
||||
# [[build_input]] an optional build input outside this repository (e.g. craft-fonts via CRAFT_FONTS_DIR);
|
||||
@@ -25,286 +26,270 @@ sha256 = "1902f1c31698e6adfdaf65b35b1fe1628f5cd2bd0182dd3b99bcf5e21720f394"
|
||||
path = "crates/ui-egui/src/i18n/zh-hans.tsv"
|
||||
title = "Simplified Chinese interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "2e23c41fcd5b9118cfde03b3a45aa2f988f7eeba650677b6f1f6664e543c7a59"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/zh-hant.tsv"
|
||||
title = "Traditional Chinese (Taiwan) interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "105703f2fbc07c0663308ebd6852199de12a5851a37507d7e51e477eb5e57218"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/cs.tsv"
|
||||
title = "Czech interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "7358300715a54e72a477c5888dad53f426ddf76da141a6202bec74594eb5ff0a"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/pt-br.tsv"
|
||||
title = "Brazilian Portuguese interface translation catalog"
|
||||
author = "André Cardoso (andrecards), PdfCraft contributors"
|
||||
source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "265083ea7dfa129fcae0b9e401aef8f7c84982011ba91fb2023c52705b81e639"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/es.tsv"
|
||||
title = "Spanish interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "ffcf42859cfe38ae13c6fe4219cbe6225a20b4572c202db9e82ee38bfb433799"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/fr.tsv"
|
||||
title = "French interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "3f31e5c9abdb0208d48d8c68aa81437d9d1e10aeb615dedf811fefa539d93279"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/de.tsv"
|
||||
title = "German interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "815a3a672421cc3590fb1f267755316659cdb2046e30bbb3ad8b31e96f08b20a"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/lo.tsv"
|
||||
title = "Lao interface translation catalog"
|
||||
author = "@bounkirdni-2025"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "6bd67286795ed487eedf2ce549249c8a83286cb4273490c1349996050b540fed"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/te.tsv"
|
||||
title = "Telugu interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "9cd63425705fb9a3aa029ff3a5110d0877a34f9038f1d64a2102ccd6c3cb35a6"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/it.tsv"
|
||||
title = "Italian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "76f138293fc12ea3584568a81f6f90a1cedfff6256e78b4f60cb21b1b66bbba4"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/pl.tsv"
|
||||
title = "Polish interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "7bca90240f873fcec687bea84e9ea5835f0903827501d0e73ec26b98b82e8a52"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ru.tsv"
|
||||
title = "Russian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "3d539a28afcf8c2e36b7087ac23334b50bac7971e03da20a62b6e7e400763a87"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/hu.tsv"
|
||||
title = "Hungarian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "71b7e8180fc759aebad4660953ab8b55383def0572c1ace2288cd8bfeb1b82dc"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/bg.tsv"
|
||||
title = "Bulgarian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "e689fb24a8acfa7e85f0f60644f7e2da1225595e6cd6a94109fbe86082926244"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/kk.tsv"
|
||||
title = "Kazakh interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "c601ea117ec2a3cdba606fdc9a62220fcffbd0c20c1133bacb653a979cf046a5"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ja.tsv"
|
||||
title = "Japanese interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "006867b891ae2f995c7a711e55b6401db29d20ab493889c6284dc3671f9faa2d"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/uk.tsv"
|
||||
title = "Ukrainian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "9e5b18a09c209525cf08ef53a242ed457cfa346295eef7facde482a75cf72f52"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ar.tsv"
|
||||
title = "Arabic interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "2306dbbe6a73671fd20df116adb159a7f66c85fbbd1bae5ecef5f6e882d6b7f1"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ckb.tsv"
|
||||
title = "Central Kurdish (Sorani) interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "864db8aa0a5e443c92e7e388f89349eb0f0e7beda35a0b81695d864dcec51b72"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/fa.tsv"
|
||||
title = "Persian (Farsi) interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-25 initial catalog covering the current 2,776-entry key union, AI-assisted translations from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Persian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/tr.tsv"
|
||||
title = "Turkish interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "463a2d28bd5c5ac8df31a5b5c68400d7a61ce51237a58d9337078c973e6f9e3d"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/lt.tsv"
|
||||
title = "Lithuanian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "dea5076ce9c19f054812b678241931ad5e7f85dee08acf1c1e12c7ecaaa5d0f5"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/hi.tsv"
|
||||
title = "Hindi interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "09d2840c02b40a6049b86c2cb68151d863913e8c91c22226f25d07496c6366aa"
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/id.tsv"
|
||||
title = "Indonesian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "0dc1abdb262e4568f19ffb2233bfeb3686ae42df8a8d8bec2951351a50e6a886"
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ko.tsv"
|
||||
title = "Korean interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "a3e67cee4f3fff776e816523f810b2bb6353235dbdf85181c3f12896604a3339"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ro.tsv"
|
||||
title = "Romanian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "18d4beda8495d7f0b91f0dc0a52c2248d9ce6fb3f4e3de0d51f42235eaab7aa8"
|
||||
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/fi.tsv"
|
||||
title = "Finnish interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "7b13e11191a3f2c0e38f1940996ae62da16e3bdb057215b2737f3a9c6a840000"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/icons/accessibility.svg"
|
||||
@@ -2454,7 +2439,7 @@ sha256 = "f225e0b044875b8fa6375b6b5ad935f0d99fcc1ad03ecf9f0baae2cedbfca4d2"
|
||||
|
||||
[[bundled]]
|
||||
crate = "epaint_default_fonts"
|
||||
version = "0.36.2"
|
||||
version = "0.37.0"
|
||||
path = "fonts/Ubuntu-Light.ttf"
|
||||
title = "Ubuntu Light"
|
||||
author = "Canonical Ltd. / Dalton Maag"
|
||||
@@ -2466,7 +2451,7 @@ sha256 = "80307b8da7649aa4ee4d484b232140e3ce1ec0ca093073d3c53c8f5a5ced7a70"
|
||||
|
||||
[[bundled]]
|
||||
crate = "epaint_default_fonts"
|
||||
version = "0.36.2"
|
||||
version = "0.37.0"
|
||||
path = "fonts/Hack-Regular.ttf"
|
||||
title = "Hack Regular"
|
||||
author = "Source Foundry Authors (derived from Bitstream Vera / DejaVu)"
|
||||
@@ -2478,28 +2463,40 @@ sha256 = "15f55cc0c85a2988d2b4b3a8cdb5d77fdfbaf319e1bb5309d725db9818fb7125"
|
||||
|
||||
[[bundled]]
|
||||
crate = "epaint_default_fonts"
|
||||
version = "0.36.2"
|
||||
version = "0.37.0"
|
||||
path = "fonts/NotoEmoji-Regular.ttf"
|
||||
title = "Noto Emoji (monochrome)"
|
||||
author = "Google Inc."
|
||||
source = "https://github.com/googlefonts/noto-emoji"
|
||||
licence = "OFL-1.1"
|
||||
kind = "font"
|
||||
usage = "egui fallback fonts (eframe feature default_fonts)"
|
||||
usage = "egui monochrome fallback font (egui feature monochrome_emoji_fonts)"
|
||||
sha256 = "415dc6290378574135b64c808dc640c1df7531973290c4970c51fdeb849cb0c5"
|
||||
|
||||
[[bundled]]
|
||||
crate = "epaint_default_fonts"
|
||||
version = "0.36.2"
|
||||
version = "0.37.0"
|
||||
path = "fonts/emoji-icon-font.ttf"
|
||||
title = "emoji-icon-font"
|
||||
author = "John Slegers"
|
||||
source = "https://github.com/jslegers/emoji-icon-font"
|
||||
licence = "MIT"
|
||||
kind = "font"
|
||||
usage = "egui fallback fonts (eframe feature default_fonts)"
|
||||
usage = "egui monochrome fallback font (egui feature monochrome_emoji_fonts)"
|
||||
sha256 = "f426bec371f484646d002717e2c555a95cd5145e635d83a48bbef83f3abf18ca"
|
||||
|
||||
[[bundled]]
|
||||
crate = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
path = "fonts/egui-icons.ttf"
|
||||
title = "egui icons (monochrome emoji-icon-font subset)"
|
||||
author = "John Slegers"
|
||||
source = "https://github.com/jslegers/emoji-icon-font"
|
||||
licence = "MIT"
|
||||
kind = "font"
|
||||
usage = "Small special-icon subset embedded by egui default_fonts; retained in FontDefinitions::default(). Provenance: https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; complete MIT copyright and permission text in NOTICE."
|
||||
sha256 = "122806555c73df7cef55aa1d945289ae27fbc4dbbd31abbb4204ee0cda829cc8"
|
||||
|
||||
[[asset]]
|
||||
path = "vendor/hayro-cmap/assets/cmaps.brotli"
|
||||
title = "Adobe CMap resources (predefined CJK CMaps)"
|
||||
@@ -3277,7 +3274,7 @@ source = "Contributor-original: hand-written PDF objects, no third-party content
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "document"
|
||||
usage = "Form-filling UI tests (crates/ui-egui/tests/forms.rs, commands.rs)"
|
||||
usage = "Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs)"
|
||||
sha256 = "c6f8b656e225101129aa36bd5467adc8dba16730915f19caca17f6a546d0b040"
|
||||
|
||||
[[asset]]
|
||||
@@ -3310,7 +3307,7 @@ source = "Contributor-original: hand-written PDF objects; signature made with `o
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "document"
|
||||
usage = "Signature validation tests (crates/sign/tests/pdf.rs): a signature PdfCraft did not make"
|
||||
usage = "Signature validation tests (crates/sign/tests/it/pdf.rs): a signature PdfCraft did not make"
|
||||
sha256 = "8b91c3b4e39c4a31717a0dd0685bd7d0468671df32aee5b9818d44dc72c2bc3c"
|
||||
|
||||
[[asset]]
|
||||
@@ -3387,13 +3384,13 @@ sha256 = "e484866d4cce403175bd8d00b128feb08ab42e208de30e42cd9889d8f1735a6e"
|
||||
[[build_input]]
|
||||
name = "craft-fonts"
|
||||
option = "CRAFT_FONTS_DIR"
|
||||
title = "Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic"
|
||||
author = "The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic)"
|
||||
source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml)"
|
||||
title = "Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic"
|
||||
author = "The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic)"
|
||||
source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9)"
|
||||
licence = "OFL-1.1"
|
||||
attribution = "https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md"
|
||||
kind = "font"
|
||||
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs never embeds (AGENTS.md §1.1)"
|
||||
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
|
||||
@@ -3403,7 +3400,7 @@ source = "Contributor-original: hand-written PDF objects; signature made with `o
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "document"
|
||||
usage = "Signature validation tests (crates/sign/tests/pdf.rs): the legacy adbe.x509.rsa_sha1 format"
|
||||
usage = "Signature validation tests (crates/sign/tests/it/pdf.rs): the legacy adbe.x509.rsa_sha1 format"
|
||||
sha256 = "b77bfb21166f4bd043597e45a1ea28b9d9f4ba6df0142b3a0fc8b7f8e0fc111b"
|
||||
|
||||
[[asset]]
|
||||
@@ -3421,23 +3418,21 @@ sha256 = "d1a443233345724859de8e4fb48968ba91e885e12ddbd710701548bd91b39428"
|
||||
path = "crates/ui-egui/src/i18n/vi.tsv"
|
||||
title = "Vietnamese interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "1c73f9d51b599923d704bf00c8e56b23696de16141b7a2c20aae6f60f88927a5"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/sl.tsv"
|
||||
title = "Slovene interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "a3b8351f0da80c2d394221dbe5d62e794bb019c74c2adfc5d933d999f7d3236f"
|
||||
|
||||
[[asset]]
|
||||
|
||||
@@ -3455,12 +3450,11 @@ sha256 = "78c59a0cfd2c829909d77006f94e34dac1ae5d1f90e7f10f72e84de541fef697"
|
||||
path = "crates/ui-egui/src/i18n/nb.tsv"
|
||||
title = "Norwegian Bokmål interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "03477c4ab2d0d52543cb91b3aec6f27b2689e6b9bb7c95bbb8463664c75a9dc0"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/icons/superscript.svg"
|
||||
@@ -3510,31 +3504,28 @@ sha256 = "864ab2f19254e6ac7240bc6a98323197332e8f714d4d3f94831f41309e5ef2f7"
|
||||
path = "crates/ui-egui/src/i18n/sq.tsv"
|
||||
title = "Albanian interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "ebd177262d8fe20f960f06df084f8a03c9504bcd9990dded3a006e35bd8ef7c9"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/th.tsv"
|
||||
title = "Thai interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "1dbb66c05af0aec06d5a6fa154e89f1684203dde32c8e8aedd9aeec6c2d5ae02"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/ui-egui/src/i18n/ca.tsv"
|
||||
title = "Catalan interface translation catalog"
|
||||
author = "PdfCraft contributors"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
|
||||
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
|
||||
licence = "MIT OR Apache-2.0"
|
||||
licence_file = "LICENSE-MIT"
|
||||
kind = "translation"
|
||||
usage = "Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
|
||||
sha256 = "cde106ae68eea0a2d6229863ea21bbea235e4c3c5e3e728d52689d54041f0593"
|
||||
|
||||
@@ -21,6 +21,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
|
||||
- See `plan/README.md` §Clean-room and `plan/adr/0001`.
|
||||
- **Privacy.** When observing Acrobat, use synthetic fixtures only. Never capture the Home view, recent files or account info. Capture by window id (`plan/acrobat/tools/`). Never commit Acrobat outputs, corpus files or personal data.
|
||||
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd (`plan/architecture.md` §3). `cos`/`filters`/`crypt`/`arlington` stay standalone.
|
||||
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state (`hover_pos`, `interact_pos`, `latest_pos`, `press_origin`, button reads); `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.
|
||||
- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.
|
||||
- **Never panic.** Every PDF, script, MCP call, settings file and keystroke is untrusted input, and none of it may crash the app or lose the user's work. This outranks feature work. Return `Result` (the crate's error enum) and propagate with `?`, or fall back leniently and record it. In non-test code:
|
||||
- No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` unless it is provably infallible, with a comment saying why.
|
||||
|
||||
Generated
+519
-349
File diff suppressed because it is too large
Load Diff
+74
-49
@@ -5,7 +5,7 @@ exclude = ["vendor"]
|
||||
default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.11.0"
|
||||
version = "0.14.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -13,47 +13,51 @@ repository = "https://github.com/storytold/pdfcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared frontend components; engines remain independent of egui.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", features = ["serde"] }
|
||||
# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f58bc1a3df490992d633393d0898af0588ce882c" }
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }
|
||||
# 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 = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", default-features = false }
|
||||
# Shared system spooler; document composition remains in pdfcraft-print.
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "666c358065261a2816b376fa3bb10538dbf53040" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "42e30cd5b3f4b114270dd053fccbc33bedc47f68" }
|
||||
# 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 = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["egui"] }
|
||||
# internal
|
||||
pdfcraft-geom = { path = "crates/geom", version = "0.11.0" }
|
||||
pdfcraft-filters = { path = "crates/filters", version = "0.11.0" }
|
||||
pdfcraft-cos = { path = "crates/cos", version = "0.11.0" }
|
||||
pdfcraft-crypt = { path = "crates/crypt", version = "0.11.0" }
|
||||
pdfcraft-organize = { path = "crates/organize", version = "0.11.0" }
|
||||
pdfcraft-measure = { path = "crates/measure", version = "0.11.0" }
|
||||
pdfcraft-annot = { path = "crates/annot", version = "0.11.0" }
|
||||
pdfcraft-audit = { path = "crates/audit", version = "0.11.0" }
|
||||
pdfcraft-fonts = { path = "crates/fonts", version = "0.11.0" }
|
||||
pdfcraft-model = { path = "crates/model", version = "0.11.0" }
|
||||
pdfcraft-content = { path = "crates/content", version = "0.11.0" }
|
||||
pdfcraft-redact = { path = "crates/redact", version = "0.11.0" }
|
||||
pdfcraft-print = { path = "crates/print", version = "0.11.0" }
|
||||
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.11.0" }
|
||||
pdfcraft-sign = { path = "crates/sign", version = "0.11.0" }
|
||||
pdfcraft-optimize = { path = "crates/optimize", version = "0.11.0" }
|
||||
pdfcraft-a11y = { path = "crates/a11y", version = "0.11.0" }
|
||||
pdfcraft-oracle = { path = "crates/oracle", version = "0.11.0" }
|
||||
pdfcraft-testkit = { path = "crates/testkit", version = "0.11.0" }
|
||||
pdfcraft-ocr = { path = "crates/ocr", version = "0.11.0" }
|
||||
pdfcraft-js = { path = "crates/js", version = "0.11.0" }
|
||||
pdfcraft-compare = { path = "crates/compare", version = "0.11.0" }
|
||||
pdfcraft-preflight = { path = "crates/preflight", version = "0.11.0" }
|
||||
pdfcraft-export = { path = "crates/export", version = "0.11.0" }
|
||||
pdfcraft-edit = { path = "crates/edit", version = "0.11.0" }
|
||||
pdfcraft-create = { path = "crates/create", version = "0.11.0" }
|
||||
pdfcraft-forms = { path = "crates/forms", version = "0.11.0" }
|
||||
pdfcraft-xfa = { path = "crates/xfa", version = "0.11.0" }
|
||||
pdfcraft-render = { path = "crates/render", version = "0.11.0" }
|
||||
pdfcraft-engine = { path = "crates/engine", version = "0.11.0" }
|
||||
pdfcraft-platform = { path = "crates/platform", version = "0.11.0" }
|
||||
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.11.0" }
|
||||
pdfcraft-automation = { path = "crates/automation", version = "0.11.0", default-features = false }
|
||||
pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }
|
||||
pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }
|
||||
pdfcraft-cos = { path = "crates/cos", version = "0.14.0" }
|
||||
pdfcraft-crypt = { path = "crates/crypt", version = "0.14.0" }
|
||||
pdfcraft-organize = { path = "crates/organize", version = "0.14.0" }
|
||||
pdfcraft-measure = { path = "crates/measure", version = "0.14.0" }
|
||||
pdfcraft-annot = { path = "crates/annot", version = "0.14.0" }
|
||||
pdfcraft-audit = { path = "crates/audit", version = "0.14.0" }
|
||||
pdfcraft-fonts = { path = "crates/fonts", version = "0.14.0" }
|
||||
pdfcraft-model = { path = "crates/model", version = "0.14.0" }
|
||||
pdfcraft-content = { path = "crates/content", version = "0.14.0" }
|
||||
pdfcraft-redact = { path = "crates/redact", version = "0.14.0" }
|
||||
pdfcraft-print = { path = "crates/print", version = "0.14.0" }
|
||||
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.14.0" }
|
||||
pdfcraft-sign = { path = "crates/sign", version = "0.14.0" }
|
||||
pdfcraft-optimize = { path = "crates/optimize", version = "0.14.0" }
|
||||
pdfcraft-a11y = { path = "crates/a11y", version = "0.14.0" }
|
||||
pdfcraft-oracle = { path = "crates/oracle", version = "0.14.0" }
|
||||
pdfcraft-testkit = { path = "crates/testkit", version = "0.14.0" }
|
||||
pdfcraft-ocr = { path = "crates/ocr", version = "0.14.0" }
|
||||
pdfcraft-js = { path = "crates/js", version = "0.14.0" }
|
||||
pdfcraft-compare = { path = "crates/compare", version = "0.14.0" }
|
||||
pdfcraft-preflight = { path = "crates/preflight", version = "0.14.0" }
|
||||
pdfcraft-export = { path = "crates/export", version = "0.14.0" }
|
||||
pdfcraft-edit = { path = "crates/edit", version = "0.14.0" }
|
||||
pdfcraft-create = { path = "crates/create", version = "0.14.0" }
|
||||
pdfcraft-forms = { path = "crates/forms", version = "0.14.0" }
|
||||
pdfcraft-xfa = { path = "crates/xfa", version = "0.14.0" }
|
||||
pdfcraft-render = { path = "crates/render", version = "0.14.0" }
|
||||
pdfcraft-engine = { path = "crates/engine", version = "0.14.0" }
|
||||
pdfcraft-platform = { path = "crates/platform", version = "0.14.0" }
|
||||
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.14.0" }
|
||||
pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-features = false }
|
||||
|
||||
# pdf
|
||||
hayro = "0.7.1"
|
||||
@@ -75,11 +79,13 @@ chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
proptest = "1"
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
egui_kittest = "0.36"
|
||||
egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
# Monotonic time for logic-only work on native and web (`App::logic` runs without a UI pass).
|
||||
web-time = "1.1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -89,20 +95,20 @@ dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
|
||||
# `"*"` matches every non-workspace package: crates.io dependencies and the
|
||||
# vendored crates under `vendor/` (excluded from the workspace). Our own crates
|
||||
# keep full debug info. Dependencies keep only line tables, so backtraces still
|
||||
# show file and line, but debug info for the whole dependency graph stays out of
|
||||
# every test binary (each UI test binary had a 500-600 MB PDB on Windows, #454).
|
||||
# vendored crates under `vendor/` (excluded from the workspace). Dependencies
|
||||
# carry no debug info and our own crates only line tables: backtraces and
|
||||
# panics still show file and line, while test binaries and the target dir stay
|
||||
# small (each UI test binary had a 500-600 MB PDB on Windows, #454).
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
debug = "line-tables-only"
|
||||
debug = false
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.low-disk]
|
||||
inherits = "dev"
|
||||
debug = "line-tables-only"
|
||||
incremental = false
|
||||
|
||||
[profile.release]
|
||||
@@ -115,8 +121,27 @@ hayro-interpret = { path = "vendor/hayro-interpret" }
|
||||
hayro = { path = "vendor/hayro" }
|
||||
hayro-syntax = { path = "vendor/hayro-syntax" }
|
||||
hayro-cmap = { path = "vendor/hayro-cmap" }
|
||||
hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
lopdf = { path = "vendor/lopdf" }
|
||||
winit = { path = "vendor/winit" }
|
||||
egui-wgpu = { path = "vendor/egui-wgpu" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
# The egui and winit crates below are pinned to immutable storytold git revisions (egui
|
||||
# 6d518fc799681571963842f95b55a6b68431b15a, winit a517b3846ee8457d84ee4975110bfda6797c44dc).
|
||||
# Only the retained `vendor/winit` and `vendor/egui-wgpu` copies are provenance for the app's
|
||||
# earlier patches and their source guards, not path patches; the other `vendor/` entries above
|
||||
# remain real path patches. See vendor/README.md and the migration plan.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -58,3 +58,21 @@ dependencies change (plan/adr/0002, 0006).
|
||||
Vendored (vendor/, patched; see vendor/README.md):
|
||||
- hayro 0.7.1 — Apache-2.0 OR MIT, Copyright the hayro authors (licence files kept in vendor/hayro).
|
||||
- hayro-interpret 0.7.0 — Apache-2.0 OR MIT, Copyright the hayro authors (LICENSE-APACHE, LICENSE-MIT kept in vendor/hayro-interpret).
|
||||
|
||||
Bundled egui font icons
|
||||
|
||||
The pinned egui dependency includes egui-icons.ttf, a small subset of John Slegers'
|
||||
emoji-icon-font, through default_fonts. The parent emoji-icon-font.ttf face is
|
||||
included through monochrome_emoji_fonts. Their upstream project is
|
||||
https://github.com/jslegers/emoji-icon-font; both use the same exact copyright
|
||||
and permission notice below.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png" width="128" height="128" alt="PdfCraft icon: an engraved lion on a teal tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">PdfCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
@@ -328,15 +332,13 @@ pdfcraft-cli ui --control ~/.pdfcraft-control.json inspect focused=true
|
||||
pdfcraft-cli ui --control ~/.pdfcraft-control.json quit
|
||||
```
|
||||
|
||||
`ui.dock` arranges the `tools` and `inspector` panels; `canvas` is the protected document view.
|
||||
Each per-panel request requires a `panel` ID and an `operation`: `open`, `close`,
|
||||
`activate`, `float` with `rect: [x, y, width, height]`, or `move` with `target` and
|
||||
`zone: center|left|right|top|bottom`. For example,
|
||||
`{"operation":"float","panel":"tools","rect":[100,100,320,440]}` floats Tools.
|
||||
`ui.dock.reset` restores the default
|
||||
arrangement. The control channel accepts these methods directly; `ui.command` also accepts
|
||||
`{"id":"ui.dock","params":{...}}`. Saved preferences retain groups, active tabs, visibility
|
||||
and floating geometry. Invalid requests return an error without changing the document or layout.
|
||||
`ui.panel` opens, closes or sizes a side panel: `{"panel":"tools"|"side","open":true|false,"width":320}`.
|
||||
`tools` is the Tools panel and `side` the panel the rail opens (reopening it shows the one open last).
|
||||
`width` is clamped to the panel's limits (Tools 240–520, side panel 260–520 points). `ui.dock.reset`
|
||||
resets the side panels: Tools open on the left, default widths. The control channel accepts these
|
||||
methods directly; `ui.command` also accepts `{"id":"ui.panel","params":{...}}`. Saved preferences keep
|
||||
the Tools side, the open panels and their widths. Invalid requests return an error without changing
|
||||
the document or the panels.
|
||||
|
||||
|
||||
`resize` requests a native inner-window size in logical points (each dimension must be between 320 and 8192); the window manager may constrain it. `state` reports the observed `window.width`, `window.height` and `window.pixels_per_point`. `focus` accepts exactly one widget `id` or unique enabled, focusable `label`; subsequent `key` requests traverse or activate the actual widgets. `inspect` includes focusability and accepts a `focused` filter. `quit` takes no parameters: clean documents exit normally, while unsaved edits or typing open the existing Save/Don't save/Cancel prompt and return `quitting: false, needs_confirmation: true`. It never silently discards work. Window resizing and application quit are native-only.
|
||||
@@ -591,13 +593,4 @@ Forks and modified versions must remove them.
|
||||
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
|
||||
</p>
|
||||
|
||||
Tools and Inspector panels can be dragged into tab groups, split beside the PDF, or floated within the app window. Read and full-screen modes keep their existing focused document view. Drag a panel header to a target edge or another header. Its context menu offers Float panel, Move to group, and Close panel. Existing panel toggles reopen panels at their saved location; Reset Panel Layout restores the app layout. Floating panels remain inside the current app window.
|
||||
|
||||
Advanced `ui.dock` operations use the same validated transaction as pointer gestures:
|
||||
`moveFloating` updates `rect`, `resizeSplit` accepts a boolean child `path` and
|
||||
`size` (`{"Ratio":0.5}`, `{"FixedFirst":280}`, or `{"FixedSecond":280}`),
|
||||
`setStackOpen` takes `open`, and `resizeStack` takes a point `height` or null.
|
||||
A center `move` can include `before` (panel ID or null to append) for tab order.
|
||||
The equivalent `{"action": ...}` form accepts a serialized shared docking action;
|
||||
this is also the form emitted by the renderer. Protected-canvas and app-specific panel
|
||||
rules apply equally to both forms.
|
||||
The Tools panel sits on the left, or on the right with Preferences ▸ Tools panel side. The rail stays at the right edge and opens one side panel beside it. Drag a panel's inner edge to resize it; widths are remembered. F4 shows or hides the side panel and Shift+F4 the Tools panel (also in the View menu); View ▸ Reset side panels restores the default arrangement.
|
||||
|
||||
+64
-3
@@ -2,6 +2,13 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: Word table cells use the widths of their own grid columns; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: table spans retain text from covered slots in Office exports; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: image export preserves soft-mask Decode opacity ranges; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: vector printing preserves existing page XObjects when adding annotation appearances; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-21 · **Last updated:** 2026-10-21 · **Change:** minor (M3, #3808: the Pages inspector has an independent 50–150% thumbnail size slider and buttons; selection and current-page following are retained, with headless ui.set coverage. Estimates unchanged.)
|
||||
> **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M11 #3507: image merging preserves content stream boundaries; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M10, #3532 partial: vector printing retains existing appearances with absent Subtype; estimates unchanged)
|
||||
@@ -53,6 +60,8 @@
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (architectural paper controls from #599; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (closed issues synced: #774, #756 and the #799–#821 batch; earlier: localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M6 #2892: Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M7 #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M7 #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Estimates unchanged)
|
||||
@@ -156,10 +165,10 @@ Portuguese and Spanish vs the current union). Detail and script notes: [localiza
|
||||
| Language | Code | Strings | Status |
|
||||
|---|---|---|---|
|
||||
| English | `en` | 100% | full |
|
||||
| Simplified Chinese | `zh-hans` | 97.4% | partial (no Hans UI face in releases, #826) |
|
||||
| Simplified Chinese | `zh-hans` | 97.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
|
||||
| Spanish | `es` | 100% of current union | partial (dialogs / tooltips; no help) |
|
||||
| Hindi | `hi` | 0% | none |
|
||||
| Arabic | `ar` | 100% | partial (layout not mirrored) |
|
||||
| Arabic | `ar` | 100% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
|
||||
| French | `fr` | 99.3% | partial |
|
||||
| Portuguese (Brazil) | `pt-br` | 100% of current union | partial |
|
||||
| Indonesian | `id` | 0% | none |
|
||||
@@ -179,7 +188,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
| Rank | Milestone | Estimate (h) |
|
||||
|---|---|---|
|
||||
| 0 | Convert and share: Create PDF from Office, Word export that keeps layout (#773) | 32–55 |
|
||||
| 1 | Backlog and platform: crash and wrong-result reports, Chinese UI face (#826) | 50–90 |
|
||||
| 1 | Backlog and platform: crash and wrong-result reports, Chinese web UI face (#826) | 50–90 |
|
||||
| 2 | Fidelity harness against Acrobat and the renderer decision (M2; owner decision on #841) | 110–190 |
|
||||
| 3 | Editing existing content (M7) | 100–180 |
|
||||
| 4 | OCR languages and Office export/import (M10) | 95–175 |
|
||||
@@ -189,12 +198,36 @@ 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-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.
|
||||
- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.
|
||||
- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.
|
||||
|
||||
- **2026-10-23 (M7, #4280):** Edit text names each standard stand-in font after its face (`PCEdTimesBold`, ...) instead of one shared `PCEdHelv`. Rewriting a bold paragraph whose subset lacks an accent no longer repoints the paragraphs set earlier in a regular stand-in at Times-Bold, and the editor's frame stays on the paragraph being edited. Pages saved by older builds keep their shared name and are not repaired. Estimates unchanged.
|
||||
- **2026-10-23 (M8, #3205 follow-up):** Phone-pattern redaction matches complete labelled Italian geographic numbers such as `Tel. +39 0426/123456`, with synthetic matcher and mark/apply/save/reopen coverage; unlabelled international slash numbers remain unsupported.
|
||||
- **2026-10-23 (M7, #2636 partial):** A new `PasteContent` edit pastes an added text box or image copied in the same document or another, keeping its style, picture, turns, flips and crop, as one undo step; `content_copy` drives it headlessly. A paste lands beside earlier copies (18 pt steps) and stays on the page. A pasted image reuses its picture object in its own document and after the first paste into another; there a colour profile is dropped and CMYK colours stored losslessly are turned to RGB. The desktop keys and menus follow in separate PRs. Estimates unchanged.
|
||||
- **2026-10-23 (M11, optimizer resolution):** Image downsampling includes each page's `/UserUnit` scale, preserving images already below the physical resolution threshold, including shared nested forms.
|
||||
Synthetic measurement and optimization regressions cover direct and indirect units and page-local defaults.
|
||||
Estimates unchanged.
|
||||
- **2026-10-23 (M10, Word table widths):** Word export sizes each cell from the grid columns it spans, keeping unequal columns and cells after a merged cell consistent with the table grid.
|
||||
- **2026-10-23 (M10, table continuation text):** Office exporters retain text from table slots covered by another cell's span as paragraph text.
|
||||
Synthetic regressions check every input fragment survives exactly once in Word, HTML, RTF and PowerPoint, while ordinary superscripts stay in their table cells.
|
||||
- **2026-10-23 (M10, image export):** Soft-mask Decode intervals preserve partial opacity in Export all images and Save Image As.
|
||||
Synthetic regressions cover direct and indirect ranges, inverted/subrange alpha, packed masks, JPEG masks and unchanged image component Decode.
|
||||
- **2026-10-23 (M10, print resources):** Vector printing preserves original page artwork when existing XObjects use annotation resource names.
|
||||
The regression checks two distinct appearances, inherited resources, print/reopen pixels and unchanged source data.
|
||||
Estimates unchanged.
|
||||
- **2026-10-21 (M3, window resize and move on Wayland):** With PdfCraft's own title bar on GNOME/Wayland, a second resize by a window edge, or a second move by the empty tab strip, works straight after the first; it waited for a click inside the window, because the compositor keeps the button's release from egui. A unit test covers the release given back; checked by hand in a test build. Estimates unchanged.
|
||||
- **2026-10-22 (M4, #3916 partial):** Document edits and Undo/Redo cancel an Organize page drag. Pointer-release regressions check exact page order and save/reopen.
|
||||
- **2026-10-22 (M10, #3752 paper):** CUPS jobs ask for the chosen paper in every size. The 13 sizes the Print dialog sent no paper for (A6, A0–A2, ARCH, ANSI C–E) use PWG 5101.1 names, checked against a synthetic PPD with `cupsfilter`, and `doc_print` to a printer sends the paper too. The macOS tray half (Auto Select instead of the PPD's default tray) is a craft-print change that needs a pin bump here. Estimates unchanged.
|
||||
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
|
||||
- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
|
||||
|
||||
- **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.
|
||||
- **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.
|
||||
- **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.
|
||||
- **2026-10-21 (M3, #3808):** Page thumbnails in the Inspector can be resized independently from the document and Organize, with a slider, buttons and `thumbnail-zoom` control option. Selection, page following and reload are covered by regressions. Estimates unchanged.
|
||||
- **2026-10-22 (M5, comment threads):** Replies join the comment their `/IRT` references, not every comment sharing its `/NM`; PyMuPDF names each page's first comment `fitz-A0`, so all replies used to land under page 1. The Comments header counts comments without their replies, with the number of replies in small text under it (in every catalogue), and a reply's thread line runs from the avatar above it to its own. A reply to a reply shows in its thread in the panel too (it was listed nowhere), an `/IRT` that leads to no comment (itself, a loop, a pop-up, an unlisted object) leaves its annotation a comment of its own instead of hiding it (a status or checkmark that leads nowhere is listed nowhere), and a Replace Text caret isn't counted as a reply. The comment tools refuse an `id` several comments share instead of acting on the first (page 1's), and take `page` + `index` for those; `comment_list` reads a status or checkmark from the annotation it was set on, as the panel does, and reports a reply's own on the reply. UI, engine and automation regressions cover it. Estimates unchanged.
|
||||
- **2026-10-22 (M2, #3107 / PR #3438):** Inline-image parsing falls back to the existing EI heuristic when missing declared samples, headers or terminators exceed the content-window budget, instead of waiting for an impossible allocation. Exact-length parsing for available samples and ordinary large streamed images is retained. Estimates unchanged.
|
||||
- **2026-10-21 (M14, Brazilian Portuguese):** Completed the `pt-br` catalog against the current 2,674-key union, including signature validation and accessibility messages; no build or compilation run. Localization remains partial because help and unpredictable engine/OS error details are not translated.
|
||||
- **2026-10-21 (M14, #3557):** Preferences: the OK button stays below the scrolling settings instead of being the last thing in them, so it is in reach in a short window.
|
||||
@@ -205,6 +238,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
- **2026-10-17 (M8, gap 6, #2662):** A filled cover over a long line counts when it hides half of any one word, not only 40% of the line's words or box, so a black box over one number in a long line — or an unapplied redaction mark over it — no longer audits clean while the number is still extractable; a sliver under half of every word it touches and under 40% of the line is still not flagged
|
||||
- **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-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.
|
||||
@@ -225,6 +259,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-20 (M3, #3541/#3620):** Comment hover follows the individual marked lines instead of the enclosing multiline rectangle, and overlapping comments follow paint order. Synthetic UI regressions cover all four text-markup kinds, page/view rotations, neighboring highlights, legacy rectangle fallback and unchanged PDF bytes. Estimates unchanged.
|
||||
- **2026-10-20 (M10, #3532 partial):** Vector printing retains existing widget artwork when its appearance lacks Subtype. A print-owned copy adds Form dispatch metadata. The source stream and all explicit subtypes stay unchanged. Synthetic source/output raster checks cover resources, selected/shared appearances, placement, flags and content modes. Appearance regeneration and physical printer validation remain outside this fix. Estimates unchanged.
|
||||
|
||||
- **2026-10-20 (M5, arrow keys move comments):** With a comment selected, the arrow keys move it a screen pixel and ⌘/Ctrl or Shift and an arrow ten, instead of scrolling the view or turning the page; up is up on screen at any zoom and rotation, and each press is one undo step. Text markup and locked comments stay put. Estimates unchanged.
|
||||
|
||||
- **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged.
|
||||
|
||||
- **2026-10-19 (M3, #3387):** Save-prompt shortcuts yield to later consent and utility dialogs; a synthetic UI regression checks that an edited document stays open. Estimates unchanged.
|
||||
@@ -243,6 +279,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-18 (M6, #2892):** Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged.
|
||||
|
||||
- **2026-10-18 (M7, #3212):** Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, with original content preserved.
|
||||
- **2026-10-18 (M12, #2589):** Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Estimates unchanged.
|
||||
- **2026-10-18 (M7, #2592):** Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Estimates unchanged.
|
||||
- **2026-10-18 (M7, #3187):** Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Estimates unchanged.
|
||||
- **2026-10-18 (M12, #2569):** Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Estimates unchanged.
|
||||
- **2026-10-18 (M12, #2572):** Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Estimates unchanged.
|
||||
@@ -270,6 +308,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.
|
||||
- **2026-10-20 (M14, Spanish catalog gaps):** `es.tsv` gains the 143 `(context, English)` keys the other catalogs carried and it was missing, so Spanish covers the whole bundled key union like Lithuanian and Vietnamese: calendar months and weekdays, the `certificate` context, X.509 key usages, signature-revision and digital-ID lines, password validation, eight plural messages, the combine-from-folder strings, the rendering and stale-file notices and the shortcut-spelled tooltips. Counts in `localization-parity.md` re-measured against the current union (`vi` restated against it for the same reason). Status stays `partial`: no translated help, and OS details stay outside the catalog. Estimates unchanged.
|
||||
- **2026-10-16 (M14, localization):** Czech goes from menus-and-dialogs to the whole surface: 2,674 entries after adding the ~220 keys the other catalogs had -- the sentences the engine words (signature details, accessibility findings and report, PDF/A problems, pages to print, history labels), the date picker's weekday heads, the certificate viewer's fields and shared buttons. "Tag" is *tag* throughout (the Tags panel said *značky*, which is also a redaction mark), and "{n} tags" no longer reads "1 značek". Two new catalog tests. Estimates unchanged.
|
||||
- **2026-10-16 (M5, #2583, #1869):** A sticky note on a page with `/Rotate` is drawn upright, with its top-left where it was placed. Notes are saved with the NoRotate flag, and the renderer now honours it: the appearance is turned against the page's rotation about the upper-left corner of `/Rect`, which stays put (ISO 32000-2 §12.5.3; vendored hayro-interpret patch 37). Attachment icons follow the same rule. Selection, hover, the edit composer, the Comments panel's flash and the `comment_list` and `doc_info` rectangles use the drawn box, and `comment_add` anchors an icon's displayed top-left at `at`. Estimates unchanged.
|
||||
- **2026-10-16 (M11, #1201):** Optimize decodes a JPEG with its colour transform: an Adobe APP14 marker's flag, else the filter's `/ColorTransform` (ISO 32000-2 §7.4.8). An RGB JPEG stored untransformed (`/ColorTransform 0`, no marker) used to be converted from YCbCr anyway and came out in other colours, recompressed or merged from strips; it now keeps them. A JPEG whose marker and `/ColorTransform` disagree, or whose components are named R, G and B without `/ColorTransform 0`, is left as it is, since readers differ on it. Estimates unchanged.
|
||||
- **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged.
|
||||
- **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged.
|
||||
- **2026-10-15 (M12, XFA, #2574):** A `pageArea` with no `<occur>` repeats without limit instead of taking a subform's default of one use, so a later page area with `occur max="1"` is no longer drawn (with a copy of its fields) over every body page. A page area's `occur min` is honoured too: one the body never reached gets the pages it still needs after the body (the once-only closing page of a form, with its button, comes last). Acrobat Pro also puts that page last, and when printing keeps it but leaves it blank (`relevant="-print"` on the page area), which PdfCraft does not do yet; both re-observed on a synthetic fixture, see the 2026-10-19 line. Synthetic regression tests. Estimates unchanged.
|
||||
@@ -281,6 +321,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-15 (M12, XFA, #2574):** A `pageArea` with no `<occur>` repeats without limit instead of taking a subform's default of one use, so a later page area with `occur max="1"` is no longer drawn (with a copy of its fields) over every body page. Synthetic regression test; the page area's `occur min` (a once-only page of its own) is still not laid out, recorded in `form.xfa-dynamic`. Estimates unchanged.
|
||||
- **2026-10-14 (M12, reading colours, #2059):** Pending page backgrounds use the document's reading colour immediately, preventing white flashes while scrolling to uncached pages. A headless canvas regression covers three pending pages in every preset and a custom background. Estimates unchanged.
|
||||
- **2026-10-15 (community, M6, #2608):** In Prepare a form the selected field moves with the arrow keys: a point per press, ten with Shift, as the object nudge and dragging it do. Each press is one undo step ("Change field properties"), and the keys no longer turn the page while a field is selected. Estimates unchanged.
|
||||
- **2026-10-15 (M3, closable community card):** The ArtCraft community card on Home has a close button that hides it for the rest of the run; it returns on the next launch, and its links stay in the top bar's Discord button and the Help menu. A UI regression covers closing and the fresh-launch default. Estimates unchanged.
|
||||
- **2026-10-13 (community, M3, #1569 review):** Pixel-only Wayland wheel, wheel-tilt and continuous input use standalone moved events, so Ctrl zoom does not remain latched after the modifier is released (#991); vendored winit patch (13), with a policy test. Estimates unchanged.
|
||||
- **2026-10-15 (M14, #2383 candidate):** Device-limit requests now clamp unsupported maxima and minimum alignments before enabling the adapter's full 2D texture extent. This addresses the reported V3D request of 16 shader variables on an adapter supporting 15. Synthetic regressions fail before the clamp and pass afterward, along with the existing HiDPI case and Windows GPU-required application tests. Raspberry Pi startup remains unverified; milestone and overall estimates are unchanged.
|
||||
- **2026-10-12 (M6):** XFDF field import and data-file extraction join all text nodes in a value, preserving text after XML comments and processing instructions. Synthetic regressions cover Unicode, CDATA, empty values and PDF save/reopen. Estimates unchanged.
|
||||
@@ -296,6 +337,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-22 (M14, JPEG and TIFF export):** Export ▸ Image as JPEG or TIFF refuses a raster that is not exactly width × height pixels, as PNG export has since #2425. A raster a pixel short panicked inside the JPEG and TIFF encoders, and a partial pixel at the end was dropped and the rest written as a valid image. Rendered pages are always the right size, so what exports is unchanged. Estimates unchanged.
|
||||
- **2026-10-13 (G14, Vietnamese localization):** Added Vietnamese (`vi`, Tiếng Việt) as an interface and date language with a 2,591-entry catalog (`plural_none`) covering 100% of the current localizable key union (plus `theme`/`Appearance`). Locale tags `vi` / `vi-VN` / `vi_VN.UTF-8` resolve; calendar months use numeric `Tháng 1`…`12` / `tháng 1`…`12`. Native-speaker community review recorded. The twelve-language localization mean moves from ≈59% to ≈68%; weighted readiness ≈49% → ≈50%. Status stays `partial`: engine/OS details, document contents, filenames, CLI/MCP and external help stay outside the catalog by design.
|
||||
|
||||
- **2026-10-12 (M10, Edit on a scanned page):** Turning Edit on (its tab, Edit text & images or Add text) for a scanned page (an image covering at least half of a page with no text of its own; comments and text boxes over it do not count) recognizes the page first, like Acrobat's "Converting scanned page to Editable Text and Images", so its words open for editing. Once per page per window, one undoable "Recognize text" step, with the language of the Recognize Text dialog (English only for now, gap 7). Pages with real text (a flyer with a background picture), read-only files and other tools are left alone. The photographs on a scan are still part of the one page image.
|
||||
- **2026-10-13 (M3, typed zoom):** The right rail's zoom percentage is an editable field: type 150, 150% or 62.5 % and press Enter, Escape discards, and nonsense keeps the current zoom. The control channel's zoom option shares its parser, which now refuses zero, negative and non-finite values.
|
||||
- **2026-10-13 (M4, indirect page rotation):** Rotation queries and edits resolve indirect integer values on pages and their page-tree ancestors. Turning a page already at 270° by 90° now saves it at 0°, including when its rotation is inherited. Synthetic full/incremental save-and-reopen tests cover nested inheritance, sibling preservation, negative/large angles and invalid-value fallback. Estimates unchanged.
|
||||
- **2026-10-14 (M1, Flate fallback):** Raw deflate whose first bytes resemble a zlib header no longer loses a decoding-limit error during fallback. Strict and tolerant filter regressions and a COS stream regression cover refusal at the caller limit and successful decoding within it. No parity status or estimate changes.
|
||||
@@ -343,6 +385,9 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-15 (community, M14, Polish signature panel):** A Polish signature panel listed its details in English: the catalog lacked every signature wording, the changes after signing they name and 34 UI literals. All 101 are translated; `polish_covers_ui_literals` and `polish_says_what_a_signature_says` keep them so. Estimates unchanged.
|
||||
- **2026-10-14 (M14, Finnish localization):** Added Finnish as another interface and date language, with a 2,674-entry catalog covering every key of the other bundled catalogs and two-form plurals (partitive after numbers other than 1). Calendar dates use partitive month names (`14. lokakuuta 2026`). Coverage tests check commands/tools, scanned UI literals and bundled catalog keys. AI-assisted; native proofreading pending.
|
||||
- **2026-10-14 (M14, Catalan localization):** Added Catalan as another interface and date language, with a 2,592-entry clean-room catalog, one/other plurals and coverage tests for commands, tools, UI literals and every key in the other catalogs. A native Catalan speaker (the contributor) has reviewed the translation. Estimates unchanged.
|
||||
|
||||
- **2026-10-15 (M3, #1248):** A fresh install follows the desktop's appearance: the theme preference defaults to System (dark on a dark desktop, Light where the desktop says nothing); saved settings and `--theme` still win. Dark page rendering is Reading colours, and the page reading themes are #1732.
|
||||
- **2026-10-15 (M3, #1767):** Restore last view settings when reopening documents, as Acrobat's preference does: a file opened again shows the page, zoom and page display it was last shown with (remembered for the last 100 files when a tab closes or settings are saved), over the file's own initial view; on by default, Preferences ▸ Documents and view turns it off.
|
||||
- **2026-10-13 (M3, native-opening candidate):** Chosen tools survive preparation, conversion and password retries; startup intake waits for pending preparation. Regression tests cover completion, cancellation and document identity. Estimates unchanged.
|
||||
- **2026-10-13 (community, M3, #531 touchpad momentum):** On Wayland a two-finger swipe keeps gliding after the fingers lift and slows to a stop, measured from the gesture's last 0.1 s and decaying with a 0.35 s time constant through the #759 1:1 path. Any wheel input, click, key, zoom or edge ends it (fingers resting on the touchpad don't yet: the vendored winit binds no Wayland hold gestures); single-page paging, macOS (which sends its own momentum), the web, and Animation effects Off never glide. Unit tests for the physics and two headless view tests. Estimates unchanged.
|
||||
- **2026-10-13 (M3, native-open admission):** Later prepared replies stay queued while a modal or native picker owns the foreground. Picker completion, cancellation and abandonment wake retained opens. Regressions cover recipient ownership, exactly-once admission, source/history preservation and one-shot repaint requests. Estimates unchanged.
|
||||
@@ -631,10 +676,19 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
|
||||
## Revision history
|
||||
|
||||
**2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged.
|
||||
|
||||
**2026-10-15 · minor:** M14/#2383 candidate: GPU device requests clamp unsupported limits while retaining the adapter texture extent. Synthetic V3D/downlevel regressions and Windows GPU-required tests pass; Raspberry Pi hardware remains unverified. Estimates unchanged.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M10: covered table slots retain their text in paragraph flow across Office exporters; emitted superscripts remain in their cells. Synthetic source and CLI regressions; estimates unchanged. |
|
||||
| 2026-10-23 | minor | M10: Export all images and Save Image As apply soft-mask Decode intervals to PNG alpha before resizing, including inverted/subrange, indirect, packed and JPEG masks. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M10: annotation appearances use unoccupied XObject names, preserving original page artwork and distinct appearances through inherited resources and print/reopen. Estimates unchanged. |
|
||||
| 2026-10-22 | minor | M4, #3916 partial: document edits and Undo/Redo cancel Organize drags. Pointer-release and save/reopen regressions check page order. Estimates unchanged. |
|
||||
| 2026-10-20 | minor | M4: initial-view window and interface options resolve indirect boolean ViewerPreferences values; synthetic true/false and save/reopen regressions retain defaults for malformed entries. Estimates unchanged. |
|
||||
| 2026-10-20 | minor | M6, #3502: form detection preserves comments across content streams; estimates unchanged. |
|
||||
| 2026-10-20 | minor | M10, #3532 partial: vector printing retains existing appearances with absent Subtype; estimates unchanged. |
|
||||
@@ -679,8 +733,15 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
- **2026-10-13 (M7):** Edit a PDF ▸ Add content: Header and footer, Watermark and Background open an Add / Update / Remove menu (Update and Remove enabled only when the document has that mark), as Acrobat's Watermark control does. The catalogue gains `ToolItem::actions`, so any tool can list more commands (#1192).
|
||||
|
||||
- **2026-10-18 (M8, #1350):** Published the history-preserving integration; simplified the inherited-form resource guard for Rust 1.96 Clippy. Formatting, 64 redaction tests, scoped Clippy, layering, assets and the scoped wasm check pass locally. CI remains pending; estimates unchanged.
|
||||
|
||||
- 2026-10-18: M11 / #3227: mark target-version compatibility partial; document the unchecked newer-content limitation.
|
||||
|
||||
- **2026-10-18 (PR #3227 integration):** M11: integrate upstream b0e5c6eb; retain partial target-version compatibility claims and effective-version reporting, correcting the borrowed version parser lifetime. Scope and estimates unchanged.
|
||||
|
||||
- **2026-10-12 (i18n):** Albanian (`sq`, Shqip) added: 2,343-entry catalog, month and weekday names, Preferences entry; not yet reviewed by a native speaker.
|
||||
|
||||
- **2026-10-21 (M4, #3865):** A new bookmark records where the reader is: the top-left of the selected text, or the top of the window, as `/XYZ left top null` (zoom kept), instead of the page top (`Edit::AddBookmark` takes `left` and `top`; `bookmark_add` takes `top` and `left`; `PageInfo::xyz_for_view`).
|
||||
|
||||
- **2026-10-18 (renderer, hayro patches 19/35):** A mesh shading (types 4–7) is sampled over its own triangles instead of the whole path: a BricsCAD plan with 310 one-triangle `sh` fills took 2 s per 1024 px tile at every zoom (and hit the 20 s watchdog on a busy machine); now about 70 ms, so zooming into dense topology drawings stays fluid. Estimates unchanged.
|
||||
|
||||
- **2026-10-22 (PR #3227 integration):** M11: integrate upstream `80b7d215`; retain partial target-version compatibility and upstream content-boundary and image-size regression coverage. Scope and estimates unchanged.
|
||||
|
||||
@@ -21,10 +21,10 @@ pdfcraft-cos = { workspace = true }
|
||||
pdfcraft-preflight = { workspace = true }
|
||||
pdfcraft-automation = { workspace = true }
|
||||
pdfcraft-platform = { workspace = true }
|
||||
base64 = "0.22"
|
||||
base64 = "0.23"
|
||||
|
||||
[dev-dependencies]
|
||||
# Decodes `render` output in tests/owner_password.rs; already a dependency of the engine.
|
||||
# Decodes `render` output in tests/it/owner_password.rs; already a dependency of the engine.
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
|
||||
@@ -84,7 +84,24 @@ help and feedback: https://discord.gg/artcraft"
|
||||
);
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an
|
||||
// `Err` value"), which a Latin-1 file name is, and it panics while collecting them: even
|
||||
// `--help` ended that way. Such a name cannot be passed on either, since the paths here are
|
||||
// `str`, so it is a usage error (photocraft#1108).
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
for arg in std::env::args_os().skip(1) {
|
||||
match arg.into_string() {
|
||||
Ok(a) => args.push(a),
|
||||
Err(bad) => {
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"pdfcraft-cli: `{}` is not valid UTF-8, so it cannot be used as an argument",
|
||||
bad.to_string_lossy()
|
||||
);
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
// `<command> --help` too; only right after the command, so a later `-h` (a value) still reaches it.
|
||||
let command = match args.get(1).map(String::as_str) {
|
||||
Some("--help" | "-h") => Some("--help"),
|
||||
@@ -169,7 +186,7 @@ fn version() -> Result<(), CliError> {
|
||||
/// found so scripts and CI can gate on it, and when the audit itself cannot run.
|
||||
fn audit(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("audit", args, AUDIT_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("audit: missing file")?;
|
||||
let path = *positional(args, AUDIT_OPTIONS).first().ok_or("audit: missing file")?;
|
||||
let bytes = read(path)?;
|
||||
let password = flag(args, "--password");
|
||||
let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).map_err(|e| format!("{path}: {e}"))?;
|
||||
@@ -208,6 +225,28 @@ struct OptionSpec {
|
||||
takes_value: bool,
|
||||
}
|
||||
|
||||
/// The options whose value is a file or folder. Only these refuse a value that is another
|
||||
/// option: a file named `--password` is never what was meant, while a password can be anything
|
||||
/// (`--password --page` is a password of `--page`, which tests/text.rs pins), and so can a title.
|
||||
/// The way to name a file that does start with `-` is `./--name`, as `--root` already offered.
|
||||
const PATH_VALUE_OPTIONS: [&str; 6] = ["--out", "--out-dir", "--json", "--root", "--control", "--script"];
|
||||
|
||||
/// Whether a token can be the value of a path option. Another option cannot: `--out --password`
|
||||
/// used to write the PDF to a file called `--password` and exit 0 (photocraft#6944).
|
||||
fn can_be_path_value(name: &str, value: Option<&str>) -> bool {
|
||||
!PATH_VALUE_OPTIONS.contains(&name) || value.is_some_and(|v| !v.is_empty() && !v.starts_with("--"))
|
||||
}
|
||||
|
||||
/// The complaint about a path option whose value is missing or is another option.
|
||||
fn needs_value(command: &str, name: &str, value: Option<&str>) -> String {
|
||||
match value {
|
||||
Some(v) if !v.is_empty() => {
|
||||
format!("{command}: {name} needs a value and `{v}` is another option; write `./{v}` for a file of that name")
|
||||
}
|
||||
_ => format!("{command}: {name} needs a value"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse unknown options and malformed confinement flags before any file is read.
|
||||
fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Result<(), CliError> {
|
||||
if specs.iter().any(|spec| spec.name == "--root") {
|
||||
@@ -230,9 +269,19 @@ fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Res
|
||||
let Some(spec) = specs.iter().find(|spec| spec.name == arg) else {
|
||||
return Err(format!("{command}: unknown option --{name}").into());
|
||||
};
|
||||
// Other missing or malformed values are left to the command, which reports them in its own
|
||||
// terms (`text` and `extract` explain what a page value must be).
|
||||
i += if spec.takes_value { 2 } else { 1 };
|
||||
// A file's name is not another option, which also closes the gap the walk left for
|
||||
// those: an unknown option in that value position was skipped along with it. Other
|
||||
// values, missing or malformed, are left to the command, which reports them in its
|
||||
// own terms (`text` and `extract` explain what a page value must be).
|
||||
i += if spec.takes_value {
|
||||
let value = args.get(i + 1).map(String::as_str);
|
||||
if !can_be_path_value(spec.name, value) {
|
||||
return Err(needs_value(command, spec.name, value).into());
|
||||
}
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
@@ -278,19 +327,24 @@ const UI_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--control", takes_value:
|
||||
#[cfg(feature = "mcp")]
|
||||
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--root", takes_value: true }, OptionSpec { name: "--compact", takes_value: false }];
|
||||
|
||||
fn positional(args: &[String]) -> Vec<&str> {
|
||||
/// The arguments that are not options or their values. Which tokens are values is the spec's
|
||||
/// answer: skipping the one after every option made `check-one --edit file.pdf` report "missing
|
||||
/// file", the file having been read as `--edit`'s value.
|
||||
fn positional<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a str> {
|
||||
let mut out = Vec::new();
|
||||
let mut skip = false;
|
||||
for a in args {
|
||||
if skip {
|
||||
skip = false;
|
||||
continue;
|
||||
let mut i = 0;
|
||||
while let Some(a) = args.get(i) {
|
||||
match specs.iter().find(|spec| spec.name == a.as_str()) {
|
||||
Some(spec) if spec.takes_value => i += 2,
|
||||
// An option that takes no value, and an unknown one, which `validate_options` has
|
||||
// already refused by the time this runs.
|
||||
Some(_) => i += 1,
|
||||
None if a.starts_with("--") => i += 1,
|
||||
None => {
|
||||
out.push(a.as_str());
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if a.starts_with("--") {
|
||||
skip = true;
|
||||
continue;
|
||||
}
|
||||
out.push(a.as_str());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -301,7 +355,7 @@ fn read(path: &str) -> Result<Arc<Vec<u8>>, String> {
|
||||
|
||||
fn info(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("info", args, INFO_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("info: missing file")?;
|
||||
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
|
||||
let bytes = read(path)?;
|
||||
let password = flag(args, "--password");
|
||||
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
|
||||
@@ -354,7 +408,7 @@ fn info(args: &[String]) -> Result<(), CliError> {
|
||||
|
||||
fn text(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("text", args, TEXT_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("text: missing file")?;
|
||||
let path = *positional(args, TEXT_OPTIONS).first().ok_or("text: missing file")?;
|
||||
let mut selected_page = None;
|
||||
// Validate every supplied value before reading, retaining the first valid selection.
|
||||
let mut options = args.iter();
|
||||
@@ -482,7 +536,13 @@ fn edit(args: &[String]) -> Result<(), CliError> {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let value = args.get(i + 1).map(String::as_str).ok_or_else(|| format!("edit: {arg} needs a value"))?;
|
||||
// `edit` parses its own options (they run in order), so `--out` is checked here in the
|
||||
// same way: it wrote a PDF to a file called `--full`.
|
||||
let value = args.get(i + 1).map(String::as_str);
|
||||
if !can_be_path_value(arg, value) {
|
||||
return Err(needs_value("edit", arg, value).into());
|
||||
}
|
||||
let value = value.ok_or_else(|| format!("edit: {arg} needs a value"))?;
|
||||
match arg {
|
||||
"--out" => out = Some(value),
|
||||
"--password" => password = Some(value),
|
||||
@@ -569,7 +629,7 @@ fn file_stem(path: &str) -> String {
|
||||
fn combine(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("combine", args, COMBINE_OPTIONS)?;
|
||||
let out = flag(args, "--out").ok_or("combine: missing --out")?;
|
||||
let inputs = positional(args);
|
||||
let inputs = positional(args, COMBINE_OPTIONS);
|
||||
if inputs.len() < 2 {
|
||||
return Err("combine: give at least two input files".into());
|
||||
}
|
||||
@@ -580,7 +640,7 @@ fn combine(args: &[String]) -> Result<(), CliError> {
|
||||
|
||||
fn extract(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("extract", args, EXTRACT_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("extract: missing file")?;
|
||||
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 mut session = pdfcraft_engine::Session::new();
|
||||
@@ -592,7 +652,7 @@ fn extract(args: &[String]) -> Result<(), CliError> {
|
||||
fn split(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("split", args, SPLIT_OPTIONS)?;
|
||||
use pdfcraft_engine::SplitBy;
|
||||
let path = *positional(args).first().ok_or("split: missing file")?;
|
||||
let path = *positional(args, SPLIT_OPTIONS).first().ok_or("split: missing file")?;
|
||||
let by = match (flag(args, "--every"), flag(args, "--before")) {
|
||||
(Some(n), None) => {
|
||||
// A count the splitter cannot hold is refused here, before the file is opened,
|
||||
@@ -637,14 +697,14 @@ fn parse_dpi(value: &str) -> Result<f32, String> {
|
||||
|
||||
fn render(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("render", args, RENDER_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("render: missing file")?;
|
||||
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_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)")?;
|
||||
// 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(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
|
||||
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),
|
||||
Some("jpg" | "jpeg") => Some(ImageFormat::Jpeg { quality: 90 }),
|
||||
Some("tif" | "tiff") => Some(ImageFormat::Tiff),
|
||||
@@ -688,6 +748,10 @@ fn render(args: &[String]) -> Result<(), CliError> {
|
||||
pdfcraft_render::RenderWarning::ContentTruncated => {
|
||||
let _ = writeln!(std::io::stderr().lock(), "warning: page {page}: content past the page's safety budget was skipped");
|
||||
}
|
||||
pdfcraft_render::RenderWarning::ColourFallback => {
|
||||
let _ =
|
||||
writeln!(std::io::stderr().lock(), "warning: page {page}: a colour that could not be computed was painted in a fallback colour");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -696,7 +760,7 @@ fn render(args: &[String]) -> Result<(), CliError> {
|
||||
/// Child-process body for `check`: prints one JSON line.
|
||||
fn check_one(args: &[String]) -> Result<(), CliError> {
|
||||
validate_options("check-one", args, CHECK_ONE_OPTIONS)?;
|
||||
let path = *positional(args).first().ok_or("check-one: missing file")?;
|
||||
let path = *positional(args, CHECK_ONE_OPTIONS).first().ok_or("check-one: missing file")?;
|
||||
let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("36"))?;
|
||||
let start = Instant::now();
|
||||
let bytes = read(path)?;
|
||||
@@ -779,7 +843,7 @@ fn collect(paths: &[&str]) -> Vec<PathBuf> {
|
||||
if let Ok(rd) = std::fs::read_dir(&p) {
|
||||
stack.extend(rd.flatten().map(|e| e.path()));
|
||||
}
|
||||
} else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
|
||||
} else if p.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
@@ -802,7 +866,7 @@ fn check(args: &[String]) -> Result<(), CliError> {
|
||||
);
|
||||
let dpi = flag(args, "--dpi").unwrap_or("36").to_string();
|
||||
parse_dpi(&dpi)?;
|
||||
let files = collect(&positional(args));
|
||||
let files = collect(&positional(args, CHECK_OPTIONS));
|
||||
if files.is_empty() {
|
||||
return Err("check: no PDF files found".into());
|
||||
}
|
||||
@@ -985,9 +1049,9 @@ fn run(args: &[String]) -> Result<(), CliError> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let tool = *positional(args).first().ok_or("run: missing tool name (see `pdfcraft-cli tools`)")?;
|
||||
let tool = *positional(args, RUN_OPTIONS).first().ok_or("run: missing tool name (see `pdfcraft-cli tools`)")?;
|
||||
let mut obj = serde_json::Map::new();
|
||||
for kv in positional(args).iter().skip(1) {
|
||||
for kv in positional(args, RUN_OPTIONS).iter().skip(1) {
|
||||
let (k, v) = kv.split_once('=').ok_or(format!("run: expected key=value, got {kv:?}"))?;
|
||||
let value = serde_json::from_str(v).unwrap_or_else(|_| serde_json::Value::String(v.to_string()));
|
||||
obj.insert(k.to_string(), value);
|
||||
@@ -1053,7 +1117,7 @@ fn ui(args: &[String]) -> Result<(), CliError> {
|
||||
// Refused rather than truncated, which would quietly reach some other port.
|
||||
let port = u16::try_from(port).map_err(|_| format!("{file}: {port} is not a port number"))?;
|
||||
let token = info["token"].as_str().ok_or(format!("{file}: no token"))?;
|
||||
let pos = positional(args);
|
||||
let pos = positional(args, UI_OPTIONS);
|
||||
let method = *pos.first().ok_or("ui: missing method (state, inspect, click, drag, type, key, command, commands, set, open, screenshot)")?;
|
||||
let method = if method.starts_with("ui.") { method.to_string() } else { format!("ui.{method}") };
|
||||
let mut params = serde_json::Map::new();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod audit;
|
||||
mod automation_roots;
|
||||
mod batch;
|
||||
mod check;
|
||||
mod edit;
|
||||
mod extract;
|
||||
mod help;
|
||||
mod info_standards;
|
||||
mod mcp_compact;
|
||||
mod options;
|
||||
mod owner_password;
|
||||
mod render;
|
||||
mod root_arguments;
|
||||
mod run_report;
|
||||
mod run_root;
|
||||
mod split;
|
||||
mod stderr;
|
||||
mod stdout;
|
||||
mod text;
|
||||
mod ui_control;
|
||||
mod version_resource;
|
||||
mod xfa;
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Every command rejects misspelled long options before opening or writing a file.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
|
||||
|
||||
#[test]
|
||||
fn non_edit_commands_reject_unknown_options_before_io() {
|
||||
for args in [
|
||||
vec!["info", "missing.pdf", "--passwrod", "secret"],
|
||||
vec!["text", "missing.pdf", "--pgae", "1"],
|
||||
vec!["combine", "a.pdf", "b.pdf", "--ot", "out.pdf"],
|
||||
vec!["extract", "missing.pdf", "--pgaes", "1", "--out", "out.pdf"],
|
||||
vec!["split", "missing.pdf", "--ever", "2"],
|
||||
vec!["render", "missing.pdf", "--dppi", "96", "--out", "out.png"],
|
||||
vec!["check-one", "missing.pdf", "--edti"],
|
||||
vec!["check", "missing.pdf", "--timout", "2"],
|
||||
vec!["audit", "missing.pdf", "--passwrod", "x"],
|
||||
vec!["audit", "missing.pdf", "--nonsense", "1"],
|
||||
vec!["run", "doc_open", "--roto", "/tmp"],
|
||||
vec!["ui", "--contro", "control.json", "state"],
|
||||
] {
|
||||
let unknown = args.iter().find(|arg| arg.starts_with("--")).expect("test option");
|
||||
let out = Command::new(BIN).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?} unexpectedly succeeded");
|
||||
assert!(stderr.contains("unknown option") && stderr.contains(unknown), "{args:?}: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// photocraft#6944: an option took the next token whatever it was, so a line with a value missing
|
||||
/// in the middle of it did something else entirely — `extract in.pdf --pages 1 --out --password`
|
||||
/// wrote the PDF to a file called `--password` and exited 0. The unknown option hidden in a value
|
||||
/// position passed the check above too, since the walk skipped it along with the option.
|
||||
///
|
||||
/// Only the options whose value is a file or folder refuse one: a password or a title can be any
|
||||
/// string, `--page` included, which `text`'s own tests pin and this does not change.
|
||||
#[test]
|
||||
fn a_file_option_refuses_a_value_that_is_another_option() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-cli-values-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
for (option, args) in [
|
||||
("--out", vec!["extract", "missing.pdf", "--pages", "1", "--out", "--password"]),
|
||||
("--out", vec!["combine", "a.pdf", "b.pdf", "--out", "--nonsense"]),
|
||||
("--out", vec!["render", "missing.pdf", "--out", "--dpi", "96"]),
|
||||
("--out-dir", vec!["split", "missing.pdf", "--every", "2", "--out-dir", "--password"]),
|
||||
("--json", vec!["check", "missing.pdf", "--json", "--dpi"]),
|
||||
("--control", vec!["ui", "--control", "--out", "state"]),
|
||||
// `edit` parses its own options, in the order given, and had the same gap.
|
||||
("--out", vec!["edit", "missing.pdf", "--out", "--full"]),
|
||||
] {
|
||||
let out = Command::new(BIN).current_dir(&dir).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?} unexpectedly succeeded");
|
||||
assert!(stderr.contains(&format!("{option} needs a value")), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("another option"), "{args:?}: {stderr}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&dir).expect("read dir").count(), 0, "nothing was written");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// And a file whose name really does start with `-` is still reachable, the way the shell reaches
|
||||
/// one and `--root` already documented: `./--name`. The error is then about the input file, which
|
||||
/// is as far as these lines get here.
|
||||
#[test]
|
||||
fn a_file_whose_name_starts_with_dashes_is_still_reachable() {
|
||||
// The error is about the file the command could not open, so the test asks which file it
|
||||
// names -- not how the OS words "not found", which differs on Windows (#3849 review).
|
||||
for (names, args) in [
|
||||
("missing.pdf", vec!["extract", "missing.pdf", "--pages", "1", "--out", "./--dash.pdf"]),
|
||||
("missing.pdf", vec!["edit", "missing.pdf", "--out", "./--dash.pdf"]),
|
||||
("./--dash.pdf", vec!["info", "./--dash.pdf"]),
|
||||
] {
|
||||
let out = Command::new(BIN).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?}: no such file either way");
|
||||
assert!(stderr.contains(names), "{args:?}: the error is about {names}: {stderr}");
|
||||
// Not a usage error: the `./--dash.pdf` reached the command as a file name.
|
||||
assert!(!stderr.contains("needs a value") && !stderr.contains("unknown option"), "{args:?}: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The token after an option that takes no value is not its value: `check-one --edit file.pdf`
|
||||
/// reported "check-one: missing file", the file having been read as `--edit`'s operand.
|
||||
#[test]
|
||||
fn a_flag_that_takes_no_value_does_not_swallow_the_file() {
|
||||
for args in [vec!["check-one", "--edit", "missing.pdf"], vec!["check-one", "missing.pdf", "--edit"]] {
|
||||
let out = Command::new(BIN).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
// Which file the error is about, not how the OS says it is missing (#3849 review).
|
||||
assert!(stderr.contains("missing.pdf"), "{args:?}: the error is about the file: {stderr}");
|
||||
assert!(!stderr.contains("missing file"), "the file was found, and then not found: {stderr}");
|
||||
assert!(!stderr.contains("needs a value"), "{args:?}: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// photocraft#1108: an argument that is not UTF-8 panicked in `std::env::args` ("called
|
||||
/// `Result::unwrap()` on an `Err` value"), while collecting the arguments — so it panicked even
|
||||
/// for `--help`. Such a name cannot be used here, where paths are `str`, so it is a usage error.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_argument_that_is_not_utf8_is_an_error_not_a_panic() {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
for args in [vec![OsStr::new("info"), OsStr::from_bytes(b"/tmp/caf\xe9.pdf")], vec![OsStr::new("--help"), OsStr::from_bytes(b"caf\xe9")]] {
|
||||
let out = Command::new(BIN).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(1), "an error, not a panic (101): {stderr}");
|
||||
assert!(stderr.contains("not valid UTF-8"), "{stderr}");
|
||||
assert!(!stderr.contains("panicked"), "{stderr}");
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
//! Every command rejects misspelled long options before opening or writing a file.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
|
||||
|
||||
#[test]
|
||||
fn non_edit_commands_reject_unknown_options_before_io() {
|
||||
for args in [
|
||||
vec!["info", "missing.pdf", "--passwrod", "secret"],
|
||||
vec!["text", "missing.pdf", "--pgae", "1"],
|
||||
vec!["combine", "a.pdf", "b.pdf", "--ot", "out.pdf"],
|
||||
vec!["extract", "missing.pdf", "--pgaes", "1", "--out", "out.pdf"],
|
||||
vec!["split", "missing.pdf", "--ever", "2"],
|
||||
vec!["render", "missing.pdf", "--dppi", "96", "--out", "out.png"],
|
||||
vec!["check-one", "missing.pdf", "--edti"],
|
||||
vec!["check", "missing.pdf", "--timout", "2"],
|
||||
vec!["audit", "missing.pdf", "--passwrod", "x"],
|
||||
vec!["audit", "missing.pdf", "--nonsense", "1"],
|
||||
vec!["run", "doc_open", "--roto", "/tmp"],
|
||||
vec!["ui", "--contro", "control.json", "state"],
|
||||
] {
|
||||
let unknown = args.iter().find(|arg| arg.starts_with("--")).expect("test option");
|
||||
let out = Command::new(BIN).args(&args).output().expect("run cli");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?} unexpectedly succeeded");
|
||||
assert!(stderr.contains("unknown option") && stderr.contains(unknown), "{args:?}: {stderr}");
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ workspace = true
|
||||
[dependencies]
|
||||
pdfcraft-ui-egui = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
|
||||
egui = { workspace = true }
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
@@ -11,15 +11,13 @@ workspace = true
|
||||
[dependencies]
|
||||
# Help ▸ Check for updates (issue #28): one HTTPS request to GitHub, over rustls with the OS's
|
||||
# trusted roots. No bundled root list (webpki-roots and webpki-root-certs are CDLA-licensed).
|
||||
ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "_ring"] }
|
||||
rustls-native-certs = "0.8"
|
||||
pdfcraft-ui-egui = { workspace = true }
|
||||
# `build_info`: the version and compile-time build label for `--version` and the log.
|
||||
pdfcraft-engine = { workspace = true }
|
||||
# wgpu draws; OpenGL (glow) is the fallback when wgpu can't start on an old or unusual GPU or
|
||||
# driver (#461, #435, #392), and can be chosen with PDFCRAFT_RENDERER=gl.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11", "persistence", "links"] }
|
||||
egui = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11", "persistence", "links", "clipboard"] }
|
||||
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 (src/logging.rs).
|
||||
log = { workspace = true }
|
||||
@@ -31,9 +29,6 @@ chrono = { workspace = true }
|
||||
# crate registers the handler (Objective-C interop needs unsafe, which our workspace forbids)
|
||||
# behind a safe API. Same version as PhotoCraft. Pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
# ⌘Q asks about unsaved changes like the close button (#1136): an app menu whose Quit asks the
|
||||
# window to close instead of winit's, which ends the process without asking.
|
||||
craft-quit = { workspace = true, features = ["menu"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback), so the window is
|
||||
@@ -71,3 +66,6 @@ uds_windows = "=1.2.1"
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for pdfcraft.exe; build.rs only uses it when targeting Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
|
||||
+142
-53
@@ -1,6 +1,6 @@
|
||||
//! PdfCraft desktop app.
|
||||
//!
|
||||
//! Usage: `pdfcraft [options] [files…]`
|
||||
//! Usage: `pdfcraft [options] [files…]` (`-h` / `--help` prints a short version of this, [`USAGE`]).
|
||||
//! `--create-images [images…]` stages the images in one PDF and asks for the page DPI.
|
||||
//!
|
||||
//! View options (applied after the files open; also the seed of the UI control channel):
|
||||
@@ -41,7 +41,6 @@ mod reopen;
|
||||
mod settings;
|
||||
mod single_instance;
|
||||
mod text_scale;
|
||||
mod updates;
|
||||
#[cfg(test)]
|
||||
#[path = "windows_manifest.rs"]
|
||||
mod windows_manifest;
|
||||
@@ -56,6 +55,32 @@ 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");
|
||||
|
||||
/// 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 = "\
|
||||
Usage: pdfcraft [options] [files…]
|
||||
|
||||
Opens the files in the PdfCraft desktop app.
|
||||
|
||||
Options:
|
||||
--new-window open a window of its own instead of passing the files to a running PdfCraft
|
||||
--create-images [images…] put the images in one PDF and ask for the page DPI
|
||||
--control <file> enable the UI control channel (pdfcraft-cli ui --control <file> …)
|
||||
--page N, --zoom 150, --layout continuous, --theme dark, …
|
||||
view settings applied once the files are open
|
||||
-h, --help print this and exit
|
||||
--version print the version and exit
|
||||
|
||||
To inspect, convert or edit PDFs from a script, use pdfcraft-cli (pdfcraft-cli --help).";
|
||||
|
||||
/// Print `text` for `--help` and `--version`. `println!` would panic on a full or closed
|
||||
/// standard output; this exits normally instead.
|
||||
fn print_and_exit(text: &str) -> eframe::Result {
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stdout().lock(), "{text}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app was called PrintCraft before; settings saved then are under this key.
|
||||
const LEGACY_STORAGE_KEY: &str = "printcraft";
|
||||
|
||||
@@ -169,6 +194,11 @@ fn rejoin_split_paths(args: Vec<String>, exists: impl Fn(&str) -> bool) -> Vec<S
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&craft_update::suite::PDFCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
let logger = logging::install();
|
||||
// Last-resort guard (AGENTS.md §4): commands, edits, opens and saves catch panics and report
|
||||
@@ -196,10 +226,9 @@ fn main() -> eframe::Result {
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--version" => {
|
||||
println!("pdfcraft {}", pdfcraft_engine::build_info::version());
|
||||
return Ok(());
|
||||
}
|
||||
"--version" => return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version())),
|
||||
// Before any window or log file, so a scripted call returns (#4076).
|
||||
"-h" | "--help" => return print_and_exit(USAGE),
|
||||
"--control" => control_file = args.next(),
|
||||
"--create-images" => create_images = true,
|
||||
"--new-window" => new_window = true,
|
||||
@@ -332,6 +361,9 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer)
|
||||
let persistence_path = settings_dir().map(|d| d.join("app.ron"));
|
||||
// Set explicitly, so the renderer never depends on which one eframe defaults to.
|
||||
let mut native = eframe::NativeOptions { viewport, persistence_path, renderer, ..Default::default() };
|
||||
// PdfCraft installs its own last-resort system face (`PDFCRAFT_SYSTEM_FONTS`); eframe's
|
||||
// provider would read every installed face, including proprietary ones, into every UI pass.
|
||||
native.system_font_fallback = false;
|
||||
if renderer == eframe::Renderer::Wgpu {
|
||||
configure_gpu(&mut native);
|
||||
}
|
||||
@@ -391,16 +423,17 @@ fn app_creator<'a>(
|
||||
{
|
||||
app.motion.source = Some(motion::source());
|
||||
}
|
||||
app.update_source = Some(std::sync::Arc::new(updates::latest_release));
|
||||
app.set_startup_update_check(true);
|
||||
app.printer_source = Some(pdfcraft_ui_egui::system_printers());
|
||||
app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows"));
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
app.os_events = Some(apple_events.connect(&cc.egui_ctx));
|
||||
// winit's Quit (⌘Q) ends the process without asking about unsaved changes (#1136). This
|
||||
// menu's Quit closes the window instead, so `guard_quit` asks, as for the close button.
|
||||
if let Err(e) = craft_quit::install_app_menu(&cc.egui_ctx, "PdfCraft") {
|
||||
log::warn!("couldn't install the app menu, so ⌘Q quits without asking to save: {e}");
|
||||
// The native menu bar. Its Quit (⌘Q) closes the window rather than ending the process as
|
||||
// winit's does (#1136), so `guard_quit` asks about unsaved changes, as for the close
|
||||
// button.
|
||||
if !app.install_native_menu(&cc.egui_ctx) {
|
||||
log::warn!("couldn't install the macOS menu bar; the menus stay in the window");
|
||||
}
|
||||
}
|
||||
if let Some(server) = instance {
|
||||
@@ -770,6 +803,41 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The lockfile package block for `name`, or a panic naming the missing package.
|
||||
fn locked_package(root: &std::path::Path, name: &str) -> String {
|
||||
let lock = std::fs::read_to_string(root.join("Cargo.lock")).expect("Cargo.lock");
|
||||
lock.split("[[package]]")
|
||||
.find(|p| p.contains(&format!("\nname = \"{name}\"\n")))
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| panic!("{name} is not in Cargo.lock"))
|
||||
}
|
||||
|
||||
/// Interim graph check for the window stack while the reviewed fork revision is not yet
|
||||
/// published. The old `vendor/winit` / `vendor/egui-wgpu` path patches were removed from the
|
||||
/// published manifest; local integration supplies the reviewed worktrees through an external
|
||||
/// Cargo config patch. A git source must name the public storytold fork; a path source is the
|
||||
/// local integration graph. Behaviour (surface fitting, error scopes, scroll phases) is tested
|
||||
/// directly elsewhere; the retained vendor copies keep provenance until the fork revision is
|
||||
/// pinned. No public revision is invented here.
|
||||
fn assert_window_stack_graph(root: &std::path::Path, name: &str, version: &str) -> String {
|
||||
let package = locked_package(root, name);
|
||||
assert!(package.contains(&format!("\nversion = \"{version}\"\n")), "{name} must resolve to {version}: {package}");
|
||||
if let Some(source) = package.lines().find_map(|line| line.strip_prefix("source = ")) {
|
||||
assert!(source.contains("github.com/storytold/"), "{name} must come from the reviewed storytold fork once published, not {source}");
|
||||
assert!(
|
||||
source.split(|c: char| !c.is_ascii_hexdigit()).any(|part| part.len() == 40),
|
||||
"{name} must pin the fork's 40-character revision, not {source}"
|
||||
);
|
||||
}
|
||||
// A path patch has no `source =` in Cargo.lock. The local integration config is the only
|
||||
// allowed path source; a machine-local path must never be in the published manifest,
|
||||
// which the root-manifest assertion below checks. A path entry carries no remote identity
|
||||
// to verify, so this test does not claim the resolved code is the published fork.
|
||||
let manifest = std::fs::read_to_string(root.join("Cargo.toml")).expect("root Cargo.toml");
|
||||
assert!(!manifest.contains(&format!("{name} = {{ path = \"vendor/")), "vendor/{name} must not be a published path patch");
|
||||
package
|
||||
}
|
||||
|
||||
use pdfcraft_ui_egui::control::Endpoint;
|
||||
|
||||
fn endpoint() -> std::io::Result<Endpoint> {
|
||||
@@ -780,7 +848,7 @@ mod tests {
|
||||
/// graphics libraries at a time. The test threads otherwise run them together, and on
|
||||
/// FreeBSD's CI machine the test process then died with SIGSEGV, in about half the runs:
|
||||
/// the first device was still being set up when the second test began its own. The UI
|
||||
/// tests take turns the same way (`crates/ui-egui/tests/view.rs`). Hold it for the whole
|
||||
/// tests take turns the same way (`crates/ui-egui/tests/it/main.rs`). Hold it for the whole
|
||||
/// test (declared before the instance, so it's released after the device is dropped).
|
||||
static GPU: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
@@ -1038,28 +1106,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression test: the lockfile resolves egui-wgpu 0.37.0 through an allowed source, the root manifest
|
||||
/// does not path-patch the vendor copy, and that copy stays as provenance for the surface-fit patch.
|
||||
#[test]
|
||||
fn egui_wgpu_carries_the_surface_size_fit() {
|
||||
// Issue #577: egui-wgpu 0.36.2 configures a window's surface at the window's size, and
|
||||
fn vendor_provenance_egui_wgpu_surface_fit_identity() {
|
||||
// Issue #577: egui-wgpu configured a window's surface at the window's size, and
|
||||
// `Surface::configure` panics when that's beyond the device's `max_texture_dimension_2d`
|
||||
// (emilk/egui#8361). vendor/egui-wgpu fits it within the limit. A dependency bump that
|
||||
// resolves egui-wgpu from crates.io again, or a re-vendored copy without the patch, would
|
||||
// bring the crash back: re-apply the patch, or drop the copy once an egui release has a
|
||||
// fix (vendor/README.md).
|
||||
// (emilk/egui#8361). The reviewed egui 0.37 worktree carries E2 (`surface_fit`); the
|
||||
// behavioural test above exercises it. The old 0.36 vendor copy is retained for
|
||||
// provenance only and is no longer a published path patch, so reading it would not prove
|
||||
// what the app runs.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
|
||||
let egui_wgpu = lock.split("[[package]]").find(|p| p.contains("\nname = \"egui-wgpu\"\n")).expect("egui-wgpu is in Cargo.lock");
|
||||
assert!(!egui_wgpu.contains("\nsource = "), "egui-wgpu must resolve to vendor/egui-wgpu, not:{egui_wgpu}");
|
||||
// `surface_fit` is tested above; these keep it in the paths that size a surface.
|
||||
let painter = std::fs::read_to_string(root.join("vendor/egui-wgpu/src/winit.rs")).unwrap().replace("\r\n", "\n");
|
||||
for patch in [
|
||||
"let (width, height, render_scale) = surface_fit(window_width, window_height, max_side);",
|
||||
"let (fit_width, fit_height, _) = surface_fit(width, height, self.max_surface_side());",
|
||||
"pixels_per_point: pixels_per_point * surface_state.render_scale,",
|
||||
"old_state.window_width,\n old_state.window_height,",
|
||||
] {
|
||||
assert!(painter.contains(patch), "vendor/egui-wgpu lost its surface size patch: {patch}");
|
||||
}
|
||||
assert_window_stack_graph(&root, "egui-wgpu", "0.37.0");
|
||||
assert!(root.join("vendor/egui-wgpu/src/winit.rs").exists(), "the vendor copy and its provenance stay until the fork revision is pinned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1115,24 +1174,20 @@ mod tests {
|
||||
assert!(matches!(caught, Err(wgpu::Error::Validation { .. })), "outer: {caught:?}");
|
||||
}
|
||||
|
||||
/// Regression test: the lockfile resolves egui-wgpu 0.37.0 through an allowed source, the root manifest
|
||||
/// does not path-patch the vendor copy, and that copy stays as provenance for the catch-errors patch.
|
||||
#[test]
|
||||
fn egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error() {
|
||||
// Issue #519: `catch_errors` is tested above; this keeps it around the first configure of
|
||||
// every new window's surface, and its error reaching eframe as `WgpuError` (eframe then
|
||||
// returns `Error::Wgpu`, which `main` retries with OpenGL). Without it a failed configure
|
||||
// panics before the app is created, and the OpenGL retry never runs.
|
||||
fn vendor_provenance_egui_wgpu_catch_errors_identity() {
|
||||
// Issue #519: E3 (`catch_errors`) is tested above against a real device. The reviewed 0.37
|
||||
// worktree carries it around the first configure of every new window's surface, and its
|
||||
// error reaches eframe as `WgpuError` (eframe then returns `Error::Wgpu`, which `main`
|
||||
// retries with OpenGL). Without it a failed configure panics before the app is created.
|
||||
// `catch_errors` is exercised against a real device in the test above and below; the
|
||||
// graph check makes sure the app runs the reviewed 0.37 worktree (the retained vendor
|
||||
// copy is not read as proof of behaviour).
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
|
||||
let egui_wgpu = lock.split("[[package]]").find(|p| p.contains("\nname = \"egui-wgpu\"\n")).expect("egui-wgpu is in Cargo.lock");
|
||||
assert!(!egui_wgpu.contains("\nsource = "), "egui-wgpu must resolve to vendor/egui-wgpu, not:{egui_wgpu}");
|
||||
let painter = std::fs::read_to_string(root.join("vendor/egui-wgpu/src/winit.rs")).unwrap().replace("\r\n", "\n");
|
||||
let add_surface = painter.split("async fn add_surface(").nth(1).and_then(|s| s.split("\n fn ").next()).expect("add_surface");
|
||||
for patch in [
|
||||
"let installed = catch_errors(&device, || {\n self.install_surface(surface, viewport_id, size.width, size.height, false);\n })",
|
||||
"return Err(crate::WgpuError::ConfigureSurface(error));",
|
||||
] {
|
||||
assert!(add_surface.contains(patch), "vendor/egui-wgpu lost its surface configure patch: {patch}");
|
||||
}
|
||||
assert_window_stack_graph(&root, "egui-wgpu", "0.37.0");
|
||||
assert!(root.join("vendor/egui-wgpu/src/winit.rs").exists(), "the vendor copy and its provenance stay until the fork revision is pinned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1166,6 +1221,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression test: winit resolves to 0.30.13 without a published vendor path patch, the retained copy
|
||||
/// still carries the W1 Windows 11 monitor-scale fix, and its upstream base is recorded.
|
||||
#[test]
|
||||
fn winit_carries_the_windows_11_monitor_scale_fix() {
|
||||
// Issue #324: winit 0.30.13 as released nudges a window dragged onto a monitor with another
|
||||
@@ -1174,13 +1231,23 @@ mod tests {
|
||||
// dependency bump that resolves winit from crates.io again, or a re-vendored copy without
|
||||
// the patch, would silently bring the bug back: re-apply the patch, or drop the copy once a
|
||||
// winit 0.30 release has the fix (vendor/README.md).
|
||||
// W1 (and W2–W13) were audited against the reviewed winit worktree: the vendor rows in
|
||||
// `vendor/README.md` match the fork's PATCHES.md entries W1–W13. The vendor source is no
|
||||
// longer a published path patch, so this checks the actual graph, not the old copy.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
|
||||
let winit = lock.split("[[package]]").find(|p| p.contains("\nname = \"winit\"\n")).expect("winit is in Cargo.lock");
|
||||
assert!(!winit.contains("\nsource = "), "winit must resolve to vendor/winit, not:{winit}");
|
||||
let dpi_changed = std::fs::read_to_string(root.join("vendor/winit/src/platform_impl/windows/event_loop.rs")).unwrap();
|
||||
let patch = "if !WIN10_BUILD_VERSION.is_some_and(|build| build < 22000) {\n new_outer_rect = suggested_rect;";
|
||||
assert!(dpi_changed.contains(patch), "vendor/winit lost its WM_DPICHANGED patch");
|
||||
assert_window_stack_graph(&root, "winit", "0.30.13");
|
||||
let event_loop = std::fs::read_to_string(root.join("vendor/winit/src/platform_impl/windows/event_loop.rs")).unwrap();
|
||||
// The audited W1 hunk itself, not merely the file's presence: Windows 11 applies the
|
||||
// rect Windows suggests, while Windows 10 keeps the old adjustment.
|
||||
for marker in [
|
||||
"PdfCraft patch: from Windows 11 (build 22000) on, apply the rect Windows suggests",
|
||||
"if !WIN10_BUILD_VERSION.is_some_and(|build| build < 22000) {",
|
||||
"new_outer_rect = suggested_rect;",
|
||||
] {
|
||||
assert!(event_loop.contains(marker), "vendor/winit lost the W1 monitor-scale patch: {marker}");
|
||||
}
|
||||
let provenance = std::fs::read_to_string(root.join("vendor/winit/.cargo_vcs_info.json")).unwrap();
|
||||
assert!(provenance.contains("e9809ef54b18499bb4f2cac945719ecc2a61061b"), "vendor/winit keeps its upstream base provenance");
|
||||
}
|
||||
|
||||
const NVIDIA: (u32, u32) = (0x10de, 0x2684);
|
||||
@@ -1414,4 +1481,26 @@ mod tests {
|
||||
let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass="));
|
||||
assert_eq!(class, Some(super::APP_ID));
|
||||
}
|
||||
|
||||
// Regression test for #246: `eprintln!` panics when standard error is a broken pipe (a GUI
|
||||
// launch on Windows), and a panic inside the panic hook aborts the process. The start-up
|
||||
// path and the hook must write to standard error without it.
|
||||
#[test]
|
||||
fn start_up_and_the_panic_hook_never_use_eprintln() {
|
||||
let source = include_str!("main.rs");
|
||||
// Everything before the top-level test module is product code.
|
||||
let product = source.split("\n#[cfg(test)]\nmod tests {").next().unwrap_or(source);
|
||||
assert!(product.len() < source.len(), "found the end of the product code");
|
||||
let offenders: Vec<_> = product
|
||||
.lines()
|
||||
.enumerate()
|
||||
.filter(|(_, line)| !line.trim_start().starts_with("//") && line.contains("eprintln!"))
|
||||
.map(|(n, line)| format!("main.rs:{}: {}", n + 1, line.trim()))
|
||||
.collect();
|
||||
assert!(
|
||||
offenders.is_empty(),
|
||||
"`eprintln!` panics on a broken standard error pipe; use `log::warn!` or `write_fmt` on `stderr()` and ignore the error:\n{}",
|
||||
offenders.join("\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
//! Asks GitHub for the latest PdfCraft release (Help ▸ Check for updates, issue #28).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use pdfcraft_ui_egui::updates::{RELEASES_PAGE, Release};
|
||||
|
||||
const LATEST: &str = "https://api.github.com/repos/storytold/pdfcraft/releases/latest";
|
||||
|
||||
/// The latest release. The answer is untrusted: its size is capped, and only a page under
|
||||
/// [`RELEASES_PAGE`] is ever offered for download (anything else falls back to that list).
|
||||
pub fn latest_release() -> Result<Release, String> {
|
||||
let agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(Duration::from_secs(10)))
|
||||
.tls_config(ureq::tls::TlsConfig::builder().root_certs(os_roots()?).build())
|
||||
.build()
|
||||
.new_agent();
|
||||
let mut response = agent
|
||||
.get(LATEST)
|
||||
.header("Accept", "application/vnd.github+json")
|
||||
.header("User-Agent", concat!("PdfCraft/", env!("CARGO_PKG_VERSION")))
|
||||
// Read error statuses ourselves: a 403 from GitHub usually means its anonymous
|
||||
// rate limit ran out, and the retry time rides along in a response header.
|
||||
.config()
|
||||
.http_status_as_error(false)
|
||||
.build()
|
||||
.call()
|
||||
.map_err(|e| format!("couldn't reach GitHub ({e})"))?;
|
||||
let status = response.status().as_u16();
|
||||
if status == 403 {
|
||||
let reset = response.headers().get("x-ratelimit-reset").and_then(|v| v.to_str().ok());
|
||||
return Err(rate_limited(reset, now_unix()));
|
||||
}
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("couldn't reach GitHub (http status: {status})"));
|
||||
}
|
||||
let body = response.body_mut().with_config().limit(1 << 20).read_to_string().map_err(|e| format!("unreadable answer ({e})"))?;
|
||||
parse(&body)
|
||||
}
|
||||
|
||||
/// The certificate authorities the operating system trusts.
|
||||
fn os_roots() -> Result<ureq::tls::RootCerts, String> {
|
||||
let found = rustls_native_certs::load_native_certs();
|
||||
let certs: Vec<ureq::tls::Certificate<'static>> = found.certs.iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect();
|
||||
if certs.is_empty() {
|
||||
return Err("no trusted certificates found on this system".into());
|
||||
}
|
||||
Ok(ureq::tls::RootCerts::new_with_certs(&certs))
|
||||
}
|
||||
|
||||
/// The current Unix time in seconds (0 when the clock gives nothing usable).
|
||||
fn now_unix() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What to tell the user when GitHub answers 403: its anonymous quota (60 checks an hour,
|
||||
/// shared by everyone behind the same address) ran out. `reset` is the `x-ratelimit-reset`
|
||||
/// header, the Unix time the quota refills; `now` is the current Unix time. Anything
|
||||
/// surprising (no header, not a number, already past) falls back to asking for patience.
|
||||
fn rate_limited(reset: Option<&str>, now: u64) -> String {
|
||||
const FALLBACK: &str = "GitHub is limiting update checks for now (shared hourly quota); try again later";
|
||||
let wait = reset.and_then(|r| r.trim().parse::<u64>().ok()).and_then(|reset| reset.checked_sub(now)).filter(|&wait| wait > 0);
|
||||
match wait {
|
||||
Some(wait) => {
|
||||
let minutes = wait.div_ceil(60).max(1);
|
||||
let plural = if minutes == 1 { "" } else { "s" };
|
||||
format!("GitHub is limiting update checks for now (shared hourly quota); try again in about {minutes} minute{plural}")
|
||||
}
|
||||
None => FALLBACK.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(body: &str) -> Result<Release, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(body).map_err(|e| format!("unreadable answer ({e})"))?;
|
||||
let version = v["tag_name"].as_str().filter(|t| !t.is_empty() && t.len() <= 64).ok_or("no release found")?.to_string();
|
||||
let url = v["html_url"]
|
||||
.as_str()
|
||||
.filter(|u| u.strip_prefix(RELEASES_PAGE).is_some_and(|rest| rest.starts_with('/') && !rest.contains(['?', '#', '\\'])))
|
||||
.unwrap_or(RELEASES_PAGE)
|
||||
.to_string();
|
||||
Ok(Release { version, url })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn answers_are_read_and_only_our_release_pages_are_offered() {
|
||||
let r = parse(r#"{"tag_name":"v0.2.0","html_url":"https://github.com/storytold/pdfcraft/releases/tag/v0.2.0"}"#).unwrap();
|
||||
assert_eq!(r, Release { version: "v0.2.0".into(), url: "https://github.com/storytold/pdfcraft/releases/tag/v0.2.0".into() });
|
||||
for elsewhere in ["https://example.com/pdfcraft.exe", "https://github.com/storytold/pdfcraft/releases.evil/x", "javascript:alert(1)"] {
|
||||
let r = parse(&format!(r#"{{"tag_name":"v9.9.9","html_url":"{elsewhere}"}}"#)).unwrap();
|
||||
assert_eq!(r.url, RELEASES_PAGE, "{elsewhere}");
|
||||
}
|
||||
assert!(parse(r#"{"message":"Not Found"}"#).is_err());
|
||||
assert!(parse("<html>").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limit_messages_name_the_wait() {
|
||||
let limited = "GitHub is limiting update checks for now (shared hourly quota); try again in about 20 minutes";
|
||||
assert_eq!(rate_limited(Some("1800001200"), 1800000000), limited);
|
||||
// Rounds up: 61 seconds out reads as 2 minutes.
|
||||
assert_eq!(
|
||||
rate_limited(Some("1800000061"), 1800000000),
|
||||
"GitHub is limiting update checks for now (shared hourly quota); try again in about 2 minutes"
|
||||
);
|
||||
assert_eq!(
|
||||
rate_limited(Some("1800000060"), 1800000000),
|
||||
"GitHub is limiting update checks for now (shared hourly quota); try again in about 1 minute"
|
||||
);
|
||||
// No header, not a number, or already past: ask for patience instead of a time.
|
||||
let later = "GitHub is limiting update checks for now (shared hourly quota); try again later";
|
||||
for bad in [None, Some(""), Some("soon"), Some("1799999999"), Some("1800000000")] {
|
||||
assert_eq!(rate_limited(bad, 1800000000), later);
|
||||
}
|
||||
}
|
||||
|
||||
/// Live: asks GitHub over TLS with the OS's roots (`cargo test -p pdfcraft -- --ignored`).
|
||||
#[test]
|
||||
#[ignore = "needs network access"]
|
||||
fn github_answers_with_the_latest_release() {
|
||||
let r = latest_release().unwrap();
|
||||
assert!(pdfcraft_ui_egui::updates::is_newer(&r.version, "0.0.0"), "{r:?}");
|
||||
assert!(r.url.starts_with(RELEASES_PAGE), "{r:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! `--help`, `-h` and `--version` print and exit without opening a window (#4076), so a script that
|
||||
//! calls them returns.
|
||||
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft");
|
||||
|
||||
/// Run the app with `args`, failing if it is still running after 60 s (it opened its window).
|
||||
fn run(args: &[&str], stdout: Stdio) -> Output {
|
||||
let mut child = Command::new(BIN).args(args).stdin(Stdio::null()).stdout(stdout).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("pdfcraft {args:?} did not exit: it started the app instead");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_and_exits() {
|
||||
for flag in ["--help", "-h"] {
|
||||
let out = run(&[flag], Stdio::piped());
|
||||
assert!(out.status.success(), "{flag}: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(stdout.starts_with("Usage: pdfcraft [options] [files…]"), "{flag}: {stdout}");
|
||||
assert!(stdout.contains("pdfcraft-cli"), "{flag}: points scripts to the CLI: {stdout}");
|
||||
}
|
||||
// Wherever it is on the command line, and with files named.
|
||||
let out = run(&["missing.pdf", "--help"], Stdio::piped());
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("Usage:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_prints_the_version_and_exits() {
|
||||
let out = run(&["--version"], Stdio::piped());
|
||||
assert!(out.status.success(), "{:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("pdfcraft "), "{}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
|
||||
/// A standard output that can't be written (here a full device) ends the run normally: `println!`
|
||||
/// would panic and exit 101.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn help_and_version_survive_an_unwritable_stdout() {
|
||||
for flag in ["--help", "--version"] {
|
||||
let full = std::fs::OpenOptions::new().write(true).open("/dev/full").unwrap();
|
||||
let out = run(&[flag], Stdio::from(full));
|
||||
assert!(out.status.success(), "{flag}: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
// Compile winit's scroll policy against its real event type, without a compositor. The vendored
|
||||
// source (`winit_wayland_scroll`) names it as `crate::event`.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod event {
|
||||
pub use winit::event::TouchPhase;
|
||||
}
|
||||
|
||||
mod vendor_graph;
|
||||
mod winit_macos_emoji_picker;
|
||||
mod winit_macos_ime_commit;
|
||||
mod winit_macos_ime_discard;
|
||||
mod winit_macos_korean_first_key;
|
||||
mod winit_macos_korean_space;
|
||||
mod winit_macos_title_bar_drag;
|
||||
mod winit_wayland_scroll;
|
||||
mod winit_wayland_text_input;
|
||||
mod winit_windows_hidden_maximized;
|
||||
mod winit_windows_ime_cursor;
|
||||
mod winit_x11_dpi;
|
||||
mod winit_x11_ime_focus;
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Dependency-graph verification for the egui 0.37 window stack.
|
||||
//!
|
||||
//! The twelve `winit_*` modules next to this one read the retained `vendor/winit` /
|
||||
//! `vendor/egui-wgpu` copies. They are provenance for W1–W13 and E2+E3, not proof of what the app
|
||||
//! runs: the root manifest pins both crates to immutable storytold git revisions, and the retained
|
||||
//! copies are not path patches. These tests check the resolved graph and the retained evidence
|
||||
//! instead of treating the copies as the runtime source. The winit fork's own W17 tests own patch
|
||||
//! behaviour.
|
||||
|
||||
/// Return the workspace root above the PdfCraft app crate.
|
||||
fn root() -> std::path::PathBuf {
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
||||
}
|
||||
|
||||
/// Every `[[package]]` block in `Cargo.lock` whose `name` is exactly `name`.
|
||||
fn locked_packages(name: &str) -> Vec<String> {
|
||||
let lock = std::fs::read_to_string(root().join("Cargo.lock")).expect("Cargo.lock");
|
||||
let needle = format!("name = \"{name}\"");
|
||||
lock.split("[[package]]").filter(|package| package.lines().any(|line| line.trim() == needle.as_str())).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// The one resolved package called `name`. A duplicate name is a lockfile problem, not something
|
||||
/// to resolve by taking the first match.
|
||||
fn locked(name: &str) -> String {
|
||||
let mut packages = locked_packages(name);
|
||||
assert_eq!(packages.len(), 1, "Cargo.lock must contain exactly one `{name}` package, found {}", packages.len());
|
||||
packages.remove(0)
|
||||
}
|
||||
|
||||
/// The resolved package must be the exact canonical storytold git source at the reviewed
|
||||
/// 40-character revision, including the `Cargo.lock` URL and fragment. A path source (no `source`
|
||||
/// line) is refused: it would make the graph depend on a developer's checkout. A published path
|
||||
/// patch is refused as well.
|
||||
fn assert_resolved(name: &str, version: &str, url: &str, rev: &str) {
|
||||
let package = locked(name);
|
||||
let expected_version = format!("version = \"{version}\"");
|
||||
assert!(package.lines().any(|line| line.trim() == expected_version.as_str()), "{name} must resolve to {version}: {package}");
|
||||
let sources: Vec<&str> = package.lines().filter_map(|line| line.trim().strip_prefix("source = ")).collect();
|
||||
assert_eq!(sources.len(), 1, "{name} must have exactly one `source` in Cargo.lock; a local path source is not accepted: {package}");
|
||||
let expected_source = format!("\"git+{url}?rev={rev}#{rev}\"");
|
||||
assert_eq!(sources[0], expected_source.as_str(), "{name} must resolve to the exact canonical git URL, revision and fragment, not {}", sources[0]);
|
||||
|
||||
let manifest = std::fs::read_to_string(root().join("Cargo.toml")).expect("root Cargo.toml");
|
||||
assert!(!manifest.contains(&format!("{name} = {{ path = \"vendor/")), "vendor/{name} cannot stay a published path patch");
|
||||
}
|
||||
|
||||
/// Regression test: the resolved window stack points at the reviewed forks and the retained vendor provenance
|
||||
/// files remain.
|
||||
#[test]
|
||||
fn vendor_provenance_window_stack_graph_is_resolved() {
|
||||
assert_resolved("winit", "0.30.13", "https://github.com/storytold/winit.git", "a517b3846ee8457d84ee4975110bfda6797c44dc");
|
||||
assert_resolved("egui-wgpu", "0.37.0", "https://github.com/storytold/egui.git", "6d518fc799681571963842f95b55a6b68431b15a");
|
||||
// Retained provenance: the audited copies and their recorded W1–W13 / E2+E3 rows.
|
||||
let readme = std::fs::read_to_string(root().join("vendor/README.md")).expect("vendor/README.md");
|
||||
for marker in ["W1–W13", "surface_fit", "catch_errors", "e9809ef54b18499bb4f2cac945719ecc2a61061b"] {
|
||||
assert!(readme.contains(marker), "vendor/README.md lost window-stack provenance: {marker}");
|
||||
}
|
||||
let vcs = std::fs::read_to_string(root().join("vendor/winit/.cargo_vcs_info.json")).expect("vendor/winit provenance");
|
||||
assert!(vcs.contains("e9809ef54b18499bb4f2cac945719ecc2a61061b"), "vendor/winit keeps its upstream base");
|
||||
for path in ["vendor/winit/src/platform_impl", "vendor/egui-wgpu/src/winit.rs"] {
|
||||
assert!(root().join(path).exists(), "retain {path} as provenance for the pinned fork");
|
||||
}
|
||||
}
|
||||
|
||||
/// Renderer, security and PostScript vendors are unrelated to the UI port and must stay path patches.
|
||||
#[test]
|
||||
fn renderer_and_security_vendors_remain() {
|
||||
let manifest = std::fs::read_to_string(root().join("Cargo.toml")).expect("root Cargo.toml");
|
||||
for vendor in [
|
||||
"vendor/hayro",
|
||||
"vendor/hayro-interpret",
|
||||
"vendor/hayro-syntax",
|
||||
"vendor/hayro-cmap",
|
||||
"vendor/hayro-jbig2",
|
||||
"vendor/hayro-postscript",
|
||||
"vendor/lopdf",
|
||||
"vendor/vello_common",
|
||||
] {
|
||||
assert!(manifest.contains(&format!("path = \"{vendor}\"")), "{vendor} must stay a path patch");
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -1,7 +1,11 @@
|
||||
//! vendor/winit patch (8) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (8) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit commits text inserted outside a key press and leaves `selectedRange`
|
||||
/// unmarked.
|
||||
#[test]
|
||||
fn winit_commits_macos_text_inserted_outside_a_key_press() {
|
||||
fn vendor_provenance_winit_macos_text_inserted_outside_a_key_press() {
|
||||
// The macOS emoji picker inserts its text with `insertText` outside any key press and without
|
||||
// a composition. winit 0.30.13 reports `insertText` only as part of a key press or a
|
||||
// composition, so an emoji picked into a PdfCraft text field was dropped. vendor/winit commits
|
||||
+6
-2
@@ -1,7 +1,11 @@
|
||||
//! vendor/winit patch (6) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (6) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit commits a composition that ended without marked text and keeps the
|
||||
/// marked-text underline.
|
||||
#[test]
|
||||
fn winit_commits_macos_compositions_that_end_without_marked_text() {
|
||||
fn vendor_provenance_winit_macos_compositions_that_end_without_marked_text() {
|
||||
// winit 0.30.13 treats `insertText` as an IME commit only while marked text is left. Input
|
||||
// methods that end a composition with `unmarkText` first lost the committed text, and Apple
|
||||
// Korean, which clears its marked text before inserting the key typed after a syllable (`한`
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (7) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (7) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: disallowing IME in the vendored winit discards the macOS input method's marked text.
|
||||
#[test]
|
||||
fn winit_discards_the_macos_composition_when_ime_is_disallowed() {
|
||||
fn vendor_provenance_winit_discards_the_macos_composition_when_ime_is_disallowed() {
|
||||
// egui disallows IME when a text field loses focus. winit 0.30.13 then forgets the marked text
|
||||
// but doesn't tell the input method, which keeps the composition and continues it once IME is
|
||||
// allowed again: the abandoned syllable comes back in the next field. vendor/winit calls
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (10) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (10) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit retries the first Apple Korean key once so it starts a composition.
|
||||
#[test]
|
||||
fn winit_retries_the_first_apple_korean_key_once() {
|
||||
fn vendor_provenance_winit_retries_the_first_apple_korean_key_once() {
|
||||
// On the first key in a freshly started app, Apple Korean can answer with `insertText` and the
|
||||
// raw compatibility jamo instead of starting a composition, so typing g k s in PdfCraft gave
|
||||
// ㅎㅏㄴ instead of 한. vendor/winit interprets that one key again before sending it to the
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (9) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (9) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit sends a key committed through macOS IME only once.
|
||||
#[test]
|
||||
fn winit_sends_a_key_committed_through_macos_ime_only_once() {
|
||||
fn vendor_provenance_winit_sends_a_key_committed_through_macos_ime_only_once() {
|
||||
// Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`,
|
||||
// `insertText(" ")` and `setMarkedText("")`. The last call resets winit 0.30.13's IME state, so
|
||||
// the key went to the app both as `Ime::Commit(" ")` and as `KeyboardInput` with text " ", and
|
||||
+6
-2
@@ -1,7 +1,11 @@
|
||||
//! vendor/winit patch (12) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (12) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit lets title-bar drags reach the app while the empty tab strip still
|
||||
/// moves the window.
|
||||
#[test]
|
||||
fn winit_lets_macos_title_bar_drags_reach_the_app() {
|
||||
fn vendor_provenance_winit_lets_macos_title_bar_drags_reach_the_app() {
|
||||
// On macOS the tab strip is the title bar: a transparent title bar over a full-size content
|
||||
// view. NSView answers YES to `mouseDownCanMoveWindow` for a view that isn't opaque, so AppKit
|
||||
// moved the whole window for a drag that began on a document tab, and tabs could not be
|
||||
+21
-10
@@ -1,13 +1,12 @@
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, RawInput, TouchPhase, vec2};
|
||||
use wayland_client::protocol::wl_pointer::AxisSource;
|
||||
|
||||
// Compile the production policy against winit's real event type, without a compositor.
|
||||
mod event {
|
||||
pub use winit::event::TouchPhase;
|
||||
}
|
||||
#[path = "../../../vendor/winit/src/platform_impl/linux/wayland/seat/pointer/scroll.rs"]
|
||||
use crate::event;
|
||||
#[path = "../../../../vendor/winit/src/platform_impl/linux/wayland/seat/pointer/scroll.rs"]
|
||||
mod scroll;
|
||||
|
||||
fn egui_phase(phase: event::TouchPhase) -> TouchPhase {
|
||||
@@ -19,6 +18,7 @@ fn egui_phase(phase: event::TouchPhase) -> TouchPhase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run three wheel frames through egui and return each frame's zoom and smooth-scroll deltas.
|
||||
fn wheel_trace(source: AxisSource, discrete: bool) -> Vec<(f32, egui::Vec2)> {
|
||||
let ctx = egui::Context::default();
|
||||
let mut previous = event::TouchPhase::Ended;
|
||||
@@ -30,7 +30,13 @@ fn wheel_trace(source: AxisSource, discrete: bool) -> Vec<(f32, egui::Vec2)> {
|
||||
let (unit, dy) = if discrete { (MouseWheelUnit::Line, 1.0) } else { (MouseWheelUnit::Point, 24.0) };
|
||||
let input = RawInput {
|
||||
time: Some(frame as f64 / 60.0),
|
||||
events: vec![Event::MouseWheel { unit, delta: vec2(0.0, dy), phase: egui_phase(phase), modifiers }],
|
||||
events: vec![Event::MouseWheel {
|
||||
unit,
|
||||
delta: vec2(0.0, dy),
|
||||
phase: egui_phase(phase),
|
||||
modifiers,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
ctx.run_ui(input, |ui| seen.push(ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta)))).textures_delta.clear();
|
||||
@@ -38,8 +44,10 @@ fn wheel_trace(source: AxisSource, discrete: bool) -> Vec<(f32, egui::Vec2)> {
|
||||
seen
|
||||
}
|
||||
|
||||
/// Regression test: releasing Ctrl after a pixel-wheel zoom makes the next wheel event scroll instead of
|
||||
/// zooming.
|
||||
#[test]
|
||||
fn releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
|
||||
fn vendor_provenance_releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
|
||||
for source in [AxisSource::Wheel, AxisSource::WheelTilt, AxisSource::Continuous] {
|
||||
let seen = wheel_trace(source, false);
|
||||
assert!(seen[1].0 > 1.0, "Ctrl must zoom: {source:?}");
|
||||
@@ -48,16 +56,18 @@ fn releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression test: discrete wheels follow the modifiers of the current event, just like pixel wheels.
|
||||
#[test]
|
||||
fn discrete_wheels_still_follow_current_modifiers() {
|
||||
fn vendor_provenance_discrete_wheels_still_follow_current_modifiers() {
|
||||
let seen = wheel_trace(AxisSource::Wheel, true);
|
||||
assert!(seen[1].0 > 1.0);
|
||||
assert_eq!(seen[2].0, 1.0);
|
||||
assert!(seen[2].1.y > 0.0);
|
||||
}
|
||||
|
||||
/// Regression test: a finger gesture keeps its Ctrl zoom through momentum until the gesture ends.
|
||||
#[test]
|
||||
fn finger_gestures_keep_their_modifier_until_the_gesture_ends() {
|
||||
fn vendor_provenance_finger_gestures_keep_their_modifier_until_the_gesture_ends() {
|
||||
// A finger scroll's momentum may arrive after Ctrl is released.
|
||||
let seen = wheel_trace(AxisSource::Finger, false);
|
||||
assert!(seen[1].0 > 1.0);
|
||||
@@ -67,8 +77,9 @@ fn finger_gestures_keep_their_modifier_until_the_gesture_ends() {
|
||||
assert_eq!(scroll::phase(event::TouchPhase::Ended, Some(AxisSource::Finger), false, false), event::TouchPhase::Started);
|
||||
}
|
||||
|
||||
/// Regression test: wheel sources without a phase keep the existing start, move and end policy.
|
||||
#[test]
|
||||
fn unknown_sources_keep_the_existing_phase_policy() {
|
||||
fn vendor_provenance_unknown_sources_keep_the_existing_phase_policy() {
|
||||
assert_eq!(scroll::phase(event::TouchPhase::Ended, None, false, false), event::TouchPhase::Started);
|
||||
assert_eq!(scroll::phase(event::TouchPhase::Started, None, false, false), event::TouchPhase::Moved);
|
||||
assert_eq!(scroll::phase(event::TouchPhase::Ended, None, true, false), event::TouchPhase::Moved);
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (2) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (2) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit keeps a Wayland seat's text input until the seat itself is removed.
|
||||
#[test]
|
||||
fn winit_keeps_the_wayland_text_input_until_the_seat_goes() {
|
||||
fn vendor_provenance_winit_keeps_the_wayland_text_input_until_the_seat_goes() {
|
||||
// winit 0.30.13 destroys a Wayland seat's text input whenever the seat loses any capability (a
|
||||
// touch screen or tablet unplugged, a remote-desktop session ending) and recreates it only when
|
||||
// a capability is added, so IME stops working in a running PdfCraft until it is restarted.
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (4) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (4) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit maximizes a hidden Windows window only when it is shown.
|
||||
#[test]
|
||||
fn winit_maximizes_a_hidden_windows_window_only_when_it_is_shown() {
|
||||
fn vendor_provenance_winit_maximizes_a_hidden_windows_window_only_when_it_is_shown() {
|
||||
// eframe creates PdfCraft's window hidden, restores the saved maximized state and shows the
|
||||
// window once its first frame is drawn. winit 0.30.13 applies the maximized state with
|
||||
// `ShowWindow(SW_MAXIMIZE)`, which shows a hidden window, so a window closed maximized came back
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (3) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (3) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit reads the Windows IME cursor only when the composition reports it.
|
||||
#[test]
|
||||
fn winit_reads_the_windows_ime_cursor_only_when_it_is_reported() {
|
||||
fn vendor_provenance_winit_reads_the_windows_ime_cursor_only_when_it_is_reported() {
|
||||
// winit 0.30.13 reads `GCS_CURSORPOS` for every composition without a target clause, whether
|
||||
// or not `WM_IME_COMPOSITION` says the IME set it. The Microsoft Korean IME never sets it, so
|
||||
// the composition's cursor read as 0, before the syllable being composed. vendor/winit puts it
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
/// Regression test: the vendored winit keeps the X11 server-DPI fallback and the desktop file does not
|
||||
/// override scaling.
|
||||
#[test]
|
||||
fn winit_carries_the_x11_server_dpi_fallback() {
|
||||
fn vendor_provenance_winit_carries_the_x11_server_dpi_fallback() {
|
||||
// The behavior tests live beside the policy in winit (util::randr::tests).
|
||||
// This guards PdfCraft's vendored copy, which workspace tests do not test itself.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
//! vendor/winit patch (5) (vendor/README.md).
|
||||
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
|
||||
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
|
||||
//! Retained vendor provenance for winit patch (5) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
|
||||
|
||||
/// Regression test: the vendored winit focuses the X11 input context it replaces.
|
||||
#[test]
|
||||
fn winit_focuses_the_x11_input_context_it_replaces() {
|
||||
fn vendor_provenance_winit_focuses_the_x11_input_context_it_replaces() {
|
||||
// egui allows IME when a text field gains focus and disallows it when the field loses focus.
|
||||
// On X11, winit 0.30.13 replaces the window's input context each time and leaves focusing the
|
||||
// new one to the next focus event, which never comes while PdfCraft's window keeps the focus:
|
||||
+49
-49
@@ -14,27 +14,27 @@
|
||||
(highlight, sticky note, stamp, ...), so annotation geometry follows the layout.
|
||||
-->
|
||||
<style>
|
||||
@font-face { font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
|
||||
@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
|
||||
@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
|
||||
@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
|
||||
@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
|
||||
@font-face { font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
|
||||
@font-face { font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
|
||||
@font-face { font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
|
||||
@font-face { font-display: swap; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
|
||||
@font-face { font-display: swap; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
|
||||
@font-face { font-display: swap; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
|
||||
@font-face { font-display: swap; font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
|
||||
@font-face { font-display: swap; font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
|
||||
@font-face { font-display: swap; font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
|
||||
|
||||
@page { size: Letter; margin: 0; }
|
||||
|
||||
@@ -401,12 +401,12 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
</div>
|
||||
<h3>The families in this specimen</h3>
|
||||
<div class="families">
|
||||
<div><span style="font-family:'PC Playfair'">Ag</span><b>Playfair Display</b>Display</div>
|
||||
<div><span style="font-family:'PC Garamond'">Ag</span><b>EB Garamond</b>Body text</div>
|
||||
<div><span style="font-family:'PC Inter';font-weight:500">Ag</span><b>Inter</b>Labels</div>
|
||||
<div><span style="font-family:'PC Mono'">Ag</span><b>JetBrains Mono</b>Code</div>
|
||||
<div><span style="font-family:'PC Vibes'">Ag</span><b>Great Vibes</b>Script</div>
|
||||
<div><span style="font-family:'PC Math'">∑x</span><b>STIX Two Math</b>Mathematics</div>
|
||||
<div><span style="font-family:'PC Playfair', serif">Ag</span><b>Playfair Display</b>Display</div>
|
||||
<div><span style="font-family:'PC Garamond', serif">Ag</span><b>EB Garamond</b>Body text</div>
|
||||
<div><span style="font-family:'PC Inter', sans-serif;font-weight:500">Ag</span><b>Inter</b>Labels</div>
|
||||
<div><span style="font-family:'PC Mono', monospace">Ag</span><b>JetBrains Mono</b>Code</div>
|
||||
<div><span style="font-family:'PC Vibes', cursive">Ag</span><b>Great Vibes</b>Script</div>
|
||||
<div><span style="font-family:'PC Math', math">∑x</span><b>STIX Two Math</b>Mathematics</div>
|
||||
</div>
|
||||
<div class="folio"><span>Foreword</span><b>ii</b></div>
|
||||
</section>
|
||||
@@ -449,7 +449,7 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
<tr><td class="tag">onum</td><td class="lbl">Old-style figures</td><td class="off" style="font-feature-settings:'lnum' 1">Since 1885: 3,467,920</td><td class="on" style="font-feature-settings:'onum' 1">Since 1885: 3,467,920</td></tr>
|
||||
<tr><td class="tag">frac</td><td class="lbl">Fractions</td><td class="off" style="font-family:var(--ui)">1/2 cup, 3/4 inch, 7/8</td><td class="on" style="font-family:var(--ui);font-feature-settings:'frac' 1">1/2 cup, 3/4 inch, 7/8</td></tr>
|
||||
<tr><td class="tag">swsh</td><td class="lbl">Swash capitals</td><td class="off" style="font-style:italic">The Quiet River</td><td class="on" style="font-style:italic;font-feature-settings:'swsh' 1">The Quiet River</td></tr>
|
||||
<tr><td class="tag">ss01</td><td class="lbl">Stylistic set 1</td><td class="off" style="font-family:'PC Inter'">a 1 4 6 9 G ?</td><td class="on" style="font-family:'PC Inter';font-feature-settings:'ss01' 1">a 1 4 6 9 G ?</td></tr>
|
||||
<tr><td class="tag">ss01</td><td class="lbl">Stylistic set 1</td><td class="off" style="font-family:'PC Inter', sans-serif">a 1 4 6 9 G ?</td><td class="on" style="font-family:'PC Inter', sans-serif;font-feature-settings:'ss01' 1">a 1 4 6 9 G ?</td></tr>
|
||||
<tr><td class="tag">kern</td><td class="lbl">Kerning</td><td class="off" style="font-kerning:none;font-family:var(--sans)">AVATAR Type Wave</td><td class="on" style="font-kerning:normal;font-family:var(--sans)">AVATAR Type Wave</td></tr>
|
||||
<tr><td class="tag">tnum</td><td class="lbl">Tabular figures</td><td class="off" style="font-family:var(--ui);font-feature-settings:'pnum' 1">1111 / 8888</td><td class="on" style="font-family:var(--ui);font-feature-settings:'tnum' 1">1111 / 8888</td></tr>
|
||||
</table>
|
||||
@@ -519,9 +519,9 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
<p class="dek">A short greeting — roughly, “every letter deserves a good home” — in writing systems that need bidirectional layout, contextual shaping, reordering and vertical setting.</p>
|
||||
<div style="display:grid;grid-template-columns:1fr 1in;gap:16pt">
|
||||
<div class="scripts">
|
||||
<div class="sc" lang="ar" dir="rtl"><div class="nm" dir="ltr">Arabic <i>RTL · joining</i></div><div class="tx" style="font-family:'PC Amiri'">لكل حرف بيت</div><div class="en" dir="ltr">Amiri</div></div>
|
||||
<div class="sc" lang="ar" dir="rtl"><div class="nm" dir="ltr">Arabic <i>RTL · joining</i></div><div class="tx" style="font-family:'PC Amiri', serif">لكل حرف بيت</div><div class="en" dir="ltr">Amiri</div></div>
|
||||
<div class="sc" lang="he" dir="rtl"><div class="nm" dir="ltr">Hebrew <i>RTL</i></div><div class="tx" style="font-family:'PC Hebrew',sans-serif">לכל אות יש בית טוב</div><div class="en" dir="ltr">Noto Sans Hebrew</div></div>
|
||||
<div class="sc" lang="hi"><div class="nm">Devanagari <i>conjuncts</i></div><div class="tx" style="font-family:'PC Devanagari'">हर अक्षर का घर</div><div class="en">Noto Sans Devanagari</div></div>
|
||||
<div class="sc" lang="hi"><div class="nm">Devanagari <i>conjuncts</i></div><div class="tx" style="font-family:'PC Devanagari', sans-serif">हर अक्षर का घर</div><div class="en">Noto Sans Devanagari</div></div>
|
||||
<div class="sc" lang="th"><div class="nm">Thai <i>no spaces</i></div><div class="tx" style="font-family:'PC Thai',sans-serif">ทุกอักษรมีบ้าน</div><div class="en">Noto Sans Thai</div></div>
|
||||
<div class="sc" lang="el"><div class="nm">Greek <i>polytonic</i></div><div class="tx" style="font-family:'PC Garamond',serif">Κάθε γράμμα ἔχει σπίτι</div><div class="en">EB Garamond</div></div>
|
||||
<div class="sc" lang="ru"><div class="nm">Cyrillic</div><div class="tx" style="font-family:'PC Garamond',serif">Каждой букве — дом</div><div class="en">EB Garamond</div></div>
|
||||
@@ -541,7 +541,7 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
</div>
|
||||
|
||||
<h3>Mixed direction in one line</h3>
|
||||
<p style="font-size:12pt;margin:0">The word <span lang="ar" style="font-family:'PC Amiri'">كتاب</span> means “book”, and <span lang="he" style="font-family:'PC Hebrew'">ספר</span> does too — the bidi algorithm keeps each run in its own direction while the sentence stays left-to-right, even across numbers like <span lang="ar" style="font-family:'PC Amiri'">٣٤٥</span> and 345.</p>
|
||||
<p style="font-size:12pt;margin:0">The word <span lang="ar" style="font-family:'PC Amiri', serif">كتاب</span> means “book”, and <span lang="he" style="font-family:'PC Hebrew', serif">ספר</span> does too — the bidi algorithm keeps each run in its own direction while the sentence stays left-to-right, even across numbers like <span lang="ar" style="font-family:'PC Amiri', serif">٣٤٥</span> and 345.</p>
|
||||
|
||||
<h3>Colour emoji</h3>
|
||||
<div class="emoji">📄🖋️🎨📐🔍🌍🧮✅🦀📎</div>
|
||||
@@ -598,11 +598,11 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
<p class="dek">Nine small plates, each exercising one piece of the PDF imaging model.</p>
|
||||
<div class="gfx">
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
|
||||
<svg role="img" aria-label="Axial shading: three-stop linear gradient" viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
|
||||
<figcaption class="caption"><b>Axial shading</b> · three-stop linear gradient</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
|
||||
<svg role="img" aria-label="Radial shading: off-centre focal point" viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
|
||||
<figcaption class="caption"><b>Radial shading</b> · off-centre focal point</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
@@ -614,31 +614,31 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
<figcaption class="caption"><b>Screen</b> · additive light, /BM /Screen</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
|
||||
<svg role="img" aria-label="Clipping path: glyph outlines as a clip" viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
|
||||
<line x1="0" y1="10" x2="160" y2="130"/><line x1="0" y1="40" x2="160" y2="160"/><line x1="0" y1="-20" x2="160" y2="100"/><line x1="0" y1="-50" x2="160" y2="70"/></g></g></svg>
|
||||
<figcaption class="caption"><b>Clipping path</b> · glyph outlines as a clip</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
|
||||
<svg role="img" aria-label="Soft mask: luminosity gradient fades artwork" viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
|
||||
<figcaption class="caption"><b>Soft mask</b> · luminosity gradient fades artwork</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
|
||||
<svg role="img" aria-label="Dash patterns: caps, joins and phase" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
|
||||
<figcaption class="caption"><b>Dash patterns</b> · caps, joins and phase</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
|
||||
<svg role="img" aria-label="Tiling patterns: checks and rotated hatch" viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
|
||||
<figcaption class="caption"><b>Tiling patterns</b> · checks and rotated hatch</figcaption>
|
||||
</figure>
|
||||
<figure>
|
||||
<svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
|
||||
<svg role="img" aria-label="Fill rules: even-odd pentagram at 45% opacity" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
|
||||
<path id="star" d="M0 -46 L13 -14 L46 -14 L19 6 L29 40 L0 20 L-29 40 L-19 6 L-46 -14 L-13 -14 Z" stroke="#f2c14e" fill="#f2c14e" fill-opacity="0.25" fill-rule="evenodd"/>
|
||||
<path d="M0 -46 L27 37 L-44 -14 L44 -14 L-27 37 Z" stroke="#e4572e" fill="#e4572e" fill-opacity="0.45" fill-rule="evenodd"/></g></g></svg>
|
||||
<figcaption class="caption"><b>Fill rules</b> · even-odd pentagram, 45% opacity</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
<div class="rule"></div>
|
||||
<svg viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
|
||||
<svg role="img" aria-label="Blend spectrum: multiplied gradient bands" viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
|
||||
<defs><linearGradient id="spec" x1="0" x2="1"><stop offset="0" stop-color="#16213b"/><stop offset="0.25" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="0.75" stop-color="#e9a100"/><stop offset="1" stop-color="#e4572e"/></linearGradient></defs>
|
||||
<g style="mix-blend-mode:multiply">
|
||||
<path d="M0 80 C 80 10, 160 110, 260 50 S 440 20, 520 70 L520 110 L0 110Z" fill="url(#spec)" opacity="0.85"/>
|
||||
@@ -789,16 +789,16 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
|
||||
</div>
|
||||
<div class="canvas">
|
||||
<span class="lab" style="left:10pt;top:8pt">Review canvas</span>
|
||||
<a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">.</a>
|
||||
<a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">.</a>
|
||||
<a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">.</a>
|
||||
<a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">.</a>
|
||||
<a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">.</a>
|
||||
<a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">.</a>
|
||||
<a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">.</a>
|
||||
<a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">.</a>
|
||||
<a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">.</a>
|
||||
<a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">.</a>
|
||||
<a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">freetext</a>
|
||||
<a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">note</a>
|
||||
<a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">attach</a>
|
||||
<a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">square</a>
|
||||
<a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">circle</a>
|
||||
<a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">polygon</a>
|
||||
<a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">polyline</a>
|
||||
<a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">line</a>
|
||||
<a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">ink</a>
|
||||
<a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">stamp</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="folio"><span>Review & Markup</span><b>9</b></div>
|
||||
|
||||
@@ -173,3 +173,10 @@ sync_github_name = true
|
||||
|
||||
[people.amoisttowe1]
|
||||
real_name = "Nick Nyssen"
|
||||
|
||||
[people.agent-reed]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
+133
-47
@@ -4,7 +4,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfcraft_content::Matrix;
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, PdfString, Stream};
|
||||
|
||||
/// A Figure element (after the role map).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -23,6 +23,8 @@ pub enum AltError {
|
||||
Untagged,
|
||||
#[error("object {0} is not a figure")]
|
||||
NotAFigure(u32),
|
||||
#[error("the page has more content than can be edited")]
|
||||
TooLarge,
|
||||
#[error("{0}")]
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
}
|
||||
@@ -48,6 +50,8 @@ pub enum ArtifactError {
|
||||
AmbiguousParent,
|
||||
#[error("couldn't update the parent tree: {0}")]
|
||||
ParentTree(String),
|
||||
#[error("the page has more content than can be edited")]
|
||||
TooLarge,
|
||||
#[error(transparent)]
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
}
|
||||
@@ -157,22 +161,19 @@ fn bdc_mcid(doc: &Document, props: &Dict, op: &pdfcraft_content::Op) -> Option<i
|
||||
}
|
||||
|
||||
pub(crate) fn page_content(doc: &Document, page: &Dict) -> Vec<u8> {
|
||||
page_content_within(doc, page, &mut DecodeBudget::page())
|
||||
}
|
||||
|
||||
/// The page's content streams, decoded against `budget` and joined with a space. Streams that
|
||||
/// don't decode, or arrive after the budget is spent, are left out.
|
||||
pub(crate) fn page_content_within(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Vec<u8> {
|
||||
let Some(c) = page.get(b"Contents") else { return Vec::new() };
|
||||
match &*doc.resolve(c) {
|
||||
Object::Stream(s) => s.decoded().unwrap_or_default(),
|
||||
Object::Array(a) => a
|
||||
.iter()
|
||||
.flat_map(|x| match &*doc.resolve(x) {
|
||||
Object::Stream(s) => {
|
||||
let mut v = s.decoded().unwrap_or_default();
|
||||
v.push(b' ');
|
||||
v
|
||||
}
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
let mut out = Vec::new();
|
||||
for data in budget.decode_contents(doc, c).into_iter().flatten() {
|
||||
out.extend_from_slice(&data);
|
||||
out.push(b' ');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn union(a: Option<[f64; 4]>, b: [f64; 4]) -> [f64; 4] {
|
||||
@@ -182,17 +183,70 @@ fn union(a: Option<[f64; 4]>, b: [f64; 4]) -> [f64; 4] {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the marked content `ids` is drawn on a page (images, forms and paths).
|
||||
fn content_bbox(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> Option<[f64; 4]> {
|
||||
/// An open marked-content sequence while bounds are gathered: its id, when it is one of those asked
|
||||
/// for, and the bounds of what has been drawn in it so far.
|
||||
struct Mark {
|
||||
id: Option<i64>,
|
||||
drawn: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// Adds `b` to what the innermost open sequence has drawn.
|
||||
fn draw(marks: &mut [Mark], b: [f64; 4]) {
|
||||
if let Some(m) = marks.last_mut() {
|
||||
m.drawn = Some(union(m.drawn, b));
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the innermost open sequence: what it drew counts for its id and for the sequence around it.
|
||||
fn close(marks: &mut Vec<Mark>, matching: &mut usize, out: &mut HashMap<i64, [f64; 4]>) {
|
||||
let Some(m) = marks.pop() else { return };
|
||||
if m.id.is_some() {
|
||||
*matching = matching.saturating_sub(1);
|
||||
}
|
||||
let Some(b) = m.drawn else { return };
|
||||
if let Some(id) = m.id {
|
||||
let e = out.entry(id).or_insert(b);
|
||||
*e = union(Some(*e), b);
|
||||
}
|
||||
draw(marks, b);
|
||||
}
|
||||
|
||||
/// The page-space box a `Do` operator paints: a form's transformed `/BBox`, or the unit square for an image.
|
||||
/// `None` when the operand is not a resolvable XObject or the form's box is malformed.
|
||||
fn xobject_bbox(doc: &Document, xobjects: &Dict, op: &pdfcraft_content::Op, top: &Matrix) -> Option<[f64; 4]> {
|
||||
let r = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)?;
|
||||
Some(match &*doc.get(r) {
|
||||
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
|
||||
let bb: Vec<f64> =
|
||||
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
|
||||
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
|
||||
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
|
||||
match bb[..] {
|
||||
[a, b, c, d] => m.then(top).bbox([a, b, c, d]),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
|
||||
})
|
||||
}
|
||||
|
||||
/// Where each of the marked content `ids` is drawn on a page (images, forms and paths), in one pass
|
||||
/// over the page. What a sequence draws counts for every sequence of `ids` around it too.
|
||||
pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> HashMap<i64, [f64; 4]> {
|
||||
let res = page.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let xobjects = res.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let props = page_properties(doc, page);
|
||||
#[cfg(test)]
|
||||
crate::BOUNDS_PASSES.with(|c| c.set(c.get() + 1));
|
||||
let mut ctm = vec![Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])];
|
||||
let mut marks: Vec<bool> = Vec::new();
|
||||
let mut bbox = None;
|
||||
// The open marked-content sequences, and how many of them are one of `ids`.
|
||||
let mut marks: Vec<Mark> = Vec::new();
|
||||
let mut matching = 0usize;
|
||||
let mut out = HashMap::new();
|
||||
let mut path: Vec<(f64, f64)> = Vec::new();
|
||||
for op in pdfcraft_content::parse(&page_content(doc, page)).ops {
|
||||
let inside = marks.iter().any(|m| *m);
|
||||
crate::count_mark_reads(1);
|
||||
let inside = matching > 0;
|
||||
let top = ctm.last().copied().unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
|
||||
match op.op.as_slice() {
|
||||
b"q" => ctm.push(top),
|
||||
@@ -206,11 +260,13 @@ fn content_bbox(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> Option<[f64;
|
||||
*t = m.then(&top);
|
||||
}
|
||||
}
|
||||
b"BMC" => marks.push(false),
|
||||
b"BDC" => marks.push(bdc_mcid(doc, &props, &op).is_some_and(|n| ids.contains(&n))),
|
||||
b"EMC" => {
|
||||
marks.pop();
|
||||
b"BMC" => marks.push(Mark { id: None, drawn: None }),
|
||||
b"BDC" => {
|
||||
let id = bdc_mcid(doc, &props, &op).filter(|n| ids.contains(n));
|
||||
matching += usize::from(id.is_some());
|
||||
marks.push(Mark { id, drawn: None });
|
||||
}
|
||||
b"EMC" => close(&mut marks, &mut matching, &mut out),
|
||||
b"m" | b"l" => {
|
||||
if let Some([x, y]) = op.nums::<2>() {
|
||||
path.push(top.apply(x, y));
|
||||
@@ -231,33 +287,23 @@ fn content_bbox(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> Option<[f64;
|
||||
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"n" => {
|
||||
if inside && !matches!(op.op.as_slice(), b"n") {
|
||||
for (x, y) in &path {
|
||||
bbox = Some(union(bbox, [*x, *y, *x, *y]));
|
||||
draw(&mut marks, [*x, *y, *x, *y]);
|
||||
}
|
||||
}
|
||||
path.clear();
|
||||
}
|
||||
b"Do" if inside => {
|
||||
let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref) else { continue };
|
||||
let unit = match &*doc.get(r) {
|
||||
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
|
||||
let bb: Vec<f64> =
|
||||
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
|
||||
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
|
||||
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
|
||||
match bb[..] {
|
||||
[a, b, c, d] => m.then(&top).bbox([a, b, c, d]),
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
|
||||
};
|
||||
bbox = Some(union(bbox, unit));
|
||||
let Some(unit) = xobject_bbox(doc, &xobjects, &op, &top) else { continue };
|
||||
draw(&mut marks, unit);
|
||||
}
|
||||
b"BI" if inside => bbox = Some(union(bbox, top.bbox([0.0, 0.0, 1.0, 1.0]))),
|
||||
b"BI" if inside => draw(&mut marks, top.bbox([0.0, 0.0, 1.0, 1.0])),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
bbox
|
||||
while !marks.is_empty() {
|
||||
close(&mut marks, &mut matching, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The figures, in document order.
|
||||
@@ -266,14 +312,28 @@ pub fn figures(doc: &Document) -> Vec<Figure> {
|
||||
let role_map = root.get(b"RoleMap").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let index: HashMap<ObjRef, usize> = pages.iter().enumerate().map(|(i, p)| (p.obj, i)).collect();
|
||||
elements(doc)
|
||||
let figures: Vec<(Element, Option<usize>)> = elements(doc)
|
||||
.into_iter()
|
||||
.filter(|e| e.dict.name(b"S").is_some_and(|s| standard(doc, &role_map, s) == b"Figure"))
|
||||
.map(|e| {
|
||||
let page = e.page.and_then(|p| index.get(&p).copied());
|
||||
(e, page)
|
||||
})
|
||||
.collect();
|
||||
let mut wanted: HashMap<usize, HashSet<i64>> = HashMap::new();
|
||||
for (e, page) in &figures {
|
||||
if let Some(p) = page {
|
||||
wanted.entry(*p).or_default().extend(mcids(&e.dict));
|
||||
}
|
||||
}
|
||||
let bounds: HashMap<usize, HashMap<i64, [f64; 4]>> =
|
||||
wanted.into_iter().filter_map(|(p, ids)| Some((p, content_bboxes(doc, &pages.get(p)?.dict, &ids)))).collect();
|
||||
figures
|
||||
.into_iter()
|
||||
.map(|(e, page)| {
|
||||
let alt = e.dict.get(b"Alt").map(|o| doc.resolve(o)).and_then(|o| o.as_string().map(|s| s.to_text()));
|
||||
let ids: HashSet<i64> = mcids(&e.dict).into_iter().collect();
|
||||
let bbox = page.and_then(|p| content_bbox(doc, &pages[p].dict, &ids));
|
||||
let on_page = page.and_then(|p| bounds.get(&p));
|
||||
let bbox = on_page.and_then(|b| mcids(&e.dict).iter().filter_map(|id| b.get(id)).fold(None, |acc, b| Some(union(acc, *b))));
|
||||
Figure { obj: e.object, page, alt, bbox }
|
||||
})
|
||||
.collect()
|
||||
@@ -322,9 +382,19 @@ fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids:
|
||||
let Some(entries) = content_entries(doc, &page.dict) else { return Ok(false) };
|
||||
let props = page_properties(doc, &page.dict);
|
||||
let mut streams: Vec<Option<(Stream, Vec<u8>)>> = Vec::with_capacity(entries.len());
|
||||
let mut budget = DecodeBudget::page();
|
||||
for entry in &entries {
|
||||
match &*doc.resolve(entry) {
|
||||
Object::Stream(s) => streams.push(Some((s.clone(), s.decoded().unwrap_or_default()))),
|
||||
Object::Stream(s) => {
|
||||
let data = match budget.decode(s) {
|
||||
Ok(data) => data,
|
||||
// Content past the budget may hold more of the figure: editing the rest
|
||||
// would leave that part marked as a figure the tree no longer has.
|
||||
Err(_) if budget.exhausted() => return Err(AltError::TooLarge),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
streams.push(Some((s.clone(), data)));
|
||||
}
|
||||
_ => streams.push(None),
|
||||
}
|
||||
}
|
||||
@@ -421,7 +491,23 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let page_ref = element.page.ok_or(ArtifactError::NoPage)?;
|
||||
let page = pages.iter().find(|page| page.obj == page_ref).ok_or(ArtifactError::NoPage)?;
|
||||
let mut ops = pdfcraft_content::parse(&page_content(doc, &page.dict)).ops;
|
||||
let mut content = Vec::new();
|
||||
if let Some(c) = page.dict.get(b"Contents") {
|
||||
let mut budget = DecodeBudget::page();
|
||||
for data in budget.decode_contents(doc, c) {
|
||||
match data {
|
||||
Ok(data) => {
|
||||
content.extend_from_slice(&data);
|
||||
content.push(b' ');
|
||||
}
|
||||
// The page's /Contents is replaced with what was decoded: content past the
|
||||
// budget would be dropped from the page.
|
||||
Err(_) if budget.exhausted() => return Err(ArtifactError::TooLarge),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ops = pdfcraft_content::parse(&content).ops;
|
||||
let mut found = HashSet::new();
|
||||
for op in &mut ops {
|
||||
let id = (op.op == b"BDC")
|
||||
|
||||
+33
-27
@@ -132,6 +132,38 @@ fn harmless_inside(op: &[u8]) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The `(BT, ET)` operator index pairs of each text object that shows text, or why the page cannot be tagged.
|
||||
fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagError> {
|
||||
let mut start = None;
|
||||
let mut has_text = false;
|
||||
let mut spans = Vec::new();
|
||||
for (at, op) in ops.iter().enumerate() {
|
||||
match op.op.as_slice() {
|
||||
b"BT" if start.is_none() => {
|
||||
start = Some(at);
|
||||
has_text = false;
|
||||
}
|
||||
b"ET" => {
|
||||
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
|
||||
if has_text {
|
||||
spans.push((first, at));
|
||||
if spans.len() > MAX_TEXT_OBJECTS {
|
||||
return Err(unsupported(index, "too many text objects (maximum 4096)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
|
||||
name if start.is_some() && harmless_inside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => {}
|
||||
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
|
||||
}
|
||||
}
|
||||
if start.is_some() {
|
||||
return Err(unsupported(index, "unterminated BT text object"));
|
||||
}
|
||||
Ok(spans)
|
||||
}
|
||||
|
||||
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
let root = doc.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let catalog = doc.get(root);
|
||||
@@ -163,33 +195,7 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS {
|
||||
return Err(unsupported(index, "content has malformed or too many operators"));
|
||||
}
|
||||
let mut start = None;
|
||||
let mut has_text = false;
|
||||
let mut spans = Vec::new();
|
||||
for (at, op) in parsed.ops.iter().enumerate() {
|
||||
match op.op.as_slice() {
|
||||
b"BT" if start.is_none() => {
|
||||
start = Some(at);
|
||||
has_text = false;
|
||||
}
|
||||
b"ET" => {
|
||||
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
|
||||
if has_text {
|
||||
spans.push((first, at));
|
||||
if spans.len() > MAX_TEXT_OBJECTS {
|
||||
return Err(unsupported(index, "too many text objects (maximum 4096)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
|
||||
name if start.is_some() && harmless_inside(name) => {}
|
||||
name if start.is_none() && harmless_outside(name) => {}
|
||||
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
|
||||
}
|
||||
}
|
||||
if start.is_some() {
|
||||
return Err(unsupported(index, "unterminated BT text object"));
|
||||
}
|
||||
let spans = text_spans(&parsed.ops, index)?;
|
||||
total = total.saturating_add(spans.len());
|
||||
out.push(Plan { page: page.obj, ops: parsed.ops, spans });
|
||||
}
|
||||
|
||||
+36
-35
@@ -6,7 +6,7 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_model::Page;
|
||||
|
||||
use crate::{Finding, Rule};
|
||||
@@ -20,6 +20,8 @@ pub(crate) struct Scan {
|
||||
pub untagged: BTreeMap<usize, usize>,
|
||||
/// Page → fonts used.
|
||||
pub fonts: BTreeMap<usize, BTreeSet<ObjRef>>,
|
||||
/// Pages read only in part: content or forms past the page's decode budget are missing.
|
||||
pub incomplete: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
const MAX_FORM_DEPTH: usize = 12;
|
||||
@@ -30,38 +32,34 @@ impl Scan {
|
||||
for &p in list {
|
||||
let Some(page) = pages.get(p) else { continue };
|
||||
let res = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let data = page_content(doc, &page.dict);
|
||||
let mut w = Walk { doc, scan: &mut s, page: p, forms: HashSet::new() };
|
||||
let mut budget = DecodeBudget::page();
|
||||
let data = crate::alt::page_content_within(doc, &page.dict, &mut budget);
|
||||
if budget.remaining() == 0 {
|
||||
s.incomplete.insert(p);
|
||||
}
|
||||
let mut w = Walk { doc, scan: &mut s, page: p, forms: HashSet::new(), budget };
|
||||
w.content(&data, &res, false, 0);
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
fn page_content(doc: &Document, page: &Dict) -> Vec<u8> {
|
||||
let Some(c) = page.get(b"Contents") else { return Vec::new() };
|
||||
match &*doc.resolve(c) {
|
||||
Object::Stream(s) => s.decoded().unwrap_or_default(),
|
||||
Object::Array(a) => a
|
||||
.iter()
|
||||
.flat_map(|x| match &*doc.resolve(x) {
|
||||
Object::Stream(s) => {
|
||||
let mut v = s.decoded().unwrap_or_default();
|
||||
v.push(b' ');
|
||||
v
|
||||
}
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Walk<'a> {
|
||||
doc: &'a Document,
|
||||
scan: &'a mut Scan,
|
||||
page: usize,
|
||||
forms: HashSet<ObjRef>,
|
||||
/// Decoded bytes and form entries left for this page.
|
||||
budget: DecodeBudget,
|
||||
}
|
||||
|
||||
fn bdc_marks(doc: &Document, op: &pdfcraft_content::Op, props: &Dict) -> bool {
|
||||
op.name(0) == Some(b"Artifact")
|
||||
|| match op.operands.get(1) {
|
||||
Some(Object::Dict(d)) => d.contains(b"MCID"),
|
||||
Some(Object::Name(n)) => props.get(n).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
@@ -79,17 +77,7 @@ impl Walk<'_> {
|
||||
let inside = covered || stack.last().copied().unwrap_or(false);
|
||||
match op.op.as_slice() {
|
||||
b"BMC" => stack.push(inside || op.name(0) == Some(b"Artifact")),
|
||||
b"BDC" => {
|
||||
let marks = op.name(0) == Some(b"Artifact")
|
||||
|| match op.operands.get(1) {
|
||||
Some(Object::Dict(d)) => d.contains(b"MCID"),
|
||||
Some(Object::Name(n)) => {
|
||||
props.get(n).map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
stack.push(inside || marks);
|
||||
}
|
||||
b"BDC" => stack.push(inside || bdc_marks(self.doc, &op, &props)),
|
||||
b"EMC" => {
|
||||
stack.pop();
|
||||
}
|
||||
@@ -116,14 +104,27 @@ impl Walk<'_> {
|
||||
self.scan.has_images = true;
|
||||
untagged += usize::from(!inside);
|
||||
}
|
||||
Some(b"Form") if depth < MAX_FORM_DEPTH && self.forms.insert(r) => {
|
||||
Some(b"Form") if depth < MAX_FORM_DEPTH && !self.forms.contains(&r) => {
|
||||
if !self.budget.enter_form() {
|
||||
self.scan.incomplete.insert(self.page);
|
||||
continue;
|
||||
}
|
||||
let data = match self.budget.decode(x) {
|
||||
Ok(data) => data,
|
||||
Err(_) => {
|
||||
if self.budget.exhausted() {
|
||||
self.scan.incomplete.insert(self.page);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
self.forms.insert(r);
|
||||
let inner = x
|
||||
.dict
|
||||
.get(b"Resources")
|
||||
.map(|o| self.doc.resolve(o))
|
||||
.and_then(|o| o.as_dict().cloned())
|
||||
.unwrap_or_else(|| res.clone());
|
||||
let data = x.decoded().unwrap_or_default();
|
||||
self.content(&data, &inner, inside, depth + 1);
|
||||
self.forms.remove(&r);
|
||||
}
|
||||
|
||||
+19
-14
@@ -182,6 +182,7 @@ pub(crate) fn mcid_texts(doc: &Document, page: &Dict) -> HashMap<i64, String> {
|
||||
let res = sub(doc, page, b"Resources");
|
||||
let (fonts, props) = (sub(doc, &res, b"Font"), sub(doc, &res, b"Properties"));
|
||||
let mut metrics: HashMap<Vec<u8>, Metrics> = HashMap::new();
|
||||
// The id each open marked-content sequence is in: its own, else the enclosing one's.
|
||||
let mut stack: Vec<Option<i64>> = Vec::new();
|
||||
let mut out: HashMap<i64, String> = HashMap::new();
|
||||
// Where each id's last glyph ended, in user space.
|
||||
@@ -191,16 +192,20 @@ pub(crate) fn mcid_texts(doc: &Document, page: &Dict) -> HashMap<i64, String> {
|
||||
let mut unsaved = 0usize;
|
||||
let (mut tm, mut tlm) = (Matrix::IDENTITY, Matrix::IDENTITY);
|
||||
for op in pdfcraft_content::parse(&page_content(doc, page)).ops {
|
||||
let id = stack.iter().rev().find_map(|m| *m);
|
||||
crate::count_mark_reads(1);
|
||||
let id = stack.last().copied().flatten();
|
||||
match op.op.as_slice() {
|
||||
b"BMC" => stack.push(None),
|
||||
b"BDC" => stack.push(match op.operands.get(1) {
|
||||
Some(Object::Dict(d)) => d.get(b"MCID").and_then(Object::as_int),
|
||||
Some(Object::Name(n)) => {
|
||||
props.get(n).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().and_then(|d| d.get(b"MCID").and_then(Object::as_int)))
|
||||
b"BMC" => stack.push(id),
|
||||
b"BDC" => stack.push(
|
||||
match op.operands.get(1) {
|
||||
Some(Object::Dict(d)) => d.get(b"MCID").and_then(Object::as_int),
|
||||
Some(Object::Name(n)) => {
|
||||
props.get(n).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().and_then(|d| d.get(b"MCID").and_then(Object::as_int)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
_ => None,
|
||||
}),
|
||||
.or(id),
|
||||
),
|
||||
b"EMC" => {
|
||||
stack.pop();
|
||||
}
|
||||
@@ -280,17 +285,17 @@ pub(crate) fn mcid_texts(doc: &Document, page: &Dict) -> HashMap<i64, String> {
|
||||
};
|
||||
for (code, len) in m.codes(&s.bytes) {
|
||||
let trm = tm.then(&gs.ctm);
|
||||
// A glyph's text is only built while its id still takes more.
|
||||
if let Some(id) = id
|
||||
&& out.get(&id).is_none_or(|t| t.len() < MAX_TITLE * 4)
|
||||
&& let Some(glyph) = m.text_of(code)
|
||||
{
|
||||
let text = out.entry(id).or_default();
|
||||
if text.len() < MAX_TITLE * 4 {
|
||||
let breaks = ends.get(&id).is_some_and(|end| new_word(&trm, *end, gs.size, gs.scale));
|
||||
if breaks && !text.is_empty() && !text.ends_with(' ') && !glyph.starts_with(' ') {
|
||||
text.push(' ');
|
||||
}
|
||||
text.push_str(&glyph);
|
||||
let breaks = ends.get(&id).is_some_and(|end| new_word(&trm, *end, gs.size, gs.scale));
|
||||
if breaks && !text.is_empty() && !text.ends_with(' ') && !glyph.starts_with(' ') {
|
||||
text.push(' ');
|
||||
}
|
||||
text.push_str(&glyph);
|
||||
}
|
||||
let advance = m.width(code) * gs.size + gs.char_spacing + if m.is_space(code, len) { gs.word_spacing } else { 0.0 };
|
||||
tm = Matrix::translate(advance * gs.scale, 0.0).then(&tm);
|
||||
|
||||
@@ -21,6 +21,22 @@ mod report;
|
||||
mod structure;
|
||||
mod tags;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Marked-content stack entries read to decide which marks enclose an operator, for the tests
|
||||
/// that keep that constant per operator.
|
||||
static MARK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Page content passes made to find figure bounds.
|
||||
static BOUNDS_PASSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Counts `n` marked-content stack reads (tests only).
|
||||
#[inline]
|
||||
fn count_mark_reads(_n: usize) {
|
||||
#[cfg(test)]
|
||||
MARK_READS.with(|c| c.set(c.get().saturating_add(_n)));
|
||||
}
|
||||
|
||||
pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt};
|
||||
pub use autotag::{AutoTagError, AutoTagResult, autotag_text};
|
||||
pub use autotag_fields::tag_form_fields;
|
||||
@@ -665,6 +681,18 @@ pub fn check(doc: &Document, options: &Options) -> Report {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A page read only in part may hold what the scan didn't find: text that makes the
|
||||
// document more than images, untagged content, or a font without Unicode mappings.
|
||||
let unsure = !scan.incomplete.is_empty()
|
||||
&& match rule {
|
||||
Rule::ImageOnly => !scan.has_text,
|
||||
Rule::TaggedContent | Rule::CharacterEncoding => findings.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
if unsure {
|
||||
results.push(RuleResult { rule, status: Status::Manual, findings: Vec::new() });
|
||||
continue;
|
||||
}
|
||||
if total > MAX_FINDINGS {
|
||||
let more = total - MAX_FINDINGS;
|
||||
findings.truncate(MAX_FINDINGS);
|
||||
|
||||
+138
-5
@@ -1,6 +1,6 @@
|
||||
//! Properties of reachable indirect structure elements.
|
||||
|
||||
use pdfcraft_cos::{CosError, Document, ObjRef, Object, PdfString};
|
||||
use pdfcraft_cos::{CosError, Dict, Document, ObjRef, Object, PdfString};
|
||||
|
||||
use crate::alt;
|
||||
|
||||
@@ -17,6 +17,10 @@ pub struct TagInfo {
|
||||
pub actual_text: Option<String>,
|
||||
pub alt: Option<String>,
|
||||
pub language: Option<String>,
|
||||
/// A table's `Summary` attribute.
|
||||
pub summary: Option<String>,
|
||||
/// A header cell's `Scope` attribute (`Row`, `Column` or `Both`).
|
||||
pub scope: Option<String>,
|
||||
/// Zero-based page when `/Pg` is known.
|
||||
pub page: Option<usize>,
|
||||
}
|
||||
@@ -36,6 +40,10 @@ pub enum TagProperty {
|
||||
ActualText,
|
||||
AlternateText,
|
||||
Language,
|
||||
/// A table's `Summary`: a Table attribute (an attribute object with `/O /Table` in `/A`).
|
||||
Summary,
|
||||
/// A header cell's `Scope` (a Table attribute): `Row`, `Column` or `Both`.
|
||||
Scope,
|
||||
}
|
||||
|
||||
/// Where to place a structure tag relative to one of its direct siblings.
|
||||
@@ -53,6 +61,8 @@ impl TagProperty {
|
||||
"actual_text" => Some(Self::ActualText),
|
||||
"alternate_text" => Some(Self::AlternateText),
|
||||
"language" => Some(Self::Language),
|
||||
"summary" => Some(Self::Summary),
|
||||
"scope" => Some(Self::Scope),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -64,6 +74,17 @@ impl TagProperty {
|
||||
Self::ActualText => b"ActualText",
|
||||
Self::AlternateText => b"Alt",
|
||||
Self::Language => b"Lang",
|
||||
Self::Summary => b"Summary",
|
||||
Self::Scope => b"Scope",
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard structure type a Table attribute belongs to; `None` for the tag's own entries.
|
||||
fn table_attribute_of(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Summary => Some("Table"),
|
||||
Self::Scope => Some("TH"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +103,10 @@ pub enum TagError {
|
||||
AmbiguousChildren,
|
||||
#[error("the tag is already at the requested position")]
|
||||
AlreadyThere,
|
||||
#[error("{0} applies only to {1} tags")]
|
||||
WrongTagType(&'static str, &'static str),
|
||||
#[error("a scope must be Row, Column or Both")]
|
||||
InvalidScope,
|
||||
#[error(transparent)]
|
||||
Cos(#[from] CosError),
|
||||
}
|
||||
@@ -142,6 +167,8 @@ pub fn tags(doc: &Document) -> Vec<TagInfo> {
|
||||
actual_text: text(doc, &e.dict, b"ActualText"),
|
||||
alt: text(doc, &e.dict, b"Alt"),
|
||||
language: text(doc, &e.dict, b"Lang"),
|
||||
summary: table_attribute(doc, &e.dict, b"Summary").and_then(|o| o.as_string().map(PdfString::to_text)),
|
||||
scope: table_attribute(doc, &e.dict, b"Scope").and_then(|o| o.as_name().map(|n| String::from_utf8_lossy(n).into_owned())),
|
||||
page: e.page.and_then(|p| page_index.get(&p).copied()),
|
||||
})
|
||||
})
|
||||
@@ -200,11 +227,97 @@ fn direct_marks(doc: &Document, item: &Object, page: Option<ObjRef>, out: &mut V
|
||||
}
|
||||
}
|
||||
|
||||
/// Change one property of a reachable tag; `None` removes a text property.
|
||||
pub fn set_tag_property(doc: &mut Document, object: ObjRef, property: TagProperty, value: Option<&str>) -> Result<(), TagError> {
|
||||
if !alt::elements(doc).iter().any(|e| e.object == object) {
|
||||
return Err(TagError::NotATag(object));
|
||||
/// The attribute objects of a tag's `/A` entry (one object, or an array of them each optionally
|
||||
/// followed by its revision number), as written: each entry and its revision number.
|
||||
fn attribute_entries(doc: &Document, d: &Dict) -> (Vec<(Object, Option<Object>)>, bool) {
|
||||
let Some(a) = d.get(b"A") else { return (Vec::new(), false) };
|
||||
// An indirect array is read as its items.
|
||||
let resolved = doc.resolve(a);
|
||||
let Object::Array(items) = &*resolved else { return (vec![(a.clone(), None)], false) };
|
||||
let mut out: Vec<(Object, Option<Object>)> = Vec::new();
|
||||
for item in items {
|
||||
match (item, out.last_mut()) {
|
||||
(Object::Int(_), Some((_, revision @ None))) => *revision = Some(item.clone()),
|
||||
_ => out.push((item.clone(), None)),
|
||||
}
|
||||
}
|
||||
(out, true)
|
||||
}
|
||||
|
||||
/// Whether attribute object `o` (resolved) is a Table attribute object.
|
||||
fn is_table_attributes(o: &Object) -> bool {
|
||||
o.as_dict().is_some_and(|d| d.name(b"O") == Some(b"Table"))
|
||||
}
|
||||
|
||||
/// The value of `key` in the first Table attribute object of tag `d` that has it.
|
||||
fn table_attribute(doc: &Document, d: &Dict, key: &[u8]) -> Option<Object> {
|
||||
attribute_entries(doc, d).0.iter().map(|(o, _)| doc.resolve(o)).filter(|o| is_table_attributes(o)).find_map(|o| o.as_dict()?.get(key).cloned())
|
||||
}
|
||||
|
||||
/// Set `key` in the Table attribute object of `object`'s `/A` entry that holds it (else the first
|
||||
/// one, else a new one), or with `None` remove it from every Table attribute object that holds it.
|
||||
/// An edited object is written into the tag's own `/A`, so an attribute object other tags share
|
||||
/// keeps its value for them; one left with nothing but its owner goes, and so does an `/A` left
|
||||
/// empty.
|
||||
fn set_table_attribute(doc: &mut Document, object: ObjRef, key: &[u8], value: Option<Object>) -> Result<(), TagError> {
|
||||
let dict = doc.get(object).as_dict().cloned().ok_or(TagError::NotATag(object))?;
|
||||
let (entries, array) = attribute_entries(doc, &dict);
|
||||
// Each entry with its Table attributes (resolved), when it is a Table attribute object.
|
||||
let mut entries: Vec<(Object, Option<Object>, Option<Dict>)> = entries
|
||||
.into_iter()
|
||||
.map(|(o, r)| {
|
||||
let table = Some(doc.resolve(&o)).filter(|a| is_table_attributes(a)).and_then(|a| a.as_dict().cloned());
|
||||
(o, r, table)
|
||||
})
|
||||
.collect();
|
||||
let holding = |e: &(Object, Option<Object>, Option<Dict>)| e.2.as_ref().is_some_and(|d| d.contains(key));
|
||||
match value {
|
||||
Some(v) => match entries.iter().position(holding).or_else(|| entries.iter().position(|e| e.2.is_some())) {
|
||||
Some(i) => {
|
||||
if let Some((o, _, Some(attributes))) = entries.get_mut(i) {
|
||||
attributes.set(key.to_vec(), v);
|
||||
*o = Object::Dict(attributes.clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut attributes = Dict::new();
|
||||
attributes.set(b"O".to_vec(), Object::name("Table"));
|
||||
attributes.set(key.to_vec(), v);
|
||||
entries.push((Object::Dict(attributes), None, None));
|
||||
}
|
||||
},
|
||||
None => {
|
||||
if !entries.iter().any(holding) {
|
||||
// Nothing to clear.
|
||||
return Ok(());
|
||||
}
|
||||
for (o, _, table) in &mut entries {
|
||||
if let Some(attributes) = table.as_mut().filter(|a| a.contains(key)) {
|
||||
attributes.remove(key);
|
||||
*o = Object::Dict(attributes.clone());
|
||||
}
|
||||
}
|
||||
entries.retain(|(_, _, table)| !table.as_ref().is_some_and(|a| a.iter().all(|(k, _)| k.as_slice() == b"O")));
|
||||
}
|
||||
}
|
||||
let entries: Vec<(Object, Option<Object>)> = entries.into_iter().map(|(o, r, _)| (o, r)).collect();
|
||||
doc.update_dict(object, |d| match entries.as_slice() {
|
||||
[] => {
|
||||
d.remove(b"A");
|
||||
}
|
||||
[(only, None)] if !array => d.set(b"A".to_vec(), only.clone()),
|
||||
_ => d.set(b"A".to_vec(), Object::Array(entries.into_iter().flat_map(|(o, r)| std::iter::once(o).chain(r)).collect())),
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Change one property of a reachable tag; `None` removes a text property. A table's summary and
|
||||
/// a header cell's scope are Table attributes ([`TagProperty::Summary`], [`TagProperty::Scope`]),
|
||||
/// set only on tags of that type after the role map.
|
||||
pub fn set_tag_property(doc: &mut Document, object: ObjRef, property: TagProperty, value: Option<&str>) -> Result<(), TagError> {
|
||||
let Some(element) = alt::elements(doc).into_iter().find(|e| e.object == object) else {
|
||||
return Err(TagError::NotATag(object));
|
||||
};
|
||||
// ActualText may intentionally contain leading or trailing whitespace; preserve it.
|
||||
let value = value.filter(|s| !s.is_empty());
|
||||
if value.is_some_and(|s| s.len() > 65_536) {
|
||||
@@ -215,6 +328,26 @@ pub fn set_tag_property(doc: &mut Document, object: ObjRef, property: TagPropert
|
||||
{
|
||||
return Err(TagError::InvalidType);
|
||||
}
|
||||
if let Some(owner) = property.table_attribute_of() {
|
||||
let role_map =
|
||||
alt::tree_root(doc).and_then(|r| r.get(b"RoleMap").map(|o| doc.resolve(o))).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
|
||||
let ty = element.dict.name(b"S").map(|s| alt::standard(doc, &role_map, s)).unwrap_or_default();
|
||||
if ty != owner.as_bytes() {
|
||||
let name = if property == TagProperty::Summary { "summary" } else { "scope" };
|
||||
return Err(TagError::WrongTagType(name, owner));
|
||||
}
|
||||
let value = match value {
|
||||
Some(s) if property == TagProperty::Scope => {
|
||||
if !matches!(s, "Row" | "Column" | "Both") {
|
||||
return Err(TagError::InvalidScope);
|
||||
}
|
||||
Some(Object::name(s))
|
||||
}
|
||||
Some(s) => Some(Object::String(PdfString::text(s))),
|
||||
None => None,
|
||||
};
|
||||
return set_table_attribute(doc, object, property.key(), value);
|
||||
}
|
||||
doc.update_dict(object, |d| match value {
|
||||
Some(s) if property == TagProperty::Type => d.set(property.key().to_vec(), Object::name(s)),
|
||||
Some(s) => d.set(property.key().to_vec(), Object::String(PdfString::text(s))),
|
||||
|
||||
@@ -367,6 +367,103 @@ fn reachable_tag_properties_round_trip_and_reject_unrelated_objects() {
|
||||
assert!(matches!(set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(4, 1), TagProperty::Title, Some("No")), Err(TagError::NotATag(_))));
|
||||
}
|
||||
|
||||
/// A table (object 4) with a header cell (6) and a data cell (7); `th` is the header cell's
|
||||
/// dictionary and `extra` more objects from 8 on, of which the Document element (3) lists `kids`
|
||||
/// after the table. The role map maps /MyTable to /Table.
|
||||
fn table_doc(th: &str, extra: &[&str], kids: &str) -> Document {
|
||||
let mut objs = vec![
|
||||
"<< /Type /Catalog /StructTreeRoot 2 0 R >>".to_string(),
|
||||
"<< /Type /StructTreeRoot /K 3 0 R /RoleMap << /MyTable /Table >> >>".to_string(),
|
||||
format!("<< /S /Document /K [4 0 R {kids}] >>"),
|
||||
"<< /S /Table /K [5 0 R] >>".to_string(),
|
||||
"<< /S /TR /K [6 0 R 7 0 R] >>".to_string(),
|
||||
th.to_string(),
|
||||
"<< /S /TD >>".to_string(),
|
||||
];
|
||||
objs.extend(extra.iter().map(ToString::to_string));
|
||||
pdf(&objs, "")
|
||||
}
|
||||
|
||||
/// The attribute objects of tag `r`'s /A entry as written (one object or an array).
|
||||
fn attributes(doc: &Document, r: pdfcraft_cos::ObjRef) -> Option<pdfcraft_cos::Object> {
|
||||
doc.get(r).as_dict()?.get(b"A").cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_summary_is_a_table_attribute() {
|
||||
let mut doc = table_doc("<< /S /TH >>", &["<< /S /MyTable >>"], "8 0 R");
|
||||
let (table, th) = (pdfcraft_cos::ObjRef::new(4, 0), pdfcraft_cos::ObjRef::new(6, 0));
|
||||
set_tag_property(&mut doc, table, TagProperty::Summary, Some("Opening hours by day")).unwrap();
|
||||
let a = attributes(&doc, table).unwrap();
|
||||
let a = a.as_dict().unwrap();
|
||||
assert_eq!(a.name(b"O"), Some(&b"Table"[..]));
|
||||
assert_eq!(
|
||||
a.get(b"Summary").and_then(pdfcraft_cos::Object::as_string).map(pdfcraft_cos::PdfString::to_text).as_deref(),
|
||||
Some("Opening hours by day")
|
||||
);
|
||||
assert_eq!(tags(&doc).iter().find(|t| t.object == table).unwrap().summary.as_deref(), Some("Opening hours by day"));
|
||||
// Only a table takes one (after the role map: /MyTable is a table).
|
||||
assert!(matches!(set_tag_property(&mut doc, th, TagProperty::Summary, Some("No")), Err(TagError::WrongTagType(..))));
|
||||
set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(8, 0), TagProperty::Summary, Some("Mapped")).unwrap();
|
||||
// Cleared, the attribute object has nothing left and goes.
|
||||
set_tag_property(&mut doc, table, TagProperty::Summary, None).unwrap();
|
||||
assert_eq!(attributes(&doc, table), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_cell_scope_keeps_its_other_attributes() {
|
||||
// The cell's /A holds a layout attribute object, then a table one with a revision number.
|
||||
let mut doc = table_doc("<< /S /TH /A [ << /O /Layout /Placement /Block >> << /O /Table /ColSpan 2 >> 1 ] >>", &[], "");
|
||||
let th = pdfcraft_cos::ObjRef::new(6, 0);
|
||||
set_tag_property(&mut doc, th, TagProperty::Scope, Some("Column")).unwrap();
|
||||
let Some(pdfcraft_cos::Object::Array(items)) = attributes(&doc, th) else { panic!("{:?}", attributes(&doc, th)) };
|
||||
assert_eq!(items.len(), 3, "{items:?}");
|
||||
assert_eq!(items[0].as_dict().and_then(|d| d.name(b"O")), Some(&b"Layout"[..]));
|
||||
let table = items[1].as_dict().unwrap();
|
||||
assert_eq!((table.int(b"ColSpan"), table.name(b"Scope")), (Some(2), Some(&b"Column"[..])));
|
||||
assert_eq!(items[2].as_int(), Some(1), "the revision number stays with its object");
|
||||
assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope.as_deref(), Some("Column"));
|
||||
// Cleared, the span stays.
|
||||
set_tag_property(&mut doc, th, TagProperty::Scope, None).unwrap();
|
||||
let Some(pdfcraft_cos::Object::Array(items)) = attributes(&doc, th) else { panic!() };
|
||||
assert_eq!(items[1].as_dict().map(|d| (d.int(b"ColSpan"), d.contains(b"Scope"))), Some((Some(2), false)));
|
||||
// A scope is Row, Column or Both, and only header cells have one.
|
||||
for bad in ["row", "Sideways", " Both"] {
|
||||
assert!(matches!(set_tag_property(&mut doc, th, TagProperty::Scope, Some(bad)), Err(TagError::InvalidScope)), "{bad}");
|
||||
}
|
||||
assert!(matches!(set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(7, 0), TagProperty::Scope, Some("Row")), Err(TagError::WrongTagType(..))));
|
||||
}
|
||||
|
||||
/// With two Table attribute objects, the one holding the value is the one set and cleared
|
||||
/// (#4130 review): a value in the second isn't left behind or shadowed.
|
||||
#[test]
|
||||
fn the_table_attribute_object_holding_a_value_is_the_one_edited() {
|
||||
let mut doc = table_doc("<< /S /TH /A [ << /O /Table /ColSpan 2 >> << /O /Table /Scope /Row >> ] >>", &[], "");
|
||||
let th = pdfcraft_cos::ObjRef::new(6, 0);
|
||||
let scopes = |doc: &Document| -> Vec<Option<Vec<u8>>> {
|
||||
let Some(pdfcraft_cos::Object::Array(items)) = attributes(doc, th) else { return vec![] };
|
||||
items.iter().map(|i| i.as_dict().and_then(|d| d.name(b"Scope")).map(<[u8]>::to_vec)).collect()
|
||||
};
|
||||
set_tag_property(&mut doc, th, TagProperty::Scope, Some("Column")).unwrap();
|
||||
assert_eq!(scopes(&doc), [None, Some(b"Column".to_vec())]);
|
||||
assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope.as_deref(), Some("Column"));
|
||||
set_tag_property(&mut doc, th, TagProperty::Scope, None).unwrap();
|
||||
assert_eq!(scopes(&doc), [None], "the second object had only the scope: {:?}", attributes(&doc, th));
|
||||
assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_attribute_object_is_not_changed_for_other_tags() {
|
||||
// Both cells point at attribute object 8.
|
||||
let mut doc = table_doc("<< /S /TH /A 8 0 R >>", &["<< /O /Table /Scope /Row >>"], "");
|
||||
doc.update_dict(pdfcraft_cos::ObjRef::new(7, 0), |d| d.set(b"A".to_vec(), pdfcraft_cos::Object::Ref(pdfcraft_cos::ObjRef::new(8, 0)))).unwrap();
|
||||
set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(6, 0), TagProperty::Scope, Some("Both")).unwrap();
|
||||
assert_eq!(doc.get(pdfcraft_cos::ObjRef::new(8, 0)).as_dict().and_then(|d| d.name(b"Scope")), Some(&b"Row"[..]));
|
||||
let a = attributes(&doc, pdfcraft_cos::ObjRef::new(6, 0)).unwrap();
|
||||
assert_eq!(a.as_dict().and_then(|d| d.name(b"Scope")), Some(&b"Both"[..]), "the cell's own copy: {a:?}");
|
||||
assert_eq!(attributes(&doc, pdfcraft_cos::ObjRef::new(7, 0)), Some(pdfcraft_cos::Object::Ref(pdfcraft_cos::ObjRef::new(8, 0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_hierarchy_keeps_indirect_parent_through_inline_tags() {
|
||||
let doc = structure_doc(&["<< /S /Document /K 4 0 R >>".into(), "<< /S /Sect /K << /S /Div /K 5 0 R >> >>".into(), "<< /S /Figure >>".into()]);
|
||||
@@ -1023,6 +1120,67 @@ fn glyph_by_tm(text: &str, size: f64, y: f64) -> String {
|
||||
ops + " ET"
|
||||
}
|
||||
|
||||
/// Marked-content stack reads while `f` runs.
|
||||
fn mark_reads(f: impl FnOnce()) -> usize {
|
||||
MARK_READS.with(|c| c.set(0));
|
||||
f();
|
||||
MARK_READS.with(|c| c.get())
|
||||
}
|
||||
|
||||
/// Page content nesting `depth` unmarked `BMC` blocks around a marked one, with `ops` operators inside.
|
||||
fn deeply_nested_page(doc: &mut Document, depth: usize, ops: usize) -> pdfcraft_cos::Dict {
|
||||
use pdfcraft_cos::{Dict, Stream};
|
||||
let mut data = "/Figure << /MCID 0 >> BDC ".to_string();
|
||||
data.push_str(&"/X BMC ".repeat(depth));
|
||||
data.push_str(&"0 0 1 1 re f ".repeat(ops));
|
||||
data.push_str(&"EMC ".repeat(depth + 1));
|
||||
let content = doc.add(Stream::flate(Dict::new(), data.as_bytes()));
|
||||
[(b"Contents".to_vec(), Object::Ref(content))].into_iter().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_text_reads_its_enclosing_id_in_constant_steps() {
|
||||
let mut doc = Document::new_empty();
|
||||
let page = deeply_nested_page(&mut doc, 5_000, 5_000);
|
||||
let reads = mark_reads(|| {
|
||||
crate::headings::mcid_texts(&doc, &page);
|
||||
});
|
||||
// About 15 000 operators; a scan of the stack per operator reads millions of entries.
|
||||
assert!(reads <= 4 * 15_000, "{reads} stack reads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn figure_bounds_read_the_marked_content_state_in_constant_steps() {
|
||||
let mut doc = Document::new_empty();
|
||||
let page = deeply_nested_page(&mut doc, 5_000, 5_000);
|
||||
// No mark encloses figure 7, so a scan of the stack per operator reads all of it.
|
||||
let reads = mark_reads(|| {
|
||||
crate::alt::content_bboxes(&doc, &page, &std::collections::HashSet::from([7]));
|
||||
});
|
||||
assert!(reads <= 4 * 15_000, "{reads} stack reads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn figure_bounds_take_one_pass_over_each_page() {
|
||||
let n = 50;
|
||||
let content: Vec<String> = (0..n).map(|i| format!("/Figure << /MCID {i} >> BDC {i} 0 1 1 re f EMC")).collect();
|
||||
let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 6 + i)).collect();
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".into(),
|
||||
stream(&content.join(" ")),
|
||||
format!("<< /Type /StructTreeRoot /K [{}] >>", kids.join(" ")),
|
||||
];
|
||||
objs.extend((0..n).map(|i| format!("<< /S /Figure /Pg 3 0 R /K {i} >>")));
|
||||
let doc = pdf(&objs, "");
|
||||
BOUNDS_PASSES.with(|c| c.set(0));
|
||||
let f = figures(&doc);
|
||||
assert_eq!(BOUNDS_PASSES.with(|c| c.get()), 1, "page passes");
|
||||
assert_eq!(f.len(), n);
|
||||
assert!(f.iter().enumerate().all(|(i, f)| f.bbox == Some([i as f64, 0.0, i as f64 + 1.0, 1.0])));
|
||||
}
|
||||
|
||||
/// One tagged page whose H1 headings show `contents` (one marked-content sequence each).
|
||||
fn heading_page(contents: &[String]) -> Document {
|
||||
let marked: Vec<String> = contents.iter().enumerate().map(|(i, c)| format!("/H1 << /MCID {i} >> BDC {c} EMC")).collect();
|
||||
@@ -1191,3 +1349,75 @@ fn horizontally_scaled_wrapped_heading_keeps_a_space_between_lines() {
|
||||
let titles: Vec<String> = headings(&doc).into_iter().map(|h| h.title).collect();
|
||||
assert_eq!(titles, ["I Overview"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_content_references_share_one_decode_budget() {
|
||||
use pdfcraft_cos::{Dict, MAX_PAGE_DECODED, Object, Stream};
|
||||
let mut doc = Document::new_empty();
|
||||
let stream = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
|
||||
let page: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(stream); 300]))].into_iter().collect();
|
||||
let data = crate::alt::page_content(&doc, &page);
|
||||
assert!(data.len() <= MAX_PAGE_DECODED + 300, "{} bytes", data.len());
|
||||
}
|
||||
|
||||
/// A figure whose marked content goes on in a stream past the page's decode budget is refused,
|
||||
/// not removed with that content still pointing at it.
|
||||
#[test]
|
||||
fn marking_decorative_refuses_content_past_the_decode_budget() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let mut doc = figures_doc();
|
||||
let filler = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
|
||||
let last = doc.add(Stream::from_raw(Dict::new(), b"/Figure << /MCID 0 >> BDC 0 0 5 5 re f EMC".to_vec()));
|
||||
let mut contents = vec![Object::Ref(ObjRef::new(4, 0))];
|
||||
contents.extend(std::iter::repeat_n(Object::Ref(filler), 256));
|
||||
contents.push(Object::Ref(last));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(contents))).unwrap();
|
||||
assert!(mark_decorative(&mut doc, ObjRef::new(7, 0)).is_err());
|
||||
assert_eq!(figures(&doc).len(), 2, "the figure stays");
|
||||
}
|
||||
|
||||
/// Text past the page's decode budget is unread, so a page that shows images and no text so far
|
||||
/// can't be called image-only, nor its content all tagged.
|
||||
#[test]
|
||||
fn content_past_the_decode_budget_needs_a_manual_check() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R >> /Font << /F1 6 0 R >> >> >>"
|
||||
.into(),
|
||||
stream("/Artifact BMC q 200 0 0 200 0 0 cm /Im Do Q EMC"),
|
||||
"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\n\u{0}\nendstream"
|
||||
.into(),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let filler = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
|
||||
let text = doc.add(Stream::from_raw(Dict::new(), b"BT /F1 12 Tf 10 10 Td (Hello) Tj ET".to_vec()));
|
||||
let mut contents = vec![Object::Ref(ObjRef::new(4, 0))];
|
||||
contents.extend(std::iter::repeat_n(Object::Ref(filler), 256));
|
||||
contents.push(Object::Ref(text));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(contents))).unwrap();
|
||||
let report = check(&doc, &Options::default());
|
||||
assert_eq!(status(&report, Rule::ImageOnly), Status::Manual);
|
||||
assert_eq!(status(&report, Rule::TaggedContent), Status::Manual);
|
||||
}
|
||||
|
||||
/// Marking a tag as an artifact replaces the page's content with what it decoded, so content past
|
||||
/// the page's decode budget is refused rather than dropped from the page.
|
||||
#[test]
|
||||
fn marking_a_tag_artifact_refuses_content_past_the_decode_budget() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let mut doc = figures_doc();
|
||||
let filler = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
|
||||
let last = doc.add(Stream::from_raw(Dict::new(), b"0 0 5 5 re f".to_vec()));
|
||||
let mut contents = vec![Object::Ref(ObjRef::new(4, 0))];
|
||||
contents.extend(std::iter::repeat_n(Object::Ref(filler), 256));
|
||||
contents.push(Object::Ref(last));
|
||||
let contents = Object::Array(contents);
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), contents.clone())).unwrap();
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::TooLarge));
|
||||
assert_eq!(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents"), Some(&contents), "the page keeps its content");
|
||||
}
|
||||
|
||||
@@ -9,10 +9,12 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
|
||||
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
|
||||
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
|
||||
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
|
||||
A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as
|
||||
ISO 32000-2 Table 178 places them, the caption in black Helvetica 10.
|
||||
Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
|
||||
line breaking by approximate Helvetica proportions (no font program is bundled). Text it can't
|
||||
draw (in a text box, callout, Fill & Sign text, measurement label or dynamic stamp's by-line;
|
||||
`appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
|
||||
draw (in a text box, callout, Fill & Sign text, line caption, measurement label or dynamic
|
||||
stamp's by-line; `appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
|
||||
the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and
|
||||
flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction
|
||||
mark's overlay text, which becomes page content when applied; and a restyle or resize of a
|
||||
@@ -51,6 +53,11 @@ deterministic; the engine supplies them.
|
||||
signature) and PdfCraft's rubber stamps counterrotate their appearance on rotated pages, so
|
||||
the picture or label reads upright as the page is displayed. Restyling a picture stamp keeps
|
||||
that appearance matrix. The rotation is the page's `/Rotate` at placement.
|
||||
- Sticky notes and file attachments are not counterrotated: they carry the NoRotate flag and
|
||||
their icon is drawn in an unturned 20 × 20 box. A viewer keeps them upright on a turned page,
|
||||
about the upper-left corner of `/Rect` (ISO 32000-2 §12.5.3). PdfCraft's renderer does so
|
||||
(vendored hayro-interpret patch 37), and `Summary::no_rotate` tells the UI where the icon is
|
||||
drawn.
|
||||
|
||||
## Not yet
|
||||
|
||||
|
||||
+502
-47
@@ -120,12 +120,18 @@ fn smooth_curve(pts: &[(f64, f64)]) -> String {
|
||||
smooth_segments(pts).iter().map(|[a, b, e]| format!("{} {} {} {} {} {} c\n", n(a.0), n(a.1), n(b.0), n(b.1), n(e.0), n(e.1))).collect()
|
||||
}
|
||||
|
||||
/// Bumps one cloudy outline draws at most (plus one per edge); past it the bumps grow.
|
||||
pub(crate) const MAX_CLOUD_BUMPS: usize = 20_000;
|
||||
|
||||
/// A closed cloudy outline through `pts` (§12.5.4 `/BE /S /C`): each edge becomes a row of
|
||||
/// half-circle bumps of about `r`, bulging outwards.
|
||||
pub fn cloud_path(pts: &[(f64, f64)], r: f64) -> String {
|
||||
let area: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.0 * b.1 - b.0 * a.1).sum();
|
||||
// Outward normal of an edge: to the right of travel for counter-clockwise outlines.
|
||||
let sign = if area >= 0.0 { 1.0 } else { -1.0 };
|
||||
let perimeter: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (b.0 - a.0).hypot(b.1 - a.1)).sum();
|
||||
// Each edge rounds to at least one bump, so the total stays within the budget plus one per edge.
|
||||
let r = r.max(perimeter / (2.0 * MAX_CLOUD_BUMPS as f64));
|
||||
let mut c = String::new();
|
||||
for (i, (a, b)) in pts.iter().zip(pts.iter().cycle().skip(1)).enumerate() {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
@@ -174,23 +180,42 @@ fn interior_color(d: &Dict, fallback: Option<Rgb>) -> Option<Rgb> {
|
||||
color(d, b"IC").flatten().or(fallback)
|
||||
}
|
||||
|
||||
/// The border width (ISO 32000-2 §12.5.4): `/BS /W` when there is a border style dictionary, which
|
||||
/// makes `/Border` ignored (Table 166), else the third element of `/Border [hr vr w [dash]]`, read
|
||||
/// whether or not the optional fourth element, a dash array, follows. 1 when neither says, and
|
||||
/// when the number given is negative or not finite.
|
||||
pub(crate) fn border_width(d: &Dict) -> f64 {
|
||||
if let Some(w) = d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()) {
|
||||
return w.max(0.0);
|
||||
}
|
||||
match nums(d, b"Border") {
|
||||
Some(b) if b.len() >= 3 => b[2].max(0.0),
|
||||
_ => 1.0,
|
||||
}
|
||||
let width = match d.get(b"BS").and_then(Object::as_dict) {
|
||||
Some(bs) => bs.get(b"W").and_then(Object::as_f64),
|
||||
None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(2)).and_then(Object::as_f64),
|
||||
};
|
||||
width.filter(|w| w.is_finite() && *w >= 0.0).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
/// Dash pattern operator for a dashed border, if any.
|
||||
/// Elements a dash array may have before it is drawn solid instead: the lengths are written into
|
||||
/// the appearance as they are, so a file can't make it arbitrarily large.
|
||||
const MAX_DASH: usize = 64;
|
||||
|
||||
/// A dash array (§8.4.3.6) as drawn: every element finite and non-negative, not all zero (that
|
||||
/// pattern is invalid) and at most [`MAX_DASH`] long. `None` for anything else, which is drawn solid.
|
||||
fn dash_array(o: &Object) -> Option<Vec<f64>> {
|
||||
let a = o.as_array().filter(|a| !a.is_empty() && a.len() <= MAX_DASH)?;
|
||||
let v: Vec<f64> = a.iter().map(Object::as_f64).collect::<Option<_>>()?;
|
||||
(v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0)).then_some(v)
|
||||
}
|
||||
|
||||
/// Dash pattern operator for a dashed border, if any: `/BS /S /D` with its `/D` (default `[3]`,
|
||||
/// Table 168), or, without `/BS`, the dash array that may follow the width in `/Border` (Table 166).
|
||||
fn dash(d: &Dict) -> String {
|
||||
let Some(bs) = d.get(b"BS").and_then(|b| b.as_dict()) else { return String::new() };
|
||||
if bs.name(b"S") != Some(b"D") {
|
||||
return String::new();
|
||||
}
|
||||
let arr = nums(bs, b"D").filter(|a| !a.is_empty() && a.iter().all(|x| *x >= 0.0)).unwrap_or_else(|| vec![3.0]);
|
||||
let arr = match d.get(b"BS").and_then(Object::as_dict) {
|
||||
Some(bs) if bs.name(b"S") != Some(b"D") => return String::new(),
|
||||
Some(bs) => match bs.get(b"D") {
|
||||
None => Some(vec![3.0]),
|
||||
Some(o) => dash_array(o),
|
||||
},
|
||||
None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(3)).and_then(dash_array),
|
||||
};
|
||||
let Some(arr) = arr else { return String::new() };
|
||||
format!("[{}] 0 d\n", arr.iter().map(|x| n(*x)).collect::<Vec<_>>().join(" "))
|
||||
}
|
||||
|
||||
@@ -277,13 +302,14 @@ fn text_turn(d: &Dict) -> i64 {
|
||||
|
||||
/// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that
|
||||
/// they can't, which would come out as `?`: what it is (for the message) and the character. The
|
||||
/// text of a text box, callout or Fill & Sign text, a measurement's label, a dynamic stamp's
|
||||
/// "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
|
||||
/// text of a text box, callout or Fill & Sign text, a line's caption, a measurement's label, a
|
||||
/// dynamic stamp's "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
|
||||
/// it can be drawn.
|
||||
pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
|
||||
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
|
||||
let (what, text) = match d.name(b"Subtype")? {
|
||||
b"FreeText" => ("the comment's text", text(b"Contents")?),
|
||||
b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?),
|
||||
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
|
||||
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
|
||||
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
|
||||
@@ -293,6 +319,55 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
|
||||
Some((what, first_undrawable(&text)?))
|
||||
}
|
||||
|
||||
/// `/Font` resources naming `/Helv`: standard Helvetica with WinAnsiEncoding.
|
||||
fn helvetica_resource() -> Object {
|
||||
let mut font = Dict::new();
|
||||
font.set(b"Type".to_vec(), Object::name("Font"));
|
||||
font.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
|
||||
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let mut fonts = Dict::new();
|
||||
fonts.set(b"Helv".to_vec(), Object::Dict(font));
|
||||
Object::Dict(fonts)
|
||||
}
|
||||
|
||||
/// Where a caret and its paragraph symbol go within `rect`: the box the caret is drawn in, and for
|
||||
/// `/Sy /P` the symbol's baseline origin and font size (ISO 32000-2 Table 183).
|
||||
///
|
||||
/// The caret lies within `/Rect` less `/RD` (left, top, right, bottom), when `/RD` is four finite,
|
||||
/// non-negative numbers that leave a box; otherwise within `/Rect`. The ¶ sits to the right of the
|
||||
/// caret, its height a little over half the caret's, in the room `/RD` leaves on the right; when
|
||||
/// that is too narrow, the caret gives up to half its width and the symbol shrinks to what is left,
|
||||
/// so both stay inside `/Rect` (the form's `/BBox`).
|
||||
fn caret_layout(d: &Dict, rect: [f64; 4]) -> ([f64; 4], Option<(f64, f64, f64)>) {
|
||||
let rd = nums(d, b"RD").filter(|r| r.len() == 4 && r.iter().all(|x| x.is_finite() && *x >= 0.0));
|
||||
let mut caret = match rd {
|
||||
Some(rd) => [rect[0] + rd[0], rect[1] + rd[3], rect[2] - rd[2], rect[3] - rd[1]],
|
||||
None => rect,
|
||||
};
|
||||
if !(caret[2] > caret[0] && caret[3] > caret[1]) {
|
||||
caret = rect;
|
||||
}
|
||||
if d.name(b"Sy") != Some(b"P") {
|
||||
return (caret, None);
|
||||
}
|
||||
let size = (caret[3] - caret[1]) * 0.6;
|
||||
let (gap, glyph) = (size * 0.1, text_width("\u{b6}", size));
|
||||
let need = gap + glyph;
|
||||
let room = rect[2] - caret[2];
|
||||
if room < need {
|
||||
caret[2] -= (need - room).min((caret[2] - caret[0]) * 0.5);
|
||||
}
|
||||
let room = rect[2] - caret[2];
|
||||
let scale = if need > room { room / need } else { 1.0 };
|
||||
let size = size * scale;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return (caret, None);
|
||||
}
|
||||
// The pilcrow descends about a sixth of the size below its baseline.
|
||||
(caret, Some((caret[2] + gap * scale, caret[1] + size * 0.18, size)))
|
||||
}
|
||||
|
||||
/// Draw the normal appearance of an annotation, or `None` if this subtype/variant isn't supported.
|
||||
/// Text the standard fonts can't draw comes out as `?`: [`undrawable_text`] says which, and
|
||||
/// [`crate::set_appearance`] marks the annotation with it (`pdfcraft_fonts::UNDRAWN_MARK`).
|
||||
@@ -315,6 +390,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
let w = border_width(d);
|
||||
let mut res = Dict::new();
|
||||
let mut c = String::new();
|
||||
// Content after `c` that isn't UTF-8 (WinAnsi text).
|
||||
let mut tail: Vec<u8> = Vec::new();
|
||||
let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly");
|
||||
if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") {
|
||||
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
|
||||
@@ -439,13 +516,29 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
return None;
|
||||
}
|
||||
let fill = interior_color(d, Some(col)).unwrap_or(col);
|
||||
let layout = line_layout(d, [(l[0], l[1]), (l[2], l[3])], w);
|
||||
let [p, q] = layout.line;
|
||||
c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d)));
|
||||
c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3])));
|
||||
for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) {
|
||||
for [s, e] in layout.leaders.iter().chain(&layout.strokes).chain(&layout.tick) {
|
||||
c.push_str(&format!("{} {} m {} {} l S\n", n(s.0), n(s.1), n(e.0), n(e.1)));
|
||||
}
|
||||
c.push_str("[] 0 d\n");
|
||||
for (end, (tip, from)) in ends.iter().zip([(p, q), (q, p)]) {
|
||||
if !line_end(&mut c, end, tip, from, w) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some((text, m)) = layout.caption {
|
||||
// The caption is black, in the standard font the measurement label uses.
|
||||
tail.extend(
|
||||
format!("q 0 g BT /Helv {} Tf {} {} {} {} {} {} Tm ", n(CAPTION_SIZE), n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5]))
|
||||
.bytes(),
|
||||
);
|
||||
// WinAnsi bytes go into the stream as-is, not through UTF-8.
|
||||
tail.extend(literal(&win_ansi(&text)));
|
||||
tail.extend_from_slice(b" Tj ET Q\n");
|
||||
res.set(b"Font".to_vec(), helvetica_resource());
|
||||
}
|
||||
}
|
||||
b"Polygon" | b"PolyLine" => {
|
||||
let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?;
|
||||
@@ -506,7 +599,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
b"Caret" => {
|
||||
// A filled caret: two curved flanks meeting at the top centre.
|
||||
let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
|
||||
let [x0, y0, x1, y1] = rect;
|
||||
let (caret, pilcrow) = caret_layout(d, rect);
|
||||
let [x0, y0, x1, y1] = caret;
|
||||
let (cx, h) = ((x0 + x1) / 2.0, y1 - y0);
|
||||
c.push_str(&format!(
|
||||
"{}{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c h f\n",
|
||||
@@ -526,11 +620,22 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
n(x1),
|
||||
n(y0)
|
||||
));
|
||||
if let Some((x, y, size)) = pilcrow {
|
||||
// `/Sy /P`: a new paragraph symbol beside the caret (Table 183), in its colour.
|
||||
// 0xB6 is the pilcrow in WinAnsiEncoding.
|
||||
let mut out = c.into_bytes();
|
||||
out.extend(format!("BT /Helv {} Tf {} {} Td (", n(size), n(x), n(y)).bytes());
|
||||
out.push(0xB6);
|
||||
out.extend_from_slice(b") Tj ET\n");
|
||||
res.set(b"Font".to_vec(), helvetica_resource());
|
||||
return Some(form(rect, &out, res));
|
||||
}
|
||||
}
|
||||
b"Ink" => {
|
||||
let col = stroke?;
|
||||
let list = d.get(b"InkList")?.as_array()?;
|
||||
c.push_str(&format!("{}{} w 1 J 1 j\n", rg_stroke(col), n(w)));
|
||||
// `/BS` gives an ink stroke its width and dash pattern (Table 182).
|
||||
c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(w), dash(d)));
|
||||
for s in list {
|
||||
let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
|
||||
let pts: Vec<(f64, f64)> = pts.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
|
||||
@@ -664,7 +769,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
}
|
||||
let kind = crate::StampKind::from_name(other)?;
|
||||
let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);
|
||||
return Some(turned(stamp(kind, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
|
||||
let sign_here = kind.group() == crate::StampGroup::SignHere;
|
||||
return Some(turned(stamp(kind.label(), sign_here, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
|
||||
}
|
||||
}
|
||||
if turn != 0 {
|
||||
@@ -767,14 +873,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
y -= size * 1.2;
|
||||
}
|
||||
out.extend_from_slice(b"ET\n");
|
||||
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"));
|
||||
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let mut fonts = Dict::new();
|
||||
fonts.set(b"Helv".to_vec(), Object::Dict(font));
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts));
|
||||
res.set(b"Font".to_vec(), helvetica_resource());
|
||||
let mut stream = form(full, &out, res);
|
||||
if let Some(m) = matrix {
|
||||
stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
|
||||
@@ -786,6 +885,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
// PdfCraft measurement captions are kept separate from the comment's free-form text.
|
||||
// A restyle regenerates the path and its value together.
|
||||
let mut out = c.into_bytes();
|
||||
out.extend(tail);
|
||||
if let Some(value) = d.get(b"PCMeasureValue").and_then(Object::as_string) {
|
||||
let value = value.to_text();
|
||||
if value.chars().count() <= 256 && matches!(subtype.as_slice(), b"Line" | b"PolyLine" | b"Polygon") {
|
||||
@@ -797,22 +897,285 @@ pub fn build(d: &Dict) -> Option<Stream> {
|
||||
// WinAnsi bytes (e.g. 0xB2 for "²") go into the stream as-is, not through UTF-8.
|
||||
out.extend(literal(&win_ansi(&value)));
|
||||
out.extend_from_slice(b" Tj ET\n");
|
||||
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"));
|
||||
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
let mut fonts = Dict::new();
|
||||
fonts.set(b"Helv".to_vec(), Object::Dict(font));
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts));
|
||||
res.set(b"Font".to_vec(), helvetica_resource());
|
||||
}
|
||||
}
|
||||
Some(form(rect, &out, res))
|
||||
}
|
||||
|
||||
/// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp
|
||||
/// another program wrote without an appearance. Names are matched byte for byte, as PDF names
|
||||
/// are compared (§7.3.5). Eight are stamps of PdfCraft's palette; the other six take a label of
|
||||
/// their own and the palette's colour for their meaning.
|
||||
fn standard_stamp(name: &[u8]) -> Option<(&'static str, Rgb)> {
|
||||
use crate::StampKind::*;
|
||||
let palette = [Approved, NotApproved, NotForPublicRelease, Confidential, Final, ForComment, Draft, ForPublicRelease];
|
||||
if let Some(kind) = palette.into_iter().find(|k| k.name().as_bytes() == name) {
|
||||
return Some((kind.label(), kind.color()));
|
||||
}
|
||||
let (label, like) = match name {
|
||||
b"Experimental" => ("EXPERIMENTAL", Draft),
|
||||
b"AsIs" => ("AS IS", Draft),
|
||||
b"Expired" => ("EXPIRED", NotApproved),
|
||||
b"Sold" => ("SOLD", Approved),
|
||||
b"Departmental" => ("DEPARTMENTAL", Draft),
|
||||
b"TopSecret" => ("TOP SECRET", Confidential),
|
||||
_ => return None,
|
||||
};
|
||||
Some((label, like.color()))
|
||||
}
|
||||
|
||||
/// The neutral grey of a stamp whose name has no drawing.
|
||||
const PLACEHOLDER_GREY: Rgb = [0.45, 0.45, 0.45];
|
||||
|
||||
/// The display appearance of a rubber stamp another program wrote without one: the stamp its
|
||||
/// `/Name` names (Draft when there is none, Table 184's default) in its `/C` colour or the
|
||||
/// stamp's own, or for any other name a thin grey frame with both diagonals, so the stamp stays
|
||||
/// visible and can be selected. The frame is grey whatever the `/C`: it stands in for a stamp
|
||||
/// that cannot be drawn, so it takes none of that stamp's colour. The name is never drawn as text.
|
||||
///
|
||||
/// For display only ([`crate::with_missing_appearances`]): [`build`] declines these stamps, so
|
||||
/// edits (restyling, flattening) never write this drawing into the file. `None` for any other
|
||||
/// annotation, one of PdfCraft's own stamps, a dictionary with an `/AP` (a stamp's own artwork is
|
||||
/// never replaced; the display copy passes the dictionary without an `/AP` that has no normal
|
||||
/// appearance), or a `/Rect` that isn't finite or is under a point wide or high.
|
||||
pub(crate) fn display_stamp(d: &Dict) -> Option<Stream> {
|
||||
let own = matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) || d.contains(b"PCPicture") || d.contains(b"PCOutline");
|
||||
if d.name(b"Subtype") != Some(b"Stamp") || own || d.contains(b"AP") {
|
||||
return None;
|
||||
}
|
||||
let rect = nums(d, b"Rect")?;
|
||||
let [a, b, c, e] = rect.as_slice() else { return None };
|
||||
let rect = [a.min(*c), b.min(*e), a.max(*c), b.max(*e)];
|
||||
if !rect.iter().all(|v| v.is_finite()) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
|
||||
return None;
|
||||
}
|
||||
let opacity = d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
// A malformed `/C` falls back to the stamp's own colour rather than hiding the stamp.
|
||||
let stroke = color(d, b"C").flatten();
|
||||
let mut res = Dict::new();
|
||||
if let Some(gs) = ext_gstate(opacity, false) {
|
||||
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
|
||||
}
|
||||
// A stamp whose intent (`/IT`, PDF 2.0) is an image or a snapshot has no `/Name` to default.
|
||||
let stamp_intent = d.name(b"IT").is_none_or(|it| it == b"Stamp");
|
||||
let name = d.name(b"Name").or(stamp_intent.then_some(b"Draft".as_slice()));
|
||||
if let Some((label, col)) = name.and_then(standard_stamp) {
|
||||
return Some(stamp(label, false, rect, stroke.unwrap_or(col), None, opacity, res));
|
||||
}
|
||||
let [x0, y0, x1, y1] = rect;
|
||||
let (a0, b0, a1, b1) = (x0 + 0.5, y0 + 0.5, x1 - 0.5, y1 - 0.5);
|
||||
let mut c = String::new();
|
||||
if opacity < 1.0 {
|
||||
c.push_str("/GS0 gs\n");
|
||||
}
|
||||
c.push_str(&format!(
|
||||
"{}1 w\n{} {} {} {} re\n{} {} m {} {} l\n{} {} m {} {} l\nS\n",
|
||||
// Grey whatever the `/C`: the placeholder is not the stamp, so it takes none of its colour.
|
||||
rg_stroke(PLACEHOLDER_GREY),
|
||||
n(a0),
|
||||
n(b0),
|
||||
n(a1 - a0),
|
||||
n(b1 - b0),
|
||||
n(a0),
|
||||
n(b0),
|
||||
n(a1),
|
||||
n(b1),
|
||||
n(a0),
|
||||
n(b1),
|
||||
n(a1),
|
||||
n(b0)
|
||||
));
|
||||
Some(form(rect, c.as_bytes(), res))
|
||||
}
|
||||
|
||||
/// Size of a line's caption, as of a measurement's label.
|
||||
const CAPTION_SIZE: f64 = 10.0;
|
||||
|
||||
/// Characters of a line's caption drawn at most, as for a measurement's label.
|
||||
const MAX_CAPTION_CHARS: usize = 256;
|
||||
|
||||
/// Leader lengths and caption offsets (Table 178) are held within this many points (200 inches,
|
||||
/// the largest page side ISO 32000-2 Annex C allows), so an absurd value can't overflow.
|
||||
const MAX_LINE_EXTENT: f64 = 14_400.0;
|
||||
|
||||
/// A Table 178 length or offset: finite and within [`MAX_LINE_EXTENT`], 0 when absent or not one.
|
||||
fn line_length(v: Option<f64>) -> f64 {
|
||||
v.filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(-MAX_LINE_EXTENT, MAX_LINE_EXTENT))
|
||||
}
|
||||
|
||||
/// The caption a Line with `/Cap true` shows (ISO 32000-2 Table 178): its `/Contents`, else the
|
||||
/// plain text of its `/RC`, on one line and cut to [`MAX_CAPTION_CHARS`]. `None` without a
|
||||
/// caption, and for PdfCraft's own measurements, whose label (`/PCMeasureValue`) is the caption.
|
||||
fn line_caption(d: &Dict) -> Option<String> {
|
||||
if !matches!(d.get(b"Cap"), Some(Object::Bool(true))) || d.contains(b"PCMeasureValue") {
|
||||
return None;
|
||||
}
|
||||
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
|
||||
let raw = text(b"Contents").filter(|t| !t.trim().is_empty()).or_else(|| text(b"RC").map(|rc| rich_plain(&rc)))?;
|
||||
let words: Vec<&str> = raw.split_whitespace().collect();
|
||||
let caption: String = words.join(" ").chars().filter(|c| !c.is_control()).take(MAX_CAPTION_CHARS).collect();
|
||||
(!caption.is_empty()).then_some(caption)
|
||||
}
|
||||
|
||||
/// The text of rich text (§12.7.4.3, XHTML): its markup dropped, the five XML entities and
|
||||
/// numeric character references read, block ends read as spaces.
|
||||
fn rich_plain(rc: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut tag: Option<String> = None;
|
||||
// Rich text past this is not caption material; it bounds the work.
|
||||
for ch in rc.chars().take(MAX_CAPTION_CHARS * 64) {
|
||||
match (&mut tag, ch) {
|
||||
(None, '<') => tag = Some(String::new()),
|
||||
(Some(name), '>') => {
|
||||
let name =
|
||||
name.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or_default().to_ascii_lowercase();
|
||||
if matches!(name.as_str(), "p" | "br" | "div" | "li") {
|
||||
out.push(' ');
|
||||
}
|
||||
tag = None;
|
||||
}
|
||||
(Some(name), c) => {
|
||||
if name.len() < 16 {
|
||||
name.push(c);
|
||||
}
|
||||
}
|
||||
(None, c) => out.push(c),
|
||||
}
|
||||
}
|
||||
let mut text = String::new();
|
||||
let mut rest = out.as_str();
|
||||
while let Some(at) = rest.find('&') {
|
||||
text.push_str(rest.get(..at).unwrap_or_default());
|
||||
let after = rest.get(at + 1..).unwrap_or_default();
|
||||
let entity = after.find(';').filter(|&end| end <= 10).and_then(|end| Some((after.get(..end)?, end)));
|
||||
let decoded = entity.and_then(|(name, end)| {
|
||||
let c = match name {
|
||||
"amp" => '&',
|
||||
"lt" => '<',
|
||||
"gt" => '>',
|
||||
"quot" => '"',
|
||||
"apos" => '\'',
|
||||
_ => {
|
||||
let num = name.strip_prefix('#')?;
|
||||
let code = match num.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
|
||||
None => num.parse().ok()?,
|
||||
};
|
||||
char::from_u32(code)?
|
||||
}
|
||||
};
|
||||
Some((c, end))
|
||||
});
|
||||
match decoded {
|
||||
Some((c, end)) => {
|
||||
text.push(c);
|
||||
rest = after.get(end + 1..).unwrap_or_default();
|
||||
}
|
||||
None => {
|
||||
text.push('&');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
text.push_str(rest);
|
||||
text
|
||||
}
|
||||
|
||||
/// Where a Line annotation's parts go (ISO 32000-2 §12.5.6.7, Table 178).
|
||||
#[derive(Debug, Default)]
|
||||
struct LineLayout {
|
||||
/// The line itself, start to end: `/L`, or `/L` moved out by its leader lines.
|
||||
line: [(f64, f64); 2],
|
||||
/// Strokes along the line: the whole line, or the two pieces either side of an inline caption.
|
||||
strokes: Vec<[(f64, f64); 2]>,
|
||||
/// The leader lines, from `/L` (past the `/LLO` gap) to the line and on by `/LLE`.
|
||||
leaders: Vec<[(f64, f64); 2]>,
|
||||
/// A short stroke from the line to a caption `/CO` moved off it.
|
||||
tick: Option<[(f64, f64); 2]>,
|
||||
/// The caption and its text matrix.
|
||||
caption: Option<(String, [f64; 6])>,
|
||||
}
|
||||
|
||||
/// Lay out a Line annotation from `/L` = `[a b]`, line width `w`, and its leader and caption
|
||||
/// entries.
|
||||
///
|
||||
/// Leader lines: a positive `/LL` puts the line on the left of travel from `a` to `b` (above `/L`
|
||||
/// for a line drawn left to right), so the leader lines, followed from the line to `/L`, turn
|
||||
/// clockwise from the direction of travel; a negative one puts it on the right. The line sits
|
||||
/// `|LL| + LLO` from `/L`. `/LLE` and `/LLO` are non-negative: a negative one counts as 0.
|
||||
///
|
||||
/// Caption (`/Cap true`): centred on the line's midpoint and turned with it so it reads left to
|
||||
/// right (bottom to top for a vertical line). `/CP /Inline` (the default) centres it on the line,
|
||||
/// which is broken around it; `/Top` sets it on top of the unbroken line. `/CO [h v]` moves it `h`
|
||||
/// along the line and `v` across it (positive: up in reading direction); a caption moved off an
|
||||
/// inline line gets a tick from the line to it.
|
||||
///
|
||||
/// A zero-length or overflowing `/L` has no direction: it gets neither leader lines nor caption.
|
||||
/// Every point is finite; if anything derived from the entries is not, they are left out.
|
||||
fn line_layout(d: &Dict, [a, b]: [(f64, f64); 2], w: f64) -> LineLayout {
|
||||
let plain = LineLayout { line: [a, b], strokes: vec![[a, b]], ..LineLayout::default() };
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let len = dx.hypot(dy);
|
||||
if !len.is_finite() || len <= 0.0 {
|
||||
return plain;
|
||||
}
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let mut out = LineLayout { line: [a, b], ..LineLayout::default() };
|
||||
let ll = line_length(d.get(b"LL").and_then(Object::as_f64));
|
||||
if ll != 0.0 {
|
||||
// The unit normal from `/L` towards the line: left of travel for a positive /LL.
|
||||
let s = ll.signum();
|
||||
let (nx, ny) = (-uy * s, ux * s);
|
||||
let llo = line_length(d.get(b"LLO").and_then(Object::as_f64)).max(0.0);
|
||||
let lle = line_length(d.get(b"LLE").and_then(Object::as_f64)).max(0.0);
|
||||
let at = |p: (f64, f64), k: f64| (p.0 + nx * k, p.1 + ny * k);
|
||||
let off = ll.abs() + llo;
|
||||
out.line = [at(a, off), at(b, off)];
|
||||
out.leaders = vec![[at(a, llo), at(a, off + lle)], [at(b, llo), at(b, off + lle)]];
|
||||
}
|
||||
let [p, _] = out.line;
|
||||
let along = |t: f64| (p.0 + ux * t, p.1 + uy * t);
|
||||
let mut gap = None;
|
||||
if let Some(text) = line_caption(d) {
|
||||
let size = CAPTION_SIZE;
|
||||
let width = text_width(&text, size);
|
||||
// Reading direction, and "up" across it.
|
||||
let (tx, ty) = if ux < 0.0 || (ux == 0.0 && uy < 0.0) { (-ux, -uy) } else { (ux, uy) };
|
||||
let (vx, vy) = (-ty, tx);
|
||||
let co = nums(d, b"CO").filter(|c| c.len() == 2).unwrap_or_default();
|
||||
let h = line_length(co.first().copied());
|
||||
let v = line_length(co.get(1).copied());
|
||||
let top = d.name(b"CP") == Some(b"Top");
|
||||
// The caption's centre, as a distance along the line from `p`.
|
||||
let centre = len / 2.0 + h * (tx * ux + ty * uy);
|
||||
let mid = along(centre);
|
||||
// Baseline across the line: on top of it, or with the text centred on it.
|
||||
let base = if top { w.max(0.0) / 2.0 + 2.0 + v } else { v - size * 0.35 };
|
||||
let origin = (mid.0 - tx * width / 2.0 + vx * base, mid.1 - ty * width / 2.0 + vy * base);
|
||||
out.caption = Some((text, [tx, ty, -ty, tx, origin.0, origin.1]));
|
||||
if !top && v.abs() < size / 2.0 {
|
||||
let half = width / 2.0 + 2.0;
|
||||
gap = Some(((centre - half).clamp(0.0, len), (centre + half).clamp(0.0, len)));
|
||||
} else if !top {
|
||||
let reach = v - v.signum() * size * 0.4;
|
||||
out.tick = Some([mid, (mid.0 + vx * reach, mid.1 + vy * reach)]);
|
||||
}
|
||||
}
|
||||
out.strokes = match gap {
|
||||
Some((g0, g1)) => [(0.0, g0), (g1, len)].into_iter().filter(|(s, e)| e > s).map(|(s, e)| [along(s), along(e)]).collect(),
|
||||
None => vec![out.line],
|
||||
};
|
||||
let finite = |q: &(f64, f64)| q.0.is_finite() && q.1.is_finite();
|
||||
let all_finite =
|
||||
out.line.iter().chain(out.strokes.iter().flatten()).chain(out.leaders.iter().flatten()).chain(out.tick.iter().flatten()).all(finite)
|
||||
&& out.caption.as_ref().is_none_or(|(_, m)| m.iter().all(|x| x.is_finite()));
|
||||
if all_finite { out } else { plain }
|
||||
}
|
||||
|
||||
/// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold
|
||||
/// capitals, and the dynamic stamps' "By … at …" line.
|
||||
fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
|
||||
fn stamp(label: &str, sign_here: bool, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
|
||||
let [x0, y0, x1, y1] = rect;
|
||||
let h = y1 - y0;
|
||||
let mut c = String::new();
|
||||
@@ -821,7 +1184,7 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
|
||||
}
|
||||
let lw = (h * 0.07).clamp(1.0, 3.0);
|
||||
let inset = lw / 2.0 + 0.5;
|
||||
if kind.group() == crate::StampGroup::SignHere {
|
||||
if sign_here {
|
||||
// A tag pointing left, filled, with white text.
|
||||
let tip = h * 0.45;
|
||||
c.push_str(&format!(
|
||||
@@ -887,16 +1250,15 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
|
||||
n(b0)
|
||||
));
|
||||
}
|
||||
let label = kind.label();
|
||||
let (title_h, by_h) = if by.is_some() { (h * 0.5, h * 0.22) } else { (h * 0.52, 0.0) };
|
||||
let text_area = if kind.group() == crate::StampGroup::SignHere { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
|
||||
let text_area = if sign_here { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
|
||||
let mut size = title_h;
|
||||
let tw = text_width(label, size) * 1.12;
|
||||
if tw > text_area.1 - text_area.0 - 4.0 {
|
||||
size *= (text_area.1 - text_area.0 - 4.0) / tw;
|
||||
}
|
||||
let tw = text_width(label, size) * 1.12;
|
||||
let text_col = if kind.group() == crate::StampGroup::SignHere { [1.0, 1.0, 1.0] } else { col };
|
||||
let text_col = if sign_here { [1.0, 1.0, 1.0] } else { col };
|
||||
let ty = if by.is_some() { y0 + h * 0.48 } else { y0 + (h - size * 0.72) / 2.0 };
|
||||
let mut out = c.into_bytes();
|
||||
out.extend(
|
||||
@@ -969,14 +1331,107 @@ fn attach_icon(name: &str, col: Rgb) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// A closed circle path (four Bézier quarters) centred on (`x`, `y`).
|
||||
fn circle_path(x: f64, y: f64, r: f64) -> String {
|
||||
let k = r * 0.5523;
|
||||
let p = |v: f64| n(v);
|
||||
format!(
|
||||
"{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c h\n",
|
||||
p(x + r),
|
||||
p(y),
|
||||
p(x + r),
|
||||
p(y + k),
|
||||
p(x + k),
|
||||
p(y + r),
|
||||
p(x),
|
||||
p(y + r),
|
||||
p(x - k),
|
||||
p(y + r),
|
||||
p(x - r),
|
||||
p(y + k),
|
||||
p(x - r),
|
||||
p(y),
|
||||
p(x - r),
|
||||
p(y - k),
|
||||
p(x - k),
|
||||
p(y - r),
|
||||
p(x),
|
||||
p(y - r),
|
||||
p(x + k),
|
||||
p(y - r),
|
||||
p(x + r),
|
||||
p(y - k),
|
||||
p(x + r),
|
||||
p(y)
|
||||
)
|
||||
}
|
||||
|
||||
/// A note's icon in a 20 × 20 box: filled in `col`, outlined in dark grey. Each name of
|
||||
/// [`crate::NoteIcon`] has its own shape, so the icon a note names is the one it shows (ISO
|
||||
/// 32000-2 §12.5.6.4, Table 175); a name PdfCraft doesn't know draws as `Note`.
|
||||
fn note_icon(name: &str, col: Rgb) -> String {
|
||||
let mut s = format!("{}0.25 0.25 0.25 RG 0.8 w 1 j 1 J\n", rg(col));
|
||||
if name == "Comment" {
|
||||
s.push_str("3 18.5 m 17 18.5 l 18.5 18.5 18.5 17 18.5 17 c 18.5 8 l 18.5 6.5 17 6.5 17 6.5 c 9.5 6.5 l 5 2 l 5.5 6.5 l 3 6.5 l 1.5 6.5 1.5 8 1.5 8 c 1.5 17 l 1.5 18.5 3 18.5 3 18.5 c h B\n");
|
||||
s.push_str("4.5 15 m 15.5 15 l 4.5 12.5 m 15.5 12.5 l 4.5 10 m 11.5 10 l S\n");
|
||||
} else {
|
||||
s.push_str("3 19 m 13 19 l 17 15 l 17 1 l 3 1 l h B\n13 19 m 13 15 l 17 15 l S\n");
|
||||
s.push_str("5.5 12 m 14.5 12 l 5.5 9 m 14.5 9 l 5.5 6 m 11.5 6 l S\n");
|
||||
match name {
|
||||
"Comment" => {
|
||||
s.push_str("3 18.5 m 17 18.5 l 18.5 18.5 18.5 17 18.5 17 c 18.5 8 l 18.5 6.5 17 6.5 17 6.5 c 9.5 6.5 l 5 2 l 5.5 6.5 l 3 6.5 l 1.5 6.5 1.5 8 1.5 8 c 1.5 17 l 1.5 18.5 3 18.5 3 18.5 c h B\n");
|
||||
s.push_str("4.5 15 m 15.5 15 l 4.5 12.5 m 15.5 12.5 l 4.5 10 m 11.5 10 l S\n");
|
||||
}
|
||||
// A key lying flat: a round bow with a hole, a shaft and two bits.
|
||||
"Key" => {
|
||||
s.push_str(&circle_path(5.5, 10.0, 4.5));
|
||||
s.push_str(&circle_path(5.0, 10.0, 1.5));
|
||||
s.push_str(
|
||||
"9.5 11.2 m 18.5 11.2 l 18.5 8.8 l 17 8.8 l 17 6 l 15 6 l 15 8.8 l 13.5 8.8 l 13.5 6.8 l 11.5 6.8 l 11.5 8.8 l 9.5 8.8 l h B*\n",
|
||||
);
|
||||
}
|
||||
// A disc with a question mark.
|
||||
"Help" => {
|
||||
s.push_str(&circle_path(10.0, 10.0, 8.5));
|
||||
s.push_str("B\n1.6 w 7 12.8 m 7 15.6 13 15.6 13 12.8 c 13 10.6 10 10.8 10 8.2 c S\n10 5 m 10 5.1 l S\n");
|
||||
}
|
||||
// An insertion caret.
|
||||
"Insert" => s.push_str("1.5 3 m 10 18 l 18.5 3 l 14.5 3 l 10 11 l 5.5 3 l h B\n"),
|
||||
// A caret over a bar: a new paragraph goes here.
|
||||
"NewParagraph" => s.push_str("3.5 9 m 10 18.5 l 16.5 9 l h B\n3 2 14 4 re B\n"),
|
||||
// A pilcrow: a filled bowl and two stems.
|
||||
"Paragraph" => {
|
||||
s.push_str("11 18.5 m 7 18.5 4 16.3 4 13.2 c 4 10.1 7 8 11 8 c h B\n");
|
||||
s.push_str("11 18.5 m 16 18.5 l 16 1.5 l 14 1.5 l 14 16.5 l 13 16.5 l 13 1.5 l 11 1.5 l h B\n");
|
||||
}
|
||||
// A tick.
|
||||
"Check" => s.push_str("1.5 10.5 m 4.5 13.5 l 8 9.5 l 16 18.5 l 18.5 15.5 l 8 3.5 l h B\n"),
|
||||
// A ring.
|
||||
"Circle" => {
|
||||
s.push_str(&circle_path(10.0, 10.0, 8.5));
|
||||
s.push_str(&circle_path(10.0, 10.0, 5.0));
|
||||
s.push_str("B*\n");
|
||||
}
|
||||
// A thick X.
|
||||
"Cross" => s.push_str("4 1.5 m 10 7.5 l 16 1.5 l 18.5 4 l 12.5 10 l 18.5 16 l 16 18.5 l 10 12.5 l 4 18.5 l 1.5 16 l 7.5 10 l 1.5 4 l h B\n"),
|
||||
// A ring with sighting lines through it.
|
||||
"CrossHairs" => {
|
||||
s.push_str(&circle_path(10.0, 10.0, 7.0));
|
||||
s.push_str(&circle_path(10.0, 10.0, 4.5));
|
||||
s.push_str("B*\n1.2 w 10 0.5 m 10 19.5 l 0.5 10 m 19.5 10 l S\n");
|
||||
}
|
||||
// A five-pointed star.
|
||||
"Star" => {
|
||||
let points: Vec<String> = (0..10)
|
||||
.map(|i| {
|
||||
let r = if i % 2 == 0 { 9.5 } else { 3.9 };
|
||||
let a = std::f64::consts::FRAC_PI_2 + f64::from(i) * std::f64::consts::PI / 5.0;
|
||||
format!("{} {}", n(10.0 + r * a.cos()), n(9.5 + r * a.sin()))
|
||||
})
|
||||
.collect();
|
||||
s.push_str(&format!("{} m {} l h B\n", points[0], points[1..].join(" l ")));
|
||||
}
|
||||
// Block arrows.
|
||||
"RightArrow" => s.push_str("1.5 7 m 11 7 l 11 2.5 l 18.5 10 l 11 17.5 l 11 13 l 1.5 13 l h B\n"),
|
||||
"UpArrow" => s.push_str("7 1.5 m 7 11 l 2.5 11 l 10 18.5 l 17.5 11 l 13 11 l 13 1.5 l h B\n"),
|
||||
_ => {
|
||||
s.push_str("3 19 m 13 19 l 17 15 l 17 1 l 3 1 l h B\n13 19 m 13 15 l 17 15 l S\n");
|
||||
s.push_str("5.5 12 m 14.5 12 l 5.5 9 m 14.5 9 l 5.5 6 m 11.5 6 l S\n");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
+169
-45
@@ -14,6 +14,8 @@
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
|
||||
|
||||
pub mod appearance;
|
||||
@@ -66,7 +68,9 @@ impl Markup {
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard text-annotation icon names (§12.5.6.4, Table 175).
|
||||
/// Text-annotation icon names (`/Name`). The first seven are the standard names ISO 32000-2
|
||||
/// §12.5.6.4, Table 175 asks every viewer to draw; the rest are further names in common use, which
|
||||
/// the same table allows ("Additional names may be supported as well").
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum NoteIcon {
|
||||
#[default]
|
||||
@@ -77,6 +81,13 @@ pub enum NoteIcon {
|
||||
Key,
|
||||
NewParagraph,
|
||||
Paragraph,
|
||||
Check,
|
||||
Circle,
|
||||
Cross,
|
||||
CrossHairs,
|
||||
Star,
|
||||
RightArrow,
|
||||
UpArrow,
|
||||
}
|
||||
|
||||
impl NoteIcon {
|
||||
@@ -89,11 +100,36 @@ impl NoteIcon {
|
||||
NoteIcon::Key => "Key",
|
||||
NoteIcon::NewParagraph => "NewParagraph",
|
||||
NoteIcon::Paragraph => "Paragraph",
|
||||
NoteIcon::Check => "Check",
|
||||
NoteIcon::Circle => "Circle",
|
||||
NoteIcon::Cross => "Cross",
|
||||
NoteIcon::CrossHairs => "CrossHairs",
|
||||
NoteIcon::Star => "Star",
|
||||
NoteIcon::RightArrow => "RightArrow",
|
||||
NoteIcon::UpArrow => "UpArrow",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every icon, the standard names first.
|
||||
pub const ALL: [NoteIcon; 14] = [
|
||||
Self::Comment,
|
||||
Self::Note,
|
||||
Self::Help,
|
||||
Self::Insert,
|
||||
Self::Key,
|
||||
Self::NewParagraph,
|
||||
Self::Paragraph,
|
||||
Self::Check,
|
||||
Self::Circle,
|
||||
Self::Cross,
|
||||
Self::CrossHairs,
|
||||
Self::Star,
|
||||
Self::RightArrow,
|
||||
Self::UpArrow,
|
||||
];
|
||||
|
||||
pub fn from_name(n: &str) -> Option<Self> {
|
||||
[Self::Comment, Self::Note, Self::Help, Self::Insert, Self::Key, Self::NewParagraph, Self::Paragraph].into_iter().find(|i| i.name() == n)
|
||||
Self::ALL.into_iter().find(|i| i.name() == n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,17 +701,20 @@ pub fn page_refs(doc: &Document) -> Result<Vec<ObjRef>, AnnotError> {
|
||||
/// Depth-first walk over the leaf pages under `top`. It keeps one cursor per open `/Kids` array,
|
||||
/// never one entry per child, so a child listed many times or shared between nodes is skipped by
|
||||
/// the seen check without being queued first (`pdfcraft_model::pages` walks the same way).
|
||||
/// Cycles end at the seen check and at most a million nodes are visited.
|
||||
/// Cycles end at the seen check, a `/Kids` array object shared by several nodes is read once,
|
||||
/// and at most a million nodes and four million `/Kids` entries are read.
|
||||
struct PageWalk<'a> {
|
||||
doc: &'a Document,
|
||||
seen: std::collections::HashSet<ObjRef>,
|
||||
pending: Vec<(std::sync::Arc<Object>, usize)>,
|
||||
/// `/Kids` entries read so far.
|
||||
examined: usize,
|
||||
}
|
||||
|
||||
impl<'a> PageWalk<'a> {
|
||||
fn new(doc: &'a Document, top: ObjRef) -> Self {
|
||||
let top = std::sync::Arc::new(Object::Array(vec![Object::Ref(top)]));
|
||||
Self { doc, seen: Default::default(), pending: vec![(top, 0)] }
|
||||
Self { doc, seen: Default::default(), pending: vec![(top, 0)], examined: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -690,8 +729,9 @@ impl Iterator for PageWalk<'_> {
|
||||
};
|
||||
let node = kid.as_ref();
|
||||
*next += 1;
|
||||
self.examined += 1;
|
||||
let Some(node) = node else { continue };
|
||||
if self.seen.len() >= 1_000_000 {
|
||||
if self.seen.len() >= 1_000_000 || self.examined > 4_000_000 {
|
||||
self.pending.clear();
|
||||
return None;
|
||||
}
|
||||
@@ -700,8 +740,15 @@ impl Iterator for PageWalk<'_> {
|
||||
}
|
||||
let obj = self.doc.get(node);
|
||||
let Some(d) = obj.as_dict() else { continue };
|
||||
match d.get(b"Kids").map(|k| self.doc.resolve(k)) {
|
||||
Some(kids) if d.name(b"Type") != Some(b"Page") => self.pending.push((kids, 0)),
|
||||
match d.get(b"Kids") {
|
||||
// A `/Kids` array object shared by several nodes is read under the first: under
|
||||
// the others it would only list nodes already seen.
|
||||
Some(Object::Ref(array)) if d.name(b"Type") != Some(b"Page") => {
|
||||
if self.seen.insert(*array) {
|
||||
self.pending.push((self.doc.get(*array), 0));
|
||||
}
|
||||
}
|
||||
Some(kids) if d.name(b"Type") != Some(b"Page") => self.pending.push((self.doc.resolve(kids), 0)),
|
||||
_ => return Some(node),
|
||||
}
|
||||
}
|
||||
@@ -717,11 +764,21 @@ fn page_ref(doc: &Document, page: usize) -> Result<ObjRef, AnnotError> {
|
||||
fn annots(doc: &Document, page: ObjRef) -> Vec<Object> {
|
||||
let obj = doc.get(page);
|
||||
let Some(a) = obj.as_dict().and_then(|d| d.get(b"Annots")) else { return Vec::new() };
|
||||
doc.resolve(a).as_array().cloned().unwrap_or_default()
|
||||
let list = doc.resolve(a).as_array().cloned().unwrap_or_default();
|
||||
#[cfg(test)]
|
||||
ANNOTS_ENTRIES_COPIED.with(|n| n.set(n.get() + list.len()));
|
||||
list
|
||||
}
|
||||
|
||||
/// Replace a page's `/Annots`, writing into the shared array object when it is indirect.
|
||||
fn set_annots(doc: &mut Document, page: ObjRef, list: Vec<Object>) -> Result<(), AnnotError> {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Entries copied out of pages' `/Annots` arrays.
|
||||
static ANNOTS_ENTRIES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Replace a page's `/Annots`, writing into the shared array object when it is indirect. An empty
|
||||
/// list removes a direct `/Annots`.
|
||||
pub fn set_annots(doc: &mut Document, page: ObjRef, list: Vec<Object>) -> Result<(), pdfcraft_cos::CosError> {
|
||||
let existing = doc.get(page).as_dict().and_then(|d| d.reference(b"Annots"));
|
||||
match existing {
|
||||
Some(r) if doc.get(r).as_array().is_some() => doc.set(r, Object::Array(list)),
|
||||
@@ -788,6 +845,17 @@ fn annotation_flags(doc: &Document, d: &Dict) -> i64 {
|
||||
d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Whether the renderer keeps the annotation upright on a turned page: the NoRotate flag, with
|
||||
/// `/F` read as the renderer reads it (a real truncated, a value that isn't a `u32` no flags).
|
||||
fn drawn_upright(doc: &Document, d: &Dict) -> bool {
|
||||
let f = match d.get(b"F").map(|f| doc.resolve(f)).as_deref() {
|
||||
Some(Object::Int(i)) => *i,
|
||||
Some(Object::Real(r)) => *r as i64,
|
||||
_ => 0,
|
||||
};
|
||||
u32::try_from(f).is_ok_and(|f| i64::from(f) & FLAG_NO_ROTATE != 0)
|
||||
}
|
||||
|
||||
/// Whether any page has a Fill & Sign annotation that flatten would bake in (not hidden).
|
||||
pub fn has_visible_fill_sign(doc: &Document) -> bool {
|
||||
let Ok(pages) = page_refs(doc) else { return false };
|
||||
@@ -956,7 +1024,7 @@ fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {
|
||||
grow(bounds([*from, *to].into_iter()).unwrap_or_default(), pad + 1.0)
|
||||
}
|
||||
Shape::Ink { strokes } | Shape::Signature { strokes } => {
|
||||
if strokes.iter().all(|s| s.is_empty()) || !strokes.iter().flatten().all(|p| finite(p)) {
|
||||
if strokes.iter().all(Vec::is_empty) || !strokes.iter().flatten().all(|p| finite(p)) {
|
||||
return Err(bad("drawing (no points)"));
|
||||
}
|
||||
// Strokes of three or more points are drawn as curves, which stay within their
|
||||
@@ -1167,7 +1235,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
|
||||
d.set(b"PCOutline".to_vec(), Object::Array(list));
|
||||
}
|
||||
Shape::CustomStamp { name, picture, image, size, .. } => {
|
||||
let clean: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
|
||||
let clean: String = name.chars().filter(char::is_ascii_alphanumeric).collect();
|
||||
d.set(b"Name".to_vec(), Object::name(&format!("PCCustom{clean}")));
|
||||
d.set(b"PCPicture".to_vec(), Object::Ref(*picture));
|
||||
d.set(b"PCPictureImage".to_vec(), Object::Bool(*image));
|
||||
@@ -1532,7 +1600,14 @@ pub fn with_missing_appearances_cached(doc: &Document, cache: &mut AppearanceCac
|
||||
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
|
||||
continue;
|
||||
}
|
||||
let Some(stream) = build_appearance(doc, &d) else { continue };
|
||||
// Another program's stamp gets a drawing for display only (ISO 32000-2 Table 184). Its
|
||||
// `/AP`, if any, has no `/N` to keep here.
|
||||
let other_stamp = || {
|
||||
let mut bare = d.clone();
|
||||
bare.remove(b"AP");
|
||||
appearance::display_stamp(&bare)
|
||||
};
|
||||
let Some(stream) = build_appearance(doc, &d).or_else(other_stamp) else { continue };
|
||||
cache.insert(r, &stream);
|
||||
// Fails only when `r` isn't a dictionary, which the build just ruled out.
|
||||
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
|
||||
@@ -1593,36 +1668,52 @@ pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Resul
|
||||
if let Some(r) = target.as_ref() {
|
||||
unlocked(doc, r)?;
|
||||
}
|
||||
let mut doomed: Vec<ObjRef> = target.as_ref().into_iter().collect();
|
||||
// Replies (`/IRT`) and pop-ups (`/Parent`) of anything doomed, to a fixpoint.
|
||||
loop {
|
||||
let before = doomed.len();
|
||||
for e in &list {
|
||||
let Some(r) = e.as_ref() else { continue };
|
||||
if doomed.contains(&r) {
|
||||
continue;
|
||||
}
|
||||
let obj = doc.get(r);
|
||||
let Some(d) = obj.as_dict() else { continue };
|
||||
let points_at = |k: &[u8]| d.reference(k).is_some_and(|t| doomed.contains(&t));
|
||||
if points_at(b"IRT") || points_at(b"Parent") {
|
||||
doomed.push(r);
|
||||
}
|
||||
}
|
||||
for r in doomed.clone() {
|
||||
if let Some(pop) = doc.get(r).as_dict().and_then(|d| d.reference(b"Popup"))
|
||||
&& !doomed.contains(&pop)
|
||||
{
|
||||
doomed.push(pop);
|
||||
}
|
||||
}
|
||||
if doomed.len() == before {
|
||||
break;
|
||||
// An inline comment has no reference to collect; the pop-up it names still goes.
|
||||
let seed = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));
|
||||
let doomed = with_replies_and_popups(doc, &list, seed);
|
||||
let kept: Vec<Object> = list.into_iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e).collect();
|
||||
Ok(set_annots(doc, p, kept)?)
|
||||
}
|
||||
|
||||
/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is
|
||||
/// one of them, or it is written inline (a file can, though the standard asks for references) and
|
||||
/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no reference
|
||||
/// for the walk to collect, so it is matched here.
|
||||
pub fn goes_with(entry: &Object, going: &HashSet<ObjRef>) -> bool {
|
||||
match entry.as_ref() {
|
||||
Some(r) => going.contains(&r),
|
||||
None => entry.as_dict().is_some_and(|d| [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten().any(|r| going.contains(&r))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `doomed` and what goes with it, as Acrobat deletes a comment: the entries of `list` (one or
|
||||
/// more pages' `/Annots`) that reply to (`/IRT`) or pop up for (`/Parent`) anything going, their
|
||||
/// own replies, and the pop-ups going annotations name (`/Popup`). An inline reply has no
|
||||
/// reference to collect, but the pop-up it names is. Each annotation is visited once, so a long or
|
||||
/// cyclic chain costs no more than its length. Filter a list with [`goes_with`], which also
|
||||
/// matches inline entries.
|
||||
pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl IntoIterator<Item = ObjRef>) -> HashSet<ObjRef> {
|
||||
let mut hanging: HashMap<ObjRef, Vec<ObjRef>> = HashMap::new();
|
||||
for e in list {
|
||||
let obj = doc.resolve(e);
|
||||
let Some(d) = obj.as_dict() else { continue };
|
||||
// What goes with the annotation this entry hangs off: the entry, or for an inline one the
|
||||
// pop-up it names.
|
||||
let Some(goes) = e.as_ref().or_else(|| d.reference(b"Popup")) else { continue };
|
||||
for on in [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten() {
|
||||
hanging.entry(on).or_default().push(goes);
|
||||
}
|
||||
}
|
||||
let kept: Vec<Object> =
|
||||
list.into_iter().enumerate().filter(|(i, e)| *i != index && !e.as_ref().is_some_and(|r| doomed.contains(&r))).map(|(_, e)| e).collect();
|
||||
set_annots(doc, p, kept)
|
||||
let mut going = HashSet::new();
|
||||
let mut todo: Vec<ObjRef> = doomed.into_iter().collect();
|
||||
while let Some(r) = todo.pop() {
|
||||
if !going.insert(r) {
|
||||
continue;
|
||||
}
|
||||
todo.extend(hanging.get(&r).into_iter().flatten());
|
||||
todo.extend(doc.get(r).as_dict().and_then(|d| d.reference(b"Popup")));
|
||||
}
|
||||
going
|
||||
}
|
||||
|
||||
/// Change a comment's text. Text boxes are redrawn to show it, and their rectangle follows the
|
||||
@@ -2200,6 +2291,10 @@ pub struct Summary {
|
||||
pub modified: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub in_reply_to: Option<String>,
|
||||
/// The page and `/Annots` position `/IRT` points at, by reference (`/NM` need not be unique).
|
||||
pub parent: Option<(usize, usize)>,
|
||||
/// `/RT /Group`: grouped with the `/IRT` annotation (Replace Text's caret), not a reply to it.
|
||||
pub grouped: bool,
|
||||
pub rect: [f32; 4],
|
||||
pub color: Option<[f32; 3]>,
|
||||
pub state: Option<String>,
|
||||
@@ -2208,6 +2303,8 @@ pub struct Summary {
|
||||
pub intent: Option<String>,
|
||||
/// A Fill & Sign mark ([`is_fill_sign`]).
|
||||
pub fill_sign: bool,
|
||||
/// The NoRotate flag (`/F` bit 5), as `pdfcraft_render::Annotation::no_rotate`.
|
||||
pub no_rotate: bool,
|
||||
/// A line's two ends (`/L`), or the corners of connected lines, a polygon or a cloud
|
||||
/// (`/Vertices`), in user space; empty for other comments.
|
||||
pub points: Vec<[f32; 2]>,
|
||||
@@ -2231,13 +2328,35 @@ pub fn is_comment_subtype(subtype: &str) -> bool {
|
||||
!matches!(subtype, "Link" | "Widget" | "Popup" | "Screen" | "Movie" | "RichMedia" | "3D" | "PrinterMark" | "TrapNet" | "Watermark")
|
||||
}
|
||||
|
||||
/// Where a reference to a reference (`5 0 obj 6 0 R endobj`) ends, as `pdfcraft_render::inspect`
|
||||
/// follows it, within a few steps (a cycle stops there).
|
||||
fn final_ref(doc: &Document, mut r: ObjRef) -> ObjRef {
|
||||
for _ in 0..8 {
|
||||
match &*doc.get(r) {
|
||||
Object::Ref(next) => r = *next,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Every comment (see [`is_comment_subtype`]), ordered by page and then top edge.
|
||||
pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(pages) = page_refs(doc) else { return out };
|
||||
for (page, p) in pages.iter().enumerate() {
|
||||
for (index, entry) in annots(doc, *p).iter().enumerate() {
|
||||
let obj = doc.resolve(entry);
|
||||
let lists: Vec<Vec<Object>> = pages.iter().map(|p| annots(doc, *p)).collect();
|
||||
// Where each annotation is first listed, so a reply's `/IRT` finds its parent by reference.
|
||||
let mut slots: std::collections::HashMap<ObjRef, (usize, usize)> = std::collections::HashMap::new();
|
||||
for (page, list) in lists.iter().enumerate() {
|
||||
for (index, entry) in list.iter().enumerate() {
|
||||
if let Some(r) = entry.as_ref() {
|
||||
slots.entry(final_ref(doc, r)).or_insert((page, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (page, list) in lists.iter().enumerate() {
|
||||
for (index, entry) in list.iter().enumerate() {
|
||||
let obj = entry.as_ref().map_or_else(|| doc.resolve(entry), |r| doc.get(final_ref(doc, r)));
|
||||
let Some(d) = obj.as_dict() else { continue };
|
||||
let Some(subtype) = d.name(b"Subtype").map(|s| String::from_utf8_lossy(s).into_owned()) else { continue };
|
||||
if !is_comment_subtype(&subtype) {
|
||||
@@ -2271,7 +2390,9 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
"PolyLine" | "Polygon" => nums(b"Vertices").as_chunks::<2>().0.to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let in_reply_to = d.get(b"IRT").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));
|
||||
let irt = d.get(b"IRT").map(|o| o.as_ref().map_or_else(|| doc.resolve(o), |r| doc.get(final_ref(doc, r))));
|
||||
let in_reply_to = irt.and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));
|
||||
let parent = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| slots.get(&final_ref(doc, r)).copied());
|
||||
out.push(Summary {
|
||||
page,
|
||||
index,
|
||||
@@ -2283,6 +2404,8 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
modified: text_value(doc, d, b"M"),
|
||||
name: text_value(doc, d, b"NM"),
|
||||
in_reply_to,
|
||||
parent,
|
||||
grouped: d.name(b"RT") == Some(b"Group"),
|
||||
rect,
|
||||
color,
|
||||
state: text_value(doc, d, b"State"),
|
||||
@@ -2290,6 +2413,7 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
|
||||
locked: annotation_flags(doc, d) & FLAG_LOCKED != 0,
|
||||
intent: d.get(b"IT").and_then(|o| doc.resolve(o).as_name().map(|n| String::from_utf8_lossy(n).into_owned())),
|
||||
fill_sign: is_fill_sign(doc, d),
|
||||
no_rotate: drawn_upright(doc, d),
|
||||
points,
|
||||
});
|
||||
}
|
||||
|
||||
+69
-13
@@ -78,11 +78,15 @@ pub struct LinkItem {
|
||||
pub style: LinkStyle,
|
||||
}
|
||||
|
||||
/// Bytes of web-address text one listing keeps, counted after conversion to UTF-8; past it a link
|
||||
/// lists as [`LinkAction::Other`].
|
||||
pub(crate) const MAX_URI_BYTES: usize = 16 << 20;
|
||||
|
||||
fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {
|
||||
o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef]) -> LinkAction {
|
||||
fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef], uri_budget: &mut usize) -> LinkAction {
|
||||
let dest_page = |dest: &Object| -> Option<usize> {
|
||||
let a = doc.resolve(dest);
|
||||
let first = a.as_array()?.first()?.clone();
|
||||
@@ -97,9 +101,20 @@ fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef]) -> LinkAction {
|
||||
}
|
||||
let Some(a) = d.get(b"A").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()) else { return LinkAction::Other("no action".into()) };
|
||||
match a.name(b"S") {
|
||||
Some(b"URI") => LinkAction::Uri(
|
||||
a.get(b"URI").and_then(|u| doc.resolve(u).as_string().map(|s| String::from_utf8_lossy(&s.bytes).into_owned())).unwrap_or_default(),
|
||||
),
|
||||
Some(b"URI") => {
|
||||
let uri = a.get(b"URI").map(|u| doc.resolve(u));
|
||||
let bytes = uri.as_ref().and_then(|u| u.as_string()).map_or(&[][..], |s| &s.bytes[..]);
|
||||
// The raw length first, so an address already over the budget is never converted; then the
|
||||
// converted text, which is up to three times longer where the bytes are not UTF-8.
|
||||
let text = (bytes.len() <= *uri_budget).then(|| String::from_utf8_lossy(bytes));
|
||||
match text.and_then(|t| Some((uri_budget.checked_sub(t.len())?, t))) {
|
||||
Some((left, text)) => {
|
||||
*uri_budget = left;
|
||||
LinkAction::Uri(text.into_owned())
|
||||
}
|
||||
None => LinkAction::Other("web address too long".into()),
|
||||
}
|
||||
}
|
||||
Some(b"GoTo") => a.get(b"D").and_then(dest_page).map_or_else(|| LinkAction::Other("named destination".into()), LinkAction::Page),
|
||||
Some(s) => LinkAction::Other(String::from_utf8_lossy(s).into_owned()),
|
||||
None => LinkAction::Other("no action".into()),
|
||||
@@ -133,8 +148,16 @@ fn style_of(doc: &Document, d: &Dict) -> LinkStyle {
|
||||
pub fn list(doc: &Document) -> Vec<LinkItem> {
|
||||
let Ok(pages) = page_refs(doc) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut uri_budget = MAX_URI_BYTES;
|
||||
for (pi, p) in pages.iter().enumerate() {
|
||||
for (k, a) in annots(doc, *p).iter().enumerate() {
|
||||
// One annotation object listed under several entries or pages is one link.
|
||||
if let Some(r) = a.as_ref()
|
||||
&& !seen.insert(r)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(d) = doc.resolve(a).as_dict().cloned() else { continue };
|
||||
if d.name(b"Subtype") != Some(b"Link") {
|
||||
continue;
|
||||
@@ -148,7 +171,7 @@ pub fn list(doc: &Document) -> Vec<LinkItem> {
|
||||
index: k,
|
||||
obj: a.as_ref(),
|
||||
rect: [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])],
|
||||
action: action_of(doc, &d, &pages),
|
||||
action: action_of(doc, &d, &pages, &mut uri_budget),
|
||||
style: style_of(doc, &d),
|
||||
});
|
||||
}
|
||||
@@ -232,6 +255,16 @@ fn checked_rect(rect: [f64; 4]) -> Result<[f64; 4], AnnotError> {
|
||||
/// Add a link over `rect` (user space). Returns its index in the page's `/Annots`.
|
||||
pub fn add(doc: &mut Document, page: usize, rect: [f64; 4], action: &LinkAction, style: &LinkStyle) -> Result<usize, AnnotError> {
|
||||
let p = page_ref(doc, page)?;
|
||||
let obj = new_link(doc, p, rect, action, style)?;
|
||||
let mut list = annots(doc, p);
|
||||
list.push(Object::Ref(obj));
|
||||
let index = list.len() - 1;
|
||||
set_annots(doc, p, list)?;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// A link annotation object for page `p`, not yet on the page's `/Annots`.
|
||||
fn new_link(doc: &mut Document, p: ObjRef, rect: [f64; 4], action: &LinkAction, style: &LinkStyle) -> Result<ObjRef, AnnotError> {
|
||||
let r = checked_rect(rect)?;
|
||||
if matches!(action, LinkAction::Other(_)) {
|
||||
return Err(AnnotError::Invalid("choose a page or a web address".into()));
|
||||
@@ -244,12 +277,7 @@ pub fn add(doc: &mut Document, page: usize, rect: [f64; 4], action: &LinkAction,
|
||||
d.set(b"F".to_vec(), Object::Int(4));
|
||||
write_style(&mut d, style);
|
||||
write_action(doc, &mut d, action)?;
|
||||
let obj = doc.add(Object::Dict(d));
|
||||
let mut list = annots(doc, p);
|
||||
list.push(Object::Ref(obj));
|
||||
let index = list.len() - 1;
|
||||
set_annots(doc, p, list)?;
|
||||
Ok(index)
|
||||
Ok(doc.add(Object::Dict(d)))
|
||||
}
|
||||
|
||||
fn link_at(doc: &Document, page: usize, index: usize) -> Result<(ObjRef, ObjRef), AnnotError> {
|
||||
@@ -292,7 +320,7 @@ pub fn delete(doc: &mut Document, page: usize, index: usize) -> Result<(), Annot
|
||||
let (p, _) = link_at(doc, page, index)?;
|
||||
let mut list = annots(doc, p);
|
||||
list.remove(index);
|
||||
set_annots(doc, p, list)
|
||||
Ok(set_annots(doc, p, list)?)
|
||||
}
|
||||
|
||||
/// Remove every link on `pages` (all when `None`). Returns how many went.
|
||||
@@ -414,12 +442,40 @@ pub fn find_urls(chars: &[char]) -> Vec<(std::ops::Range<usize>, String)> {
|
||||
/// Create links for found URLs: `(page, quads, uri)` with quads in user space (one link per
|
||||
/// line rectangle). Returns how many links were added.
|
||||
pub fn add_many(doc: &mut Document, links: &[(usize, Vec<[f64; 4]>, String)], style: &LinkStyle) -> Result<usize, AnnotError> {
|
||||
let pages = page_refs(doc)?;
|
||||
// Check the whole batch first, so a bad entry fails it before any link object is created.
|
||||
for (page, rects, uri) in links {
|
||||
pages.get(*page).ok_or(AnnotError::NoSuchPage(*page))?;
|
||||
if uri.trim().is_empty() {
|
||||
return Err(AnnotError::Invalid("type the web address first".into()));
|
||||
}
|
||||
for r in rects {
|
||||
checked_rect(*r)?;
|
||||
}
|
||||
}
|
||||
// Each page's `/Annots` is extended once, with its new links in the order given.
|
||||
let mut added: Vec<(ObjRef, Vec<Object>)> = Vec::new();
|
||||
let mut slot: std::collections::HashMap<ObjRef, usize> = std::collections::HashMap::new();
|
||||
let mut n = 0;
|
||||
for (page, rects, uri) in links {
|
||||
let p = pages.get(*page).copied().ok_or(AnnotError::NoSuchPage(*page))?;
|
||||
let action = LinkAction::Uri(uri.clone());
|
||||
for r in rects {
|
||||
add(doc, *page, *r, &LinkAction::Uri(uri.clone()), style)?;
|
||||
let obj = new_link(doc, p, *r, &action, style)?;
|
||||
let k = *slot.entry(p).or_insert_with(|| {
|
||||
added.push((p, Vec::new()));
|
||||
added.len() - 1
|
||||
});
|
||||
if let Some((_, list)) = added.get_mut(k) {
|
||||
list.push(Object::Ref(obj));
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
for (p, new) in added {
|
||||
let mut list = annots(doc, p);
|
||||
list.extend(new);
|
||||
set_annots(doc, p, list)?;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
+633
-2
@@ -229,6 +229,47 @@ fn delete_takes_popup_and_reply_chain() {
|
||||
assert_eq!(delete_annotation(&mut doc, 0, 9), Err(AnnotError::NoSuchAnnotation { page: 0, index: 9 }));
|
||||
}
|
||||
|
||||
/// A reply or pop-up written inline in `/Annots` (a file can, though the standard asks for
|
||||
/// references) goes with the comment it points at, and so does a pop-up an inline reply or an
|
||||
/// inline comment names. An unrelated inline comment stays until it is deleted itself.
|
||||
#[test]
|
||||
fn delete_takes_inline_replies_and_popups() {
|
||||
let mut doc = fixture();
|
||||
let mut popup = |note: &str| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
d.set(b"Subtype".to_vec(), Object::name("Popup"));
|
||||
d.set(b"Contents".to_vec(), PdfString::text(note));
|
||||
doc.add(Object::Dict(d))
|
||||
};
|
||||
let (reply_popup, square_popup) = (popup("of the reply"), popup("of the square"));
|
||||
let inline = |subtype: &str, links: &[(&[u8], ObjRef)]| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
d.set(b"Subtype".to_vec(), Object::name(subtype));
|
||||
links.iter().for_each(|(key, r)| d.set(key.to_vec(), Object::Ref(*r)));
|
||||
Object::Dict(d)
|
||||
};
|
||||
let stamp = ObjRef::new(6, 0);
|
||||
let entries = vec![
|
||||
Object::Ref(stamp),
|
||||
inline("Text", &[(b"IRT", stamp), (b"Popup", reply_popup)]),
|
||||
Object::Ref(reply_popup),
|
||||
inline("Popup", &[(b"Parent", stamp)]),
|
||||
inline("Square", &[(b"Popup", square_popup)]),
|
||||
Object::Ref(square_popup),
|
||||
];
|
||||
doc.set(ObjRef::new(5, 0), Object::Array(entries));
|
||||
let subtypes = |doc: &Document| -> Vec<String> {
|
||||
list(doc, 1).iter().map(|d| String::from_utf8_lossy(d.name(b"Subtype").unwrap()).into_owned() + ":" + &text(d, b"Contents")).collect()
|
||||
};
|
||||
delete_annotation(&mut doc, 1, 0).unwrap();
|
||||
let mut doc = reopen(&doc);
|
||||
assert_eq!(subtypes(&doc), ["Square:", "Popup:of the square"]);
|
||||
delete_annotation(&mut doc, 1, 0).unwrap();
|
||||
assert!(subtypes(&reopen(&doc)).is_empty(), "the inline comment's pop-up went with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_last_comment_removes_annots() {
|
||||
let mut doc = fixture();
|
||||
@@ -1014,6 +1055,89 @@ fn a_note_without_an_appearance_is_shown_at_icon_size() {
|
||||
assert_eq!(rects(&doc), original, "the source document is unchanged");
|
||||
}
|
||||
|
||||
/// The fourteen rubber stamp names viewers draw without an appearance (ISO 32000-2 Table 184).
|
||||
const TABLE_184_STAMPS: [(&str, &str); 14] = [
|
||||
("Approved", "APPROVED"),
|
||||
("Experimental", "EXPERIMENTAL"),
|
||||
("NotApproved", "NOT APPROVED"),
|
||||
("AsIs", "AS IS"),
|
||||
("Expired", "EXPIRED"),
|
||||
("NotForPublicRelease", "NOT FOR PUBLIC RELEASE"),
|
||||
("Confidential", "CONFIDENTIAL"),
|
||||
("Final", "FINAL"),
|
||||
("Sold", "SOLD"),
|
||||
("Departmental", "DEPARTMENTAL"),
|
||||
("ForComment", "FOR COMMENT"),
|
||||
("TopSecret", "TOP SECRET"),
|
||||
("Draft", "DRAFT"),
|
||||
("ForPublicRelease", "FOR PUBLIC RELEASE"),
|
||||
];
|
||||
|
||||
fn stamp_dict(extra: &str) -> Dict {
|
||||
let doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
format!("<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] {extra} >>").as_bytes(),
|
||||
]);
|
||||
list(&doc, 0).remove(0)
|
||||
}
|
||||
|
||||
fn drawn(d: &Dict) -> String {
|
||||
String::from_utf8_lossy(&appearance::display_stamp(d).expect("a stamp is drawn").decoded().unwrap()).into_owned()
|
||||
}
|
||||
|
||||
/// A stamp another program wrote without an appearance draws the stamp its `/Name` names, Draft
|
||||
/// when it has none, and a frame with both diagonals for any other name, never the name itself.
|
||||
#[test]
|
||||
fn a_stamp_without_an_appearance_draws_the_stamp_it_names() {
|
||||
for (name, label) in TABLE_184_STAMPS {
|
||||
let content = drawn(&stamp_dict(&format!("/Name /{name}")));
|
||||
assert!(content.contains(&format!("({label}) Tj")), "{name}: {content}");
|
||||
}
|
||||
assert!(drawn(&stamp_dict("")).contains("(DRAFT) Tj"), "Table 184's default");
|
||||
assert!(drawn(&stamp_dict("/IT /Stamp")).contains("(DRAFT) Tj"), "a stamp intent keeps the default");
|
||||
// Any other name, a name in another case (names are compared byte for byte, §7.3.5), and an
|
||||
// image stamp (`/IT`, which has no `/Name` to default): the frame and its diagonals.
|
||||
for extra in ["/Name /MyCustomStamp", "/Name /draft", "/Name /APPROVED", "/IT /StampImage", "/Name /PCVoid"] {
|
||||
let content = drawn(&stamp_dict(extra));
|
||||
assert!(!content.contains("Tj") && content.contains(" re\n") && content.matches(" l\n").count() == 2, "{extra}: {content}");
|
||||
}
|
||||
// `/C` colours the stamp, as it does PdfCraft's own.
|
||||
assert!(drawn(&stamp_dict("/Name /Final /C [1 0 1]")).contains("1 0 1 RG"));
|
||||
// The placeholder stays grey whatever the `/C`: it is not the stamp, so it takes none of its colour.
|
||||
let placeholder = drawn(&stamp_dict("/Name /MyCustomStamp /C [1 0 0]"));
|
||||
assert!(placeholder.contains("0.45 0.45 0.45 RG") && !placeholder.contains("1 0 0 RG"), "{placeholder}");
|
||||
// A stamp's own artwork is never replaced, and the drawing is for display only: edits
|
||||
// (restyling, flattening) still find nothing they may write.
|
||||
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /AP << /N 9 0 R >>")).is_none());
|
||||
assert!(appearance::build(&stamp_dict("/Name /Draft")).is_none());
|
||||
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /PCStamp true")).is_none(), "PdfCraft's own stamps are drawn by `build`");
|
||||
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /Rect [5 5 5 50]")).is_none(), "no width");
|
||||
}
|
||||
|
||||
/// The display copy draws a stamp that has no normal appearance, and keeps one that has.
|
||||
#[test]
|
||||
fn the_display_copy_draws_stamps_without_a_normal_appearance_only() {
|
||||
let doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 7 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] /Name /TopSecret >>",
|
||||
b"<< /Type /Annot /Subtype /Stamp /Rect [20 140 140 200] /Name /Draft /AP << /N 8 0 R >> >>",
|
||||
b"<< /Type /Annot /Subtype /Stamp /Rect [20 240 140 300] /Name /Sold /AP << /D 8 0 R >> >>",
|
||||
b"<< /Type /Annot /Subtype /Stamp /Rect [20 340 140 400] /Name /Unheard >>",
|
||||
b"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 8 >>\nstream\n1 0 0 rg\nendstream",
|
||||
]);
|
||||
let display = with_missing_appearances(&doc).expect("three stamps need an appearance");
|
||||
let shown = list(&display, 0);
|
||||
assert!(ap_content(&display, &shown[0]).contains("(TOP SECRET) Tj"));
|
||||
assert_eq!(shown[1].get(b"AP"), list(&doc, 0)[1].get(b"AP"), "an existing appearance is kept");
|
||||
assert!(ap_content(&display, &shown[2]).contains("(SOLD) Tj"), "an /AP without /N has nothing to keep");
|
||||
assert!(!ap_content(&display, &shown[3]).contains("Tj"), "an unknown name gets the placeholder");
|
||||
assert!(list(&doc, 0)[0].get(b"AP").is_none(), "the document itself is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_line_ending_is_drawn() {
|
||||
let filled = [LineEnding::Square, LineEnding::Circle, LineEnding::Diamond, LineEnding::ClosedArrow, LineEnding::RClosedArrow];
|
||||
@@ -1316,9 +1440,9 @@ fn cached_appearances_are_reused_while_annotations_are_unchanged() {
|
||||
.expect("strips");
|
||||
let mut cache = AppearanceCache::default();
|
||||
let first = with_missing_appearances_cached(&doc, &mut cache).expect("builds");
|
||||
assert_eq!((cache.builds(), cache.hits()), (1, 0), "only the note needs an appearance");
|
||||
assert_eq!((cache.builds(), cache.hits()), (2, 0), "the note and the file's stamp need an appearance");
|
||||
let second = with_missing_appearances_cached(&doc, &mut cache).expect("reuses");
|
||||
assert_eq!((cache.builds(), cache.hits()), (1, 1), "nothing is redrawn");
|
||||
assert_eq!((cache.builds(), cache.hits()), (2, 2), "nothing is redrawn");
|
||||
let [a, b] = [&first, &second].map(|copy| ap_content(copy, &list(copy, 0)[idx]));
|
||||
assert!(!a.is_empty());
|
||||
assert_eq!(a, b, "the reused appearance is byte-identical");
|
||||
@@ -1504,3 +1628,510 @@ fn typed_signature_uses_nonzero_winding_fill() {
|
||||
assert!(ap.ends_with("h\nf\n"), "expected non-zero winding fill (`f`), got: {ap}");
|
||||
assert!(!ap.contains("f*"), "must not use even-odd fill (`f*`): {ap}");
|
||||
}
|
||||
|
||||
/// Many page tree nodes sharing one `/Kids` array read it once, not once per node.
|
||||
#[test]
|
||||
fn page_walk_reads_a_shared_kids_array_once() {
|
||||
let mut doc = fixture();
|
||||
let root = ObjRef { num: 2, generation: 0 };
|
||||
let (first, second) = (ObjRef { num: 3, generation: 0 }, ObjRef { num: 4, generation: 0 });
|
||||
let shared = doc.add(Object::Array([Object::Ref(first), Object::Ref(second)].into_iter().cycle().take(2_000).collect()));
|
||||
let nodes: Vec<Object> = (0..1_000)
|
||||
.map(|_| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("Pages"));
|
||||
d.set(b"Kids".to_vec(), Object::Ref(shared));
|
||||
Object::Ref(doc.add(d))
|
||||
})
|
||||
.collect();
|
||||
doc.update_dict(root, |d| d.set(b"Kids".to_vec(), Object::Array(nodes))).unwrap();
|
||||
let mut walk = PageWalk::new(&doc, root);
|
||||
let pages: Vec<ObjRef> = walk.by_ref().collect();
|
||||
assert_eq!(pages, [first, second]);
|
||||
assert!(walk.examined <= 10_000, "{} kids entries read", walk.examined);
|
||||
}
|
||||
|
||||
/// Adding many links to a page extends its `/Annots` once, not once per link.
|
||||
#[test]
|
||||
fn many_links_extend_a_page_annotation_list_once() {
|
||||
let mut doc = fixture();
|
||||
let before = annots(&doc, page_refs(&doc).unwrap()[0]).len();
|
||||
let n = 2_000;
|
||||
let rects: Vec<[f64; 4]> = (0..n).map(|i| [10.0, i as f64 * 0.1, 50.0, i as f64 * 0.1 + 5.0]).collect();
|
||||
ANNOTS_ENTRIES_COPIED.with(|c| c.set(0));
|
||||
let added = links::add_many(&mut doc, &[(0, rects, "https://example.com".into())], &links::LinkStyle::default()).unwrap();
|
||||
let copied = ANNOTS_ENTRIES_COPIED.with(std::cell::Cell::get);
|
||||
assert_eq!(added, n);
|
||||
assert_eq!(annots(&doc, page_refs(&doc).unwrap()[0]).len(), before + n);
|
||||
assert!(copied <= 4 * n, "{copied} annotation entries copied for {n} links");
|
||||
}
|
||||
|
||||
/// A batch with one bad entry adds nothing: no link objects are left behind unattached.
|
||||
#[test]
|
||||
fn a_link_batch_with_a_bad_entry_creates_no_objects() {
|
||||
let mut doc = fixture();
|
||||
let page = page_refs(&doc).unwrap()[0];
|
||||
let before = (annots(&doc, page).len(), doc.scan_objects().count());
|
||||
let good = [10.0, 10.0, 50.0, 20.0];
|
||||
let style = links::LinkStyle::default();
|
||||
for bad in [
|
||||
vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good, [f64::NAN, 0.0, 10.0, 10.0]], "https://example.com".into())],
|
||||
vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good], " ".into())],
|
||||
vec![(0, vec![good], "https://example.com".to_string()), (99, vec![good], "https://example.com".into())],
|
||||
] {
|
||||
assert!(links::add_many(&mut doc, &bad, &style).is_err());
|
||||
assert_eq!((annots(&doc, page).len(), doc.scan_objects().count()), before);
|
||||
}
|
||||
}
|
||||
|
||||
fn doc_of(objs: &[String]) -> Document {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
Document::open(Arc::new(out)).expect("opens")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_listing_skips_repeated_refs_and_caps_web_address_text() {
|
||||
// One link referenced 1000 times, and 300 small links sharing one 64 KiB address.
|
||||
let annots = format!("{}{}", " 4 0 R".repeat(1000), "<< /Subtype /Link /Rect [0 0 1 1] /A 5 0 R >>".repeat(300));
|
||||
let doc = doc_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
|
||||
format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
|
||||
"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A 5 0 R >>".into(),
|
||||
"<< /S /URI /URI 6 0 R >>".into(),
|
||||
format!("({})", "u".repeat(64 << 10)),
|
||||
]);
|
||||
let all = links::list(&doc);
|
||||
assert_eq!(all.iter().filter(|l| l.obj == Some(ObjRef::new(4, 0))).count(), 1);
|
||||
assert_eq!(all.len(), 301, "every distinct link is still listed");
|
||||
let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();
|
||||
assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");
|
||||
assert!(matches!(&all[0].action, links::LinkAction::Uri(u) if u.len() == 64 << 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_address_cap_counts_the_text_kept_after_conversion() {
|
||||
// 200 links sharing a 64 KiB address of invalid UTF-8: 12.5 MiB of bytes, each byte kept as a
|
||||
// three-byte replacement character.
|
||||
let annots = "<< /Subtype /Link /Rect [0 0 1 1] /A 4 0 R >>".repeat(200);
|
||||
let doc = doc_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
|
||||
format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
|
||||
"<< /S /URI /URI 5 0 R >>".into(),
|
||||
format!("<{}>", "FF".repeat(64 << 10)),
|
||||
]);
|
||||
let all = links::list(&doc);
|
||||
assert_eq!(all.len(), 200);
|
||||
let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();
|
||||
assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");
|
||||
assert!(kept > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_outline_has_a_bump_budget() {
|
||||
// 50 long edges would each ask for 10,000 bumps of radius 1.
|
||||
let pts: Vec<(f64, f64)> = (0..50).map(|i| (f64::from(i) * std::f64::consts::TAU / 50.0).sin_cos()).map(|(s, c)| (1e7 * c, 1e7 * s)).collect();
|
||||
let bumps = appearance::cloud_path(&pts, 1.0).lines().filter(|l| l.ends_with(" c")).count();
|
||||
assert!((pts.len()..=appearance::MAX_CLOUD_BUMPS + 2 * pts.len()).contains(&bumps), "{bumps} bumps");
|
||||
}
|
||||
|
||||
/// A note's drawn icon (its built appearance's content) for `/Name` (none when `None`) and `/C`.
|
||||
fn note_drawing(name: Option<&str>, color: [f64; 3]) -> Vec<u8> {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Subtype".to_vec(), Object::name("Text"));
|
||||
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 20.0, 20.0].map(Object::Real).to_vec()));
|
||||
d.set(b"C".to_vec(), Object::Array(color.map(Object::Real).to_vec()));
|
||||
if let Some(n) = name {
|
||||
d.set(b"Name".to_vec(), Object::name(n));
|
||||
}
|
||||
crate::appearance::build(&d).expect("a note is drawn").decoded().unwrap()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.5.6.4, Table 175: a viewer shall provide icons for the seven standard names,
|
||||
/// and may support more. Each of the fourteen names PdfCraft offers draws a shape of its own, so
|
||||
/// a note shows the icon it names; a name it doesn't know, and a note without one, draw `Note`
|
||||
/// (the table's default).
|
||||
#[test]
|
||||
fn every_note_icon_draws_its_own_shape() {
|
||||
let yellow = [1.0, 0.82, 0.0];
|
||||
let drawn: Vec<Vec<u8>> = NoteIcon::ALL.iter().map(|i| note_drawing(Some(i.name()), yellow)).collect();
|
||||
for (i, a) in drawn.iter().enumerate() {
|
||||
for (j, b) in drawn.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(a, b, "{} and {} look alike", NoteIcon::ALL[i].name(), NoteIcon::ALL[j].name());
|
||||
}
|
||||
}
|
||||
let note = note_drawing(Some("Note"), yellow);
|
||||
assert_eq!(note_drawing(Some("Sparkle"), yellow), note, "an unknown name");
|
||||
assert_eq!(note_drawing(None, yellow), note, "no name");
|
||||
for icon in NoteIcon::ALL {
|
||||
assert_eq!(NoteIcon::from_name(icon.name()), Some(icon));
|
||||
}
|
||||
}
|
||||
|
||||
/// A note named with one of the further icons reads as that icon, and a colour change redraws it
|
||||
/// as itself, not as a page.
|
||||
#[test]
|
||||
fn a_star_note_keeps_its_star_when_recoloured() {
|
||||
let mut doc = document_of(&[
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 600] >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
b"<< /Type /Annot /Subtype /Text /Rect [100 100 120 120] /Name /Star /C [1 0.82 0] /F 4 >>",
|
||||
]);
|
||||
assert_eq!(props(&doc, 0, 0).and_then(|p| p.icon), Some(NoteIcon::Star));
|
||||
set_style(&mut doc, 0, 0, Some([0.0, 0.0, 1.0]), None, None, None, &meta("")).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let d = &list(&doc, 0)[0];
|
||||
assert_eq!(d.name(b"Name"), Some(&b"Star"[..]));
|
||||
let n = d.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
|
||||
let Object::Stream(s) = &*doc.get(n) else { panic!() };
|
||||
assert_eq!(s.decoded().unwrap(), note_drawing(Some("Star"), [0.0, 0.0, 1.0]));
|
||||
}
|
||||
|
||||
/// The built appearance's content for an annotation dictionary written in PDF syntax.
|
||||
fn content_of(src: &str) -> String {
|
||||
let doc = document_of(&[src.as_bytes()]);
|
||||
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().expect("a dictionary");
|
||||
let stream = appearance::build(&d).expect("drawn");
|
||||
String::from_utf8_lossy(&stream.decoded().unwrap()).into_owned()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 166: `/Border [hr vr w [dash]]`; the optional fourth element, a dash array,
|
||||
/// used to hide the width (drawn 1 pt solid instead of 3 pt dashed).
|
||||
#[test]
|
||||
fn legacy_border_width_and_dash_are_drawn() {
|
||||
let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
|
||||
let c = square("/Border [0 0 3 [6 3]]");
|
||||
assert!(c.contains("3 w") && c.contains("[6 3] 0 d"), "{c}");
|
||||
assert!(c.contains("1.5 1.5 97 97 re"), "the stroke is inset by half its width: {c}");
|
||||
let c = square("/Border [0 0 3]");
|
||||
assert!(c.contains("3 w") && !c.contains(" d\n"), "no dash array: solid: {c}");
|
||||
// `/BS` overrides `/Border` (Table 166), for the width and the dashes alike.
|
||||
let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 >>");
|
||||
assert!(c.contains("2 w") && !c.contains(" d\n"), "{c}");
|
||||
let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 /S /D /D [4 1] >>");
|
||||
assert!(c.contains("2 w") && c.contains("[4 1] 0 d"), "{c}");
|
||||
// A /BS without /W means its default width 1, not the ignored /Border's.
|
||||
let c = square("/Border [0 0 3] /BS << /S /S >>");
|
||||
assert!(c.contains("1 w") && !c.contains("3 w"), "{c}");
|
||||
// A FreeText border and a line take the legacy dash array too.
|
||||
let c = content_of("<< /Subtype /FreeText /Rect [0 0 100 40] /Contents (x) /Border [0 0 2 [5 2]] >>");
|
||||
assert!(c.contains("2 w") && c.contains("[5 2] 0 d"), "{c}");
|
||||
let c = content_of("<< /Subtype /Line /Rect [0 0 100 100] /L [10 10 90 90] /C [0 0 1] /Border [0 0 2 [5 2]] >>");
|
||||
assert!(c.contains("[5 2] 0 d"), "{c}");
|
||||
}
|
||||
|
||||
/// Dash arrays that can't be drawn (§8.4.3.6: all zeros is invalid; negative or non-numeric
|
||||
/// lengths, and absurdly long arrays) draw solid, without a panic. A non-finite or negative
|
||||
/// width falls back to 1.
|
||||
#[test]
|
||||
fn bad_dash_arrays_draw_solid() {
|
||||
let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
|
||||
let long = format!("[{}]", vec!["1"; 65].join(" "));
|
||||
for bad in ["[0 0]", "[-3 2]", "[]", "[(a) 2]", "5", long.as_str()] {
|
||||
let c = square(&format!("/Border [0 0 3 {bad}]"));
|
||||
assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
|
||||
let c = square(&format!("/BS << /W 3 /S /D /D {bad} >>"));
|
||||
assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
|
||||
}
|
||||
assert!(square(&format!("/Border [0 0 3 [{}]]", vec!["1"; 64].join(" "))).contains(" 0 d\n"), "64 elements are drawn");
|
||||
// `/S /D` without `/D` uses the default `[3]` (Table 168).
|
||||
assert!(square("/BS << /W 3 /S /D >>").contains("[3] 0 d"));
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Subtype".to_vec(), Object::name("Square"));
|
||||
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 100.0, 100.0].map(Object::Real).to_vec()));
|
||||
d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
|
||||
for w in [f64::NAN, f64::INFINITY, -2.0] {
|
||||
let dash = Object::Array([f64::NAN, 2.0].map(Object::Real).to_vec());
|
||||
d.set(b"Border".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Real(w), dash]));
|
||||
let c = String::from_utf8_lossy(&appearance::build(&d).unwrap().decoded().unwrap()).into_owned();
|
||||
assert!(c.contains("1 w") && !c.contains(" d\n") && !c.contains("NaN") && !c.contains("inf"), "{w}: {c}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Table 182: an ink annotation's `/BS` gives the width and dash pattern its paths are drawn with.
|
||||
#[test]
|
||||
fn ink_draws_its_border_style_dashes() {
|
||||
let ink = |style: &str| content_of(&format!("<< /Subtype /Ink /Rect [0 0 100 100] /C [1 0 0] /InkList [[5 5 50 95 95 5]] {style} >>"));
|
||||
let c = ink("/BS << /W 3 /S /D /D [6 3] >>");
|
||||
assert!(c.contains("3 w 1 J 1 j\n[6 3] 0 d"), "{c}");
|
||||
assert!(!ink("/BS << /W 3 >>").contains(" d\n"));
|
||||
assert!(ink("/Border [0 0 2 [4 4]]").contains("[4 4] 0 d"));
|
||||
}
|
||||
|
||||
/// Table 183: `/Sy /P` associates a new paragraph symbol (¶) with the caret. It is drawn to the
|
||||
/// caret's right in the caret's colour, inside `/Rect`; `/Sy /None` (the default) draws none.
|
||||
#[test]
|
||||
fn a_caret_with_a_paragraph_symbol_draws_the_pilcrow() {
|
||||
let caret = |extra: &str| {
|
||||
let doc = document_of(&[format!("<< /Subtype /Caret /Rect [30 30 60 60] /C [0.9 0.1 0.1] {extra} >>").as_bytes()]);
|
||||
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
|
||||
let s = appearance::build(&d).unwrap();
|
||||
(s.decoded().unwrap(), s.dict.get(b"Resources").and_then(Object::as_dict).is_some_and(|r| r.contains(b"Font")))
|
||||
};
|
||||
let has_pilcrow = |c: &[u8]| c.windows(5).any(|w| w == b"(\xb6) T");
|
||||
let (c, font) = caret("/Sy /P");
|
||||
assert!(has_pilcrow(&c) && font, "{}", String::from_utf8_lossy(&c));
|
||||
let text = String::from_utf8_lossy(&c).into_owned();
|
||||
assert!(text.starts_with("0.9 0.1 0.1 rg"), "{text}");
|
||||
// The caret gives up room on the right for the symbol, which stays within /Rect.
|
||||
let td: Vec<f64> = text.split("Tf ").nth(1).unwrap().split_whitespace().take(2).map(|v| v.parse().unwrap()).collect();
|
||||
let size: f64 = text.split("/Helv ").nth(1).unwrap().split_whitespace().next().unwrap().parse().unwrap();
|
||||
assert!(td[0] > 45.0 && td[0] + appearance::text_width("\u{b6}", size) <= 60.0 + 1e-6 && td[1] >= 30.0, "{text}");
|
||||
assert!(!text.contains("60 30 c h f"), "the caret no longer reaches the right edge: {text}");
|
||||
for none in ["/Sy /None", ""] {
|
||||
let (c, font) = caret(none);
|
||||
assert!(!has_pilcrow(&c) && !font, "{none}");
|
||||
assert!(String::from_utf8_lossy(&c).contains("60 30 c h f"), "{none}: the caret fills /Rect as before");
|
||||
}
|
||||
// With /RD leaving room on the right, the caret keeps its box and the symbol fits beside it.
|
||||
let (c, _) = caret("/Sy /P /RD [0 0 15 0]");
|
||||
let text = String::from_utf8_lossy(&c).into_owned();
|
||||
assert!(text.contains("45 30 c h f") && has_pilcrow(&c), "{text}");
|
||||
// Malformed /RD and a degenerate /Rect don't panic.
|
||||
for rd in ["/RD [40 0 40 0]", "/RD [-1 0 0 0]", "/RD [1 2]", "/RD (x)"] {
|
||||
assert!(has_pilcrow(&caret(&format!("/Sy /P {rd}")).0), "{rd}");
|
||||
}
|
||||
let doc = document_of(&[b"<< /Subtype /Caret /Rect [30 30 30 30] /Sy /P >>"]);
|
||||
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
|
||||
assert!(appearance::build(&d).is_some());
|
||||
}
|
||||
|
||||
// ── Line annotations: leader lines and captions (ISO 32000-2 §12.5.6.7, Table 178) ──────────
|
||||
|
||||
/// A red Line from `l` with a 1 pt border, a generous `/Rect`, and `extra` entries.
|
||||
fn table_178_line(l: [f64; 4], extra: &[(&str, Object)]) -> Dict {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Subtype".to_vec(), Object::name("Line"));
|
||||
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 600.0, 800.0].map(Object::Real).to_vec()));
|
||||
d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
|
||||
d.set(b"L".to_vec(), Object::Array(l.map(Object::Real).to_vec()));
|
||||
for (k, v) in extra {
|
||||
d.set(k.as_bytes().to_vec(), v.clone());
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The built appearance's content.
|
||||
fn line_drawing(d: &Dict) -> String {
|
||||
let s = crate::appearance::build(d).expect("the line is drawn");
|
||||
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
|
||||
}
|
||||
|
||||
/// Every straight two-point stroke (`x0 y0 m x1 y1 l S`) in a drawing.
|
||||
fn segments(content: &str) -> Vec<[f64; 4]> {
|
||||
content
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let t: Vec<&str> = line.split_whitespace().collect();
|
||||
if t.len() != 7 || t[2] != "m" || t[5] != "l" || t[6] != "S" {
|
||||
return None;
|
||||
}
|
||||
let v: Vec<f64> = [t[0], t[1], t[3], t[4]].iter().map(|x| x.parse().unwrap()).collect();
|
||||
Some([v[0], v[1], v[2], v[3]])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The caption's text matrix (`a b c d e f Tm`), if any.
|
||||
fn caption_matrix(content: &str) -> Option<[f64; 6]> {
|
||||
let at = content.find(" Tm")?;
|
||||
let before: Vec<f64> = content[..at].split_whitespace().rev().take(6).map(|x| x.parse().unwrap()).collect();
|
||||
Some([before[5], before[4], before[3], before[2], before[1], before[0]])
|
||||
}
|
||||
|
||||
fn has(segs: &[[f64; 4]], want: [f64; 4]) -> bool {
|
||||
segs.iter().any(|s| s.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below() {
|
||||
let up = segments(&line_drawing(&table_178_line([72.0, 620.0, 272.0, 620.0], &[("LL", Object::Real(20.0))])));
|
||||
assert!(has(&up, [72.0, 640.0, 272.0, 640.0]), "the line is 20 above /L: {up:?}");
|
||||
assert!(has(&up, [72.0, 620.0, 72.0, 640.0]) && has(&up, [272.0, 620.0, 272.0, 640.0]), "leader lines from /L up to it: {up:?}");
|
||||
assert!(!has(&up, [72.0, 620.0, 272.0, 620.0]), "nothing along /L itself: {up:?}");
|
||||
|
||||
let down = segments(&line_drawing(&table_178_line([72.0, 540.0, 272.0, 540.0], &[("LL", Object::Real(-20.0)), ("LLE", Object::Real(10.0))])));
|
||||
assert!(has(&down, [72.0, 520.0, 272.0, 520.0]), "the line is 20 below /L: {down:?}");
|
||||
assert!(has(&down, [72.0, 540.0, 72.0, 510.0]) && has(&down, [272.0, 540.0, 272.0, 510.0]), "leaders run 10 past it: {down:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leader_offset_leaves_a_gap_and_the_endings_sit_on_the_line_itself() {
|
||||
let d = table_178_line(
|
||||
[72.0, 460.0, 272.0, 460.0],
|
||||
&[("LL", Object::Real(20.0)), ("LLO", Object::Real(10.0)), ("LE", Object::Array(vec![Object::name("OpenArrow"), Object::name("OpenArrow")]))],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let segs = segments(&content);
|
||||
assert!(has(&segs, [72.0, 490.0, 272.0, 490.0]), "the line sits |LL| + LLO above /L: {segs:?}");
|
||||
assert!(has(&segs, [72.0, 470.0, 72.0, 490.0]) && has(&segs, [272.0, 470.0, 272.0, 490.0]), "leaders start LLO from /L: {segs:?}");
|
||||
// The open arrows' tips (`tip l`) are at the ends of the line, not of /L.
|
||||
assert!(content.contains(" 72 490 l ") && content.contains(" 272 490 l "), "arrows at the moved line: {content}");
|
||||
assert!(!content.contains(" 72 460 l "), "no arrow on /L: {content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_caption_breaks_the_line_around_its_text() {
|
||||
let d =
|
||||
table_178_line([72.0, 380.0, 272.0, 380.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("Inline 50 mm")))]);
|
||||
let content = line_drawing(&d);
|
||||
assert!(content.contains("(Inline 50 mm) Tj"), "the caption is drawn: {content}");
|
||||
assert!(content.contains("/Helv 10 Tf"), "in Helvetica 10: {content}");
|
||||
let m = caption_matrix(&content).expect("text matrix");
|
||||
let width = crate::appearance::text_width("Inline 50 mm", 10.0);
|
||||
assert!((m[4] - (172.0 - width / 2.0)).abs() < 0.01 && m[5] < 380.0 && m[5] > 380.0 - 10.0, "centred on the line: {m:?}");
|
||||
let segs = segments(&content);
|
||||
assert_eq!(segs.len(), 2, "two pieces: {segs:?}");
|
||||
assert!(segs.iter().all(|s| s[2] <= 172.0 - width / 2.0 || s[0] >= 172.0 + width / 2.0), "no stroke under the text: {segs:?}");
|
||||
assert!(has(&segs, [72.0, 380.0, 172.0 - width / 2.0 - 2.0, 380.0]), "the left piece starts at the line's start: {segs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_caption_sits_above_the_unbroken_line() {
|
||||
let d = table_178_line(
|
||||
[72.0, 300.0, 272.0, 300.0],
|
||||
&[("Cap", Object::Bool(true)), ("CP", Object::name("Top")), ("Contents", Object::String(PdfString::text("Top 50 mm")))],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let m = caption_matrix(&content).expect("text matrix");
|
||||
assert!(m[5] > 300.0 && m[5] < 305.0, "baseline just above the line: {m:?}");
|
||||
assert_eq!(segments(&content), vec![[72.0, 300.0, 272.0, 300.0]], "the line is whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caption_offset_moves_it_along_and_off_the_line_with_a_tick() {
|
||||
let co = |h: f64, v: f64| Object::Array(vec![Object::Real(h), Object::Real(v)]);
|
||||
let text = ("Contents", Object::String(PdfString::text("Offset 15")));
|
||||
let base = caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), text.clone()]))).unwrap();
|
||||
let content = line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(0.0, 15.0)), text.clone()]));
|
||||
let up = caption_matrix(&content).unwrap();
|
||||
assert!((up[5] - base[5] - 15.0).abs() < 0.01 && (up[4] - base[4]).abs() < 0.01, "15 up: {base:?} → {up:?}");
|
||||
let segs = segments(&content);
|
||||
assert!(has(&segs, [330.0, 700.0, 530.0, 700.0]), "a caption off the line leaves it whole: {segs:?}");
|
||||
assert!(segs.iter().any(|s| s[0] == 430.0 && s[2] == 430.0 && s[1] == 700.0 && s[3] > 705.0), "a tick from the midpoint up: {segs:?}");
|
||||
let along =
|
||||
caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(-30.0, 0.0)), text])))
|
||||
.unwrap();
|
||||
assert!((along[4] - base[4] + 30.0).abs() < 0.01 && (along[5] - base[5]).abs() < 0.01, "30 left: {base:?} → {along:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_cap_true_no_caption_is_drawn() {
|
||||
for cap in [None, Some(Object::Bool(false)), Some(Object::Int(1))] {
|
||||
let mut extra = vec![("Contents", Object::String(PdfString::text("Hidden caption")))];
|
||||
if let Some(c) = cap.clone() {
|
||||
extra.push(("Cap", c));
|
||||
}
|
||||
let d = table_178_line([330.0, 620.0, 530.0, 620.0], &extra);
|
||||
let content = line_drawing(&d);
|
||||
assert!(!content.contains("Tj"), "{cap:?}: {content}");
|
||||
assert_eq!(segments(&content), vec![[330.0, 620.0, 530.0, 620.0]]);
|
||||
assert!(crate::appearance::undrawable_text(&d).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diagonal_lines_leaders_are_perpendicular_and_its_caption_turns_with_it() {
|
||||
let d = table_178_line(
|
||||
[330.0, 460.0, 530.0, 560.0],
|
||||
&[
|
||||
("LL", Object::Real(20.0)),
|
||||
("LLE", Object::Real(10.0)),
|
||||
("Cap", Object::Bool(true)),
|
||||
("Contents", Object::String(PdfString::text("Diagonal"))),
|
||||
],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
let segs = segments(&content);
|
||||
let (ux, uy) = (200.0 / 100f64.hypot(200.0), 100.0 / 100f64.hypot(200.0));
|
||||
let leaders: Vec<&[f64; 4]> = segs.iter().filter(|s| (s[2] - s[0]) * ux + (s[3] - s[1]) * uy < 1e-2).collect();
|
||||
assert_eq!(leaders.len(), 2, "two leader lines across the line: {segs:?}");
|
||||
for l in leaders {
|
||||
let (dx, dy) = (l[2] - l[0], l[3] - l[1]);
|
||||
assert!((dx.hypot(dy) - 30.0).abs() < 0.01, "|LL| + LLE long: {l:?}");
|
||||
assert!(dx < 0.0 && dy > 0.0, "up and to the left (left of travel): {l:?}");
|
||||
}
|
||||
let m = caption_matrix(&content).expect("caption");
|
||||
assert!((m[0] - ux).abs() < 1e-3 && (m[1] - uy).abs() < 1e-3, "the text runs along the line: {m:?}");
|
||||
// Drawn right to left, it still reads left to right.
|
||||
let back = caption_matrix(&line_drawing(&table_178_line(
|
||||
[530.0, 560.0, 330.0, 460.0],
|
||||
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("x")))],
|
||||
)))
|
||||
.unwrap();
|
||||
assert!(back[0] > 0.0, "{back:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caption_from_rich_text_and_one_the_font_cant_draw() {
|
||||
let rc = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\"><p>Dim & <b>5</b>0 mm <x></p></body>";
|
||||
let d = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("RC", Object::String(PdfString::text(rc)))]);
|
||||
let s = crate::appearance::build(&d).unwrap().decoded().unwrap();
|
||||
assert!(s.windows(17).any(|w| w == b"(Dim & 50 mm <x>)"), "{}", String::from_utf8_lossy(&s));
|
||||
let cjk = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("長さ")))]);
|
||||
assert_eq!(crate::appearance::undrawable_text(&cjk), Some(("the line's caption", '長')));
|
||||
// A PdfCraft measurement's label is its caption: the comment text isn't drawn a second time.
|
||||
let mut measured = cjk.clone();
|
||||
measured.set(b"PCMeasureValue".to_vec(), Object::String(PdfString::text("5 mm")));
|
||||
assert_eq!(crate::appearance::undrawable_text(&measured), None);
|
||||
let content = line_drawing(&measured);
|
||||
assert_eq!(content.matches(" Tj").count(), 1, "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() {
|
||||
let cap = ("Cap", Object::Bool(true));
|
||||
let text = ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))));
|
||||
// A zero-length line has no direction: no leader lines, no caption, no NaN.
|
||||
let point =
|
||||
line_drawing(&table_178_line([50.0, 50.0, 50.0, 50.0], &[("LL", Object::Real(20.0)), ("LLE", Object::Real(5.0)), cap.clone(), text.clone()]));
|
||||
assert!(!point.contains("NaN") && !point.contains("inf") && !point.contains("Tj"), "{point}");
|
||||
assert_eq!(segments(&point).len(), 1);
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MAX] {
|
||||
let d = table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[
|
||||
("LL", Object::Real(bad)),
|
||||
("LLE", Object::Real(bad)),
|
||||
("LLO", Object::Real(bad)),
|
||||
("CO", Object::Array(vec![Object::Real(bad), Object::Real(bad)])),
|
||||
cap.clone(),
|
||||
text.clone(),
|
||||
],
|
||||
);
|
||||
let content = line_drawing(&d);
|
||||
assert!(!content.contains("NaN") && !content.contains("inf"), "{bad}: {content}");
|
||||
for s in segments(&content) {
|
||||
assert!(s.iter().all(|x| x.abs() <= 50_000.0), "{bad}: {s:?}");
|
||||
}
|
||||
}
|
||||
// Negative LLE and LLO count as 0.
|
||||
let neg = segments(&line_drawing(&table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[("LL", Object::Real(10.0)), ("LLE", Object::Real(-5.0)), ("LLO", Object::Real(-5.0))],
|
||||
)));
|
||||
assert!(has(&neg, [0.0, 0.0, 0.0, 10.0]) && has(&neg, [0.0, 10.0, 100.0, 10.0]), "{neg:?}");
|
||||
// Huge endpoints whose midpoint would overflow fall back to the plain line.
|
||||
let huge = line_drawing(&table_178_line([f64::MAX, f64::MAX, f64::MAX / 2.0, f64::MAX], &[("LL", Object::Real(20.0)), cap, text]));
|
||||
assert!(!huge.contains("NaN") && !huge.contains("inf"), "{huge}");
|
||||
// The caption is cut to 256 characters.
|
||||
let long = line_drawing(&table_178_line(
|
||||
[0.0, 0.0, 100.0, 0.0],
|
||||
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))))],
|
||||
));
|
||||
assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256");
|
||||
assert!(!long.contains(&"w".repeat(257)));
|
||||
}
|
||||
|
||||
@@ -33,7 +33,12 @@ Limits, by design and documented rather than hidden:
|
||||
less than 40% of its words (a sliver of a long value) is not flagged.
|
||||
|
||||
It fails closed: an undecodable content stream, malformed `/Annots`, form XObjects nested deeper
|
||||
than 32 or in a cycle, or a walk past the operator bound is an error, never "no findings".
|
||||
than 32 or in a cycle, a walk past the operator bound, more than 50 million cover-against-word
|
||||
comparisons on a page, or more than 64 MiB of covered text in the report is an error, never "no
|
||||
findings".
|
||||
|
||||
A document whose permissions withhold copying (Table 22, bit 5) still gets every finding, with
|
||||
an empty `covered_text`: the audit hands out no text that copying would refuse.
|
||||
|
||||
Surfaces: the `doc_audit_redactions` automation tool and `pdfcraft-cli audit`. Both report each
|
||||
rectangle in points from the top-left of the page as displayed (y down, after `/Rotate`), like
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! Positions compare lexicographically in paint order.
|
||||
|
||||
use pdfcraft_content::{Matrix, Op, Pieces, parse};
|
||||
use pdfcraft_cos::{Dict, Document, Object};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, Object};
|
||||
|
||||
use crate::AuditError;
|
||||
|
||||
@@ -109,6 +109,9 @@ struct Walker<'a> {
|
||||
pieces: &'a Pieces,
|
||||
out: Vec<FilledRect>,
|
||||
ops_seen: usize,
|
||||
/// Decoded bytes and form entries left for the page, its forms included: spending either
|
||||
/// fails the audit.
|
||||
budget: DecodeBudget,
|
||||
}
|
||||
|
||||
impl<'a> Walker<'a> {
|
||||
@@ -144,10 +147,11 @@ impl<'a> Walker<'a> {
|
||||
match op.op.as_slice() {
|
||||
b"q" => stack.push(gs.clone()),
|
||||
b"Q" => {
|
||||
// The current path is not graphics state (ISO 32000-2 §8.4.1): `re Q f` still
|
||||
// fills the rectangle, whose corners are already in user space.
|
||||
if let Some(g) = stack.pop() {
|
||||
*gs = g;
|
||||
}
|
||||
path = Path::Empty;
|
||||
}
|
||||
b"cm" => {
|
||||
let before = gs.ctm;
|
||||
@@ -258,7 +262,7 @@ impl<'a> Walker<'a> {
|
||||
let resolved = self.doc.resolve(entry);
|
||||
let Object::Stream(stream) = &*resolved else { return Ok(()) };
|
||||
let dict = &stream.dict;
|
||||
if dict.name(b"Subtype") != Some(b"Form") {
|
||||
if crate::subtype(self.doc, dict)?.as_deref() != Some(b"Form") {
|
||||
return Ok(());
|
||||
}
|
||||
let matrix = dict
|
||||
@@ -271,8 +275,11 @@ impl<'a> Walker<'a> {
|
||||
})
|
||||
.unwrap_or(Matrix::IDENTITY);
|
||||
let sub_resources = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
|
||||
if !self.budget.enter_form() {
|
||||
return Err(AuditError::TooManyForms);
|
||||
}
|
||||
// A form stream that cannot be decoded fails the audit: it might hide a cover.
|
||||
let data = stream.decoded_strict()?;
|
||||
let data = self.budget.decode_strict(stream)?;
|
||||
let ops = parse(&data).ops;
|
||||
// The XObject matrix maps form space into the user space active at `Do`.
|
||||
let mut sub_gs = gs.clone();
|
||||
@@ -304,7 +311,8 @@ fn ext_alpha(doc: &Document, resources: &Dict, name: &[u8]) -> f64 {
|
||||
/// Every opaque filled rectangle drawn by a page's content (and its form XObjects), with paint
|
||||
/// positions. A page's content streams are walked once, joined, with one graphics state, so
|
||||
/// state set in an earlier stream is still in force in the later ones. Any content stream that
|
||||
/// cannot be decoded is an audit failure, never an empty result.
|
||||
/// cannot be decoded, or content and forms that decode or enter past one page's [`DecodeBudget`]
|
||||
/// in all, is an audit failure, never an empty result.
|
||||
pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, AuditError> {
|
||||
let resources = page.get(b"Resources").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
|
||||
let contents: Vec<Object> = match page.get(b"Contents") {
|
||||
@@ -314,15 +322,16 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, Audi
|
||||
_ => vec![c.clone()],
|
||||
},
|
||||
};
|
||||
let mut budget = DecodeBudget::page();
|
||||
let mut streams = Vec::with_capacity(contents.len());
|
||||
for c in &contents {
|
||||
if let Object::Stream(s) = &*doc.resolve(c) {
|
||||
streams.push(s.decoded_strict()?);
|
||||
streams.push(budget.decode_strict(s)?);
|
||||
}
|
||||
}
|
||||
let pieces = Pieces::join(&streams);
|
||||
let parsed = pieces.parse();
|
||||
let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0 };
|
||||
let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget };
|
||||
let mut gs = Gs::default();
|
||||
let mut stack = Vec::new();
|
||||
w.walk_ops(&parsed.ops, &mut gs, &mut stack, &resources, 0, None)?;
|
||||
|
||||
+155
-34
@@ -65,7 +65,7 @@ pub struct AuditFinding {
|
||||
/// `rect[0] <= rect[2]` and `rect[1] <= rect[3]`.
|
||||
pub rect: [f64; 4],
|
||||
/// The extractable text the cover hides, lines joined with single spaces and trimmed.
|
||||
/// Possibly empty when nothing decodable remains under the cover.
|
||||
/// Empty when the document's permissions withhold copying (see [`audit_redactions`]).
|
||||
pub covered_text: String,
|
||||
}
|
||||
|
||||
@@ -77,8 +77,14 @@ pub enum AuditError {
|
||||
TooManyOps,
|
||||
#[error("form XObjects nest deeper than the audit follows")]
|
||||
TooDeep,
|
||||
#[error("content walk entered more form XObjects than the audit follows")]
|
||||
TooManyForms,
|
||||
#[error("page has a malformed /Annots entry")]
|
||||
BadAnnots,
|
||||
#[error("page has more covers and text lines than the audit compares")]
|
||||
TooManyComparisons,
|
||||
#[error("covered text exceeds the audit's report budget")]
|
||||
TooMuchOutput,
|
||||
#[error(transparent)]
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
#[error(transparent)]
|
||||
@@ -95,47 +101,122 @@ const WORD_FRACTION: f64 = 0.5;
|
||||
const COVER_CONTRAST: f64 = 3.0;
|
||||
|
||||
/// Audit every page for faux redactions and unapplied redaction marks. Fails closed: any
|
||||
/// content that cannot be decoded is returned as an error, never as an empty finding list.
|
||||
/// content that cannot be decoded, or that needs more work or report than the audit's bounds, is
|
||||
/// returned as an error, never as an empty finding list.
|
||||
///
|
||||
/// When the document's permissions withhold copying (ISO 32000-2 Table 22, bit 5), findings are
|
||||
/// still reported but their `covered_text` is empty: the audit hands out no text that copying
|
||||
/// would refuse.
|
||||
pub fn audit_redactions(doc: &Document) -> Result<Vec<AuditFinding>, AuditError> {
|
||||
audit(doc, Limits::DEFAULT)
|
||||
}
|
||||
|
||||
/// Work and output bounds for one audit.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Limits {
|
||||
/// Cover-against-line comparisons per page, counting a line once per word box it has (at
|
||||
/// least once), since [`covers`] walks them.
|
||||
comparisons: usize,
|
||||
/// Bytes of covered text the findings report.
|
||||
covered_text: usize,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// Every cover is compared with every line of its page, and each finding repeats the text
|
||||
/// it covers, so both grow with the square of the content: a few megabytes of covers over
|
||||
/// one long line would otherwise take hours and gigabytes.
|
||||
const DEFAULT: Limits = Limits { comparisons: 50_000_000, covered_text: 64 << 20 };
|
||||
}
|
||||
|
||||
/// The work and report the audit has spent against its [`Limits`].
|
||||
struct Budget {
|
||||
limits: Limits,
|
||||
comparisons: usize,
|
||||
/// What comparing one cover with every line of the current page costs.
|
||||
page_cost: usize,
|
||||
covered_text: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
/// Resets the comparison count for a page with these `lines`. A line costs its word boxes
|
||||
/// or its runs, whichever are more (at least one): a cover check walks the boxes, and the
|
||||
/// covered text walks the runs, which can draw no words at all (`( ) Tj`).
|
||||
fn start_page(&mut self, lines: &[TextLine]) {
|
||||
self.comparisons = 0;
|
||||
self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(line.runs().count()).max(1)));
|
||||
}
|
||||
|
||||
/// The text `cover` hides in the `lines` that `hides` ([`covered_words`]), joined with single
|
||||
/// spaces, or `None` when they show no text. Without `copying` the text is empty and never
|
||||
/// assembled: one long line under many covers would otherwise be copied once per cover,
|
||||
/// outside both bounds.
|
||||
fn hidden_text(
|
||||
&mut self,
|
||||
lines: &[TextLine],
|
||||
copying: bool,
|
||||
cover: &[f64; 4],
|
||||
hides: impl Fn(&TextLine) -> bool,
|
||||
) -> Result<Option<String>, AuditError> {
|
||||
self.comparisons = self.comparisons.saturating_add(self.page_cost);
|
||||
if self.comparisons > self.limits.comparisons {
|
||||
return Err(AuditError::TooManyComparisons);
|
||||
}
|
||||
if !copying {
|
||||
return Ok(lines.iter().any(|line| hides(line) && !line.text.trim().is_empty()).then(String::new));
|
||||
}
|
||||
let mut covered = String::new();
|
||||
for line in lines.iter().filter(|l| hides(l)) {
|
||||
if !covered.is_empty() {
|
||||
covered.push(' ');
|
||||
}
|
||||
covered_words(cover, line, &mut covered);
|
||||
}
|
||||
Ok((!covered.trim().is_empty()).then_some(covered))
|
||||
}
|
||||
|
||||
/// The text a finding reports for `covered`: none when copying is withheld. Charges what it
|
||||
/// reports against the output bound.
|
||||
fn report_text(&mut self, covered: String, copying: bool) -> Result<String, AuditError> {
|
||||
let reported = if copying { covered } else { String::new() };
|
||||
self.covered_text = self.covered_text.saturating_add(reported.len());
|
||||
if self.covered_text > self.limits.covered_text {
|
||||
return Err(AuditError::TooMuchOutput);
|
||||
}
|
||||
Ok(reported)
|
||||
}
|
||||
}
|
||||
|
||||
fn audit(doc: &Document, limits: Limits) -> Result<Vec<AuditFinding>, AuditError> {
|
||||
let copying = doc.permissions().is_none_or(|p| p.copy());
|
||||
let mut budget = Budget { limits, comparisons: 0, page_cost: 0, covered_text: 0 };
|
||||
let mut out = Vec::new();
|
||||
for (n, page) in pdfcraft_model::pages(doc).iter().enumerate() {
|
||||
let lines = pdfcraft_edit::text_lines(doc, n).map_err(|e| AuditError::Text(n, e.to_string()))?;
|
||||
// The glyphs themselves: `/ActualText` is the file's own claim about them, and an empty
|
||||
// or substitute one must not hide text a cover sits on.
|
||||
let lines = pdfcraft_edit::glyph_text_lines(doc, page).map_err(|e| AuditError::Text(n, e.to_string()))?;
|
||||
budget.start_page(&lines);
|
||||
// 1. Opaque filled rectangles over extractable text.
|
||||
for r in cover::filled_rects(doc, &page.dict)? {
|
||||
let mut covered = String::new();
|
||||
for line in &lines {
|
||||
if is_cover(&r, line) {
|
||||
if !covered.is_empty() {
|
||||
covered.push(' ');
|
||||
}
|
||||
covered.push_str(line.text.trim());
|
||||
}
|
||||
}
|
||||
if !covered.trim().is_empty() {
|
||||
out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text: covered });
|
||||
if let Some(covered) = budget.hidden_text(&lines, copying, &r.rect, |line| is_cover(&r, line))? {
|
||||
let covered_text = budget.report_text(covered, copying)?;
|
||||
out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text });
|
||||
}
|
||||
}
|
||||
// 2. Annotation covers over extractable text.
|
||||
for annot in annots(doc, &page.dict)? {
|
||||
let mut covered = String::new();
|
||||
for line in &lines {
|
||||
let hidden = match &annot {
|
||||
AnnotationCover::Redact(rect) => covers(rect, line),
|
||||
AnnotationCover::Square { rect, rgb } => covers(rect, line) && contrast(line.color, *rgb) < COVER_CONTRAST,
|
||||
};
|
||||
if hidden {
|
||||
if !covered.is_empty() {
|
||||
covered.push(' ');
|
||||
}
|
||||
covered.push_str(line.text.trim());
|
||||
}
|
||||
}
|
||||
if !covered.trim().is_empty() {
|
||||
let cover = match &annot {
|
||||
AnnotationCover::Redact(rect) | AnnotationCover::Square { rect, .. } => *rect,
|
||||
};
|
||||
if let Some(covered) = budget.hidden_text(&lines, copying, &cover, |line| match &annot {
|
||||
AnnotationCover::Redact(rect) => covers(rect, line),
|
||||
AnnotationCover::Square { rect, rgb } => covers(rect, line) && contrast(line.color, *rgb) < COVER_CONTRAST,
|
||||
})? {
|
||||
let (kind, rect) = match annot {
|
||||
AnnotationCover::Redact(rect) => (FindingKind::UnappliedMark, rect),
|
||||
AnnotationCover::Square { rect, .. } => (FindingKind::CoveredText, rect),
|
||||
};
|
||||
out.push(AuditFinding { page: n, kind, rect, covered_text: covered });
|
||||
let covered_text = budget.report_text(covered, copying)?;
|
||||
out.push(AuditFinding { page: n, kind, rect, covered_text });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,11 +224,13 @@ pub fn audit_redactions(doc: &Document) -> Result<Vec<AuditFinding>, AuditError>
|
||||
}
|
||||
|
||||
/// A filled rectangle is a faux-redaction cover for a text line iff it was painted strictly
|
||||
/// after the line, overlaps it substantially, and is dark enough against the line's color to
|
||||
/// make the text unreadable. Light covers (table shading, highlights) over dark text fail the
|
||||
/// contrast check and are not flagged.
|
||||
/// after the start of the line, overlaps it substantially, and is dark enough against the line's
|
||||
/// color to make the text unreadable. Light covers (table shading, highlights) over dark text fail
|
||||
/// the contrast check and are not flagged. A line can join runs painted before and after the
|
||||
/// cover; the later ones are drawn on it in the same low-contrast color, so they are unreadable
|
||||
/// too.
|
||||
fn is_cover(rect: &cover::FilledRect, line: &TextLine) -> bool {
|
||||
rect.pos > line.paint_pos() && covers(&rect.rect, line) && contrast(line.color, rect.rgb) < COVER_CONTRAST
|
||||
rect.pos > line.first_paint_pos() && covers(&rect.rect, line) && contrast(line.color, rect.rgb) < COVER_CONTRAST
|
||||
}
|
||||
|
||||
/// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough:
|
||||
@@ -179,6 +262,34 @@ fn covers(cover: &[f64; 4], line: &TextLine) -> bool {
|
||||
inked || (boxed && (line.ink.is_empty() || word_intersects()))
|
||||
}
|
||||
|
||||
/// Appends the text of `line` that `cover` lies on to `out`: the runs whose words it overlaps
|
||||
/// (#4164), so the words of the line painted beside the cover, which stay visible, are not
|
||||
/// reported as hidden. Neighbouring runs are joined as the line joins them, so a word split
|
||||
/// across runs stays one word; runs with others left out between them are spaced. The whole
|
||||
/// line when its runs can't say: a single run, a line whose text was reordered for reading, or
|
||||
/// a cover that overlaps the line's box but none of its words.
|
||||
fn covered_words(cover: &[f64; 4], line: &TextLine, out: &mut String) {
|
||||
let overlaps = |w: &[f64; 4]| area(&[cover[0].max(w[0]), cover[1].max(w[1]), cover[2].min(w[2]), cover[3].min(w[3])]) > 0.0;
|
||||
let mut words = String::new();
|
||||
let mut last = None;
|
||||
for (i, (text, ink, spaced)) in line.runs().enumerate() {
|
||||
if text.trim().is_empty() || !ink.iter().any(overlaps) {
|
||||
continue;
|
||||
}
|
||||
let apart = last.is_some_and(|l: usize| l.saturating_add(1) != i || spaced);
|
||||
if apart && !words.ends_with(char::is_whitespace) && !text.starts_with(char::is_whitespace) {
|
||||
words.push(' ');
|
||||
}
|
||||
words.push_str(text);
|
||||
last = Some(i);
|
||||
}
|
||||
if line.runs().nth(1).is_none() || last.is_none() {
|
||||
out.push_str(line.text.trim());
|
||||
} else {
|
||||
out.push_str(words.trim());
|
||||
}
|
||||
}
|
||||
|
||||
/// The area of a rectangle, 0 when it is empty or inverted.
|
||||
fn area(r: &[f64; 4]) -> f64 {
|
||||
(r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0)
|
||||
@@ -229,7 +340,7 @@ fn annots(doc: &Document, page: &Dict) -> Result<Vec<AnnotationCover>, AuditErro
|
||||
continue;
|
||||
}
|
||||
let rect = [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])];
|
||||
match dict.name(b"Subtype") {
|
||||
match subtype(doc, &dict)?.as_deref() {
|
||||
Some(b"Redact") => out.push(AnnotationCover::Redact(rect)),
|
||||
Some(b"Square") => {
|
||||
let flags = dict.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);
|
||||
@@ -249,6 +360,16 @@ fn annots(doc: &Document, page: &Dict) -> Result<Vec<AnnotationCover>, AuditErro
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `/Subtype` name of `dict`, following an indirect reference. A reference that cannot be
|
||||
/// loaded fails the audit: the subtype decides whether the object is checked at all.
|
||||
fn subtype(doc: &Document, dict: &Dict) -> Result<Option<Vec<u8>>, AuditError> {
|
||||
let name = match dict.get(b"Subtype") {
|
||||
Some(pdfcraft_cos::Object::Ref(r)) => doc.try_get(r.num)?.as_name().map(<[u8]>::to_vec),
|
||||
other => other.and_then(pdfcraft_cos::Object::as_name).map(<[u8]>::to_vec),
|
||||
};
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn annotation_color(doc: &Document, dict: &Dict, key: &[u8]) -> Option<[f64; 3]> {
|
||||
let values: Vec<f64> = dict.get(key).map(|o| doc.resolve(o))?.as_array()?.iter().map(|o| doc.resolve(o).as_f64()).collect::<Option<_>>()?;
|
||||
if !values.iter().all(|v| v.is_finite()) {
|
||||
|
||||
@@ -592,3 +592,231 @@ fn reading_blocks_respect_stream_comments_and_split_operands() {
|
||||
assert_eq!(text, "Replacement text", "{}", String::from_utf8_lossy(s1));
|
||||
}
|
||||
}
|
||||
|
||||
/// The current path is not graphics state: a rectangle built before `Q` and filled after it
|
||||
/// paints the box, so it is a cover.
|
||||
#[test]
|
||||
fn rectangle_filled_after_restore_is_a_cover() {
|
||||
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g\nq 100 688 220 32 re Q f\n";
|
||||
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{findings:?}");
|
||||
assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
|
||||
}
|
||||
|
||||
/// A `/Subtype` may be an indirect reference to the name, like any other value: a `/Redact`
|
||||
/// annotation and a covering form XObject named that way are still checked.
|
||||
#[test]
|
||||
fn indirect_subtype_is_resolved() {
|
||||
let mut b = Builder::new();
|
||||
b.add("<< /Type /Catalog /Pages 2 0 R >>");
|
||||
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
|
||||
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>");
|
||||
b.add_stream(b"BT /F1 24 Tf 100 700 Td (DO NOT SHARE) Tj ET\n");
|
||||
b.add(FONT);
|
||||
b.add("<< /Type /Annot /Subtype 7 0 R /Rect [95 685 305 725] >>");
|
||||
b.add("/Redact");
|
||||
let findings = audit_redactions(&open(b.build())).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{findings:?}");
|
||||
assert_eq!(findings[0].kind, FindingKind::UnappliedMark);
|
||||
|
||||
let mut b = Builder::new();
|
||||
b.add("<< /Type /Catalog /Pages 2 0 R >>");
|
||||
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
|
||||
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /X 5 0 R >> >> >>");
|
||||
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n/X Do\n");
|
||||
b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype 7 0 R /BBox [0 0 612 792]");
|
||||
b.add(FONT);
|
||||
b.add("/Form");
|
||||
let findings = audit_redactions(&open(b.build())).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{findings:?}");
|
||||
assert_eq!(findings[0].kind, FindingKind::CoveredText);
|
||||
}
|
||||
|
||||
/// Text drawn after a cover on the same baseline joins the covered text in one line. The cover
|
||||
/// still hides the words painted before it.
|
||||
#[test]
|
||||
fn later_text_on_the_line_does_not_clear_an_earlier_cover() {
|
||||
let content = b"0 g\nBT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n";
|
||||
let doc = open(one_page(content, ""));
|
||||
let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
|
||||
assert_eq!(lines.len(), 1, "the runs join one line: {:?}", lines.iter().map(|l| &l.text).collect::<Vec<_>>());
|
||||
let findings = audit_redactions(&doc).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{findings:?}");
|
||||
assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
|
||||
}
|
||||
|
||||
/// #4164: a cover over part of a line reports the words under it, not the words of the same
|
||||
/// line painted beside it, which stay visible.
|
||||
#[test]
|
||||
fn covered_text_leaves_out_the_words_beside_the_cover() {
|
||||
let covered = |content: &[u8]| {
|
||||
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
|
||||
findings.into_iter().map(|f| f.covered_text).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
|
||||
// A word shown in two runs with nothing between them stays one word (review on #4198).
|
||||
assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SE) Tj (CRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
|
||||
|
||||
// The same for an unapplied redaction mark over the first run only. A mark over both runs
|
||||
// reports both, with the space the line has between them (`tail` is set apart here).
|
||||
for (rect, expected) in [("[98 688 192 720]", "SECRET"), ("[98 688 310 720]", "SECRET tail")] {
|
||||
let mut b = Builder::new();
|
||||
b.add("<< /Type /Catalog /Pages 2 0 R >>");
|
||||
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
|
||||
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>");
|
||||
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\nBT /F1 24 Tf 250 700 Td (tail) Tj ET\n");
|
||||
b.add(FONT);
|
||||
b.add(&format!("<< /Type /Annot /Subtype /Redact /Rect {rect} >>"));
|
||||
let findings = audit_redactions(&open(b.build())).expect("audit must run");
|
||||
assert_eq!(findings.iter().map(|f| (f.kind.clone(), f.covered_text.as_str())).collect::<Vec<_>>(), [(FindingKind::UnappliedMark, expected)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Many covers over the same long line repeat its text in every finding: a small file must not
|
||||
/// expand into an unbounded report. Past the budget the audit fails rather than truncate.
|
||||
#[test]
|
||||
fn covered_text_across_findings_is_bounded() {
|
||||
let text = "X".repeat(60_000);
|
||||
let mut content = format!("BT /F1 1 Tf 0 700 Td ({text}) Tj ET\n0 g\n").into_bytes();
|
||||
for i in 0..1_200 {
|
||||
content.extend_from_slice(format!("-{i} 690 50000 20 re f\n").as_bytes());
|
||||
}
|
||||
let result = audit_redactions(&open(one_page(&content, "")));
|
||||
assert!(matches!(result, Err(crate::AuditError::TooMuchOutput)), "{:?}", result.map(|f| f.len()));
|
||||
}
|
||||
|
||||
/// Covers compared against lines are bounded per page, so content that is quadratic in its
|
||||
/// covers and lines fails the audit instead of running for hours. A line costs one comparison per
|
||||
/// word: 20 covers against 20 two-word lines are 800.
|
||||
#[test]
|
||||
fn cover_and_line_comparisons_are_bounded() {
|
||||
let mut content = Vec::new();
|
||||
for i in 0..20 {
|
||||
content.extend_from_slice(format!("BT /F1 12 Tf 72 {} Td (Line {i}) Tj ET\n", 700 - 14 * i).as_bytes());
|
||||
}
|
||||
for _ in 0..20 {
|
||||
content.extend_from_slice(b"1 g 0 0 10 10 re f\n");
|
||||
}
|
||||
let doc = open(one_page(&content, ""));
|
||||
let limits = crate::Limits { comparisons: 799, covered_text: usize::MAX };
|
||||
assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
|
||||
let limits = crate::Limits { comparisons: 800, covered_text: usize::MAX };
|
||||
assert!(crate::audit(&doc, limits).expect("within the budget").is_empty());
|
||||
}
|
||||
|
||||
/// A run that draws no word still costs a comparison: the covered text walks every run of a
|
||||
/// covered line, so a word followed by many `( ) Tj` must not be checked for free (review on
|
||||
/// #4198).
|
||||
#[test]
|
||||
fn runs_without_words_count_against_the_comparison_bound() {
|
||||
let mut content = b"BT /F1 24 Tf 100 700 Td (SECRET) Tj".to_vec();
|
||||
content.extend_from_slice(&b" ( ) Tj".repeat(50));
|
||||
content.extend_from_slice(
|
||||
b" ET
|
||||
0 g
|
||||
98 688 94 32 re f
|
||||
",
|
||||
);
|
||||
let doc = open(one_page(&content, ""));
|
||||
let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text");
|
||||
assert_eq!(lines.iter().map(|l| (l.ink.len(), l.runs().count())).collect::<Vec<_>>(), [(1, 51)]);
|
||||
let limits = crate::Limits { comparisons: 50, covered_text: usize::MAX };
|
||||
assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
|
||||
let limits = crate::Limits { comparisons: 51, covered_text: usize::MAX };
|
||||
assert_eq!(crate::audit(&doc, limits).expect("within the budget").len(), 1);
|
||||
}
|
||||
|
||||
/// Covered text is document text: a document whose permissions withhold copying reports where
|
||||
/// its covers are but not what they hide, unless it was opened with the owner password.
|
||||
#[test]
|
||||
fn copy_restricted_documents_withhold_covered_text() {
|
||||
let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g\n100 688 220 32 re f\n";
|
||||
let mut doc = open(one_page(content, ""));
|
||||
doc.set_encryption(&pdfcraft_cos::NewEncryption {
|
||||
algorithm: pdfcraft_cos::Algorithm::Aes256,
|
||||
user_password: "",
|
||||
owner_password: "owner",
|
||||
permissions: -1 ^ 0b1_0000,
|
||||
encrypt_metadata: true,
|
||||
seed: [7; 32],
|
||||
})
|
||||
.expect("encrypt");
|
||||
let bytes = Arc::new(pdfcraft_cos::write_full(&doc, &Default::default()).expect("save"));
|
||||
let user = Document::open_with_password(bytes.clone(), None).expect("open");
|
||||
let findings = audit_redactions(&user).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "the cover is still reported: {findings:?}");
|
||||
assert_eq!(findings[0].covered_text, "");
|
||||
// The output bound counts the text reported, so withheld text costs nothing.
|
||||
let nothing = crate::Limits { comparisons: usize::MAX, covered_text: 0 };
|
||||
assert_eq!(crate::audit(&user, nothing).expect("withheld text is not output").len(), 1);
|
||||
let owner = Document::open_with_password(bytes, Some("owner")).expect("open");
|
||||
let findings = audit_redactions(&owner).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{findings:?}");
|
||||
assert_eq!(findings[0].covered_text, "SECRET DATA 123");
|
||||
let exact = crate::Limits { comparisons: usize::MAX, covered_text: "SECRET DATA 123".len() };
|
||||
assert!(crate::audit(&owner, exact).is_ok());
|
||||
let short = crate::Limits { covered_text: exact.covered_text - 1, ..exact };
|
||||
assert!(matches!(crate::audit(&owner, short), Err(crate::AuditError::TooMuchOutput)));
|
||||
}
|
||||
|
||||
/// Withheld text is never assembled: covers over one long line would otherwise copy the line once
|
||||
/// per cover, a volume neither the comparison nor the output bound charges.
|
||||
#[test]
|
||||
fn withheld_covered_text_is_not_assembled() {
|
||||
const PAGE: [f64; 4] = [0.0, 0.0, 612.0, 792.0];
|
||||
let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n", ""));
|
||||
let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
|
||||
let mut budget = crate::Budget { limits: crate::Limits::DEFAULT, comparisons: 0, page_cost: 0, covered_text: 0 };
|
||||
budget.start_page(&lines);
|
||||
let withheld = budget.hidden_text(&lines, false, &PAGE, |_| true).expect("within the budget");
|
||||
assert_eq!(withheld.map(|t| t.capacity()), Some(0), "a finding, with no text built for it");
|
||||
assert_eq!(budget.hidden_text(&lines, false, &PAGE, |_| false).expect("within the budget"), None);
|
||||
let copied = budget.hidden_text(&lines, true, &PAGE, |_| true).expect("within the budget");
|
||||
assert_eq!(copied.as_deref(), Some("SECRET DATA 123"));
|
||||
}
|
||||
|
||||
/// `/ActualText` is metadata the file's author controls: an empty or substitute replacement must
|
||||
/// not hide the glyphs a cover sits on.
|
||||
#[test]
|
||||
fn a_cover_over_text_with_empty_or_substitute_actual_text_is_found() {
|
||||
for actual in ["()", "(nothing here)"] {
|
||||
let content =
|
||||
format!("/Span << /ActualText {actual} >> BDC\nBT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nEMC\n0 g\n100 688 220 32 re f\n");
|
||||
let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run");
|
||||
assert_eq!(findings.len(), 1, "{actual}: {findings:?}");
|
||||
assert!(findings[0].covered_text.contains("SECRET"), "{actual}: covered_text was {:?}", findings[0].covered_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_stream_references_share_one_decode_budget() {
|
||||
use pdfcraft_cos::{Dict, Document, Object, Stream};
|
||||
// One 1 MiB stream of spaces (a kilobyte on disk), named 300 times: by the page's /Contents,
|
||||
// and by 300 draws of a form holding it.
|
||||
let mut doc = Document::new_empty();
|
||||
let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
|
||||
let contents: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(spaces); 300]))].into_iter().collect();
|
||||
assert!(crate::cover::filled_rects(&doc, &contents).is_err(), "repeated content streams");
|
||||
|
||||
let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
|
||||
let form = doc.add(Stream::flate(form_dict, &vec![b' '; 1 << 20]));
|
||||
let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(300).into_bytes()));
|
||||
let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
|
||||
let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
|
||||
let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
|
||||
assert!(crate::cover::filled_rects(&doc, &page).is_err(), "repeated form draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_entries_past_the_page_allowance_fail_the_audit() {
|
||||
use pdfcraft_cos::{Dict, Document, Object, Stream};
|
||||
// An empty form decodes to no bytes, so only the count of entries bounds drawing it again.
|
||||
let mut doc = Document::new_empty();
|
||||
let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
|
||||
let form = doc.add(Stream::from_raw(form_dict, Vec::new()));
|
||||
let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(pdfcraft_cos::MAX_PAGE_FORMS + 1).into_bytes()));
|
||||
let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
|
||||
let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
|
||||
let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
|
||||
assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms)));
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pdfcraft-platform = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = "0.11"
|
||||
tempfile = "3.27"
|
||||
base64 = { version = "0.22", optional = true }
|
||||
base64 = { version = "0.23", optional = true }
|
||||
|
||||
|
||||
[features]
|
||||
|
||||
@@ -33,7 +33,7 @@ its undo/redo history.
|
||||
- For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. `comment_edit` accepts the resulting rectangle.
|
||||
- `doc_close` refuses to drop unsaved changes unless `discard_changes: true`. `doc_save` writes atomically, incrementally in place, and in full for a new path. Atomic output writes call `sync_all` on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss.
|
||||
- With a root set, every read and write path must resolve inside it (symlinks and `..` included). Relative paths resolve inside the root, and `..` is resolved by name before the check. Every path outside the root gets the same refusal (`<path> is outside the allowed directory <root>`), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (`\\host\share`, `\\?\UNC\…`, `\\.\…`) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by `_`, so a name can't lead them out of the folder. The root itself must be a folder.
|
||||
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. It applies on top of `with_root`.
|
||||
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of `with_root`.
|
||||
|
||||
## Text search and cache limits
|
||||
|
||||
@@ -128,7 +128,7 @@ claude mcp add pdfcraft -- pdfcraft-cli mcp --root <dir>
|
||||
1. Add the engine capability first, with its tests (the tool is a thin adapter).
|
||||
2. Add a `ToolDef` in `src/tools.rs`: a precise description, the schema, `ro()`/`destructive()`, and `cmd()` if a registry command exists.
|
||||
3. Handle it in `Automation::call`, validating pages and positions with the existing helpers.
|
||||
4. Add an end-to-end test in `tests/automation.rs`. `tool_table_is_well_formed` checks names, schemas and command links.
|
||||
4. Add an end-to-end test in `tests/it/automation.rs`. `tool_table_is_well_formed` checks names, schemas and command links.
|
||||
|
||||
|
||||
## Moving several page objects
|
||||
|
||||
@@ -504,7 +504,7 @@ impl Automation {
|
||||
"object": t.object.num, "generation": t.object.generation, "type": t.kind,
|
||||
"parent": t.parent.map(|p| json!({ "object": p.num, "generation": p.generation })), "depth": t.depth,
|
||||
"title": t.title, "actual_text": t.actual_text, "alternate_text": t.alt,
|
||||
"language": t.language, "page": t.page.map(|p| p + 1),
|
||||
"language": t.language, "summary": t.summary, "scope": t.scope, "page": t.page.map(|p| p + 1),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -575,6 +575,8 @@ impl Automation {
|
||||
}
|
||||
|
||||
impl Automation {
|
||||
/// Recognition settings from the arguments: `dpi` (clamped to 72–600), `language` (refused
|
||||
/// unless the models read it) and `skip_text_pages`, each left at its default when absent.
|
||||
pub(crate) fn ocr_settings(&self, a: &Args) -> Result<pdfcraft_engine::ocr::OcrSettings> {
|
||||
let mut settings = pdfcraft_engine::ocr::OcrSettings::default();
|
||||
if let Some(d) = a.opt_num("dpi")? {
|
||||
@@ -592,6 +594,9 @@ impl Automation {
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
/// Recognizes text in each of `paths` and writes the result under the same file name in
|
||||
/// `folder`, reporting per file its output, word count and skipped pages, or its error. A
|
||||
/// path outside the root refuses the whole call before any work starts.
|
||||
pub(crate) fn ocr_recognize_files(&mut self, a: &Args) -> Result<Value> {
|
||||
let settings = self.ocr_settings(a)?;
|
||||
let folder = self.resolve(a.str("folder")?, true)?;
|
||||
@@ -601,15 +606,26 @@ impl Automation {
|
||||
for p in &paths {
|
||||
self.resolve_for(p, crate::file_access::Access::Read, true)?;
|
||||
}
|
||||
// Two inputs that would write the same output file overwrite each other while both report
|
||||
// success, so the whole batch is refused here: before the folder is created, anything is
|
||||
// read, or the OCR engines load.
|
||||
let targets: Vec<std::path::PathBuf> = paths.iter().map(|p| child(&folder, &input_file_name(p))).collect();
|
||||
let shared = shared_file_names(&targets);
|
||||
if !shared.is_empty() {
|
||||
return Err(ToolError::InvalidArgs(format!(
|
||||
"more than one input would write to the same output file, so each would replace the one before it. Colliding file names: {}. Give each input a different file name, or run them in separate batches with different folders.",
|
||||
shared.join(", ")
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(&folder).map_err(|e| failed(e.to_string()))?;
|
||||
let ocr = pdfcraft_engine::ocr::engine().map_err(failed)?;
|
||||
let mut out = Vec::new();
|
||||
for p in paths {
|
||||
let name = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into());
|
||||
let name = input_file_name(p);
|
||||
let result =
|
||||
self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| std::fs::read(&src).map_err(|e| e.to_string())).and_then(|bytes| {
|
||||
pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true)
|
||||
});
|
||||
self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string())).and_then(
|
||||
|bytes| pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true),
|
||||
);
|
||||
out.push(match result {
|
||||
Ok(r) => {
|
||||
let target = child(&folder, &name);
|
||||
@@ -623,21 +639,29 @@ impl Automation {
|
||||
Ok(json!({ "files": out }))
|
||||
}
|
||||
|
||||
/// Recognizes text on the open document's `pages` (every page when absent) and adds it,
|
||||
/// reporting the total word count and, per page, why it was skipped or what it found.
|
||||
pub(crate) fn ocr_recognize(&mut self, a: &Args) -> Result<Value> {
|
||||
let settings = self.ocr_settings(a)?;
|
||||
let pages = if a.opt_ints("pages")?.is_some() { self.pages(a, "pages")? } else { Vec::new() };
|
||||
let id = self.doc(a)?.id;
|
||||
let doc = self.doc(a)?;
|
||||
// Recognizing needs only permission to change the document; the words it found are
|
||||
// returned only when copying is allowed too.
|
||||
let (id, copy) = (doc.id, doc.allows_copying());
|
||||
let found = self.session.recognize_text(id, &pages, settings).map_err(failed)?;
|
||||
let list: Vec<Value> = found
|
||||
.iter()
|
||||
.map(|p| match &p.skipped {
|
||||
Some(why) => json!({ "page": p.page + 1, "skipped": why }),
|
||||
None => json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page, "text": p.text() }),
|
||||
None if copy => json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page, "text": p.text() }),
|
||||
None => json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page }),
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "words": found.iter().map(|p| p.words.len()).sum::<usize>(), "pages": list }))
|
||||
}
|
||||
|
||||
/// Whether text recognition's models are installed, the directories searched for them (in
|
||||
/// order), and the languages it reads, each as a code and a name.
|
||||
pub(crate) fn ocr_status(&self) -> Result<Value> {
|
||||
use pdfcraft_engine::ocr;
|
||||
let dirs: Vec<String> = ocr::Models::search_dirs().iter().map(|d| d.to_string_lossy().into_owned()).collect();
|
||||
@@ -646,6 +670,39 @@ impl Automation {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name an input is written under: its own file name, or `document.pdf` when it has none.
|
||||
fn input_file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into())
|
||||
}
|
||||
|
||||
/// The output file names that two or more of `targets` share, each spelling listed once, in input
|
||||
/// order. Names are compared without regard to case on Windows and macOS and exactly elsewhere; on
|
||||
/// Windows a trailing dot or space is not part of the name (`scan.pdf.` is `scan.pdf`). Unicode
|
||||
/// normalization forms (NFC and NFD spellings of one name) are not compared, so such inputs are
|
||||
/// not caught. The folder is the same for every target, so only the names are compared.
|
||||
fn shared_file_names(targets: &[std::path::PathBuf]) -> Vec<String> {
|
||||
let mut groups: std::collections::BTreeMap<String, (usize, Vec<String>)> = std::collections::BTreeMap::new();
|
||||
for target in targets {
|
||||
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let key = if cfg!(windows) {
|
||||
name.trim_end_matches(['.', ' ']).to_lowercase()
|
||||
} else if cfg!(target_os = "macos") {
|
||||
// Case only; NFC and NFD spellings of one name stay distinct here (a known limit).
|
||||
name.to_lowercase()
|
||||
} else {
|
||||
name.clone()
|
||||
};
|
||||
let (count, spellings) = groups.entry(key).or_insert_with(|| (0, Vec::new()));
|
||||
*count += 1;
|
||||
if !spellings.contains(&name) {
|
||||
spellings.push(name);
|
||||
}
|
||||
}
|
||||
groups.into_values().filter(|(count, _)| *count > 1).flat_map(|(_, spellings)| spellings).collect()
|
||||
}
|
||||
|
||||
/// A script's request to the viewer as the JSON that running a script reports; a side panel
|
||||
/// goes by its fixed id.
|
||||
fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
|
||||
use pdfcraft_engine::js::Request as R;
|
||||
match r {
|
||||
@@ -657,6 +714,7 @@ fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
|
||||
R::Focus(f) => json!({ "focus": f }),
|
||||
R::Beep => json!({ "beep": true }),
|
||||
R::SaveAs => json!({ "save_as": true }),
|
||||
R::ShowPanel(p) => json!({ "panel": p.id() }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,7 +723,9 @@ impl Automation {
|
||||
let id = self.doc(a)?.id;
|
||||
let o = self.session.run_javascript(id, a.str("script")?, a.opt_str("field")?).map_err(failed)?;
|
||||
let reqs: Vec<Value> = o.requests.iter().map(request_json).collect();
|
||||
Ok(json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "result": o.result }))
|
||||
Ok(
|
||||
json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "document_errors": o.doc_errors, "result": o.result }),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn js_document_scripts(&self, a: &Args) -> Result<Value> {
|
||||
@@ -696,7 +756,7 @@ impl Automation {
|
||||
let mut files = Vec::new();
|
||||
for p in a.strs("paths")? {
|
||||
let path = self.resolve(p, false)?;
|
||||
files.push((p.to_string(), std::fs::read(&path).map_err(|e| failed(format!("{p}: {e}")))?));
|
||||
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 target = self.resolve(a.str("path")?, true)?;
|
||||
@@ -841,7 +901,7 @@ impl Automation {
|
||||
let result = self
|
||||
.resolve(p, false)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|src| std::fs::read(&src).map_err(|e| e.to_string()))
|
||||
.and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string()))
|
||||
.and_then(|bytes| run_on(&action, &name, std::sync::Arc::new(bytes), |_, _| {}));
|
||||
out.push(match result {
|
||||
Ok(r) => {
|
||||
@@ -1038,3 +1098,21 @@ mod review_html_tests {
|
||||
assert!(!html.contains("<script>"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_output_name_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_output_names_follow_the_default_filesystem() {
|
||||
let targets = |names: &[&str]| -> Vec<std::path::PathBuf> { names.iter().map(|n| std::path::Path::new("out").join(n)).collect() };
|
||||
// A spelling that repeats is one shared name, listed once.
|
||||
assert_eq!(shared_file_names(&targets(&["a.pdf", "b.pdf", "a.pdf"])), vec!["a.pdf".to_string()]);
|
||||
assert!(shared_file_names(&targets(&["a.pdf", "b.pdf"])).is_empty());
|
||||
// Case is ignored on Windows and macOS only; a trailing dot is ignored on Windows only.
|
||||
let case = shared_file_names(&targets(&["scan.pdf", "Scan.PDF"]));
|
||||
let dot = shared_file_names(&targets(&["scan.pdf", "scan.pdf."]));
|
||||
assert_eq!(case.len(), if cfg!(any(windows, target_os = "macos")) { 2 } else { 0 }, "{case:?}");
|
||||
assert_eq!(dot.len(), if cfg!(windows) { 2 } else { 0 }, "{dot:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ impl<'a> Recipe<'a> {
|
||||
}
|
||||
|
||||
fn accepts(&self, path: &Path) -> bool {
|
||||
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
|
||||
let extension = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
|
||||
extension == "pdf" || (self.steps.contains(&"convert") && pdfcraft_engine::CONVERTIBLE.contains(&extension.as_str()))
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ impl<'a> Recipe<'a> {
|
||||
if input.len() as u64 > MAX_INPUT {
|
||||
return Err(failed("input exceeds 512 MiB"));
|
||||
}
|
||||
let name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| failed("input name is not UTF-8"))?;
|
||||
let name = path.file_name().and_then(std::ffi::OsStr::to_str).ok_or_else(|| failed("input name is not UTF-8"))?;
|
||||
let mut bytes = Arc::new(input);
|
||||
let mut log = Vec::new();
|
||||
for step in &self.steps {
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
//! Geometry follows the automation convention: points from the top-left of the displayed page,
|
||||
//! y down. It is converted to PDF user space (crop box, `/Rotate`) here.
|
||||
|
||||
use pdfcraft_engine::{
|
||||
Edit, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort};
|
||||
use pdfcraft_render::{Annotation, PageInfo};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -13,6 +13,8 @@ use crate::{Args, Automation, Content, DEFAULT_DPI, MAX_DPI, Result, ToolError,
|
||||
|
||||
/// Author used when a tool call names none.
|
||||
pub(crate) const DEFAULT_AUTHOR: &str = "PdfCraft";
|
||||
/// The largest side of a stamp's box, in points: the largest page PDF allows (ISO 32000-2 Annex C).
|
||||
const MAX_STAMP_SIDE: f64 = 14_400.0;
|
||||
|
||||
pub(crate) fn parse_color(s: &str) -> Result<Rgb> {
|
||||
let named = match s.to_ascii_lowercase().as_str() {
|
||||
@@ -79,13 +81,11 @@ fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
|
||||
}
|
||||
|
||||
/// The engine's `at` for a note or attachment icon whose top-left corner *as displayed* is the
|
||||
/// view point (x, y): the top-left (`[x0, y1]`) of the icon's square in user space. Converting
|
||||
/// the point alone is only right on unrotated pages — under `/Rotate` that corner of the
|
||||
/// displayed square is another corner of the user-space one, and the icon lands one icon-width
|
||||
/// away from where it was asked for.
|
||||
/// view point (x, y): the upper-left corner (`[x0, y1]`) of its `/Rect`. Notes and attachments
|
||||
/// are NoRotate, so on a turned page the icon is drawn upright with its top-left at that corner
|
||||
/// (ISO 32000-2 §12.5.3), and `comment_list` reports that square (`Annotation::shown_rect`).
|
||||
fn icon_anchor(p: &PageInfo, x: f64, y: f64) -> [f64; 2] {
|
||||
let r = rect_to_user(p, [x, y, x + NOTE_SIZE, y + NOTE_SIZE]);
|
||||
[r[0], r[3]]
|
||||
to_user(p, x, y)
|
||||
}
|
||||
|
||||
/// A user-space rectangle as the displayed-page rectangle every tool reports and accepts:
|
||||
@@ -154,8 +154,13 @@ impl Automation {
|
||||
fn comment_target(&self, a: &Args) -> Result<(usize, usize)> {
|
||||
let all = self.comments(a)?;
|
||||
if let Some(id) = a.opt_str("id")? {
|
||||
let c =
|
||||
all.iter().find(|c| c.name.as_deref() == Some(id)).ok_or_else(|| failed(format!("no comment with id {id:?} (see comment_list)")))?;
|
||||
// `/NM` need not be unique (PyMuPDF names the first comment on every page `fitz-A0`):
|
||||
// the first match could be another page's comment, so a shared id is refused.
|
||||
let mut named = all.iter().filter(|c| c.name.as_deref() == Some(id));
|
||||
let c = named.next().ok_or_else(|| failed(format!("no comment with id {id:?} (see comment_list)")))?;
|
||||
if named.next().is_some() {
|
||||
return Err(failed(format!("several comments have the id {id:?}: pass page and index instead (see comment_list)")));
|
||||
}
|
||||
return Ok((c.page, c.index));
|
||||
}
|
||||
let (Some(page), Some(index)) = (a.opt_int("page")?, a.opt_int("index")?) else {
|
||||
@@ -181,8 +186,7 @@ impl Automation {
|
||||
"author": c.author,
|
||||
"contents": c.contents,
|
||||
"modified": c.modified,
|
||||
// Unchanged on a page the viewer could not read (#2660), as `doc_info` reports it.
|
||||
"rect": crate::view_rect(&doc.info, c.page, c.rect),
|
||||
"rect": crate::view_rect(&doc.info, c.page, c.shown_rect(doc.info.pages.get(c.page).map_or(0, |p| p.rotation))),
|
||||
"color": c.color.map(hex),
|
||||
});
|
||||
// A line's ends, or the corners of connected lines, a polygon or a cloud, as
|
||||
@@ -196,33 +200,44 @@ impl Automation {
|
||||
}
|
||||
v
|
||||
};
|
||||
// Every reply under the comment its thread starts from, at any depth, in document order:
|
||||
// a reply to a reply keeps its `/IRT` on the direct parent, so following one level would
|
||||
// drop it. Parents are found by reference, as `/NM` need not be unique. A status or
|
||||
// checkmark belongs to the annotation its `/IRT` names (ISO 32000-2 §12.5.6.2), as in the
|
||||
// Comments panel: one set on a reply is not the comment's.
|
||||
let tops = pdfcraft_render::thread_tops(&all);
|
||||
let mut threads: HashMap<(usize, usize), Vec<&Annotation>> = HashMap::new();
|
||||
for r in &all {
|
||||
let Some(&top) = tops.get(&(r.page, r.index)) else { continue };
|
||||
let key = match r.parent {
|
||||
Some(parent) if r.state.is_some() => parent,
|
||||
_ => top,
|
||||
};
|
||||
threads.entry(key).or_default().push(r);
|
||||
}
|
||||
// An annotation's review status and checkmark: the latest of each set on it.
|
||||
let states = |c: &Annotation, v: &mut Value| {
|
||||
let set = threads.get(&(c.page, c.index)).map(Vec::as_slice).unwrap_or(&[]);
|
||||
v["status"] = json!(set.iter().rev().filter(|r| !r.is_mark()).find_map(|r| r.state.clone()));
|
||||
v["marked"] = json!(set.iter().rev().find(|r| r.is_mark()).is_some_and(|r| r.state.as_deref() == Some("Marked")));
|
||||
};
|
||||
let roots: Vec<Value> = all
|
||||
.iter()
|
||||
.filter(|c| c.in_reply_to.is_none() && only.is_none_or(|p| c.page == p))
|
||||
.filter(|c| c.is_comment() && only.is_none_or(|p| c.page == p))
|
||||
.map(|c| {
|
||||
let mut v = view(c);
|
||||
// Every reply under this comment, at any depth, in document order. A reply to a
|
||||
// reply keeps its `/IRT` on the direct parent, so following one level would drop it.
|
||||
let descends_from = |r: &Annotation, root: &str| -> bool {
|
||||
let mut parent = r.in_reply_to.as_deref();
|
||||
for _ in 0..64 {
|
||||
let Some(nm) = parent else { return false };
|
||||
if nm == root {
|
||||
return true;
|
||||
}
|
||||
parent = all.iter().find(|x| x.name.as_deref() == Some(nm)).and_then(|x| x.in_reply_to.as_deref());
|
||||
}
|
||||
false
|
||||
};
|
||||
let thread: Vec<&Annotation> = match c.name.as_deref() {
|
||||
Some(nm) => all.iter().filter(|r| r.in_reply_to.is_some() && descends_from(r, nm)).collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let status = thread.iter().rev().filter(|r| !r.is_mark()).find_map(|r| r.state.clone());
|
||||
v["status"] = json!(status);
|
||||
v["marked"] = json!(thread.iter().rev().find(|r| r.is_mark()).is_some_and(|r| r.state.as_deref() == Some("Marked")));
|
||||
states(c, &mut v);
|
||||
v["locked"] = json!(c.locked);
|
||||
v["replies"] = thread.iter().filter(|r| r.state.is_none()).map(|r| view(r)).collect();
|
||||
let thread = threads.get(&(c.page, c.index)).map(Vec::as_slice).unwrap_or(&[]);
|
||||
v["replies"] = thread
|
||||
.iter()
|
||||
.filter(|r| r.state.is_none())
|
||||
.map(|r| {
|
||||
let mut reply = view(r);
|
||||
states(r, &mut reply);
|
||||
reply
|
||||
})
|
||||
.collect();
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -385,7 +400,7 @@ impl Automation {
|
||||
"attachment" => {
|
||||
let [x, y] = a.need::<2>("at", "an attachment (its icon's top-left)")?;
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let data = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let data = crate::read_input(&path)?;
|
||||
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let icon = match a.opt_str("icon")? {
|
||||
Some(n) => pdfcraft_engine::AttachIcon::from_name(n)
|
||||
@@ -638,7 +653,12 @@ impl Automation {
|
||||
edits.push(Edit::FontSizeAnnotation { page, index, size });
|
||||
}
|
||||
if let Some(r) = a.nums::<4>("rect")? {
|
||||
edits.push(Edit::ResizeAnnotation { page, index, rect: rect_to_user(&info, r) });
|
||||
// The rectangle as comment_list reports it: where the comment is drawn.
|
||||
let doc = self.doc(a)?;
|
||||
let rect = rect_to_user(&info, r);
|
||||
let rect =
|
||||
doc.info.annotations.iter().find(|c| c.page == page && c.index == index).map_or(rect, |c| c.rect_for_shown(rect, info.rotation));
|
||||
edits.push(Edit::ResizeAnnotation { page, index, rect });
|
||||
}
|
||||
if let Some([dx, dy]) = a.nums::<2>("move")? {
|
||||
let (o, d) = (to_user(&info, 0.0, 0.0), to_user(&info, dx, dy));
|
||||
@@ -674,19 +694,34 @@ impl Automation {
|
||||
|
||||
impl Automation {
|
||||
/// A custom stamp: a picture file (PDF page or image) centred at `at`, at its natural size
|
||||
/// (at most 200 pt) or `width` points wide.
|
||||
/// (at most 200 pt), or fitted inside `rect`, keeping its shape and centred (#4077).
|
||||
pub(crate) fn stamp_custom(&mut self, a: &Args) -> Result<Value> {
|
||||
let page = self.page(a)?;
|
||||
let info = self.doc(a)?.info.pages[page].clone();
|
||||
let rect = match (a.nums::<4>("rect")?, a.get("at")) {
|
||||
(Some(_), Some(_)) => return Err(ToolError::InvalidArgs("pass at (a point) or rect (a box), not both".into())),
|
||||
(Some(r), None) => {
|
||||
let (w, h) = ((r[2] - r[0]).abs(), (r[3] - r[1]).abs());
|
||||
if !((1.0..=MAX_STAMP_SIDE).contains(&w) && (1.0..=MAX_STAMP_SIDE).contains(&h)) {
|
||||
return Err(ToolError::InvalidArgs(format!(
|
||||
"rect must be [x0, y0, x1, y1] with each side at least 1 pt and at most {MAX_STAMP_SIDE} pt"
|
||||
)));
|
||||
}
|
||||
rect_to_user(&info, r)
|
||||
}
|
||||
(None, _) => {
|
||||
let [x, y] = a.need::<2>("at", "a stamp (its centre, or pass rect)")?;
|
||||
let [ux, uy] = to_user(&info, x, y);
|
||||
[ux, uy, ux, uy]
|
||||
}
|
||||
};
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = a.opt_str("name")?.map(str::to_owned).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(s, _)| s.to_owned()));
|
||||
let [x, y] = a.need::<2>("at", "a stamp (its centre)")?;
|
||||
let [ux, uy] = to_user(&info, x, y);
|
||||
let edit = Edit::AddCustomStamp {
|
||||
page,
|
||||
rect: [ux, uy, ux, uy],
|
||||
rect,
|
||||
name,
|
||||
file: pdfcraft_engine::MarkFile {
|
||||
name: file,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! move/resize/retype/restyle it, delete it. Geometry is in points from the top-left of the
|
||||
//! displayed page (y down), like every other tool.
|
||||
|
||||
use pdfcraft_engine::{AddedContent, AddedText, Edit, FontFamily, TextAlign};
|
||||
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::comments::parse_color;
|
||||
@@ -61,6 +61,12 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
|
||||
other => return Err(bad(format!("unknown align {other:?}"))),
|
||||
};
|
||||
}
|
||||
if let Some(c) = a.opt_num("char_spacing")? {
|
||||
if !(-ADDED_CHAR_SPACING_LIMIT..=ADDED_CHAR_SPACING_LIMIT).contains(&c) {
|
||||
return Err(bad(format!("char_spacing must be between -{ADDED_CHAR_SPACING_LIMIT} and {ADDED_CHAR_SPACING_LIMIT} points")));
|
||||
}
|
||||
t.char_spacing = c;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -85,6 +91,7 @@ impl Automation {
|
||||
v["size"] = json!(t.size);
|
||||
v["bold"] = json!(t.bold);
|
||||
v["italic"] = json!(t.italic);
|
||||
v["char_spacing"] = json!(t.char_spacing);
|
||||
}
|
||||
AddedContent::Image(_) => v["type"] = json!("image"),
|
||||
}
|
||||
@@ -118,7 +125,7 @@ impl Automation {
|
||||
let page = self.page(a)?;
|
||||
let ph = self.doc(a)?.info.pages[page].height as f64;
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let rect = rect_arg(a, "rect")?.map(|r| to_display(r, ph));
|
||||
let mut out = self.apply(a, Edit::AddImage { page, rect, name, bytes: std::sync::Arc::new(bytes) })?;
|
||||
@@ -164,8 +171,8 @@ impl Automation {
|
||||
if a.get("text").is_some() {
|
||||
return Err(bad("images have no text"));
|
||||
}
|
||||
if ["font", "size", "bold", "italic", "color", "align"].iter().any(|k| a.get(k).is_some()) {
|
||||
return Err(bad("font, size, bold, italic, color and align apply to text"));
|
||||
if ["font", "size", "bold", "italic", "color", "align", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
|
||||
return Err(bad("font, size, bold, italic, color, align and char_spacing apply to text"));
|
||||
}
|
||||
if let Some(deg) = a.opt_int("rotate")? {
|
||||
if deg.rem_euclid(90) != 0 {
|
||||
@@ -181,14 +188,16 @@ impl Automation {
|
||||
i.flip_v = !i.flip_v;
|
||||
}
|
||||
if let Some(c) = rect_arg(a, "crop")? {
|
||||
if !c.iter().all(|v| (0.0..0.5).contains(v)) {
|
||||
return Err(bad("crop takes fractions from 0 to under 0.5 (left, bottom, right, top)"));
|
||||
if !pdfcraft_engine::AddedImage::crop_valid(c) {
|
||||
return Err(bad(
|
||||
"crop takes fractions from 0 to under 1 (left, bottom, right, top); left and right together, and bottom and top together, trim at most 0.95",
|
||||
));
|
||||
}
|
||||
i.crop = c;
|
||||
}
|
||||
if let Some(p) = a.opt_str("image")? {
|
||||
let path = self.resolve(p, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// Box and transforms first, then the new picture.
|
||||
self.apply(a, Edit::UpdateContent { page, index, content: content.clone() })?;
|
||||
@@ -203,6 +212,63 @@ impl Automation {
|
||||
let (page, index, _, _) = self.item(a)?;
|
||||
self.apply(a, Edit::DeleteContent { page, index })
|
||||
}
|
||||
|
||||
/// Edit ▸ Copy, then Paste: an added item onto `to_page` of `to_doc` (its own page and
|
||||
/// document by default), as it is, at `at` (its top-left) or where it was, stepped down and to
|
||||
/// the right past copies of it already on that page.
|
||||
pub(crate) fn content_copy(&mut self, a: &Args) -> Result<Value> {
|
||||
let (page, index, content, _) = self.item(a)?;
|
||||
let source = self.doc(a)?;
|
||||
source.check_copying()?;
|
||||
let from = source.id;
|
||||
let file = match &content {
|
||||
AddedContent::Text(_) => None,
|
||||
AddedContent::Image(_) => {
|
||||
let (ext, bytes) = source.added_image_file(page, index).map_err(failed)?;
|
||||
Some((format!("Pasted image.{ext}"), std::sync::Arc::new(bytes)))
|
||||
}
|
||||
};
|
||||
let to_doc = match a.opt_int("to_doc")? {
|
||||
Some(d) => {
|
||||
let d = u64::try_from(d).map_err(|_| bad("to_doc must be positive"))?;
|
||||
self.session.get(pdfcraft_engine::DocId(d)).ok_or_else(|| failed(format!("no open document with id {d} (see doc_list)")))?.id
|
||||
}
|
||||
None => from,
|
||||
};
|
||||
let doc = self.session.get(to_doc).ok_or_else(|| failed("the document is no longer open"))?;
|
||||
let n = doc.info.pages.len();
|
||||
let to_page = match a.opt_int("to_page")? {
|
||||
Some(p) => usize::try_from(p)
|
||||
.ok()
|
||||
.and_then(|p| p.checked_sub(1))
|
||||
.filter(|p| *p < n)
|
||||
.ok_or_else(|| bad(format!("to_page {p} is out of range: the document has {n} pages")))?,
|
||||
None if page < n => page,
|
||||
None => return Err(bad(format!("page {} is out of range in the target: it has {n} pages; pass to_page", page + 1))),
|
||||
};
|
||||
let info = doc.info.pages.get(to_page).ok_or_else(|| bad("the page no longer exists"))?;
|
||||
let (pw, ph) = (f64::from(info.width), f64::from(info.height));
|
||||
let at = match a.get("at") {
|
||||
Some(v) => {
|
||||
let p: Option<Vec<f64>> = v.as_array().and_then(|x| x.iter().map(Value::as_f64).collect());
|
||||
let [x, y]: [f64; 2] = p.and_then(|p| p.try_into().ok()).ok_or_else(|| bad("at must be [x, y]"))?;
|
||||
Some([x, ph - y])
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let on_page = || doc.added().iter().filter(|x| x.page == to_page);
|
||||
let rect = match at {
|
||||
Some(at) => pdfcraft_engine::added_paste_rect(content.rect(), [pw, ph], 0, Some(at)),
|
||||
None => pdfcraft_engine::added_paste_place(on_page().map(|x| &x.content), &content, [pw, ph]),
|
||||
};
|
||||
let before = on_page().count();
|
||||
let target = json!({ "doc": to_doc.0 });
|
||||
let mut out = self.apply(&Args(&target), Edit::PasteContent { page: to_page, content: content.with_rect(rect), file })?;
|
||||
out["page"] = json!(to_page + 1);
|
||||
out["index"] = json!(before + 1);
|
||||
out["rect"] = json!(to_view(rect, ph).map(|x| (x * 100.0).round() / 100.0));
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl Automation {
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`)
|
||||
//! than the root's is refused by name, before anything is resolved: resolving it would contact
|
||||
//! the host.
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), without regard to case on Windows.
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
@@ -97,7 +100,10 @@ impl AutomationRoots {
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")),
|
||||
};
|
||||
};
|
||||
if inside(&resolve(shown, target)?, folder) {
|
||||
let absolute = absolute(shown, target)?;
|
||||
// Another network share or a device is refused by name, as `--root` refuses it: even
|
||||
// resolving the path would contact the host (#4003).
|
||||
if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) {
|
||||
return Ok(());
|
||||
}
|
||||
let root = root_shown.display();
|
||||
@@ -123,9 +129,8 @@ fn plain(path: PathBuf) -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
/// `path` made absolute against the working directory, by name: nothing on disk is read.
|
||||
fn absolute(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
@@ -133,10 +138,15 @@ fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
|
||||
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {shown}"));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?;
|
||||
std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))
|
||||
}
|
||||
|
||||
/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing
|
||||
/// folder's links followed and the rest appended.
|
||||
fn resolve(shown: &str, absolute: &Path) -> Result<PathBuf, String> {
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
let mut at = absolute;
|
||||
loop {
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
@@ -189,6 +199,24 @@ fn same_component(a: Component, b: Component) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` names another network share or device namespace than `root` (Windows
|
||||
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
|
||||
/// that one exists would contact the host. Drive letters are left to the normal check.
|
||||
pub(crate) fn foreign_share(path: &Path, root: &Path) -> bool {
|
||||
use std::path::Prefix;
|
||||
fn share(p: &Path) -> Option<String> {
|
||||
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
|
||||
let (kind, a, b) = match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
|
||||
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
|
||||
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
|
||||
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
|
||||
};
|
||||
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
|
||||
}
|
||||
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
@@ -233,6 +261,27 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// #4003: another share or a device namespace is refused by name, with the same words as any
|
||||
/// other path outside the root, before anything is resolved (which would contact the host).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_shares_and_devices_are_refused_before_they_are_resolved() {
|
||||
let (base, roots) = folders("shares");
|
||||
for p in [
|
||||
r"\\.\pipe\pdfcraft-4003.pdf",
|
||||
r"\\?\GLOBALROOT\Device\Null",
|
||||
r"\\pdfcraft-no-such-host.invalid\share\a.pdf",
|
||||
"//pdfcraft-no-such-host.invalid/share/a.pdf",
|
||||
r"\\?\UNC\pdfcraft-no-such-host.invalid\share\a.pdf",
|
||||
] {
|
||||
let e = roots.check(p, Access::Read).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the read root"), "{p}: {e}");
|
||||
let e = roots.check(p, Access::Write).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the write root"), "{p}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sibling_with_the_same_prefix_is_outside() {
|
||||
let (base, roots) = folders("prefix");
|
||||
@@ -345,7 +394,8 @@ mod tests {
|
||||
// Helpers that are only called with a resolved path. `doc_batch` (batch.rs) resolves its
|
||||
// inputs and out_dir, walks only inside them (skipping links) and resolves every
|
||||
// discovered file again before `process` reads it or `publish` writes it.
|
||||
const RESOLVED_BY_CALLER: &[&str] = &["write_atomic", "write_atomic_with", "read_review_sidecar", "process", "linked", "walk", "publish"];
|
||||
const RESOLVED_BY_CALLER: &[&str] =
|
||||
&["write_atomic", "write_atomic_with", "read_input", "read_input_bytes", "read_review_sidecar", "process", "linked", "walk", "publish"];
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut offenders = vec![];
|
||||
for entry in std::fs::read_dir(&dir).unwrap() {
|
||||
@@ -365,7 +415,8 @@ mod tests {
|
||||
|| !(trimmed.contains("std::fs")
|
||||
|| trimmed.contains("File::open")
|
||||
|| trimmed.contains("File::create")
|
||||
|| trimmed.contains("OpenOptions"))
|
||||
|| trimmed.contains("OpenOptions")
|
||||
|| trimmed.contains("read_input"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -288,6 +288,23 @@ impl Automation {
|
||||
let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Fill in form".into(), edits } };
|
||||
let mut out = self.apply(a, edit)?;
|
||||
out["filled"] = json!(values.len());
|
||||
// A value the box cuts off at a fixed font size is saved whole but shows only in part:
|
||||
// said, not silent (#4018).
|
||||
let doc = self.doc(a)?;
|
||||
let cut: Vec<Value> = values
|
||||
.keys()
|
||||
.filter_map(|name| doc.field_overflow(name).map(|(page, o)| (name, page, o)))
|
||||
.map(|(name, page, o)| {
|
||||
let page = page.map(|p| format!(" (page {})", p.saturating_add(1))).unwrap_or_default();
|
||||
json!(format!("form field {name:?}{page}: {o}, so the box shows only part of it (the whole value is saved)"))
|
||||
})
|
||||
.collect();
|
||||
if !cut.is_empty() {
|
||||
match out.get_mut("warnings").and_then(Value::as_array_mut) {
|
||||
Some(w) => w.extend(cut),
|
||||
None => out["warnings"] = Value::Array(cut),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -684,7 +701,7 @@ impl Automation {
|
||||
|
||||
pub(crate) fn doc_import_data(&mut self, a: &Args) -> Result<Value> {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let before = (self.doc(a)?.info.annotations.len(), self.doc(a)?.form.iter().filter(|f| !f.value.is_empty()).count());
|
||||
let mut out = self.apply(a, Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) })?;
|
||||
|
||||
+187
-36
@@ -106,6 +106,7 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;
|
||||
const FIND_FIRST_BATCH: usize = 8;
|
||||
const FIND_MAX_BATCH: usize = 128;
|
||||
|
||||
use file_access::foreign_share;
|
||||
use text_cache::TextCache;
|
||||
|
||||
type PageTexts = Vec<(usize, std::result::Result<Arc<PageText>, String>)>;
|
||||
@@ -173,6 +174,12 @@ impl Automation {
|
||||
self
|
||||
}
|
||||
|
||||
/// Multiply the time XFA form scripts may take (tests). See [`Session::with_xfa_time_scale`].
|
||||
pub fn with_xfa_time_scale(mut self, factor: u32) -> Self {
|
||||
self.session = std::mem::take(&mut self.session).with_xfa_time_scale(factor);
|
||||
self
|
||||
}
|
||||
|
||||
/// The clock and time zone of a host without its own. See [`Session::with_wall_clock`].
|
||||
pub fn with_wall_clock(mut self, clock: fn() -> i64, utc_offset: fn() -> i64) -> Self {
|
||||
self.session = std::mem::take(&mut self.session).with_wall_clock(clock, utc_offset);
|
||||
@@ -383,6 +390,36 @@ impl Automation {
|
||||
let (path, page) = (a.path("path")?, self.page(&a)?);
|
||||
self.apply(&a, Edit::SetBookmarkPage { path, page })?
|
||||
}
|
||||
"bookmark_set_style" => {
|
||||
let path = a.path("path")?;
|
||||
// Left out keeps the colour; [0, 0, 0] is the default black.
|
||||
let color = match a.get("color") {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
let rgb: Option<Vec<f64>> = v.as_array().and_then(|c| c.iter().map(Value::as_f64).collect());
|
||||
match rgb.as_deref() {
|
||||
Some(&[r, g, b]) if [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) => Some([r, g, b]),
|
||||
_ => return Err(ToolError::InvalidArgs("color must be [r, g, b], each from 0 to 1".into())),
|
||||
}
|
||||
}
|
||||
};
|
||||
let (bold, italic) = (a.opt_bool("bold")?, a.opt_bool("italic")?);
|
||||
if color.is_none() && bold.is_none() && italic.is_none() {
|
||||
return Err(ToolError::InvalidArgs("give color, bold or italic".into()));
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
if let Some(color) = color {
|
||||
edits.push(Edit::SetBookmarkColor { path: path.clone(), color: Some(color) });
|
||||
}
|
||||
if bold.is_some() || italic.is_some() {
|
||||
edits.push(Edit::SetBookmarkStyle { path, bold, italic });
|
||||
}
|
||||
// A colour and a style given together are one step to undo, applied all or nothing.
|
||||
match edits.len() {
|
||||
1 => self.apply(&a, edits.remove(0))?,
|
||||
_ => self.apply(&a, Edit::Batch { label: "Style".into(), edits })?,
|
||||
}
|
||||
}
|
||||
"bookmark_from_structure" => {
|
||||
let mut out = self.apply(&a, Edit::BookmarksFromStructure)?;
|
||||
let listing = self.bookmark_listing(&a)?;
|
||||
@@ -394,7 +431,7 @@ impl Automation {
|
||||
"page_replace" => {
|
||||
let pages = self.pages(&a, "pages")?;
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
|
||||
let bytes = Arc::new(read_input(&path)?);
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let src_pages = match a.opt_ints("from_pages")? {
|
||||
Some(p) => one_based(&p)?,
|
||||
@@ -435,7 +472,7 @@ impl Automation {
|
||||
"doc_revisions" => self.doc_revisions(&a)?,
|
||||
"text_lines" => {
|
||||
let page = self.page(&a)?;
|
||||
let doc = self.doc(&a)?;
|
||||
let doc = self.doc_to_copy(&a)?;
|
||||
let info = &doc.info.pages[page];
|
||||
let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
|
||||
let lines: Vec<Value> = doc
|
||||
@@ -543,7 +580,7 @@ impl Automation {
|
||||
"delete" => ImageEdit::Delete,
|
||||
"replace" => {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_input(&path)?;
|
||||
ImageEdit::Replace {
|
||||
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
bytes: Arc::new(bytes),
|
||||
@@ -709,7 +746,11 @@ impl Automation {
|
||||
let moved = [block.rect[0] + dx, block.rect[1] + dy, block.rect[2] + dx, block.rect[3] + dy];
|
||||
let wanted: String = text.split_whitespace().collect();
|
||||
let mut out = self.apply(&a, Edit::EditTextBlock { page, block: index, text, style })?;
|
||||
let after = self.doc(&a)?.text_blocks(page);
|
||||
let doc = self.doc(&a)?;
|
||||
let after = doc.text_blocks(page);
|
||||
// Without `text` the paragraph keeps the document's own words: not echoed when
|
||||
// the document doesn't allow copying them.
|
||||
let copy = doc.allows_copying();
|
||||
// Only a paragraph that now shows exactly the requested text is the edited one. A
|
||||
// neighbour that overlaps the old box (overlaid text, a text layer) must not take
|
||||
// its number, and neither must a paragraph the edit merged it into: rewriting that
|
||||
@@ -717,7 +758,10 @@ impl Automation {
|
||||
let edited = block_overlapping(&after, moved)
|
||||
.filter(|&i| !wanted.is_empty() && after.get(i).is_some_and(|b| b.text.split_whitespace().collect::<String>() == wanted));
|
||||
if let Some(b) = edited.and_then(|i| after.get(i)) {
|
||||
out["paragraph"] = json!({ "text": b.text, "lines": b.lines.len(), "font": b.base_font });
|
||||
out["paragraph"] = json!({ "lines": b.lines.len(), "font": b.base_font });
|
||||
if copy {
|
||||
out["paragraph"]["text"] = json!(b.text);
|
||||
}
|
||||
}
|
||||
let stale = self.follow_edit(id, page, k, edited.and_then(|i| after.get(i)), &after);
|
||||
if !stale.is_empty() {
|
||||
@@ -766,7 +810,7 @@ impl Automation {
|
||||
"form_fill" => self.form_fill(&a)?,
|
||||
"form_set_image" => {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_input(&path)?;
|
||||
self.apply(&a, Edit::SetFieldImage { name: a.str("field")?.to_owned(), image: Arc::new(bytes) })?
|
||||
}
|
||||
"form_reset" => self.form_reset(&a)?,
|
||||
@@ -798,7 +842,27 @@ impl Automation {
|
||||
"page_add_image" => self.page_add_image(&a)?,
|
||||
"content_update" => self.content_update(&a)?,
|
||||
"content_delete" => self.content_delete(&a)?,
|
||||
"content_copy" => self.content_copy(&a)?,
|
||||
"doc_print" => self.doc_print(&a)?,
|
||||
"attachment_add" => {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = read_input(&path)?;
|
||||
let name = match a.opt_str("name")? {
|
||||
Some(n) => n.to_string(),
|
||||
None => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
};
|
||||
let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string);
|
||||
let description = a.opt_str("description")?.map(str::to_string);
|
||||
// Only the document-level keys: an annotation attachment of the same name is not the new one.
|
||||
let before = document_attachment_keys(self.doc(&a)?);
|
||||
let out = self.apply(&a, Edit::AddAttachment { name, bytes, description, mime })?;
|
||||
let key = document_attachment_keys(self.doc(&a)?).into_iter().find(|n| !before.contains(n)).unwrap_or_default();
|
||||
json!({ "name": key, "document": out })
|
||||
}
|
||||
"attachment_delete" => {
|
||||
let edit = Edit::DeleteAttachment { key: a.str("name")?.into() };
|
||||
self.apply(&a, edit)?
|
||||
}
|
||||
"doc_remove_hidden" => self.doc_remove_hidden(&a)?,
|
||||
"doc_audit_redactions" => self.doc_audit_redactions(&a)?,
|
||||
"fill_sign_add" => self.fill_sign_add(&a)?,
|
||||
@@ -1000,7 +1064,7 @@ impl Automation {
|
||||
|
||||
fn doc_open(&mut self, a: &Args) -> Result<Value> {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
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 doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?;
|
||||
@@ -1178,7 +1242,7 @@ impl Automation {
|
||||
}
|
||||
|
||||
fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
|
||||
use pdfcraft_engine::optimize::{Compression, ImageSettings, Preset};
|
||||
use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};
|
||||
let id = self.doc(a)?.id;
|
||||
let before = self.doc(a)?.bytes.len();
|
||||
let path = self.resolve(a.str("path")?, true)?;
|
||||
@@ -1186,6 +1250,10 @@ impl Automation {
|
||||
None => Preset::Standard.settings(),
|
||||
Some(p) => Preset::from_name(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown preset {p:?} (standard, mobile)")))?.settings(),
|
||||
};
|
||||
if let Some(c) = a.opt_str("compatibility")? {
|
||||
settings.compatibility = Compatibility::from_name(c)
|
||||
.ok_or_else(|| ToolError::InvalidArgs(format!("unknown compatibility {c:?} (retain, 1.4, 1.5, 1.6, 1.7, 2.0)")))?;
|
||||
}
|
||||
let images = |key: &str, base: ImageSettings| -> Result<ImageSettings> {
|
||||
let Some(v) = a.get(key) else { return Ok(base) };
|
||||
let mut s = base;
|
||||
@@ -1219,6 +1287,8 @@ impl Automation {
|
||||
("discard_tags", &mut settings.discard_tags),
|
||||
("discard_print_settings", &mut settings.discard_print_settings),
|
||||
("flate_unencoded", &mut settings.flate_unencoded),
|
||||
("object_streams", &mut settings.object_streams),
|
||||
("lzw_to_flate", &mut settings.lzw_to_flate),
|
||||
("remove_invalid_links", &mut settings.remove_invalid_links),
|
||||
("remove_unreferenced_dests", &mut settings.remove_unreferenced_dests),
|
||||
] {
|
||||
@@ -1241,9 +1311,26 @@ impl Automation {
|
||||
};
|
||||
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
|
||||
write_atomic(&path, &bytes)?;
|
||||
fn valid_version(v: &[u8]) -> Option<&str> {
|
||||
if matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']) { std::str::from_utf8(v).ok() } else { None }
|
||||
}
|
||||
let catalog_version = (settings.compatibility == Compatibility::Retain)
|
||||
.then(|| {
|
||||
let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
|
||||
let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
|
||||
let root = doc.root()?;
|
||||
doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
|
||||
})
|
||||
.flatten();
|
||||
let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
|
||||
// Viewers read the later of the two (object streams raise the header past a lower catalog
|
||||
// entry). Both are "d.d", so text order is version order.
|
||||
let pdf_version = catalog_version.as_deref().into_iter().chain(header_version).max();
|
||||
let o = &r.optimize;
|
||||
Ok(json!({
|
||||
"path": path.to_string_lossy(),
|
||||
"pdf_version": pdf_version,
|
||||
"object_streams": settings.effective_object_streams(),
|
||||
"bytes_before": before,
|
||||
"bytes_after": bytes.len(),
|
||||
"merged_images": o.merged_images,
|
||||
@@ -1257,6 +1344,7 @@ impl Automation {
|
||||
"alternate_images": o.alternate_images,
|
||||
"tags_removed": o.tags_removed,
|
||||
"streams_compressed": o.streams_compressed,
|
||||
"lzw_streams": o.lzw_streams,
|
||||
"invalid_links": o.invalid_links,
|
||||
"invalid_bookmarks": o.invalid_bookmarks,
|
||||
"unreferenced_dests": o.unreferenced_dests,
|
||||
@@ -1270,7 +1358,7 @@ impl Automation {
|
||||
fn mark_file(&self, a: &Args) -> Result<Option<pdfcraft_engine::MarkFile>> {
|
||||
let Some(p) = a.opt_str("file")? else { return Ok(None) };
|
||||
let path = self.resolve(p, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_input(&path)?;
|
||||
let page = a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1;
|
||||
Ok(Some(pdfcraft_engine::MarkFile {
|
||||
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
@@ -1444,7 +1532,7 @@ impl Automation {
|
||||
let mut images = Vec::new();
|
||||
for p in a.strs("paths")? {
|
||||
let path = self.resolve(p, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_input(&path)?;
|
||||
images.push((path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), bytes));
|
||||
}
|
||||
let name = if images.len() == 1 {
|
||||
@@ -1459,7 +1547,7 @@ impl Automation {
|
||||
(Some(t), _) => ("Text".to_string(), t.to_string()),
|
||||
(None, Some(p)) => {
|
||||
let path = self.resolve(p, false)?;
|
||||
let t = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let t = read_input(&path)?;
|
||||
(path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), pdfcraft_engine::decode_text(&t))
|
||||
}
|
||||
(None, None) => return Err(ToolError::InvalidArgs("text needs `text` or `path`".into())),
|
||||
@@ -1634,7 +1722,7 @@ impl Automation {
|
||||
fn insert_file(&mut self, a: &Args) -> Result<Value> {
|
||||
let at = self.position(a, "at")?;
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_input(&path)?;
|
||||
let pages = a.opt_ints("pages")?.map(|p| one_based(&p)).transpose()?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.apply(a, Edit::InsertPagesFrom { name, bytes: Arc::new(bytes), pages, at, field_conflicts: pdfcraft_organize::FieldConflicts::Rename })
|
||||
@@ -1677,7 +1765,7 @@ impl Automation {
|
||||
// Each file is read, converted and copied in turn, so a long list holds one file at a time.
|
||||
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 = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
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 title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
@@ -1694,7 +1782,7 @@ impl Automation {
|
||||
let mut out = Vec::new();
|
||||
for &p in paths {
|
||||
let converted = self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| {
|
||||
let bytes = std::fs::read(&src).map_err(|e| format!("{}: {e}", src.display()))?;
|
||||
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())?;
|
||||
@@ -1798,7 +1886,7 @@ impl Automation {
|
||||
if let Some(g) = group {
|
||||
firsts.push((g, path.clone(), sources.len()));
|
||||
}
|
||||
let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
|
||||
let bytes = Arc::new(read_input(&path)?);
|
||||
// Images and text files are made into PDFs first (#569), as in the Combine files tab.
|
||||
let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.session.as_pdf(&file_name, &bytes).map_err(failed)?
|
||||
@@ -2291,24 +2379,6 @@ fn lexical(path: &Path) -> Option<PathBuf> {
|
||||
Some(parts.iter().collect())
|
||||
}
|
||||
|
||||
/// Whether `path` names another network share or device namespace than `root` (Windows
|
||||
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
|
||||
/// that one exists would contact the host. Drive letters are left to the normal check.
|
||||
fn foreign_share(path: &Path, root: &Path) -> bool {
|
||||
use std::path::{Component, Prefix};
|
||||
fn share(p: &Path) -> Option<String> {
|
||||
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
|
||||
let (kind, a, b) = match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
|
||||
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
|
||||
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
|
||||
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
|
||||
};
|
||||
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
|
||||
}
|
||||
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
|
||||
}
|
||||
|
||||
// ---- JSON helpers ----------------------------------------------------------------------------
|
||||
|
||||
fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {
|
||||
@@ -2425,6 +2495,18 @@ impl Args<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The name-tree keys of a document's own attachments, leaving out the files attached to pages as comments.
|
||||
fn document_attachment_keys(doc: &Document) -> Vec<String> {
|
||||
doc.info
|
||||
.attachments
|
||||
.iter()
|
||||
.filter_map(|x| match &x.source {
|
||||
pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()),
|
||||
pdfcraft_render::AttachmentSource::Annotation { .. } => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Bookmark rows in listing order as JSON: a row holds the rows that follow it on the page at the
|
||||
/// next level down in `children`, and paths and pages are 1-based.
|
||||
fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::PageInfo]) -> Vec<Value> {
|
||||
@@ -2438,6 +2520,16 @@ fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::Pa
|
||||
}
|
||||
let path: Vec<usize> = row.path.iter().map(|p| p.saturating_add(1)).collect();
|
||||
let mut fields = json!({ "path": path, "title": row.title, "page": row.page.map(|p| p.saturating_add(1)), "open": row.open });
|
||||
// Only what differs from the defaults (black, regular), as the PDF itself stores it.
|
||||
if let Some(color) = row.color {
|
||||
fields["color"] = json!(color);
|
||||
}
|
||||
if row.bold {
|
||||
fields["bold"] = json!(true);
|
||||
}
|
||||
if row.italic {
|
||||
fields["italic"] = json!(true);
|
||||
}
|
||||
if let Some(destination) = row.page.and_then(|p| pages.get(p)).and_then(|p| destination(&row.view, p)) {
|
||||
fields["destination"] = destination;
|
||||
}
|
||||
@@ -2549,6 +2641,9 @@ fn info(d: &Document) -> Value {
|
||||
"creator": i.creator, "producer": i.producer,
|
||||
"tagged": i.tagged,
|
||||
"has_javascript": i.has_javascript,
|
||||
// Where the document opens (/OpenAction, named destinations resolved): 1-based page and
|
||||
// destination, null without one.
|
||||
"open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })),
|
||||
// XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic"
|
||||
// (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed).
|
||||
"xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }),
|
||||
@@ -2569,7 +2664,8 @@ fn info(d: &Document) -> Value {
|
||||
// geometry-taking tools (#129).
|
||||
"annotations": i.annotations.iter().map(|a| json!({
|
||||
"page": page1(a.page), "type": a.subtype, "author": a.author, "contents": a.contents,
|
||||
"modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to, "rect": view_rect(i, a.page, a.rect),
|
||||
"modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to,
|
||||
"rect": view_rect(i, a.page, a.shown_rect(i.pages.get(a.page).map_or(0, |p| p.rotation))),
|
||||
})).collect::<Vec<_>>(),
|
||||
"fields": i.fields.iter().map(|f| json!({
|
||||
"name": f.name, "kind": format!("{:?}", f.kind), "value": f.value, "page": f.page.map(page1),
|
||||
@@ -2591,7 +2687,8 @@ fn info(d: &Document) -> Value {
|
||||
})).collect::<Vec<_>>(),
|
||||
"preserve_rb": preserve_rb,
|
||||
}),
|
||||
pdfcraft_render::LinkTarget::RemoteGoTo { file, destination, new_window } => json!({
|
||||
pdfcraft_render::LinkTarget::RemoteGoTo { launch, file, destination, new_window } => json!({
|
||||
"action": if *launch { "Launch" } else { "GoToR" },
|
||||
"remote_document": file,
|
||||
"destination": match destination {
|
||||
pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }),
|
||||
@@ -2652,7 +2749,7 @@ fn extract_parallel(bytes: &Arc<Vec<u8>>, password: Option<Arc<str>>, pages: &[u
|
||||
}
|
||||
};
|
||||
let config = RenderConfig { password, ..Default::default() };
|
||||
let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).min(8) };
|
||||
let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get).min(8) };
|
||||
// Small jobs aren't worth a second parse of the document.
|
||||
if workers == 1 || pages.len() < 8 {
|
||||
let mut r = PageRenderer::new(bytes.clone(), config);
|
||||
@@ -2700,6 +2797,28 @@ fn unused(dir: &Path, stem: &str) -> PathBuf {
|
||||
(2..10_000u32).map(|n| child(dir, &format!("{stem} ({n}).pdf"))).find(|p| !p.exists()).unwrap_or(first)
|
||||
}
|
||||
|
||||
/// Largest input file a tool reads into memory (512 MiB, matching `doc_batch`).
|
||||
pub(crate) const MAX_INPUT: u64 = 512 * 1024 * 1024;
|
||||
|
||||
/// Read a resolved input file of at most [`MAX_INPUT`] bytes without buffering past the cap.
|
||||
pub(crate) fn read_input_bytes(path: &Path) -> std::io::Result<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path)?;
|
||||
if file.metadata().is_ok_and(|m| m.is_file() && m.len() > MAX_INPUT) {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_INPUT + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_INPUT {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn read_input(path: &Path) -> Result<Vec<u8>> {
|
||||
read_input_bytes(path).map_err(|e| failed(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// Write and sync a temporary file in the same directory, then rename over the target.
|
||||
/// This flushes staged contents; it does not promise parent-directory durability after a
|
||||
/// power loss. Filesystems that refuse sync cause the save to fail before publication.
|
||||
@@ -3257,4 +3376,36 @@ mod tests {
|
||||
assert!(a.session.get(id).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_file_reads_refuse_inputs_exceeding_512_mib() {
|
||||
let dir = staging_dir("capped-read");
|
||||
let huge = dir.join("huge.bin");
|
||||
let file = std::fs::File::create(&huge).unwrap();
|
||||
file.set_len(MAX_INPUT + 1).unwrap();
|
||||
drop(file);
|
||||
let huge_str = huge.to_string_lossy().into_owned();
|
||||
|
||||
let mut a = Automation::new();
|
||||
let id = a.session.open("a.pdf", None, Arc::new(numbered_pages(2)), None).unwrap().0;
|
||||
for (tool, args) in [
|
||||
("doc_open", json!({ "path": huge_str })),
|
||||
("page_insert_file", json!({ "doc": id, "at": 1, "path": huge_str })),
|
||||
("page_replace", json!({ "doc": id, "pages": [1], "path": huge_str })),
|
||||
("page_add_image", json!({ "doc": id, "page": 1, "path": huge_str })),
|
||||
("doc_import_data", json!({ "doc": id, "path": huge_str })),
|
||||
("doc_create", json!({ "from": "text", "path": huge_str })),
|
||||
("doc_create", json!({ "from": "images", "paths": [huge_str] })),
|
||||
("doc_combine", json!({ "paths": [huge_str, huge_str] })),
|
||||
("form_merge_data", json!({ "paths": [huge_str], "path": dir.join("out.csv").to_string_lossy() })),
|
||||
("comment_add", json!({ "doc": id, "page": 1, "type": "attachment", "at": [72.0, 72.0], "path": huge_str })),
|
||||
("stamp_custom", json!({ "doc": id, "page": 1, "at": [72.0, 72.0], "path": huge_str })),
|
||||
("sign_trust", json!({ "paths": [huge_str] })),
|
||||
("attachment_add", json!({ "doc": id, "path": huge_str })),
|
||||
] {
|
||||
let err = a.call(tool, &args).unwrap_err().to_string();
|
||||
assert!(err.contains("input exceeds 512 MiB"), "{tool}: {err}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ 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 {
|
||||
let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else {
|
||||
return Err(bad("the selected link is not a supported local PDF GoToR link"));
|
||||
};
|
||||
(source.path.clone(), file.clone(), destination.clone(), *new_window)
|
||||
|
||||
@@ -25,6 +25,10 @@ const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
const INTERNAL_ERROR: i64 = -32603;
|
||||
|
||||
/// Longest JSON-RPC request line [`McpServer::serve`] buffers into memory (16 MiB).
|
||||
pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
const INSTRUCTIONS: &str = "PdfCraft edits PDFs. Open a file with doc_open to get a document id, then inspect \
|
||||
(doc_info, text_extract, text_find, page_render) or edit it (page_*, doc_set_info). Edits are undoable \
|
||||
@@ -83,18 +87,36 @@ impl McpServer {
|
||||
}
|
||||
|
||||
/// Serve until `input` reaches end of file.
|
||||
pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
|
||||
for line in input.lines() {
|
||||
let line = line?;
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
match read_line_limited(&mut input, &mut buf, MAX_LINE_BYTES)? {
|
||||
LineRead::End => return Ok(()),
|
||||
LineRead::TooLong => {
|
||||
drain_line(&mut input)?;
|
||||
buf.clear();
|
||||
buf.shrink_to(64 * 1024);
|
||||
let reply = error(Value::Null, INVALID_REQUEST, &format!("request line exceeds {MAX_LINE_BYTES} bytes"));
|
||||
writeln!(output, "{reply}")?;
|
||||
output.flush()?;
|
||||
continue;
|
||||
}
|
||||
LineRead::Line => {}
|
||||
}
|
||||
if let Some(reply) = self.handle_line(&line) {
|
||||
let reply = match std::str::from_utf8(&buf) {
|
||||
Ok(line) if line.trim().is_empty() => None,
|
||||
Ok(line) => self.handle_line(line),
|
||||
Err(e) => Some(error(Value::Null, PARSE_ERROR, &format!("parse error: {e}")).to_string()),
|
||||
};
|
||||
if buf.capacity() > 64 * 1024 {
|
||||
buf.clear();
|
||||
buf.shrink_to(64 * 1024);
|
||||
}
|
||||
if let Some(reply) = reply {
|
||||
writeln!(output, "{reply}")?;
|
||||
output.flush()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle one JSON-RPC message; returns the serialized reply, if one is due.
|
||||
@@ -116,7 +138,7 @@ impl McpServer {
|
||||
};
|
||||
let params = obj.get("params").cloned().unwrap_or(Value::Null);
|
||||
let id = id?; // notifications/initialized, notifications/cancelled, …: nothing to answer
|
||||
let result = if method == "tools/call" { guarded_tool(|| self.dispatch(method, ¶ms)) } else { self.dispatch(method, ¶ms) };
|
||||
let result = guarded_dispatch(method, || self.dispatch(method, ¶ms));
|
||||
Some(match result {
|
||||
Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
|
||||
Err((code, message)) => error(id, code, &message),
|
||||
@@ -323,11 +345,67 @@ fn unwrap_tool_call(args: &Value) -> Result<(String, Value), String> {
|
||||
Ok((name.to_owned(), inner))
|
||||
}
|
||||
|
||||
/// What [`read_line_limited`] found.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum LineRead {
|
||||
/// A line, now in the buffer (newline and a trailing `\r` stripped).
|
||||
Line,
|
||||
/// End of stream.
|
||||
End,
|
||||
/// The line is longer than the limit; at most `max + 1` bytes of it were read.
|
||||
TooLong,
|
||||
}
|
||||
|
||||
/// Read one `\n`-terminated line of at most `max` bytes into `buf`.
|
||||
fn read_line_limited(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> std::io::Result<LineRead> {
|
||||
use std::io::Read as _;
|
||||
buf.clear();
|
||||
// `take` bounds what is buffered for one line: never more than `max + 1` bytes.
|
||||
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
|
||||
if reader.take(limit).read_until(b'\n', buf)? == 0 {
|
||||
return Ok(LineRead::End);
|
||||
}
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
if buf.last() == Some(&b'\r') {
|
||||
buf.pop();
|
||||
}
|
||||
return Ok(LineRead::Line);
|
||||
}
|
||||
// No newline: either the limit was passed, or this is a last line before end of stream.
|
||||
Ok(if buf.len() > max { LineRead::TooLong } else { LineRead::Line })
|
||||
}
|
||||
|
||||
/// Discard the rest of an overlong line up to `\n` or end of stream without buffering it.
|
||||
fn drain_line(reader: &mut impl BufRead) -> std::io::Result<()> {
|
||||
loop {
|
||||
let chunk = reader.fill_buf()?;
|
||||
if chunk.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(pos) = chunk.iter().position(|&b| b == b'\n') {
|
||||
reader.consume(pos + 1);
|
||||
return Ok(());
|
||||
}
|
||||
let len = chunk.len();
|
||||
reader.consume(len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Last-resort boundary shared by every tools/call route, including compact dispatch.
|
||||
fn guarded_tool(f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
|
||||
pdfcraft_engine::guard(f).unwrap_or_else(|message| Ok(tool_error(&format!("internal error: {message}"))))
|
||||
}
|
||||
|
||||
/// Last-resort boundary for every JSON-RPC method: tool calls report panics in the tool result
|
||||
/// (`isError: true`), while resource and protocol methods report a JSON-RPC internal error.
|
||||
fn guarded_dispatch(method: &str, f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
|
||||
if method == "tools/call" {
|
||||
return guarded_tool(f);
|
||||
}
|
||||
pdfcraft_engine::guard(f).unwrap_or_else(|message| Err((INTERNAL_ERROR, format!("internal error: {message}"))))
|
||||
}
|
||||
|
||||
fn tool_content(name: &str, content: Vec<Content>) -> Value {
|
||||
let failed = matches!(name, "command_batch" | "doc_batch")
|
||||
&& content.iter().any(|c| match c {
|
||||
@@ -509,7 +587,12 @@ fn call_result(content: Vec<Content>) -> Value {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Resource, first_sentence, parse_uri};
|
||||
use std::io::{BufReader, Read as _};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{McpServer, Resource, first_sentence, parse_uri};
|
||||
use crate::Automation;
|
||||
|
||||
#[test]
|
||||
fn conventions_panic_is_a_tool_error() {
|
||||
@@ -520,6 +603,59 @@ mod tests {
|
||||
assert_eq!(next["ok"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guarded_dispatch_catches_resource_and_protocol_panics() {
|
||||
for method in ["resources/read", "resources/list", "resources/templates/list", "initialize"] {
|
||||
let (code, msg) = super::guarded_dispatch(method, || panic!("synthetic {method} failure")).unwrap_err();
|
||||
assert_eq!(code, -32603, "{method}");
|
||||
assert!(msg.contains(&format!("synthetic {method} failure")), "{msg}");
|
||||
}
|
||||
let ok = super::guarded_dispatch("resources/list", || Ok(json!({"resources": []}))).unwrap();
|
||||
assert_eq!(ok["resources"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_line_limited_and_drain_line_respect_boundaries() {
|
||||
use super::{LineRead, drain_line, read_line_limited};
|
||||
let mut buf = Vec::new();
|
||||
let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc";
|
||||
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
|
||||
assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted");
|
||||
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
|
||||
assert_eq!(buf, b"bb", "CRLF is stripped");
|
||||
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
|
||||
assert_eq!(buf, b"cc", "a last line without a newline is still read");
|
||||
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::End);
|
||||
|
||||
let mut overlong: &[u8] = b"0123456789abcdef\nafter\n";
|
||||
assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::TooLong);
|
||||
assert_eq!(buf.len(), 11, "at most max + 1 bytes are buffered");
|
||||
drain_line(&mut overlong).unwrap();
|
||||
assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::Line);
|
||||
assert_eq!(buf, b"after", "the next line after an overlong line is read cleanly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_answers_non_utf8_and_overlong_lines_and_keeps_serving() {
|
||||
let init = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "0" } }
|
||||
})
|
||||
.to_string();
|
||||
let tail = format!("\n{init}\n");
|
||||
let stream = (&b"\xff\n"[..]).chain(std::io::repeat(b'a').take(64 * 1024 * 1024)).chain(tail.as_bytes());
|
||||
let mut out = Vec::new();
|
||||
McpServer::new(Automation::new()).serve(BufReader::new(stream), &mut out).unwrap();
|
||||
let replies: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), 3, "{replies:?}");
|
||||
assert_eq!(replies[0]["error"]["code"], -32700);
|
||||
assert_eq!(replies[1]["error"]["code"], -32600);
|
||||
assert_eq!(replies[2]["id"], 1);
|
||||
assert_eq!(replies[2]["result"]["serverInfo"]["name"], "pdfcraft");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_sentence_skips_abbreviations() {
|
||||
assert_eq!(first_sentence("Rotate pages. Undoable."), "Rotate pages.");
|
||||
|
||||
@@ -22,11 +22,72 @@ fn duplex(value: &str, cut_stack: bool) -> Result<Option<spool::Duplex>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// [`duplex`] for a job laid out as `layout`: the name is checked either way, and a booklet
|
||||
/// decides two-sided itself (#2707), as the Print dialog does (`print::booklet_duplex`).
|
||||
fn job_duplex(value: &str, layout: &Layout) -> Result<Option<spool::Duplex>> {
|
||||
let chosen = duplex(value, matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
|
||||
Ok(match layout {
|
||||
Layout::Booklet { subset, .. } => Some(print::booklet_duplex(*subset)),
|
||||
_ => chosen,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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(", ")
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The spooler job for `doc_print` to `printer`. It feeds the paper the PDF was laid out on
|
||||
/// (`PAPERS[paper]`, as `media` after the driver's `options`) rather than the queue's default
|
||||
/// paper, which a job naming none got (A4 under Letter sheets on the queue in #3752).
|
||||
fn spool_job(a: &Args, printer: &str, title: String, duplex: Option<spool::Duplex>, paper: usize) -> Result<spool::Job> {
|
||||
let options = match a.get("options") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Object(m)) => m
|
||||
.iter()
|
||||
.map(|(k, v)| match v.as_str() {
|
||||
Some(v) => Ok((k.clone(), v.to_string())),
|
||||
None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
|
||||
};
|
||||
Ok(spool::Job {
|
||||
printer: if printer == "default" { None } else { Some(printer.to_string()) },
|
||||
copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
|
||||
collate: a.opt_bool("collate")?.unwrap_or(true),
|
||||
duplex,
|
||||
scaling: spool::Scaling::Exact,
|
||||
grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
|
||||
title,
|
||||
options: options.into_iter().chain(print::media_option(paper)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Automation {
|
||||
/// `printers`: the system's printers, the default marked, and each one's two-sided support
|
||||
/// where the spooler reports it.
|
||||
pub(crate) fn printers(&self) -> Result<Value> {
|
||||
let list: Vec<Value> = spool::printers()
|
||||
.into_iter()
|
||||
@@ -53,6 +114,8 @@ impl Automation {
|
||||
Ok(json!({ "printer": printer, "count": list.len(), "options": list }))
|
||||
}
|
||||
|
||||
/// `doc_print`: lay the document out with the Print dialog's options, then save the
|
||||
/// print-ready PDF to `path` or send it to `printer` with the chosen paper.
|
||||
pub(crate) fn doc_print(&mut self, a: &Args) -> Result<Value> {
|
||||
let doc = self.doc(a)?;
|
||||
let (id, count) = (doc.id, doc.info.pages.len());
|
||||
@@ -108,7 +171,7 @@ impl Automation {
|
||||
},
|
||||
l => return Err(bad(format!("unknown layout {l:?}"))),
|
||||
};
|
||||
let duplex = duplex(a.opt_str("duplex")?.unwrap_or("off"), matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
|
||||
let duplex = job_duplex(a.opt_str("duplex")?.unwrap_or("off"), &layout)?;
|
||||
if a.opt_str("order")? == Some("cut-stack") && !matches!(layout, Layout::Multiple { .. }) {
|
||||
return Err(bad("cut-stack order needs layout multiple"));
|
||||
}
|
||||
@@ -125,20 +188,7 @@ impl Automation {
|
||||
"form-fields-only" => Content::FormFieldsOnly,
|
||||
c => return Err(bad(format!("unknown comments_forms {c:?}"))),
|
||||
};
|
||||
let paper = match a.opt_str("paper")? {
|
||||
None => PAPERS[0].1,
|
||||
Some(p) => PAPERS
|
||||
.iter()
|
||||
.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))
|
||||
})
|
||||
.map(|x| x.1)
|
||||
.ok_or_else(|| {
|
||||
bad(format!("unknown paper {p:?}; choose one of {}", PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")))
|
||||
})?,
|
||||
};
|
||||
let (paper_index, paper) = paper_named(a.opt_str("paper")?)?;
|
||||
// Print as image (Acrobat's Advanced Print Setup): pictures at `dpi`, grey when
|
||||
// `grayscale` is also asked for.
|
||||
let raster = if a.opt_bool("as_image")?.unwrap_or(false) {
|
||||
@@ -162,27 +212,7 @@ impl Automation {
|
||||
out["path"] = json!(path.to_string_lossy());
|
||||
}
|
||||
(None, Some(printer)) => {
|
||||
let name = self.doc(a)?.name.clone();
|
||||
let job = spool::Job {
|
||||
printer: if printer == "default" { None } else { Some(printer.to_string()) },
|
||||
copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
|
||||
collate: a.opt_bool("collate")?.unwrap_or(true),
|
||||
duplex,
|
||||
scaling: spool::Scaling::Exact,
|
||||
grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
|
||||
title: name,
|
||||
options: match a.get("options") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Object(m)) => m
|
||||
.iter()
|
||||
.map(|(k, v)| match v.as_str() {
|
||||
Some(v) => Ok((k.clone(), v.to_string())),
|
||||
None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
|
||||
},
|
||||
};
|
||||
let job = spool_job(a, printer, self.doc(a)?.name.clone(), duplex, paper_index)?;
|
||||
out["job"] = json!(spool::submit(&bytes, &job).map_err(|e| failed(e.to_string()))?);
|
||||
}
|
||||
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
|
||||
@@ -195,6 +225,19 @@ impl Automation {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #2707: a booklet sets two-sided itself whatever `duplex` asks; a bad name is still an error.
|
||||
#[test]
|
||||
fn a_booklet_decides_two_sided_itself() {
|
||||
let booklet = |subset| Layout::Booklet { subset, binding: Binding::Left };
|
||||
for asked in ["printer", "off", "long-edge", "short-edge"] {
|
||||
assert_eq!(job_duplex(asked, &booklet(BookletSubset::BothSides)).ok(), Some(Some(spool::Duplex::ShortEdge)), "{asked}");
|
||||
assert_eq!(job_duplex(asked, &booklet(BookletSubset::FrontOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
|
||||
assert_eq!(job_duplex(asked, &booklet(BookletSubset::BackOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
|
||||
}
|
||||
assert!(job_duplex("sideways", &booklet(BookletSubset::BothSides)).is_err());
|
||||
assert_eq!(job_duplex("long-edge", &Layout::Size(SizeMode::Fit)).ok(), Some(Some(spool::Duplex::LongEdge)), "other layouts keep it");
|
||||
}
|
||||
|
||||
/// `printer` leaves two-sided to the printer's own default (#2422); cut and stack still asks
|
||||
/// for single-sided sheets, and refuses an explicit edge.
|
||||
#[test]
|
||||
@@ -207,4 +250,30 @@ mod tests {
|
||||
assert!(duplex("long-edge", true).is_err());
|
||||
assert!(duplex("sideways", false).is_err());
|
||||
}
|
||||
|
||||
/// #3752: `doc_print` to a printer sent no paper, so the queue's default paper stood in for
|
||||
/// the one the sheets were laid out on (A4 under Letter sheets on the report's queue).
|
||||
#[test]
|
||||
fn printing_to_a_printer_feeds_the_laid_out_paper() {
|
||||
let job = |args: Value, paper_name: Option<&str>| {
|
||||
let (index, _) = paper_named(paper_name).unwrap();
|
||||
spool_job(&Args(&args), "Office", "a.pdf".into(), None, index).unwrap()
|
||||
};
|
||||
let media = |m: &str| ("media".to_string(), m.to_string());
|
||||
// US Letter when no paper is asked for, after the driver's own options.
|
||||
let letter = job(json!({ "options": { "InputSlot": "Tray3" } }), None);
|
||||
assert_eq!(letter.options, [("InputSlot".to_string(), "Tray3".to_string()), media("Letter")]);
|
||||
assert_eq!((letter.printer.as_deref(), letter.title.as_str()), (Some("Office"), "a.pdf"));
|
||||
// Every paper, by its full name, goes out as its own media name.
|
||||
for (i, (name, size)) in PAPERS.iter().enumerate() {
|
||||
assert_eq!(paper_named(Some(name)).ok(), Some((i, *size)), "{name}");
|
||||
assert_eq!(job(json!({}), Some(name)).options, print::media_option(i).into_iter().collect::<Vec<_>>(), "{name}");
|
||||
}
|
||||
// Short forms find the same paper.
|
||||
assert_eq!(job(json!({}), Some("letter")).options, [media("Letter")]);
|
||||
assert_eq!(job(json!({}), Some("ARCH D")).options, [media("na_arch-d_24x36in")]);
|
||||
assert!(matches!(paper_named(Some("Quarto")), Err(ToolError::InvalidArgs(m)) if m.contains("US Letter")));
|
||||
assert_eq!(spool_job(&Args(&json!({})), "default", String::new(), None, 0).ok().map(|j| j.printer), Some(None));
|
||||
assert!(spool_job(&Args(&json!({ "options": { "InputSlot": 3 } })), "Office", String::new(), None, 0).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ impl Automation {
|
||||
return Err(failed(format!("windows:{r}: Windows certificate store identities are only available on Windows")));
|
||||
}
|
||||
let path = self.resolve(a.str("id")?, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(|e| match e {
|
||||
sign::SignError::WrongPassword => bad("the digital ID password is incorrect"),
|
||||
e => failed(e),
|
||||
@@ -320,7 +320,7 @@ impl Automation {
|
||||
};
|
||||
for p in paths {
|
||||
let path = self.resolve(&p, false)?;
|
||||
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_input(&path)?;
|
||||
let lower = p.to_ascii_lowercase();
|
||||
let found = if lower.ends_with(".p12") || lower.ends_with(".pfx") {
|
||||
let id = sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(failed)?;
|
||||
|
||||
@@ -60,7 +60,10 @@ fn color() -> Value {
|
||||
fn comment_ref(mut extra: Value) -> Value {
|
||||
if let Some(props) = extra.as_object_mut() {
|
||||
props.insert("doc".into(), doc());
|
||||
props.insert("id".into(), json!({ "type": "string", "description": "The comment's id (from comment_list)." }));
|
||||
props.insert(
|
||||
"id".into(),
|
||||
json!({ "type": "string", "description": "The comment's id (from comment_list). An id several comments share is refused: pass page and index." }),
|
||||
);
|
||||
props.insert("page".into(), json!({ "type": "integer", "minimum": 1, "description": "With `index`, instead of `id`." }));
|
||||
props.insert(
|
||||
"index".into(),
|
||||
@@ -129,11 +132,17 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"dpi": {"type":"number","minimum":72,"maximum":600},
|
||||
"language": {"type":"string"}, "skip_text_pages": {"type":"boolean"}
|
||||
}), &["paths","out_dir","steps"])),
|
||||
t("attachment_add", "Attach a file", "Attach the file at path to the document (document level, the Attachments panel; not a paper-clip comment on a page). name defaults to the file's name; the attachment's key, unique in the document, is returned. Undoable.")
|
||||
.cmd("edit.attach")
|
||||
.with(schema(json!({"doc": doc(), "path": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "path"])),
|
||||
t("attachment_delete", "Delete an attachment", "Remove the document-level attachment with this name (as doc_info lists it). Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({"doc": doc(), "name": {"type": "string"}}), &["doc", "name"])),
|
||||
t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited.")
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, attachments, fonts, security and repair notes.")
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security and repair notes.")
|
||||
.ro()
|
||||
.cmd("file.properties")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
@@ -278,7 +287,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"bookmark_list",
|
||||
"List bookmarks",
|
||||
"The bookmarks in outline order, one page at a time: each with its path (1-based, as the other bookmark tools take it), title, target page and open state, and its children on the same page. next is the offset of the following page, or null at the end. Bookmarks nested deeper than 33 levels are not listed.",
|
||||
"The bookmarks in outline order, one page at a time: each with its path (1-based, as the other bookmark tools take it), title, target page and open state, its colour ([r, g, b], 0-1) and bold or italic style when it has them, and its children on the same page. next is the offset of the following page, or null at the end. Bookmarks nested deeper than 33 levels are not listed.",
|
||||
)
|
||||
.ro()
|
||||
.with(schema(
|
||||
@@ -317,6 +326,21 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
t("bookmark_set_page", "Set a bookmark's page", "Point a bookmark at another page. Undoable.")
|
||||
.with(schema(json!({ "doc": doc(), "path": path("The bookmark"), "page": { "type": "integer", "minimum": 1 } }), &["doc", "path", "page"])),
|
||||
t(
|
||||
"bookmark_set_style",
|
||||
"Set a bookmark's style and colour",
|
||||
"Colour a bookmark's title and make it bold or italic (ISO 32000-2 §12.3.3: /C and /F), as bookmark_list reports them. Give any of color ([r, g, b], each 0-1; [0, 0, 0] is the default black), bold and italic; what is left out stays as it is. Undoable.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(),
|
||||
"path": path("The bookmark"),
|
||||
"color": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 3, "maxItems": 3 },
|
||||
"bold": { "type": "boolean" },
|
||||
"italic": { "type": "boolean" }
|
||||
}),
|
||||
&["doc", "path"],
|
||||
)),
|
||||
t(
|
||||
"bookmark_from_structure",
|
||||
"New bookmarks from structure",
|
||||
@@ -349,7 +373,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"form_add_field",
|
||||
"Prepare form: add a field",
|
||||
"Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1). Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
|
||||
"Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1); a dotted name such as MASTER.first makes the field first under the parent field MASTER. Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -389,7 +413,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc", "page", "rect", "rows"],
|
||||
)),
|
||||
t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1) or an image file, centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt. name labels it (default: the file name). Undoable.")
|
||||
t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1, kept as vector content in a form XObject) or an image file. Either centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt, or fitted inside rect [x0, y0, x1, y1] (the same coordinates; each side 1–14400 pt), scaled to keep its shape and centred in the box. Like at, rect is not clipped to the page. Pass at or rect, not both. name labels it (default: the file name). Undoable.")
|
||||
.cmd("comment.stamp")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -397,18 +421,19 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"page": { "type": "integer", "minimum": 1 },
|
||||
"path": { "type": "string" },
|
||||
"at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
|
||||
"file_page": { "type": "integer", "minimum": 1 },
|
||||
"name": { "type": "string" },
|
||||
"author": { "type": "string" },
|
||||
}),
|
||||
&["doc", "page", "path", "at"],
|
||||
&["doc", "page", "path"],
|
||||
)),
|
||||
t("form_set_image", "Set an image field's picture", "Show an image file (PNG, JPEG, TIFF, GIF or BMP) in an image field or button, scaled to fit and centred (what clicking an image field does). On an XFA form the picture is kept in its data too (base64, as Designer saves it) and the form shows it from there. Undoable.")
|
||||
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "path": { "type": "string" } }), &["doc", "field", "path"])),
|
||||
t(
|
||||
"form_set_props",
|
||||
"Field properties",
|
||||
"Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
|
||||
"Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename: a dotted name such as MASTER.first is the full name and moves the field under those parent fields; a plain name renames it within its parent), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -527,7 +552,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; default all); subset odd/even; reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, 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), 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, or US #10 Envelope (short names or full preset labels); 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).",
|
||||
"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; 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, 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, or US #10 Envelope (short names or full preset labels); 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).",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -566,7 +591,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"page_add_text",
|
||||
"Add text to a page",
|
||||
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right. Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
|
||||
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
|
||||
)
|
||||
.cmd("edit.text")
|
||||
.with(schema(
|
||||
@@ -578,6 +603,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
|
||||
}),
|
||||
&["doc", "page", "text"],
|
||||
)),
|
||||
@@ -591,7 +617,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "path": { "type": "string" }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 } }),
|
||||
&["doc", "page", "path"],
|
||||
)),
|
||||
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
|
||||
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
|
||||
@@ -599,12 +625,27 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
|
||||
"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },
|
||||
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },
|
||||
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.95 }, "minItems": 4, "maxItems": 4, "description": "Fractions trimmed: left, bottom, right, top. Left and right together, and bottom and top together, trim at most 0.95." },
|
||||
"image": { "type": "string", "description": "Replace the picture with this file." },
|
||||
}),
|
||||
&["doc", "page", "index"],
|
||||
)),
|
||||
t(
|
||||
"content_copy",
|
||||
"Copy and paste added content",
|
||||
"Copy an added item (page, index from content_list) and paste it, as Edit ▸ Copy and Paste do: onto to_page of to_doc (by default its own page and document) as it is: a text box's text, font, size, colour, alignment and box; an image's picture, box, turns, flips and crop (within its document the same image object is drawn again; into another one the picture goes as its JPEG or JPEG 2000 file, or else a PNG, without a colour profile and with CMYK colours turned to RGB). It goes at at [x, y] (its top-left, points from the top-left of the page), else where it was, 18 points down and to the right past each copy of it already there; kept on the page. Refused when the source document doesn't allow copying. Returns the new item's page, index and rect. Undoable in the target document.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
|
||||
"to_doc": { "type": "integer", "minimum": 1, "description": "The document to paste into (default doc)." },
|
||||
"to_page": { "type": "integer", "minimum": 1, "description": "The page to paste onto (default page)." },
|
||||
"at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
|
||||
}),
|
||||
&["doc", "page", "index"],
|
||||
)),
|
||||
t("content_delete", "Delete added content", "Delete an added item (page, index from content_list). Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 } }), &["doc", "page", "index"])),
|
||||
@@ -662,7 +703,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro().cmd("measure.snap").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"tolerance":{"type":"number","minimum":0,"maximum":10000},"endpoints":{"type":"boolean"},"midpoints":{"type":"boolean"},"intersections":{"type":"boolean"},"paths":{"type":"boolean"}}), &["doc","page","at"])),
|
||||
t("measure_export", "Export measurements as CSV", "Atomically write saved measurement values, labels, authors and scale ratios as spreadsheet-safe CSV. Returns how many unsupported measurements were left out.")
|
||||
.cmd("measure.export").with(schema(json!({"doc":doc(),"out":path_arg()}), &["doc","out"])),
|
||||
t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status and replies.")
|
||||
t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status, checkmark and replies (each with its own status and checkmark).")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1, "description": "Only this page." } }), &["doc"])),
|
||||
t(
|
||||
@@ -693,7 +734,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"stamp": { "type": "string" },
|
||||
"dynamic": { "type": "boolean" },
|
||||
"strokes": { "type": "array", "items": { "type": "array", "items": point() } },
|
||||
"icon": { "type": "string", "description": "note: Comment, Note, Help, Insert, Key, NewParagraph, Paragraph; attachment: PushPin, Paperclip, Graph, Tag." },
|
||||
"icon": { "type": "string", "description": "note: Comment, Note, Help, Insert, Key, NewParagraph, Paragraph (the standard names), Check, Circle, Cross, CrossHairs, Star, RightArrow, UpArrow; attachment: PushPin, Paperclip, Graph, Tag." },
|
||||
"color": color(),
|
||||
"fill": color(),
|
||||
"opacity": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
@@ -915,7 +956,7 @@ 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>> (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. 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. replace: true swaps out existing ones (Update). Undoable.",
|
||||
)
|
||||
.cmd("edit.header_footer")
|
||||
.with(schema(
|
||||
@@ -1053,7 +1094,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
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.")
|
||||
.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 and language, 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.")
|
||||
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.")
|
||||
.ro()
|
||||
.cmd("a11y.tags")
|
||||
.with(schema(
|
||||
@@ -1071,11 +1112,11 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro()
|
||||
.cmd("a11y.tags")
|
||||
.with(schema(json!({ "doc": doc(), "object": { "type": "integer", "minimum": 1 }, "generation": { "type": "integer", "minimum": 0, "maximum": 65535 } }), &["doc", "object", "generation"])),
|
||||
t("accessibility_set_tag_property", "Edit tag property", "Set or clear one property of a reachable indirect structure tag. Use object and generation from accessibility_tags. Properties: type, title, actual_text, alternate_text, language. Empty or omitted value clears text properties; type requires a nonempty PDF name. Undoable.")
|
||||
t("accessibility_set_tag_property", "Edit tag property", "Set or clear one property of a reachable indirect structure tag. Use object and generation from accessibility_tags. Properties: type, title, actual_text, alternate_text, language, summary (Table tags: the table's Summary attribute), scope (TH tags: Row, Column or Both). Summary and scope are written in the tag's Table attribute object (/A, /O /Table); the role map decides a tag's type. Empty or omitted value clears text properties, summary and scope; type requires a nonempty PDF name. Undoable.")
|
||||
.with(schema(json!({
|
||||
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
|
||||
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
|
||||
"property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language"] },
|
||||
"property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] },
|
||||
"value": { "type": "string" },
|
||||
}), &["doc", "object", "generation", "property"])),
|
||||
t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, or content not found on its page are rejected. Undoable.")
|
||||
@@ -1094,7 +1135,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
|
||||
.cmd("form.merge_data")
|
||||
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
|
||||
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts. Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit) and error.")
|
||||
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit), error, and the errors of document-level scripts that failed (the rest still ran).")
|
||||
.cmd("tools.js_console")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." } }),
|
||||
@@ -1172,7 +1213,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
t("js_enabled", "JavaScript on or off", "Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript: set it with `enabled`, or read it. With JavaScript off, field scripts other than Acrobat's AF calls don't run.")
|
||||
.with(schema(json!({ "enabled": { "type": "boolean" } }), &[])),
|
||||
t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable (a searchable image; the image is not changed). Pages that already have text are skipped unless skip_text_pages is false; then pictures on those pages are read too, and recognised words that the page's own text already has (an earlier OCR layer included) are left out and counted as already_on_page. Returns each page's recognised text, word count or why it was skipped. Needs the OCR models (ocr_status). Undoable as one step.")
|
||||
t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable (a searchable image; the image is not changed). Pages that already have text are skipped unless skip_text_pages is false; then pictures on those pages are read too, and recognised words that the page's own text already has (an earlier OCR layer included) are left out and counted as already_on_page. Returns each page's recognised text (left out when the document's security doesn't allow copying), word count or why it was skipped. Needs the OCR models (ocr_status). Undoable as one step.")
|
||||
.cmd("ocr.recognize")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -1184,7 +1225,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc"],
|
||||
)),
|
||||
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Returns, per file, the output path, word count and skipped pages, or the error.")
|
||||
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Two inputs that would write the same output file are refused before anything is read or written. Returns, per file, the output path, word count and skipped pages, or the error.")
|
||||
.cmd("ocr.recognize_batch")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -1332,7 +1373,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro()
|
||||
.cmd("edit.edit_text")
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "paragraph": { "type": "integer", "minimum": 1 }, "text": { "type": "string" }, "size": { "type": "number" }, "width": { "type": "number" }, "font_resource":{"type":"string"}, "ranges":{"type":"array","maxItems":1024,"items":{"type":"object"}} }), &["doc", "page", "paragraph"])),
|
||||
t("text_edit", "Edit text", "Replace the text of one paragraph (paragraph, from text_paragraphs: rewrapped to the paragraph's width with its line spacing) or one line (line, from text_lines) in place, keeping position, size and colour. For a mixed-style region, editor_text supplies visual row breaks; surviving text keeps its source-run styles and inserted text inherits the surrounding run. For a paragraph, also change its formatting: font (helvetica, times, courier) with bold/italic, size (points), color (#rrggbb), align (left, center, right, justify), underline, line_spacing (× size), char_spacing (points) and scale (horizontal, percent), or move it (dx, dy in points; up is +dy) and rewrap it to a new width (points); text may then be omitted. Its own font is reused when it can show every character and no font/weight change is requested; otherwise it uses a standard font matching the source style or, for text no standard font can show, real fallback outlines from PdfCraft's own faces, from the one that has every character: the craft-fonts Japanese faces (Mincho/Gothic matching the requested/source family and available weight) or, behind them, the bundled Inter face, which carries the Latin, Greek and Cyrillic letters they lack (Uzbek қ, Kazakh ә). The result shows the font used. Missing Japanese weights use Regular, not synthetic bold; the small web build has only Gothic Regular. Paragraph bold may be set without font to keep the source family. Text that no available font can show is refused. A paragraph number is refused when an earlier edit merged that paragraph into a neighbour (list the page again); the result's stale_paragraphs names the numbers gone. Undoable.")
|
||||
t("text_edit", "Edit text", "Replace the text of one paragraph (paragraph, from text_paragraphs: rewrapped to the paragraph's width with its line spacing) or one line (line, from text_lines) in place, keeping position, size and colour. For a mixed-style region, editor_text supplies visual row breaks; surviving text keeps its source-run styles and inserted text inherits the surrounding run. For a paragraph, also change its formatting: font (helvetica, times, courier) with bold/italic, size (points), color (#rrggbb), align (left, center, right, justify), underline, line_spacing (× size), char_spacing (points) and scale (horizontal, percent), or move it (dx, dy in points; up is +dy) and rewrap it to a new width (points); text may then be omitted. Its own font is reused when it can show every character and no font/weight change is requested; otherwise it uses a standard font matching the source style or, for text no standard font can show, real fallback outlines from PdfCraft's own faces, from the one that has every character: the craft-fonts Japanese faces (Mincho/Gothic matching the requested/source family and available weight) or, behind them, the bundled Inter face, which carries the Latin, Greek and Cyrillic letters they lack (Uzbek қ, Kazakh ә). The result shows the font used, and for a paragraph its text unless the document's security doesn't allow copying. Missing Japanese weights use Regular, not synthetic bold; the small web build has only Gothic Regular. Paragraph bold may be set without font to keep the source family. Text that no available font can show is refused. A paragraph number is refused when an earlier edit merged that paragraph into a neighbour (list the page again); the result's stale_paragraphs names the numbers gone. Undoable.")
|
||||
.cmd("edit.edit_text")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "line": { "type": "integer", "minimum": 1 },
|
||||
@@ -1359,13 +1400,14 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
|
||||
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
|
||||
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
|
||||
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
|
||||
.cmd("optimize.advanced")
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(),
|
||||
"path": { "type": "string" },
|
||||
"preset": { "type": "string", "enum": ["standard", "mobile"] },
|
||||
"compatibility": { "type": "string", "enum": ["retain", "1.4", "1.5", "1.6", "1.7", "2.0"] },
|
||||
"merge_fragments": { "type": "boolean" },
|
||||
"color": { "type": "object" },
|
||||
"gray": { "type": "object" },
|
||||
@@ -1374,6 +1416,8 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"discard_tags": { "type": "boolean" },
|
||||
"discard_print_settings": { "type": "boolean" },
|
||||
"flate_unencoded": { "type": "boolean" },
|
||||
"object_streams": { "type": "boolean" },
|
||||
"lzw_to_flate": { "type": "boolean" },
|
||||
"remove_invalid_links": { "type": "boolean" },
|
||||
"remove_unreferenced_dests": { "type": "boolean" },
|
||||
"discard": { "type": "array", "items": { "type": "string" } },
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! `attachment_add` reports the name-tree key of the file it added, even when a file attached to
|
||||
//! a page as a comment already has the same name.
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use pdfcraft_engine::{AttachIcon, Edit, NewAnnotation, Session, Shape, Style};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
|
||||
match a.call(name, &args).unwrap().remove(0) {
|
||||
Content::Json(value) => value,
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attachment_add_reports_its_own_key_when_a_page_comment_has_the_same_file_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut session = Session::new();
|
||||
let bytes = session.create_blank(300.0, 400.0, 1).unwrap();
|
||||
let id = session.open("a.pdf", None, bytes, None).unwrap();
|
||||
let shape = Shape::Attachment { at: [20.0, 300.0], icon: AttachIcon::Paperclip, file: "notes.txt".into(), data: b"on the page".to_vec() };
|
||||
session
|
||||
.apply(id, Edit::AddAnnotation(NewAnnotation { page: 0, shape, style: Style::default(), contents: String::new(), author: "Ada".into() }))
|
||||
.unwrap();
|
||||
std::fs::write(dir.path().join("a.pdf"), session.save_bytes(id).unwrap().as_slice()).unwrap();
|
||||
std::fs::write(dir.path().join("notes.txt"), b"for the document").unwrap();
|
||||
|
||||
let mut auto = Automation::new().with_root(dir.path()).unwrap();
|
||||
let doc = tool(&mut auto, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
let added = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
|
||||
assert_eq!(added["name"], "notes.txt", "{added}");
|
||||
let again = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
|
||||
assert_eq!(again["name"], "notes.txt (2)", "{again}");
|
||||
}
|
||||
+1036
-19
File diff suppressed because it is too large
Load Diff
+14
@@ -152,6 +152,7 @@ fn tools_that_read_a_path_are_held_to_the_read_root() {
|
||||
("doc_create_multiple", json!({"paths": [secret], "mode": "combine", "out": out})),
|
||||
("doc_create", json!({"from": "images", "paths": [pic]})),
|
||||
("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "at": [10, 10]})),
|
||||
("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "rect": [10, 10, 493, 300]})),
|
||||
("page_add_image", json!({"doc": 1, "page": 1, "path": pic})),
|
||||
("image_edit", json!({"doc": 1, "page": 1, "image": 1, "action": "replace", "path": pic})),
|
||||
("comment_add", json!({"doc": 1, "page": 1, "type": "attachment", "at": [10, 10], "path": secret})),
|
||||
@@ -351,6 +352,19 @@ fn links_out_of_a_root_are_refused() {
|
||||
assert_eq!(names(&base.join("outside")), ["pic.png", "secret.pdf"]);
|
||||
}
|
||||
|
||||
/// #4003: without `--root`, another network share or a device is refused by name through the
|
||||
/// tools too, with the same words as any other path outside a root.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn other_shares_and_devices_are_refused_by_name() {
|
||||
let (mut server, base) = confined("shares", true, true);
|
||||
ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))}));
|
||||
for p in [r"\\.\pipe\pdfcraft-4003.pdf", r"\\pdfcraft-no-such-host.invalid\share\a.pdf", "//pdfcraft-no-such-host.invalid/share/a.pdf"] {
|
||||
refused(&mut server, "doc_open", json!({"path": p}), "outside the read root");
|
||||
refused(&mut server, "doc_save", json!({"doc": 1, "path": p}), "outside the write root");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_roots_nothing_is_confined() {
|
||||
let base = folders("none");
|
||||
+61
-8
@@ -190,6 +190,54 @@ fn guarded(a: &mut Automation, tool: &str, args: &Value) -> std::result::Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// A new one-page blank document, by id.
|
||||
fn blank_doc(a: &mut Automation) -> u64 {
|
||||
let created = a.call("doc_create", &json!({ "from": "blank", "pages": 1 })).expect("create a blank document");
|
||||
created
|
||||
.into_iter()
|
||||
.find_map(|c| match c {
|
||||
pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(),
|
||||
pdfcraft_automation::Content::Png { .. } => None,
|
||||
})
|
||||
.expect("the new document has an id")
|
||||
}
|
||||
|
||||
/// Delete everything inside `dir`, so one tool never sees files an earlier tool wrote: a digital ID
|
||||
/// that `sign_id_create` wrote to the `in.pdf` placeholder would stop every later `sign_document`
|
||||
/// call at its decrypt, before the argument under test.
|
||||
///
|
||||
/// The entries are reached through the canonical path, as the tools reach them: on Windows that
|
||||
/// is a `\\?\` path, whose names are taken literally. Through the plain path a file the tools
|
||||
/// named `" "` would lose its trailing space and name `dir` itself, which would then be deleted.
|
||||
fn empty_dir(dir: &Path) {
|
||||
let dir = dir.canonicalize().expect("the root exists");
|
||||
for entry in std::fs::read_dir(&dir).expect("read the root") {
|
||||
let entry = entry.unwrap_or_else(|e| panic!("list {}: {e}", dir.display()));
|
||||
let path = entry.path();
|
||||
let is_dir = entry.file_type().unwrap_or_else(|e| panic!("file type of {}: {e}", path.display())).is_dir();
|
||||
let removed = if is_dir { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) };
|
||||
removed.unwrap_or_else(|e| panic!("remove {} before the next tool: {e}", path.display()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Real values for the arguments a tool checks before the others, so a hostile value reaches the
|
||||
/// argument it is meant for instead of failing on a placeholder. `sign_document` checks its
|
||||
/// digital ID first and its document second: this ID opens with its password, and each call gets
|
||||
/// a fresh document (which the caller closes), since a successful call signs it. The ID is a test
|
||||
/// key with a low key derivation count, so the hundreds of calls that open it stay fast.
|
||||
fn fixture(a: &mut Automation, root: &Path, tool: &str) -> serde_json::Map<String, Value> {
|
||||
match tool {
|
||||
"sign_document" => {
|
||||
let id = Path::new(env!("CARGO_MANIFEST_DIR")).join("../sign/tests/data/ec-p256.p12");
|
||||
std::fs::copy(&id, root.join("id.p12")).expect("copy the test digital ID");
|
||||
let doc = blank_doc(a);
|
||||
let args = json!({ "doc": doc, "id": "id.p12", "password": "test", "out": "signed.pdf" });
|
||||
args.as_object().cloned().unwrap_or_default()
|
||||
}
|
||||
_ => serde_json::Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tool_panics_on_hostile_arguments() {
|
||||
let root = tmp("args");
|
||||
@@ -199,6 +247,7 @@ fn no_tool_panics_on_hostile_arguments() {
|
||||
let mut calls = 0usize;
|
||||
|
||||
for def in tools() {
|
||||
empty_dir(&root);
|
||||
// The whole arguments object, not just its properties.
|
||||
for bad in [json!(null), json!([]), json!("string"), json!(7), json!(true), json!({})] {
|
||||
calls += 1;
|
||||
@@ -210,13 +259,24 @@ fn no_tool_panics_on_hostile_arguments() {
|
||||
for prop in &props {
|
||||
for value in &values {
|
||||
let mut obj = plausible(&def);
|
||||
let fixed = fixture(&mut a, &root, def.name);
|
||||
let fixture_doc = fixed.get("doc").cloned();
|
||||
obj.extend(fixed);
|
||||
obj.insert(prop.clone(), value.clone());
|
||||
calls += 1;
|
||||
if let Err(e) = guarded(&mut a, def.name, &Value::Object(obj)) {
|
||||
failures.push(e);
|
||||
}
|
||||
// Later tools pass placeholder document ids, which must not find this one open.
|
||||
if let Some(doc) = fixture_doc {
|
||||
a.call("doc_close", &json!({ "doc": doc, "discard_changes": true })).expect("close the fixture's document");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A signed file shows the fixture got calls past the ID and document checks.
|
||||
if def.name == "sign_document" {
|
||||
assert!(root.join("signed.pdf").is_file(), "no sign_document call signed: the hostile values stop at the ID or document");
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("hostile arguments: {calls} calls over {} tools, {} panics", tools().len(), failures.len());
|
||||
@@ -256,14 +316,7 @@ fn no_tool_escapes_the_root() {
|
||||
let mut a = Automation::new().with_root(&root).expect("root");
|
||||
|
||||
// A real document, so tools reach their path arguments instead of failing on `doc` first.
|
||||
let created = a.call("doc_create", &json!({ "from": "blank", "pages": 1 })).expect("create a blank document");
|
||||
let doc = created
|
||||
.into_iter()
|
||||
.find_map(|c| match c {
|
||||
pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(),
|
||||
pdfcraft_automation::Content::Png { .. } => None,
|
||||
})
|
||||
.expect("the new document has an id");
|
||||
let doc = blank_doc(&mut a);
|
||||
|
||||
let mut leaked = Vec::new();
|
||||
let mut tried = 0usize;
|
||||
@@ -0,0 +1,10 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod attachment_key;
|
||||
mod automation;
|
||||
mod automation_roots;
|
||||
mod batch;
|
||||
mod button_caption;
|
||||
mod form_bulk;
|
||||
mod hostile_args;
|
||||
mod optimize_content_boundaries;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user