Merge branch 'main' into fix/persist-form-reminder

This commit is contained in:
FredApps
2026-12-02 06:33:17 +01:00
committed by GitHub
233 changed files with 13992 additions and 1170 deletions
+8 -1
View File
@@ -6,10 +6,17 @@ xtask = "run -p xtask --"
[target.wasm32-unknown-unknown]
rustflags = ["-C", "target-feature=+simd128"]
[env]
# aws-lc (digital signatures and TLS, through aws-lc-rs) detects the CPU when `main` asks it to
# (`pdfcraft_sign::init_crypto`), not in a static initializer before `main`. On x86 it reads
# `OPENSSL_ia32cap` then, and aborts when that asks for a feature the processor lacks; each
# executable first runs itself again without the variable (#2916, `pdfcraft_platform::crypto_env`),
# which it can only do once `main` runs.
[env]
AWS_LC_SYS_CFLAGS = "-DBORINGSSL_NO_STATIC_INITIALIZER"
# The optional craft-fonts build input (the Japanese face and the other UI faces; see
# crates/fonts/build.rs). A plain build embeds nothing and prints no warning, so a local build
# embeds a craft-fonts checkout next to this repository when there is one. A `CRAFT_FONTS_DIR`
# already in the environment wins (CI sets its own), and a missing checkout only gives the
# "building without craft-fonts" warning.
CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true }
+117
View File
@@ -0,0 +1,117 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/pdfcraft",
"repository_id": 1398086162,
"producer_workflow_id": 434362399,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "pdfcraft-nightly-20261129-initial",
"repository": "storytold/pdfcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 372163538,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_pdfcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_pdfcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
# egui/winit/rfd, and the independent oracles (crates/oracle).
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev qpdf poppler-utils
libgtk-3-dev qpdf poppler-utils xvfb libxkbcommon-x11-0
# cargo-deny for the deny step of `cargo xtask ci`, which requires it under CI.
tools: cargo-nextest@0.9.150,cargo-deny@0.20.2
# A missing oracle fails the job instead of printing a skip notice that reads as a pass.
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [PdfCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# Transport only: exact repository and workflow_run event guard.
if: >-
github.repository == 'storytold/pdfcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/pdfcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/pdfcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/pdfcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/pdfcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'pdfcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+59
View File
@@ -0,0 +1,59 @@
name: PdfCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: pdfcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/pdfcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: main
app-name: pdfcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+35
View File
@@ -0,0 +1,35 @@
name: PdfCraft unsigned nightly
# Scheduled nightly at 08:00 UTC, plus supervised manual runs by the reviewed manual actors.
# Completed scheduled runs are transported to the protected signer branch by nightly-dispatch.yml.
on:
schedule:
- cron: '0 8 * * *'
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/pdfcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: main
app-name: pdfcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release.
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+1
View File
@@ -37,6 +37,7 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: pdfcraft
app-title: PdfCraft
macos-runner: macos-15
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
+3 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
@@ -19,6 +19,8 @@ jobs:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
coverage-application-binaries: pdfcraft
linux-test-packages: xvfb libxkbcommon-x11-0
# Same craft-fonts commit as ci.yml and release.yml.
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
+1 -1
View File
@@ -81,7 +81,7 @@ For the crates you changed: `cargo fmt --check`, `cargo clippy -p <crate> -- -D
- The workspace sets `unsafe_code = "forbid"`; no module allows `unsafe`. `[lints] workspace = true` in every crate.
- Hostile-input sweep: `crates/automation/tests/it/hostile_args.rs`. The last-resort `catch_unwind` guards are in `crates/engine/src/doc_state.rs` and `crates/ui-egui/src/frame_guard.rs`.
- Attribution: `ATTRIBUTION.toml` is the source (one entry per asset, SHA-256 each); `ATTRIBUTION.md` is generated by `cargo xtask assets --write`. The ArtCraft logos in `docs/brand/` are trademark assets under `docs/brand/LICENSE-brand.txt`.
- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped).
- Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; `.cargo/config.toml` points it at `../craft-fonts`, and a `CRAFT_FONTS_DIR` in the environment wins; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped).
- Automation: every feature is a tool in `crates/automation` (`pdfcraft-cli run` and `pdfcraft-cli mcp` share the table; see `crates/automation/README.md`). MCP and the UI control channel are opt-in. The control channel runs only with `--control <PORT>`, binds to loopback and authenticates with a token (`--control-token`, or an owner-only file named by `--control-token-file`, which `craft_platform::owner_only` sets and checks); never enable it by default or log the token.
- Page modules register `PagePart`s (`canvas/page_parts.rs`) and act through the tool host (`canvas/page_tools.rs`). Keys and clipboard events are commands and tool claims, and the framework blocks both while a modal is open.
- Large binary test oracles live in storytold/photocraft-corpus, not here; `cargo xtask corpus` fetches the pdf.js corpus pinned by commit and SHA-256.
+9 -1
View File
@@ -4,7 +4,7 @@
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
## In this repository (136)
## In this repository (144)
| Asset | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|
@@ -25,6 +25,8 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/braces.svg` | Lucide icon "braces" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/braces.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/camera.svg` | Lucide icon "camera" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/camera.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/check-circle-2.svg` | Lucide icon "check-circle-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check-circle-2.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/chevrons-down.svg` | Lucide icon "chevrons-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-down.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/chevrons-up.svg` | Lucide icon "chevrons-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-up.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | Source of the path data that crates/sign/src/status_layers.rs draws into displayed signature status layers; the UI draws this icon from the built-in catalogue |
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/clock-3.svg` | Lucide icon "clock-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock-3.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
@@ -50,6 +52,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/film.svg` | Lucide icon "film" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/film.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/filter.svg` | Lucide icon "filter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/filter.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/folder-plus.svg` | Lucide icon "folder-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-plus.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/freehand-highlighter.svg` | Freehand highlighter | Combiler01 | CC0-1.0 | https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/git-compare.svg` | Lucide icon "git-compare" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/git-compare.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/hash.svg` | Lucide icon "hash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hash.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/heading.svg` | Lucide icon "heading" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/heading.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
@@ -66,6 +69,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/minimize-2.svg` | Lucide icon "minimize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize-2.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/paperclip.svg` | Lucide icon "paperclip" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paperclip.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/pen-line.svg` | Lucide icon "pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/pin-off.svg` | Lucide icon "pin-off" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin-off.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/presentation.svg` | Lucide icon "presentation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/presentation.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/printer.svg` | Lucide icon "printer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/printer.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
| `assets/icons/replace.svg` | Lucide icon "replace" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/replace.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
@@ -103,6 +107,10 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/app-icon/pdfcraft-1024.png` | PdfCraft app icon, 1024 px on Apple's icon grid | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/pdfcraft.icns` | PdfCraft app icon (macOS .icns) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | macOS app bundle icon |
| `assets/app-icon/pdfcraft.ico` | PdfCraft app icon (Windows .ico, 16-256 px) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab) |
| `assets/app-icon/pdfcraft-nightly-1024.png` | PdfCraft Nightly app icon, 1024 px on Apple's icon grid | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/pdfcraft-nightly.icns` | PdfCraft Nightly app icon (macOS .icns) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh) |
| `assets/app-icon/pdfcraft-nightly.ico` | PdfCraft Nightly app icon (Windows .ico, 16-256 px) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs |
| `assets/app-icon/pdfcraft-nightly.png` | PdfCraft Nightly app icon (256 px PNG) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly |
| `assets/app-icon/pdfcraft-document.svg` | PdfCraft PDF document icon (master vector) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Master artwork for the Windows PDF file type icon; rendered by packaging/icons.sh, without fonts or external images |
| `assets/app-icon/pdfcraft-document.ico` | PdfCraft PDF document icon (Windows .ico, 16-256 px) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Embedded in pdfcraft.exe as resource 2; the Windows installer uses it for PdfCraft.Document and Applications/pdfcraft.exe PDF file associations |
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 16 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
+88
View File
@@ -197,6 +197,28 @@ kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "765ebd1031367e2fd2a940b62f4402fac8976dea0210b0e3b1e59a2c75897928"
[[asset]]
path = "assets/icons/chevrons-down.svg"
title = "Lucide icon \"chevrons-down\""
author = "Lucide Contributors (portions Cole Bemis, Feather)"
source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-down.svg)"
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "f6fb7f1c3d539665c0d4c6ea5c13436ef1eb1a0df8e6c9f0de65fb960cc27083"
[[asset]]
path = "assets/icons/chevrons-up.svg"
title = "Lucide icon \"chevrons-up\""
author = "Lucide Contributors (portions Cole Bemis, Feather)"
source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-up.svg)"
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "36890150a699c3c16fbc28fce1ee2582c0b74c7fe3f4ff30c6917960933051af"
[[asset]]
path = "assets/icons/circle-check.svg"
title = "Lucide icon \"circle-check\""
@@ -472,6 +494,17 @@ kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "76d62eb7796ce6c7e303c437464923de2d1ae19a5c8d010f8b36dfc1d6180890"
[[asset]]
path = "assets/icons/freehand-highlighter.svg"
title = "Freehand highlighter"
author = "Combiler01"
source = "https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg"
licence = "CC0-1.0"
licence_file = "assets/icons/LICENSE-freehand-highlighter.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "6198c9cbdb182132b00ad25e8782ac7c7d237d0736c1d1c1f2f94dd6b8b87132"
[[asset]]
path = "assets/icons/git-compare.svg"
title = "Lucide icon \"git-compare\""
@@ -648,6 +681,17 @@ kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "195939cbf88689334dc3a9d64bd0b3f459ce1de7d71e53620f6b0448b958f9c8"
[[asset]]
path = "assets/icons/pin-off.svg"
title = "Lucide icon \"pin-off\""
author = "Lucide Contributors (portions Cole Bemis, Feather)"
source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin-off.svg)"
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
sha256 = "4c9c29a91905ccc7473f7c62061092abab0c89697f9ab7f7041631a53720d67a"
[[asset]]
path = "assets/icons/presentation.svg"
title = "Lucide icon \"presentation\""
@@ -1605,6 +1649,50 @@ kind = "icon"
usage = "Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab)"
sha256 = "709271d66e07710a3f785ea21b0c85c5228eaf8bebe5058bc0f71f9ef20749eb"
[[asset]]
path = "assets/app-icon/pdfcraft-nightly-1024.png"
title = "PdfCraft Nightly app icon, 1024 px on Apple's icon grid"
author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)"
source = "Contributor-original (see assets/app-icon/nightly-provenance.json)"
licence = "MIT OR Apache-2.0"
licence_file = "assets/app-icon/LICENSE.txt"
kind = "icon"
usage = "Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs)"
sha256 = "7a9ef45c0a3239584f28517740587a8ab029c11bd1462ea708e5875c96e2fe53"
[[asset]]
path = "assets/app-icon/pdfcraft-nightly.icns"
title = "PdfCraft Nightly app icon (macOS .icns)"
author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)"
source = "Contributor-original (see assets/app-icon/nightly-provenance.json)"
licence = "MIT OR Apache-2.0"
licence_file = "assets/app-icon/LICENSE.txt"
kind = "icon"
usage = "macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh)"
sha256 = "51392518f539474c67aa3aa6e119eb814ea9aa221e0841baf90f8ebb1c168e8d"
[[asset]]
path = "assets/app-icon/pdfcraft-nightly.ico"
title = "PdfCraft Nightly app icon (Windows .ico, 16-256 px)"
author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)"
source = "Contributor-original (see assets/app-icon/nightly-provenance.json)"
licence = "MIT OR Apache-2.0"
licence_file = "assets/app-icon/LICENSE.txt"
kind = "icon"
usage = "Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs"
sha256 = "b984192f9417a11a5f7fbfdbaaaf1a1f2a33cb714e7fa2079aa4be01ac2f6c17"
[[asset]]
path = "assets/app-icon/pdfcraft-nightly.png"
title = "PdfCraft Nightly app icon (256 px PNG)"
author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)"
source = "Contributor-original (see assets/app-icon/nightly-provenance.json)"
licence = "MIT OR Apache-2.0"
licence_file = "assets/app-icon/LICENSE.txt"
kind = "icon"
usage = "Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly"
sha256 = "d73ed05f534074cd0cc267fcfcac07b66919331d4331c060521721b77e00b800"
[[asset]]
path = "assets/app-icon/pdfcraft-document.svg"
title = "PdfCraft PDF document icon (master vector)"
Generated
+140 -129
View File
File diff suppressed because it is too large Load Diff
+77 -75
View File
@@ -5,7 +5,7 @@ exclude = ["vendor"]
default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"]
[workspace.package]
version = "0.22.0"
version = "0.23.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -13,92 +13,94 @@ repository = "https://github.com/storytold/pdfcraft"
[workspace.dependencies]
# The framework facade: every framework crate is reached through it (contract head); its features pick the crates.
craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false }
craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
craft-markdown = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Small, revision-bound UI drafts; the existing engine remains the owner of PDF edits/history.
edit-session = { path = "vendor/edit-session", version = "=0.1.0-alpha.2" }
# Shared frontend components; engines remain independent of egui.
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# One menu definition for the native macOS menu bar and the in-window bar elsewhere.
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false }
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Shared system spooler; document composition remains in pdfcraft-print.
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# ICC transforms for app-managed print colour; at craft-print's commit, so one craft-libs checkout.
craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# The installed-font catalog the engine reads faces from (Edit ▸ Add text, font embedding).
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", default-features = false }
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", default-features = false }
# The craft-fonts manifest parser and `EmbeddedFace`, the face table the interface font stack takes; already in the
# tree through craft-ui.
craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-fonts-build = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", features = ["ui"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", features = ["cos", "crypt", "filters", "fonts"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["ui"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", features = ["cos", "crypt", "filters", "fonts"] }
# The writers the Word and RTF exports map onto (storytold/craft-libs#793), at storytold/craft-libs#1467:
# its font and colour lookups take constant time, as PdfCraft's own writer did. craft-rtf, craft-wordmodel and
# craft-docx move together: craft_rtf::doc::export takes its own revision's Document.
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Shared Base64 encoder; use the existing RTF revision to reuse its codepage dependency.
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-mime = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-csv = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-xml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-docx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-pptx = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-opc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Shared MCP stdio framing and JSON-RPC 2.0 envelopes (storytold/craft-libs#778).
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.22.0" }
pdfcraft-filters = { path = "crates/filters", version = "0.22.0" }
pdfcraft-cos = { path = "crates/cos", version = "0.22.0" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.22.0" }
pdfcraft-organize = { path = "crates/organize", version = "0.22.0" }
pdfcraft-measure = { path = "crates/measure", version = "0.22.0" }
pdfcraft-annot = { path = "crates/annot", version = "0.22.0" }
pdfcraft-audit = { path = "crates/audit", version = "0.22.0" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.22.0" }
pdfcraft-model = { path = "crates/model", version = "0.22.0" }
pdfcraft-content = { path = "crates/content", version = "0.22.0" }
pdfcraft-redact = { path = "crates/redact", version = "0.22.0" }
pdfcraft-print = { path = "crates/print", version = "0.22.0" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.22.0" }
pdfcraft-sign = { path = "crates/sign", version = "0.22.0" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.22.0" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.22.0" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.22.0" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.22.0" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.22.0" }
pdfcraft-js = { path = "crates/js", version = "0.22.0" }
pdfcraft-compare = { path = "crates/compare", version = "0.22.0" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.22.0" }
pdfcraft-export = { path = "crates/export", version = "0.22.0" }
pdfcraft-edit = { path = "crates/edit", version = "0.22.0" }
pdfcraft-create = { path = "crates/create", version = "0.22.0" }
pdfcraft-forms = { path = "crates/forms", version = "0.22.0" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.22.0" }
pdfcraft-render = { path = "crates/render", version = "0.22.0" }
pdfcraft-engine = { path = "crates/engine", version = "0.22.0" }
pdfcraft-platform = { path = "crates/platform", version = "0.22.0" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.22.0" }
pdfcraft-automation = { path = "crates/automation", version = "0.22.0", default-features = false }
pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.22.0" }
pdfcraft-geom = { path = "crates/geom", version = "0.23.1" }
pdfcraft-filters = { path = "crates/filters", version = "0.23.1" }
pdfcraft-cos = { path = "crates/cos", version = "0.23.1" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.23.1" }
pdfcraft-organize = { path = "crates/organize", version = "0.23.1" }
pdfcraft-measure = { path = "crates/measure", version = "0.23.1" }
pdfcraft-annot = { path = "crates/annot", version = "0.23.1" }
pdfcraft-audit = { path = "crates/audit", version = "0.23.1" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.23.1" }
pdfcraft-model = { path = "crates/model", version = "0.23.1" }
pdfcraft-content = { path = "crates/content", version = "0.23.1" }
pdfcraft-redact = { path = "crates/redact", version = "0.23.1" }
pdfcraft-print = { path = "crates/print", version = "0.23.1" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.23.1" }
pdfcraft-sign = { path = "crates/sign", version = "0.23.1" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.23.1" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.23.1" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.23.1" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.23.1" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.23.1" }
pdfcraft-js = { path = "crates/js", version = "0.23.1" }
pdfcraft-compare = { path = "crates/compare", version = "0.23.1" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.23.1" }
pdfcraft-export = { path = "crates/export", version = "0.23.1" }
pdfcraft-edit = { path = "crates/edit", version = "0.23.1" }
pdfcraft-create = { path = "crates/create", version = "0.23.1" }
pdfcraft-forms = { path = "crates/forms", version = "0.23.1" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.23.1" }
pdfcraft-render = { path = "crates/render", version = "0.23.1" }
pdfcraft-engine = { path = "crates/engine", version = "0.23.1" }
pdfcraft-platform = { path = "crates/platform", version = "0.23.1" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.23.1" }
pdfcraft-automation = { path = "crates/automation", version = "0.23.1", default-features = false }
pdfcraft-prc = { package = "craft-prc", git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-prc = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.23.1" }
# pdf
hayro = "0.7.1"
@@ -180,14 +182,14 @@ unset_env = ["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "CRAFT_I18N_DIR", "CRAFT
# BEGIN port-kit framework patch
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
@@ -202,7 +204,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
lopdf = { path = "vendor/lopdf" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
+6 -1
View File
@@ -16,7 +16,7 @@ sha256 = "cd7032ea33b71427f188e34ffb4aee9d6868a57fd196037c5c8b2be03a2a0352"
[[document]]
source = "NOTICE"
destination = "NOTICE"
sha256 = "ac29fe01fc951570ebda159bc84b17f12129e3f0800c36759e2f4829c10d8685"
sha256 = "c0cd7347f4c596dc01ac7fdc4aca323b6ba97385eb399bc5dd40e460bacf247d"
[[document]]
source = "vendor/edit-session/LICENSE-MIT"
@@ -55,6 +55,11 @@ source = "assets/fonts/OFL-JetBrainsMono.txt"
destination = "assets/fonts/OFL-JetBrainsMono.txt"
sha256 = "a76abf002c49097d146e86740a3105a5d00450b1592e820a1109a8c5680cd697"
[[document]]
source = "assets/icons/LICENSE-freehand-highlighter.txt"
destination = "assets/icons/LICENSE-freehand-highlighter.txt"
sha256 = "83cba0ac883f6ef4866e457536bf58727a5702ebf6e7b407579e4f1863ca4c7d"
[[document]]
source = "assets/icons/LICENSE-lucide.txt"
destination = "assets/icons/LICENSE-lucide.txt"
+2 -1
View File
@@ -14,11 +14,12 @@ Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
- Lucide icons (assets/icons/*.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt.
- Lucide icons (assets/icons/*.svg, except freehand-highlighter.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt.
The Windows PDF file icon (assets/app-icon/pdfcraft-document.svg and .ico) adapts Lucide's
file-text outline and combines it with contributor-original artwork. See
assets/app-icon/LICENSE-document.txt (ISC AND (MIT OR Apache-2.0)), packaged as
LICENSE-document.txt beside the Windows executables.
- Freehand highlighter icon (assets/icons/freehand-highlighter.svg) — CC0-1.0, Combiler01. See assets/icons/LICENSE-freehand-highlighter.txt.
- Inter typeface (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt.
- JetBrains Mono typeface (assets/fonts/JetBrainsMono-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt.
- Dancing Script typeface (assets/fonts/DancingScript.ttf), Copyright 2016 The Dancing Script Project Authors — SIL Open Font License 1.1 (Reserved Font Name "Dancing Script"). See assets/fonts/OFL-DancingScript.txt.
+1
View File
@@ -76,6 +76,7 @@
PdfCraft is part of [ArtCraft](https://getartcraft.com). Come say hello, get help and follow development:
- **Discord: [discord.gg/artcraft](https://discord.gg/artcraft)**. This is the fastest way to get help and share feedback. The app has a Discord button in its title bar.
- [Collect a Windows startup log](docs/windows-renderer-startup.md#if-the-window-freezes-at-startup) if the app opens a frozen window.
- **Web page:** [getartcraft.com/apps/pdfcraft](https://getartcraft.com/apps/pdfcraft)
- **Source:** [github.com/storytold/pdfcraft](https://github.com/storytold/pdfcraft)
+20 -16
View File
@@ -1,6 +1,6 @@
use super::options::{
COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, flag, needs_value, positional,
validate_options,
COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, needs_value, positional,
validate_options, value_of_flag,
};
use super::{Arc, CliError, ImageFormat, PageRenderer, Path, PathBuf, RenderConfig, RenderRequest, RequestKind, Write, inspect, stdout_line};
@@ -26,7 +26,7 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
validate_options("info", args, INFO_OPTIONS)?;
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
let bytes = read(path)?;
let password = flag(args, "--password");
let password = value_of_flag("info", args, INFO_OPTIONS, "--password")?;
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password);
let mut info = inspect(bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?;
@@ -104,7 +104,7 @@ pub(crate) fn text(args: &[String]) -> Result<(), CliError> {
options.next();
}
}
let password = flag(args, "--password");
let password = value_of_flag("text", args, TEXT_OPTIONS, "--password")?;
let mut bytes = read(path)?;
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
// Worked out from the file as read: `bytes` may become the session's display copy below.
@@ -306,7 +306,7 @@ fn file_stem(path: &str) -> String {
pub(crate) fn combine(args: &[String]) -> Result<(), CliError> {
validate_options("combine", args, COMBINE_OPTIONS)?;
let out = flag(args, "--out").ok_or("combine: missing --out")?;
let out = value_of_flag("combine", args, COMBINE_OPTIONS, "--out")?.ok_or("combine: missing --out")?;
let inputs = positional(args, COMBINE_OPTIONS);
if inputs.len() < 2 {
return Err("combine: give at least two input files".into());
@@ -319,10 +319,10 @@ pub(crate) fn combine(args: &[String]) -> Result<(), CliError> {
pub(crate) fn extract(args: &[String]) -> Result<(), CliError> {
validate_options("extract", args, EXTRACT_OPTIONS)?;
let path = *positional(args, EXTRACT_OPTIONS).first().ok_or("extract: missing file")?;
let out = flag(args, "--out").ok_or("extract: missing --out")?;
let pages = page_list(flag(args, "--pages").ok_or("extract: missing --pages")?)?;
let out = value_of_flag("extract", args, EXTRACT_OPTIONS, "--out")?.ok_or("extract: missing --out")?;
let pages = page_list(value_of_flag("extract", args, EXTRACT_OPTIONS, "--pages")?.ok_or("extract: missing --pages")?)?;
let mut session = pdfcraft_engine::Session::new();
let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;
let id = session.open(path, None, read(path)?, value_of_flag("extract", args, EXTRACT_OPTIONS, "--password")?).map_err(|e| e.to_string())?;
let bytes = session.extract(id, &pages).map_err(|e| e.to_string())?;
write_pdf(Path::new(out), &bytes)
}
@@ -331,7 +331,7 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> {
validate_options("split", args, SPLIT_OPTIONS)?;
use pdfcraft_engine::SplitBy;
let path = *positional(args, SPLIT_OPTIONS).first().ok_or("split: missing file")?;
let by = match (flag(args, "--every"), flag(args, "--before")) {
let by = match (value_of_flag("split", args, SPLIT_OPTIONS, "--every")?, value_of_flag("split", args, SPLIT_OPTIONS, "--before")?) {
(Some(n), None) => {
// A count the splitter cannot hold is refused here, before the file is opened,
// rather than silently clamped to 1 further down.
@@ -345,9 +345,9 @@ pub(crate) fn split(args: &[String]) -> Result<(), CliError> {
(None, Some(list)) => SplitBy::Before(page_list(list)?),
_ => return Err("split: give either --every N or --before PAGES".into()),
};
let dir = PathBuf::from(flag(args, "--out-dir").unwrap_or("."));
let dir = PathBuf::from(value_of_flag("split", args, SPLIT_OPTIONS, "--out-dir")?.unwrap_or("."));
let mut session = pdfcraft_engine::Session::new();
let id = session.open(path, None, read(path)?, flag(args, "--password")).map_err(|e| e.to_string())?;
let id = session.open(path, None, read(path)?, value_of_flag("split", args, SPLIT_OPTIONS, "--password")?).map_err(|e| e.to_string())?;
let stem = file_stem(path);
let parts = session.split(id, &by).map_err(|e| e.to_string())?;
// An output folder that does not exist yet is created (#249); one that can't be is reported
@@ -376,11 +376,15 @@ pub(crate) fn parse_dpi(value: &str) -> Result<f32, String> {
pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
validate_options("render", args, RENDER_OPTIONS)?;
let path = *positional(args, RENDER_OPTIONS).first().ok_or("render: missing file")?;
let page: usize =
flag(args, "--page").unwrap_or("1").parse().ok().filter(|page| *page > 0).ok_or("bad --page: expected a positive page number")?;
let page: usize = value_of_flag("render", args, RENDER_OPTIONS, "--page")?
.unwrap_or("1")
.parse()
.ok()
.filter(|page| *page > 0)
.ok_or("bad --page: expected a positive page number")?;
let page_index = page - 1;
let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("96"))?;
let out = flag(args, "--out").ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?;
let dpi = parse_dpi(value_of_flag("render", args, RENDER_OPTIONS, "--dpi")?.unwrap_or("96"))?;
let out = value_of_flag("render", args, RENDER_OPTIONS, "--out")?.ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?;
// The file is what its name says (#248): a `.png` used to get a netpbm PAM stream.
let format = match Path::new(out).extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).as_deref() {
Some("png") => Some(ImageFormat::Png),
@@ -393,7 +397,7 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
// of named-layer signatures (here with no trusted certificates); the CLI must agree with it
// (and with independent viewers), while keeping the file it reads intact.
let bytes = read(path)?;
let password = flag(args, "--password");
let password = value_of_flag("render", args, RENDER_OPTIONS, "--password")?;
// The renderer takes only the user password of R2–R4 files; `Session::open` and the display
// copy take either.
let render_password = pdfcraft_engine::render_password_for(bytes.clone(), password);
+51
View File
@@ -4,6 +4,29 @@ pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The operand of the last `name` in `args`, read the way `validate_options` and `positional` walk
/// them: a token that is another option's operand is never taken for an option. [`flag`] matches
/// any token, so in `--password --out input.pdf --out out.pdf` (a password of `--out`) it answered
/// `input.pdf` for `--out` and the command wrote over its own source file (#7516). `Err` when
/// `name` is the last token and so has no operand.
pub(crate) fn value_of_flag<'a>(command: &str, args: &'a [String], specs: &[OptionSpec], name: &str) -> Result<Option<&'a str>, CliError> {
let mut i = 0;
let mut result = None;
while let Some(a) = args.get(i) {
if a == name {
let value = args.get(i + 1).map(String::as_str).ok_or_else(|| needs_value(command, name, None))?;
result = Some(value);
i += 2;
continue;
}
match specs.iter().find(|spec| spec.name == a.as_str()) {
Some(spec) if spec.takes_value => i += 2,
_ => i += 1,
}
}
Ok(result)
}
#[derive(Clone, Copy)]
pub(crate) struct OptionSpec {
pub(crate) name: &'static str,
@@ -151,3 +174,31 @@ pub(crate) fn positional<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn args(tokens: &[&str]) -> Vec<String> {
tokens.iter().map(|token| (*token).to_string()).collect()
}
/// #7516: a password that reads like an option is still a password, not that option.
#[test]
fn value_of_flag_skips_password_operand() {
let line = args(&["--password", "--out", "input.pdf", "--out", "out.pdf"]);
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--out").unwrap(), Some("out.pdf"));
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--password").unwrap(), Some("--out"));
// The old lookup, for contrast: it is why the call sites moved.
assert_eq!(flag(&line, "--out"), Some("input.pdf"));
}
#[test]
fn value_of_flag_reports_absent_and_dangling_options() {
let line = args(&["in.pdf", "--password", "--pages"]);
assert_eq!(value_of_flag("extract", &line, EXTRACT_OPTIONS, "--pages").unwrap(), None);
let dangling = args(&["in.pdf", "--pages"]);
let error = value_of_flag("extract", &dangling, EXTRACT_OPTIONS, "--pages").unwrap_err();
assert_eq!(error.to_string(), "extract: --pages needs a value");
}
}
+1
View File
@@ -12,6 +12,7 @@ mod help;
mod info_repairs;
mod info_standards;
mod mcp_compact;
mod option_operands;
mod options;
mod owner_password;
mod render;
@@ -0,0 +1,167 @@
//! A value-taking option's operand is never read as another option (#7516). A password can be any
//! string, `--out` included, and the commands used to look options up by scanning every token:
//! in `extract --password --out in.pdf --pages 1 --out out.pdf` the password's operand was taken
//! for the real `--out`, its neighbour `in.pdf` for the output, and the source file was replaced.
use std::path::PathBuf;
use std::process::Command;
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
/// A PDF with `n` empty 200×300 pt pages.
fn fixture(n: usize) -> Vec<u8> {
let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];
let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 3 + i)).collect();
objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")).into_bytes());
for _ in 0..n {
objs.push(b"<< /Type /Page /Parent 2 0 R >>".to_vec());
}
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
/// A fresh directory holding `in.pdf` (3 pages), and that file's path as the command line takes it.
fn workdir(test: &str) -> (PathBuf, String) {
let d = std::env::temp_dir().join(format!("pdfcraft-cli-operands-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let input = d.join("in.pdf");
std::fs::write(&input, fixture(3)).unwrap();
let name = input.to_str().unwrap().to_string();
(d, name)
}
/// The page count and first page size `info` reports for a PDF the CLI wrote.
fn pages_of(path: &std::path::Path) -> (u64, serde_json::Value) {
let run = Command::new(BIN).args(["info", path.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "info {}: {}", path.display(), String::from_utf8_lossy(&run.stderr));
let info: serde_json::Value = serde_json::from_slice(&run.stdout).unwrap();
(info["pages"].as_u64().unwrap(), info["first_page_pt"].clone())
}
/// The names in `dir`, sorted, so a test sees a stray staging file or a missing part.
fn listing(dir: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
// Ordinary command lines through the shared atomic writer (`craft::atomic`): the lookup still
// finds each command's real options, writes what they ask for, and leaves the source alone.
#[test]
fn ordinary_extract_writes_the_chosen_pages_and_keeps_its_source() {
let (dir, input) = workdir("plain-extract");
let out = dir.join("out.pdf");
let run = Command::new(BIN).args(["extract", &input, "--pages", "2-3", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(pages_of(&out), (2, serde_json::json!([200.0, 300.0])));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "out.pdf"], "only the output was written");
}
#[test]
fn ordinary_split_writes_one_part_per_page_and_keeps_its_source() {
let (dir, input) = workdir("plain-split");
let parts = dir.join("parts");
let run = Command::new(BIN).args(["split", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(listing(&parts), ["in-p1.pdf", "in-p2.pdf", "in-p3.pdf"]);
for n in 1..=3 {
assert_eq!(pages_of(&parts.join(format!("in-p{n}.pdf"))).0, 1, "part {n}");
}
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "parts"]);
}
#[test]
fn ordinary_render_writes_the_chosen_page_at_the_chosen_dpi_and_keeps_its_source() {
let (dir, input) = workdir("plain-render");
let png = dir.join("page.png");
let run = Command::new(BIN).args(["render", &input, "--page", "2", "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
let image = craft_image_codecs::decode(&std::fs::read(&png).unwrap()).unwrap();
// 200×300 pt at 36 dpi.
assert_eq!((image.width(), image.height()), (100, 150));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
assert_eq!(listing(&dir), ["in.pdf", "page.png"], "only the image was written");
}
#[test]
fn extract_does_not_write_over_its_source_when_the_password_is_out() {
let (dir, input) = workdir("extract");
let out = dir.join("out.pdf");
let run = Command::new(BIN).args(["extract", "--password", "--out", &input, "--pages", "1", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced");
assert!(out.is_file(), "the page went to the real --out");
}
#[test]
fn extract_reads_the_real_pages_when_the_password_is_pages() {
let (dir, input) = workdir("extract-pages");
let out = dir.join("out.pdf");
// `--password --pages` then the file: the old lookup read the file's name as the page list.
let run = Command::new(BIN).args(["extract", "--password", "--pages", &input, "--pages", "2", "--out", out.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert_eq!(pages_of(&out).0, 1, "the real --pages chose one page");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
}
#[test]
fn split_writes_to_the_real_out_dir_when_the_password_is_out_dir() {
let (dir, input) = workdir("split");
let parts = dir.join("parts");
let run =
Command::new(BIN).args(["split", "--password", "--out-dir", &input, "--every", "1", "--out-dir", parts.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
for n in 1..=3 {
assert!(parts.join(format!("in-p{n}.pdf")).is_file(), "part {n} missing");
}
assert_eq!(std::fs::read(&input).unwrap(), fixture(3));
}
#[test]
fn render_writes_to_the_real_out_when_the_password_is_out() {
let (dir, input) = workdir("render");
let png = dir.join("page.png");
let run = Command::new(BIN).args(["render", "--password", "--out", &input, "--dpi", "36", "--out", png.to_str().unwrap()]).output().unwrap();
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG"), "the image went to the real --out");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file was replaced");
}
/// An option left without its operand at the end of the line is named, instead of being read as
/// absent: `render in.pdf --out page.png --page` used to render page 1 and exit 0.
#[test]
fn an_option_with_no_operand_is_named() {
let (dir, input) = workdir("dangling");
let png = dir.join("page.png");
for args in [
vec!["render", &input, "--out", png.to_str().unwrap(), "--page"],
vec!["render", &input, "--out", png.to_str().unwrap(), "--dpi"],
vec!["split", &input, "--every", "1", "--password"],
] {
let option = *args.last().unwrap();
let run = Command::new(BIN).current_dir(&dir).args(&args).output().unwrap();
let stderr = String::from_utf8_lossy(&run.stderr);
assert!(!run.status.success(), "{args:?} unexpectedly succeeded");
assert!(stderr.contains(&format!("{option} needs a value")), "{args:?}: {stderr}");
}
assert!(!png.exists(), "nothing was rendered");
assert_eq!(listing(&dir), ["in.pdf"], "a refused command left a file behind");
assert_eq!(std::fs::read(&input).unwrap(), fixture(3), "the source file changed");
}
+2 -2
View File
@@ -15,8 +15,8 @@ pdfcraft-ui-egui = { workspace = true }
craft = { workspace = true, features = ["automation", "platform-browser", "ui", "window"] }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0" }
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
serde_json = { workspace = true }
+5 -1
View File
@@ -15,6 +15,8 @@ pdfcraft-ui-egui = { workspace = true }
# The framework, through its facade (contract head): host, platform, automation, pages and quit,
# and the UI runtime and window policy the window is installed with.
craft = { workspace = true, features = ["platform", "automation", "pages", "quit", "ui", "window"] }
# Shared nightly-v1 profile isolation, launch protocol, and security fence.
craft-nightly = { workspace = true }
# `build_info`: the version and compile-time build label for `--version` and the log.
pdfcraft-engine = { workspace = true }
# `crypto_env`: the cryptography environment the engine opens files with.
@@ -26,6 +28,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"
serde_json = { workspace = true }
# Records from every crate go to standard error and the log file (`craft_platform::logs`).
log = { workspace = true }
# Native error dialog when a Nightly profile cannot be prepared.
rfd = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
# Finder double-click / Open With / Dock drops arrive as Apple events (#73); this small audited
@@ -58,7 +62,7 @@ winit = { version = "0.30", default-features = false, features = ["wayland"] }
# Which GPU drives which display (EnumDisplayDevices), so the window is drawn on the GPU that
# shows it (issue #378). Safe wrappers over Win32; only the `user` feature (which brings `kernel` with it),
# and `advapi` for the session id that names the single-instance socket (#3338).
winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi"] }
winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi", "shell"] }
# Single instance (#282): later launches hand their files to the running app over a Unix domain
# socket. `std` has no Unix sockets on Windows, and calling Winsock directly needs unsafe, which
# our workspace forbids. Already in the lockfile through zbus; pinned exactly, review before bumping.
+49 -7
View File
@@ -2,10 +2,16 @@
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab. A separate PDF document icon
//! uses resource ID 2; the installer references it as `pdfcraft.exe,-2`.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
//! The build channel comes from `PDFCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build
//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused
//! rather than silently producing a stable binary with a nightly name.
//!
//! On every other target the Windows resource step does nothing. A missing resource compiler is a
//! warning, so a cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1`
//! turns it into an error (for release builds).
#[path = "src/build_channel.rs"]
mod build_channel;
#[path = "src/windows_manifest.rs"]
mod windows_manifest;
@@ -18,10 +24,41 @@ const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"];
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=src/build_channel.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-nightly.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-document.ico");
println!("cargo:rerun-if-changed=src/windows_manifest.rs");
println!("cargo:rerun-if-env-changed=PDFCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_SHA");
println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=PDFCRAFT_VERSION");
println!("cargo:rustc-check-cfg=cfg(pdfcraft_nightly_v1)");
let nightly = match std::env::var("PDFCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=pdfcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported PDFCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
let built_version = if nightly {
match std::env::var("PDFCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit PDFCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=PDFCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
@@ -32,14 +69,19 @@ fn main() {
println!("cargo:rustc-link-arg-bins=delayimp.lib");
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/pdfcraft.ico")
.set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2")
res.set_icon(build_channel::windows_icon_path(nightly))
.set_manifest(windows_manifest::WINDOWS_MANIFEST)
.set("ProductName", "PdfCraft")
.set("FileDescription", "PdfCraft PDF workbench")
.set("ProductName", if nightly { "PdfCraft Nightly" } else { "PdfCraft" })
.set("FileDescription", if nightly { "PdfCraft Nightly PDF workbench" } else { "PdfCraft PDF workbench" })
.set("LegalCopyright", "Copyright (c) the PdfCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "pdfcraft.exe")
.set("InternalName", "pdfcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
} else {
res.set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2");
}
if let Err(e) = res.compile() {
if std::env::var_os("PDFCRAFT_REQUIRE_WINRES").is_some() {
println!("cargo::error=embedding Windows resources failed: {e}");
-1
View File
@@ -33,7 +33,6 @@ impl AppleEvents {
/// The inbox belongs to the main thread (it is not `Send`, and drains inside its own wake
/// would borrow it twice), so the returned function does the forwarding: the frame calls it
/// once per frame on the main thread.
// PLAN: pdf-hub-w1 calls the returned function once per frame (it replaces the `OsEventsFn` poll).
pub fn connect(&self, sender: IntakeSender, ctx: &egui::Context) -> Box<dyn Fn()> {
let wake = ctx.clone();
self.inbox.set_wake(move || wake.request_repaint());
+57
View File
@@ -0,0 +1,57 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/pdfcraft-nightly.ico" } else { "../../assets/app-icon/pdfcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::{is_nightly_version, windows_icon_path};
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/pdfcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/pdfcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.22.0-nightly.20261129.17.1.gabcdef012345"));
for invalid in [
"",
"0.22.0",
"0.22.0-nightly",
"0.22.0-nightly.20261129",
"0.22.0-nightly.20261129.17.1.gABCDEF012345",
"0.22.0-nightly.20261129.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.22.0-nightly.20261129.1.1.gabcdef012345",
"0.22.0-nightly.20261129.1.1.gabcdef012345/other",
"0.22.0-nightly.20261129.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(pdfcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
/// The packaging/version probe must work even when no profile location can be resolved.
pub fn version_query(args: &[std::ffi::OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
#[cfg_attr(not(test), allow(dead_code))]
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version};
#[test]
fn plain_version_queries_are_unambiguous() {
assert!(super::version_query(&["--version".into()]));
assert!(super::version_query(&["-V".into()]));
assert!(!super::version_query(&["--".into(), "--version".into()]));
assert!(!super::version_query(&["--version".into(), "example".into()]));
}
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_version_format_distinguishes_channel() {
assert_eq!(version(BuildFlavor::Stable, "0.22.0"), "0.22.0");
assert_eq!(version(BuildFlavor::NightlyV1, "0.22.0"), "0.22.0 (nightly-v1)");
}
}
+197
View File
@@ -0,0 +1,197 @@
//! Nightly-v1 bootstrap backed by `craft_nightly`. Selected before logging, updates, fonts or
//! saved state. Stable launches retain their original arguments and directory policy.
use std::ffi::OsString;
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
use crate::profile_root;
/// Returns the active process profile, defaulting to [`Profile::Stable`] before initialization.
pub fn current() -> &'static Profile {
craft_nightly::current().unwrap_or(&Profile::Stable)
}
/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root for
/// nightly builds (self-isolating into [`craft_nightly::canonical_profile_root`] on direct
/// launch), and installs the process-wide profile.
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
let spec = profile_root::spec();
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new())
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::path::PathBuf;
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
use craft_nightly::launch_arguments;
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use crate::profile_root;
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
struct TempProfileDir(PathBuf);
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
impl TempProfileDir {
fn new(label: &str) -> Self {
#[cfg(unix)]
let base = std::fs::canonicalize(std::path::Path::new("/tmp")).unwrap_or_else(|_| PathBuf::from("/tmp"));
#[cfg(windows)]
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
let dir = base.join(format!("pc-{label}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
impl Drop for TempProfileDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\pdfcraft" } else { "/nightly-data/profiles/pdfcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = profile_root::spec();
for argv in [args(&[]), args(&["--new-window", "a.pdf"]), args(&["--", "--launch-profile", "file.pdf"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
assert!(launch.leading_flags.is_empty());
assert!(!launch.has_launcher_separator());
}
}
#[test]
fn stable_build_refuses_nightly_launch_flags() {
let spec = profile_root::spec();
let err = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = profile_root::spec();
let expected_root = canonical_profile_root("pdfcraft").unwrap();
for argv in [args(&[]), args(&["document.pdf"]), args(&["--two-paged", "document.pdf"])] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root.clone()));
assert_eq!(launch.passthrough_args, argv);
}
}
#[test]
fn explicit_launcher_arguments_override_root_and_preserve_file_names() {
let spec = profile_root::spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "document with spaces.pdf"]));
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.passthrough_args, args(&["--profile-root", "document with spaces.pdf"]));
}
#[test]
fn malformed_nightly_launch_flags_are_refused() {
let spec = profile_root::spec();
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
}
}
#[test]
fn nightly_version_queries_are_recognized_for_direct_and_launcher_invocations() {
let spec = profile_root::spec();
for argv in [
args(&["--version"]),
args(&["-V"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "-V"]),
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "--version"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--version"]),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
for argv in [args(&[]), args(&["--help"]), args(&["--version", "--version"])] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(!launch.is_version_query(), "{argv:?}");
}
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_nightly_profile_accepts_existing_single_instance_socket() {
use std::os::unix::net::UnixListener;
let tmp = TempProfileDir::new("si");
let profile = tmp.0.join("p");
let single_instance = profile.join("single-instance");
std::fs::create_dir_all(&single_instance).unwrap();
let expected_root = std::fs::canonicalize(&profile).unwrap();
let sock_path = single_instance.join("instance.sock");
let listener = UnixListener::bind(&sock_path).unwrap();
// Live listener socket already present inside <profile>/single-instance/.
let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone()));
assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"]));
// Leftover/stale socket remaining after the previous instance exits.
drop(listener);
assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk");
let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"]));
}
#[cfg(windows)]
#[test]
fn windows_nightly_profile_accepts_existing_single_instance_socket() {
let tmp = TempProfileDir::new("si");
let profile = tmp.0.join("p");
let single_instance = profile.join("single-instance");
std::fs::create_dir_all(&single_instance).unwrap();
let expected_root = std::fs::canonicalize(&profile).unwrap();
let sock_path = single_instance.join("instance-s1.sock");
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
// Live AF_UNIX listener socket already present inside <profile>\single-instance\.
let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap();
assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone()));
assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"]));
// Leftover/stale socket remaining after the previous instance exits.
drop(listener);
assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk");
let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap();
assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"]));
}
}
+274 -35
View File
@@ -40,16 +40,26 @@ use pdfcraft_ui_egui::PdfCraftApp;
#[cfg(target_os = "macos")]
mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod compositor_gpu;
mod launch_profile;
mod nightly_session;
mod process_identity;
mod profile_root;
mod reopen;
mod single_instance;
mod startup;
#[cfg(target_os = "windows")]
mod window_placement;
#[cfg(test)]
#[path = "windows_manifest.rs"]
mod windows_manifest;
/// Freedesktop app id: the `.desktop` file name and the hicolor icon name.
const APP_ID: &str = "ai.storyteller.pdfcraft";
const NIGHTLY_APP_ID: &str = "ai.storyteller.pdfcraft.nightly";
/// The app icon (assets/app-icon/README.md). macOS gets the version on Apple's icon grid, with a
/// transparent margin; Windows and Linux get the full-bleed tile.
@@ -58,6 +68,91 @@ const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-10
#[cfg(not(target_os = "macos"))]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png");
#[cfg(target_os = "macos")]
const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly-1024.png");
#[cfg(not(target_os = "macos"))]
const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly.png");
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
}
fn app_id() -> &'static str {
if is_nightly() { NIGHTLY_APP_ID } else { APP_ID }
}
fn app_title() -> &'static str {
if is_nightly() { "PdfCraft Nightly" } else { "PdfCraft" }
}
fn app_icon_png() -> &'static [u8] {
if is_nightly() { NIGHTLY_APP_ICON_PNG } else { APP_ICON_PNG }
}
fn built_version() -> &'static str {
env!("PDFCRAFT_BUILT_VERSION")
}
fn nightly_version_line() -> String {
format!("PdfCraft {} (nightly-v1)", built_version())
}
fn initialize_nightly_process_identity() -> Result<(), String> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, NIGHTLY_APP_ID)
}
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
fn report_launch_profile_error(error: &str) {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {error}\n"));
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(err) = initialize_nightly_process_identity() {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {err}\n"));
return;
}
let _ = rfd::MessageDialog::new()
.set_title("PdfCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer
/// the version query before any of that: `None` means the query has been answered.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
let _ = std::io::Write::write_fmt(&mut std::io::stdout().lock(), format_args!("{}\n", nightly_version_line()));
return None;
}
let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
let _ = std::io::Write::write_fmt(&mut std::io::stdout().lock(), format_args!("{}\n", nightly_version_line()));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error);
std::process::exit(2);
}
if let Some(root) = early.profile.root()
&& let Err(error) = pdfcraft_ui_egui::settings::install_nightly_profile_root(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.passthrough_args)
}
/// What `-h` / `--help` prints (#4076): a hint, not the full option list (that is this file's
/// doc comment and the README). Scripts want `pdfcraft-cli`, which never opens a window.
const USAGE: &str = "\
@@ -104,7 +199,7 @@ fn portable() -> bool {
/// folder is left alone when the new one already exists or the move fails. A portable copy leaves
/// the per-user folders alone.
fn migrate_legacy_folders() {
if portable() {
if is_nightly() || portable() {
return;
}
let mut moves = vec![(eframe::storage_dir("PrintCraft"), eframe::storage_dir("PdfCraft"))];
@@ -165,9 +260,12 @@ fn main() -> eframe::Result {
}
// aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`).
pdfcraft_engine::sign::init_crypto();
let Some(raw_args) = prepare_launch() else { return Ok(()) };
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !is_nightly()
&& let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &raw_args)
{
std::process::exit(i32::from(result.is_err()));
}
// First, so the panic hook and every start-up warning are recorded.
@@ -193,7 +291,7 @@ fn main() -> eframe::Result {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {report}\n"));
}
}));
let mut startup = startup::Arguments::parse(std::env::args().skip(1));
let mut startup = startup::Arguments::parse_for_profile(raw_args.into_iter().map(|a| a.to_string_lossy().into_owned()), is_nightly());
if startup.version {
return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version()));
}
@@ -204,18 +302,29 @@ fn main() -> eframe::Result {
let may_hand_off = startup.may_hand_off();
let startup::Arguments { files, options, control_port, control_token, control_token_file, create_images, combine, two_paged, .. } = startup;
// A bad control configuration stops the launch before any window opens.
let control = match control_options(control_port, control_token, control_token_file) {
Ok(control) => control,
Err(message) => usage_error(&message),
// Nightly disables the control server so inherited stable env vars cannot open one.
let control = if is_nightly() {
None
} else {
match control_options(control_port, control_token, control_token_file) {
Ok(control) => control,
Err(message) => usage_error(&message),
}
};
migrate_legacy_folders();
// The log file stays in the data folder; opened after the arguments (so `--version` leaves
// no file behind) and after the PrintCraft migration (which a fresh folder would block).
// Records logged until now are written to it first.
let data_dir = if portable() { settings_dir() } else { eframe::storage_dir("PdfCraft") };
let data_dir = if let Some(root) = launch_profile::current().root() {
Some(root.to_path_buf())
} else if portable() {
settings_dir()
} else {
eframe::storage_dir("PdfCraft")
};
if let (Some(logger), Some(dir)) = (logger, data_dir) {
match logger.attach_dir(&dir.join("logs")) {
Ok(path) => log::info!("PdfCraft {}, log file {}", pdfcraft_engine::build_info::version(), path.display()),
Ok(path) => log::info!("{} {}, log file {}", app_title(), built_version(), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
}
@@ -226,16 +335,36 @@ fn main() -> eframe::Result {
// window.
// Absolute for this instance too: links relative to a document resolve against its folder,
// never the working directory.
let startup_time = std::time::Instant::now();
startup_stage(startup_time, "claiming application instance");
let files = single_instance::absolute(&files);
let instance = match single_instance::claim(&files, may_hand_off, combine) {
let instance = match single_instance::claim(&files, may_hand_off, combine, launch_profile::current().root()) {
single_instance::Claim::HandedOff => return Ok(()),
single_instance::Claim::Primary(server) => Some(server),
single_instance::Claim::Alone => None,
};
let (nightly_watch, previous_unclean) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("PDFCRAFT_BUILD_SHA")) {
Ok((watch, unavailable)) => {
if unavailable {
log::warn!("another PdfCraft Nightly holds this profile's session lease; this window keeps no health record");
}
let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
(std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean)
}
Err(error) => {
log::warn!("Nightly session state: {error}");
(std::sync::Arc::new(std::sync::Mutex::new(None)), false)
}
};
if previous_unclean {
log::warn!("the previous PdfCraft Nightly ended without finishing its session record");
}
// Who draws the window frame: the platform and Preferences ▸ Use system title bar decide,
// unless `PDFCRAFT_TITLEBAR` overrides them. The store is read here and opened again by the
// app (each window attempt opens its own: the OpenGL retry runs the creator again).
// The interface language is read the same way, for the fonts the runtime installs with.
startup_stage(startup_time, "reading startup preferences");
let (title_bar, saved_lang) = {
let settings = pdfcraft_ui_egui::settings::open();
let saved = settings.get();
@@ -247,7 +376,8 @@ fn main() -> eframe::Result {
let frame = craft::window::policy::decide_for(craft::window::Prefix::new("PDFCRAFT"), craft::window::policy::Backend::from_env(), title_bar);
let lang = startup_lang(saved_lang.as_deref(), &options);
let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref());
let launch = Launch { files, options, control, create_images, combine, frame, lang, two_paged };
let launch =
Launch { startup_time, files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch: nightly_watch.clone() };
// Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one
// that launched us as well as later ones. Lives until the event loop returns.
#[cfg(target_os = "macos")]
@@ -255,8 +385,9 @@ fn main() -> eframe::Result {
// Set once the app is created, which is after the renderer has started.
let started = Rc::new(Cell::new(false));
let first = if choice == RendererChoice::Gl { eframe::Renderer::Glow } else { eframe::Renderer::Wgpu };
startup_stage(startup_time, if choice == RendererChoice::Gl { "initializing OpenGL" } else { "initializing wgpu" });
let result = eframe::run_native(
"PdfCraft",
app_title(),
native_options(launch.integrated(), first),
app_creator(
launch.clone(),
@@ -266,19 +397,20 @@ fn main() -> eframe::Result {
&apple_events,
),
);
match result {
let final_result = match result {
// Only a renderer that couldn't start: without a window or display at all, OpenGL can't
// help either, and winit's own error says more.
Err(e @ eframe::Error::Wgpu(_)) if retry_with_gl(choice, started.get()) => {
// Old or unusual GPUs and drivers (#461, #435, #392) can't give wgpu a device; OpenGL
// usually still works there, so that's better than quitting.
log::error!("the GPU renderer (wgpu) didn't start: {e}. Starting with OpenGL instead; set PDFCRAFT_RENDERER=gl to skip wgpu.");
startup_stage(startup_time, "retrying with OpenGL");
eframe::run_native(
"PdfCraft",
app_title(),
native_options(launch.integrated(), eframe::Renderer::Glow),
app_creator(
launch,
started,
Rc::clone(&started),
instance.as_ref(),
#[cfg(target_os = "macos")]
&apple_events,
@@ -286,7 +418,13 @@ fn main() -> eframe::Result {
)
}
other => other,
}
};
nightly_session::finish_once(&nightly_watch, started.get());
final_result
}
fn startup_stage(start: std::time::Instant, stage: &str) {
log::info!(target: "pdfcraft::startup", "+{} ms: {stage}", start.elapsed().as_millis());
}
/// Which renderer to start with, from `PDFCRAFT_RENDERER`.
@@ -358,12 +496,12 @@ fn retry_with_gl(choice: RendererChoice, app_started: bool) -> bool {
/// The window and renderer settings for one run.
fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::NativeOptions {
let mut viewport = egui::ViewportBuilder::default()
.with_title("PdfCraft")
.with_title(app_title())
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(pdfcraft_ui_egui::MIN_WINDOW_SIZE)
.with_drag_and_drop(true)
// Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop.
.with_app_id(APP_ID);
// Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop (or .nightly).
.with_app_id(app_id());
// eframe replaces ICON_BIG with a system-sized icon on its first active frame.
// An explicitly empty icon disables that setter (None selects eframe's default).
// Windows installs both sizes directly through winit in app_creator instead.
@@ -373,7 +511,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ
}
// Dock, taskbar, Alt-Tab and launcher icon when running unbundled.
#[cfg(not(target_os = "windows"))]
match eframe::icon_data::from_png_bytes(APP_ICON_PNG) {
match eframe::icon_data::from_png_bytes(app_icon_png()) {
Ok(icon) => viewport = viewport.with_icon(icon),
Err(e) => log::warn!("app icon: {e}"),
}
@@ -401,6 +539,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ
/// What the command line asked for, kept so a second run (with OpenGL) can start the same way.
#[derive(Clone)]
struct Launch {
startup_time: std::time::Instant,
files: Vec<String>,
options: Vec<(String, String)>,
/// The control server's port and token, when `--control` asked for one.
@@ -413,6 +552,7 @@ struct Launch {
/// The language the interface starts in, whose fonts are installed with the runtime.
lang: pdfcraft_ui_egui::i18n::Lang,
two_paged: bool,
nightly_watch: nightly_session::Shared,
}
impl Launch {
@@ -444,7 +584,7 @@ fn install_runtime(
let system = craft::ui::runtime::env::SystemReader::start(move || ctx.request_repaint());
let spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), std::sync::Arc::new(SystemWindows))
.system(system)
.app_id(APP_ID)
.app_id(app_id())
.frame(frame);
craft::ui::shell::embed::install(&cc.egui_ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(lang))
.map(drop)
@@ -483,7 +623,7 @@ fn install_taskbar_icon(png: &[u8], set: impl FnOnce(winit::window::Icon)) {
#[cfg(target_os = "windows")]
fn set_taskbar_icon(window: &winit::window::Window) {
use winit::platform::windows::{IconExtWindows as _, WindowExtWindows as _};
install_taskbar_icon(APP_ICON_PNG, |icon| window.set_taskbar_icon(Some(icon)));
install_taskbar_icon(app_icon_png(), |icon| window.set_taskbar_icon(Some(icon)));
// The title bar's icon: the small image drawn for this scale in the exe's own icon (build.rs).
let side = (16.0 * window.scale_factor()).round().clamp(16.0, 256.0) as u32;
match winit::window::Icon::from_resource(1, Some(winit::dpi::PhysicalSize::new(side, side))) {
@@ -499,9 +639,10 @@ fn app_creator<'a>(
instance: Option<&'a single_instance::Server>,
#[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents,
) -> eframe::AppCreator<'a> {
let Launch { files, options, control, create_images, combine, frame, lang, two_paged } = launch;
let Launch { startup_time, files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch } = launch;
Box::new(move |cc| {
started.set(true);
startup_stage(startup_time, "renderer ready, installing fonts and runtime");
install_runtime(cc, frame, lang)?;
let ctx = cc.egui_ctx.clone();
let wake = craft::host::Wake::new(move || ctx.request_repaint());
@@ -511,22 +652,39 @@ fn app_creator<'a>(
Some(server) => server.connect(&cc.egui_ctx),
None => craft::platform::open::FileIntake::new(wake).0,
};
// Finder, Open With and the Dock deliver files as Apple events, not arguments.
// Finder, Open With and the Dock deliver files as Apple events, not arguments; each frame
// drains them into the intake.
#[cfg(target_os = "macos")]
apple_events.connect(intake.sender(), &cc.egui_ctx);
let apple_events_poll = apple_events.connect(intake.sender(), &cc.egui_ctx);
startup_stage(startup_time, "initializing application and recovery");
let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake);
#[cfg(target_os = "linux")]
if let Some(window) = cc.winit_window() {
use raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle};
if window.display_handle().is_ok_and(|h| matches!(h.as_raw(), RawDisplayHandle::Wayland(_))) {
app.use_wayland_clipboard(&cc.egui_ctx);
}
}
let exit_watch = nightly_watch.clone();
app.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, true)));
#[cfg(target_os = "macos")]
{
app.os_events = Some(apple_events_poll);
}
// First start (or settings from before Units existed): the region's unit.
app.units = pdfcraft_ui_egui::units::Unit::system();
// The system's reopen-windows choice (macOS) starts the preference; a saved choice replaces it.
app.reopen_last_session = reopen::system_default();
startup_stage(startup_time, "applying preferences");
let settings = pdfcraft_ui_egui::settings::open();
app.apply_settings(settings.get());
app.attach_settings(settings);
#[cfg(target_os = "windows")]
if let Some(window) = cc.winit_window() {
window_placement::restore(window);
set_taskbar_icon(window);
}
app.set_startup_update_check(true);
app.set_startup_update_check(!is_nightly());
app.printer_source = Some(pdfcraft_ui_egui::system_printers());
app.two_sided_source = Some(pdfcraft_ui_egui::system_two_sided());
app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows"));
@@ -564,6 +722,7 @@ fn app_creator<'a>(
if let Some(warning) = &pdfcraft_ui_egui::settings::resolution().warning {
app.notify(warning.clone());
}
startup_stage(startup_time, "restoring session and opening requested documents");
let defer_layout = two_paged && !files.is_empty() && !create_images;
if create_images {
if let Err(e) = app.begin_image_import_paths(&cc.egui_ctx, &files) {
@@ -584,6 +743,8 @@ fn app_creator<'a>(
log::warn!("--{k} {v}: {e}");
}
}
startup_stage(startup_time, "entering UI event loop");
app.startup_time = Some(startup_time);
Ok(Box::new(app))
})
}
@@ -644,21 +805,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) {
descriptor.required_limits = surface_texture_limits(descriptor.required_limits, &adapter.limits());
descriptor
});
if std::env::var_os("WGPU_POWER_PREF").is_none() {
let power_chosen = std::env::var_os("WGPU_POWER_PREF").is_some();
let explicit_renderer = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()) == RendererChoice::Wgpu;
if !power_chosen {
setup.power_preference = eframe::wgpu::PowerPreference::LowPower;
let displays = display_gpus();
let compositor = compositor_gpu::compositor_gpu();
if !displays.is_empty() || compositor.is_some() {
// Always on Windows, so that an OpenGL-only GPU is declined (`wgpu_draws_with`) even when
// no display names its GPU, as over Remote Desktop; `pick_adapter` then ranks by kind,
// most frugal first, as wgpu's own low-power choice does.
if !displays.is_empty() || compositor.is_some() || cfg!(target_os = "windows") {
let backend_chosen = explicit_renderer || std::env::var_os("WGPU_BACKEND").is_some();
setup.native_adapter_selector = Some(std::sync::Arc::new(move |adapters, surface| {
let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
let infos: Vec<(u32, u32, eframe::wgpu::DeviceType)> = usable
let infos: Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> = usable
.iter()
.map(|a| {
let info = a.get_info();
(info.vendor, info.device, info.device_type)
(info.vendor, info.device, info.device_type, info.backend)
})
.collect();
let picked = pick_adapter(&infos, &displays, compositor).and_then(|i| usable.get(i)).map(|a| (*a).clone());
if let Some(a) = &picked
&& !wgpu_draws_with(a.get_info().backend, cfg!(target_os = "windows"), backend_chosen)
{
log::warn!(
"wgpu found no Direct3D 12 adapter for {}, only its OpenGL backend: drawing with eframe's OpenGL renderer instead",
a.get_info().name
);
return Err("wgpu would draw through its OpenGL backend".to_string());
}
match &picked {
// Which GPU draws is the first question when a window stays black (#8, #378, #445).
Some(a) => {
@@ -671,14 +847,36 @@ fn configure_gpu(native: &mut eframe::NativeOptions) {
}));
}
}
if cfg!(target_os = "windows") && std::env::var_os("WGPU_BACKEND").is_none() {
setup.instance_descriptor.backends = eframe::wgpu::Backends::DX12 | eframe::wgpu::Backends::GL;
if let Some(backends) =
automatic_windows_backends(cfg!(target_os = "windows"), std::env::var_os("WGPU_BACKEND").is_some(), power_chosen, explicit_renderer)
{
setup.instance_descriptor.backends = backends;
}
if cfg!(target_os = "windows") {
setup.instance_descriptor.backend_options.dx12.presentation_system = dx12_presentation(eframe::wgpu::Dx12SwapchainKind::from_env());
}
}
/// A power preference delegates adapter ranking to wgpu, bypassing the selector that declines
/// its OpenGL surface on Windows. Auto mode must then try DX12 alone before native OpenGL.
fn automatic_windows_backends(windows: bool, explicit_backend: bool, power_chosen: bool, explicit_renderer: bool) -> Option<eframe::wgpu::Backends> {
use eframe::wgpu::Backends;
if !windows || explicit_backend {
return None;
}
Some(if power_chosen && !explicit_renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL })
}
/// Whether wgpu should draw with the adapter it picked on `backend`. On Windows (`windows`) wgpu
/// reaches its OpenGL backend only for a GPU with no Direct3D 12 driver, such as Intel's Ivy
/// Bridge, and there that backend fails in `Surface::configure` a few seconds after the window
/// opens: too late for the start-up retry with OpenGL, so the app closed (#519, #4134, #5553).
/// eframe's own OpenGL renderer works on the same GPUs, so wgpu declines and that retry takes over.
/// An explicit `PDFCRAFT_RENDERER=wgpu` or `WGPU_BACKEND` selection (`backend_chosen`) is kept.
fn wgpu_draws_with(backend: eframe::wgpu::Backend, windows: bool, backend_chosen: bool) -> bool {
!(windows && backend == eframe::wgpu::Backend::Gl && !backend_chosen)
}
/// How Direct3D 12 presents on Windows: through a DirectComposition visual (issue #2738), unless
/// `WGPU_DX12_PRESENTATION_SYSTEM` asked for something else (`asked`).
fn dx12_presentation(asked: Option<eframe::wgpu::Dx12SwapchainKind>) -> eframe::wgpu::Dx12SwapchainKind {
@@ -806,14 +1004,25 @@ fn linux_display_gpus(drm: &std::path::Path) -> Vec<DisplayGpu> {
/// primary display (a hybrid laptop's panel, #8; the primary display on Windows, #378), or else,
/// with no primary display known (a Linux desktop with a monitor on each GPU, #445), the discrete
/// one. Otherwise the most frugal kind: integrated, discrete, other, virtual, software.
fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[DisplayGpu], compositor: Option<(u32, u32)>) -> Option<usize> {
use eframe::wgpu::DeviceType;
///
/// On Windows wgpu offers a Direct3D 12 GPU through OpenGL too, and declines OpenGL there
/// (`wgpu_draws_with`), so an OpenGL adapter comes after another adapter of its vendor. wgpu's
/// OpenGL adapter has no device id and guesses its kind (every Intel GPU is integrated), so it is
/// matched by vendor alone, before its kind is compared: an Intel discrete GPU's Direct3D 12
/// adapter beats its own OpenGL one. A GPU with only OpenGL (Intel's Ivy Bridge) still beats the
/// software adapter, Microsoft's.
fn pick_adapter(
adapters: &[(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)],
displays: &[DisplayGpu],
compositor: Option<(u32, u32)>,
) -> Option<usize> {
use eframe::wgpu::{Backend, DeviceType};
let display = |pci: (u32, u32)| displays.iter().find(|g| g.pci == pci);
let multi_gpu_desktop = displays.len() > 1 && !displays.iter().any(|g| g.primary);
adapters
.iter()
.enumerate()
.min_by_key(|(_, (vendor, device, kind))| {
.min_by_key(|(_, (vendor, device, kind, backend))| {
let shown = display((*vendor, *device));
let drives_display = shown.is_some();
let drives_primary = shown.is_some_and(|g| g.primary);
@@ -827,10 +1036,40 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D
DeviceType::VirtualGpu => 4,
DeviceType::Cpu => 5,
};
(compositor != Some((*vendor, *device)), !drives_display, !drives_primary, rank)
let gl = *backend == Backend::Gl;
let vendor_has_more = gl && adapters.iter().any(|(v, _, _, b)| v == vendor && *b != Backend::Gl);
(compositor != Some((*vendor, *device)), !drives_display, !drives_primary, vendor_has_more, rank, gl)
})
.map(|(i, _)| i)
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod nightly_bootstrap_tests {
use super::{
APP_ICON_PNG, APP_ID, app_icon_png, app_id, app_title, built_version, initialize_nightly_process_identity, is_nightly, nightly_version_line,
refusal_dialog,
};
use crate::build_flavor::BuildFlavor;
#[test]
fn stable_defaults_and_nightly_version_line() {
assert!(!is_nightly());
assert_eq!(app_id(), APP_ID);
assert_eq!(app_title(), "PdfCraft");
assert_eq!(app_icon_png(), APP_ICON_PNG);
assert!(!built_version().is_empty());
assert_eq!(nightly_version_line(), format!("PdfCraft {} (nightly-v1)", built_version()));
assert!(initialize_nightly_process_identity().is_ok());
}
#[test]
fn refusal_dialog_never_blocks_macos_or_headless_or_stable() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false));
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true));
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false));
assert!(!refusal_dialog(BuildFlavor::Stable, true, false));
}
}
+230
View File
@@ -0,0 +1,230 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write as _};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if !metadata.file_type().is_file() => {
return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory"));
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let dir = path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..32_u32 {
let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
return match std::fs::rename(&temporary, path) {
Ok(()) => Ok(()),
Err(error) => {
let _ = std::fs::remove_file(&temporary);
Err(error)
}
};
}
Err(io::Error::other("no free temporary name for the Nightly session state"))
}
impl Session {
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.len() > MAX_METADATA_BYTES || commit.is_some_and(|c| c.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance exceeds its metadata bound"));
}
let lease_path = root.join(LEASE);
let _ = regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit,
}))
.map_err(io::Error::other)?;
write_atomic_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take((self.own_record.len() as u64).saturating_add(1)).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session record was replaced by another writer"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::{LEASE, MAX_METADATA_BYTES, RECORD, Session, Shared, finish_once};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
static COUNTER: AtomicU64 = AtomicU64::new(0);
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("pdfcraft-nightly-session-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn clean_exit_clears_record_and_unclean_drop_leaves_it() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("abc")).unwrap().unwrap();
assert!(!first.previous_unclean());
assert!(Session::begin(Some(&fixture.0), "busy", None).unwrap().is_none());
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let dropped = Session::begin(Some(&fixture.0), "dropped", None).unwrap().unwrap();
drop(dropped);
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.finish(false).unwrap();
assert!(fixture.0.join(RECORD).exists());
let final_run = Session::begin(Some(&fixture.0), "final", None).unwrap().unwrap();
assert!(final_run.previous_unclean());
final_run.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn finish_once_runs_only_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists());
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
successor.complete().unwrap();
}
#[test]
fn provenance_is_bounded() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert!(Session::begin(None, "", None).unwrap().is_none());
assert_eq!(LEASE, "nightly-session.lock");
}
#[test]
fn begin_with_health_reports_busy_and_complete_refuses_replaced_record() {
let fixture = Fixture::new();
let (owner, unavailable) = Session::begin_with_health(Some(&fixture.0), "owner", Some("123")).unwrap();
assert!(!unavailable);
let owner = owner.unwrap();
let (secondary, sec_unavailable) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none());
assert!(sec_unavailable);
std::fs::write(fixture.0.join(RECORD), b"foreign writer").unwrap();
assert!(owner.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"foreign writer");
}
#[cfg(unix)]
#[test]
fn symlink_record_or_lease_is_refused() {
let fixture = Fixture::new();
let target = fixture.0.join("outside.txt");
std::fs::write(&target, b"keep").unwrap();
for name in [LEASE, RECORD] {
let link = fixture.0.join(name);
std::os::unix::fs::symlink(&target, &link).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&target).unwrap(), b"keep");
std::fs::remove_file(&link).unwrap();
}
}
}
+65
View File
@@ -0,0 +1,65 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), String> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::configure;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
assert!(super::initialize(false, "nightly-id").is_ok());
}
}
+199
View File
@@ -0,0 +1,199 @@
//! App-owned nightly profile specification passed to `craft_nightly`.
use std::path::PathBuf;
use craft_nightly::AppProfileSpec;
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.pdfcraft.nightly";
/// The app id eframe derives stable's storage folder from.
const STABLE_APP_ID: &str = "ai.storyteller.pdfcraft";
/// The subfolder autosave and recovery write inside a nightly profile.
pub const AUTOSAVE: &str = "autosave";
const STABLE_DIR_NAMES: [&str; 3] = ["pdfcraft", "PdfCraft", "PrintCraft"];
const FORBIDDEN_ENV_VARS: [&str; 1] = ["PDFCRAFT_CONFIG_DIR"];
const PORTABLE_MARKERS: [&str; 3] = ["portable.txt", "PdfCraft.portable", "PdfCraftData"];
const PROFILE_FOLDERS: [&str; 5] = [AUTOSAVE, "logs", "single-instance", "dictionary", "Digital IDs"];
/// Builds PDFCraft's [`AppProfileSpec`] for `craft_nightly` validation.
pub fn spec() -> AppProfileSpec {
AppProfileSpec {
app_id: "pdfcraft",
display_name: "PdfCraft",
stable_dir_names: &STABLE_DIR_NAMES,
stable_package_id: STABLE_APP_ID,
nightly_package_id: NIGHTLY_FLATPAK_ID,
profile_root_env: None,
forbidden_env_vars: &FORBIDDEN_ENV_VARS,
portable_markers: &PORTABLE_MARKERS,
folder_only_entries: &PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(),
}
}
fn extra_forbidden_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs_env(key) {
roots.push(base.join("ArtCraft").join("PdfCraft"));
}
}
}
#[cfg(all(unix, not(target_os = "macos")))]
{
roots.extend(["/usr/bin/pdfcraft", "/usr/local/bin/pdfcraft", "/opt/pdfcraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs_env("HOME") {
roots.push(home.join(".var/app/ai.storyteller.pdfcraft"));
}
}
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/PdfCraft.app"));
if let Some(home) = non_empty_abs_env("HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.pdfcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.pdfcraft.savedState"));
roots.push(home.join("Applications/PdfCraft.app"));
}
}
roots
}
fn non_empty_abs_env(key: &str) -> Option<PathBuf> {
let value = std::env::var_os(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use craft_nightly::{ProfileError, nightly_flatpak_id, validate_and_prepare_root};
use super::{FORBIDDEN_ENV_VARS, NIGHTLY_FLATPAK_ID, PORTABLE_MARKERS, PROFILE_FOLDERS, STABLE_DIR_NAMES, spec};
static COUNTER: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("pdfcraft-profile-root-{label}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let canonical = std::fs::canonicalize(&dir).unwrap();
Self(canonical)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn spec_preserves_pdfcraft_isolation_contract() {
let spec = spec();
assert_eq!(spec.app_id, "pdfcraft");
assert_eq!(spec.display_name, "PdfCraft");
assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, "ai.storyteller.pdfcraft");
assert_eq!(spec.nightly_package_id, NIGHTLY_FLATPAK_ID);
assert_eq!(nightly_flatpak_id(spec.app_id), NIGHTLY_FLATPAK_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, &FORBIDDEN_ENV_VARS);
assert_eq!(spec.portable_markers, &PORTABLE_MARKERS);
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
}
#[test]
fn failed_profile_preparation_does_not_start_with_stable() {
let dir = TempDir::new("file-root");
let root = dir.0.join("not-a-directory");
std::fs::write(&root, b"an ordinary file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let dir = TempDir::new("reopen");
let private = dir.0.join("nightly-reopen");
let spec = spec();
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["app.ron", "config.toml", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
"{name} must stay a directory"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn extra_forbidden_root_overlap_is_refused() {
let dir = TempDir::new("overlap");
let forbidden = dir.0.join("stable-install");
std::fs::create_dir_all(&forbidden).unwrap();
let mut spec = spec();
spec.extra_forbidden_roots.push(forbidden.clone());
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(matches!(validate_and_prepare_root(&forbidden.join("child"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let dir = TempDir::new("dangling");
let outside = dir.0.join("outside");
std::fs::create_dir_all(&outside).unwrap();
let private = dir.0.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
assert!(matches!(validate_and_prepare_root(&private, &spec()), Err(ProfileError::SymlinkEntry(_))));
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
#[cfg(unix)]
#[test]
fn hardlinked_profile_file_is_refused() {
let dir = TempDir::new("hardlink");
let private = dir.0.join("nightly-hardlink");
let spec = spec();
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
let external = dir.0.join("external.ron");
std::fs::write(&external, b"shared").unwrap();
std::fs::hard_link(&external, private.join("app.ron")).unwrap();
assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::HardlinkedEntry { .. })));
}
}
+24 -10
View File
@@ -159,26 +159,29 @@ pub fn absolute(paths: &[String]) -> Vec<String> {
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
/// when the launch asked for anything besides opening (or, with `combine`, combining) files, so
/// it gets its own window.
pub fn claim(files: &[String], may_hand_off: bool, combine: bool) -> Claim {
pub fn claim(files: &[String], may_hand_off: bool, combine: bool, profile_root: Option<&std::path::Path>) -> Claim {
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
{
match socket_path() {
match socket_path(profile_root) {
Some(path) => claim_at(&path, files, may_hand_off, combine),
None => Claim::Alone,
}
}
#[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
{
let _ = (files, may_hand_off, combine);
let _ = (files, may_hand_off, combine, profile_root);
Claim::Alone
}
}
/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder); none when
/// `%LOCALAPPDATA%` is unset.
/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder), or inside the
/// nightly profile's `single-instance` folder when running isolated; none when `%LOCALAPPDATA%` is unset.
#[cfg(windows)]
fn socket_path() -> Option<std::path::PathBuf> {
fn socket_path(profile_root: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
let name = socket_name(session_id(), std::env::var("SESSIONNAME").ok().as_deref());
if let Some(root) = profile_root {
return Some(root.join("single-instance").join(name));
}
// %LOCALAPPDATA% is private to the user's sign-in, so other accounts can't receive this
// user's file paths or send it files to open. A portable copy uses it too (#889), under its
// own name so it never hands files to an installed copy (which keeps its settings elsewhere).
@@ -187,12 +190,15 @@ fn socket_path() -> Option<std::path::PathBuf> {
std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("PdfCraft").join(name))
}
/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`; none when `$XDG_RUNTIME_DIR` is unset. Never `/tmp`
/// instead: other accounts can create files there, and so could listen in this user's place.
/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`, or inside the nightly profile's `single-instance`
/// folder when running isolated; none when `$XDG_RUNTIME_DIR` is unset.
#[cfg(all(unix, not(target_os = "macos")))]
fn socket_path() -> Option<std::path::PathBuf> {
fn socket_path(profile_root: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
let name = display_socket_name(var("WAYLAND_DISPLAY").or_else(|| var("DISPLAY")).as_deref());
if let Some(root) = profile_root {
return Some(root.join("single-instance").join(name));
}
// The XDG base directory spec makes it the user's own (mode 0700), so the folder inside it is
// out of other accounts' reach whatever the umask.
var("XDG_RUNTIME_DIR").map(|d| std::path::PathBuf::from(d).join("pdfcraft").join(name))
@@ -476,7 +482,7 @@ mod tests {
let id = super::session_id();
assert!(id.is_some(), "the access token names the session");
let name = socket_name(id, None);
assert!(socket_path().is_none_or(|p| p.file_name().is_some_and(|f| f.to_string_lossy().ends_with(&name))), "{name}");
assert!(socket_path(None).is_none_or(|p| p.file_name().is_some_and(|f| f.to_string_lossy().ends_with(&name))), "{name}");
}
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
@@ -540,4 +546,12 @@ mod tests {
assert!(std::fs::symlink_metadata(&path).is_ok(), "the socket file stays behind");
assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true, false), Claim::Primary(_)));
}
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
#[test]
fn nightly_profile_root_isolates_the_single_instance_socket() {
let root = std::env::temp_dir().join(format!("pdfcraft-si-nightly-{}", std::process::id()));
let path = socket_path(Some(&root)).unwrap();
assert_eq!(path.parent(), Some(root.join("single-instance").as_path()));
}
}
+25
View File
@@ -28,11 +28,25 @@ impl Arguments {
!self.new_window && !self.files.is_empty() && self.options.is_empty() && self.control_port.is_none() && !self.create_images && !self.two_paged
}
/// Launcher-provided filenames follow a delimiter, not the ordinary option parser. Direct
/// Nightly launches still accept the normal application options before a delimiter.
pub fn parse_for_profile(args: impl IntoIterator<Item = String>, nightly: bool) -> Self {
if nightly { Self::parse_impl(args, true) } else { Self::parse(args) }
}
pub fn parse(args: impl IntoIterator<Item = String>) -> Self {
Self::parse_impl(args, false)
}
fn parse_impl(args: impl IntoIterator<Item = String>, literal_separator: bool) -> Self {
let mut parsed = Self::default();
let mut args = args.into_iter();
while let Some(a) = args.next() {
match a.as_str() {
"--" if literal_separator => {
parsed.files.extend(args.map(craft::platform::default_app::path_from_arg));
break;
}
"--version" => {
parsed.version = true;
break;
@@ -126,6 +140,17 @@ mod tests {
Arguments::parse(args.iter().map(|s| s.to_string()))
}
#[test]
fn nightly_delimiter_keeps_launcher_file_names_literal() {
let parsed = Arguments::parse_for_profile(["--", "--two-paged", "document.pdf"].map(str::to_owned), true);
assert_eq!(parsed.files, ["--two-paged", "document.pdf"]);
assert!(!parsed.two_paged);
assert!(parsed.options.is_empty());
let direct = Arguments::parse_for_profile(["--two-paged", "document.pdf"].map(str::to_owned), true);
assert!(direct.two_paged);
assert_eq!(direct.files, ["document.pdf"]);
}
#[test]
fn standalone_flag_keeps_files_in_either_position() {
for args in
+78 -5
View File
@@ -19,6 +19,71 @@ pub(crate) fn install_runtime(ctx: &egui::Context) {
craft::ui::shell::embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(Lang::EN)).expect("the runtime installs on a fresh context");
}
#[test]
fn a_power_preference_without_an_explicit_renderer_retries_native_opengl_on_windows() {
use eframe::wgpu::Backends;
for power in [false, true] {
for renderer in [false, true] {
assert_eq!(super::automatic_windows_backends(false, false, power, renderer), None);
assert_eq!(super::automatic_windows_backends(true, true, power, renderer), None);
let expected = if power && !renderer { Backends::DX12 } else { Backends::DX12 | Backends::GL };
assert_eq!(super::automatic_windows_backends(true, false, power, renderer), Some(expected));
}
}
}
#[test]
fn on_windows_wgpu_leaves_an_opengl_only_gpu_to_eframes_opengl_renderer() {
use eframe::wgpu::Backend;
// Issues #4134 and #5553: an Intel HD 4000 has no Direct3D 12 driver, so wgpu picks its
// OpenGL backend, which fails a few seconds after the window opens.
assert!(!super::wgpu_draws_with(Backend::Gl, true, false), "declined, so the start-up retry uses glow");
// Everything else draws with wgpu as before.
assert!(super::wgpu_draws_with(Backend::Dx12, true, false));
assert!(super::wgpu_draws_with(Backend::Gl, true, true), "WGPU_BACKEND asked for it");
for backend in [Backend::Gl, Backend::Vulkan, Backend::Metal] {
assert!(super::wgpu_draws_with(backend, false, false), "{backend:?} off Windows");
}
}
#[test]
fn pick_adapter_takes_a_gpus_opengl_adapter_last_and_an_opengl_only_gpu_over_software() {
use eframe::wgpu::{Backend, DeviceType};
// wgpu's OpenGL adapter has its vendor's id, no device id, and a kind guessed from its
// strings: every Intel GPU is integrated, and most others are "other" (wgpu-hal's gles
// `make_info`).
let gl = |vendor: u32, kind| (vendor, 0, kind, Backend::Gl);
// A GPU offered through OpenGL and through Direct3D 12 or Vulkan, in either order, with or
// without a known display: never OpenGL, which `wgpu_draws_with` declines on Windows.
const ARC: (u32, u32) = (0x8086, 0x56a0);
for other in [Backend::Dx12, Backend::Vulkan] {
for (gpu, kind, guessed) in [
(INTEL_IGPU, DeviceType::IntegratedGpu, DeviceType::IntegratedGpu),
// An Intel discrete GPU, which wgpu's OpenGL backend calls integrated (CodeRabbit).
(ARC, DeviceType::DiscreteGpu, DeviceType::IntegratedGpu),
(NVIDIA, DeviceType::DiscreteGpu, DeviceType::Other),
] {
let gl_first = [gl(gpu.0, guessed), (gpu.0, gpu.1, kind, other)];
for displays in [&[panel(gpu)][..], &[]] {
assert_eq!(super::pick_adapter(&gl_first, displays, None), Some(1), "{gpu:x?} {other:?} {displays:?}");
assert_eq!(super::pick_adapter(&[gl_first[1], gl_first[0]], displays, None), Some(0), "{gpu:x?} {other:?} {displays:?}");
}
}
}
// Issue #4134: an Intel HD 4000 has only OpenGL, and the Microsoft Basic Render Driver (in
// software) has Direct3D 12. The GPU is still picked, by kind, with or without a known
// display, as over Remote Desktop; declining it then starts glow on that GPU.
const HD_4000: (u32, u32) = (0x8086, 0x0166);
let ivy_bridge = [(0x1414, 0x008c, DeviceType::Cpu, Backend::Dx12), gl(HD_4000.0, DeviceType::IntegratedGpu)];
assert_eq!(super::pick_adapter(&ivy_bridge, &[panel(HD_4000)], None), Some(1));
assert_eq!(super::pick_adapter(&ivy_bridge, &[], None), Some(1));
assert!(!super::wgpu_draws_with(Backend::Gl, true, false));
// Only OpenGL, or only software: that adapter.
assert_eq!(super::pick_adapter(&ivy_bridge[1..], &[], None), Some(0));
assert_eq!(super::pick_adapter(&ivy_bridge[..1], &[], None), Some(0));
assert_eq!(super::pick_adapter(&[], &[], None), None);
}
#[test]
fn opengl_is_the_fallback_unless_a_renderer_was_chosen() {
use super::{RendererChoice, native_options, renderer_choice, retry_with_gl};
@@ -322,9 +387,13 @@ const NVIDIA: (u32, u32) = (0x10de, 0x2684);
const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204);
const AMD_IGPU: (u32, u32) = (0x1002, 0x164e);
fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType)> {
use eframe::wgpu::DeviceType;
vec![(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu), (0, 0, DeviceType::Cpu)]
fn adapters() -> Vec<(u32, u32, eframe::wgpu::DeviceType, eframe::wgpu::Backend)> {
use eframe::wgpu::{Backend, DeviceType};
vec![
(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan),
(AMD_IGPU.0, AMD_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan),
(0, 0, DeviceType::Cpu, Backend::Vulkan),
]
}
const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780);
@@ -391,8 +460,12 @@ fn pick_adapter_keeps_the_integrated_gpu_on_hybrid_laptops() {
#[test]
fn pick_adapter_prefers_the_discrete_gpu_on_desktops_with_a_monitor_on_each() {
// Issue #445: one monitor on the Intel iGPU, one on the NVIDIA card, no built-in panel.
use eframe::wgpu::DeviceType;
let desktop = [(INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu), (NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu), (0, 0, DeviceType::Cpu)];
use eframe::wgpu::{Backend, DeviceType};
let desktop = [
(INTEL_IGPU.0, INTEL_IGPU.1, DeviceType::IntegratedGpu, Backend::Vulkan),
(NVIDIA.0, NVIDIA.1, DeviceType::DiscreteGpu, Backend::Vulkan),
(0, 0, DeviceType::Cpu, Backend::Vulkan),
];
assert_eq!(super::pick_adapter(&desktop, &[monitor(INTEL_IGPU), monitor(NVIDIA)], None), Some(1));
assert_eq!(super::pick_adapter(&desktop, &[monitor(NVIDIA), monitor(INTEL_IGPU)], None), Some(1));
// A GPU driving no display still loses to one that does.
+101
View File
@@ -0,0 +1,101 @@
//! Keep the restored Windows window on its monitor after a first launch or DPI change.
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
use winsafe::{HMONITOR, HWND, POINT, RECT, WINDOWPLACEMENT, co};
pub(super) fn restore(window: &winit::window::Window) {
// Presentation belongs to the document session. An OS fullscreen flag restored
// by eframe while PdfCraft is showing Home otherwise leaves Home without captions.
if window.fullscreen().is_some() {
window.set_fullscreen(None);
}
let Ok(handle) = window.window_handle() else { return };
let RawWindowHandle::Win32(raw) = handle.as_raw() else { return };
// Borrow the matching handle from the window thread using winsafe's safe API.
if let Err(error) = winsafe::EnumThreadWindows(winsafe::GetCurrentThreadId(), |hwnd| {
if hwnd.ptr() as isize == raw.hwnd.get()
&& let Err(error) = fit_restore_bounds(&hwnd)
{
log::warn!("could not fit the restored PdfCraft window: {error}");
}
true
}) {
log::warn!("could not read the PdfCraft window placement: {error}");
}
}
fn fit_restore_bounds(hwnd: &HWND) -> winsafe::SysResult<()> {
let mut placement = WINDOWPLACEMENT::default();
hwnd.GetWindowPlacement(&mut placement)?;
let monitor = hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()?;
// WINDOWPLACEMENT for the main window is in workspace coordinates. Monitor work
// areas are in screen coordinates, including the taskbar's left/top displacement.
let dx = monitor.rcWork.left - monitor.rcMonitor.left;
let dy = monitor.rcWork.top - monitor.rcMonitor.top;
let r = placement.rcNormalPosition;
let screen = RECT { left: r.left + dx, right: r.right + dx, top: r.top + dy, bottom: r.bottom + dy };
if let Some(bounds) = fitted(screen, monitor.rcWork) {
// On vertically staggered monitors, opposite corners can be visible while
// the top-right caption controls are in the gap between screens.
let corners = [
POINT { x: screen.left, y: screen.top },
POINT { x: screen.right - 1, y: screen.top },
POINT { x: screen.left, y: screen.bottom - 1 },
POINT { x: screen.right - 1, y: screen.bottom - 1 },
];
if corners.iter().all(|p| {
HMONITOR::MonitorFromPoint(*p, co::MONITOR::DEFAULTTONULL)
.GetMonitorInfo()
.is_ok_and(|m| p.x >= m.rcWork.left && p.x < m.rcWork.right && p.y >= m.rcWork.top && p.y < m.rcWork.bottom)
}) {
return Ok(());
}
placement.rcNormalPosition = RECT { left: bounds.left - dx, right: bounds.right - dx, top: bounds.top - dy, bottom: bounds.bottom - dy };
// Keep showCmd: maximized windows stay maximized, but Restore gets usable bounds.
hwnd.SetWindowPlacement(&placement)?;
}
Ok(())
}
fn fitted(rect: RECT, work: RECT) -> Option<RECT> {
let width = rect.right.saturating_sub(rect.left);
let height = rect.bottom.saturating_sub(rect.top);
let room_x = work.right.saturating_sub(work.left);
let room_y = work.bottom.saturating_sub(work.top);
if width <= 0 || height <= 0 || room_x <= 0 || room_y <= 0 {
return None;
}
if rect.left >= work.left && rect.top >= work.top && rect.right <= work.right && rect.bottom <= work.bottom {
return None;
}
// A screen-sized default plus Windows' cascaded origin is the common first-run case.
// Leave room around the restored window so Maximize and Restore are visibly distinct.
let (width, height) =
if width >= room_x && height >= room_y { (room_x - room_x / 10, room_y - room_y / 10) } else { (width.min(room_x), height.min(room_y)) };
let left = rect.left.clamp(work.left, work.right - width);
let top = rect.top.clamp(work.top, work.bottom - height);
Some(RECT { left, top, right: left + width, bottom: top + height })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restore_after_high_dpi_startup_keeps_the_caption_controls_on_screen() {
let work = RECT { left: 0, top: 0, right: 3456, bottom: 2040 };
let old = RECT { left: 305, top: 305, right: 3761, bottom: 2465 };
let expected = RECT { left: 305, top: 204, right: 3416, bottom: 2040 };
assert!(fitted(old, work) == Some(expected));
assert!(fitted(work, work).is_none());
}
#[test]
fn a_saved_window_keeps_its_size_and_monitor_when_only_its_origin_is_wrong() {
let work = RECT { left: -1920, top: 40, right: 0, bottom: 1080 };
let old = RECT { left: -620, top: 200, right: 580, bottom: 900 };
let expected = RECT { left: -1200, top: 200, right: 0, bottom: 900 };
assert!(fitted(old, work) == Some(expected));
assert!(fitted(expected, work).is_none());
}
}
+106
View File
@@ -0,0 +1,106 @@
#![cfg(target_os = "linux")]
//! The logger must reach disk while the real desktop app is running, before it can be closed.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
struct Running(Child);
impl Drop for Running {
fn drop(&mut self) {
if self.0.try_wait().ok().flatten().is_none() {
let _ = self.0.kill();
}
let _ = self.0.wait();
}
}
#[test]
fn startup_breadcrumbs_reach_the_portable_log_before_quit() {
use std::os::unix::fs::PermissionsExt;
let xvfb = Command::new("Xvfb").args(["-displayfd", "1", "-screen", "0", "1024x768x24", "-nolisten", "tcp"]).stdout(Stdio::piped()).spawn();
let mut display = match xvfb {
Ok(p) => Running(p),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::env::var_os("CI").is_none() => {
eprintln!("Xvfb is needed to exercise desktop startup");
return;
}
Err(e) => panic!("start Xvfb: {e}"),
};
let mut number = String::new();
BufReader::new(display.0.stdout.take().unwrap()).read_line(&mut number).unwrap();
assert!(!number.trim().is_empty(), "Xvfb did not open a display");
let root = std::env::temp_dir().join(format!("pdfcraft-startup-log-{}", std::process::id()));
std::fs::create_dir(&root).unwrap();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
let exe = root.join("pdfcraft");
let bin = env!("CARGO_BIN_EXE_pdfcraft");
if std::fs::hard_link(bin, &exe).is_err() {
std::fs::copy(bin, &exe).unwrap();
}
std::fs::write(root.join("portable.txt"), []).unwrap();
let port = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let mut secret = [0_u8; 32];
std::fs::File::open("/dev/urandom").unwrap().read_exact(&mut secret).unwrap();
let token: String = secret.iter().map(|byte| format!("{byte:02x}")).collect();
let mut app = Running(
Command::new(exe)
.args(["--new-window", "--control", &port.to_string()])
.env("PDFCRAFT_CONTROL_TOKEN", &token)
.env("HOME", &root)
.env("XDG_RUNTIME_DIR", &root)
.env("XDG_CONFIG_HOME", &root)
.env("XDG_DATA_HOME", &root)
.env_remove("WAYLAND_DISPLAY")
.env_remove("PDFCRAFT_CONFIG_DIR")
.env("DISPLAY", format!(":{}", number.trim()))
.env("PDFCRAFT_RENDERER", "gl")
.env("RUST_LOG", "info")
.env("LIBGL_ALWAYS_SOFTWARE", "1")
.spawn()
.unwrap(),
);
let deadline = Instant::now() + Duration::from_secs(60);
let log = root.join("PdfCraftData/logs/pdfcraft.log");
let mut socket = loop {
if log.exists()
&& std::fs::read_to_string(&log).unwrap_or_default().contains("first UI pass finished")
&& let Ok(socket) = TcpStream::connect(("127.0.0.1", port))
{
break socket;
}
assert!(app.0.try_wait().unwrap().is_none(), "PdfCraft exited during startup");
assert!(Instant::now() < deadline, "startup log: {:?}", std::fs::read_to_string(&log));
std::thread::sleep(Duration::from_millis(100));
};
let log = std::fs::read_to_string(log).unwrap();
let mut rest = log.as_str();
for stage in [
"claiming application instance",
"reading startup preferences",
"initializing OpenGL",
"renderer ready, installing fonts and runtime",
"initializing application and recovery",
"applying preferences",
"restoring session and opening requested documents",
"entering UI event loop",
"first UI pass finished",
] {
rest = rest.split_once(stage).unwrap_or_else(|| panic!("missing or misordered stage {stage}: {log}")).1;
}
socket.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let mut read = BufReader::new(socket.try_clone().unwrap());
for (method, params) in [("auth", serde_json::json!({"token":token})), ("ui.quit", serde_json::json!({}))] {
writeln!(socket, "{}", serde_json::json!({"id":1,"method":method,"params":params})).unwrap();
let mut reply = String::new();
read.read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<serde_json::Value>(&reply).unwrap()["ok"], true);
}
while app.0.try_wait().unwrap().is_none() {
assert!(Instant::now() < deadline, "PdfCraft did not quit");
std::thread::sleep(Duration::from_millis(100));
}
assert!(app.0.wait().unwrap().success());
std::fs::remove_dir_all(root).unwrap();
}
+24
View File
@@ -0,0 +1,24 @@
{
"schema": "craft-nightly-icon-provenance/v1",
"app": "pdfcraft",
"channel": "nightly-v1",
"source": {
"master": "assets/app-icon/pdfcraft-1024.png",
"note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon."
},
"transform": {
"summary": "The app mark (white/light strokes and their antialiasing) is copied unchanged; only the background square is deepened.",
"background": {
"from": "#b70228",
"to": "#710118",
"rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were."
}
},
"outputs": {
"pdfcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as pdfcraft-nightly.png",
"pdfcraft-nightly-1024.png": "the padded 1024 master the icns is generated from",
"pdfcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon",
"pdfcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile pdfcraft-nightly)"
},
"not_done_here": "No badge, crescent or N was added, and the stable pdfcraft.png/.ico/.icns files are untouched."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

@@ -0,0 +1,116 @@
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
http://creativecommons.org/publicdomain/zero/1.0/
+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v1.49.0 - ISC -->
<svg
class="lucide lucide-chevrons-down"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m7 6 5 5 5-5" />
<path d="m7 13 5 5 5-5" />
</svg>

After

Width:  |  Height:  |  Size: 349 B

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

After

Width:  |  Height:  |  Size: 350 B

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

After

Width:  |  Height:  |  Size: 4.0 KiB

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

After

Width:  |  Height:  |  Size: 486 B

+1 -2
View File
@@ -266,10 +266,9 @@ impl Automation {
let path = self.resolve(p, false)?;
files.push((p.to_string(), crate::read_input_bytes(&path).map_err(|e| failed(format!("{p}: {e}")))?));
}
let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?;
let (csv, columns) = pdfcraft_engine::merge_data_files_with_columns(&files).map_err(failed)?;
let target = self.resolve(a.str("path")?, true)?;
write_atomic(&target, csv.as_bytes())?;
let columns = csv.lines().next().map_or(0, |h| h.split(',').count());
Ok(json!({ "path": target.to_string_lossy(), "rows": files.len(), "columns": columns }))
}
+6
View File
@@ -33,6 +33,12 @@ impl Automation {
Some(Value::Object(params)) => params.clone(),
Some(_) => return Err(ToolError::InvalidArgs("params must be an object".into())),
};
// Without it the tool would do something else: add a header and footer, not update one.
if let Some(arg) = tools::command_needs(id)
&& params.get(arg).is_none_or(Value::is_null)
{
return Err(ToolError::InvalidArgs(format!("{id} needs params.{arg} (see {tool})")));
}
let props = def.input_schema.get("properties").and_then(Value::as_object).ok_or_else(|| failed("tool has no parameter schema"))?;
let accepted = props.keys().map(String::as_str).collect::<Vec<_>>().join(", ");
let mut warnings = Vec::new();
+9
View File
@@ -44,6 +44,14 @@ fn view_transform_to_user(info: &pdfcraft_render::PageInfo, m: [f64; 6]) -> Resu
impl Automation {
/// Run the tool `name` with JSON `args` (an object; `null` means no arguments).
pub fn call(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
let out = self.call_tool(name, args);
// Whatever the call did, failed or not: the id of a header and footer it removed must not
// pass to one a later call adds with the same settings (#5785).
self.forget_removed_header_footers();
out
}
fn call_tool(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
let empty = json!({});
let args = if args.is_null() { &empty } else { args };
if !args.is_object() {
@@ -722,6 +730,7 @@ impl Automation {
"doc_export_images" | "doc_export_text" | "doc_export_all_images" => self.export(name, &a)?,
"doc_header_footer" | "doc_watermark" | "doc_background" | "doc_printer_marks" | "doc_remove_marks" => self.marks(name, &a)?,
"doc_backdrops" => self.backdrops(&a)?,
"doc_header_footers" => self.header_footers(&a)?,
"doc_unprotect" => {
let mut out = self.apply(&a, Edit::RemoveProtection)?;
out["security"] = security(self.doc(&a)?);
+167 -5
View File
@@ -15,7 +15,107 @@ const BOOKMARK_PAGE: usize = 100;
const MAX_BOOKMARK_PAGE: usize = 1000;
/// The ids `doc_header_footers` gives one document's headers and footers, for
/// `doc_header_footer`'s `update` (#5785).
///
/// A mark is known by its recorded settings (marks with equal ones count as one, and Update finds
/// the one to change by them), so the id names the mark with those settings wherever it moves and
/// however the list around it changes. But equal settings alone don't make the same mark: one
/// removed and then added again with the same settings is a new one. So each mark gets a serial
/// when it is first seen, never given before, which it keeps only while it stays: every tool call
/// ends by forgetting the serials of the marks it removed or changed
/// ([`Automation::forget_removed_header_footers`]). An id taken before then names no mark, and
/// a stale selection is refused rather than applied to another mark.
pub(crate) struct HeaderFooterIds {
/// The working file the serials were last checked against: a call that leaves it as it was
/// removed no mark.
seen: Arc<Vec<u8>>,
/// The serial of each mark the document has, by [`settings_digest`].
serials: std::collections::HashMap<u64, u64>,
}
/// The key ids are hashed with: afresh each run, like doc handles, so an id tells nothing about
/// text a document doesn't allow copying.
fn id_hasher() -> std::hash::DefaultHasher {
use std::hash::BuildHasher;
static KEY: std::sync::OnceLock<std::collections::hash_map::RandomState> = std::sync::OnceLock::new();
KEY.get_or_init(Default::default).build_hasher()
}
/// The `id` of the mark with settings digest `digest` and serial `serial` ([`HeaderFooterIds`]).
fn header_footer_id(digest: u64, serial: u64) -> String {
use std::hash::Hasher;
let mut h = id_hasher();
h.write_u64(digest);
h.write_u64(serial);
format!("{:016x}", h.finish())
}
/// Settings equal as compared, and only those, digest alike.
fn settings_digest(settings: &pdfcraft_engine::HeaderFooter) -> u64 {
use std::hash::{Hash, Hasher};
// Every field, so a new one can't be left out.
let pdfcraft_engine::HeaderFooter { text, font, font_size, color, underline, margins, start_number, shrink } = settings;
let mut h = id_hasher();
text.hash(&mut h);
h.write_u8(match font {
pdfcraft_engine::FontFamily::Helvetica => 0,
pdfcraft_engine::FontFamily::Times => 1,
pdfcraft_engine::FontFamily::Courier => 2,
});
// -0.0 equals 0.0 as a setting, so both hash as 0.0. (Listed settings are finite.)
for v in std::iter::once(font_size).chain(color).chain(margins) {
h.write_u64(if *v == 0.0 { 0 } else { v.to_bits() });
}
underline.hash(&mut h);
start_number.hash(&mut h);
shrink.hash(&mut h);
h.finish()
}
impl Automation {
/// The headers and footers of `id` (as `Document::header_footers` lists them) with their ids,
/// giving a new serial to each one not seen before and forgetting those of the ones gone.
fn header_footers_with_ids(&mut self, id: DocId) -> Result<Vec<(pdfcraft_engine::HeaderFooterMark, String)>> {
let doc = self.session.get(id).ok_or_else(|| failed("no such document"))?;
let marks = doc.header_footers();
let ids = self.header_footer_ids.entry(id).or_insert_with(|| HeaderFooterIds { seen: doc.bytes.clone(), serials: Default::default() });
ids.seen = doc.bytes.clone();
let digests: Vec<u64> = marks.iter().map(|m| settings_digest(&m.settings)).collect();
ids.serials.retain(|d, _| digests.contains(d));
let last = &mut self.last_header_footer;
Ok(marks
.into_iter()
.zip(digests)
.map(|(m, d)| {
let serial = *ids.serials.entry(d).or_insert_with(|| {
*last += 1;
*last
});
(m, header_footer_id(d, serial))
})
.collect())
}
/// After every tool call: forget the ids of the headers and footers the call removed or
/// changed, in each document ids were given for, so none passes to one added later
/// ([`HeaderFooterIds`]). A document whose working file the call left as it was is skipped.
pub(crate) fn forget_removed_header_footers(&mut self) {
let docs: Vec<DocId> = self.header_footer_ids.keys().copied().collect();
for id in docs {
let changed = match self.session.get(id) {
None => {
self.header_footer_ids.remove(&id);
continue;
}
Some(doc) => !Arc::ptr_eq(&doc.bytes, &self.header_footer_ids[&id].seen),
};
if changed {
let _ = self.header_footers_with_ids(id);
}
}
}
// ---- documents ---------------------------------------------------------------------------
/// One page of a document's bookmarks: `offset` (from 0) and `limit` (1 to `MAX_BOOKMARK_PAGE`).
@@ -179,6 +279,13 @@ impl Automation {
// A save that adds or removes encryption, or must not keep the old revision (Sanitize,
// redaction), is rewritten in full even when an incremental save was asked for.
let incremental = !full && bytes.starts_with(&self.doc(a)?.saved_bytes());
// A file that can't be replaced in place (read-only, extended attributes it can't keep, a
// folder that refuses the new file) stays as it was, and so does the unsaved edit: say how
// to keep the work, as 0.22.0 did before the writer moved into the framework.
let write = |path: &Path, bytes: &[u8]| match write(path, bytes) {
Err(ToolError::Failed(m)) if same_file => Err(failed(format!("{m}; save a copy with Save As (doc_save with a new path)"))),
other => other,
};
let mut out = self.publish_save(id, &target, bytes, incremental, write)?;
if !scripts.is_empty()
&& let Some(o) = out.as_object_mut()
@@ -596,6 +703,33 @@ impl Automation {
Ok(out)
}
/// The headers and footers with recorded settings, each with the `id` `doc_header_footer`'s
/// `update` names it by. Their text is copied out only where the document allows copying, as
/// with `doc_to_copy`.
pub(crate) fn header_footers(&mut self, a: &Args) -> Result<Value> {
let id = self.doc(a)?.id;
let marks = self.header_footers_with_ids(id)?;
let copying = self.doc(a)?.check_copying().is_ok();
let found: Vec<Value> = marks
.iter()
.map(|(m, id)| {
let mut out = json!({ "id": id, "pages": m.pages.iter().map(|p| p + 1).collect::<Vec<_>>() });
if copying {
let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"];
let text: serde_json::Map<String, Value> =
boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect();
out["text"] = Value::Object(text);
}
out
})
.collect();
let mut out = json!({ "header_footers": found });
if !copying {
out["text_withheld"] = json!("the document does not allow copying its text");
}
Ok(out)
}
/// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`).
pub(crate) fn backdrops(&mut self, a: &Args) -> Result<Value> {
let n = self.doc(a)?.info.pages.len();
@@ -621,9 +755,28 @@ impl Automation {
pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result<Value> {
use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark};
let n = self.doc(a)?.info.pages.len();
let pages = match a.opt_ints("pages")? {
Some(_) => self.pages(a, "pages")?,
None => (0..n).collect(),
// The header and footer `update` names, as `doc_header_footers` lists it.
let updating = match a.opt_str("update")? {
Some(_) if tool != "doc_header_footer" => return Err(ToolError::InvalidArgs("update is only for doc_header_footer".into())),
Some(_) if a.opt_bool("replace")?.is_some() => return Err(ToolError::InvalidArgs("give update or replace, not both".into())),
Some(id) => {
// By id, never by place in the list: a selection made before the list changed
// still reaches its own header and footer, or none (#5785).
let doc = self.doc(a)?.id;
let mark = self.header_footers_with_ids(doc)?.into_iter().find(|(_, i)| i == id).map(|(m, _)| m);
Some(mark.ok_or_else(|| {
ToolError::InvalidArgs(format!(
"no header and footer has the id {id:?}: it was changed or removed since doc_header_footers listed it, so list them again"
))
})?)
}
None => None,
};
let updated = updating.is_some();
let pages = match (a.opt_ints("pages")?, &updating) {
(Some(_), _) => self.pages(a, "pages")?,
(None, Some(mark)) => mark.pages.clone(),
(None, None) => (0..n).collect(),
};
let color =
|key: &str, default: [f64; 3]| -> Result<[f64; 3]> { Ok(a.opt_str(key)?.map(comments::parse_color).transpose()?.unwrap_or(default)) };
@@ -654,7 +807,10 @@ impl Automation {
hf.start_number = s.clamp(1, u32::MAX as i64) as u32;
}
hf.shrink = a.opt_bool("shrink")?.unwrap_or(false);
Edit::AddHeaderFooter { pages, settings: hf, replace }
match updating {
Some(mark) => Edit::UpdateHeaderFooter { old: mark.settings, pages, settings: hf },
None => Edit::AddHeaderFooter { pages, settings: hf, replace },
}
}
"doc_watermark" => {
let d = Watermark::default();
@@ -735,7 +891,13 @@ impl Automation {
Edit::RemoveMarks { kind }
}
};
self.apply(a, edit)
let mut out = self.apply(a, edit)?;
// An update gives the header and footer it changed a new id (its settings changed): hand
// back the list as it now is.
if updated {
out["header_footers"] = self.header_footers(a)?["header_footers"].take();
}
Ok(out)
}
pub(crate) fn export(&mut self, tool: &str, a: &Args) -> Result<Value> {
+6
View File
@@ -101,6 +101,10 @@ pub struct Automation {
next_ocr_review: u64,
/// What object_copy copied, for object_paste into any open document.
objects_clipboard: Option<pdfcraft_engine::ObjectClipboard>,
/// The header and footer ids handed out, by document (see `documents::HeaderFooterIds`).
header_footer_ids: HashMap<DocId, documents::HeaderFooterIds>,
/// The last serial a header and footer id was given; none is given twice.
last_header_footer: u64,
}
impl Default for Automation {
@@ -122,6 +126,8 @@ impl Automation {
ocr_reviews: HashMap::new(),
next_ocr_review: 0,
objects_clipboard: None,
header_footer_ids: HashMap::new(),
last_header_footer: 0,
}
}
+42 -4
View File
@@ -2,6 +2,8 @@
//! document, and manage trusted certificates. Rectangles are points from the top-left of the
//! displayed page.
use std::io::Read;
use pdfcraft_engine::js::SignEvent;
use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey};
use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus};
@@ -9,6 +11,9 @@ use serde_json::{Value, json};
use crate::{Args, Automation, Result, ToolError, failed, write_atomic};
/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`).
const EU_LIST: &str = "EU Trusted List";
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
@@ -377,8 +382,10 @@ impl Automation {
}
pub(crate) fn sign_trust(&mut self, a: &Args) -> Result<Value> {
let mut certs: Vec<Certificate> =
if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Every argument is read and checked first, so a bad one changes nothing, and the changes
// are applied together: the open documents are revalidated once, not once per change.
let clear = a.opt_bool("clear")?.unwrap_or(false);
let mut certs: Vec<Certificate> = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Which certificates are already in, by their bytes: a set, so a bundle of many distinct
// certificates isn't compared against every one before it.
let mut known: std::collections::HashSet<Vec<u8>> = certs.iter().map(|c| c.raw.clone()).collect();
@@ -391,6 +398,7 @@ impl Automation {
.map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings")))
.collect::<Result<_>>()?,
};
let certs_changed = clear || !paths.is_empty();
for p in paths {
let path = self.resolve(&p, false)?;
let bytes = crate::read_input(&path)?;
@@ -407,7 +415,37 @@ impl Automation {
}
}
}
self.session.set_trusted_certificates(certs);
Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>() }))
// The trust list, off until asked for. `None`: not mentioned, left alone.
let eu_list = match a.get("eu_trusted_list") {
None => None,
Some(Value::Bool(false) | Value::Null) => Some(None),
Some(Value::String(p)) => {
let path = self.resolve(p, false)?;
// One byte more than allowed is read, so an oversize file (or one that grows, or a
// device) is refused by `from_bytes` instead of being read whole.
let mut bytes = Vec::new();
std::fs::File::open(&path)
.and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes))
.map_err(|e| failed(format!("{}: {e}", path.display())))?;
Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?))
}
Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")),
};
if certs_changed || eu_list.is_some() {
self.session.update_trust(|trust| {
if certs_changed {
trust.certs = certs;
}
match eu_list {
Some(Some(list)) => trust.add_list(list),
Some(None) => trust.remove_list(EU_LIST),
None => {}
}
});
}
Ok(json!({
"trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>(),
"trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::<Vec<_>>(),
}))
}
}
+2 -1
View File
@@ -469,7 +469,8 @@ fn a_failed_save_sync_keeps_the_document_dirty_and_can_be_retried() {
let before = summary(a.doc(&Args(&args)).unwrap());
// The writer refuses as a storage whose flush fails does: nothing reaches the file.
let result = a.doc_save_with(&Args(&args), |_, _| Err(failed("injected storage sync failure".to_string())));
assert!(result.is_err());
let error = result.unwrap_err().to_string();
assert!(error.contains("injected storage sync failure") && error.contains("Save As"), "the refusal says how to keep the work: {error}");
let doc = a.doc(&Args(&args)).unwrap();
assert!(doc.dirty);
assert_eq!(summary(doc), before, "failed save must not reset history or saved state");
+36 -6
View File
@@ -1086,8 +1086,8 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "id", "out"],
)),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }),
&[],
)),
t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema(
@@ -1246,13 +1246,14 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_header_footer",
"Add header and footer",
"Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out existing ones (Update). Undoable.",
"Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> <<dd.mm.yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier; Thai is drawn from PdfCraft's built-in Thai face beside it (a build without one refuses it). replace: true swaps out every one on those pages. update: an id from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults, and the result lists them again (the changed one under a new id). Undoable.",
)
.cmd("edit.header_footer")
.with(schema(
json!({
"doc": doc(),
"pages": pages("to mark (default: all)"),
"update": { "type": "string", "minLength": 1, "description": "The id doc_header_footers lists for the header and footer to change; refused once that one has been changed or removed. Not with replace." },
"header_left": { "type": "string" }, "header_center": { "type": "string" }, "header_right": { "type": "string" },
"footer_left": { "type": "string" }, "footer_center": { "type": "string" }, "footer_right": { "type": "string" },
"font": { "type": "string", "enum": ["Helvetica", "Times", "Courier"] },
@@ -1310,6 +1311,10 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("edit.background")
.with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])),
// No command: edit.header_footer.update changes the document, and this only lists.
t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `id` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded (left out, with `text_withheld`, when the document does not allow copying). Lists those PdfCraft recorded settings for, in page order; older ones and other tools' are left out. An id names its header and footer wherever it moves and whatever else changes, until that one is changed or removed (or PdfCraft restarts); an update with it after that is refused, even once one with the same settings is added again (that one gets a new id).")
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_remove_marks", "Remove header & footer, watermark, background or printer marks", "Remove every header and footer, watermark, background or printer marks PdfCraft (or a compatible tool) added. Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background", "printer_marks"] } }), &["doc", "kind"])),
@@ -1448,10 +1453,10 @@ pub fn tools() -> Vec<ToolDef> {
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
.cmd("form.merge_data")
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; AcroForm replies consume ordered answers; missing replies cancel input or use the alert button set's safe default), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.")
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers (on an XFA button only its message boxes do, xfa.host.messageBox, $host.messageBox and app.alert; its xfa.host.response and app.response return null and take none), each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.")
.cmd("tools.js_console")
.with(schema(
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and alert answers; strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects an alert default (OK, Cancel or No, by button set)."} }),
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and message box answers (every message box takes one, OK-only ones too; an XFA button's responses take none; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }),
&["doc", "script"],
)),
t(
@@ -1859,8 +1864,18 @@ pub(crate) fn find(name: &str) -> Option<&'static ToolDef> {
TOOLS.iter().find(|t| t.name == name)
}
/// Commands a tool runs besides its own [`ToolDef::command`], each with the argument that makes
/// the tool do what the command does: Update header & footer is `doc_header_footer`'s `update`.
const MORE_COMMANDS: &[(&str, &str, &str)] = &[("edit.header_footer.update", "doc_header_footer", "update")];
pub(crate) fn tool_for_command(id: &str) -> Option<&'static str> {
TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name)
let more = || MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(_, tool, _)| *tool);
TOOLS.iter().find(|t| t.command == Some(id)).map(|t| t.name).or_else(more)
}
/// The argument command `id` needs, when its tool does something else without it.
pub(crate) fn command_needs(id: &str) -> Option<&'static str> {
MORE_COMMANDS.iter().find(|(command, ..)| *command == id).map(|(.., arg)| *arg)
}
/// Reject unknown and missing arguments (types are checked when each value is read).
@@ -1878,3 +1893,18 @@ pub(crate) fn check_args(def: &ToolDef, args: &Value) -> Result<(), ToolError> {
}
Ok(())
}
#[cfg(test)]
mod tests {
/// Each extra command is a registered one, run by a tool that takes the argument it needs.
#[test]
fn more_commands_name_real_commands_tools_and_arguments() {
for (command, tool, arg) in super::MORE_COMMANDS {
assert!(pdfcraft_engine::commands::command(command).is_some(), "{command} is not registered");
assert!(super::TOOLS.iter().all(|t| t.command != Some(*command)), "{command} already has a tool");
let def = super::find(tool).unwrap_or_else(|| panic!("{tool} is not a tool"));
assert!(def.input_schema["properties"].get(*arg).is_some(), "{tool} takes no {arg}");
assert_eq!(super::tool_for_command(command), Some(*tool));
}
}
}
+256
View File
@@ -3275,6 +3275,11 @@ fn copy_restricted_text_stays_in_the_document() {
}
let restyled = ok(&mut a, "text_edit", json!({ "doc": re, "page": 1, "paragraph": 1, "size": 30 }));
assert!(!restyled.to_string().contains("Page"), "{restyled}");
// A header's text is listed only where copying is allowed: its index and pages still are.
ok(&mut a, "doc_header_footer", json!({ "doc": re, "pages": [1], "header_left": "HEADERTEXT" }));
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": re }));
assert!(!listed.to_string().contains("HEADERTEXT") && listed["text_withheld"].is_string(), "{listed}");
assert_eq!(listed["header_footers"][0]["pages"], json!([1]));
// A path that would carry the page's words OUT of the document — the editable output, or
// the review word list — is refused on a copy-restricted document (no engines needed).
match a.call("ocr_recognize", &json!({ "doc": re, "output_mode": "editable", "out": "copy.pdf" })) {
@@ -3914,6 +3919,127 @@ fn duplicating_and_cropping_through_tools() {
assert!(matches!(a.call("page_set_box", &json!({ "doc": doc, "rect": [0, 0, 10, 10] })), Err(ToolError::InvalidArgs(_))));
}
#[test]
fn header_footer_update_changes_the_one_named() {
let dir = workdir("marks-update");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "header_left": "FIRST" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2, 3], "header_left": "SECOND" }));
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(listed["header_footers"][0]["pages"], json!([1]));
let second = &listed["header_footers"][1];
assert_eq!((&second["pages"], &second["text"]), (&json!([2, 3]), &json!({ "header_left": "SECOND" })));
assert!(second["id"].as_str().is_some_and(|id| !id.is_empty()), "{second}");
let first = listed["header_footers"][0]["id"].clone();
assert_ne!(first, second["id"]);
// THIRD shares page 1 with FIRST and must stay.
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" }));
let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": first, "header_left": "CHANGED" }));
assert_eq!(updated["header_footers"], ok(&mut a, "doc_header_footers", json!({ "doc": doc }))["header_footers"], "the ids as they are now");
let texts = page_text(&mut a, doc);
assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}");
assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}");
assert!(texts[1].contains("SECOND") && !texts[1].contains("CHANGED"), "{texts:?}");
// Given pages, the update goes there instead: it leaves every page the old one was on, and
// the other header and footer on those pages stays.
let changed = header_footer_id(&updated, "CHANGED");
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": changed, "pages": [2], "header_left": "MOVED" }));
let texts = page_text(&mut a, doc);
assert!(!texts[0].contains("CHANGED") && !texts[0].contains("MOVED") && texts[0].contains("THIRD"), "{texts:?}");
assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "{texts:?}");
assert!(!texts[2].contains("MOVED") && texts[2].contains("SECOND"), "{texts:?}");
let moved = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "MOVED");
for bad in [
json!({ "doc": doc, "update": "no-such-id", "header_left": "X" }),
json!({ "doc": doc, "update": 1, "header_left": "X" }),
json!({ "doc": doc, "update": moved, "replace": true, "header_left": "X" }),
] {
assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}");
}
// The Update command runs the update, and only with an id: without one, the tool would add
// a header and footer instead.
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
let no_id = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "header_left": "NO ID" } });
assert!(matches!(a.call("command_run", &no_id), Err(ToolError::InvalidArgs(_))));
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), listed, "nothing changed");
let third = header_footer_id(&listed, "");
let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": third, "header_left": "VIA COMMAND" } });
ok(&mut a, "command_run", by_command);
let texts = page_text(&mut a, doc);
assert!(texts[0].contains("VIA COMMAND") && !texts[0].contains("THIRD"), "{texts:?}");
assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "the others stay: {texts:?}");
}
/// The `id` a `doc_header_footers` (or update) result lists for the header and footer whose
/// header_left is `text` ("" for one without).
fn header_footer_id(listed: &Value, text: &str) -> Value {
let marks = listed["header_footers"].as_array().unwrap();
let mark = marks.iter().find(|m| m["text"]["header_left"].as_str().unwrap_or("") == text).unwrap_or_else(|| panic!("no {text:?} in {listed}"));
mark["id"].clone()
}
/// A selection names its header and footer, never a place in the list (#5785). After the list
/// changes under it (another one added in front, another moved to other pages), an update with an
/// id taken earlier changes only that one; with the id of one changed since, it is refused and
/// nothing changes. With list indices, both would have reached a different header and footer.
/// Equal settings don't make the same one either: an id taken before its header and footer was
/// removed is refused after one with the same settings is added again.
#[test]
fn header_footer_update_never_reaches_another_one() {
let dir = workdir("marks-update-stale");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2], "header_left": "EARLY" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "LATE" }));
// The selection: both ids, as listed (in page order, EARLY first).
let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
let (early, late) = (header_footer_id(&listed, "EARLY"), header_footer_id(&listed, "LATE"));
assert_eq!((&listed["header_footers"][0]["id"], &listed["header_footers"][1]["id"]), (&early, &late));
// The list changes: a new one comes first, and LATE moves to page 1 (a new id, and now listed
// ahead of EARLY too).
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "NEW" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": late, "pages": [1], "header_left": "LATE MOVED" }));
let now = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(now["header_footers"].as_array().unwrap().len(), 3, "{now}");
assert_eq!(now["header_footers"][2]["id"], early, "EARLY is listed last, and NEW where EARLY was: {now}");
// LATE's id is stale: refused, and no header and footer changes.
let before = page_text(&mut a, doc);
let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": late, "header_left": "WRONG" }));
assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}");
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), now, "nothing changed");
assert_eq!(page_text(&mut a, doc), before);
// EARLY's id still names EARLY alone, though another now sits where it was listed.
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": early, "header_left": "EARLY CHANGED" }));
let texts = page_text(&mut a, doc);
assert!(texts[1].contains("EARLY CHANGED"), "{texts:?}");
assert!(texts[0].contains("LATE MOVED") && texts[0].contains("NEW") && !texts[0].contains("EARLY"), "{texts:?}");
assert!(!texts[2].contains("EARLY") && !texts[2].contains("LATE"), "{texts:?}");
// Removed, and then added again with the same settings on another page, without a listing in
// between: that is a new header and footer. The id taken before the removal names none, so it
// is refused and the new one stays as it is.
let gone = header_footer_id(&ok(&mut a, "doc_header_footers", json!({ "doc": doc })), "EARLY CHANGED");
ok(&mut a, "doc_remove_marks", json!({ "doc": doc, "kind": "header_footer" }));
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [3], "header_left": "EARLY CHANGED" }));
let recreated = ok(&mut a, "doc_header_footers", json!({ "doc": doc }));
assert_eq!(recreated["header_footers"].as_array().unwrap().len(), 1, "{recreated}");
assert_ne!(header_footer_id(&recreated, "EARLY CHANGED"), gone, "a new id: {recreated}");
let before = page_text(&mut a, doc);
assert!(before[2].contains("EARLY CHANGED") && !before[1].contains("EARLY"), "{before:?}");
let stale = a.call("doc_header_footer", &json!({ "doc": doc, "update": gone, "header_left": "WRONG" }));
assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("list them again")), "{stale:?}");
assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), recreated, "the recreated one is unchanged");
assert_eq!(page_text(&mut a, doc), before);
// Its own id, listed after it was added, reaches it.
let fresh = header_footer_id(&recreated, "EARLY CHANGED");
ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": fresh, "header_left": "RECREATED CHANGED" }));
assert!(page_text(&mut a, doc)[2].contains("RECREATED CHANGED"));
}
#[test]
fn headers_watermarks_and_backgrounds_through_tools() {
let dir = workdir("marks");
@@ -8899,6 +9025,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() {
assert_eq!(piece_info("small.pdf"), ["Illustrator"]);
}
#[test]
fn a_trust_list_is_off_until_loaded_through_sign_trust() {
let dir = workdir("trust_list");
let mut a = auto(&dir);
ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" }));
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" }));
let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string();
assert_eq!(status(&mut a), "unknown", "nothing trusted by default");
// Default: no list.
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0));
// A trust list file (the certificate as DER), loaded by path.
let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap();
std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap();
let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" }));
assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List");
assert_eq!(t["trust_lists"][0]["certificates"], 1);
assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates");
assert_eq!(status(&mut a), "valid");
// Bad input is refused and leaves the list as it was.
std::fs::write(dir.join("junk.der"), b"not certificates").unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_))));
// A file over the size limit (sparse, so cheap) is refused without being read whole.
let big = std::fs::File::create(dir.join("big.der")).unwrap();
big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_))));
assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root");
assert_eq!(status(&mut a), "valid");
// Removing it makes the signer unknown again.
assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0));
assert_eq!(status(&mut a), "unknown");
// One call can change everything at once (and revalidates once).
let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" }));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1)));
// A bad argument changes nothing, not even what came before it in the same call.
ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false }));
for bad in [
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }),
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }),
] {
assert!(a.call("sign_trust", &bad).is_err(), "{bad}");
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}");
}
assert_eq!(status(&mut a), "unknown");
}
#[test]
fn optimizing_through_tools() {
let dir = workdir("optimize");
@@ -9953,6 +10132,47 @@ fn merging_form_data_into_a_spreadsheet() {
assert_eq!(std::fs::read_to_string(dir.join("report.csv")).unwrap(), "City\nParis\nOslo\nOslo\n");
}
#[test]
fn merging_form_data_counts_a_quoted_header_as_one_column() {
let dir = workdir("merge-data-quoted-header");
let mut a = auto(&dir);
let xfdf = |name: &str| {
format!(
r#"<?xml version="1.0" encoding="UTF-8"?><xfdf xmlns="http://ns.adobe.com/xfdf/"><fields><field name="{name}"><value>Checked</value></field></fields></xfdf>"#
)
};
// A comma or a quote in a name makes it a quoted CSV cell, still one column.
for (file, name) in [
("comma.xfdf", "Shipping, notes"),
("quote.xfdf", "Say &quot;hi&quot;, ok"),
("plain.xfdf", "Shipping notes"),
("lf.xfdf", "a&#10;b"),
("tab.xfdf", "a&#9;b"),
] {
std::fs::write(dir.join(file), xfdf(name)).unwrap();
let out = format!("{file}.csv");
let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}");
}
// A field with an empty name is one column, not the empty header of a file without fields.
std::fs::write(dir.join("noname.xfdf"), xfdf("")).unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["noname.xfdf"], "path": "noname.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{r}");
assert_eq!(std::fs::read_to_string(dir.join("noname.csv")).unwrap(), "\nChecked\n");
// Files without fields: no column.
std::fs::write(dir.join("empty.xfdf"), r#"<?xml version="1.0" encoding="UTF-8"?><xfdf xmlns="http://ns.adobe.com/xfdf/"><fields/></xfdf>"#)
.unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["empty.xfdf"], "path": "empty.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(0)), "{r}");
assert_eq!(std::fs::read_to_string(dir.join("empty.csv")).unwrap(), "\n\n");
// Two files with different names, one of them quoted: three columns in all.
std::fs::write(dir.join("a.xfdf"), xfdf("A, B")).unwrap();
std::fs::write(dir.join("b.xfdf"), xfdf("C")).unwrap();
std::fs::write(dir.join("c.xfdf"), xfdf("D")).unwrap();
let r = ok(&mut a, "form_merge_data", json!({ "paths": ["a.xfdf", "b.xfdf", "c.xfdf"], "path": "three.csv" }));
assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(3), Some(3)), "{r}");
}
#[test]
fn field_actions_through_tools() {
let dir = workdir("field-actions");
@@ -11521,6 +11741,42 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() {
assert_eq!(r["alerts"], json!([{ "message": "Hello 4", "title": null, "icon": "error", "buttons": "ok" }]));
}
/// An XFA button that asks Yes or No branches on the answer `js_run` gives, in JavaScript and
/// FormCalc alike, and without one takes the No branch (#4291).
#[test]
fn js_run_answers_an_xfa_buttons_message_boxes() {
let dir = workdir("xfa-answers");
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"qty.rawValue = xfa.host.messageBox("Clear?", "Order form", 2, 2) == 4 ? 0 : 7;"#,
)
.replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 1) == 1) then qty = 50 else qty = 9 endif"#);
std::fs::write(dir.join("asking.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
let mut a = auto(&dir).with_xfa_time_scale(100);
let doc = ok(&mut a, "doc_open", json!({ "path": "asking.pdf" }))["doc"].as_u64().unwrap();
let qty = |a: &mut Automation| {
let f = ok(a, "form_fields", json!({ "doc": doc }));
f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "qty").unwrap()["value"].clone()
};
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["4"] }));
assert!(r["error"].is_null(), "{r}");
assert_eq!(r["alerts"], json!([{ "message": "Clear?", "title": "Order form", "icon": "question", "buttons": "yes_no" }]));
assert_eq!(qty(&mut a), "0");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["3"] }));
assert_eq!(qty(&mut a), "7");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": ["1"] }));
assert_eq!(qty(&mut a), "50");
// No answer: No, and Cancel.
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" }));
assert_eq!(qty(&mut a), "7");
ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": [null] }));
assert_eq!(qty(&mut a), "9");
// An answer the buttons can't give is the script's error, naming it.
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["2"] }));
assert!(r["error"].as_str().is_some_and(|e| e.contains("message box 1 (2)")), "{r}");
}
/// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the
/// change scripts, then the click scripts, a radio group's before those of the button now on.
#[test]
+156 -3
View File
@@ -104,11 +104,96 @@ pub(super) fn draw_laid_shaped(
Ok(())
}
/// Wrap each paragraph using advances from the face that will actually draw it.
fn wrap_measured(t: &AddedText, measure: impl Fn(&str) -> Result<f64, EditError>) -> Result<Vec<(String, usize)>, EditError> {
let width = (t.rect[2] - t.rect[0]).abs().max(t.size);
let space = if t.text.contains(' ') { measure(" ")? } else { 0.0 };
let mut out = Vec::new();
for (paragraph, text) in t.text.split('\n').enumerate() {
let mut words = text.split(' ');
let mut line = words.next().unwrap_or_default().to_string();
let mut line_width = measure(&line)?;
for word in words {
let word_width = measure(word)?;
if !line.is_empty() && line_width + space + word_width > width {
out.push((std::mem::take(&mut line), paragraph));
line_width = 0.0;
} else {
line.push(' ');
line_width += space;
}
line.push_str(word);
line_width += word_width;
}
out.push((line, paragraph));
}
Ok(out)
}
/// Shape complex text with the selected PDF font program. The output CIDs map to
/// shaped glyphs. ActualText keeps each line in logical Unicode order for copying.
fn draw_selected_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, font: &Dict, mut out: Vec<u8>) -> Result<DrawnItem, EditError> {
use pdfcraft_fonts::source_shaping::{ShapedRun, shape};
let bytes = pdfcraft_fonts::pdf::embedded_sfnt(doc, font)
.ok_or_else(|| EditError::Invalid("the selected PDF font has no embedded font program for shaping; choose an installed font".into()))?;
let width = |run: &ShapedRun| run.advance * t.size + t.char_spacing * run.glyphs.iter().filter(|g| !g.text.is_empty()).count() as f64;
let lines = wrap_measured(t, |word| shape(&bytes, word).map(|run| width(&run)).map_err(EditError::Invalid))?;
let runs = lines.iter().map(|(line, _)| shape(&bytes, line).map_err(EditError::Invalid)).collect::<Result<Vec<_>, _>>()?;
let mappings: Vec<_> = runs.iter().flat_map(|run| run.glyphs.iter().map(|g| (g.text.clone(), g.id))).collect();
let mut fonts = Dict::new();
let family = font.get(b"BaseFont").and_then(Object::as_name).and_then(|name| std::str::from_utf8(name).ok()).unwrap_or("Selected");
let embedded = pdfcraft_fonts::embedding::embed_mapping(doc, &mut fonts, &bytes, family, &mappings).map_err(EditError::Invalid)?;
let program = fonts.get(embedded.as_bytes()).cloned().ok_or_else(|| EditError::Invalid("missing shaped font".into()))?;
// Own only the mapping for this item. The selected page resource remains available
// to other items after this one is removed. own_fonts cleans up our PCAr names.
let resource = crate::text::unique_font_name(taken, "PCArSource");
let mut used = Dict::new();
used.set(resource.as_bytes().to_vec(), program);
let mut res = Dict::new();
res.set(b"Font".to_vec(), Object::Dict(used));
let mut rect = norm(t.rect);
rect[1] = rect[3] - runs.len().max(1) as f64 * t.size * 1.2;
let paragraphs: Vec<_> = lines.iter().map(|(_, paragraph)| *paragraph).collect();
let mut cid = 0;
for (i, ((line, _), run)) in lines.iter().zip(&runs).enumerate() {
let rtl = unicode_bidi::get_base_direction(line.as_str()) == unicode_bidi::Direction::Rtl;
let (x, word_spacing) = placed(t, rect, &paragraphs, i, width(run), line.matches(' ').count(), rtl);
let y = rect[3] - (i as f64 * 1.2 + 0.95) * t.size;
let logical: String = line.encode_utf16().map(|unit| format!("{unit:04X}")).collect();
out.extend(format!("/Span <</ActualText <FEFF{logical}>>> BDC\nBT /{resource} {} Tf {}\n", n(t.size), t.fill_op()).bytes());
let mut extra = 0.0;
let mut after_cluster = 0.0;
for glyph in &run.glyphs {
if !glyph.text.is_empty() {
extra += after_cluster;
after_cluster = t.char_spacing + word_spacing * glyph.text.matches(' ').count() as f64;
}
let gx = x + glyph.position[0] * t.size + extra;
let gy = y + glyph.position[1] * t.size;
cid += 1;
out.extend(format!("1 0 0 1 {} {} Tm <{cid:04X}> Tj\n", n(gx), n(gy)).bytes());
}
out.extend_from_slice(b"ET\nEMC\n");
}
out.extend_from_slice(b"Q\n");
Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(rect) })
}
/// Content and resources produced by drawing an added item.
pub(super) struct DrawnItem {
/// Content stream operations.
pub stream: Vec<u8>,
/// Added resources for fonts or images.
pub resources: Dict,
/// Adjusted bounding box if drawn with custom font metrics.
pub custom_rect: Option<[f64; 4]>,
}
/// Content and resources for an item; `view` maps display space to user space. `taken` holds the
/// page's font names. `existing`: the item is being replaced, so a build without the Arabic or
/// Hebrew face keeps drawing that text as `?`, as before it was supported, rather than refusing to
/// move it.
pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec<u8>, Dict), EditError> {
pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<DrawnItem, EditError> {
let mut res = Dict::new();
let mut out = format!(
"q {} {} {} {} {} {} cm\n",
@@ -122,6 +207,70 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
.into_bytes();
match c {
Content::Text(t) => {
if let Some(resource) = &t.font_resource {
let font_obj = taken
.get(resource.as_bytes())
.cloned()
.ok_or_else(|| EditError::Invalid(format!("font resource /{resource} not found on page")))?;
let font_dict = doc
.resolve(&font_obj)
.as_dict()
.cloned()
.ok_or_else(|| EditError::Invalid(format!("font resource /{resource} is not a dictionary")))?;
if pdfcraft_fonts::source_shaping::required(&t.text) {
return draw_selected_shaped(doc, t, taken, &font_dict, out);
}
let metrics = pdfcraft_fonts::pdf::Metrics::from_dict(doc, &font_dict);
let mut fonts = Dict::new();
fonts.set(resource.as_bytes().to_vec(), font_obj);
res.set(b"Font".to_vec(), Object::Dict(fonts));
let all = wrap_measured(t, |s| {
let encoded = metrics.encode(s).ok_or_else(|| {
let missing = s.chars().find(|c| metrics.encode(&c.to_string()).is_none()).unwrap_or('?');
EditError::Invalid(format!("the selected font /{resource} cannot show U+{:04X}", u32::from(missing)))
})?;
Ok(metrics.codes(&encoded).iter().map(|(code, _)| metrics.width(*code) * t.size).sum::<f64>()
+ t.char_spacing * s.chars().count() as f64)
})?;
let norm_r = norm(t.rect);
let h = all.len().max(1) as f64 * t.size * 1.2;
let r = [norm_r[0], norm_r[3] - h, norm_r[2], norm_r[3]];
// Painted like standard-font text: its gray or CMYK ink when it has one, else RGB.
out.extend_from_slice(b"BT ");
out.extend(pdfcraft_content::serialize_ops(&[pdfcraft_content::Op::new(
"Tf",
vec![Object::name(resource.as_str()), Object::Real(t.size)],
)]));
out.extend(format!("{}\n", t.fill_op()).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
let paragraphs: Vec<usize> = all.iter().map(|(_, p)| *p).collect();
const HEX_DIGITS: &[u8; 16] = b"0123456789ABCDEF";
for (i, (line, _)) in all.iter().enumerate() {
let encoded = metrics.encode(line).ok_or_else(|| {
let unencodable = line.chars().find(|c| metrics.encode(&c.to_string()).is_none()).unwrap_or('?');
EditError::Invalid(format!(
"the selected font resource {resource} cannot show '{unencodable}' (U+{:04X})",
u32::from(unencodable)
))
})?;
let glyph_w: f64 = metrics.codes(&encoded).iter().map(|(c, _)| metrics.width(*c) * t.size).sum();
let w = glyph_w + t.char_spacing * line.chars().count() as f64;
let spaces = line.matches(' ').count();
let (x, tw) = placed(t, r, &paragraphs, i, w, spaces, false);
let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
out.extend(format!("1 0 0 1 {} {} Tm {} Tw <", n(x), n(y), n(tw)).bytes());
for &b in &encoded {
out.push(HEX_DIGITS[(b >> 4) as usize]);
out.push(HEX_DIGITS[(b & 0x0F) as usize]);
}
out.extend_from_slice(b"> Tj\n");
}
out.extend_from_slice(b"ET\n");
out.extend_from_slice(b"Q\n");
return Ok(DrawnItem { stream: out, resources: res, custom_rect: Some(r) });
}
let base = t.family.base_font(t.bold, t.italic);
let name = font_name(base);
let mut font = Dict::new();
@@ -141,7 +290,7 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
draw_shaped(doc, t, taken, &mut fonts, &mut out)?;
res.set(b"Font".to_vec(), Object::Dict(fonts));
out.extend_from_slice(b"Q\n");
return Ok((out, res));
return Ok(DrawnItem { stream: out, resources: res, custom_rect: None });
}
res.set(b"Font".to_vec(), Object::Dict(fonts));
let r = text_rect(t);
@@ -193,9 +342,10 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
}
}
out.extend_from_slice(b"Q\n");
Ok((out, res))
Ok(DrawnItem { stream: out, resources: res, custom_rect: None })
}
/// Extracts the parameters of an added item into a `/PCAdded` dictionary.
pub(super) fn params(c: &Content) -> Dict {
let mut d = Dict::new();
let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect());
@@ -204,6 +354,9 @@ pub(super) fn params(c: &Content) -> Dict {
d.set(b"Kind".to_vec(), Object::name("Text"));
d.set(b"Text".to_vec(), PdfString::text(&t.text));
d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
if let Some(font_resource) = &t.font_resource {
d.set(b"FontResource".to_vec(), Object::name(font_resource));
}
d.set(b"Size".to_vec(), Object::Real(t.size));
d.set(b"Color".to_vec(), arr(&t.color));
// The ink beside its RGB look, which a reader that knows no ink keeps showing.
+3
View File
@@ -194,6 +194,9 @@ pub(super) fn is_hebrew(c: char) -> bool {
/// draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text editor
/// keeps it open.
pub fn first_undrawable(t: &AddedText) -> Option<char> {
if t.font_resource.is_some() {
return None;
}
if t.text.chars().any(is_thai) {
if let Some(c) = t.text.chars().find(|c| is_thai(*c) && !pdfcraft_fonts::thai_has(*c)) {
return Some(c);
+30 -20
View File
@@ -28,12 +28,14 @@ fn read_value<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> T) -> T
}
}
/// Parses an added item dictionary (`/PCAdded`) into [`Content`].
fn parse(doc: &Document, d: &Dict) -> Option<Content> {
let r = nums(doc, d.get(b"Rect"));
let rect: [f64; 4] = r.try_into().ok()?;
match d.name(b"Kind")? {
b"Text" => {
let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica"));
let font_resource = d.name(b"FontResource").map(|n| String::from_utf8_lossy(n).into_owned());
let c = nums(doc, d.get(b"Color"));
let text = d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();
let align = align_from(d.int(b"Align"));
@@ -59,6 +61,7 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
aligns: crate::paragraph_align::tidy(aligns, align),
// Items written before character spacing have none.
char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
font_resource,
};
// An ink whose look isn't the stored colour (a file edited by hand) is none.
t.drop_stale_ink();
@@ -155,6 +158,7 @@ pub fn scan_markers(doc: &Document) -> MarkerScan {
scan
}
/// Validates that `c` has finite positions, sensible dimensions, and encodable text.
fn validate(c: &Content) -> Result<(), EditError> {
let r = c.rect();
if !r.iter().all(|v| v.is_finite()) {
@@ -179,22 +183,24 @@ fn validate(c: &Content) -> Result<(), EditError> {
if (r[2] - r[0]).abs() < 1.0 {
return Err(EditError::Invalid("the text box is too narrow".into()));
}
if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() {
return Err(thai_error(GlyphError::NoFont, &t.text));
}
// Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new
// item is refused with what's missing, and one that already holds Arabic stays movable.
// Everything else in it is drawn in the standard font, so it still has to fit.
let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() {
t.text.split('\n').find_map(|line| {
line.chars()
.find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c)))
})
} else {
first_undrawable(t)
};
if let Some(c) = undrawable {
return Err(crate::undrawable(c));
if t.font_resource.is_none() {
if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() {
return Err(thai_error(GlyphError::NoFont, &t.text));
}
// Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new
// item is refused with what's missing, and one that already holds Arabic stays movable.
// Everything else in it is drawn in the standard font, so it still has to fit.
let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() {
t.text.split('\n').find_map(|line| {
line.chars()
.find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c)))
})
} else {
first_undrawable(t)
};
if let Some(c) = undrawable {
return Err(crate::undrawable(c));
}
}
}
Content::Image(_) => {
@@ -221,11 +227,11 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> R
drop_fonts(doc, &mut pres, &own_fonts(doc, r));
}
let taken = pres.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let (content, res) = draw(doc, c, view, &taken, obj.is_some())?;
let drawn = draw(doc, c, view, &taken, obj.is_some())?;
if obj.is_none() {
crate::check_on_top(doc, p)?;
}
for (k, v) in res.iter() {
for (k, v) in drawn.resources.iter() {
let mut sub = pres.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default();
for (n2, o) in v.as_dict().into_iter().flat_map(|d| d.iter()) {
sub.set(n2.clone(), o.clone());
@@ -236,11 +242,15 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> R
let mut sd = Dict::new();
sd.set(b"PCMark".to_vec(), Object::name(TAG));
let mut added = params(c);
if let Some(rect) = drawn.custom_rect {
let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect());
added.set(b"Rect".to_vec(), arr(&rect));
}
if user_unit != 1.0 {
added.set(b"UserUnit".to_vec(), Object::Real(user_unit));
}
sd.set(b"PCAdded".to_vec(), Object::Dict(added));
let stream = Stream::flate(sd, &content);
let stream = Stream::flate(sd, &drawn.stream);
match obj {
Some(r) => {
doc.set(r, Object::Stream(stream));
@@ -249,7 +259,7 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> R
None => {
// place_tagged appends a new stream; recover its reference.
let p = page_list(doc).swap_remove(page);
place_tagged(doc, &p, TAG, content.clone(), false)?;
place_tagged(doc, &p, TAG, drawn.stream.clone(), false)?;
let p = page_list(doc).swap_remove(page);
let r = contents(doc, &p)?.last().and_then(Object::as_ref).ok_or_else(|| EditError::Invalid("could not add the content".into()))?;
doc.set(r, Object::Stream(stream));
+3
View File
@@ -165,6 +165,8 @@ pub struct AddedText {
pub align: Align,
/// Extra space after every character, in points: the PDF's character spacing (`Tc`).
pub char_spacing: f64,
/// Explicit page font resource for custom or embedded Unicode fonts (e.g. from `RegisterTextFont`).
pub font_resource: Option<String>,
/// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;
/// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).
pub aligns: Vec<Option<Align>>,
@@ -229,6 +231,7 @@ impl Default for AddedText {
align: Align::Left,
aligns: Vec::new(),
char_spacing: 0.0,
font_resource: None,
}
}
}
+276 -21
View File
@@ -1,14 +1,14 @@
use pdfcraft_fonts::shaped_text::{is_thai, thai_refusal, thai_width};
use super::marks::{
Background, Context, HeaderFooter, MarkKind, MarkText, Watermark, add_picture_resource, bates_start, expand, matrix_number, n, picture, rgb,
shrink_matrix,
Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkText, SETTINGS_KEY, Watermark, add_picture_resource, bates_start, expand,
matrix_number, n, picture, read, rgb, shrink_matrix,
};
use super::place::{
END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place,
place_inside_wrapper, stream_tag, undrawable, wrapper_role,
END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, content_list, contents, first_wrapper, free_font_name, isolation,
page_fonts, page_list, place, place_at, place_inside_wrapper, stream_tag, undrawable, wrapper_role,
};
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
use super::{Document, EditError, ObjRef, Object, added, backdrop, helvetica_width};
/// Commit one complete mark operation only after every selected page succeeds. The snapshot
/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table
@@ -25,24 +25,182 @@ fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document)
/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic:
/// on error, the document (including earlier selected pages) is unchanged.
pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx))
let replacing = if replace { Replacing::OnThosePages } else { Replacing::Nothing };
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replacing, cx))
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
/// Replace one header and footer: `old` (settings from [`header_footers`]) goes from every page
/// it is on and `hf` is added to `pages`. Any other header or footer stays, on those pages too
/// (#5785). On a page `old` was on, `hf` takes its place among the page's marks, so one added
/// after `old` still draws over it; on the others it goes on top. The whole call is atomic.
pub fn update_header_footer(doc: &mut Document, old: &HeaderFooter, pages: &[usize], hf: &HeaderFooter, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, Replacing::Only(old), cx))
}
/// How many different headers and footers [`header_footers`] lists: enough for any real document,
/// and a limit on the work a file with a different one in every stream can ask for.
const MAX_HEADER_FOOTERS: usize = 256;
/// The settings a content stream records for its header and footer, if it records any.
fn recorded_settings(doc: &Document, stream: &Object) -> Option<HeaderFooter> {
if stream_tag(doc, stream).as_deref() != Some(MarkKind::HeaderFooter.tag()) {
return None;
}
read(doc, stream, |s| HeaderFooter::from_object(doc, s.as_dict()?.get(SETTINGS_KEY)?))
}
/// The most bytes of recorded text one scan of a document converts: the text of hundreds of
/// thousands of real headers, yet a bound on a file that repeats a large one in every stream.
const MAX_SCAN_TEXT: usize = 16 * 1024 * 1024;
/// One scan of a document's headers and footers. A stream, or a settings entry, given by reference
/// is read once however many pages share it, and the text converted in all is bounded
/// ([`MAX_SCAN_TEXT`]): a file repeating its settings can't make listing them slow.
struct Scan {
found: Vec<HeaderFooterMark>,
streams: std::collections::HashMap<ObjRef, Recorded>,
settings: std::collections::HashMap<ObjRef, Recorded>,
budget: usize,
/// Some settings went [`Recorded::Unread`].
unread: bool,
}
/// What a content stream records.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Recorded {
/// No header and footer, or one whose settings can't be read (from before they were recorded,
/// another tool's, or unreadable).
Nothing,
/// Settings past the scan's text budget ([`MAX_SCAN_TEXT`]), not read: they may be any
/// header and footer's, so a listed one may be on more pages than the scan found.
Unread,
/// Settings, listed as `found[k]`, or not listed (`None`) past [`MAX_HEADER_FOOTERS`].
Settings(Option<usize>),
}
impl Scan {
fn of(doc: &Document) -> Self {
let mut scan = Self { found: Vec::new(), streams: Default::default(), settings: Default::default(), budget: MAX_SCAN_TEXT, unread: false };
for (i, page) in page_list(doc).iter().enumerate() {
for o in content_list(doc, page).iter() {
if let Recorded::Settings(Some(k)) = scan.stream(doc, o)
&& let Some(mark) = scan.found.get_mut(k)
&& mark.pages.last() != Some(&i)
{
mark.pages.push(i);
}
}
}
scan
}
fn stream(&mut self, doc: &Document, o: &Object) -> Recorded {
let Object::Ref(r) = o else { return self.read_stream(doc, o) };
if let Some(known) = self.streams.get(r) {
return *known;
}
let recorded = self.read_stream(doc, o);
self.streams.insert(*r, recorded);
recorded
}
fn read_stream(&mut self, doc: &Document, o: &Object) -> Recorded {
if stream_tag(doc, o).as_deref() != Some(MarkKind::HeaderFooter.tag()) {
return Recorded::Nothing;
}
read(doc, o, |s| Some(self.entry(doc, s.as_dict()?.get(SETTINGS_KEY)?))).unwrap_or(Recorded::Nothing)
}
/// A stream's [`SETTINGS_KEY`] entry.
fn entry(&mut self, doc: &Document, value: &Object) -> Recorded {
let Object::Ref(r) = value else { return self.read_settings(doc, value) };
if let Some(known) = self.settings.get(r) {
return *known;
}
let recorded = self.read_settings(doc, value);
self.settings.insert(*r, recorded);
recorded
}
fn read_settings(&mut self, doc: &Document, value: &Object) -> Recorded {
let Some(settings) = HeaderFooter::from_object_within(doc, value, &mut self.budget) else {
// Running out of budget spends all of it.
if self.budget == 0 {
self.unread = true;
return Recorded::Unread;
}
return Recorded::Nothing;
};
if let Some(k) = self.found.iter().position(|m| m.settings == settings) {
return Recorded::Settings(Some(k));
}
if self.found.len() >= MAX_HEADER_FOOTERS {
return Recorded::Settings(None);
}
self.found.push(HeaderFooterMark { pages: Vec::new(), settings });
Recorded::Settings(Some(self.found.len() - 1))
}
}
/// The headers and footers that record their settings, in page order, each with the pages it is
/// on. Marks from before settings were recorded, or from another tool, are not listed. In a file
/// recording more text than one scan reads ([`MAX_SCAN_TEXT`]) a mark may be on more pages than
/// it lists, and [`remove_header_footer`] refuses rather than leave it on the others.
pub fn header_footers(doc: &Document) -> Vec<HeaderFooterMark> {
Scan::of(doc).found
}
/// The header and footer added last to page `page` (0-based): `Some(None)` when it records no
/// settings (from before they were recorded, or another tool), `None` when the page has none.
/// Each mark's own stream goes on top of the page's content, so the last one is the newest; a
/// shrink goes underneath, inside the wrapper, and is never last.
pub fn newest_header_footer(doc: &Document, page: usize) -> Option<Option<HeaderFooter>> {
let page = page_list(doc).into_iter().nth(page)?;
let content = content_list(doc, &page);
let newest = content.iter().rev().find(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()))?;
Some(recorded_settings(doc, newest))
}
/// Where in a page's content list `list` the header and footer recorded with `old` draws: the
/// last stream that records `old`, not counting shrinks, which go first inside the wrapper
/// ([`place_inside_wrapper`]) and draw nothing. `None` when it is not on the page.
fn mark_slot(doc: &Document, list: &[Object], old: &HeaderFooter) -> Option<usize> {
let shrinks = first_wrapper(doc, list).map_or(0..0, |open| {
let start = open.saturating_add(1);
let run = list.iter().skip(start).take_while(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag())).count();
start..start.saturating_add(run)
});
list.iter().enumerate().rev().find(|(i, o)| !shrinks.contains(i) && recorded_settings(doc, o).as_ref() == Some(old)).map(|(i, _)| i)
}
/// Pages (0-based) with a header and footer that records no settings: Update can only replace
/// those page-wide, as it did before settings were recorded.
pub fn unrecorded_header_footer_pages(doc: &Document) -> Vec<usize> {
let tagged = |o: &Object| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag());
let mut scan = Scan::of(doc);
page_list(doc)
.iter()
.enumerate()
.filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && scan.stream(doc, o) == Recorded::Nothing))
.map(|(i, _)| i)
.collect()
}
/// Which existing headers and footers an added one takes the place of.
#[derive(Clone, Copy)]
enum Replacing<'a> {
Nothing,
OnThosePages,
Only(&'a HeaderFooter),
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replacing: Replacing, cx: &Context) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if hf.text.iter().all(|t| t.trim().is_empty()) {
return Err(EditError::Invalid("type the header or footer text first".into()));
}
if let Some(why) = hf.text.iter().find_map(|t| thai_refusal(t)) {
return Err(EditError::Invalid(why));
}
if let Some(c) = hf.first_undrawable() {
return Err(undrawable(c));
}
if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) {
return Err(EditError::Invalid("invalid font size or margins".into()));
}
hf.check()?;
// Page numbers count up from start_number, so the last selected page needs the most room.
// Refuse the whole run before drawing anything: headers applied to some pages and then a
// failed page number would leave the document half changed.
@@ -74,9 +232,17 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo
for &i in pages {
check_on_top(doc, &all[i])?;
}
if replace {
remove_marks(doc, pages, MarkKind::HeaderFooter)?;
match replacing {
Replacing::Nothing => {}
Replacing::OnThosePages => {
remove_marks(doc, pages, MarkKind::HeaderFooter)?;
}
Replacing::Only(old) => {
// Where the new one goes, `old` stays for now, to mark its place.
remove_recorded(doc, old, pages)?;
}
}
let settings = hf.to_object();
let all = page_list(doc);
let count = all.len();
let number_of = |k: usize| {
@@ -147,11 +313,22 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo
}
thai.add_to(doc, &page_list(doc)[i])?;
let page = &page_list(doc)[i];
place(doc, page, MarkKind::HeaderFooter, content, false)?;
let slot = match replacing {
Replacing::Only(old) => mark_slot(doc, &content_list(doc, page), old),
Replacing::Nothing | Replacing::OnThosePages => None,
};
let mark = match slot {
Some(at) => place_at(doc, page, at, MarkKind::HeaderFooter, content)?,
None => place(doc, page, MarkKind::HeaderFooter, content, false)?,
};
doc.update_dict(mark, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?;
if let Some(Some(m)) = shrinks.get(k) {
let cm = format!("{} cm\n", m.map(matrix_number).join(" "));
let page = &page_list(doc)[i];
place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?;
// The shrink goes with its header: it records the same settings, so Update takes it too.
if let Some(shrink) = place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())? {
doc.update_dict(shrink, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?;
}
}
}
Ok(())
@@ -301,6 +478,78 @@ fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background,
/// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where
/// it isn't are [`backdrops_left_off`].
pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result<usize, EditError> {
remove_matching(doc, pages, kind, |_, _| true, |_, _, _| None)
}
/// Remove the header and footer recorded with `old` from every page it is on, and no other
/// header and footer: what [`update_header_footer`] takes away before it adds the new one in its
/// place. Returns how many mark streams went; an error when no header and footer records `old`
/// any more, or when the document records more header and footer text than one scan reads, so
/// not every page it is on can be known.
pub fn remove_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
remove_recorded(doc, old, &[])
}
/// [`remove_header_footer`], except that on `kept_on` (pages, 0-based) the stream `old` draws
/// with ([`mark_slot`]) stays, for the header and footer replacing it to take its place.
fn remove_recorded(doc: &mut Document, old: &HeaderFooter, kept_on: &[usize]) -> Result<usize, EditError> {
let scan = Scan::of(doc);
if scan.unread {
return Err(EditError::Invalid(
"this document records too much header and footer text to find every page one is on: replace the headers and footers on the pages instead".into(),
));
}
let on = scan.found.into_iter().find(|m| m.settings == *old).map(|m| m.pages);
let on = on.ok_or_else(|| EditError::Invalid("that header and footer is no longer in the document".into()))?;
let kept = |doc: &Document, page: usize, list: &[Object]| if kept_on.contains(&page) { mark_slot(doc, list, old) } else { None };
remove_matching(doc, &on, MarkKind::HeaderFooter, |doc, o| recorded_settings(doc, o).as_ref() == Some(old), kept)
}
/// The pages under the header and footer recorded with `old`, for Update's preview: `old` goes
/// from every page it is on, with everything drawn after it there, which
/// [`over_header_footer`] keeps. Returns how many mark streams of `old` went; an error as
/// [`remove_header_footer`] gives one.
pub fn under_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
for page in page_list(doc) {
let list = content_list(doc, &page);
if let Some(slot) = mark_slot(doc, &list, old)
&& slot.saturating_add(1) < list.len()
{
let mut list = contents(doc, &page)?;
list.truncate(slot.saturating_add(1));
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
}
}
remove_header_footer(doc, old)
}
/// What Update of the header and footer recorded with `old` leaves drawn over the one replacing
/// it, for its preview: each page keeps only what is drawn after `old` (nothing, where `old` is
/// not, as the new one goes on top there) and no annotations, which [`under_header_footer`]'s
/// pages already show. Returns how many pages have anything left.
pub fn over_header_footer(doc: &mut Document, old: &HeaderFooter) -> Result<usize, EditError> {
let mut left = 0;
for page in page_list(doc) {
let list = content_list(doc, &page);
let over: Vec<Object> = mark_slot(doc, &list, old).map(|slot| list.into_iter().skip(slot.saturating_add(1)).collect()).unwrap_or_default();
left += usize::from(!over.is_empty());
doc.update_dict(page.obj, |d| {
d.set(b"Contents".to_vec(), Object::Array(over));
d.remove(b"Annots");
})?;
}
Ok(left)
}
/// [`remove_marks`], only for the mark streams `matches` accepts, and on each page not the one
/// at the place in its content list `kept` names, if any.
fn remove_matching(
doc: &mut Document,
pages: &[usize],
kind: MarkKind,
matches: impl Fn(&Document, &Object) -> bool,
kept: impl Fn(&Document, usize, &[Object]) -> Option<usize>,
) -> Result<usize, EditError> {
let all = page_list(doc);
check(pages, all.len())?;
let mut removed = 0;
@@ -311,7 +560,13 @@ pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Resu
}
let list = contents(doc, page)?;
let before = list.len();
let mut kept: Vec<Object> = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect();
let stays = kept(doc, i, &list);
let mut kept: Vec<Object> = list
.into_iter()
.enumerate()
.filter(|(k, o)| Some(*k) == stays || stream_tag(doc, o).as_deref() != Some(kind.tag()) || !matches(doc, o))
.map(|(_, o)| o)
.collect();
removed += before - kept.len();
// Strip only wrapper pairs whose close ends the list (after stripping the pairs after
// it): nothing comes after them to need the state they restore. Pairs come from the
+5 -2
View File
@@ -83,10 +83,13 @@ mod apply;
mod marks;
mod place;
pub use apply::{add_background, add_header_footer, add_watermark, marks_present, remove_marks};
pub use apply::{
add_background, add_header_footer, add_watermark, header_footers, marks_present, newest_header_footer, over_header_footer, remove_header_footer,
remove_marks, under_header_footer, unrecorded_header_footer_pages, update_header_footer,
};
#[cfg(test)]
use marks::bates_start;
pub use marks::{Background, Context, HeaderFooter, MarkKind, MarkSource, Watermark, expand};
pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand, recorded_header_footer};
use marks::{matrix_number, n};
pub(crate) use place::undrawable;
#[cfg(test)]
+156
View File
@@ -160,6 +160,162 @@ impl HeaderFooter {
}
}
/// One header and footer in a document: its settings and the pages (0-based, ascending) it is on.
/// Marks with the same settings count as one.
#[derive(Clone, Debug, PartialEq)]
pub struct HeaderFooterMark {
pub pages: Vec<usize>,
pub settings: HeaderFooter,
}
/// The entry of a header and footer's content streams that keeps its settings, so Update can tell
/// several apart and fill the dialog with the one chosen (#5785). Drawn text alone can't say
/// which tokens made it. Private to PdfCraft (like `/PCMark`); other readers ignore it.
pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter";
/// The most bytes one recorded text box may take. A dialog box never needs more, and it bounds
/// what listing the headers and footers of a hostile file decodes.
const MAX_RECORDED_TEXT: usize = 16 * 1024;
/// `f` of `o`, or of what it refers to: a direct value is read in place, never copied, so a large
/// one costs nothing until it has been checked. (`Document::resolve` copies a direct value whole.)
pub(crate) fn read<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> Option<T>) -> Option<T> {
match o {
Object::Ref(_) => f(&doc.resolve(o)),
_ => f(o),
}
}
/// An array of exactly `N` numbers, each resolved: a rewriting tool may make any of them indirect.
fn numbers<const N: usize>(doc: &Document, o: &Object) -> Option<[f64; N]> {
read(doc, o, |array| {
let items = array.as_array().filter(|a| a.len() == N)?;
let values: Vec<f64> = items.iter().map(|v| read(doc, v, Object::as_f64)).collect::<Option<_>>()?;
<[f64; N]>::try_from(values).ok()
})
}
impl HeaderFooter {
/// Why [`add_header_footer`] refuses these settings, if it does. A recorded header and footer
/// is listed only when it passes too, so every one Update offers is one OK can apply.
pub(crate) fn check(&self) -> Result<(), EditError> {
if self.text.iter().all(|t| t.trim().is_empty()) {
return Err(EditError::Invalid("type the header or footer text first".into()));
}
// Measured as recorded: a box the listing would refuse to decode must not be added, or it
// could never be listed and updated, only replaced page-wide.
if self.text.iter().any(|t| pdfcraft_cos::PdfString::text(t).bytes.len() > MAX_RECORDED_TEXT) {
return Err(EditError::Invalid(format!("a header or footer box can hold at most {} KB of text", MAX_RECORDED_TEXT / 1024)));
}
if let Some(c) = self.first_undrawable() {
return Err(super::place::undrawable(c));
}
if !(self.font_size.is_finite() && self.font_size > 0.0 && self.font_size <= 200.0 && self.margins.iter().all(|m| m.is_finite() && *m >= 0.0))
{
return Err(EditError::Invalid("invalid font size or margins".into()));
}
Ok(())
}
/// These settings as the [`SETTINGS_KEY`] entry. The colour is recorded as drawn (see `rgb`),
/// so a header added with an out-of-range colour can still be listed and updated.
pub(crate) fn to_object(&self) -> Object {
let reals = |v: &[f64]| Object::Array(v.iter().copied().map(Object::Real).collect());
let drawn = self.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });
let mut d = Dict::new();
d.set(b"Text".to_vec(), Object::Array(self.text.iter().map(|t| Object::String(pdfcraft_cos::PdfString::text(t))).collect()));
d.set(
b"Font".to_vec(),
Object::name(match self.font {
added::Family::Helvetica => "Helvetica",
added::Family::Times => "Times",
added::Family::Courier => "Courier",
}),
);
d.set(b"Size".to_vec(), Object::Real(self.font_size));
d.set(b"Color".to_vec(), reals(&drawn));
d.set(b"Underline".to_vec(), Object::Bool(self.underline));
d.set(b"Margins".to_vec(), reals(&self.margins));
d.set(b"Start".to_vec(), Object::Int(i64::from(self.start_number)));
d.set(b"Shrink".to_vec(), Object::Bool(self.shrink));
Object::Dict(d)
}
/// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog
/// could have written: a file can say anything here.
pub(crate) fn from_object(doc: &Document, o: &Object) -> Option<Self> {
let mut unlimited = usize::MAX;
Self::from_object_within(doc, o, &mut unlimited)
}
/// [`from_object`](Self::from_object), converting at most `budget` bytes of text, which it
/// takes from: `None` once that is spent, leaving it 0 so a scan can tell settings it could not
/// afford from ones it could not read. Bounds what one scan of a document converts.
pub(crate) fn from_object_within(doc: &Document, o: &Object, budget: &mut usize) -> Option<Self> {
#[cfg(test)]
DECODED.with(|n| n.set(n.get() + 1));
// Every value resolved, as a rewriting tool may make any of them indirect, and read in
// place: nothing is copied before it is checked.
read(doc, o, |o| {
let d = o.as_dict()?;
let flag = |key: &[u8]| {
read(doc, d.get(key)?, |v| match v {
Object::Bool(b) => Some(*b),
_ => None,
})
};
// The count and each size are checked before anything is decoded.
let text: Vec<String> = read(doc, d.get(b"Text")?, |texts| {
let texts = texts.as_array().filter(|a| a.len() == 6)?;
texts
.iter()
.map(|t| {
read(doc, t, |t| {
let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?;
let Some(left) = budget.checked_sub(s.bytes.len()) else {
*budget = 0;
return None;
};
*budget = left;
Some(s.to_text())
})
})
.collect()
})?;
let hf = Self {
text: text.try_into().ok()?,
font: read(doc, d.get(b"Font")?, |v| match v.as_name()? {
b"Helvetica" => Some(added::Family::Helvetica),
b"Times" => Some(added::Family::Times),
b"Courier" => Some(added::Family::Courier),
_ => None,
})?,
font_size: read(doc, d.get(b"Size")?, Object::as_f64)?,
color: numbers(doc, d.get(b"Color")?)?,
underline: flag(b"Underline")?,
margins: numbers(doc, d.get(b"Margins")?)?,
start_number: read(doc, d.get(b"Start")?, |v| u32::try_from(v.as_int()?).ok())?,
shrink: flag(b"Shrink")?,
};
let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c));
sane.then_some(hf)
})
}
}
#[cfg(test)]
thread_local! {
/// How many settings entries [`HeaderFooter::from_object_within`] has read on this thread.
pub(crate) static DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The header and footer settings a [`SETTINGS_KEY`] entry records, if it records ones that
/// [`add_header_footer`](crate::add_header_footer) would accept: what redaction matches a
/// header's streams by, however each stores them.
pub fn recorded_header_footer(doc: &Document, value: &Object) -> Option<HeaderFooter> {
HeaderFooter::from_object(doc, value)
}
/// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free,
/// for a page shown `size` (display space) with view matrix `view` (display to user space): an
/// even scale, centred across, the content's bottom on the footer's band.
+45 -17
View File
@@ -306,11 +306,25 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation {
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
/// (appended, after wrapping the original content in q/Q).
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
place_tagged(doc, page, kind.tag(), content, behind)?;
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<ObjRef, EditError> {
let mark = place_tagged(doc, page, kind.tag(), content, behind)?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(())
Ok(mark)
}
/// Put a mark's content on a page in the place of the stream at `at` in its `/Contents`: an
/// earlier mark of the same kind, which drew there in the state the content before it leaves, so
/// the new one needs no wrapper and keeps the old one's place among the page's other marks.
pub(crate) fn place_at(doc: &mut Document, page: &pdfcraft_model::Page, at: usize, kind: MarkKind, content: Vec<u8>) -> Result<ObjRef, EditError> {
let mut list = contents(doc, page)?;
let mark_ref = doc.add(Object::Stream(Stream::flate(tagged(kind.tag()), &content)));
let slot = list.get_mut(at).ok_or_else(|| EditError::Invalid("the mark to replace is no longer on the page".into()))?;
*slot = Object::Ref(mark_ref);
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(mark_ref)
}
#[cfg(test)]
@@ -461,29 +475,43 @@ fn too_deep_on_top() -> EditError {
/// The refusal [`place_tagged`] gives for a mark on top of `page`, checked before an edit changes
/// anything (removing old marks, adding resources) so a refused edit leaves the document as it was.
pub(crate) fn check_on_top(doc: &Document, page: &pdfcraft_model::Page) -> Result<(), EditError> {
let obj = doc.get(page.obj);
let list = match obj.as_dict().and_then(|d| d.get(b"Contents")) {
None => return Ok(()),
Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]),
Some(Object::Array(a)) => a.clone(),
Some(other) => vec![other.clone()],
};
match isolation(doc, &list) {
match isolation(doc, &content_list(doc, page)) {
Isolation::TooDeep => Err(too_deep_on_top()),
_ => Ok(()),
}
}
/// The streams of a page's /Contents, read without changing the document.
pub(crate) fn content_list(doc: &Document, page: &pdfcraft_model::Page) -> Vec<Object> {
let obj = doc.get(page.obj);
match obj.as_dict().and_then(|d| d.get(b"Contents")) {
None => Vec::new(),
Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]),
Some(Object::Array(a)) => a.clone(),
Some(other) => vec![other.clone()],
}
}
/// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original
/// content and nothing else (a header's shrink). A page without a wrapper has no original content
/// on it and is left alone.
pub(crate) fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>) -> Result<(), EditError> {
/// on it and is left alone. Returns the new content stream, if one was placed.
pub(crate) fn place_inside_wrapper(
doc: &mut Document,
page: &pdfcraft_model::Page,
tag: &str,
content: Vec<u8>,
) -> Result<Option<ObjRef>, EditError> {
let mut list = contents(doc, page)?;
let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(()) };
let stream = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content))));
list.insert(open + 1, stream);
let Some(open) = first_wrapper(doc, &list) else { return Ok(None) };
let stream = doc.add(Object::Stream(Stream::flate(tagged(tag), &content)));
list.insert(open + 1, Object::Ref(stream));
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
Ok(())
Ok(Some(stream))
}
/// The first `Wrap`-tagged stream in `list`, which [`place_inside_wrapper`] puts content after.
pub(crate) fn first_wrapper(doc: &Document, list: &[Object]) -> Option<usize> {
list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap"))
}
/// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica
+257
View File
@@ -302,6 +302,263 @@ fn replace_and_remove_restore_the_original_content() {
assert_eq!(streams(&reopen(&doc), 0), original, "back to exactly the original content");
}
fn with_text(text: &str) -> HeaderFooter {
let mut hf = HeaderFooter::default();
hf.text[1] = text.into();
hf
}
/// #5785: Update could only reach the newest header and footer, and took every other one on
/// those pages with it.
#[test]
fn update_changes_one_header_and_footer_and_leaves_the_others() {
let mut doc = fixture();
let (header, footer) = (with_text("Héader <<1>>"), with_text("Footer"));
add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0], &footer, false, &cx()).unwrap();
// Listed after a save too, in the document's own words: tokens unexpanded, accents kept.
let doc = &mut reopen(&doc);
let found = header_footers(doc);
assert_eq!(found.iter().map(|m| (&m.settings, &m.pages[..])).collect::<Vec<_>>(), [(&header, &[0][..]), (&footer, &[0][..])]);
// "Héader 1" is drawn with its é as an escape: what follows it is the old header's drawing.
assert!(streams(doc, 0).iter().any(|x| x.contains("ader 1)")), "{:?}", streams(doc, 0));
update_header_footer(doc, &found[0].settings, &[0], &with_text("New"), &cx()).unwrap();
let s = streams(doc, 0);
assert!(s.iter().any(|x| x.contains("(New)")) && s.iter().any(|x| x.contains("(Footer)")), "{s:?}");
assert!(!s.iter().any(|x| x.contains("ader 1)")), "the old header is gone: {s:?}");
assert_eq!(header_footers(doc).len(), 2);
let gone = update_header_footer(doc, &header, &[0], &with_text("Again"), &cx());
assert!(matches!(gone, Err(EditError::Invalid(_))), "{gone:?}");
assert!(streams(doc, 0).iter().any(|x| x.contains("(New)")), "a refused update changes nothing");
}
/// FredApps on #6352: an updated header and footer stays under the ones added after it, where
/// they overlap, as before the update, and its shrink is never taken for its place.
#[test]
fn update_keeps_the_header_and_footer_in_its_place_among_the_others() {
let mut doc = fixture();
let (header, footer) = (HeaderFooter { shrink: true, ..with_text("Under") }, with_text("Over"));
add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0, 1], &footer, false, &cx()).unwrap();
let at = |doc: &Document, page: usize, text: &str| streams(doc, page).iter().position(|x| x.contains(text));
update_header_footer(&mut doc, &header, &[0, 1], &with_text("New"), &cx()).unwrap();
let s = streams(&doc, 0);
assert!(at(&doc, 0, "(New)") < at(&doc, 0, "(Over)"), "still under the footer added after it: {s:?}");
assert!(!s.iter().any(|x| x.contains("(Under)") || x.trim_end().ends_with(" cm")), "the old one and its shrink are gone: {s:?}");
assert!(at(&doc, 1, "(New)") > at(&doc, 1, "(Over)"), "on a page it was not on, it goes on top");
}
/// Update's preview draws its draft between the two: the page under the header and footer it
/// replaces, and what is drawn over it.
#[test]
fn update_preview_layers_split_the_page_at_the_header_and_footer() {
let mut doc = fixture();
let (old, later) = (with_text("Old"), with_text("Later"));
add_header_footer(&mut doc, &[0], &old, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0, 1], &later, false, &cx()).unwrap();
let original = streams(&fixture(), 0);
let mut under = doc.clone();
assert!(under_header_footer(&mut under, &old).unwrap() > 0);
let s = streams(&under, 0);
assert!(!s.iter().any(|x| x.contains("(Old)") || x.contains("(Later)")), "{s:?}");
assert!(original.iter().all(|o| s.contains(o)), "the page's own content stays: {s:?}");
assert!(streams(&under, 1).iter().any(|x| x.contains("(Later)")), "a page without it is left as it is");
let mut over = doc.clone();
assert_eq!(over_header_footer(&mut over, &old).unwrap(), 1);
let s = streams(&over, 0);
assert!(s.iter().any(|x| x.contains("(Later)")) && !s.iter().any(|x| x.contains("(Old)")), "{s:?}");
assert!(!original.iter().any(|o| s.contains(o)), "nothing under it: {s:?}");
assert!(streams(&over, 1).is_empty(), "where it is not, the new one goes on top");
assert_eq!(over_header_footer(&mut doc.clone(), &later).unwrap(), 0, "nothing is over the newest");
}
#[test]
fn updating_a_shrinking_header_takes_its_shrink_away_too() {
let mut doc = fixture();
let original = streams(&doc, 0);
let shrunk = HeaderFooter { shrink: true, ..with_text("Small") };
add_header_footer(&mut doc, &[0], &shrunk, false, &cx()).unwrap();
update_header_footer(&mut doc, &shrunk, &[0], &with_text("Plain"), &cx()).unwrap();
let s = streams(&doc, 0);
assert_eq!(s.iter().filter(|x| x.contains("/PCMark")).count(), 1);
assert!(original.iter().all(|o| s.contains(o)), "{s:?}");
assert_eq!(s.len(), original.len() + 3, "the original, one wrapper and the new mark: {s:?}");
}
/// A document with one header "Real" on page 1, and that header's stream.
fn one_recorded_header() -> (Document, pdfcraft_cos::ObjRef) {
let mut doc = fixture();
add_header_footer(&mut doc, &[0], &with_text("Real"), false, &cx()).unwrap();
let page = crate::page_list(&doc).swap_remove(0);
let marks: Vec<_> = crate::contents(&mut doc, &page)
.unwrap()
.iter()
.filter_map(Object::as_ref)
.filter(|r| doc.get(*r).as_dict().is_some_and(|d| d.contains(b"PCHeaderFooter")))
.collect();
assert_eq!(marks.len(), 1);
(doc, marks[0])
}
/// A change made to recorded settings, for [`settings_a_file_makes_up_are_not_listed`].
type Change = Box<dyn FnOnce(&mut Document, &mut Dict)>;
/// The recorded settings of `with_text("Real")`, changed by `change`.
fn real_settings_with(doc: &mut Document, change: impl FnOnce(&mut Document, &mut Dict)) -> Object {
let mut d = with_text("Real").to_object().as_dict().cloned().unwrap();
change(doc, &mut d);
Object::Dict(d)
}
#[test]
fn settings_a_file_makes_up_are_not_listed() {
let texts = |entries: Vec<&[u8]>| Object::Array(entries.into_iter().map(|t| Object::String(pdfcraft_cos::PdfString::literal(t))).collect());
let long = vec![b'x'; 16 * 1024 + 1];
let cases: Vec<(&str, Change)> = vec![
("not text", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1); 6])))),
("five boxes", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b"a"[..]; 5])))),
("a million boxes", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Null; 1_000_000])))),
("a box too long", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..], &long[..], &b""[..], &b""[..], &b""[..], &b""[..]])))),
("no text", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..]; 6])))),
("undrawable", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::String(pdfcraft_cos::PdfString::text("中")); 6])))),
("size not a number", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(f64::NAN)))),
("size too big", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(300.0)))),
("a negative margin", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(-1.0); 4])))),
("three margins", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(1.0); 3])))),
("a colour out of range", Box::new(|_, d| d.set(b"Color".to_vec(), Object::Array(vec![Object::Real(2.0); 3])))),
("an unknown face", Box::new(|_, d| d.set(b"Font".to_vec(), Object::name("Comic")))),
("a negative start", Box::new(|_, d| d.set(b"Start".to_vec(), Object::Int(-1)))),
];
for (what, change) in cases {
let (mut doc, mark) = one_recorded_header();
let hostile = real_settings_with(&mut doc, change);
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), hostile)).unwrap();
assert!(header_footers(&doc).is_empty(), "{what}");
assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "{what}: still a mark: Remove and page-wide Update reach it");
assert_eq!(unrecorded_header_footer_pages(&doc), [0], "{what}");
assert_eq!(newest_header_footer(&doc, 0), Some(None), "{what}");
}
}
/// #6352 review: listing read a header's settings again for every stream that recorded them, so a
/// file repeating one shared entry (or one stream) across its pages could make it slow. A scan now
/// reads each stream and each settings entry given by reference once, and still finds every page.
#[test]
fn settings_shared_by_many_streams_are_read_once_in_a_scan() {
let (mut doc, mark) = one_recorded_header();
let settings = doc.get(mark).as_dict().unwrap().get(b"PCHeaderFooter").cloned().unwrap();
let shared = Object::Ref(doc.add(settings));
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), shared)).unwrap();
let Object::Stream(copy) = (*doc.get(mark)).clone() else { panic!("a stream") };
// Page 0 draws the header's own stream 500 times; page 1 has 200 streams of its own, each
// recording the same settings by reference.
let mut first = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))];
first.extend(std::iter::repeat_n(Object::Ref(mark), 500));
let mut second = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))];
second.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(copy.clone())))));
doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(first))).unwrap();
doc.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |d| d.set(b"Contents".to_vec(), Object::Array(second))).unwrap();
crate::marks::DECODED.with(|n| n.set(0));
let found = header_footers(&doc);
assert_eq!(crate::marks::DECODED.with(std::cell::Cell::get), 1, "the shared entry is read once");
assert_eq!(found.len(), 1);
assert_eq!((found[0].pages.as_slice(), found[0].settings.text[1].as_str()), (&[0, 1][..], "Real"));
assert!(unrecorded_header_footer_pages(&doc).is_empty());
}
/// #6352 review: past the scan's text budget, settings went unread like a header that records
/// none, so a header and footer listed itself on only the pages before that, and Update removed
/// it from those alone. Update now refuses instead, and the unread ones are not offered as older.
#[test]
fn update_refuses_when_the_scan_cannot_find_every_page_of_a_header() {
let (mut doc, mark) = one_recorded_header();
let pages = crate::page_list(&doc);
let Object::Stream(real) = (*doc.get(mark)).clone() else { panic!("a stream") };
// Page 0: the real header, then 200 others recording 96 KiB of text each, past the budget.
let big = HeaderFooter { text: std::array::from_fn(|_| "x".repeat(16 * 1024)), ..HeaderFooter::default() };
let mut heavy = real.clone();
heavy.dict.set(b"PCHeaderFooter".to_vec(), big.to_object());
let mut first = crate::contents(&mut doc, &pages[0]).unwrap();
first.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(heavy.clone())))));
// Page 1: the real header again, in a stream of its own, which the scan no longer reads.
let mut second = crate::contents(&mut doc, &pages[1]).unwrap();
second.push(Object::Ref(doc.add(Object::Stream(real))));
let page_refs: Vec<_> = pages.iter().map(|p| p.obj).collect();
doc.update_dict(page_refs[0], |d| d.set(b"Contents".to_vec(), Object::Array(first.clone()))).unwrap();
doc.update_dict(page_refs[1], |d| d.set(b"Contents".to_vec(), Object::Array(second.clone()))).unwrap();
let real = with_text("Real");
let listed = header_footers(&doc);
assert_eq!(listed.iter().find(|m| m.settings == real).map(|m| m.pages.as_slice()), Some(&[0][..]), "the scan stops short");
assert!(unrecorded_header_footer_pages(&doc).is_empty(), "settings it did not read are not offered as older ones");
assert!(matches!(remove_header_footer(&mut doc, &real), Err(EditError::Invalid(_))));
assert!(matches!(update_header_footer(&mut doc, &real, &[0], &with_text("New"), &cx()), Err(EditError::Invalid(_))));
assert_eq!(crate::contents(&mut doc, &pages[0]).unwrap(), first, "page 0 is as it was");
assert_eq!(crate::contents(&mut doc, &pages[1]).unwrap(), second, "and the header stays on page 1");
}
#[test]
fn settings_a_rewriting_tool_made_indirect_are_still_listed() {
let (mut doc, mark) = one_recorded_header();
let indirect = real_settings_with(&mut doc, |doc, d| {
for key in [&b"Font"[..], b"Size", b"Start", b"Underline", b"Text"] {
let value = d.get(key).cloned().unwrap();
d.set(key.to_vec(), Object::Ref(doc.add(value)));
}
let half = Object::Ref(doc.add(Object::Real(0.5)));
d.set(b"Color".to_vec(), Object::Array(vec![half.clone(), half.clone(), half]));
let margins = Object::Array(vec![Object::Ref(doc.add(Object::Real(36.0))), Object::Real(36.0), Object::Real(72.0), Object::Real(72.0)]);
d.set(b"Margins".to_vec(), Object::Ref(doc.add(margins)));
});
doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), indirect)).unwrap();
let found = header_footers(&doc);
assert_eq!(found.len(), 1);
assert_eq!(found[0].settings, HeaderFooter { color: [0.5; 3], ..with_text("Real") });
assert!(unrecorded_header_footer_pages(&doc).is_empty());
}
#[test]
fn a_header_too_long_to_be_listed_is_not_added() {
// Every header add accepts is one the listing can name, so Update never has to fall back to
// replacing it page-wide.
let mut doc = fixture();
let too_long = with_text(&"x".repeat(16 * 1024 + 1));
assert!(matches!(add_header_footer(&mut doc, &[0], &too_long, false, &cx()), Err(EditError::Invalid(_))));
assert!(marks_present(&doc).is_empty(), "nothing drawn");
let longest = with_text(&"x".repeat(16 * 1024));
add_header_footer(&mut doc, &[0], &longest, false, &cx()).unwrap();
assert_eq!(header_footers(&doc).len(), 1, "the longest box add accepts is listed");
}
#[test]
fn a_header_added_with_an_out_of_range_colour_can_be_updated() {
let mut doc = fixture();
let bright = HeaderFooter { color: [2.0, -1.0, 0.5], ..with_text("Bright") };
add_header_footer(&mut doc, &[0], &bright, false, &cx()).unwrap();
let found = header_footers(&doc);
assert_eq!(found.len(), 1, "listed with the colour it is drawn in");
assert_eq!(found[0].settings.color, [1.0, 0.0, 0.5]);
update_header_footer(&mut doc, &found[0].settings, &[0], &with_text("Calm"), &cx()).unwrap();
assert_eq!(header_footers(&doc).iter().map(|m| m.settings.text[1].as_str()).collect::<Vec<_>>(), ["Calm"]);
}
#[test]
fn the_newest_header_on_a_page_is_the_one_added_last() {
let mut doc = fixture();
assert_eq!(newest_header_footer(&doc, 0), None);
let (first, second) = (HeaderFooter { shrink: true, ..with_text("First") }, HeaderFooter { shrink: true, ..with_text("Second") });
add_header_footer(&mut doc, &[0, 1], &first, false, &cx()).unwrap();
add_header_footer(&mut doc, &[0], &second, false, &cx()).unwrap();
// The second shrink goes in ahead of the first, so content order alone would say First.
assert_eq!(newest_header_footer(&doc, 0), Some(Some(second)));
assert_eq!(newest_header_footer(&doc, 1), Some(Some(first)));
assert_eq!(newest_header_footer(&doc, 9), None);
}
/// The six numbers of the first `… cm` in `content`.
fn first_cm(content: &str) -> [f64; 6] {
let line = content.lines().find(|l| l.ends_with(" cm")).unwrap_or_else(|| panic!("no cm in {content:?}"));
+1 -1
View File
@@ -306,7 +306,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("comment.underline", "Underline text", None, None, Annotate, "text_underline"),
c("comment.strikeout", "Strikethrough text", None, None, Annotate, "text_strikethrough"),
c("comment.squiggly", "Squiggly underline text", None, None, Annotate, "spline"),
c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "highlighter"),
c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "freehand-highlighter"),
c("comment.ink", "Draw freehand", None, None, Annotate, "pencil"),
c("comment.line", "Draw a line", None, None, Annotate, "minus"),
c("comment.arrow", "Draw an arrow", None, None, Annotate, "move-right"),
+6 -1
View File
@@ -34,9 +34,14 @@ pub enum ImageEdit {
/// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a
/// filled-in PDF form), as CSV with one row per file.
pub fn merge_data_files(files: &[(String, Vec<u8>)]) -> Result<String, String> {
merge_data_files_with_columns(files).map(|(csv, _)| csv)
}
/// Merge the files to CSV and report the distinct field count.
pub fn merge_data_files_with_columns(files: &[(String, Vec<u8>)]) -> Result<(String, usize), String> {
let rows =
files.iter().map(|(name, bytes)| pdfcraft_xfdf::data_values(bytes).map_err(|e| format!("{name}: {e}"))).collect::<Result<Vec<_>, _>>()?;
Ok(pdfcraft_xfdf::merge_csv(&rows))
Ok(pdfcraft_xfdf::merge_csv_with_columns(&rows))
}
/// One file produced by a split: (1-based first page, last page, PDF bytes).
+19
View File
@@ -65,6 +65,10 @@ pub struct Document {
/// since they last gained focus: their exit on losing focus has run already
/// ([`Session::field_focus`]).
pub(crate) xfa_exited: std::collections::HashSet<String>,
/// An XFA button click run on a worker ([`Session::start_javascript_target`]) had a script
/// run away: the next edit turns the form's scripts off, as it would have had the click been
/// kept (it may have been dropped: the document changed, or the app stopped waiting).
pub(crate) xfa_ran_away: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// A content-only refresh keeps `info` from before the edit; an edit may have added or
/// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]).
pub(crate) fonts_stale: bool,
@@ -616,6 +620,21 @@ impl Document {
.marks
}
/// The headers and footers Update can tell apart (`pdfcraft_edit::header_footers`).
pub fn header_footers(&self) -> Vec<pdfcraft_edit::HeaderFooterMark> {
self.editor.as_ref().map(|e| pdfcraft_edit::header_footers(&e.cos)).unwrap_or_default()
}
/// The header and footer added last to page `page` (`pdfcraft_edit::newest_header_footer`).
pub fn newest_header_footer(&self, page: usize) -> Option<Option<pdfcraft_edit::HeaderFooter>> {
self.editor.as_ref().and_then(|e| pdfcraft_edit::newest_header_footer(&e.cos, page))
}
/// Pages whose header and footer records no settings (`pdfcraft_edit::unrecorded_header_footer_pages`).
pub fn unrecorded_header_footer_pages(&self) -> Vec<usize> {
self.editor.as_ref().map(|e| pdfcraft_edit::unrecorded_header_footer_pages(&e.cos)).unwrap_or_default()
}
/// Text and images added with Edit a PDF ▸ Add content (still editable).
pub fn added(&self) -> &[pdfcraft_edit::Added] {
&self
+7
View File
@@ -556,6 +556,13 @@ pub enum Edit {
settings: HeaderFooter,
replace: bool,
},
/// Update one header and footer: `old` (settings from `Document::header_footers`) goes from
/// every page it is on and `settings` is added to `pages`. Others stay.
UpdateHeaderFooter {
old: HeaderFooter,
pages: Vec<usize>,
settings: HeaderFooter,
},
/// `file`: a picture from a file (an image, or a page of a PDF) instead of text.
AddWatermark {
pages: Vec<usize>,
+1 -1
View File
@@ -316,7 +316,7 @@ impl Edit {
ImageEdit::Ungroup => "Ungroup artwork",
}),
Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),
Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),
Edit::AddHeaderFooter { .. } | Edit::UpdateHeaderFooter { .. } => Label::of("Update header & footer"),
Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"),
Edit::AddWatermark { .. } => Label::of("Update watermark"),
Edit::AddBackground { replace: false, .. } => Label::of("Add background"),
+9
View File
@@ -110,6 +110,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re
}
Edit::SetInfo { .. }
| Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddPrinterMarks { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
@@ -260,6 +261,8 @@ pub(crate) struct EditCtx {
pub(crate) xfa_unchanged: bool,
/// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).
pub(crate) xfa_time_scale: u32,
/// The answers the edit's XFA event takes ([`Session::xfa_answers`](crate::Session)).
pub(crate) xfa_answers: xfa::XfaAnswers,
/// The form's scripts or new data laid it out again: its pages and widgets were replaced.
pub(crate) xfa_relaid: bool,
/// The edit took the XFA out of the form: what went with it, for the document's warnings.
@@ -333,6 +336,7 @@ impl EditCtx {
xfa_ran_away: false,
xfa_unchanged: false,
xfa_time_scale: 1,
xfa_answers: Default::default(),
xfa_relaid: false,
xfa_removed: Vec::new(),
pages: 0,
@@ -794,6 +798,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: std::mem::take(&mut cx.xfa_answers),
relaid: false,
};
let ran = if matches!(activity.as_str(), "enter" | "exit") {
@@ -971,6 +976,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
let date = cx.today;
pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?;
}
Edit::UpdateHeaderFooter { old, pages, settings } => {
let date = cx.today;
pdfcraft_edit::update_header_footer(doc, old, pages, settings, &pdfcraft_edit::Context { date })?;
}
Edit::AddWatermark { pages, settings, replace, file } => {
let mut s = settings.clone();
if let Some(f) = file {
+1
View File
@@ -103,6 +103,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
| Edit::PasteContent { .. }
| Edit::PasteObjects { .. }
| Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
| Edit::RemoveMarks { .. }
+143 -20
View File
@@ -1193,24 +1193,18 @@ impl Session {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let cos = doc.editor.as_ref().map(|e| e.cos.clone()).ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
validate_script_target(target, target_id, &doc.form)?;
// A button PdfCraft generated from an XFA template runs its XFA click script.
if let Some(t) = target
&& event_name.is_none_or(|n| n == "Mouse Up")
&& let Some(tpl) = doc.xfa_template.clone()
&& let Some(field) = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))
&& field.kind == crate::FormFieldKind::PushButton
&& let Some(som) = crate::xfa::clickable_som(&cos, &tpl, field)
// A button PdfCraft generated from an XFA template runs its XFA click script, its
// message boxes taking `answers` (then their buttons' safe default: nobody is asked).
if event_name.is_none_or(|n| n == "Mouse Up")
&& let Some(som) = xfa_click_som(doc, &cos, target, target_id)
{
self.xfa_answers = Some(crate::xfa::XfaAnswers { given: answers.to_vec(), ..Default::default() });
// The click returns only the output of its own edit; output from opening or from earlier edits stays.
let ((), out) = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }))?;
return Ok(Outcome {
rc: true,
alerts: out.alerts,
console: out.console,
requests: out.requests,
error: out.errors.first().cloned(),
..Default::default()
});
let ran = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }));
// Not taken when the edit stopped before it ran the event: no later edit takes it.
self.xfa_answers = None;
let ((), out) = ran?;
return Ok(xfa_click_outcome(out));
}
let mut runner = JsRunner::new(&cos, &doc.name, self.field_highlight);
runner.doc.zoom = doc.js_zoom;
@@ -1699,6 +1693,32 @@ mod caption_tests {
}
}
/// The SOM path of the XFA click script button `target` runs, when it is a push button PdfCraft
/// generated from a laid-out XFA form's template.
fn xfa_click_som(doc: &crate::Document, cos: &pdfcraft_cos::Document, target: Option<&str>, target_id: Option<u64>) -> Option<String> {
let t = target?;
let tpl = doc.xfa_template.as_ref()?;
let field = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))?;
if field.kind != crate::FormFieldKind::PushButton {
return None;
}
crate::xfa::clickable_som(cos, tpl, field)
}
/// What an XFA button click did, as a button script's outcome.
fn xfa_click_outcome(out: JsOutput) -> Outcome {
Outcome { rc: true, alerts: out.alerts, console: out.console, requests: out.requests, error: out.errors.first().cloned(), ..Default::default() }
}
/// Stack for the thread an XFA button click runs on in the app: it lays the form out again, as
/// the app's main thread does for other edits.
#[cfg(not(target_arch = "wasm32"))]
const XFA_CLICK_STACK: usize = 8 << 20;
/// An XFA button click's edit, once its worker has run it ([`Session::start_javascript_target`]).
#[cfg(not(target_arch = "wasm32"))]
type XfaClick = std::sync::Arc<std::sync::Mutex<Option<(crate::session::BegunEdit, Result<(), EditError>)>>>;
/// A failed link action commits nothing: its field changes, requests and layer changes are
/// dropped (the realm put its timers back), its alerts, console lines and error kept (#2081).
fn drop_failed_link_effects(o: &mut Outcome) {
@@ -1822,6 +1842,16 @@ pub struct PendingScript {
/// Whether the script may add or show pages from templates ([`may_change_pages`]).
may_change_pages: bool,
pub receiver: std::sync::mpsc::Receiver<pdfcraft_js::interaction::InteractiveEvent>,
/// An XFA button click: its edit, filled in by its worker before it completes.
xfa: Option<XfaClick>,
}
#[cfg(not(target_arch = "wasm32"))]
impl PendingScript {
/// Whether this is an XFA button's click ([`Session::start_javascript_target`]). It reads
/// no view state (zoom, page) the way an AcroForm script does, and its own limits bound it.
pub fn is_xfa(&self) -> bool {
self.xfa.is_some()
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Session {
@@ -1846,12 +1876,15 @@ impl Session {
}
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let cos = &doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?.cos;
let fields = pdfcraft_forms::fields(cos);
validate_script_target(target, target_id, &fields)?;
if let Some(som) = xfa_click_som(doc, cos, target, target_id) {
return self.start_xfa_click(id, som);
}
let mut runner = JsRunner::new(cos, &doc.name, self.field_highlight);
runner.doc.zoom = doc.js_zoom;
runner.doc.page = doc.js_page;
runner.doc.layers = crate::live_scripts::js_layers(&doc.info);
let fields = pdfcraft_forms::fields(cos);
validate_script_target(target, target_id, &fields)?;
let states = std::sync::Arc::new(fields.iter().map(|f| crate::live_scripts::live_state(doc, cos, f, &runner.doc)).collect::<Vec<_>>());
let job = pdfcraft_js::session::Job {
script: script.into(),
@@ -1868,7 +1901,65 @@ impl Session {
let receiver =
doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?;
let may_change_pages = may_change_pages(target, &fields);
Ok(PendingScript { id, link: false, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver })
Ok(PendingScript {
id,
link: false,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states,
may_change_pages,
receiver,
xfa: None,
})
}
/// Start XFA button `som`'s click on a worker, so the app goes on drawing while it runs and
/// can ask its message boxes' questions: each comes through the pending script's receiver
/// as a prompt, and the script waits for the answer with its clock stopped. Once the worker
/// is done, [`Session::finish_javascript`] keeps the click as one undo step, as
/// [`Session::apply`] would, unless the document changed meanwhile.
fn start_xfa_click(&mut self, id: DocId, som: String) -> Result<PendingScript, EditError> {
let (prompts, receiver) = std::sync::mpsc::channel();
self.xfa_answers = Some(crate::xfa::XfaAnswers { prompts: Some(prompts.clone()), ..Default::default() });
let begun = self.begin_edit(id, Edit::XfaEvent { som, activity: "click".into() });
// Not taken when the edit stopped before it began.
self.xfa_answers = None;
let begun = begun?;
let doc = self.get(id).ok_or(EditError::NoDocument)?;
let click: XfaClick = Default::default();
let pending = PendingScript {
id,
link: false,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states: Default::default(),
// Its edit is kept as an undo step of its own (`finish_javascript`), never applied as a
// script outcome, so it adds no pages from templates.
may_change_pages: false,
receiver,
xfa: Some(click.clone()),
};
let Some(mut begun) = begun else {
// Nothing to run: done at once.
let _ = prompts.send(InteractiveEvent::Complete(Outcome::default()));
return Ok(pending);
};
let ran_away = std::sync::Arc::clone(&doc.xfa_ran_away);
std::thread::Builder::new()
.name("pdfcraft-xfa-click".into())
.stack_size(XFA_CLICK_STACK)
.spawn(move || {
let checked = crate::session::run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx);
if begun.cx.xfa_ran_away {
ran_away.store(true, std::sync::atomic::Ordering::Relaxed);
}
// A poisoned lock only means a panic elsewhere while it was held: the slot is still ours.
*click.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((begun, checked));
// The app may have stopped waiting: then nobody takes the click.
let _ = prompts.send(InteractiveEvent::Complete(Outcome::default()));
})
.map_err(|e| EditError::Invalid(format!("the form script could not start: {e}")))?;
Ok(pending)
}
/// Start link `index` on page `page` as [`Session::run_link_javascript`] runs it, without
/// blocking on its prompts; [`Session::finish_javascript`] commits nothing if it failed.
@@ -1879,10 +1970,23 @@ impl Session {
doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?;
// A link's script has the document as its target, as a document script does.
let may_change_pages = may_change_pages(None, &[]);
Ok(PendingScript { id, link: true, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver })
Ok(PendingScript {
id,
link: true,
generation: doc.generation,
runtime: doc.js_runtime.clone(),
states,
may_change_pages,
receiver,
xfa: None,
})
}
/// Discard only the captured runtime, preserving a newer realm created by an intervening edit.
pub fn discard_javascript(&mut self, p: &PendingScript) {
// An XFA click's worker holds no realm: what it did is dropped with the pending script.
if p.xfa.is_some() {
return;
}
if let Some(doc) = self.docs.iter_mut().find(|d| d.id == p.id)
&& std::sync::Arc::ptr_eq(&doc.js_runtime, &p.runtime)
{
@@ -1891,6 +1995,10 @@ impl Session {
}
/// Discard a timed-out invocation and retain the worker slot until its thread exits.
pub fn timeout_javascript(&mut self, p: PendingScript) {
// An XFA click's scripts are bounded on its worker; what it did is dropped.
if p.xfa.is_some() {
return;
}
if self.script_pending_current(&p)
&& let Ok(mut runtime) = p.runtime.lock()
{
@@ -1902,6 +2010,21 @@ impl Session {
/// Apply a current worker result, or discard it and reset the realm when the document changed.
pub fn finish_javascript(&mut self, p: PendingScript, mut out: Outcome) -> Result<Outcome, EditError> {
if let Some(click) = &p.xfa {
if !self.script_pending_current(&p) {
return Err(EditError::Invalid("document changed while the script was running".into()));
}
let ran = click.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
let Some((begun, checked)) = ran else { return Ok(Outcome { rc: true, ..Default::default() }) };
let ran_away = begun.cx.xfa_ran_away;
let ((), out) = self.with_own_js_output(p.id, |s| s.finish_edit(p.id, begun, checked).map(|_| ()))?;
// Kept, a click that ran away turned the scripts off itself: not again. A flag another
// click set (one this commit makes stale) stays for the next edit.
if ran_away && let Some(d) = self.get(p.id) {
d.xfa_ran_away.store(false, std::sync::atomic::Ordering::Relaxed);
}
return Ok(xfa_click_outcome(out));
}
if p.link {
drop_failed_link_effects(&mut out);
}
+2 -2
View File
@@ -106,7 +106,7 @@ pub use pdfcraft_edit::added::{
pub use pdfcraft_edit::paragraph_align;
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, ColourTarget, ColoursConverted, Content as AddedContent, ConvertColours,
Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, Ink as TextInk, MarkKind, PrinterMarks, Watermark,
Family as FontFamily, Hairlines, HairlinesFixed, HeaderFooter, HeaderFooterMark, Ink as TextInk, MarkKind, PrinterMarks, Watermark,
};
pub use pdfcraft_forms::{
BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont,
@@ -191,7 +191,7 @@ mod doc_state;
pub use pdfcraft_edit::ArrangeOrder;
use clock::{local_utc_offset, parse_ymd};
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files};
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files, merge_data_files_with_columns};
use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable};
/// The configuration of the pool that draws the viewer: the document's own, plus installed CJK
+2
View File
@@ -232,6 +232,7 @@ impl Session {
ran_away: false,
highlight: context.highlight,
time_scale: context.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let changes = xfa::on_open(&mut work, &tpl, &mut run);
@@ -405,6 +406,7 @@ impl Session {
xfa_template: None,
xfa_scripts_off: false,
xfa_exited: Default::default(),
xfa_ran_away: Default::default(),
fonts_stale: false,
xfa_warnings: Vec::new(),
edit_notices: Vec::new(),
+10 -1
View File
@@ -20,6 +20,8 @@ use crate::{
};
mod editing;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use editing::{BegunEdit, run_checked_edit};
mod files;
mod save;
mod view;
@@ -35,10 +37,14 @@ pub struct Session {
/// injected time AS local time and zeroes the zone, so injecting only it leaves either the
/// local dates or the UTC ones wrong by the zone's offset.
utc_offset: Option<fn() -> i64>,
/// Certificates trusted for signing (Acrobat: Trusted Certificates).
/// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the
/// trust lists they loaded.
pub(crate) trust: Arc<TrustStore>,
/// The words signature status layers are drawn with, in the interface language.
pub(crate) captions: Arc<StatusCaptions>,
/// How often every open document's signatures were validated again after a trust change.
#[cfg(test)]
pub(crate) revalidations: usize,
/// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default).
pub(crate) js_off: bool,
/// Preferences ▸ Date format, when not the default (see [`dates`]).
@@ -51,4 +57,7 @@ pub struct Session {
/// What the XFA scripts' time limits are multiplied by (`None`: 1); see
/// [`Session::with_xfa_time_scale`].
pub(crate) xfa_time_scale: Option<u32>,
/// The answers the next XFA event takes for its message boxes, set by the caller running it
/// (`js_run`'s answers, an app's button click) and taken by that event's edit.
pub(crate) xfa_answers: Option<crate::xfa::XfaAnswers>,
}
+57 -5
View File
@@ -46,7 +46,7 @@ fn deletes_pages(edit: &Edit) -> bool {
}
/// Keep edits to the working copy until both the operation and its script callbacks succeed.
fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
pub(crate) fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
let result = guard(|| run_edit(next, edit, cx))
.unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))));
let refusal = cx.js.as_mut().and_then(|runner| runner.refused.take());
@@ -122,6 +122,20 @@ fn sync_script_history(doc: &Document, previous: &pdfcraft_cos::Document, restor
}
}
/// An edit between [`Session::begin_edit`] and [`Session::finish_edit`]: the copy of the
/// document it runs on (`next`) and its context. Send, so an XFA button click can run on a
/// worker while the app goes on drawing and asks the click's questions.
pub(crate) struct BegunEdit {
pub(crate) edit: Edit,
pub(crate) next: pdfcraft_cos::Document,
pub(crate) cx: EditCtx,
scope: Scope,
is_xfa: bool,
signed: bool,
/// The document's generation it was made from: a changed document doesn't take it.
generation: u64,
}
impl Session {
/// Apply an edit. On success the previous state is undoable and the view data is refreshed.
pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {
@@ -138,12 +152,27 @@ impl Session {
/// [`Session::apply`], giving back what an [`Edit::PrepareText`] did (`None` for other edits).
fn apply_reporting(&mut self, id: DocId, edit: Edit) -> Result<Option<pdfcraft_edit::text::forms::Preparation>, EditError> {
let Some(mut begun) = self.begin_edit(id, edit)? else { return Ok(None) };
// `next` is a copy: if the edit fails or crashes, the document is unchanged.
let checked = run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx);
self.finish_edit(id, begun, checked)
}
/// The first part of [`Session::apply`]: check that `edit` may be made, and make the copy of
/// the document it runs on, with its context. `None`: there is nothing to do.
pub(crate) fn begin_edit(&mut self, id: DocId, edit: Edit) -> Result<Option<BegunEdit>, EditError> {
let now = self.now();
let today = self.today();
let js_off = self.js_off;
let highlight = self.field_highlight;
let xfa_time_scale = self.xfa_time_scale.unwrap_or(1);
let xfa_answers = self.xfa_answers.take().unwrap_or_default();
let doc = self.doc_mut(id)?;
// A script of an XFA click run on a worker ran away: the form's scripts go off, whether
// or not the click was kept.
if doc.xfa_ran_away.swap(false, std::sync::atomic::Ordering::Relaxed) {
take_xfa_output(doc, js::JsOutput::default(), true);
}
// An edit must never read globals from a completed-but-unapplied button invocation.
// Fork its realm before any edit-triggered calculation, even if the edit later fails.
#[cfg(not(target_arch = "wasm32"))]
@@ -153,12 +182,13 @@ impl Session {
doc.edit_notices.clear();
let name = doc.name.clone();
let is_xfa = doc.info.xfa.is_some();
let mut scope = scope_of(&edit);
let scope = scope_of(&edit);
let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48));
if !js_off {
cx.xfa = doc.xfa_template.clone();
}
cx.xfa_time_scale = xfa_time_scale;
cx.xfa_answers = xfa_answers;
cx.pages = doc.info.pages.len();
cx.highlight = highlight;
cx.today = today;
@@ -175,7 +205,7 @@ impl Session {
if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) {
return Ok(None);
}
let mut next = editor.cos.clone();
let next = editor.cos.clone();
if !js_off && uses_scripts(&edit) {
let mut runner = js::JsRunner::new(&next, &name, highlight);
runner.runtime = doc.js_runtime.clone();
@@ -187,8 +217,27 @@ impl Session {
cx.renamed_fields.clear();
cx.redaction_overlays.clear();
cx.redaction_marks.clear();
// `next` is a copy: if the edit fails or crashes, the document is unchanged.
run_checked_edit(&mut next, &edit, &mut cx)?;
Ok(Some(BegunEdit { edit, next, cx, scope, is_xfa, signed, generation: doc.generation }))
}
/// The last part of [`Session::apply`]: keep the edit [`Session::begin_edit`] prepared once
/// it ran (`checked`), as one undo step, unless it failed or the document changed meanwhile
/// (an XFA button click runs on a worker: [`Session::start_javascript_target`]).
pub(crate) fn finish_edit(
&mut self,
id: DocId,
begun: BegunEdit,
checked: Result<(), EditError>,
) -> Result<Option<pdfcraft_edit::text::forms::Preparation>, EditError> {
let BegunEdit { edit, mut next, mut cx, mut scope, is_xfa, signed, generation } = begun;
let doc = self.doc_mut(id)?;
if doc.generation != generation {
discard_edit_callbacks(&cx);
return Err(EditError::Invalid("the document changed while the form's script ran; what it did was not kept".into()));
}
let reason = doc.read_only_reason.clone().unwrap_or_default();
let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;
checked?;
// A field's enter or exit scripts that changed nothing leave no edit behind (no undo step,
// nothing unsaved); what they showed or asked for still goes out. Only an event on its own:
// a batch keeps the other edits it holds.
@@ -278,6 +327,7 @@ impl Session {
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
// Every changed field's scripts, then the calculations once (after a reset,
@@ -623,6 +673,7 @@ impl Session {
matches!(
e,
Edit::AddHeaderFooter { .. }
| Edit::UpdateHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
| Edit::AddPrinterMarks { .. }
@@ -788,6 +839,7 @@ fn rerun_layout_ready(next: &mut pdfcraft_cos::Document, cx: &mut EditCtx) {
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let ran = guard(|| xfa::on_layout(next, &tpl, &mut run)).unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
+37 -4
View File
@@ -252,11 +252,44 @@ impl Session {
&self.trust.certs
}
/// Replace the trusted certificates, revalidate every open document's signatures,
/// and rebuild its display copy and renderer to match (working file untouched,
/// generation/dirty unchanged: trust alone is not an edit).
/// Change the trust store, revalidate every open document's signatures, and rebuild its
/// display copy and renderer to match (working file untouched, generation/dirty unchanged:
/// trust alone is not an edit). This happens once, however many changes `change` makes:
/// revalidating runs chain building and signature verification for every signature, against
/// every certificate of every trust list.
pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) {
let mut trust = (*self.trust).clone();
change(&mut trust);
self.trust = Arc::new(trust);
self.revalidate_signatures();
}
/// Replace the trusted certificates (see [`Session::update_trust`]).
pub fn set_trusted_certificates(&mut self, certs: Vec<pdfcraft_sign::Certificate>) {
self.trust = Arc::new(TrustStore { certs });
self.update_trust(|trust| trust.certs = certs);
}
/// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default.
/// They are not part of [`Session::trusted_certificates`].
pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] {
&self.trust.lists
}
/// Load `list` (replacing a list of the same name) and revalidate every open document.
pub fn add_trust_list(&mut self, list: pdfcraft_sign::trust::TrustList) {
self.update_trust(|trust| trust.add_list(list));
}
/// Remove the trust list called `name` and revalidate every open document.
pub fn remove_trust_list(&mut self, name: &str) {
self.update_trust(|trust| trust.remove_list(name));
}
fn revalidate_signatures(&mut self) {
#[cfg(test)]
{
self.revalidations += 1;
}
for doc in &mut self.docs {
Self::revalidate(doc, self.trust.clone());
}
+371 -4
View File
@@ -4534,6 +4534,51 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() {
assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");
}
/// #5785: Update of one header and footer previews the page without that one alone, so a second
/// header and footer on the same page, which OK keeps, is still drawn in the preview.
#[test]
fn update_of_one_header_previews_the_page_with_the_others() {
let (mut s, id) = session_with(2);
let header = |text: &str, color: [f64; 3]| {
let mut hf = pdfcraft_edit::HeaderFooter { color, font_size: 24.0, ..pdfcraft_edit::HeaderFooter::default() };
hf.text[1] = text.into();
hf
};
let (red, blue) = (header("REDREDRED", [1.0, 0.0, 0.0]), header("BLUEBLUEBLUE", [0.0, 0.0, 1.0]));
s.apply(id, Edit::AddHeaderFooter { pages: vec![0, 1], settings: red.clone(), replace: false }).unwrap();
let mut footer = blue.clone();
footer.text.swap(1, 4);
s.apply(id, Edit::AddHeaderFooter { pages: vec![0], settings: footer.clone(), replace: false }).unwrap();
let doc = s.get(id).unwrap();
let generation = doc.edit_generation();
let count =
|p: &pdfcraft_render::RenderedPage, f: fn(u8, u8, u8) -> bool| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| f(*r, *g, *b)).count();
let reds = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| r > 200 && g < 80 && b < 80);
let blues = |p: &pdfcraft_render::RenderedPage| count(p, |r, g, b| b > 200 && r < 80 && g < 80);
let mut without_red = doc.without_header_footer(&red).unwrap().expect("the red header is on the pages");
let page = without_red.render_page(0, 1.0).unwrap();
assert_eq!(reds(&page), 0, "the header Update replaces is gone");
assert_eq!(blues(&page), 0, "the footer added after it is drawn over the new one, so not under it");
assert_eq!(reds(&without_red.render_page(1, 1.0).unwrap()), 0, "from every page it is on");
// The footer OK keeps over the new header, alone.
let mut over_red = doc.over_header_footer(&red).unwrap().expect("the blue footer is over the red header");
let page = over_red.render_page(0, 1.0).unwrap();
let opaque = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[.., a]| *a > 0).count();
assert!(blues(&page) > 20 && reds(&page) == 0, "the other header and footer on the page stays, as OK keeps it");
assert!(opaque(&page) < page.rgba.len() / 8, "on a transparent page: the draft under it shows");
assert_eq!(opaque(&over_red.render_page(1, 1.0).unwrap()), 0, "nothing is over it where it is alone");
assert!(doc.over_header_footer(&footer).unwrap().is_none(), "nothing is over the newest");
let page = doc.without_header_footer(&footer).unwrap().expect("the blue footer is on page 1").render_page(0, 1.0).unwrap();
assert!(reds(&page) > 20 && blues(&page) == 0, "and the other way round");
// Every header and footer goes for a page-wide replace, and a header no page records has nothing to prepare.
let page = doc.without_marks(MarkKind::HeaderFooter).unwrap().expect("there are headers").render_page(0, 1.0).unwrap();
assert_eq!((reds(&page), blues(&page)), (0, 0));
assert!(doc.without_header_footer(&header("GONE", [0.0, 1.0, 0.0])).unwrap().is_none());
assert_eq!(s.get(id).unwrap().edit_generation(), generation, "the document is unchanged");
}
#[test]
fn marker_indexes_match_after_open_and_save_when_requested() {
let (mut source, source_id) = session_with(1);
@@ -5218,6 +5263,7 @@ fn pasted_added_content_keeps_its_style_and_picture() {
align: TextAlign::Center,
aligns: Vec::new(),
char_spacing: 0.0,
font_resource: None,
};
s.apply(id, Edit::AddText { page: 0, text: text.clone() }).unwrap();
let copied = s.get(id).unwrap().added()[0].content.clone();
@@ -5798,6 +5844,31 @@ fn reading_colors_set_and_invalidated() {
assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK));
}
#[test]
fn several_trust_changes_revalidate_the_open_documents_once() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate;
let mut s = Session::default();
// Each setter changes one thing and revalidates.
s.set_trusted_certificates(vec![cert.clone()]);
s.set_trusted_certificates(Vec::new());
assert_eq!(s.revalidations, 2);
// One `update_trust` changes any number of things and revalidates once.
let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap();
s.update_trust(|trust| {
trust.certs = vec![cert.clone()];
trust.add_list(list.clone());
});
assert_eq!(s.revalidations, 3);
assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1));
// A list loaded again under its name replaces itself; removing it by that name takes it back.
s.add_trust_list(list);
assert_eq!(s.trust_lists().len(), 1);
s.remove_trust_list("Test list");
assert!(s.trust_lists().is_empty());
assert_eq!(s.revalidations, 5);
}
#[test]
fn signing_saving_trusting_and_commenting_afterwards() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
@@ -8346,13 +8417,29 @@ fn on_changes_notes_only_the_exits_that_ran() {
let names = vec!["probe".to_string()];
let mut exited = Vec::new();
let mut out = crate::js::JsOutput::default();
let mut stopped =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: true, highlight: false, time_scale: 1, relaid: false };
let mut stopped = crate::xfa::XfaRun {
page_count: 1,
out: &mut out,
datasets: None,
ran_away: true,
highlight: false,
time_scale: 1,
answers: Default::default(),
relaid: false,
};
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut stopped, &mut exited).unwrap();
assert!(exited.is_empty(), "no exit ran: {exited:?}");
let mut out = crate::js::JsOutput::default();
let mut running =
crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: false, highlight: false, time_scale: 1, relaid: false };
let mut running = crate::xfa::XfaRun {
page_count: 1,
out: &mut out,
datasets: None,
ran_away: false,
highlight: false,
time_scale: 1,
answers: Default::default(),
relaid: false,
};
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut running, &mut exited).unwrap();
assert_eq!(exited.len(), 1, "the exit ran: {exited:?}");
}
@@ -10422,6 +10509,284 @@ fn xfa_message_boxes_keep_their_title_icon_and_buttons() {
assert_eq!(o.alerts, vec![titled("Too many", "Limits", MessageIcon::Warning, MessageButtons::OkCancel)]);
}
/// A form whose buttons branch on their message boxes' answers (#4291): `hello` (JavaScript)
/// shows a message, then asks two questions; `legacy` (FormCalc) asks one.
fn asking_form() -> (Session, DocId) {
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"xfa.host.messageBox("Starting"); var a = xfa.host.messageBox("Clear?", "T", 2, 2); var b = app.alert("Really?", 2, 1); qty.rawValue = (a == 4 ? 10 : 20) + (b == 1 ? 1 : 2);"#,
)
.replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 2) == 4) then qty = 50 else qty = 1 endif"#);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("asking.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
(s, id)
}
fn qty(s: &Session, id: DocId) -> Vec<String> {
s.get(id).unwrap().form.iter().find(|f| f.name == "qty").unwrap().value.clone()
}
fn answers(a: &[&str]) -> Vec<Option<String>> {
a.iter().map(|a| Some(a.to_string())).collect()
}
/// An XFA button's message boxes return the answers given, in order, headless (`js_run`'s
/// answers), in JavaScript and FormCalc alike: a form can branch on No and Cancel (#4291).
/// Without answers each question gets its buttons' safe default (No; Cancel), not OK.
#[test]
fn xfa_message_boxes_return_the_answers_given() {
let (mut s, id) = asking_form();
assert_eq!(qty(&s, id), ["2"]);
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "4", "1"])).unwrap();
assert_eq!((o.error.as_deref(), o.alerts.len()), (None, 3), "{o:?}");
assert_eq!(qty(&s, id), ["11"]);
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "3", "2"])).unwrap();
assert_eq!(o.error, None);
assert_eq!(qty(&s, id), ["22"]);
s.run_javascript(id, "", Some("hello")).unwrap();
assert_eq!(qty(&s, id), ["22"], "no answers: No and Cancel");
s.run_javascript_answers(id, "", Some("legacy"), &answers(&["4"])).unwrap();
assert_eq!(qty(&s, id), ["50"]);
s.run_javascript(id, "", Some("legacy")).unwrap();
assert_eq!(qty(&s, id), ["1"]);
// An answer the buttons can't give fails the script and says which.
let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "2"])).unwrap();
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 2 (2)")), "{o:?}");
}
/// Wait for the next event of an XFA click started as the app starts it.
#[cfg(not(target_arch = "wasm32"))]
fn next_event(p: &crate::js::PendingScript) -> crate::js::InteractiveEvent {
p.receiver.recv_timeout(std::time::Duration::from_secs(20)).expect("the click goes on")
}
/// Answer the click's questions in turn with `answers` (each prompt checked against `asked`),
/// then keep the click. Returns the outcome.
#[cfg(not(target_arch = "wasm32"))]
fn answer_click(s: &mut Session, p: crate::js::PendingScript, asked: &[&str], answers: &[Option<&str>]) -> Result<js::Outcome, EditError> {
use crate::js::{InteractiveEvent, Prompt};
for (want, answer) in asked.iter().zip(answers) {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(m), reply) => {
assert_eq!(m.text, *want);
reply.send(answer.map(String::from)).expect("the script waits");
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(_) => panic!("finished before asking {want}"),
}
}
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("asked more than {asked:?}") };
s.finish_javascript(p, out)
}
/// An XFA button clicked in the app runs on a worker and asks its message boxes' questions,
/// each script waiting for its answer, in JavaScript and FormCalc alike (#4291), as an AcroForm
/// script's `app.alert` does: nothing changes while it asks, and the click is kept as one undo
/// step once answered.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_started_in_the_app_asks_and_waits_for_each_answer() {
use crate::js::{InteractiveEvent, Prompt};
let (mut s, id) = asking_form();
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert_eq!((m.text.as_str(), m.buttons), ("Starting", js::MessageButtons::Ok));
// The script waits; the document is as it was.
assert_eq!(qty(&s, id), ["2"]);
assert!(s.get(id).unwrap().can_undo().is_none());
reply.send(Some("1".into())).unwrap();
let o = answer_click(&mut s, p, &["Clear?", "Really?"], &[Some("4"), None]).unwrap();
assert_eq!((o.error, o.alerts.len()), (None, 3));
assert_eq!(qty(&s, id), ["12"], "Yes, then closed (Cancel)");
assert!(s.get(id).unwrap().can_undo().is_some());
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
answer_click(&mut s, p, &["Sure?"], &[Some("3")]).unwrap();
assert_eq!(qty(&s, id), ["1"]);
}
/// A document changed while its XFA click waits for an answer doesn't take the click.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_is_dropped_when_the_document_changes_while_it_asks() {
use crate::js::{InteractiveEvent, Prompt};
let (mut s, id) = asking_form();
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(_), reply) = next_event(&p) else { panic!("asks") };
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("7".into()) }).unwrap();
reply.send(Some("4".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert!(!s.script_pending_current(&p));
assert!(s.finish_javascript(p, out).is_err());
assert_eq!(qty(&s, id), ["7"]);
}
/// A click asks at most 32 questions; every later message box gets its buttons' safe default (No
/// for Yes/No) without asking, and the script goes on, as it does when the click's questions are
/// spent across its script sessions (review on #6984).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_click_asks_at_most_32_questions() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"var yes = 0; var no = 0; for (var i = 0; i &lt; 60; i++) { var a = xfa.host.messageBox("Again?", "", 2, 2); if (a == 4) yes++; else if (a == 3) no++; } qty.rawValue = yes * 10000 + no;"#,
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("many.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let mut asked = 0;
let out = loop {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(_), reply) => {
asked += 1;
reply.send(Some("4".into())).unwrap();
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(out) => break out,
}
};
assert_eq!(asked, 32);
let o = s.finish_javascript(p, out).unwrap();
assert!(o.error.is_none(), "the script goes on: {o:?}");
// 32 answered Yes; the other 28 got No without being asked.
assert_eq!(qty(&s, id), ["320028"]);
}
/// The 32-question limit holds for the whole click, not for each script session: a script that
/// turns field highlighting on or off starts a new session for the next, and the calculations
/// after it still can't ask more (they get the buttons' safe default).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_xfa_clicks_question_limit_holds_across_its_script_sessions() {
use crate::js::{InteractiveEvent, Prompt};
let asks = "app.runtimeHighlight = !app.runtimeHighlight; for (var i = 0; i &lt; 20; i++) xfa.host.messageBox(\"Again?\", \"\", 0, 1);";
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, asks)
.replace(
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
&format!("<calculate><script contentType=\"application/x-javascript\">{asks} qty.rawValue * price.rawValue</script></calculate>"),
)
.replace(
r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i &lt; rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#,
&format!("{asks} 0"),
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("hostile.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let mut asked = 0;
loop {
match next_event(&p) {
InteractiveEvent::Prompt(Prompt::Alert(_), reply) => {
asked += 1;
reply.send(Some("1".into())).unwrap();
}
InteractiveEvent::Prompt(other, _) => panic!("{other:?}"),
InteractiveEvent::Complete(_) => break,
}
}
assert_eq!(asked, 32, "the click and two calculations would ask 60 times");
}
/// A click whose script ran away turns the form's scripts off even when the click itself is
/// dropped (here the document changed while it ran), as a kept one does.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off() {
use crate::js::InteractiveEvent;
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
"xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j &lt; 99999; j++) {} } for (var k = 0; k &lt; 5000; k++) f();",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
// The script waits on its question until the other edit is in, so it cannot run away first.
let InteractiveEvent::Prompt(_, reply) = next_event(&p) else { panic!("asks first") };
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("6".into()) }).unwrap();
reply.send(Some("1".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert!(s.finish_javascript(p, out).is_err(), "the document changed");
assert!(!s.get(id).unwrap().xfa_scripts_off());
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap();
assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off");
assert!(s.take_js_output(id).errors.iter().any(|e| e.contains("scripts are off")));
}
/// Another click kept while a dropped one ran away leaves its signal for the next edit.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_click_kept_beside_one_that_ran_away_leaves_the_scripts_to_turn_off() {
use crate::js::InteractiveEvent;
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
"xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j &lt; 99999; j++) {} } for (var k = 0; k &lt; 5000; k++) f();",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let runaway = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
// The runaway script waits on its question until the other click has begun.
let InteractiveEvent::Prompt(_, reply) = next_event(&runaway) else { panic!("asks first") };
let kept = s.start_javascript_target(id, "", Some("addRow"), None).unwrap();
reply.send(Some("1".into())).unwrap();
let InteractiveEvent::Complete(ran) = next_event(&runaway) else { panic!("finishes") };
let InteractiveEvent::Complete(out) = next_event(&kept) else { panic!("finishes") };
assert_eq!(s.finish_javascript(kept, out).unwrap().error, None);
assert!(s.finish_javascript(runaway, ran).is_err(), "the document changed");
s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap();
assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off");
}
/// The viewer is asked with a FormCalc message clipped, as the message box kept is.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_formcalc_question_is_asked_clipped() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"$host.messageBox("FormCalc")"#, r#"var t = "x" while (Len(t) &lt; 100000) do t = Concat(t, t) endwhile $host.messageBox(t, t)"#);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("long.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert!(m.text.chars().count() <= 4_097, "{}", m.text.len());
assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097));
reply.send(None).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
assert_eq!(s.finish_javascript(p, out).unwrap().error, None);
}
/// The time a calculation waits for the user isn't the event's: the calculations after it still
/// run, though the wait is longer than their whole budget.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn waiting_for_an_answer_does_not_spend_the_events_time() {
use crate::js::{InteractiveEvent, Prompt};
let tpl = pdfcraft_xfa::fixtures::scripted_template()
.replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, "qty.rawValue = 5;")
.replace(
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
"<calculate><script contentType=\"application/x-javascript\">if (qty.rawValue == 5) xfa.host.messageBox(\"Recalculate?\", \"\", 2, 2); qty.rawValue * price.rawValue</script></calculate>",
)
.replace(
r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i &lt; rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#,
"qty.rawValue + 100",
);
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("slow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens");
let grand = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "grand").unwrap().value.clone();
assert_eq!(grand(&s), ["102"]);
let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap();
let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") };
assert_eq!(m.text, "Recalculate?");
// Longer than the calculations' 3 s budget.
std::thread::sleep(std::time::Duration::from_millis(3_500));
reply.send(Some("4".into())).unwrap();
let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") };
let o = s.finish_javascript(p, out).unwrap();
assert_eq!(o.error, None, "{o:?}");
assert_eq!(grand(&s), ["105"], "the calculation after the question ran");
}
#[test]
fn runaway_xfa_calculations_at_open_end_quickly_with_a_report() {
// Nested loops in one frame stop at the loop limit; loops in nested calls (that limit is per
@@ -11219,6 +11584,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
align: TextAlign::Left,
aligns: Vec::new(),
char_spacing: 0.0,
font_resource: None,
};
session.apply(id, Edit::AddText { page: 1, text }).unwrap();
let after = session.get(id).unwrap();
@@ -11261,6 +11627,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
align: TextAlign::Left,
aligns: Vec::new(),
char_spacing: 0.0,
font_resource: None,
},
},
Edit::MoveObjects { page: 0, objects: vec![target(crate::ObjectKind::Added)], offset: [1.0, 0.0] },
+38 -3
View File
@@ -157,17 +157,52 @@ impl Document {
if !self.marks().contains(&kind) {
return Ok(None);
}
self.unmarked_by(false, |cos| {
let n = pdfcraft_model::pages(cos).len();
pdfcraft_edit::remove_marks(cos, &(0..n).collect::<Vec<_>>(), kind)
})
}
/// The pages under the one header and footer recorded with `old`: without it and without what
/// is drawn after it on its pages, with every other mark under it. Update of that header and
/// footer puts the new one in its place (#5785), so its preview draws the draft on these and
/// [`Self::over_header_footer`] over the draft. `None` when nothing records `old`. Read-only,
/// like [`Self::without_marks`].
pub fn without_header_footer(&self, old: &pdfcraft_edit::HeaderFooter) -> Result<Option<UnmarkedPages>, String> {
if !self.marks().contains(&crate::MarkKind::HeaderFooter) {
return Ok(None);
}
// A header and footer gone since the dialog read it removes nothing here: the thumbnail is the page.
self.unmarked_by(false, |cos| pdfcraft_edit::under_header_footer(cos, old).or(Ok(0)))
}
/// What is drawn after the header and footer recorded with `old` on its pages, alone on
/// transparent pages: what Update keeps over the one replacing it. `None` when nothing is.
/// Read-only, like [`Self::without_marks`].
pub fn over_header_footer(&self, old: &pdfcraft_edit::HeaderFooter) -> Result<Option<UnmarkedPages>, String> {
if !self.marks().contains(&crate::MarkKind::HeaderFooter) {
return Ok(None);
}
self.unmarked_by(true, |cos| pdfcraft_edit::over_header_footer(cos, old))
}
/// A copy of the document with `remove` applied, for the preview, on `transparent` pages:
/// `None` when it removed nothing.
fn unmarked_by(
&self,
transparent: bool,
remove: impl FnOnce(&mut pdfcraft_cos::Document) -> Result<usize, pdfcraft_edit::EditError>,
) -> Result<Option<UnmarkedPages>, String> {
guard(|| {
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
let mut cos = editor.cos.clone();
let n = pdfcraft_model::pages(&cos).len();
if pdfcraft_edit::remove_marks(&mut cos, &(0..n).collect::<Vec<_>>(), kind).map_err(|e| e.to_string())? == 0 {
if remove(&mut cos).map_err(|e| e.to_string())? == 0 {
return Ok(None);
}
let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);
Ok(Some(UnmarkedPages {
bytes,
config: self.config.clone(),
config: RenderConfig { transparent, ..self.config.clone() },
parsed: None,
#[cfg(test)]
builds: 0,
+53 -4
View File
@@ -67,6 +67,8 @@ struct Clock {
#[cfg(not(target_arch = "wasm32"))]
started: std::time::Instant,
budget_ms: u64,
/// Time the scripts spent waiting for the user: not counted.
waited: std::time::Duration,
}
impl Clock {
@@ -75,17 +77,23 @@ impl Clock {
#[cfg(not(target_arch = "wasm32"))]
started: std::time::Instant::now(),
budget_ms,
waited: std::time::Duration::ZERO,
}
}
/// Leave `waited` out of the time spent: the time the scripts waited for the user isn't theirs.
fn extend(&mut self, waited: std::time::Duration) {
self.waited = self.waited.saturating_add(waited);
}
fn spent(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
self.started.elapsed() >= std::time::Duration::from_millis(self.budget_ms)
self.started.elapsed().saturating_sub(self.waited) >= std::time::Duration::from_millis(self.budget_ms)
}
#[cfg(target_arch = "wasm32")]
{
let _ = self.budget_ms;
let _ = (self.budget_ms, self.waited);
false
}
}
@@ -135,11 +143,33 @@ pub(crate) struct XfaRun<'a> {
/// start and each script's own): 1, unless the session was given another
/// ([`crate::Session::with_xfa_time_scale`]).
pub time_scale: u32,
/// The answers to the event's message boxes.
pub answers: XfaAnswers,
/// The form was laid out again: its pages, widgets and fields were replaced, so the edit
/// must rebuild the document's page and field lists, not only refresh their values.
pub relaid: bool,
}
/// The answers to one event's message boxes (`xfa.host.messageBox`, `$host.messageBox`,
/// `app.alert`): its click script and the calculations after it take them in order, each
/// script starting after the ones the scripts before it took. Past them, a message box asks the
/// user when `prompts` is set (an app's button click, run on a worker:
/// [`crate::Session::start_javascript_target`]), and otherwise gets its buttons' safe default.
#[derive(Clone, Debug, Default)]
pub(crate) struct XfaAnswers {
/// The answers, in order (`None`: closed without picking a button).
pub given: Vec<Option<String>>,
/// Message boxes the event's scripts have shown so far.
pub used: usize,
/// Where the scripts' questions go, for the viewer to ask.
#[cfg(not(target_arch = "wasm32"))]
pub prompts: Option<std::sync::mpsc::Sender<crate::js::InteractiveEvent>>,
/// Questions the event has asked, across the script sessions it uses
/// ([`XfaSession::with_prompts`]).
#[cfg(not(target_arch = "wasm32"))]
pub asked: Arc<std::sync::atomic::AtomicUsize>,
}
/// The script engine's copies of a form's property trees, by the address of the tree each was
/// made from: made the first time a script of the form needs one, then shared by every later
/// script and event of that form. They are kept in the form's template
@@ -567,7 +597,17 @@ impl<'a, 'b> Runner<'a, 'b> {
fn session(&mut self) -> &mut XfaSession {
let doc_info = XfaDoc { file_name: String::new(), page: 0, page_count: self.run.page_count, highlight: self.run.highlight };
let scale = self.run.time_scale;
self.session.get_or_insert_with(|| XfaSession::new(doc_info).with_time_scale(scale))
#[cfg(not(target_arch = "wasm32"))]
let (prompts, asked) = (self.run.answers.prompts.clone(), Arc::clone(&self.run.answers.asked));
self.session.get_or_insert_with(|| {
let session = XfaSession::new(doc_info).with_time_scale(scale);
#[cfg(not(target_arch = "wasm32"))]
let session = match prompts {
Some(p) => session.with_prompts(p, asked),
None => session,
};
session
})
}
/// Give the object at `som` the value `text` in the data and in the live form (refreshed
@@ -1015,7 +1055,14 @@ impl<'a, 'b> Runner<'a, 'b> {
self.runs += 1;
#[cfg(test)]
self.check_live();
let event = XfaEvent { activity: ev.activity.clone(), target: ev.som.clone(), new_text: new_text.to_string(), prev_text: String::new() };
let used = self.run.answers.used;
let event = XfaEvent {
activity: ev.activity.clone(),
target: ev.som.clone(),
new_text: new_text.to_string(),
prev_text: String::new(),
answers: self.run.answers.given.get(used..).unwrap_or_default().to_vec(),
};
let tpl = self.tpl;
let root = match &self.js_root {
Some(r) => Arc::clone(r),
@@ -1039,6 +1086,8 @@ impl<'a, 'b> Runner<'a, 'b> {
// The thread is left to the runaway script: nothing more is sent to it.
self.session = None;
}
self.clock.extend(o.waited);
self.run.answers.used = used.saturating_add(o.messages);
self.console(o.console.iter().cloned());
for n in &o.notes {
self.error(format!("{} ({}): {n}", ev.som, ev.activity));
+1
View File
@@ -243,6 +243,7 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E
ran_away: false,
highlight,
time_scale: cx.xfa_time_scale,
answers: Default::default(),
relaid: false,
};
let r = guard(|| xfa::on_data_replaced(doc, &tpl, calculate, &mut run))
+1 -1
View File
@@ -16,7 +16,7 @@ craft-mime.workspace = true
craft-rtf = { workspace = true, features = ["doc"] }
craft-wordmodel.workspace = true
craft-docx.workspace = true
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844", version = "0.1.0", features = ["standalone"] }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8", version = "0.1.0", features = ["standalone"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
craft-pptx.workspace = true
craft-xml.workspace = true
+2
View File
@@ -138,6 +138,7 @@ pub(crate) fn run_formcalc_at(
Err(e) => return XfaOutcome { error: Some(e), ..Default::default() },
};
let mut host = XHost::new(root, reuse, &event.target, doc);
host.answers = event.answers.clone();
#[cfg(target_arch = "wasm32")]
let _ = deadline;
let mut interp = Interp {
@@ -186,6 +187,7 @@ pub(crate) fn run_formcalc_at(
out.notes = host.notes();
out.effects = host.effects;
out.console = host.console;
out.messages = host.messages;
clip_result(&mut out);
out
}
+11 -4
View File
@@ -249,10 +249,17 @@ impl Interp<'_> {
let title = Some(self.arg_str(args, 1)?).filter(|t| !t.is_empty());
let icon = MessageIcon::from_code(Some(self.arg_num(args, 2)?));
let buttons = MessageButtons::from_code(Some(self.arg_num(args, 3)?));
self.h.push(XfaEffect::MessageBox(Message { text, title, icon, buttons }));
// Always OK for now: the viewer can't ask the user and run the script on
// with the answer yet (#4291).
Ok(Val::Num(1.0))
// The button picked: 1 OK, 2 Cancel, 3 No, 4 Yes. Time spent waiting for the
// user isn't the script's: its deadline moves on by it.
#[cfg(not(target_arch = "wasm32"))]
let asked = std::time::Instant::now();
let reply = self.h.message_box(Message { text, title, icon, buttons })?;
#[cfg(not(target_arch = "wasm32"))]
if crate::interaction::has_host() {
let waited = asked.elapsed();
self.deadline = self.deadline.and_then(|d| d.checked_add(waited));
}
Ok(Val::Num(f64::from(reply)))
}
"resetdata" => {
let list = self.arg_str(args, 0)?;
+6 -21
View File
@@ -78,33 +78,18 @@ pub(crate) fn message_box_message(args: &[JsValue], ctx: &mut Context) -> JsResu
}
/// `app.alert(cMsg, nIcon, nType, cTitle)`: records the message with its title, icon and buttons,
/// given in that order or as one object with those keys, and returns 1 (the OK button).
/// given in that order or as one object with those keys, and returns the button picked (1 OK,
/// 2 Cancel, 3 No, 4 Yes). Where nobody can be asked (the web build, a script run outside a
/// document's session), that is the buttons' safe default, as when the dialog is closed.
fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = alert_message(args, ctx)?;
host(ctx)?.borrow_mut().alert(m.clone());
if !crate::interaction::has_host() {
return Ok(JsValue::from(1));
return Ok(JsValue::from(i32::from(m.buttons.safe_default())));
}
let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone()))?;
let fallback = match m.buttons {
MessageButtons::Ok => "1",
MessageButtons::YesNo => "3",
_ => "2",
};
let answer = answer.as_deref().unwrap_or(fallback);
let accepted = match m.buttons {
MessageButtons::Ok => ["1"].as_slice(),
MessageButtons::OkCancel => ["1", "2"].as_slice(),
MessageButtons::YesNo => ["3", "4"].as_slice(),
MessageButtons::YesNoCancel => ["2", "3", "4"].as_slice(),
};
if answer == "1" && !accepted.contains(&"1") {
return Ok(JsValue::from(2));
}
if !accepted.contains(&answer) {
return Err(error("invalid alert response"));
}
Ok(JsValue::from(answer.parse::<i32>().unwrap_or(2)))
let reply = m.buttons.reply(answer.as_deref()).ok_or_else(|| error("invalid alert response"))?;
Ok(JsValue::from(i32::from(reply)))
}
/// `app.beep()`: queues a request to beep.
+8 -1
View File
@@ -21,6 +21,8 @@ pub enum InteractiveEvent {
Prompt(Prompt, Sender<Option<String>>),
Complete(Outcome),
}
/// Most prompts one script invocation (an AcroForm script, an XFA event) shows the user.
pub const MAX_PROMPTS: usize = 32;
thread_local! { static HOST:RefCell<Option<(Sender<InteractiveEvent>,usize)>>=const {RefCell::new(None)}; }
/// Tell alert/menu helpers whether this worker has an interactive or deterministic reply channel.
pub(crate) fn has_host() -> bool {
@@ -31,12 +33,17 @@ pub(crate) fn has_host() -> bool {
pub(crate) fn set_host(host: Option<Sender<InteractiveEvent>>) {
HOST.with(|h| *h.borrow_mut() = host.map(|h| (h, 0)));
}
/// Whether the invocation may still ask: it has a prompt channel and has asked fewer than
/// [`MAX_PROMPTS`] questions.
pub(crate) fn can_ask() -> bool {
HOST.with(|h| h.borrow().as_ref().is_some_and(|(_, n)| *n < MAX_PROMPTS))
}
/// Charge one prompt to the invocation's budget: the channel to send it on, if the worker has one.
fn reserve() -> JsResult<Option<Sender<InteractiveEvent>>> {
HOST.with(|h| {
let mut h = h.borrow_mut();
let Some((tx, n)) = h.as_mut() else { return Ok(None) };
if *n >= 32 {
if *n >= MAX_PROMPTS {
return Err(error("too many interactive prompts"));
}
*n += 1;
+35
View File
@@ -266,6 +266,41 @@ impl MessageButtons {
MessageButtons::YesNoCancel => "yes_no_cancel",
}
}
/// What a script receives when nobody picks a button (closing the dialog, no answer given):
/// OK (1) when that is the only button, No (3) for Yes/No, otherwise Cancel (2).
pub fn safe_default(self) -> u8 {
match self {
MessageButtons::Ok => 1,
MessageButtons::YesNo => 3,
MessageButtons::OkCancel | MessageButtons::YesNoCancel => 2,
}
}
/// The number a script receives for `answer`, the button picked as the references number
/// them (1 OK, 2 Cancel, 3 No, 4 Yes): no answer is [`MessageButtons::safe_default`], and OK
/// where these buttons have none is Cancel. `None`: an answer these buttons can't give.
pub fn reply(self, answer: Option<&str>) -> Option<u8> {
let Some(answer) = answer else { return Some(self.safe_default()) };
let n = match answer {
"1" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
_ => return None,
};
let accepted: &[u8] = match self {
MessageButtons::Ok => &[1],
MessageButtons::OkCancel => &[1, 2],
MessageButtons::YesNo => &[3, 4],
MessageButtons::YesNoCancel => &[2, 3, 4],
};
match n {
1 if !accepted.contains(&1) => Some(2),
n if accepted.contains(&n) => Some(n),
_ => None,
}
}
}
/// `code` as one of the numbers 0 to 3 the references define, when it is exactly one.
+122 -6
View File
@@ -504,9 +504,32 @@ fn app_alert_falls_back_on_bad_icon_and_button_numbers() {
assert_eq!(m, Message::plain("Hi"), "{bad}");
}
assert_eq!(alerted("'Hi', '2', '3'"), Message { icon: MessageIcon::Question, buttons: MessageButtons::YesNoCancel, ..Message::plain("Hi") });
// Every call still answers OK (1) until answers are asked for (#4291).
let o = go("event.value = String(app.alert('Delete?', 2, 2));", &Event::field("Mouse Up", "agree", ""));
assert_eq!(o.value, "1");
// Outside a document's session (and on the web build) nobody can be asked: each call gets
// its buttons' safe default, as a closed dialog does (#4291).
for (buttons, want) in [(0, "1"), (1, "2"), (2, "3"), (3, "2")] {
let o = go(&format!("event.value = String(app.alert('Delete?', 2, {buttons}));"), &Event::field("Mouse Up", "agree", ""));
assert_eq!(o.value, want, "{buttons}");
}
}
/// The number a script receives for each answer: the references' button numbers, checked
/// against the buttons shown, with no answer the safe default (#4291).
#[test]
fn message_replies_follow_the_buttons() {
use MessageButtons as B;
let cases = [
(B::Ok, [Some(1), Some(1), None, None, None]),
(B::OkCancel, [Some(2), Some(1), Some(2), None, None]),
(B::YesNo, [Some(3), Some(2), None, Some(3), Some(4)]),
(B::YesNoCancel, [Some(2), Some(2), Some(2), Some(3), Some(4)]),
];
for (buttons, want) in cases {
let got = [None, Some("1"), Some("2"), Some("3"), Some("4")].map(|a| buttons.reply(a));
assert_eq!(got, want, "{buttons:?}");
for bad in ["0", "5", " 4", "04", "yes", ""] {
assert_eq!(buttons.reply(Some(bad)), None, "{buttons:?} {bad}");
}
}
}
/// A title is cut to a message's length like the text, and both are charged to the run's byte
@@ -1242,9 +1265,35 @@ mod xfa_model {
assert_eq!(boxed("xfa.host.messageBox('Hi', null, 2.5, 'x')"), Message::plain("Hi"));
let m = boxed("xfa.host.messageBox('Hi', new Array(100000).join('t'))");
assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097));
// Answers are always OK for now (#4291).
let o = go("this.rawValue = xfa.host.messageBox('Delete?', 'T', 2, 2)", "form1[0].page1[0].qty[0]", "click");
assert!(o.effects.iter().any(|e| matches!(e, XfaEffect::SetValue { value, .. } if value == "1")), "{:?}", o.effects);
}
/// Run the JavaScript `script` as the go button's click, with `answers` to its message boxes.
fn answered(script: &str, answers: &[Option<&str>]) -> XfaOutcome {
let ev = XfaEvent {
activity: "click".into(),
target: "form1[0].page1[0].go[0]".into(),
answers: answers.iter().map(|a| a.map(String::from)).collect(),
..Default::default()
};
run_xfa(script, &ev, &XfaDoc::default(), &form(), Limits::default())
}
/// `xfa.host.messageBox` and `app.alert` in an XFA script return the button picked, from the
/// event's answers in order (#4291), so a script can branch on No and Cancel; past the
/// answers, where nobody can be asked, each gets its buttons' safe default.
#[test]
fn message_box_returns_the_answer_given() {
let script = "var r = [xfa.host.messageBox('Clear?', 'T', 2, 2), app.alert('Sure?', 2, 3), xfa.host.messageBox('Saved')]; r.join(',')";
let o = answered(script, &[Some("4"), Some("2"), None]);
assert_eq!((o.result.as_deref(), o.error.as_deref(), o.messages), (Some("4,2,1"), None, 3), "{o:?}");
let o = answered(script, &[Some("3"), Some("4")]);
assert_eq!(o.result.as_deref(), Some("3,4,1"), "{o:?}");
// No answers: the safe defaults (No; Cancel; OK).
let o = answered(script, &[]);
assert_eq!(o.result.as_deref(), Some("3,2,1"), "{o:?}");
// An answer the buttons can't give fails the script, naming it.
let o = answered("xfa.host.messageBox('Clear?', 'T', 2, 2)", &[Some("2")]);
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (2)") && e.contains("yes_no")), "{o:?}");
}
/// `app.alert` in an XFA form's script reads its own order (`cMsg, nIcon, nType, cTitle`)
@@ -2065,6 +2114,35 @@ $host.gotoURL("https://example.org")"#,
assert!(matches!(o.effects.as_slice(), [XfaEffect::MessageBox(m)] if m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097)));
}
/// FormCalc's `$host.messageBox` returns the button picked, from the event's answers in
/// order, as the JavaScript one does (#4291).
#[test]
fn formcalc_message_box_returns_the_answer_given() {
let run = |answers: &[Option<&str>]| {
let ev = XfaEvent {
activity: "click".into(),
target: "form1[0].page1[0].go[0]".into(),
answers: answers.iter().map(|a| a.map(String::from)).collect(),
..Default::default()
};
run_formcalc(
"Concat($host.messageBox(\"Clear?\", \"T\", 2, 3), \",\", $host.messageBox(\"Sure?\", \"\", 2, 1))",
&ev,
&XfaDoc::default(),
&form(),
Limits::default(),
)
};
let o = run(&[Some("3"), Some("1")]);
assert_eq!(o.result.as_deref(), Some("3,1"), "{o:?}");
let o = run(&[Some("4")]);
assert_eq!(o.result.as_deref(), Some("4,2"), "{o:?}");
let o = run(&[None, None]);
assert_eq!(o.result.as_deref(), Some("2,2"), "{o:?}");
let o = run(&[Some("9")]);
assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (9)")), "{o:?}");
}
fn run_hostile_formcalc(script: &str) -> XfaOutcome {
let ev = XfaEvent { activity: "calculate".into(), target: "form1[0].page1[0].total[0]".into(), ..Default::default() };
let doc = XfaDoc::default();
@@ -2133,6 +2211,44 @@ mod session {
assert_eq!(o.result.as_deref(), Some("4:hidden"), "{o:?}");
}
/// A session that can ask passes each message box's question on and gives the script the
/// answer, in JavaScript and FormCalc alike (#4291). The user's time isn't the script's: one
/// answered after its time limit has passed still finishes, and says how long it waited.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_session_that_can_ask_waits_for_the_answer_with_its_clock_stopped() {
use crate::interaction::{InteractiveEvent, Prompt};
let (tx, rx) = std::sync::mpsc::channel();
let answerer = std::thread::spawn(move || {
let mut asked = Vec::new();
for answer in ["4", "3", "2"] {
let Ok(InteractiveEvent::Prompt(Prompt::Alert(m), reply)) = rx.recv() else { break };
asked.push(m.text);
// Longer than the scripts' time limit below.
std::thread::sleep(std::time::Duration::from_millis(400));
let _ = reply.send(Some(answer.to_string()));
}
asked
});
let mut s = XfaSession::new(XfaDoc::default()).with_prompts(tx, Default::default());
let mut js = script("xfa.host.messageBox('Clear?', 'T', 2, 2) + ',' + app.alert('Sure?', 2, 2)", false, "form1[0].page1[0].go[0]", "click");
js.timeout = std::time::Duration::from_millis(300);
let o = s.run(js);
assert_eq!((o.result.as_deref(), o.error.as_deref(), o.abandoned), (Some("4,3"), None, false), "{o:?}");
assert!(o.waited >= std::time::Duration::from_millis(800), "{:?}", o.waited);
// FormCalc keeps its own deadline, read as it works: it works on after the answer.
let mut fc = script(
"var r = $host.messageBox(\"Save?\", \"\", 2, 3)\nvar i = 0\nwhile (i < 20000) do i = i + 1 endwhile\nr",
true,
"form1[0].page1[0].go[0]",
"click",
);
fc.timeout = std::time::Duration::from_millis(300);
assert_eq!(s.run(fc).result.as_deref(), Some("2"));
drop(s);
assert_eq!(answerer.join().unwrap_or_default(), ["Clear?", "Sure?", "Save?"]);
}
/// JavaScript and FormCalc scripts run in turn in one session, each on the form the caller
/// sends: nothing an earlier script changed or defined leaks into the next, a failing script
/// doesn't end the session, and hundreds of scripts run on its one thread.
+11 -9
View File
@@ -43,23 +43,25 @@ fn set_runtime_highlight(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> Js
Ok(JsValue::undefined())
}
/// `xfa.host.messageBox(message, title, icon, buttons)`: records the message with its title,
/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns 1.
/// Shows message box `m` and returns the button picked ([`XHost::message_box`]).
fn show(ctx: &mut Context, m: crate::Message) -> JsResult<JsValue> {
let reply = host(ctx)?.borrow_mut().message_box(m).map_err(super::error)?;
Ok(JsValue::from(f64::from(reply)))
}
/// `xfa.host.messageBox(message, title, icon, buttons)`: shows the message with its title,
/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns the button
/// picked: 1 OK, 2 Cancel, 3 No, 4 Yes.
fn message_box(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = crate::globals::message_box_message(args, ctx)?;
effect(ctx, XfaEffect::MessageBox(m))?;
// Always OK for now: the viewer can't ask the user and run the script on with the answer
// yet (#4291).
Ok(JsValue::from(1.0))
show(ctx, m)
}
/// `app.alert(cMsg, nIcon, nType, cTitle)` in an XFA form's script: the same message box, its
/// arguments in `app.alert`'s order (or one object with those keys).
fn app_alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = crate::globals::alert_message(args, ctx)?;
effect(ctx, XfaEffect::MessageBox(m))?;
// The OK button, as for `messageBox` (#4291).
Ok(JsValue::from(1.0))
show(ctx, m)
}
/// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when
+34
View File
@@ -110,6 +110,10 @@ pub(crate) struct XHost {
/// Bytes of edges and corners copied when a script reached sides a border doesn't list,
/// against [`super::props::MAX_COPIED`].
pub(super) copied: usize,
/// The answers to the script's message boxes ([`super::XfaEvent::answers`]).
pub(crate) answers: Vec<Option<String>>,
/// Message boxes shown so far ([`super::XfaOutcome::messages`]).
pub(crate) messages: usize,
}
impl XHost {
@@ -153,9 +157,39 @@ impl XHost {
prop_writes: super::props::PropWrites::new(),
dropped_prop_writes: 0,
copied: 0,
answers: Vec::new(),
messages: 0,
}
}
/// Show message box `m` and return the button picked: the next of the event's answers
/// (headless runs); past them, the user's answer when the viewer can ask (an app's button
/// click: the script waits on its thread, as an AcroForm script's `app.alert` does), or
/// else the buttons' safe default. Past [`crate::interaction::MAX_PROMPTS`] questions nobody
/// is asked and the safe default is given, as it is when the click's questions are spent
/// across its script sessions: a form follows the same path either way. `Err`: an answer
/// `m`'s buttons can't give.
pub(crate) fn message_box(&mut self, m: Message) -> Result<u8, String> {
// Clipped before the viewer is asked, as the effect is: the dialog shows no more than is kept.
let m = Message { text: clip(m.text), title: m.title.map(clip), ..m };
let at = self.messages;
self.messages = self.messages.saturating_add(1);
let invalid = |answer: Option<&str>| {
let given: String = answer.unwrap_or("null").chars().take(32).collect();
format!("the answer to the script's message box {} ({given}) is not one of its buttons ({})", at.saturating_add(1), m.buttons.name())
};
let reply = match self.answers.get(at) {
Some(answer) => m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?,
None if crate::interaction::can_ask() => {
let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone())).map_err(|e| e.to_string())?;
m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?
}
None => m.buttons.safe_default(),
};
self.push(XfaEffect::MessageBox(m));
Ok(reply)
}
/// Room for `bytes` more bytes of kept text: charged when there is, a drop counted when not.
pub(super) fn room(&mut self, bytes: usize) -> bool {
match self.kept.checked_add(bytes).filter(|k| *k <= MAX_PAYLOAD) {
+12
View File
@@ -64,6 +64,12 @@ pub struct XfaEvent {
pub target: String,
pub new_text: String,
pub prev_text: String,
/// Answers to the script's message boxes, in order: each `xfa.host.messageBox`,
/// `$host.messageBox` or `app.alert` takes the next (`None`: closed without picking a
/// button), checked against its buttons by [`crate::MessageButtons::reply`]. Past the end,
/// a message asks the user when the viewer can ask ([`crate::xfa_session::XfaSession::with_prompts`]),
/// and otherwise gets its buttons' safe default.
pub answers: Vec<Option<String>>,
}
/// About the document.
@@ -141,6 +147,12 @@ pub struct XfaOutcome {
/// The script ran past its time limit and was left running on its own thread (the engine
/// can't interrupt it): the caller should run no more of this form's scripts.
pub abandoned: bool,
/// How many message boxes the script showed: the answers it took from
/// [`XfaEvent::answers`], so the next script of the event starts after them.
pub messages: usize,
/// How long the script waited for the user to answer its message boxes: not counted
/// against its time limit, nor the event's.
pub waited: std::time::Duration,
}
/// Most nodes a snapshot may hold.
+3 -1
View File
@@ -143,7 +143,8 @@ pub(crate) fn run_here(
};
ctx.runtime_limits_mut().set_loop_iteration_limit(limits.loop_iterations);
ctx.runtime_limits_mut().set_recursion_limit(limits.recursion);
let host_state = XHost::new(root, reuse, &event.target, doc);
let mut host_state = XHost::new(root, reuse, &event.target, doc);
host_state.answers = event.answers.clone();
let current = host_state.current;
ctx.insert_data(RefCell::new(host_state));
let mut out = XfaOutcome::default();
@@ -174,6 +175,7 @@ pub(crate) fn run_here(
out.notes = h.notes();
out.effects = h.effects;
out.console = h.console;
out.messages = h.messages;
}
clip_result(&mut out);
out
+62 -2
View File
@@ -75,13 +75,22 @@ mod native {
use std::time::{Duration, Instant};
use super::{Script, run_script};
use crate::interaction::{InteractiveEvent, MAX_PROMPTS, Prompt};
use crate::xfa::{ENGINE_START_LIMIT, XfaDoc, XfaOutcome};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Longest a script waits for the user to answer one message box, as an AcroForm script's
/// prompt waits; then it gets the buttons' safe default.
const PROMPT_LIMIT: Duration = Duration::from_secs(300);
enum Reply {
/// The thread is up.
Ready,
/// The engine is ready for the script just sent: its time starts now.
Started,
/// The script asks the user (a message box) and waits for the answer.
Prompt(Prompt, Sender<Option<String>>),
Outcome(Box<XfaOutcome>),
}
@@ -99,11 +108,26 @@ mod native {
dead: Option<String>,
/// How long the engine has to be ready for a script ([`ENGINE_START_LIMIT`] by default).
start_limit: Duration,
/// Where the scripts' questions go, when the viewer can ask the user
/// ([`XfaSession::with_prompts`]), and how many the event has asked.
prompts: Option<(Sender<InteractiveEvent>, Arc<AtomicUsize>)>,
}
impl XfaSession {
pub fn new(doc: XfaDoc) -> XfaSession {
XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT }
XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT, prompts: None }
}
/// Let the scripts' message boxes ask the user: each question goes to `prompts` with a
/// sender for the answer, and the script waits on its thread (at most [`PROMPT_LIMIT`]
/// for each), its time limit stopped meanwhile. `asked` counts the event's questions,
/// across every session the event uses (a script turning field highlighting on or off
/// starts a new one): past [`MAX_PROMPTS`] nobody is asked and each message box gets its
/// buttons' safe default, so a form can't keep the user answering. Without it a message
/// box takes the event's answers, then its buttons' safe default.
pub fn with_prompts(mut self, prompts: Sender<InteractiveEvent>, asked: Arc<AtomicUsize>) -> XfaSession {
self.prompts = Some((prompts, asked));
self
}
/// Multiply the time the engine has to be ready for a script by `factor` (a script's
@@ -125,7 +149,26 @@ mod native {
let (to, inbox) = channel::<Box<Script>>();
let (reply, from) = channel::<Reply>();
let doc = self.doc.clone();
let asking = self.prompts.is_some();
let spawned = std::thread::Builder::new().name("pdfcraft-xfa-session".into()).stack_size(crate::SCRIPT_STACK).spawn(move || {
// The scripts' questions reach the session (which passes them on and stops
// the clock while the user answers) through the reply channel. The host is
// set once for the thread, so the prompt limit holds for the whole event.
if asking {
let (questions, asked) = channel::<InteractiveEvent>();
let forward = reply.clone();
let forwarder = std::thread::Builder::new().name("pdfcraft-xfa-prompts".into()).spawn(move || {
while let Ok(InteractiveEvent::Prompt(prompt, answer)) = asked.recv() {
if forward.send(Reply::Prompt(prompt, answer)).is_err() {
break;
}
}
});
// Without the forwarder nobody would answer: the scripts don't ask.
if forwarder.is_ok() {
crate::interaction::set_host(Some(questions));
}
}
crate::xfa::warm_up();
// The caller is gone when a send fails: nothing to report then.
let _ = reply.send(Reply::Ready);
@@ -164,6 +207,7 @@ mod native {
}
let timeout = script.timeout;
let start_limit = self.start_limit;
let prompts = self.prompts.clone();
let worker = match self.worker() {
Ok(w) => w,
Err(why) => return failed(why),
@@ -176,18 +220,34 @@ mod native {
// The engine's start, then the script's own time.
let (mut running, mut limit) = (false, start_limit);
let mut deadline = Instant::now().checked_add(limit);
let mut waited = Duration::ZERO;
loop {
let left = deadline.map_or(limit, |d| d.saturating_duration_since(Instant::now()));
match worker.from.recv_timeout(left) {
Ok(Reply::Outcome(o)) => {
Ok(Reply::Outcome(mut o)) => {
// A FormCalc script its own clock stopped reports as abandoned: the
// session ends as it does when the wait runs out first.
if o.abandoned {
self.dead = o.error.clone();
self.worker = None;
}
o.waited = waited;
return *o;
}
Ok(Reply::Prompt(prompt, answer)) => {
// The user's time isn't the script's: its clock stops until the answer.
let asked = Instant::now();
let (give, given) = channel();
let sent = prompts.as_ref().is_some_and(|(p, asked)| {
asked.fetch_add(1, Ordering::Relaxed) < MAX_PROMPTS && p.send(InteractiveEvent::Prompt(prompt, give)).is_ok()
});
let reply = if sent { given.recv_timeout(PROMPT_LIMIT).ok().flatten() } else { None };
// The script's own wait may have ended first: then it took the default.
let _ = answer.send(reply);
let paused = asked.elapsed();
waited = waited.saturating_add(paused);
deadline = deadline.and_then(|d| d.checked_add(paused));
}
Ok(Reply::Started) => {
// A second call changes nothing: the script's time has already begun.
if !running {
+27 -2
View File
@@ -17,12 +17,24 @@ const MAX_ZONE_STREAM: u64 = 64 * 1024;
/// Give `target` the zone of `source`: its `Zone.Identifier` stream, copied as it is, or the
/// Internet zone when `source` is `None` or has no zone. Windows only; elsewhere nothing is
/// written. Fails where the volume keeps no alternate data streams (FAT32, exFAT, some network
/// shares), so callers treat the mark as best effort.
/// shares), so callers treat the mark as best effort. Fails with `NotFound` when `target` isn't an
/// existing file: writing `target:Zone.Identifier` would otherwise create an empty `target`. The
/// target is held open, without delete sharing, until the stream is written.
pub fn mark_from(target: &Path, source: Option<&Path>) -> std::io::Result<()> {
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
// FILE_SHARE_READ | FILE_SHARE_WRITE, without FILE_SHARE_DELETE: while this handle is open
// the target can't be deleted or renamed, so the stream write below can't recreate it.
const SHARE_READ_WRITE: u32 = 0x1 | 0x2;
let held = std::fs::OpenOptions::new().read(true).share_mode(SHARE_READ_WRITE).open(target)?;
if !held.metadata()?.is_file() {
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the zone's target is not a file"));
}
let zone = source.and_then(read_zone).unwrap_or_else(|| INTERNET_ZONE.as_bytes().to_vec());
std::fs::write(zone_stream(target), zone)
let written = std::fs::write(zone_stream(target), zone);
drop(held);
written
}
#[cfg(not(windows))]
{
@@ -109,6 +121,19 @@ mod tests {
assert_eq!(std::fs::read(&target).unwrap(), b"MZ", "the file's own bytes are untouched");
}
#[test]
fn a_missing_target_is_not_created() {
let dir = Dir::new("missing");
let target = dir.0.join("never saved.bin");
assert_eq!(mark_from(&target, None).unwrap_err().kind(), std::io::ErrorKind::NotFound);
assert!(!target.exists(), "marking a file that was never written must not create it");
assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0);
let folder = dir.0.join("folder");
std::fs::create_dir(&folder).unwrap();
assert!(mark_from(&folder, None).is_err(), "a folder is not given a zone");
assert!(read_zone(&folder).is_none());
}
#[test]
fn a_file_from_a_document_gets_that_documents_zone() {
let dir = Dir::new("copy");
+1 -1
View File
@@ -11,7 +11,7 @@ repository.workspace = true
workspace = true
[dependencies]
craft-cms-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-cms-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
craft-xml = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-cos = { workspace = true }
+42 -7
View File
@@ -35,6 +35,7 @@ mod pattern_guard;
pub mod patterns;
pub mod sanitize;
mod tags;
#[cfg(test)]
mod tests;
#[cfg(test)]
@@ -920,6 +921,13 @@ struct Applying {
pruned_patterns: Vec<ObjRef>,
}
/// Whether a stream's `/PCHeaderFooter` entry `v` records the same header and footer as one of
/// the entries taken off redacted streams (`raw`, and those of them that decode, `decoded`).
fn same_settings(doc: &Document, raw: &[Object], decoded: &[pdfcraft_edit::HeaderFooter], v: &Object) -> bool {
let value = doc.resolve(v);
raw.iter().any(|r| *doc.resolve(r) == *value) || pdfcraft_edit::recorded_header_footer(doc, v).is_some_and(|hf| decoded.contains(&hf))
}
/// Step 1 for one page: rewrites its content so nothing readable stays under a mark, and cleans the tags it no longer shows.
fn redact_page_content(
doc: &mut Document,
@@ -969,6 +977,8 @@ fn redact_page_content(
retired_properties.extend(out.retired_properties);
let mut new_list = list.clone();
let mut changed = false;
// Header and footer settings taken off a redacted stream (see below).
let mut redacted_settings: Vec<Object> = Vec::new();
for (i, new) in out.streams.into_iter().enumerate() {
let Some(bytes) = new else { continue };
let mut dict = match &*doc.resolve(&list[i]) {
@@ -980,10 +990,32 @@ fn redact_page_content(
// are redacted, keeping it would leave the redacted text in the file. The item stays
// as plain drawn content but is no longer editable.
dict.remove(b"PCAdded");
// A header and footer keeps its text templates in `/PCHeaderFooter` (#5785): the same goes.
// The mark stays as drawn content, which Update can only replace page-wide.
redacted_settings.extend(dict.remove(b"PCHeaderFooter"));
// A new object: the original may be shared with other pages.
new_list[i] = Object::Ref(doc.add(Object::Stream(Stream::flate(dict, &bytes))));
changed = true;
}
// A shrinking header's `cm` stream records the same settings but draws no text, so it is
// never rewritten above: take its copy of the templates away too.
// Matched by what the settings say, not how they are stored: a rewriting tool may make the
// entry indirect on one stream and leave it direct on the other.
// Only the entry goes: the stream's content is still what was read for it above.
let mut settings_only = Vec::new();
if !redacted_settings.is_empty() {
let decoded: Vec<pdfcraft_edit::HeaderFooter> =
redacted_settings.iter().filter_map(|v| pdfcraft_edit::recorded_header_footer(doc, v)).collect();
for (i, o) in new_list.iter_mut().enumerate() {
let mut stream = match &*doc.resolve(o) {
Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| same_settings(doc, &redacted_settings, &decoded, v)) => s.clone(),
_ => continue,
};
stream.dict.remove(b"PCHeaderFooter");
*o = Object::Ref(doc.add(Object::Stream(stream)));
settings_only.push(i);
}
}
if changed || !out.xobjects.is_empty() || !out.replaced.is_empty() {
let mut res = resources.clone();
if !out.xobjects.is_empty() || !out.replaced.is_empty() {
@@ -999,14 +1031,17 @@ fn redact_page_content(
.iter()
.zip(&list)
.zip(&data)
.map(|((now, was), read)| match &*doc.resolve(now) {
// Left as it was: what was read above, with its parameters by reference.
_ if now == was => read.clone(),
// Written above by `Stream::flate`, which leaves no `/DecodeParms`.
Object::Stream(s) => s.decoded().unwrap_or_default(),
_ => Vec::new(),
.enumerate()
.map(|(i, ((now, was), read))| match &*doc.resolve(now) {
// Left as it was, or only its header settings taken off (keeping its
// `/Filter` and `/DecodeParms`, perhaps by reference): what was read above.
_ if now == was || settings_only.contains(&i) => Ok(read.clone()),
// Written above by `Stream::flate`. One that won't decode is an error, not
// empty content: `prune` would take that as drawing nothing.
Object::Stream(s) => doc.with_direct_parms(s).decoded(),
_ => Ok(Vec::new()),
})
.collect();
.collect::<Result<_, _>>()?;
interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content)?;
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
+91
View File
@@ -245,6 +245,44 @@ fn an_image_drawn_again_in_content_with_parameters_by_reference_stays() {
assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4])));
}
/// #6352 review: a stream that only records a redacted header's settings keeps its `/Filter`
/// and `/DecodeParms` when the settings are taken off. Read again without its parameters (given by
/// reference), it seemed to draw nothing, so an image it draws, removed under the mark elsewhere on
/// the page, lost its resource while the stream still drew it.
#[test]
fn an_image_drawn_by_a_stream_keeping_header_settings_stays() {
use pdfcraft_cos::{Dict, ObjRef, Object};
let img = stream("/Type /XObject /Subtype /Image /Width 4 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", [255, 255, 255, 255]);
let mut doc = one_page(b"q 10 0 0 10 10 270 cm /Im1 Do Q", "/XObject << /Im1 7 0 R >>", vec![img]);
let mut hf = pdfcraft_edit::HeaderFooter::default();
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let mut contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let settings = contents
.iter()
.find_map(|o| match &*doc.resolve(o) {
Object::Stream(s) => s.dict.get(b"PCHeaderFooter").cloned(),
_ => None,
})
.unwrap();
let mut again = predicted(&mut doc, Dict::new(), b"q 10 0 0 10 200 100 cm /Im1 Do Q");
again.dict.set(b"PCHeaderFooter".to_vec(), settings);
contents.push(Object::Ref(doc.add(Object::Stream(again))));
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap();
// Over the header and the image drawn at the top, not the one drawn again below.
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.images_removed, 1, "{r:?}");
let doc = reopen(&doc);
assert!(content(&doc, 0).contains("200 100 cm /Im1 Do"), "{}", content(&doc, 0));
let p = pdfcraft_model::pages(&doc).swap_remove(0);
let res = doc.resolve(p.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
let Some(Object::Stream(image)) = xo.reference(b"Im1").map(|r| (*doc.get(r)).clone()) else { panic!("no /Im1: {xo:?}") };
assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4])));
}
/// #2130: a font with no /Widths is drawn with its embedded program's advances. Measured with a
/// guess from its name instead (Courier's 600 units for "Mono"), the end of the line seemed to
/// lie past a mark that covers all of it on screen, and was kept.
@@ -687,6 +725,59 @@ fn added_text_parameters_do_not_keep_redacted_text() {
assert!(!bytes.windows(4).any(|w| w == b"1234"), "redacted text left in the saved file");
}
#[test]
fn a_redacted_header_keeps_no_copy_of_its_text() {
// A header and footer records its templates in /PCHeaderFooter, on its own stream and, when
// it shrinks the page, on the shrink's `cm` stream too (#5785).
let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() };
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(7).any(|w| w == b"SECRET9"), "the settings are written in the clear");
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
apply(&mut doc, None).unwrap();
let bytes = write_full(&doc, &SaveOptions::default()).unwrap();
assert!(!bytes.windows(7).any(|w| w == b"SECRET9"), "the redacted header's text left in the saved file");
assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays");
}
#[test]
fn a_redacted_header_keeps_no_copy_of_its_text_however_its_streams_store_it() {
let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() };
hf.text[1] = "SECRET9".into();
pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap();
// As a rewriting tool may: one stream's settings moved to an object of their own, the
// other's left in place, so the two entries are no longer the same value.
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let recorded: Vec<ObjRef> = contents
.iter()
.filter_map(|o| match o {
Object::Ref(r) => Some(*r),
_ => None,
})
.filter(|r| matches!(&*doc.resolve(&Object::Ref(*r)), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some()))
.collect();
assert_eq!(recorded.len(), 2, "the header's stream and its shrink's");
for &moved in &recorded {
let mut doc = doc.clone();
let settings = match &*doc.resolve(&Object::Ref(moved)) {
Object::Stream(s) => s.dict.get(b"PCHeaderFooter").unwrap().clone(),
_ => panic!("a content stream"),
};
let indirect = doc.add(settings);
doc.update_dict(moved, |d| d.set(b"PCHeaderFooter".to_vec(), Object::Ref(indirect))).unwrap();
mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], "");
apply(&mut doc, None).unwrap();
let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone();
let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec();
let left = contents.iter().filter(|o| matches!(&*doc.resolve(o), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some())).count();
assert_eq!(left, 0, "a stream of the redacted header still records its settings ({moved:?} indirect)");
assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays");
}
}
#[test]
fn operators_split_across_content_streams_are_redacted_whole() {
// One content stream in three pieces, split between tokens: a marked-content dictionary
+1 -1
View File
@@ -12,7 +12,7 @@ workspace = true
[dependencies]
# Existing shared ASN.1 codec; PDF signature policy remains local.
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "0a6e42b80bfd586aee6ee1144aa98cf1ea37a844" }
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" }
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-content = { workspace = true }
+9
View File
@@ -114,6 +114,15 @@ needs a prompt to open is listed and asks at signing (issue #179).
- **Weak algorithms still validate, and say so.** SHA-1 and RIPEMD-160 signatures are common in
documents signed years ago, so they validate (new signatures never use SHA-1), but the signature's
details say that the algorithm is weak and shouldn't be relied on.
- **Trust is the user's decision.** Only the user's own list (`TrustStore::certs`) is trusted by
default. A trust list the user loads from a file (`sign_trust eu_trusted_list`, the EU Trusted
Lists' qualified CAs, say) is kept apart from it (`TrustStore::lists`), off until loaded, and
named in the details when it vouches. Nothing of the kind is embedded. A list vouches for
signers, never for a time-stamp authority: trusted time comes from the user's own certificates.
- **Not Adobe's list.** Adobe's AATL is not used: Adobe-authored data outside the closed list in
AGENTS.md §1.1 needs the owner's explicit approval, and the EU Trusted Lists (and, planned, the
operating system's store) cover the same ground. A signer that chains only to an AATL root stays
"unknown" until the user trusts that root.
- **Validation algorithms:** digests SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256,
SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and
salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and
+3 -2
View File
@@ -21,6 +21,7 @@ pub mod pkcs12;
pub mod revocation;
pub mod status_layers;
pub mod timestamp;
pub mod trust;
#[cfg(target_os = "windows")]
pub mod windows;
pub mod x509;
@@ -29,8 +30,8 @@ pub use der::Time;
pub use graphic::Graphic;
pub use keys::{DigestAlg, PrivateKey, PublicKey};
pub use pdf::{
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words,
has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustSource, TrustStore, WORDINGS,
Words, has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
};
pub use pkcs12::DigitalId;
pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb};

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