From aec0a777869625b7b848667e9e34f1ca94587590 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:15:29 +0100 Subject: [PATCH 01/13] [repo] Workspace: CLAUDE.md, DEPENDENCIES.md, deps check, pinned pdfium fetch --- CLAUDE.md | 55 +++++++++++++++++++++++++ Cargo.toml | 39 ++++++++++++++++++ docs/DEPENDENCIES.md | 86 ++++++++++++++++++++++++++++++++++++++++ rustfmt.toml | 2 + scripts/deps.mjs | 66 ++++++++++++++++++++++++++++++ scripts/fetch-pdfium.ps1 | 42 ++++++++++++++++++++ 6 files changed, 290 insertions(+) create mode 100644 CLAUDE.md create mode 100644 Cargo.toml create mode 100644 docs/DEPENDENCIES.md create mode 100644 rustfmt.toml create mode 100644 scripts/deps.mjs create mode 100644 scripts/fetch-pdfium.ps1 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..181fc42 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,55 @@ +# Pictor Domi — core (public) + +Pictor (Latin: painter) is the Domi snipping tool, PDF workbench and image toolbox. +This repository is the **public, MPL-2.0 core** (`https://gitea.marek-novak.cz/mnovak/Pictor-public`; the brief +calls it `pictor-core`): pure Rust, no network, no UI. The Windows app lives in the private `Pictor` repo +(`https://gitea.marek-novak.cz/mnovak/Pictor`, the brief's `pictor`) and depends on this one **by git tag**, +never by a local path. The brief and roadmap are in the app repo, `docs/roadmap.md`; the day pages are there too +(`docs/01_v1.md`). + +## Layout +``` +crates/raster decode (with pixel and size caps), encode, convert, crop, rotate, resize, batch presets, + compress to a target size; HEIC/HEIF through the Windows Imaging Component (OS codec, Windows only) +crates/pdf pdfium (render, text, search, outline, forms, page ops, merge/split, image <-> pdf, flatten, + unlock) + lopdf (annotations, stamps, redaction rebuild, encryption, metadata); docs/FORMATS.md +crates/meta read and strip EXIF / GPS / XMP / IPTC from images, document info and XMP from PDFs +crates/qr QR payloads (text, URL, Wi-Fi, contact), PNG and SVG, centre logo (level forced to H) +crates/save atomic save: temp file + flush + rename, the .bak, the -edited.pdf naming +crates/worker pictor-worker.exe: the only process that parses outside files (JSON lines on stdin/stdout, + docs/FORMATS.md); the app spawns it in a Job Object with a memory cap and kills it on a time cap +scripts/ fetch-pdfium.ps1 (pinned release + sha256 -> third_party/pdfium/), deps.mjs (DEPENDENCIES.md table) +fixtures-fetch/ fetch.ps1: sha256-pinned hostile corpora -> fixtures/fetched/ (never in git) +docs/ FORMATS.md (formats, the worker protocol), DEPENDENCIES.md (every crate and its licence) +``` +Direction: `worker → pdf, raster, meta, qr, save`; `pdf → meta, raster`. The library crates never spawn processes, +open sockets or touch the registry. + +## Commands +``` +powershell -File scripts/fetch-pdfium.ps1 # pdfium.dll -> third_party/pdfium/bin (tests need it) +powershell -File fixtures-fetch/fetch.ps1 # optional extra hostile corpora; the generated ones need nothing +cargo test --workspace # all mandatory tests (PDFIUM_DYNAMIC_LIB_PATH overrides the dll folder) +node scripts/deps.mjs # regenerate the crate table in docs/DEPENDENCIES.md; exits 1 on a + # licence outside the allowed set +``` +On the dev machine `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits) — already set. + +## Rules +- Commits: `[] : `, e.g. `[pdf] Redaction: drop the struct tree`. +- **No AI attribution in commits or PRs, ever**: no `Co-Authored-By`, no session links, no "Generated with". +- **No binaries in git**: pdfium and corpora are fetched by sha256-pinned scripts. +- **Licence rule**: a new crate is recorded in `docs/DEPENDENCIES.md` (with its licence) before it is used. + Allowed: MIT, Apache-2.0, BSD, Zlib, MPL-2.0 (and their no-deal equivalents listed there), or an OS codec. + Anything else: stop and report. `node scripts/deps.mjs` must exit 0. +- **Hostile input**: every outside file is parsed only inside `pictor-worker`, with caps (pixels, bytes, time, + memory). Library functions take explicit `Limits`; no unbounded allocation from a size read out of a file. +- Tests first where the risk is (redaction, hostile PDFs and images, metadata, save safety, QR round trip). +- Branch → PR on Gitea (token in `$GITEA_TOKEN`, never echoed; pushed through git's environment config) → + self-review in the PR body → merge `--no-ff` → push → `git rev-parse HEAD origin/main` twice the same → + tag `vX.Y.Z` (the app pins tags). + +## Known traps +- pdfium is not thread-safe: pdfium-render's `thread_safe` feature serialises calls; one `Pdfium` per process. +- pdfium's own save copies unreferenced objects of the original file: anything that must *disappear* (redaction) + is written by lopdf after `prune_objects`, never by pdfium. diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..904f6dc --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,39 @@ +[workspace] +resolver = "3" +members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public" +rust-version = "1.88" + +# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. +[workspace.dependencies] +pictor-raster = { path = "crates/raster" } +pictor-pdf = { path = "crates/pdf" } +pictor-meta = { path = "crates/meta" } +pictor-qr = { path = "crates/qr" } +pictor-save = { path = "crates/save" } + +thiserror = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +base64 = "0.22" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] } +kamadak-exif = "0.6" +img-parts = "0.4" +qrcode = { version = "0.14", default-features = false, features = ["svg"] } +lopdf = { version = "0.47", default-features = false } +pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] } +tempfile = "3" +sha2 = "0.11" +windows = "0.62" + +# dev-only +rqrr = "0.11" +proptest = "1" + +[profile.dev.package."*"] +opt-level = 2 diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md new file mode 100644 index 0000000..2b24528 --- /dev/null +++ b/docs/DEPENDENCIES.md @@ -0,0 +1,86 @@ +# Dependencies and their licences + +Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. +The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the +OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. + +## The allowed set, as checked by `scripts/deps.mjs` + +| Licence (SPDX) | Why it is allowed | +| :-- | :-- | +| MIT, MIT-0 | named in the brief | +| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | +| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | +| Zlib | named in the brief | +| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | +| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | +| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | +| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | + +An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the +script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). + +## Direct dependencies + +| Crate | Version | Licence | Used by | For | +| :-- | :-- | :-- | :-- | :-- | +| thiserror | 2 | MIT OR Apache-2.0 | all | error types | +| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | +| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | +| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | +| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | +| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | +| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | +| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | +| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | +| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | +| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | +| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | + +## Binaries (fetched, never in git) + +| Binary | Licence | Fetched by | +| :-- | :-- | :-- | +| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | + +### pdfium + +Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 +`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches +pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside +the dll (the app's installer copies them). Read from those files on 2026-11-16: + +| Component inside pdfium.dll | Licence | In the allowed set? | +| :-- | :-- | :-- | +| the binary build (bblanchon/pdfium-binaries) | MIT | yes | +| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | +| abseil, highway | Apache-2.0 | yes | +| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | +| fast_float, simdutf | MIT | yes | +| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | +| OpenJPEG | BSD-2-Clause | yes | +| zlib | Zlib | yes | +| HarfBuzz | "Old MIT" | yes (MIT family) | +| ICU | Unicode-3.0 | **interpretation** (see above) | +| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | +| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | +| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | + +None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked +"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF +support depends on pdfium, which the brief chose). + +## OS codecs (not bundled) + +| Codec | Provided by | Used for | +| :-- | :-- | :-- | +| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | + +## Every crate in Cargo.lock + +Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. + + + diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c2c651f --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/scripts/deps.mjs b/scripts/deps.mjs new file mode 100644 index 0000000..c9b767c --- /dev/null +++ b/scripts/deps.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +// Regenerates the "Every crate in Cargo.lock" table in docs/DEPENDENCIES.md from `cargo metadata` +// and exits 1 when a crate's licence is outside the allowed set (or missing). +// Usage: node scripts/deps.mjs [--check] (--check: do not rewrite the file, only verify it is current) +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const docPath = join(root, 'docs', 'DEPENDENCIES.md'); + +export const ALLOWED = new Set([ + 'MIT', 'MIT-0', 'Apache-2.0', 'Apache-2.0 WITH LLVM-exception', 'BSD-2-Clause', 'BSD-3-Clause', '0BSD', + 'Zlib', 'MPL-2.0', 'ISC', 'Unicode-3.0', 'Unicode-DFS-2016', 'BSL-1.0', 'CC0-1.0', +]); + +// Minimal SPDX evaluator: OR / AND / WITH and parentheses. Old crates write "MIT/Apache-2.0" for OR. +export function allowed(expr) { + if (!expr) return false; + const tokens = expr.replace(/\//g, ' OR ').replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').split(/\s+/).filter(Boolean); + let i = 0; + function primary() { + if (tokens[i] === '(') { i++; const v = orExpr(); i++; return v; } + let id = tokens[i++]; + if (tokens[i] === 'WITH') { id += ` WITH ${tokens[i + 1]}`; i += 2; } + return ALLOWED.has(id); + } + function andExpr() { let v = primary(); while (tokens[i] === 'AND') { i++; v = primary() && v; } return v; } + function orExpr() { let v = andExpr(); while (tokens[i] === 'OR') { i++; v = andExpr() || v; } return v; } + return orExpr(); +} + +function main() { + const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked', '--filter-platform', 'x86_64-pc-windows-msvc'], { + cwd: root, maxBuffer: 1 << 28, encoding: 'utf8', + })); + // Only crates reachable on Windows x64 (the one target of V1), not every lockfile entry of every platform: + // with --filter-platform, resolve.nodes lists what the workspace really depends on there. + const used = new Set(meta.resolve.nodes.map((n) => n.id)); + const workspace = new Set(meta.workspace_members); + const rows = meta.packages + .filter((p) => used.has(p.id) && !workspace.has(p.id)) + .map((p) => ({ name: p.name, version: p.version, licence: p.license ?? (p.license_file ? `file: ${p.license_file}` : '') })) + .sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version)); + const bad = rows.filter((r) => !allowed(r.licence)); + const table = [ + `${rows.length} crates; ${bad.length} outside the allowed set.`, + '', + '| Crate | Version | Licence | Allowed |', + '| :-- | :-- | :-- | :-- |', + ...rows.map((r) => `| ${r.name} | ${r.version} | ${r.licence || '(none)'} | ${allowed(r.licence) ? 'yes' : '**NO**'} |`), + ].join('\n'); + const doc = readFileSync(docPath, 'utf8'); + const next = doc.replace(/[\s\S]*/, `\n${table}\n`); + if (process.argv.includes('--check')) { + if (next !== doc) { console.error('docs/DEPENDENCIES.md is out of date: run node scripts/deps.mjs'); process.exit(1); } + } else if (next !== doc) { + writeFileSync(docPath, next); + } + for (const r of bad) console.error(`not allowed: ${r.name} ${r.version} (${r.licence || 'no licence field'})`); + console.log(`${rows.length} crates, ${bad.length} not allowed`); + process.exit(bad.length ? 1 : 0); +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main(); diff --git a/scripts/fetch-pdfium.ps1 b/scripts/fetch-pdfium.ps1 new file mode 100644 index 0000000..91a1f5d --- /dev/null +++ b/scripts/fetch-pdfium.ps1 @@ -0,0 +1,42 @@ +# Fetches the pinned pdfium build (bblanchon/pdfium-binaries, Windows x64) into third_party/pdfium/. +# The archive's sha256 is pinned: a different file is refused and nothing is extracted. +# pdfium-render's `pdfium_latest` feature (0.9.5) targets chromium/8125: keep the two in step. +# Usage: powershell -File scripts/fetch-pdfium.ps1 [-Dest ] +param([string]$Dest = (Join-Path $PSScriptRoot '..\third_party\pdfium')) +$ErrorActionPreference = 'Stop' + +$Release = 'chromium/8125' +$Url = 'https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F8125/pdfium-win-x64.tgz' +$Sha256 = '9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b' + +$Dest = [IO.Path]::GetFullPath($Dest) +$marker = Join-Path $Dest 'RELEASE' +if ((Test-Path (Join-Path $Dest 'bin\pdfium.dll')) -and (Test-Path $marker) -and ((Get-Content $marker -Raw).Trim() -eq "$Release $Sha256")) { + Write-Host "pdfium $Release already in $Dest" + exit 0 +} + +$tmp = Join-Path ([IO.Path]::GetTempPath()) ("pdfium-" + [Guid]::NewGuid()) +New-Item -ItemType Directory -Force $tmp | Out-Null +try { + $archive = Join-Path $tmp 'pdfium-win-x64.tgz' + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $archive + $got = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLowerInvariant() + if ($got -ne $Sha256) { throw "pdfium archive sha256 mismatch: expected $Sha256, got $got. Nothing was extracted." } + $x = Join-Path $tmp 'x' + New-Item -ItemType Directory -Force $x | Out-Null + # Windows' own bsdtar: Git's GNU tar on PATH reads "F:\..." as a remote host. + & (Join-Path $env:SystemRoot 'System32\tar.exe') -xzf $archive -C $x + if ($LASTEXITCODE -ne 0) { throw "tar failed ($LASTEXITCODE)" } + if (Test-Path $Dest) { Remove-Item -Recurse -Force $Dest } + New-Item -ItemType Directory -Force (Join-Path $Dest 'bin') | Out-Null + Copy-Item (Join-Path $x 'bin\pdfium.dll') (Join-Path $Dest 'bin\pdfium.dll') + Copy-Item (Join-Path $x 'LICENSE') (Join-Path $Dest 'LICENSE') + Copy-Item -Recurse (Join-Path $x 'licenses') (Join-Path $Dest 'licenses') + Copy-Item (Join-Path $x 'VERSION') (Join-Path $Dest 'VERSION') + Set-Content -Encoding ascii $marker "$Release $Sha256" + Write-Host "pdfium $Release -> $Dest" +} finally { + Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue +} From eae7ef5578c16bd6ffd7ebe738a70d3c877f3f00 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:15:30 +0100 Subject: [PATCH 02/13] [qr] QR: payloads, PNG and SVG, centre logo at level H, round-trip tests --- crates/qr/Cargo.toml | 17 +++ crates/qr/src/base64.rs | 35 ++++++ crates/qr/src/colour.rs | 42 +++++++ crates/qr/src/encode.rs | 144 +++++++++++++++++++++ crates/qr/src/error.rs | 68 ++++++++++ crates/qr/src/lib.rs | 89 +++++++++++++ crates/qr/src/payload.rs | 227 ++++++++++++++++++++++++++++++++++ crates/qr/src/render.rs | 94 ++++++++++++++ crates/qr/src/svg.rs | 105 ++++++++++++++++ crates/qr/tests/common/mod.rs | 58 +++++++++ crates/qr/tests/errors.rs | 84 +++++++++++++ crates/qr/tests/payload.rs | 114 +++++++++++++++++ crates/qr/tests/round_trip.rs | 145 ++++++++++++++++++++++ crates/qr/tests/svg.rs | 113 +++++++++++++++++ 14 files changed, 1335 insertions(+) create mode 100644 crates/qr/Cargo.toml create mode 100644 crates/qr/src/base64.rs create mode 100644 crates/qr/src/colour.rs create mode 100644 crates/qr/src/encode.rs create mode 100644 crates/qr/src/error.rs create mode 100644 crates/qr/src/lib.rs create mode 100644 crates/qr/src/payload.rs create mode 100644 crates/qr/src/render.rs create mode 100644 crates/qr/src/svg.rs create mode 100644 crates/qr/tests/common/mod.rs create mode 100644 crates/qr/tests/errors.rs create mode 100644 crates/qr/tests/payload.rs create mode 100644 crates/qr/tests/round_trip.rs create mode 100644 crates/qr/tests/svg.rs diff --git a/crates/qr/Cargo.toml b/crates/qr/Cargo.toml new file mode 100644 index 0000000..b62721c --- /dev/null +++ b/crates/qr/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "pictor-qr" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true +qrcode.workspace = true + +[dev-dependencies] +rqrr.workspace = true +serde_json.workspace = true diff --git a/crates/qr/src/base64.rs b/crates/qr/src/base64.rs new file mode 100644 index 0000000..084b646 --- /dev/null +++ b/crates/qr/src/base64.rs @@ -0,0 +1,35 @@ +//! Standard base64 (RFC 4648, with padding), for the SVG logo's data URI. + +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +pub(crate) fn encode(data: &[u8]) -> String { + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [chunk[0], chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for i in 0..4 { + if i <= chunk.len() { + out.push(ALPHABET[((n >> (18 - 6 * i)) & 0x3f) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::encode; + + #[test] + fn rfc4648_vectors() { + let cases = + [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE=")]; + for (input, expected) in cases { + assert_eq!(encode(input.as_bytes()), expected); + } + assert_eq!(encode(b"foobar"), "Zm9vYmFy"); + assert_eq!(encode(&[0xff, 0xfe, 0xfd]), "//79"); + } +} diff --git a/crates/qr/src/colour.rs b/crates/qr/src/colour.rs new file mode 100644 index 0000000..b8f37be --- /dev/null +++ b/crates/qr/src/colour.rs @@ -0,0 +1,42 @@ +//! WCAG contrast between the two colours, and the check the renderers run before drawing anything. + +use crate::QrError; + +/// The least WCAG contrast ratio the renderers accept. +const MIN_CONTRAST: f64 = 3.0; + +/// The colour composited over white (a half-transparent colour reads lighter), as linear-light sRGB luminance. +fn luminance([r, g, b, a]: [u8; 4]) -> f64 { + let alpha = f64::from(a) / 255.0; + let channel = |c: u8| { + let c = (f64::from(c) * alpha + 255.0 * (1.0 - alpha)) / 255.0; + if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) +} + +/// The WCAG 2 contrast ratio between two RGBA colours (1.0 to 21.0), each composited over white first. +pub fn contrast_ratio(a: [u8; 4], b: [u8; 4]) -> f64 { + let (la, lb) = (luminance(a), luminance(b)); + (la.max(lb) + 0.05) / (la.min(lb) + 0.05) +} + +/// Whether scanners will read `dark` modules on a `light` background: the dark colour is not fully transparent, +/// is darker than the background, and the WCAG contrast ratio is at least 3:1. +pub fn contrast_ok(dark: [u8; 4], light: [u8; 4]) -> bool { + check(dark, light).is_ok() +} + +pub(crate) fn check(dark: [u8; 4], light: [u8; 4]) -> Result<(), QrError> { + if dark[3] == 0 { + return Err(QrError::TransparentDark); + } + if luminance(light) < luminance(dark) { + return Err(QrError::Inverted); + } + let ratio = contrast_ratio(dark, light); + if ratio < MIN_CONTRAST { + return Err(QrError::LowContrast { ratio }); + } + Ok(()) +} diff --git a/crates/qr/src/encode.rs b/crates/qr/src/encode.rs new file mode 100644 index 0000000..7803608 --- /dev/null +++ b/crates/qr/src/encode.rs @@ -0,0 +1,144 @@ +//! Text to module matrix, and the geometry shared by the raster and SVG renderers. + +use qrcode::bits::Bits; +use qrcode::types::QrError as RawError; +use qrcode::{Color, EcLevel, QrCode, Version}; + +use crate::{LOGO_FRACTION, Level, MAX_QUIET_ZONE, MAX_SIZE_PX, QrError, Style}; + +/// The module matrix, row-major, `true` = dark. +pub(crate) struct Matrix { + pub width: u32, + pub dark: Vec, +} + +impl Matrix { + pub fn is_dark(&self, x: u32, y: u32) -> bool { + self.dark[(y * self.width + x) as usize] + } +} + +/// Encodes `text` at `level`. ASCII uses the encoder's optimal segmentation (numeric, alphanumeric, byte); anything +/// else is one UTF-8 byte segment, because the optimiser would put some UTF-8 byte pairs in Kanji mode, which phone +/// scanners turn into Japanese characters. +pub(crate) fn encode(text: &str, level: Level, logo: bool) -> Result { + if text.trim().is_empty() { + return Err(QrError::Empty); + } + let ec = level.ec(); + let code = if text.is_ascii() { + QrCode::with_error_correction_level(text.as_bytes(), ec) + } else { + byte_mode(text.as_bytes(), ec) + } + .map_err(|e| match e { + RawError::DataTooLong => QrError::TooLong { level, logo }, + other => QrError::Encode(other.to_string()), + })?; + let width = code.width() as u32; + let dark = code.to_colors().into_iter().map(|c| c == Color::Dark).collect(); + Ok(Matrix { width, dark }) +} + +fn byte_mode(data: &[u8], ec: EcLevel) -> qrcode::QrResult { + for v in 1..=40 { + let mut bits = Bits::new(Version::Normal(v)); + if bits.push_byte_data(data).is_ok() && bits.push_terminator(ec).is_ok() { + return QrCode::with_bits(bits, ec); + } + } + Err(RawError::DataTooLong) +} + +/// Pixel geometry of one rendering. +pub(crate) struct Geometry { + /// Modules across the code, quiet zone excluded. + pub modules: u32, + pub quiet: u32, + /// Pixels per module. + pub scale: u32, +} + +impl Geometry { + pub fn new(modules: u32, style: &Style) -> Result { + if style.quiet_zone > MAX_QUIET_ZONE { + return Err(QrError::QuietZoneTooLarge { max: MAX_QUIET_ZONE }); + } + if style.size_px > MAX_SIZE_PX { + return Err(QrError::SizeTooLarge { max_px: MAX_SIZE_PX }); + } + let total = modules + 2 * style.quiet_zone; + let scale = style.size_px / total; + if scale == 0 { + return Err(QrError::SizeTooSmall { min_px: total }); + } + Ok(Geometry { modules, quiet: style.quiet_zone, scale }) + } + + /// Modules across the whole image, quiet zone included. + pub fn total_modules(&self) -> u32 { + self.modules + 2 * self.quiet + } + + pub fn size_px(&self) -> u32 { + self.total_modules() * self.scale + } +} + +/// Where the logo goes. The plate is whole modules (all cleared to the light colour), an odd number across so it +/// sits exactly in the middle, with at least half a module of padding around the logo. +pub(crate) struct Plate { + /// Plate, in modules, relative to the code's top-left corner (quiet zone excluded). + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, + /// The logo's box, in pixels, relative to the code's top-left corner (quiet zone excluded). + pub logo_x: u32, + pub logo_y: u32, + pub logo_w: u32, + pub logo_h: u32, +} + +impl Plate { + pub fn new(g: &Geometry, logo_w: u32, logo_h: u32) -> Plate { + let code_px = f64::from(g.modules * g.scale); + let max_px = code_px * LOGO_FRACTION; + let k = max_px / f64::from(logo_w.max(logo_h)); + let lw = ((f64::from(logo_w) * k).floor() as u32).max(1); + let lh = ((f64::from(logo_h) * k).floor() as u32).max(1); + let s = f64::from(g.scale); + let odd = |n: u32| if n.is_multiple_of(2) { n + 1 } else { n }; + let w = odd((f64::from(lw) / s + 1.0).ceil() as u32).min(g.modules); + let h = odd((f64::from(lh) / s + 1.0).ceil() as u32).min(g.modules); + let (x, y) = ((g.modules - w) / 2, (g.modules - h) / 2); + Plate { + x, + y, + w, + h, + logo_x: x * g.scale + (w * g.scale - lw) / 2, + logo_y: y * g.scale + (h * g.scale - lh) / 2, + logo_w: lw, + logo_h: lh, + } + } + + pub fn contains(&self, mx: u32, my: u32) -> bool { + mx >= self.x && mx < self.x + self.w && my >= self.y && my < self.y + self.h + } +} + +/// Encodes for a rendering: checks the colours, forces level H with a logo, and lays out the pixels. +pub(crate) fn prepare( + text: &str, + level: Level, + style: &Style, + logo: bool, +) -> Result<(Matrix, Geometry, Level), QrError> { + crate::colour::check(style.dark, style.light)?; + let level = if logo { Level::H } else { level }; + let matrix = encode(text, level, logo)?; + let geometry = Geometry::new(matrix.width, style)?; + Ok((matrix, geometry, level)) +} diff --git a/crates/qr/src/error.rs b/crates/qr/src/error.rs new file mode 100644 index 0000000..5c97fe6 --- /dev/null +++ b/crates/qr/src/error.rs @@ -0,0 +1,68 @@ +use crate::Level; + +/// Everything that can go wrong. `Display` is a plain sentence for the user. +#[derive(Debug, Clone, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum QrError { + #[error("There is nothing to put in the QR code yet. Type some text first.")] + Empty, + + /// A required field of a payload is empty; `field` is its plain name ("Wi-Fi network name", ...). + #[error("The {field} is empty. Fill it in first.")] + EmptyField { field: &'static str }, + + /// The content does not fit in a QR code at `level`; `logo` says the level was forced to H by a logo. + #[error("{}", too_long(*level, *logo))] + TooLong { level: Level, logo: bool }, + + #[error( + "The two colours are too similar for a scanner to tell apart (contrast {ratio:.1}:1, it needs at least 3:1). \ + Make the code colour darker or the background lighter." + )] + LowContrast { ratio: f64 }, + + #[error( + "The code colour is lighter than the background. Many scanners only read dark codes on a light background, \ + so swap the two colours." + )] + Inverted, + + #[error("The code colour is fully transparent, so the code would be invisible. Choose a solid colour.")] + TransparentDark, + + #[error( + "The image is too small for this much content: it needs at least {min_px} pixels across. \ + Make it larger or shorten the content." + )] + SizeTooSmall { min_px: u32 }, + + #[error("The image can be at most {max_px} pixels across. Choose a smaller size.")] + SizeTooLarge { max_px: u32 }, + + #[error("The quiet zone can be at most {max} modules wide. Choose a narrower one.")] + QuietZoneTooLarge { max: u32 }, + + /// The logo could not be used; the text says why. + #[error("The logo cannot be used: {0}")] + Logo(String), + + /// An internal encoder failed (should not happen); the text is the encoder's. + #[error("The QR code could not be made: {0}")] + Encode(String), +} + +fn too_long(level: Level, logo: bool) -> String { + if logo { + "This is too much content for a QR code with a logo. A logo needs the highest error-correction level (H), \ + which holds the least. Remove the logo or shorten the content." + .to_string() + } else if level == Level::L { + "This is too much content for one QR code, even at the lowest error-correction level (L). Shorten it." + .to_string() + } else { + format!( + "This is too much content for one QR code at error-correction level {level}. \ + Shorten it or choose a lower level." + ) + } +} diff --git a/crates/qr/src/lib.rs b/crates/qr/src/lib.rs new file mode 100644 index 0000000..08170a2 --- /dev/null +++ b/crates/qr/src/lib.rs @@ -0,0 +1,89 @@ +//! QR codes for Pictor's Toolbox: payload builders (text, URL, Wi-Fi, contact), raster (RGBA, PNG) and SVG output, +//! an optional centre logo (which forces error-correction level H), and a colour check that refuses combinations +//! scanners will not read. +//! +//! Every error is a [`QrError`] whose `Display` is a plain-English sentence meant to be shown to the user. + +mod base64; +mod colour; +mod encode; +mod error; +mod payload; +mod render; +mod svg; + +use serde::{Deserialize, Serialize}; + +pub use colour::{contrast_ok, contrast_ratio}; +pub use error::QrError; +pub use payload::{Payload, WifiSecurity, payload_string}; +pub use render::{Rendered, encode_png, render_png, render_rgba}; +pub use svg::render_svg; + +/// The largest output, in pixels across, that the renderers will produce. +pub const MAX_SIZE_PX: u32 = 4096; +/// The widest quiet zone, in modules, that the renderers accept. +pub const MAX_QUIET_ZONE: u32 = 40; +/// The largest logo PNG, in bytes, that [`render_svg`] accepts. +pub const MAX_LOGO_BYTES: usize = 8 * 1024 * 1024; +/// The largest logo, in pixels across either side, that the renderers accept. +pub const MAX_LOGO_PX: u32 = 4096; +/// The logo's largest side, as a fraction of the code's width (quiet zone excluded). +pub const LOGO_FRACTION: f64 = 0.22; + +/// Error-correction level: how much of the code can be damaged or covered and still read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +pub enum Level { + /// About 7% recoverable; the most content. + L, + /// About 15% recoverable; the usual choice. + #[default] + M, + /// About 25% recoverable. + Q, + /// About 30% recoverable; the least content. Forced when a logo is drawn. + H, +} + +impl Level { + pub(crate) fn ec(self) -> qrcode::EcLevel { + match self { + Level::L => qrcode::EcLevel::L, + Level::M => qrcode::EcLevel::M, + Level::Q => qrcode::EcLevel::Q, + Level::H => qrcode::EcLevel::H, + } + } +} + +impl std::fmt::Display for Level { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Level::L => "L", + Level::M => "M", + Level::Q => "Q", + Level::H => "H", + }) + } +} + +/// How the code looks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Style { + /// Target width and height in pixels. Modules are scaled by a whole number of pixels, so the output may be a + /// little smaller; [`Rendered::size_px`] reports the real size. + pub size_px: u32, + /// Light border around the code, in modules. Scanners want 4; less works on most phones. + pub quiet_zone: u32, + /// The modules' colour, RGBA. + pub dark: [u8; 4], + /// The background (and quiet zone, and logo plate) colour, RGBA. May be transparent. + pub light: [u8; 4], +} + +impl Default for Style { + fn default() -> Self { + Style { size_px: 512, quiet_zone: 4, dark: [0, 0, 0, 255], light: [255, 255, 255, 255] } + } +} diff --git a/crates/qr/src/payload.rs b/crates/qr/src/payload.rs new file mode 100644 index 0000000..0dac4fb --- /dev/null +++ b/crates/qr/src/payload.rs @@ -0,0 +1,227 @@ +//! What goes inside the code: plain text, a web address, a Wi-Fi login, or a contact card. + +use serde::{Deserialize, Serialize}; + +use crate::{Level, QrError}; + +/// Wi-Fi security, as the `T:` field of the Wi-Fi payload names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WifiSecurity { + /// WPA, WPA2 or WPA3 personal (phones read `T:WPA` for all of them). + #[default] + Wpa, + /// The old WEP. + Wep, + /// No password. + Open, +} + +/// The content of a code, before it is turned into the string that is encoded. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Payload { + /// Any text, kept exactly as given. + Text(String), + /// A web address; `https://` is added when it has no scheme. + Url(String), + /// A Wi-Fi login. The password is ignored for [`WifiSecurity::Open`]. + Wifi { + ssid: String, + #[serde(default)] + password: String, + #[serde(default)] + security: WifiSecurity, + #[serde(default)] + hidden: bool, + }, + /// A contact card (vCard 3.0). Empty optional fields are left out. + Contact { + name: String, + #[serde(default)] + phone: Option, + #[serde(default)] + email: Option, + #[serde(default)] + organisation: Option, + #[serde(default)] + url: Option, + #[serde(default)] + address: Option, + #[serde(default)] + note: Option, + }, +} + +/// The string to encode for `payload`. Fails on empty required fields and on content that no QR code can hold +/// (even at level L); whether it fits at a higher level is checked when it is rendered. +pub fn payload_string(payload: &Payload) -> Result { + let s = match payload { + Payload::Text(t) => { + if t.trim().is_empty() { + return Err(QrError::Empty); + } + t.clone() + } + Payload::Url(u) => url(u)?, + Payload::Wifi { ssid, password, security, hidden } => wifi(ssid, password, *security, *hidden)?, + Payload::Contact { name, phone, email, organisation, url, address, note } => { + let field = |f: &Option| f.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned); + vcard(&Contact { + name: name.trim(), + phone: field(phone), + email: field(email), + organisation: field(organisation), + url: field(url), + address: field(address), + note: field(note), + })? + } + }; + crate::encode::encode(&s, Level::L, false)?; + Ok(s) +} + +fn url(u: &str) -> Result { + let u = u.trim(); + if u.is_empty() { + return Err(QrError::EmptyField { field: "web address" }); + } + Ok(if has_scheme(u) { u.to_string() } else { format!("https://{u}") }) +} + +/// RFC 3986 `scheme ":"`, where the colon is not followed by a digit (so `localhost:8080` is a host and a port). +fn has_scheme(u: &str) -> bool { + let Some((scheme, rest)) = u.split_once(':') else { return false }; + let mut chars = scheme.chars(); + let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic()); + first_ok + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + && !rest.starts_with(|c: char| c.is_ascii_digit()) +} + +/// The de-facto Wi-Fi format (`WIFI:T:WPA;S:;P:;H:true;;`), with `\ ; , : "` backslash-escaped. +fn wifi(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> Result { + fn esc(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + if matches!(c, '\\' | ';' | ',' | ':' | '"') { + out.push('\\'); + } + out.push(c); + } + out + } + if ssid.is_empty() { + return Err(QrError::EmptyField { field: "Wi-Fi network name" }); + } + let t = match security { + WifiSecurity::Wpa => "WPA", + WifiSecurity::Wep => "WEP", + WifiSecurity::Open => "nopass", + }; + let mut s = format!("WIFI:T:{t};S:{};", esc(ssid)); + if security != WifiSecurity::Open { + if password.is_empty() { + return Err(QrError::EmptyField { field: "Wi-Fi password (choose \"Open\" for a network without one)" }); + } + s.push_str(&format!("P:{};", esc(password))); + } + if hidden { + s.push_str("H:true;"); + } + s.push(';'); + Ok(s) +} + +struct Contact<'a> { + name: &'a str, + phone: Option, + email: Option, + organisation: Option, + url: Option, + address: Option, + note: Option, +} + +/// vCard text value escaping (RFC 2426 / 6350): `\` `,` `;` get a backslash, every line break becomes `\n`. +fn esc_text(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '\\' | ',' | ';' => { + out.push('\\'); + out.push(c); + } + '\r' => { + chars.next_if_eq(&'\n'); + out.push_str("\\n"); + } + '\n' => out.push_str("\\n"), + _ => out.push(c), + } + } + out +} + +/// A value that is not text (telephone, e-mail, URI): kept as given, but on one line. +fn one_line(s: &str) -> String { + s.split(['\r', '\n']).filter(|p| !p.is_empty()).collect::>().join(" ") +} + +/// vCard 3.0 with CRLF line endings. `N` is split at the last space into given and family name. Lines are not +/// folded at 75 octets: every scanner reads long lines, and some do not unfold. +fn vcard(c: &Contact) -> Result { + if c.name.is_empty() { + return Err(QrError::EmptyField { field: "contact name" }); + } + let (given, family) = match c.name.rsplit_once(char::is_whitespace) { + Some((g, f)) => (g.trim_end(), f), + None => ("", c.name), + }; + let mut lines = vec![ + "BEGIN:VCARD".to_string(), + "VERSION:3.0".to_string(), + format!("N:{};{};;;", esc_text(family), esc_text(given)), + format!("FN:{}", esc_text(c.name)), + ]; + if let Some(v) = &c.organisation { + lines.push(format!("ORG:{}", esc_text(v))); + } + if let Some(v) = &c.phone { + lines.push(format!("TEL:{}", one_line(v))); + } + if let Some(v) = &c.email { + lines.push(format!("EMAIL:{}", one_line(v))); + } + if let Some(v) = &c.url { + lines.push(format!("URL:{}", one_line(v))); + } + if let Some(v) = &c.address { + lines.push(format!("ADR:;;{};;;;", esc_text(v))); + } + if let Some(v) = &c.note { + lines.push(format!("NOTE:{}", esc_text(v))); + } + lines.push("END:VCARD".to_string()); + let mut s = lines.join("\r\n"); + s.push_str("\r\n"); + Ok(s) +} + +#[cfg(test)] +mod tests { + use super::has_scheme; + + #[test] + fn scheme_detection() { + assert!(has_scheme("https://a")); + assert!(has_scheme("mailto:x@y")); + assert!(has_scheme("tel:+420")); + assert!(!has_scheme("example.com")); + assert!(!has_scheme("example.com:8080/x")); + assert!(!has_scheme("1http://x")); + assert!(!has_scheme("ex ample:x")); + } +} diff --git a/crates/qr/src/render.rs b/crates/qr/src/render.rs new file mode 100644 index 0000000..4b38c31 --- /dev/null +++ b/crates/qr/src/render.rs @@ -0,0 +1,94 @@ +//! Raster output: an RGBA image, and PNG bytes. + +use image::{ImageEncoder, Rgba, RgbaImage, imageops}; + +use crate::encode::{Plate, prepare}; +use crate::{Level, MAX_LOGO_PX, QrError, Style}; + +/// A rendered code. +#[derive(Debug, Clone)] +pub struct Rendered { + /// The code, `size_px` square, quiet zone included. + pub image: RgbaImage, + /// The error-correction level actually used: H whenever a logo was drawn, whatever was asked. + pub level_used: Level, + /// Modules across the code, quiet zone excluded (21 for version 1, up to 177). + pub modules: u32, + /// Pixels per module. + pub module_px: u32, + /// The real width and height in pixels: `(modules + 2 * quiet_zone) * module_px`, at most the asked size. + pub size_px: u32, +} + +/// Renders `text` as an RGBA image. With a `logo` the level is forced to H and the logo (aspect kept, its largest +/// side about 22% of the code's width) is drawn centred on a plate of cleared, light-coloured modules. +pub fn render_rgba(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result { + if let Some(l) = logo { + check_logo_size(l.width(), l.height())?; + } + let (matrix, g, level_used) = prepare(text, level, style, logo.is_some())?; + let plate = logo.map(|l| Plate::new(&g, l.width(), l.height())); + let size = g.size_px(); + let mut img = RgbaImage::from_pixel(size, size, Rgba(style.light)); + let dark = Rgba(style.dark); + for my in 0..g.modules { + for mx in 0..g.modules { + if !matrix.is_dark(mx, my) || plate.as_ref().is_some_and(|p| p.contains(mx, my)) { + continue; + } + let (x0, y0) = ((g.quiet + mx) * g.scale, (g.quiet + my) * g.scale); + for y in y0..y0 + g.scale { + for x in x0..x0 + g.scale { + img.put_pixel(x, y, dark); + } + } + } + } + if let (Some(logo), Some(p)) = (logo, &plate) { + let scaled = imageops::resize(logo, p.logo_w, p.logo_h, imageops::FilterType::Lanczos3); + let (ox, oy) = (g.quiet * g.scale + p.logo_x, g.quiet * g.scale + p.logo_y); + for (x, y, src) in scaled.enumerate_pixels() { + let dst = img.get_pixel_mut(ox + x, oy + y); + *dst = over(*src, *dst); + } + } + Ok(Rendered { image: img, level_used, modules: g.modules, module_px: g.scale, size_px: size }) +} + +/// [`render_rgba`], encoded as PNG. +pub fn render_png(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result, QrError> { + encode_png(&render_rgba(text, level, style, logo)?.image) +} + +/// Encodes an RGBA image (a [`Rendered::image`]) as PNG. +pub fn encode_png(image: &RgbaImage) -> Result, QrError> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new(&mut out) + .write_image(image.as_raw(), image.width(), image.height(), image::ExtendedColorType::Rgba8) + .map_err(|e| QrError::Encode(e.to_string()))?; + Ok(out) +} + +pub(crate) fn check_logo_size(w: u32, h: u32) -> Result<(), QrError> { + if w == 0 || h == 0 { + return Err(QrError::Logo("the image is empty.".into())); + } + if w > MAX_LOGO_PX || h > MAX_LOGO_PX { + return Err(QrError::Logo(format!( + "it is {w} x {h} pixels; at most {MAX_LOGO_PX} pixels on each side is allowed. Use a smaller image." + ))); + } + Ok(()) +} + +/// Straight-alpha "source over destination". +fn over(src: Rgba, dst: Rgba) -> Rgba { + let sa = f32::from(src[3]) / 255.0; + let da = f32::from(dst[3]) / 255.0; + let oa = sa + da * (1.0 - sa); + if oa <= 0.0 { + return Rgba([0, 0, 0, 0]); + } + let mix = |s: u8, d: u8| ((f32::from(s) * sa + f32::from(d) * da * (1.0 - sa)) / oa).round() as u8; + Rgba([mix(src[0], dst[0]), mix(src[1], dst[1]), mix(src[2], dst[2]), (oa * 255.0).round() as u8]) +} diff --git a/crates/qr/src/svg.rs b/crates/qr/src/svg.rs new file mode 100644 index 0000000..caf68b0 --- /dev/null +++ b/crates/qr/src/svg.rs @@ -0,0 +1,105 @@ +//! SVG output: one path of dark-module runs, a background rect, and the logo as a base64 PNG data URI. + +use std::fmt::Write as _; +use std::io::Cursor; + +use crate::encode::{Plate, prepare}; +use crate::render::check_logo_size; +use crate::{Level, MAX_LOGO_BYTES, MAX_LOGO_PX, QrError, Style}; + +/// Renders `text` as SVG. The view box is in modules (quiet zone included); `width` and `height` are the same pixel +/// size [`crate::render_rgba`] would produce. Dark modules are one `` of horizontal runs +/// (`M{x} {y}h{n}v1h-{n}z`). With `logo_png` (PNG bytes) the level is forced to H, the modules under the logo's +/// plate are left out, and the PNG is embedded unchanged as an `` data URI. +pub fn render_svg(text: &str, level: Level, style: &Style, logo_png: Option<&[u8]>) -> Result { + let logo_size = logo_png.map(logo_dimensions).transpose()?; + let (matrix, g, _) = prepare(text, level, style, logo_png.is_some())?; + let plate = logo_size.map(|(w, h)| Plate::new(&g, w, h)); + let total = g.total_modules(); + let size = g.size_px(); + + let mut svg = String::with_capacity(256 + (g.modules * g.modules) as usize * 4); + let _ = writeln!( + svg, + "\n" + ); + if style.light[3] > 0 { + let _ = writeln!(svg, "", fill(style.light)); + } + let _ = write!(svg, "\n"); + if let (Some(png), Some(p)) = (logo_png, &plate) { + let s = f64::from(g.scale); + let q = f64::from(g.quiet); + let _ = writeln!( + svg, + "", + num(q + f64::from(p.logo_x) / s), + num(q + f64::from(p.logo_y) / s), + num(f64::from(p.logo_w) / s), + num(f64::from(p.logo_h) / s), + crate::base64::encode(png) + ); + } + svg.push_str("\n"); + Ok(svg) +} + +/// Decodes the logo PNG (with caps on bytes, pixels and memory) to check it and read its size. +fn logo_dimensions(png: &[u8]) -> Result<(u32, u32), QrError> { + if png.len() > MAX_LOGO_BYTES { + return Err(QrError::Logo(format!( + "the file is {} MB; at most {} MB is allowed.", + png.len().div_ceil(1024 * 1024), + MAX_LOGO_BYTES / (1024 * 1024) + ))); + } + let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(MAX_LOGO_PX); + limits.max_image_height = Some(MAX_LOGO_PX); + limits.max_alloc = Some(u64::from(MAX_LOGO_PX) * u64::from(MAX_LOGO_PX) * 8); + reader.limits(limits); + let img = reader.decode().map_err(|e| match e { + image::ImageError::Limits(_) => { + QrError::Logo(format!("it is larger than {MAX_LOGO_PX} pixels on a side. Use a smaller image.")) + } + _ => QrError::Logo("it is not a readable PNG image.".into()), + })?; + check_logo_size(img.width(), img.height())?; + Ok((img.width(), img.height())) +} + +/// ` fill="#rrggbb"`, plus ` fill-opacity` when the colour is not opaque. +fn fill([r, g, b, a]: [u8; 4]) -> String { + let mut s = format!(" fill=\"#{r:02x}{g:02x}{b:02x}\""); + if a < 255 { + let _ = write!(s, " fill-opacity=\"{}\"", num(f64::from(a) / 255.0)); + } + s +} + +/// A number with at most three decimals and no trailing zeros. +fn num(v: f64) -> String { + let s = format!("{v:.3}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s.is_empty() || s == "-" { "0".into() } else { s.to_string() } +} diff --git a/crates/qr/tests/common/mod.rs b/crates/qr/tests/common/mod.rs new file mode 100644 index 0000000..5c7c9be --- /dev/null +++ b/crates/qr/tests/common/mod.rs @@ -0,0 +1,58 @@ +//! Helpers shared by the integration tests: decoding a rendered code back with rqrr. + +#![allow(dead_code)] + +use image::{DynamicImage, GrayImage, Rgba, RgbaImage}; + +/// Decodes the single QR code in `img` and returns its text and the ECC level rqrr read (0 = M, 1 = L, 2 = H, 3 = Q). +pub fn decode_gray(gray: GrayImage) -> (String, u16) { + let mut prepared = rqrr::PreparedImage::prepare(gray); + let grids = prepared.detect_grids(); + assert_eq!(grids.len(), 1, "expected exactly one QR code in the image, found {}", grids.len()); + let (meta, content) = grids[0].decode().expect("the QR code should decode"); + (content, meta.ecc_level) +} + +pub fn decode(img: &RgbaImage) -> String { + decode_with_level(img).0 +} + +pub fn decode_with_level(img: &RgbaImage) -> (String, u16) { + decode_gray(DynamicImage::ImageRgba8(img.clone()).to_luma8()) +} + +/// rqrr's `ecc_level` numbering is the format-information encoding: M = 0, L = 1, H = 2, Q = 3. +pub fn rqrr_level(level: pictor_qr::Level) -> u16 { + match level { + pictor_qr::Level::M => 0, + pictor_qr::Level::L => 1, + pictor_qr::Level::H => 2, + pictor_qr::Level::Q => 3, + } +} + +/// A logo: a filled red circle on a yellow square, with a transparent border. +pub fn logo(w: u32, h: u32) -> RgbaImage { + let mut img = RgbaImage::from_pixel(w, h, Rgba([0, 0, 0, 0])); + let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0); + let r = (w.min(h) as f64) * 0.35; + for y in 0..h { + for x in 0..w { + let border = x < w / 10 || y < h / 10 || x >= w - w / 10 || y >= h - h / 10; + let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy); + let px = if dx * dx + dy * dy <= r * r { + Rgba([200, 20, 40, 255]) + } else if border { + Rgba([0, 0, 0, 0]) + } else { + Rgba([240, 200, 30, 255]) + }; + img.put_pixel(x, y, px); + } + } + img +} + +pub fn logo_png(w: u32, h: u32) -> Vec { + pictor_qr::encode_png(&logo(w, h)).expect("logo PNG") +} diff --git a/crates/qr/tests/errors.rs b/crates/qr/tests/errors.rs new file mode 100644 index 0000000..6462de7 --- /dev/null +++ b/crates/qr/tests/errors.rs @@ -0,0 +1,84 @@ +//! Colour checks and input errors: typed, with a plain message. + +mod common; + +use common::logo; +use pictor_qr::{Level, QrError, Style, contrast_ok, contrast_ratio, render_png, render_rgba, render_svg}; + +#[test] +fn contrast_ratio_matches_wcag() { + assert!((contrast_ratio([0, 0, 0, 255], [255, 255, 255, 255]) - 21.0).abs() < 1e-9); + assert!((contrast_ratio([255, 255, 255, 255], [255, 255, 255, 255]) - 1.0).abs() < 1e-9); + // #777777 on white is about 4.48:1. + assert!((contrast_ratio([0x77, 0x77, 0x77, 255], [255, 255, 255, 255]) - 4.48).abs() < 0.01); +} + +#[test] +fn contrast_ok_cases() { + assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 255])); + assert!(contrast_ok([16, 32, 96, 255], [255, 250, 225, 255])); + assert!(!contrast_ok([200, 200, 200, 255], [255, 255, 255, 255]), "too light"); + assert!(!contrast_ok([255, 255, 255, 255], [0, 0, 0, 255]), "inverted"); + assert!(!contrast_ok([0, 0, 0, 0], [255, 255, 255, 255]), "transparent dark"); + assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 0]), "a transparent background is allowed"); +} + +#[test] +fn low_contrast_is_refused() { + let style = Style { dark: [180, 180, 180, 255], light: [255, 255, 255, 255], ..Style::default() }; + let err = render_rgba("hello", Level::M, &style, None).unwrap_err(); + assert!(matches!(err, QrError::LowContrast { .. }), "{err:?}"); + assert!(err.to_string().contains("contrast"), "{err}"); + assert!(matches!(render_svg("hello", Level::M, &style, None), Err(QrError::LowContrast { .. }))); + assert!(matches!(render_png("hello", Level::M, &style, None), Err(QrError::LowContrast { .. }))); +} + +#[test] +fn inverted_and_transparent_are_refused() { + let inverted = Style { dark: [255, 255, 255, 255], light: [0, 0, 0, 255], ..Style::default() }; + assert_eq!(render_rgba("x", Level::M, &inverted, None).unwrap_err(), QrError::Inverted); + let invisible = Style { dark: [0, 0, 0, 0], ..Style::default() }; + assert_eq!(render_rgba("x", Level::M, &invisible, None).unwrap_err(), QrError::TransparentDark); +} + +#[test] +fn empty_input_is_refused() { + assert_eq!(render_rgba("", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty); + assert_eq!(render_svg(" ", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty); + assert!(!QrError::Empty.to_string().is_empty()); +} + +#[test] +fn data_too_long_is_refused() { + let text = "ž".repeat(700); // 1400 bytes: fits at L, not at H (max 1273 bytes) + let err = render_rgba(&text, Level::H, &Style::default(), None).unwrap_err(); + assert_eq!(err, QrError::TooLong { level: Level::H, logo: false }); + assert!(err.to_string().contains("too much"), "{err}"); + let style = Style { size_px: 2000, ..Style::default() }; + assert!(render_rgba(&text, Level::L, &style, None).is_ok()); + // With a logo the level is H whatever was asked, and the message says why. + let err = render_rgba(&text, Level::L, &style, Some(&logo(32, 32))).unwrap_err(); + assert_eq!(err, QrError::TooLong { level: Level::H, logo: true }); + assert!(err.to_string().contains("logo"), "{err}"); + let err = render_rgba(&"a".repeat(5000), Level::L, &Style::default(), None).unwrap_err(); + assert_eq!(err, QrError::TooLong { level: Level::L, logo: false }); +} + +#[test] +fn size_too_small_is_refused() { + let style = Style { size_px: 20, ..Style::default() }; + let err = render_rgba("hello", Level::M, &style, None).unwrap_err(); + assert!(matches!(err, QrError::SizeTooSmall { min_px: 29 }), "{err:?}"); +} + +#[test] +fn size_too_large_is_refused() { + let style = Style { size_px: 100_000, ..Style::default() }; + assert!(matches!(render_rgba("hello", Level::M, &style, None), Err(QrError::SizeTooLarge { .. }))); +} + +#[test] +fn empty_logo_is_refused() { + let empty = image::RgbaImage::new(0, 0); + assert!(matches!(render_rgba("x", Level::M, &Style::default(), Some(&empty)), Err(QrError::Logo(_)))); +} diff --git a/crates/qr/tests/payload.rs b/crates/qr/tests/payload.rs new file mode 100644 index 0000000..92bccc4 --- /dev/null +++ b/crates/qr/tests/payload.rs @@ -0,0 +1,114 @@ +//! Payload builders: the exact strings, escaping, and the input errors. + +use pictor_qr::{Level, Payload, QrError, WifiSecurity, payload_string}; + +fn contact(name: &str) -> Payload { + Payload::Contact { + name: name.into(), + phone: None, + email: None, + organisation: None, + url: None, + address: None, + note: None, + } +} + +#[test] +fn text_is_kept_exactly() { + let s = payload_string(&Payload::Text(" Příliš žluťoučký kůň\n".into())).unwrap(); + assert_eq!(s, " Příliš žluťoučký kůň\n"); +} + +#[test] +fn url_without_scheme_gets_https() { + assert_eq!(payload_string(&Payload::Url("example.com/a?b=1".into())).unwrap(), "https://example.com/a?b=1"); + assert_eq!(payload_string(&Payload::Url(" localhost:8080/x ".into())).unwrap(), "https://localhost:8080/x"); +} + +#[test] +fn url_with_scheme_is_kept() { + assert_eq!(payload_string(&Payload::Url("http://example.com".into())).unwrap(), "http://example.com"); + assert_eq!(payload_string(&Payload::Url("mailto:a@b.cz".into())).unwrap(), "mailto:a@b.cz"); + assert_eq!(payload_string(&Payload::Url("HTTPS://X.CZ".into())).unwrap(), "HTTPS://X.CZ"); +} + +#[test] +fn wifi_escapes_special_characters() { + let p = Payload::Wifi { + ssid: r#"Café;"Net",1:2\x"#.into(), + password: "pa;ss:wo,rd\"\\".into(), + security: WifiSecurity::Wpa, + hidden: true, + }; + assert_eq!(payload_string(&p).unwrap(), r#"WIFI:T:WPA;S:Café\;\"Net\"\,1\:2\\x;P:pa\;ss\:wo\,rd\"\\;H:true;;"#); +} + +#[test] +fn wifi_open_and_wep() { + let open = + Payload::Wifi { ssid: "Guest".into(), password: "ignored".into(), security: WifiSecurity::Open, hidden: false }; + assert_eq!(payload_string(&open).unwrap(), "WIFI:T:nopass;S:Guest;;"); + let wep = + Payload::Wifi { ssid: "Old".into(), password: "12345".into(), security: WifiSecurity::Wep, hidden: false }; + assert_eq!(payload_string(&wep).unwrap(), "WIFI:T:WEP;S:Old;P:12345;;"); +} + +#[test] +fn wifi_needs_ssid_and_password() { + let no_ssid = Payload::Wifi { ssid: "".into(), password: "x".into(), security: WifiSecurity::Wpa, hidden: false }; + assert!(matches!(payload_string(&no_ssid), Err(QrError::EmptyField { .. }))); + let no_pass = + Payload::Wifi { ssid: "Home".into(), password: "".into(), security: WifiSecurity::Wpa, hidden: false }; + let err = payload_string(&no_pass).unwrap_err(); + assert!(matches!(err, QrError::EmptyField { .. })); + assert!(err.to_string().contains("password"), "{err}"); +} + +#[test] +fn vcard_full_contact() { + let p = Payload::Contact { + name: " Jan Novák ".into(), + phone: Some("+420 777 123 456".into()), + email: Some("jan@example.cz".into()), + organisation: Some("Firma, s.r.o.; IT".into()), + url: Some("https://example.cz/a,b".into()), + address: Some("Dlouhá 1\nPraha".into()), + note: Some("Back\\slash; and, comma\r\nnew line".into()), + }; + let expected = "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Novák;Jan;;;\r\nFN:Jan Novák\r\nORG:Firma\\, s.r.o.\\; IT\r\n\ + TEL:+420 777 123 456\r\nEMAIL:jan@example.cz\r\nURL:https://example.cz/a,b\r\n\ + ADR:;;Dlouhá 1\\nPraha;;;;\r\nNOTE:Back\\\\slash\\; and\\, comma\\nnew line\r\nEND:VCARD\r\n"; + assert_eq!(payload_string(&p).unwrap(), expected); +} + +#[test] +fn vcard_name_only_skips_empty_fields() { + let mut p = contact("Acme"); + if let Payload::Contact { phone, .. } = &mut p { + *phone = Some(" ".into()); + } + assert_eq!(payload_string(&p).unwrap(), "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Acme;;;;\r\nFN:Acme\r\nEND:VCARD\r\n"); +} + +#[test] +fn empty_inputs_are_rejected() { + assert_eq!(payload_string(&Payload::Text("".into())), Err(QrError::Empty)); + assert_eq!(payload_string(&Payload::Text(" \n ".into())), Err(QrError::Empty)); + assert!(matches!(payload_string(&Payload::Url(" ".into())), Err(QrError::EmptyField { .. }))); + assert!(matches!(payload_string(&contact(" ")), Err(QrError::EmptyField { .. }))); +} + +#[test] +fn payload_too_long_for_any_qr_code() { + let err = payload_string(&Payload::Text("a".repeat(8000))).unwrap_err(); + assert_eq!(err, QrError::TooLong { level: Level::L, logo: false }); + assert!(!err.to_string().is_empty()); +} + +#[test] +fn payload_serde_round_trip() { + let p = Payload::Wifi { ssid: "A".into(), password: "B".into(), security: WifiSecurity::Wep, hidden: true }; + let json = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), p); +} diff --git a/crates/qr/tests/round_trip.rs b/crates/qr/tests/round_trip.rs new file mode 100644 index 0000000..19bdd60 --- /dev/null +++ b/crates/qr/tests/round_trip.rs @@ -0,0 +1,145 @@ +//! Every generated code must decode back to the exact payload string (rqrr), at every level, in colour and with a +//! logo. + +mod common; + +use common::{decode, decode_with_level, logo, rqrr_level}; +use pictor_qr::{Level, Payload, Style, WifiSecurity, payload_string, render_png, render_rgba}; + +const LEVELS: [Level; 4] = [Level::L, Level::M, Level::Q, Level::H]; + +fn payloads() -> Vec<(&'static str, String)> { + vec![ + ("czech text", payload_string(&Payload::Text("Příliš žluťoučký kůň úpěl ďábelské ódy".into())).unwrap()), + ("url", payload_string(&Payload::Url("www.example.cz/cesta?q=žluť&x=1".into())).unwrap()), + ( + "wifi", + payload_string(&Payload::Wifi { + ssid: r#"Domov; "5G", 2:4\x"#.into(), + password: r#"heslo;:,"\ž"#.into(), + security: WifiSecurity::Wpa, + hidden: true, + }) + .unwrap(), + ), + ( + "vcard", + payload_string(&Payload::Contact { + name: "Jan Novák".into(), + phone: Some("+420 777 123 456".into()), + email: Some("jan.novak@example.cz".into()), + organisation: Some("Domi, s.r.o.".into()), + url: Some("https://example.cz".into()), + address: Some("Dlouhá 12\n110 00 Praha 1".into()), + note: Some("Poznámka; s čárkou, a\nřádkem".into()), + }) + .unwrap(), + ), + ("ascii", "HELLO 12345 hello".to_string()), + ] +} + +fn navy_on_cream() -> Style { + Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 255], ..Style::default() } +} + +#[test] +fn all_payloads_all_levels_black_on_white() { + for (name, text) in payloads() { + for level in LEVELS { + let r = render_rgba(&text, level, &Style::default(), None).unwrap(); + assert_eq!(r.level_used, level); + let (decoded, ecc) = decode_with_level(&r.image); + assert_eq!(decoded, text, "{name} at {level:?}"); + assert_eq!(ecc, rqrr_level(level), "{name} at {level:?}"); + } + } +} + +#[test] +fn all_payloads_all_levels_navy_on_cream() { + for (name, text) in payloads() { + for level in LEVELS { + let r = render_rgba(&text, level, &navy_on_cream(), None).unwrap(); + assert_eq!(r.image.get_pixel(0, 0).0, [255, 250, 225, 255], "the quiet zone is the light colour"); + assert_eq!(decode(&r.image), text, "{name} at {level:?}"); + } + } +} + +#[test] +fn with_logo_forces_level_h_and_still_decodes() { + let logos = [logo(200, 200), logo(300, 120), logo(40, 90)]; + for (name, text) in payloads() { + for lg in &logos { + for level in [Level::L, Level::M] { + let r = render_rgba(&text, level, &navy_on_cream(), Some(lg)).unwrap(); + assert_eq!(r.level_used, Level::H, "a logo forces level H"); + let (decoded, ecc) = decode_with_level(&r.image); + assert_eq!(decoded, text, "{name} with a {}x{} logo", lg.width(), lg.height()); + assert_eq!(ecc, rqrr_level(Level::H)); + } + } + } +} + +#[test] +fn logo_is_drawn_centred_and_bounded() { + let text = payloads()[0].1.clone(); + let style = Style { size_px: 600, ..Style::default() }; + let r = render_rgba(&text, Level::M, &style, Some(&logo(100, 100))).unwrap(); + let size = r.image.width(); + let module_px = r.module_px; + let code_px = r.modules * module_px; + // The logo's red circle is in the middle of the image. + let centre = r.image.get_pixel(size / 2, size / 2).0; + assert_eq!(centre, [200, 20, 40, 255]); + // Nothing red farther than 22% of the code's width / 2 from the centre (plus a pixel of resampling). + let half = (code_px as f64 * 0.22 / 2.0).ceil() as i64 + 1; + for (x, y, p) in r.image.enumerate_pixels() { + if p.0[0] > 150 && p.0[1] < 100 { + let (dx, dy) = (x as i64 - size as i64 / 2, y as i64 - size as i64 / 2); + assert!(dx.abs() <= half && dy.abs() <= half, "logo pixel at {x},{y} outside the 22% box"); + } + } +} + +#[test] +fn small_payload_with_logo_still_decodes() { + for text in ["Hi", "https://x.cz", "1234567890"] { + let r = render_rgba(text, Level::L, &Style::default(), Some(&logo(64, 64))).unwrap(); + assert_eq!(r.level_used, Level::H); + assert_eq!(decode(&r.image), text); + } +} + +#[test] +fn size_is_integer_scaled_and_reported() { + let style = Style { size_px: 500, quiet_zone: 4, ..Style::default() }; + let r = render_rgba("hello", Level::M, &style, None).unwrap(); + let total = r.modules + 2 * 4; + assert_eq!(r.image.width(), r.image.height()); + assert_eq!(r.image.width(), r.size_px); + assert_eq!(r.size_px, total * r.module_px); + assert!(r.size_px <= 500 && r.size_px > 500 - total, "{} px", r.size_px); + assert_eq!(r.module_px, 500 / total); +} + +#[test] +fn png_decodes_back() { + let text = payloads()[3].1.clone(); + let png = render_png(&text, Level::Q, &navy_on_cream(), Some(&logo(50, 50))).unwrap(); + assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n"); + let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(decode(&img), text); +} + +#[test] +fn quiet_zone_widths_decode() { + for qz in [1, 4, 10] { + let style = Style { quiet_zone: qz, ..Style::default() }; + let r = render_rgba("quiet zone", Level::M, &style, None).unwrap(); + assert_eq!(r.size_px, (r.modules + 2 * qz) * r.module_px); + assert_eq!(decode(&r.image), "quiet zone"); + } +} diff --git a/crates/qr/tests/svg.rs b/crates/qr/tests/svg.rs new file mode 100644 index 0000000..6ed79ea --- /dev/null +++ b/crates/qr/tests/svg.rs @@ -0,0 +1,113 @@ +//! SVG output: the structure, and a rasterisation of its module path that must decode back. + +mod common; + +use common::{decode_gray, logo_png}; +use image::{GrayImage, Luma}; +use pictor_qr::{Level, QrError, Style, render_rgba, render_svg}; + +/// The SVG's dark modules as horizontal runs `(x, y, len)` in module units (quiet zone included), parsed from the +/// path's `M{x} {y}h{len}v1h-{len}z` segments. +fn runs(svg: &str) -> Vec<(u32, u32, u32)> { + let start = svg.find(" d=\"").expect("a path with d") + 4; + let end = start + svg[start..].find('"').unwrap(); + let d = &svg[start..end]; + d.split('M') + .filter(|s| !s.is_empty()) + .map(|seg| { + let (xy, rest) = seg.split_once('h').expect("h after M"); + let (x, y) = xy.split_once(' ').expect("x y"); + let (len, tail) = rest.split_once('v').expect("v after h"); + assert_eq!(tail, format!("1h-{len}z"), "segment {seg}"); + (x.parse().unwrap(), y.parse().unwrap(), len.parse().unwrap()) + }) + .collect() +} + +fn view_box_size(svg: &str) -> u32 { + let start = svg.find("viewBox=\"0 0 ").unwrap() + 13; + let rest = &svg[start..]; + rest[..rest.find(' ').unwrap()].parse().unwrap() +} + +fn rasterise(svg: &str, scale: u32) -> GrayImage { + let n = view_box_size(svg); + let mut img = GrayImage::from_pixel(n * scale, n * scale, Luma([255])); + for (x, y, len) in runs(svg) { + for py in y * scale..(y + 1) * scale { + for px in x * scale..(x + len) * scale { + img.put_pixel(px, py, Luma([0])); + } + } + } + img +} + +#[test] +fn svg_structure() { + let text = "Příliš žluťoučký kůň"; + let style = Style { size_px: 400, ..Style::default() }; + let svg = render_svg(text, Level::M, &style, None).unwrap(); + assert!(svg.starts_with("")); + assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\"")); + assert_eq!(svg.matches(" Date: Mon, 16 Nov 2026 13:18:19 +0100 Subject: [PATCH 03/13] [save] Atomic save: temp + flush + rename, .bak first, kill tests --- crates/save/Cargo.toml | 11 ++++ crates/save/src/lib.rs | 106 +++++++++++++++++++++++++++++++ crates/save/tests/kill.rs | 130 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 247 insertions(+) create mode 100644 crates/save/Cargo.toml create mode 100644 crates/save/src/lib.rs create mode 100644 crates/save/tests/kill.rs diff --git a/crates/save/Cargo.toml b/crates/save/Cargo.toml new file mode 100644 index 0000000..831fe04 --- /dev/null +++ b/crates/save/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "pictor-save" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +tempfile.workspace = true diff --git a/crates/save/src/lib.rs b/crates/save/src/lib.rs new file mode 100644 index 0000000..2babae7 --- /dev/null +++ b/crates/save/src/lib.rs @@ -0,0 +1,106 @@ +//! Safe saving for Pictor: a file on disk is either the old version or the new one, never half of each. +//! +//! - [`save_new`] writes a new file and refuses to replace an existing one (the default: `-edited.pdf`). +//! - [`save_overwrite`] replaces a file, first keeping the current version as `.bak`. +//! +//! Both write to a temporary file in the target's folder, flush it to disk, and then rename it into place, so a +//! crash, a kill or a full disk at any moment leaves the original as it was. The `.bak` is written the same way, so +//! it is always either the previous backup or a full copy of the original. +use std::fs::File; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, thiserror::Error)] +pub enum SaveError { + #[error("A file named {0} already exists.")] + Exists(String), + #[error("Pictor could not save {path}: {source}")] + Io { path: String, source: io::Error }, +} + +fn io_err(path: &Path) -> impl FnOnce(io::Error) -> SaveError + '_ { + move |source| SaveError::Io { path: path.display().to_string(), source } +} + +/// The default name for an edited copy: `report.pdf` → `report-edited.pdf`, then `report-edited-2.pdf`, … +/// (the first one that does not exist yet). +pub fn edited_path(original: &Path) -> PathBuf { + let dir = original.parent().unwrap_or(Path::new(".")); + let stem = original.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let ext = original.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + let mut n = 1u32; + loop { + let name = if n == 1 { format!("{stem}-edited{ext}") } else { format!("{stem}-edited-{n}{ext}") }; + let candidate = dir.join(name); + if !candidate.exists() { + return candidate; + } + n += 1; + } +} + +/// The backup path of `target`: `doc.pdf` → `doc.pdf.bak`. +pub fn bak_path(target: &Path) -> PathBuf { + let mut name = target.file_name().unwrap_or_default().to_os_string(); + name.push(".bak"); + target.with_file_name(name) +} + +fn temp_in(dir: &Path) -> Result { + tempfile::Builder::new().prefix(".pictor-").suffix(".tmp").tempfile_in(dir).map_err(io_err(dir)) +} + +fn parent(target: &Path) -> &Path { + match target.parent() { + Some(p) if !p.as_os_str().is_empty() => p, + _ => Path::new("."), + } +} + +/// Writes `bytes` to a new file at `target`; fails with [`SaveError::Exists`] if something is already there. +pub fn save_new(target: &Path, bytes: &[u8]) -> Result<(), SaveError> { + let mut tmp = temp_in(parent(target))?; + tmp.write_all(bytes).map_err(io_err(target))?; + tmp.as_file().sync_all().map_err(io_err(target))?; + tmp.persist_noclobber(target).map_err(|e| { + if e.error.kind() == io::ErrorKind::AlreadyExists || target.exists() { + SaveError::Exists(target.file_name().unwrap_or_default().to_string_lossy().into_owned()) + } else { + SaveError::Io { path: target.display().to_string(), source: e.error } + } + })?; + Ok(()) +} + +/// Replaces `target` with `bytes`, keeping the current version as `.bak` first. Returns the `.bak` path +/// (which does not exist if `target` did not exist). +pub fn save_overwrite(target: &Path, bytes: &[u8]) -> Result { + save_overwrite_hooked(target, |f| f.write_all(bytes), || {}) +} + +/// [`save_overwrite`] with the content written by `write` and a hook called just before the `.bak` is renamed into +/// place. Only the save-safety tests use the hooks (they stop the process inside a save and kill it). +#[doc(hidden)] +pub fn save_overwrite_hooked( + target: &Path, + write: impl FnOnce(&mut File) -> io::Result<()>, + before_bak_rename: impl FnOnce(), +) -> Result { + let dir = parent(target); + let bak = bak_path(target); + // 1. The backup: a full copy written beside the target, flushed, then renamed over any older .bak. + if target.exists() { + let mut tmp = temp_in(dir)?; + let mut src = File::open(target).map_err(io_err(target))?; + io::copy(&mut src, tmp.as_file_mut()).map_err(io_err(&bak))?; + tmp.as_file().sync_all().map_err(io_err(&bak))?; + before_bak_rename(); + tmp.persist(&bak).map_err(|e| SaveError::Io { path: bak.display().to_string(), source: e.error })?; + } + // 2. The new content, flushed, then renamed over the target in one step. + let mut tmp = temp_in(dir)?; + write(tmp.as_file_mut()).map_err(io_err(target))?; + tmp.as_file().sync_all().map_err(io_err(target))?; + tmp.persist(target).map_err(|e| SaveError::Io { path: target.display().to_string(), source: e.error })?; + Ok(bak) +} diff --git a/crates/save/tests/kill.rs b/crates/save/tests/kill.rs new file mode 100644 index 0000000..9d22ad4 --- /dev/null +++ b/crates/save/tests/kill.rs @@ -0,0 +1,130 @@ +//! Mandatory test 5 (save safety): a write killed mid-way leaves the original intact and the .bak valid. +//! The test binary re-runs itself as the child (PICTOR_SAVE_CHILD set), which stops inside a save and is killed. +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +const ORIGINAL: &[u8] = b"%PDF-1.7 original content that must survive"; +const OLD_BAK: &[u8] = b"%PDF-1.7 the previous backup"; + +fn new_content() -> Vec { + let mut v = b"%PDF-1.7 new content ".to_vec(); + v.resize(4 << 20, b'x'); + v +} + +/// The child half: started by `run_child`, never run directly (it waits forever inside the save). +#[test] +fn child() { + let Ok(dir) = std::env::var("PICTOR_SAVE_CHILD") else { return }; + let stage = std::env::var("PICTOR_SAVE_STAGE").unwrap(); + let dir = PathBuf::from(dir); + let target = dir.join("doc.pdf"); + let ready = dir.join("ready"); + let stop = || { + std::fs::write(&ready, b"1").unwrap(); + loop { + std::thread::sleep(Duration::from_secs(60)); + } + }; + let content = new_content(); + let _ = pictor_save::save_overwrite_hooked( + &target, + |f| { + use std::io::Write; + f.write_all(&content[..content.len() / 2])?; + f.flush()?; + if stage == "content" { + stop(); + } + f.write_all(&content[content.len() / 2..]) + }, + || { + if stage == "bak" { + stop(); + } + }, + ); +} + +fn run_child(dir: &Path, stage: &str) { + let exe = std::env::current_exe().unwrap(); + let mut child = Command::new(exe) + .args(["--exact", "child", "--nocapture", "--test-threads=1"]) + .env("PICTOR_SAVE_CHILD", dir) + .env("PICTOR_SAVE_STAGE", stage) + .spawn() + .unwrap(); + let started = Instant::now(); + while !dir.join("ready").exists() { + assert!(started.elapsed() < Duration::from_secs(30), "child never reached the stage"); + std::thread::sleep(Duration::from_millis(20)); + } + child.kill().unwrap(); + child.wait().unwrap(); +} + +fn setup(with_old_bak: bool) -> tempfile::TempDir { + let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); + std::fs::write(dir.path().join("doc.pdf"), ORIGINAL).unwrap(); + if with_old_bak { + std::fs::write(dir.path().join("doc.pdf.bak"), OLD_BAK).unwrap(); + } + dir +} + +#[test] +fn killed_while_writing_new_content_keeps_original_and_bak() { + let dir = setup(false); + run_child(dir.path(), "content"); + assert_eq!(std::fs::read(dir.path().join("doc.pdf")).unwrap(), ORIGINAL, "original changed"); + assert_eq!(std::fs::read(dir.path().join("doc.pdf.bak")).unwrap(), ORIGINAL, ".bak is not the original"); +} + +#[test] +fn killed_while_writing_bak_keeps_original_and_old_bak() { + let dir = setup(true); + run_child(dir.path(), "bak"); + assert_eq!(std::fs::read(dir.path().join("doc.pdf")).unwrap(), ORIGINAL, "original changed"); + let bak = std::fs::read(dir.path().join("doc.pdf.bak")).unwrap(); + assert!(bak == OLD_BAK || bak == ORIGINAL, ".bak is neither the old backup nor the original"); +} + +#[test] +fn a_finished_overwrite_replaces_the_file_and_keeps_a_bak() { + let dir = setup(true); + let target = dir.path().join("doc.pdf"); + let content = new_content(); + let bak = pictor_save::save_overwrite(&target, &content).unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), content); + assert_eq!(bak, dir.path().join("doc.pdf.bak")); + assert_eq!(std::fs::read(&bak).unwrap(), ORIGINAL); + let leftovers: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .filter(|n| n != "doc.pdf" && n != "doc.pdf.bak") + .collect(); + assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}"); +} + +#[test] +fn save_new_never_overwrites_and_names_the_copy() { + let dir = setup(false); + let target = dir.path().join("doc.pdf"); + let first = pictor_save::edited_path(&target); + assert_eq!(first, dir.path().join("doc-edited.pdf")); + pictor_save::save_new(&first, b"one").unwrap(); + assert!(pictor_save::save_new(&first, b"two").is_err(), "save_new clobbered an existing file"); + assert_eq!(std::fs::read(&first).unwrap(), b"one"); + assert_eq!(pictor_save::edited_path(&target), dir.path().join("doc-edited-2.pdf")); + assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL); +} + +#[test] +fn overwrite_of_a_missing_file_makes_no_bak() { + let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); + let target = dir.path().join("fresh.png"); + let bak = pictor_save::save_overwrite(&target, b"png").unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"png"); + assert!(!bak.exists()); +} From 2c1611b34a6d5a8d9d5d54b401560d964a088986 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:26:02 +0100 Subject: [PATCH 04/13] [pdf] Redaction: rebuild redacted pages as one image, scrub hidden data, prune; reader and AES-256 protect/unlock --- Cargo.toml | 80 +++---- crates/pdf/Cargo.toml | 19 ++ crates/pdf/src/edit.rs | 1 + crates/pdf/src/engine.rs | 46 ++++ crates/pdf/src/error.rs | 70 ++++++ crates/pdf/src/geometry.rs | 92 ++++++++ crates/pdf/src/lib.rs | 47 ++++ crates/pdf/src/pages.rs | 1 + crates/pdf/src/reader.rs | 170 ++++++++++++++ crates/pdf/src/redact.rs | 406 +++++++++++++++++++++++++++++++++ crates/pdf/src/security.rs | 51 +++++ crates/pdf/tests/common/mod.rs | 267 ++++++++++++++++++++++ crates/pdf/tests/redaction.rs | 153 +++++++++++++ docs/DEPENDENCIES.md | 174 +++++++------- 14 files changed, 1452 insertions(+), 125 deletions(-) create mode 100644 crates/pdf/Cargo.toml create mode 100644 crates/pdf/src/edit.rs create mode 100644 crates/pdf/src/engine.rs create mode 100644 crates/pdf/src/error.rs create mode 100644 crates/pdf/src/geometry.rs create mode 100644 crates/pdf/src/lib.rs create mode 100644 crates/pdf/src/pages.rs create mode 100644 crates/pdf/src/reader.rs create mode 100644 crates/pdf/src/redact.rs create mode 100644 crates/pdf/src/security.rs create mode 100644 crates/pdf/tests/common/mod.rs create mode 100644 crates/pdf/tests/redaction.rs diff --git a/Cargo.toml b/Cargo.toml index 904f6dc..7c4a332 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,39 +1,41 @@ -[workspace] -resolver = "3" -members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"] - -[workspace.package] -version = "0.1.0" -edition = "2024" -license = "MPL-2.0" -repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public" -rust-version = "1.88" - -# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. -[workspace.dependencies] -pictor-raster = { path = "crates/raster" } -pictor-pdf = { path = "crates/pdf" } -pictor-meta = { path = "crates/meta" } -pictor-qr = { path = "crates/qr" } -pictor-save = { path = "crates/save" } - -thiserror = "2" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -base64 = "0.22" -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] } -kamadak-exif = "0.6" -img-parts = "0.4" -qrcode = { version = "0.14", default-features = false, features = ["svg"] } -lopdf = { version = "0.47", default-features = false } -pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] } -tempfile = "3" -sha2 = "0.11" -windows = "0.62" - -# dev-only -rqrr = "0.11" -proptest = "1" - -[profile.dev.package."*"] -opt-level = 2 +[workspace] +resolver = "3" +members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public" +rust-version = "1.88" + +# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. +[workspace.dependencies] +pictor-raster = { path = "crates/raster" } +pictor-pdf = { path = "crates/pdf" } +pictor-meta = { path = "crates/meta" } +pictor-qr = { path = "crates/qr" } +pictor-save = { path = "crates/save" } + +thiserror = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +base64 = "0.22" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] } +kamadak-exif = "0.6" +img-parts = "0.4" +qrcode = { version = "0.14", default-features = false, features = ["svg"] } +lopdf = { version = "0.47", default-features = false } +pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] } +tempfile = "3" +sha2 = "0.11" +getrandom = "0.4" +flate2 = "1" +windows = "0.62" + +# dev-only +rqrr = "0.11" +proptest = "1" + +[profile.dev.package."*"] +opt-level = 2 diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml new file mode 100644 index 0000000..ee43f81 --- /dev/null +++ b/crates/pdf/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "pictor-pdf" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true +lopdf.workspace = true +pdfium-render.workspace = true +pictor-meta.workspace = true +getrandom.workspace = true + +[dev-dependencies] +flate2.workspace = true diff --git a/crates/pdf/src/edit.rs b/crates/pdf/src/edit.rs new file mode 100644 index 0000000..6354e9c --- /dev/null +++ b/crates/pdf/src/edit.rs @@ -0,0 +1 @@ +//! The edit pipeline (form fill, annotations, stamps, flatten, security). diff --git a/crates/pdf/src/engine.rs b/crates/pdf/src/engine.rs new file mode 100644 index 0000000..a63468f --- /dev/null +++ b/crates/pdf/src/engine.rs @@ -0,0 +1,46 @@ +use crate::PdfError; +use pdfium_render::prelude::*; +use std::path::Path; +use std::sync::OnceLock; + +/// The one pdfium instance of the process (pdfium is not thread-safe; pdfium-render's `thread_safe` feature +/// serialises calls). Load it once with [`Engine::load`]. +pub struct Engine { + pub(crate) pdfium: Pdfium, +} + +static ENGINE: OnceLock = OnceLock::new(); +static LOAD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +impl Engine { + /// Loads pdfium.dll from `dir` (or from the system search path when `None`). Later calls return the same engine. + pub fn load(dir: Option<&Path>) -> Result<&'static Engine, PdfError> { + if let Some(e) = ENGINE.get() { + return Ok(e); + } + let _guard = LOAD_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(e) = ENGINE.get() { + return Ok(e); + } + let bindings = match dir { + Some(d) => Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path(d)), + None => Pdfium::bind_to_system_library(), + } + .map_err(|e| PdfError::EngineMissing(e.to_string()))?; + let _ = ENGINE.set(Engine { pdfium: Pdfium::new(bindings) }); + Ok(ENGINE.get().expect("just set")) + } + + pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result, PdfError> { + self.pdfium.load_pdf_from_byte_slice(bytes, password).map_err(|e| PdfError::from_pdfium_open(e, password.is_some())) + } + + pub(crate) fn new_document(&self) -> Result, PdfError> { + self.pdfium.create_new_pdf().map_err(PdfError::from_pdfium) + } +} + +/// pdfium's save, with the security handler removed (Pictor re-encrypts with lopdf when asked). +pub(crate) fn pdfium_save(doc: &PdfDocument) -> Result, PdfError> { + doc.save_to_bytes().map_err(|e| PdfError::Write(e.to_string())) +} diff --git a/crates/pdf/src/error.rs b/crates/pdf/src/error.rs new file mode 100644 index 0000000..3d65fe1 --- /dev/null +++ b/crates/pdf/src/error.rs @@ -0,0 +1,70 @@ +use pdfium_render::prelude::{PdfiumError, PdfiumInternalError}; + +/// Errors shown to the user; the messages are plain sentences. +#[derive(Debug, thiserror::Error)] +pub enum PdfError { + #[error("Pictor's PDF engine (pdfium.dll) could not be loaded: {0}")] + EngineMissing(String), + #[error("This PDF is password-protected. Enter its password to open it.")] + NeedsPassword, + #[error("That password is not right for this PDF.")] + WrongPassword, + #[error("This file is not a PDF Pictor can read: {0}")] + Damaged(String), + #[error("This PDF uses a feature Pictor does not support: {0}")] + Unsupported(String), + #[error("Page {0} does not exist in this PDF.")] + NoSuchPage(usize), + #[error("{0}")] + Invalid(String), + #[error("Pictor could not write the PDF: {0}")] + Write(String), + #[error("This PDF is too large for Pictor: {0}")] + TooLarge(String), +} + +impl PdfError { + pub(crate) fn from_pdfium(e: PdfiumError) -> PdfError { + match e { + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::PasswordError) => PdfError::WrongPassword, + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::FormatError) => { + PdfError::Damaged("its structure is broken beyond repair".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::FileError) => { + PdfError::Damaged("the file could not be read".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::SecurityError) => { + PdfError::Unsupported("its encryption method".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::PageError) => { + PdfError::Damaged("a page could not be read".into()) + } + other => PdfError::Damaged(other.to_string()), + } + } + + pub(crate) fn from_pdfium_open(e: PdfiumError, had_password: bool) -> PdfError { + match PdfError::from_pdfium(e) { + PdfError::WrongPassword if !had_password => PdfError::NeedsPassword, + other => other, + } + } + + pub(crate) fn from_lopdf(e: lopdf::Error, had_password: bool) -> PdfError { + use lopdf::Error as E; + let text = e.to_string(); + match e { + E::Decryption(_) | E::InvalidPassword if had_password => PdfError::WrongPassword, + E::Decryption(_) | E::InvalidPassword => PdfError::NeedsPassword, + _ if text.to_ascii_lowercase().contains("password") => { + if had_password { + PdfError::WrongPassword + } else { + PdfError::NeedsPassword + } + } + _ if text.to_ascii_lowercase().contains("limit") => PdfError::TooLarge(text), + _ => PdfError::Damaged(text), + } + } +} diff --git a/crates/pdf/src/geometry.rs b/crates/pdf/src/geometry.rs new file mode 100644 index 0000000..11412ae --- /dev/null +++ b/crates/pdf/src/geometry.rs @@ -0,0 +1,92 @@ +//! View space ↔ PDF user space. +//! +//! View space: points from the top-left corner of the page *as displayed* — the crop box, turned by `/Rotate` +//! (clockwise). That is what the UI draws and what the user drags on. PDF user space: the page's own coordinates, +//! origin bottom-left of the media box, before rotation. +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct ViewPoint { + pub x: f32, + pub y: f32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct ViewRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +impl ViewRect { + pub fn is_empty(&self) -> bool { + !(self.w > 0.0 && self.h > 0.0) || !self.x.is_finite() || !self.y.is_finite() + } +} + +/// What view space needs to know about a page. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct PageFrame { + /// The crop box in user space: x0, y0, x1, y1 (normalised so x0 < x1, y0 < y1). + pub crop: [f32; 4], + /// `/Rotate`, normalised to 0, 90, 180 or 270. + pub rotate: u16, +} + +impl PageFrame { + /// The displayed size in points (width, height). + pub fn view_size(&self) -> (f32, f32) { + let (w, h) = (self.crop[2] - self.crop[0], self.crop[3] - self.crop[1]); + if self.rotate % 180 == 90 { (h, w) } else { (w, h) } + } + + /// A view-space point → user space. + pub fn to_user(&self, p: ViewPoint) -> (f32, f32) { + let [x0, y0, x1, y1] = self.crop; + match self.rotate { + 90 => (x0 + p.y, y0 + p.x), + 180 => (x1 - p.x, y0 + p.y), + 270 => (x1 - p.y, y1 - p.x), + _ => (x0 + p.x, y1 - p.y), + } + } + + /// A view-space rectangle → a user-space rectangle [x0, y0, x1, y1]. + pub fn rect_to_user(&self, r: ViewRect) -> [f32; 4] { + let (ax, ay) = self.to_user(ViewPoint { x: r.x, y: r.y }); + let (bx, by) = self.to_user(ViewPoint { x: r.x + r.w, y: r.y + r.h }); + [ax.min(bx), ay.min(by), ax.max(bx), ay.max(by)] + } +} + +pub(crate) fn normalise_rotate(r: i64) -> u16 { + (((r % 360) + 360) % 360 / 90 * 90) as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corners_map_for_every_rotation() { + let crop = [10.0, 20.0, 110.0, 220.0]; // 100 × 200 + let top_left = ViewPoint { x: 0.0, y: 0.0 }; + let f = |r| PageFrame { crop, rotate: r }; + assert_eq!(f(0).to_user(top_left), (10.0, 220.0)); + assert_eq!(f(90).to_user(top_left), (10.0, 20.0)); + assert_eq!(f(180).to_user(top_left), (110.0, 20.0)); + assert_eq!(f(270).to_user(top_left), (110.0, 220.0)); + assert_eq!(f(90).view_size(), (200.0, 100.0)); + // The far corner of the view is the opposite user corner. + let (w, h) = f(90).view_size(); + assert_eq!(f(90).to_user(ViewPoint { x: w, y: h }), (110.0, 220.0)); + } + + #[test] + fn rotate_is_normalised() { + assert_eq!(normalise_rotate(-90), 270); + assert_eq!(normalise_rotate(450), 90); + assert_eq!(normalise_rotate(45), 0); + } +} diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs new file mode 100644 index 0000000..1fe854d --- /dev/null +++ b/crates/pdf/src/lib.rs @@ -0,0 +1,47 @@ +//! Pictor's PDF engine: pdfium for everything that reads or draws a page, lopdf for structure that must be written +//! exactly (annotations, stamps, the redaction rebuild, encryption). Which library does which operation, and why, +//! is recorded in the app's `docs/01_v1.md` and in [`docs/FORMATS.md`](../../docs/FORMATS.md). +//! +//! Coordinates: the UI works in **view space** — PDF points (1/72 inch) from the top-left corner of the page as it +//! is displayed (crop box, `/Rotate` applied). [`geometry`] converts view space to a page's own user space. +//! +//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches +//! the file system. Outside files are hostile; call these only inside `pictor-worker`. + +mod edit; +mod engine; +mod error; +pub mod geometry; +mod pages; +mod reader; +mod redact; +mod security; + +pub use edit::*; +pub use engine::Engine; +pub use error::PdfError; +pub use geometry::{ViewRect, ViewPoint}; +pub use pages::*; +pub use reader::*; +pub use redact::{RedactOptions, Redacted, Redaction, redact}; +pub use security::{is_encrypted, protect, unlock}; + +/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB). +pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result { + let mut opts = lopdf::LoadOptions::default(); + opts.max_decompressed_size = Some(256 << 20); + if let Some(p) = password { + opts.password = Some(p.to_owned()); + } + match lopdf::Document::load_mem_with_options(bytes, opts) { + Ok(doc) if doc.is_encrypted() => Err(PdfError::NeedsPassword), + Ok(doc) => Ok(doc), + Err(e) => Err(PdfError::from_lopdf(e, password.is_some())), + } +} + +pub(crate) fn lopdf_save(doc: &mut lopdf::Document) -> Result, PdfError> { + let mut out = Vec::new(); + doc.save_to(&mut out).map_err(|e| PdfError::Write(e.to_string()))?; + Ok(out) +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs new file mode 100644 index 0000000..e63a04d --- /dev/null +++ b/crates/pdf/src/pages.rs @@ -0,0 +1 @@ +//! Page operations, merge, split, images to PDF, PDF to images (pdfium). diff --git a/crates/pdf/src/reader.rs b/crates/pdf/src/reader.rs new file mode 100644 index 0000000..5a49583 --- /dev/null +++ b/crates/pdf/src/reader.rs @@ -0,0 +1,170 @@ +//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a +//! file Edge opens, Pictor opens). +use crate::{Engine, PdfError, ViewRect}; +use image::DynamicImage; +use pdfium_render::prelude::*; +use serde::Serialize; + +/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). +pub const MAX_RENDER_PIXELS: i64 = 50_000_000; + +#[derive(Debug, Clone, Serialize)] +pub struct DocInfo { + pub pages: Vec, + pub outline: Vec, + pub has_form: bool, + pub encrypted: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PageInfo { + /// Displayed size in points. + pub width: f32, + pub height: f32, + pub label: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct OutlineItem { + pub title: String, + pub page: Option, + pub depth: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SearchHit { + pub page: usize, + /// The hit's boxes in view space. + pub rects: Vec, +} + +pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { + let doc = engine.open(bytes, password)?; + let mut pages = Vec::new(); + for page in doc.pages().iter() { + pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); + } + let mut outline = Vec::new(); + fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { + if *budget == 0 || depth > 32 { + return; + } + *budget -= 1; + let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); + out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); + if let Some(child) = b.first_child() { + let mut next = Some(child); + while let Some(c) = next { + next = c.next_sibling(); + walk(c, depth + 1, out, budget); + } + } + } + let mut budget = 5000; + let mut next = doc.bookmarks().root(); + while let Some(b) = next { + next = b.next_sibling(); + walk(b, 0, &mut outline, &mut budget); + } + let has_form = doc.form().is_some(); + Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) +} + +/// The displayed size of every page, in points. +pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) +} + +pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result { + let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; + let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); + let width = width_px.clamp(1, 20_000) as i64; + let height = ((width as f32) * h / w).ceil().max(1.0) as i64; + if width * height > MAX_RENDER_PIXELS { + return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); + } + let cfg = PdfRenderConfig::new() + .set_target_size(width as i32, height as i32) + .render_form_data(forms) + .render_annotations(true) + .set_clear_color(PdfColor::WHITE); + page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) +} + +/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. +pub fn render_page( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + index: usize, + width_px: u32, +) -> Result { + let doc = engine.open(bytes, password)?; + render_doc_page(&doc, index, width_px, true) +} + +/// The text of every page, in order. +pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for page in doc.pages().iter() { + out.push(page.text().map(|t| t.all()).map_err(PdfError::from_pdfium)?); + } + Ok(out) +} + +/// Case-insensitive search over every page; at most `limit` hits. +pub fn search( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + query: &str, + limit: usize, +) -> Result, PdfError> { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + let doc = engine.open(bytes, password)?; + let mut hits = Vec::new(); + for (i, page) in doc.pages().iter().enumerate() { + let frame = page_frame(&page); + let text = page.text().map_err(PdfError::from_pdfium)?; + let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; + while let Some(segments) = search.find_next() { + let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); + hits.push(SearchHit { page: i, rects }); + if hits.len() >= limit { + return Ok(hits); + } + } + } + Ok(hits) +} + +pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { + let crop = page.boundaries().crop().or_else(|_| page.boundaries().media()).map(|b| b.bounds).unwrap_or(PdfRect::ZERO); + let rotate = match page.rotation() { + Ok(PdfPageRenderRotation::Degrees90) => 90, + Ok(PdfPageRenderRotation::Degrees180) => 180, + Ok(PdfPageRenderRotation::Degrees270) => 270, + _ => 0, + }; + let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; + crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } +} + +impl crate::geometry::PageFrame { + /// A user-space rectangle → view space. + pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { + let [x0, y0, x1, y1] = self.crop; + let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); + let (vx0, vy0, vx1, vy1) = match self.rotate { + 90 => (b - y0, l - x0, t - y0, rt - x0), + 180 => (x1 - rt, b - y0, x1 - l, t - y0), + 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), + _ => (l - x0, y1 - t, rt - x0, y1 - b), + }; + ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } + } +} diff --git a/crates/pdf/src/redact.rs b/crates/pdf/src/redact.rs new file mode 100644 index 0000000..02045c7 --- /dev/null +++ b/crates/pdf/src/redact.rs @@ -0,0 +1,406 @@ +//! True redaction. Each redacted page is rendered by pdfium, the boxes are painted black into the pixels, and the +//! page is rebuilt by lopdf as that one image: no text, image, vector, annotation or form content of the old page +//! survives. The other pages are not touched (their objects are written back byte for byte). The document's +//! metadata and the places hidden text can live (XMP, /Info, the struct tree's ActualText, bookmarks, +//! attachments, JavaScript) are removed, every unreferenced object is pruned, and the file is written fresh (no +//! incremental history). +//! +//! The brief's alternative, rewriting the page's content stream to cut out only what lies under the box, is not +//! used: it needs a full content-stream interpreter (fonts, glyph positions, form XObjects, inline images, +//! clipping, shadings, Type 3 fonts) and any mistake leaves text behind. The cost of the chosen method: the text of +//! a redacted page is no longer selectable or searchable. docs/FORMATS.md records this. +use crate::{Engine, PdfError, ViewRect, lopdf_load, lopdf_save, reader::render_doc_page}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeSet, HashSet}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Redaction { + /// 0-based page index. + pub page: usize, + /// Boxes in view space (points, top-left origin of the displayed page). + pub rects: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedactOptions { + /// Resolution of the rebuilt pages. + pub dpi: u32, + pub jpeg_quality: u8, +} + +impl Default for RedactOptions { + fn default() -> Self { + RedactOptions { dpi: 200, jpeg_quality: 90 } + } +} + +#[derive(Debug, Clone)] +pub struct Redacted { + /// The new PDF, not encrypted. + pub bytes: Vec, + /// Plain sentences for the user (for example, hidden layers left on pages that were not redacted). + pub warnings: Vec, +} + +const IMAGE_NAME: &[u8] = b"PictorRedacted"; + +pub fn redact( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + redactions: &[Redaction], + opts: &RedactOptions, +) -> Result { + if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) { + return Err(PdfError::Invalid("Draw at least one box to redact.".into())); + } + // 1. Render every redacted page with pdfium (annotations and form fields included) and burn the boxes in. + let pdfium_doc = engine.open(bytes, password)?; + let page_count = pdfium_doc.pages().len() as usize; + let mut images: Vec<(usize, Vec, u32, u32, f32, f32)> = Vec::new(); + let mut seen = BTreeSet::new(); + for r in redactions { + if r.page >= page_count { + return Err(PdfError::NoSuchPage(r.page + 1)); + } + if !seen.insert(r.page) { + continue; + } + let rects: Vec = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect(); + let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?; + let (vw, vh) = (page.width().value, page.height().value); + drop(page); + let mut dpi = opts.dpi.clamp(72, 600) as f32; + while (vw * dpi / 72.0) * (vh * dpi / 72.0) > crate::reader::MAX_RENDER_PIXELS as f32 / 2.0 && dpi > 36.0 { + dpi *= 0.8; + } + let px_w = (vw * dpi / 72.0).round().max(1.0) as u32; + let mut img = render_doc_page(&pdfium_doc, r.page, px_w, true)?.to_rgb8(); + let scale = img.width() as f32 / vw; + for rect in &rects { + let x0 = ((rect.x * scale).floor() as i64 - 1).clamp(0, img.width() as i64) as u32; + let y0 = ((rect.y * scale).floor() as i64 - 1).clamp(0, img.height() as i64) as u32; + let x1 = (((rect.x + rect.w) * scale).ceil() as i64 + 1).clamp(0, img.width() as i64) as u32; + let y1 = (((rect.y + rect.h) * scale).ceil() as i64 + 1).clamp(0, img.height() as i64) as u32; + for y in y0..y1 { + for x in x0..x1 { + img.put_pixel(x, y, image::Rgb([0, 0, 0])); + } + } + } + let mut jpeg = Vec::new(); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, opts.jpeg_quality.clamp(50, 100)) + .encode_image(&img) + .map_err(|e| PdfError::Write(e.to_string()))?; + images.push((r.page, jpeg, img.width(), img.height(), vw, vh)); + } + drop(pdfium_doc); + + // 2. Rebuild those pages with lopdf. + let mut doc = lopdf_load(bytes, password)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + if pages.len() != page_count { + return Err(PdfError::Damaged(format!( + "its page tree is inconsistent ({} pages by one reading, {} by another); Pictor will not redact it", + page_count, + pages.len() + ))); + } + let mut removed_annots: HashSet = HashSet::new(); + let redacted_pages: HashSet = images.iter().map(|i| pages[i.0]).collect(); + for (index, jpeg, pw, ph, vw, vh) in images { + let page_id = pages[index]; + let old = doc.get_dictionary(page_id).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + if let Ok(annots) = old.get(b"Annots") { + let list = match annots { + Object::Reference(id) => doc.get_object(*id).and_then(Object::as_array).cloned().unwrap_or_default(), + Object::Array(a) => a.clone(), + _ => Vec::new(), + }; + for a in list { + if let Object::Reference(id) = a { + removed_annots.insert(id); + if let Ok(Object::Dictionary(d)) = doc.get_object(id) + && let Ok(Object::Reference(popup)) = d.get(b"Popup") + { + removed_annots.insert(*popup); + } + } + } + } + let mut image = Stream::new( + dictionary! { + "Type" => "XObject", "Subtype" => "Image", "Width" => pw as i64, "Height" => ph as i64, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode", + }, + jpeg, + ); + image.allows_compression = false; + let image_id = doc.add_object(image); + let content = format!("q {vw:.4} 0 0 {vh:.4} 0 0 cm /PictorRedacted Do Q").into_bytes(); + let content_id = doc.add_object(Stream::new(dictionary! {}, content)); + let bbox = vec![0.into(), 0.into(), Object::Real(vw), Object::Real(vh)]; + let mut fresh = dictionary! { + "Type" => "Page", + "MediaBox" => bbox.clone(), + "CropBox" => bbox, + "Rotate" => 0, + "Resources" => dictionary! { "XObject" => Dictionary::from_iter([(IMAGE_NAME.to_vec(), Object::Reference(image_id))]) }, + "Contents" => content_id, + }; + if let Ok(parent) = old.get(b"Parent") { + fresh.set("Parent", parent.clone()); + } + doc.objects.insert(page_id, Object::Dictionary(fresh)); + } + // The annotations of redacted pages go, even if something else still points at them. + for id in &removed_annots { + doc.objects.remove(id); + } + + // Resources inherited from a Pages node would keep the redacted page's old fonts and images alive: give each + // remaining page that relied on them its own copy, then remove them from the Pages nodes. + push_down_resources(&mut doc, &pages, &redacted_pages); + + // 3. The form: fields whose widgets were all on redacted pages go. + let mut warnings = Vec::new(); + prune_form(&mut doc, &removed_annots); + + // 4. Document-level hiding places. + scrub_document(&mut doc, &redacted_pages, &mut warnings); + + // 5. Drop everything no longer referenced and write a fresh file. + doc.prune_objects(); + let out = lopdf_save(&mut doc)?; + Ok(Redacted { bytes: out, warnings }) +} + +fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSet) { + let mut nodes = HashSet::new(); + for &page in pages { + // The nearest ancestor's /Resources, and every Pages node on the way up. + let mut inherited = None; + let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok()); + let mut depth = 0; + while let Some(id) = current { + if depth > 64 || !nodes.insert(id) && inherited.is_some() { + break; + } + depth += 1; + let Ok(d) = doc.get_dictionary(id) else { break }; + if inherited.is_none() + && let Ok(r) = d.get(b"Resources") + { + inherited = Some(r.clone()); + } + current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + } + if redacted.contains(&page) { + continue; + } + if let (Some(r), Ok(d)) = (inherited, doc.get_dictionary_mut(page)) + && !d.has(b"Resources") + { + d.set("Resources", r); + } + } + for id in nodes { + if let Ok(d) = doc.get_dictionary_mut(id) { + d.remove(b"Resources"); + } + } +} + +fn prune_form(doc: &mut Document, removed: &HashSet) { + let Ok(catalog) = doc.catalog() else { return }; + let acroform = match catalog.get(b"AcroForm") { + Ok(Object::Reference(id)) => Some(*id), + _ => None, + }; + let fields: Vec = { + let form = match acroform { + Some(id) => doc.get_dictionary(id).ok(), + None => catalog.get(b"AcroForm").and_then(Object::as_dict).ok(), + }; + match form.and_then(|f| f.get(b"Fields").ok()) { + Some(Object::Array(a)) => a.clone(), + Some(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), + _ => Vec::new(), + } + }; + fn keep(doc: &mut Document, field: &Object, removed: &HashSet, depth: u32) -> bool { + let Object::Reference(id) = field else { return true }; + if removed.contains(id) { + return false; + } + if depth > 32 { + return true; + } + let kids = match doc.get_dictionary(*id).ok().and_then(|d| d.get(b"Kids").ok()) { + Some(Object::Array(a)) => a.clone(), + _ => return true, + }; + if kids.is_empty() { + return true; + } + let kept: Vec = kids.into_iter().filter(|k| keep(doc, k, removed, depth + 1)).collect(); + if kept.is_empty() { + return false; + } + if let Ok(d) = doc.get_dictionary_mut(*id) { + d.set("Kids", kept); + } + true + } + let kept: Vec = fields.iter().filter(|f| keep(doc, f, removed, 0)).cloned().collect(); + let changed = kept.len() != fields.len(); + let catalog_id = match doc.trailer.get(b"Root") { + Ok(Object::Reference(id)) => *id, + _ => return, + }; + if kept.is_empty() { + if let Ok(c) = doc.get_dictionary_mut(catalog_id) { + c.remove(b"AcroForm"); + } + return; + } + if changed { + let target = match acroform { + Some(id) => doc.get_dictionary_mut(id).ok(), + None => doc.get_dictionary_mut(catalog_id).ok().and_then(|c| c.get_mut(b"AcroForm").ok()).and_then(|o| o.as_dict_mut().ok()), + }; + if let Some(f) = target { + f.set("Fields", kept); + f.remove(b"CO"); + } + } +} + +/// Removes the document-level places where text can hide. Shared with [`crate::edit`]'s "remove hidden data". +pub(crate) fn scrub_document(doc: &mut Document, redacted_pages: &HashSet, warnings: &mut Vec) { + doc.trailer.remove(b"Info"); + let catalog_id = match doc.trailer.get(b"Root") { + Ok(Object::Reference(id)) => *id, + _ => return, + }; + // Hidden layers: drop the layer definitions only if no remaining page still uses one (else those pages would + // suddenly show their hidden content). + let pages: Vec = doc.get_pages().values().copied().collect(); + let mut oc_pages = Vec::new(); + for (i, p) in pages.iter().enumerate() { + if !redacted_pages.contains(p) && uses_optional_content(doc, *p) { + oc_pages.push(i + 1); + } + } + if let Ok(catalog) = doc.get_dictionary_mut(catalog_id) { + for key in [ + &b"Metadata"[..], + b"StructTreeRoot", + b"MarkInfo", + b"Outlines", + b"PieceInfo", + b"Threads", + b"AA", + b"Collection", + b"AF", + b"SpiderInfo", + b"Perms", + b"Legal", + ] { + catalog.remove(key); + } + if matches!(catalog.get(b"PageMode"), Ok(Object::Name(n)) if n == b"UseOutlines") { + catalog.remove(b"PageMode"); + } + if !matches!(catalog.get(b"OpenAction"), Ok(Object::Array(_))) { + catalog.remove(b"OpenAction"); + } + if oc_pages.is_empty() { + catalog.remove(b"OCProperties"); + } + } + if !oc_pages.is_empty() { + warnings.push(format!( + "Pages {} have hidden layers, which were left as they are. Redact those pages too to remove them.", + oc_pages.iter().map(|p| p.to_string()).collect::>().join(", ") + )); + } + // Names: attachments and document JavaScript go; destinations stay. + let names = match doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"Names").ok()) { + Some(Object::Reference(id)) => Some(*id), + _ => None, + }; + let strip_names = |d: &mut Dictionary| { + d.remove(b"EmbeddedFiles"); + d.remove(b"JavaScript"); + }; + match names { + Some(id) => { + if let Ok(d) = doc.get_dictionary_mut(id) { + strip_names(d); + } + } + None => { + if let Ok(c) = doc.get_dictionary_mut(catalog_id) + && let Ok(Object::Dictionary(d)) = c.get_mut(b"Names") + { + strip_names(d); + } + } + } + // Every /Metadata and /PieceInfo on every object. + for o in doc.objects.values_mut() { + let d = match o { + Object::Dictionary(d) => d, + Object::Stream(s) => &mut s.dict, + _ => continue, + }; + d.remove(b"Metadata"); + d.remove(b"PieceInfo"); + } +} + +/// Whether a page (its resources, XObjects and annotations, followed by reference) uses optional content. +fn uses_optional_content(doc: &Document, page: ObjectId) -> bool { + let mut stack = vec![Object::Reference(page)]; + let mut seen = HashSet::new(); + let mut budget = 20_000u32; + while let Some(o) = stack.pop() { + if budget == 0 { + return true; // too deep to tell: be conservative and keep the layers + } + budget -= 1; + let o = match o { + Object::Reference(id) => { + if !seen.insert(id) { + continue; + } + match doc.get_object(id) { + Ok(o) => o.clone(), + Err(_) => continue, + } + } + o => o, + }; + let dict = match &o { + Object::Dictionary(d) => d, + Object::Stream(s) => &s.dict, + Object::Array(a) => { + stack.extend(a.iter().cloned()); + continue; + } + _ => continue, + }; + if dict.has(b"OC") || dict.has_type(b"OCG") || dict.has_type(b"OCMD") { + return true; + } + for (k, v) in dict.iter() { + if k == b"Parent" || k == b"P" { + continue; + } + stack.push(v.clone()); + } + } + false +} diff --git a/crates/pdf/src/security.rs b/crates/pdf/src/security.rs new file mode 100644 index 0000000..ca76a01 --- /dev/null +++ b/crates/pdf/src/security.rs @@ -0,0 +1,51 @@ +//! Password on and off. pdfium cannot write encryption, so lopdf does both: AES-256 (PDF 2.0, revision 6) to +//! protect, and a decrypting load plus a plain save to unlock. +use crate::{PdfError, lopdf_load, lopdf_save}; +use lopdf::encryption::crypt_filters::{Aes256CryptFilter, CryptFilter}; +use lopdf::{EncryptionState, EncryptionVersion, Permissions}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// Whether opening the document needs a password. +pub fn is_encrypted(bytes: &[u8]) -> bool { + matches!(lopdf_load(bytes, None), Err(PdfError::NeedsPassword)) +} + +/// Protects a document with `user_password` (needed to open it). `owner_password` defaults to the same password. +/// `current_password` opens an already protected document first. The result uses AES-256 and allows everything to +/// whoever opens it (Pictor does not set permission restrictions: they are not a security boundary). +pub fn protect( + bytes: &[u8], + current_password: Option<&str>, + user_password: &str, + owner_password: Option<&str>, +) -> Result, PdfError> { + if user_password.is_empty() { + return Err(PdfError::Invalid("Choose a password.".into())); + } + let mut doc = lopdf_load(bytes, current_password)?; + let mut key = [0u8; 32]; + getrandom::fill(&mut key).map_err(|e| PdfError::Write(format!("no random numbers from Windows: {e}")))?; + let filter: Arc = Arc::new(Aes256CryptFilter); + let state = EncryptionState::try_from(EncryptionVersion::V5 { + encrypt_metadata: true, + crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), filter)]), + file_encryption_key: &key, + stream_filter: b"StdCF".to_vec(), + string_filter: b"StdCF".to_vec(), + owner_password: owner_password.filter(|p| !p.is_empty()).unwrap_or(user_password), + user_password, + permissions: Permissions::all(), + }) + .map_err(|e| PdfError::Write(e.to_string()))?; + doc.encrypt(&state).map_err(|e| PdfError::Write(e.to_string()))?; + key.fill(0); + lopdf_save(&mut doc) +} + +/// Removes the password from a document (the password must be right). +pub fn unlock(bytes: &[u8], password: &str) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, Some(password))?; + doc.trailer.remove(b"Encrypt"); + lopdf_save(&mut doc) +} diff --git a/crates/pdf/tests/common/mod.rs b/crates/pdf/tests/common/mod.rs new file mode 100644 index 0000000..4638108 --- /dev/null +++ b/crates/pdf/tests/common/mod.rs @@ -0,0 +1,267 @@ +//! Fixtures built in code (nothing in git) and helpers shared by the pdf tests. +#![allow(dead_code)] +use lopdf::{Document, Object, ObjectId, Stream, StringFormat, dictionary}; +use std::path::PathBuf; + +pub fn engine() -> &'static pictor_pdf::Engine { + let dir = std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin")); + pictor_pdf::Engine::load(Some(&dir)).expect("pdfium: run scripts/fetch-pdfium.ps1 first") +} + +/// Every string that sits under the redaction box (or in a hidden place of the document) in [`secret_pdf`]. +pub const SECRETS: &[&str] = &[ + "TOP-SECRET-ALPHA", + "HIDDEN-LAYER-SECRET", + "ANNOT-SECRET", + "FORM-SECRET", + "META-SECRET-TITLE", + "META-SECRET-AUTHOR", + "XMP-SECRET", + "OUTLINE-SECRET", + "STRUCT-SECRET", + "ATTACH-SECRET", + "IMAGE-SECRET", + "123.456 654.321", +]; + +/// The redaction box over page 1 in view space (points, top-left origin): it covers everything secret on page 1 +/// (y 590..760 in PDF space) and leaves "PUBLIC-LINE" (y 300) outside. +pub fn secret_box() -> pictor_pdf::ViewRect { + pictor_pdf::ViewRect { x: 50.0, y: 30.0, w: 500.0, h: 180.0 } +} + +pub const PAGE_TWO_CONTENT: &[u8] = b"BT /F2 14 Tf 72 720 Td (PAGE-TWO-KEEP) Tj ET\n"; + +fn s(text: &str) -> Object { + Object::String(text.as_bytes().to_vec(), StringFormat::Literal) +} + +pub struct Options { + pub compress: bool, + /// /Rotate on page 1. + pub rotate: i64, + /// Put Resources and Rotate on the Pages node (inherited) instead of page 1. + pub inherited: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { compress: false, rotate: 0, inherited: false } + } +} + +/// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in +/// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings. +/// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal. +pub fn secret_pdf(opts: &Options) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let f1 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); + let f2 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Times-Roman"}); + let mut pixels = Vec::new(); + while pixels.len() < 8 * 8 * 3 { + pixels.extend_from_slice(b"IMAGE-SECRET-PIXEL-DATA-"); + } + pixels.truncate(8 * 8 * 3); + let mut im = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 8, "Height" => 8, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}, + pixels, + ); + im.allows_compression = false; + let im1 = doc.add_object(im); + let oc1 = doc.add_object(dictionary! {"Type" => "OCG", "Name" => s("Hidden notes")}); + + let content1 = b"BT /F1 18 Tf 72 720 Td (TOP-SECRET-ALPHA) Tj ET\n\ +q 1 0 0 rg 123.456 654.321 m 300.5 650.25 l 300 600 l h f Q\n\ +q 100 0 0 50 72 610 cm /Im1 Do Q\n\ +/OC /oc1 BDC BT /F1 12 Tf 72 690 Td (HIDDEN-LAYER-SECRET) Tj ET EMC\n\ +BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n" + .to_vec(); + let c1 = doc.add_object(Stream::new(dictionary! {}, content1)); + let c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec())); + + let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", + "Encoding" => "WinAnsiEncoding"}); + let field_ap = doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()], + "Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, + b"/Tx BMC BT /Helv 10 Tf 0 g 2 6 Td (FORM-SECRET) Tj ET EMC".to_vec(), + )); + let page1_id = doc.new_object_id(); + let field = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Tx", "T" => s("Account"), "V" => s("FORM-SECRET"), + "DA" => s("/Helv 10 Tf 0 g"), "F" => 4, "P" => page1_id, + "Rect" => vec![300.into(), 700.into(), 500.into(), 720.into()], + "AP" => dictionary! {"N" => field_ap}, + }); + let note = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Text", "Rect" => vec![80.into(), 700.into(), 100.into(), 720.into()], + "Contents" => s("ANNOT-SECRET"), "F" => 4, + }); + + let resources1 = dictionary! { + "Font" => dictionary! {"F1" => f1}, + "XObject" => dictionary! {"Im1" => im1}, + "Properties" => dictionary! {"oc1" => oc1}, + }; + let mut page1 = dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c1, + "Annots" => vec![note.into(), field.into()], + "StructParents" => 0, + }; + if !opts.inherited { + page1.set("Resources", resources1.clone()); + if opts.rotate != 0 { + page1.set("Rotate", opts.rotate); + } + } + doc.objects.insert(page1_id, Object::Dictionary(page1)); + let page2_id = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c2, + "Resources" => dictionary! {"Font" => dictionary! {"F2" => f2}}, + }); + let mut pages = dictionary! { + "Type" => "Pages", "Kids" => vec![page1_id.into(), page2_id.into()], "Count" => 2, + "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()], + }; + if opts.inherited { + pages.set("Resources", resources1); + if opts.rotate != 0 { + pages.set("Rotate", opts.rotate); + } + // Page 2 has its own Resources and must not inherit the rotation. + if let Ok(Object::Dictionary(p2)) = doc.get_object_mut(page2_id) { + p2.set("Rotate", 0); + } + } + doc.objects.insert(pages_id, Object::Dictionary(pages)); + + let xmp = doc.add_object(Stream::new( + dictionary! {"Type" => "Metadata", "Subtype" => "XML"}, + b"\ +XMP-SECRET\ +" + .to_vec(), + )); + let outlines_id = doc.new_object_id(); + let item = doc.add_object(dictionary! { + "Title" => s("OUTLINE-SECRET"), "Parent" => outlines_id, + "Dest" => vec![page1_id.into(), "Fit".into()], + }); + doc.objects.insert( + outlines_id, + Object::Dictionary(dictionary! {"Type" => "Outlines", "First" => item, "Last" => item, "Count" => 1}), + ); + let struct_root_id = doc.new_object_id(); + let elem = doc.add_object(dictionary! { + "Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id, + "ActualText" => s("STRUCT-SECRET"), "K" => 0, + }); + doc.objects.insert( + struct_root_id, + Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}), + ); + let attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec())); + let filespec = doc.add_object(dictionary! { + "Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach}, + }); + let catalog = doc.add_object(dictionary! { + "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp, "Outlines" => outlines_id, + "PageMode" => "UseOutlines", + "StructTreeRoot" => struct_root_id, "MarkInfo" => dictionary! {"Marked" => true}, + "OCProperties" => dictionary! { + "OCGs" => vec![oc1.into()], + "D" => dictionary! {"OFF" => vec![oc1.into()], "Order" => vec![oc1.into()]}, + }, + "AcroForm" => dictionary! {"Fields" => vec![field.into()], "DA" => s("/Helv 10 Tf 0 g"), + "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, + "Names" => dictionary! {"EmbeddedFiles" => dictionary! {"Names" => vec![s("notes.txt"), filespec.into()]}}, + }); + let info = doc.add_object(dictionary! { + "Title" => s("META-SECRET-TITLE"), "Author" => s("META-SECRET-AUTHOR"), "Producer" => s("fixture"), + }); + doc.trailer.set("Root", catalog); + doc.trailer.set("Info", info); + if opts.compress { + doc.compress(); + } + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +/// A simple n-page document; page i says "Page i+1" (for page operations, merge and split). +pub fn numbered_pdf(n: usize, label: &str) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); + let mut kids = Vec::new(); + for i in 0..n { + let content = format!("BT /F1 24 Tf 72 700 Td ({label} page {}) Tj ET", i + 1).into_bytes(); + let c = doc.add_object(Stream::new(dictionary! {}, content)); + let p = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, + }); + kids.push(Object::Reference(p)); + } + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}), + ); + let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); + doc.trailer.set("Root", catalog); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +/// Every byte string an "object scan" can see: string objects, names, and stream contents both raw and decompressed. +pub fn scan_objects(bytes: &[u8]) -> Vec> { + let doc = Document::load_mem(bytes).expect("lopdf reloads the output"); + let mut found = Vec::new(); + fn walk(o: &Object, found: &mut Vec>) { + match o { + Object::String(v, _) | Object::Name(v) => found.push(v.clone()), + Object::Array(a) => a.iter().for_each(|x| walk(x, found)), + Object::Dictionary(d) => d.iter().for_each(|(k, v)| { + found.push(k.clone()); + walk(v, found) + }), + Object::Stream(st) => { + st.dict.iter().for_each(|(k, v)| { + found.push(k.clone()); + walk(v, found) + }); + found.push(st.content.clone()); + if let Ok(d) = st.decompressed_content() { + found.push(d); + } + } + _ => {} + } + } + for o in doc.objects.values() { + walk(o, &mut found); + } + walk(&Object::Dictionary(doc.trailer.clone()), &mut found); + found +} + +pub fn contains(hay: &[u8], needle: &str) -> bool { + hay.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// The page dictionaries of a document, in order. +pub fn page_ids(doc: &Document) -> Vec { + doc.get_pages().values().copied().collect() +} + +/// A page's content, decompressed and concatenated. +pub fn page_content(doc: &Document, page: ObjectId) -> Vec { + doc.get_page_content(page) +} diff --git a/crates/pdf/tests/redaction.rs b/crates/pdf/tests/redaction.rs new file mode 100644 index 0000000..2ef49df --- /dev/null +++ b/crates/pdf/tests/redaction.rs @@ -0,0 +1,153 @@ +//! Mandatory test 1 (blocker): true redaction. After redacting the box on page 1, neither pdfium's text +//! extraction, a lopdf object scan (strings, names, raw and decompressed streams) nor a raw byte grep finds any +//! redacted string, the document's metadata and hidden parts are gone, and page 2 is byte-equal in content. +mod common; +use common::*; +use lopdf::Document; +use pictor_pdf::{Redaction, ViewRect}; + +fn redact(input: &[u8], rects: Vec) -> pictor_pdf::Redacted { + pictor_pdf::redact(engine(), input, None, &[Redaction { page: 0, rects }], &Default::default()) + .expect("redaction succeeds") +} + +fn assert_no_secrets(output: &[u8]) { + // 1. pdfium text extraction, every page. + let text = pictor_pdf::extract_text(engine(), output, None).expect("pdfium opens the output"); + let all: String = text.concat(); + for secret in SECRETS { + assert!(!all.contains(secret), "pdfium text extraction still finds {secret:?}"); + } + assert!(all.contains("PAGE-TWO-KEEP"), "page 2 lost its text: {all:?}"); + // 2. lopdf object scan. + for blob in scan_objects(output) { + for secret in SECRETS { + assert!(!contains(&blob, secret), "lopdf object scan still finds {secret:?}"); + } + } + // 3. Raw byte grep of the whole file. + for secret in SECRETS { + assert!(!contains(output, secret), "a raw byte grep still finds {secret:?}"); + } +} + +fn assert_page_two_unchanged(input: &[u8], output: &[u8]) { + let a = Document::load_mem(input).unwrap(); + let b = Document::load_mem(output).unwrap(); + let (pa, pb) = (page_ids(&a)[1], page_ids(&b)[1]); + assert_eq!(page_content(&a, pa), page_content(&b, pb), "page 2's content changed"); + let font = |d: &Document, p| { + let fonts = d.get_page_fonts(p).unwrap(); + fonts.iter().map(|(k, v)| (k.clone(), format!("{:?}", v))).collect::>() + }; + assert_eq!(font(&a, pa), font(&b, pb), "page 2's fonts changed"); + // The raw stream bytes too (lopdf writes untouched streams as they were). + let raw = |d: &Document, p| -> Vec> { + d.get_page_contents(p).iter().map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone()).collect() + }; + assert_eq!(raw(&a, pa), raw(&b, pb), "page 2's raw content stream bytes changed"); +} + +fn assert_hidden_parts_gone(output: &[u8]) { + let doc = Document::load_mem(output).unwrap(); + assert!(doc.trailer.get(b"Info").is_err(), "/Info survived"); + let catalog = doc.catalog().unwrap(); + for key in ["Metadata", "OCProperties", "StructTreeRoot", "Outlines", "AcroForm"] { + assert!(catalog.get(key.as_bytes()).is_err(), "catalog /{key} survived"); + } + for o in doc.objects.values() { + let dict = match o { + lopdf::Object::Dictionary(d) => d, + lopdf::Object::Stream(s) => &s.dict, + _ => continue, + }; + assert!(dict.get(b"Metadata").is_err(), "a /Metadata entry survived"); + assert!(!dict.has_type(b"OCG"), "an optional content group survived"); + assert!(!dict.has_type(b"EmbeddedFile"), "an attachment survived"); + } +} + +fn check(opts: Options, page1_size: (f32, f32)) { + let input = secret_pdf(&opts); + // The fixture really contains every secret before redaction (else the test proves nothing). + let before: Vec> = scan_objects(&input); + for secret in SECRETS { + assert!(before.iter().any(|b| contains(b, secret)), "fixture lacks {secret:?}"); + } + let rect = match opts.rotate { + 0 => secret_box(), + // For a page shown rotated, the same content sits elsewhere in view space; redact the whole page then. + _ => ViewRect { x: 0.0, y: 0.0, w: page1_size.0, h: page1_size.1 }, + }; + let out = redact(&input, vec![rect]); + assert_no_secrets(&out.bytes); + assert_page_two_unchanged(&input, &out.bytes); + assert_hidden_parts_gone(&out.bytes); + let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap(); + assert_eq!(sizes.len(), 2); + assert!((sizes[0].0 - page1_size.0).abs() < 0.5 && (sizes[0].1 - page1_size.1).abs() < 0.5, "{sizes:?}"); +} + +#[test] +fn text_image_vector_hidden_layer_and_metadata_are_gone() { + check(Options::default(), (612.0, 792.0)); +} + +#[test] +fn compressed_streams_are_redacted_too() { + check(Options { compress: true, ..Default::default() }, (612.0, 792.0)); +} + +#[test] +fn a_rotated_page_keeps_its_displayed_size() { + check(Options { rotate: 90, ..Default::default() }, (792.0, 612.0)); +} + +#[test] +fn inherited_resources_and_rotation_are_handled() { + check(Options { inherited: true, rotate: 90, ..Default::default() }, (792.0, 612.0)); +} + +#[test] +fn the_box_is_black_and_the_rest_of_the_page_still_shows() { + let input = secret_pdf(&Options::default()); + let out = redact(&input, vec![secret_box()]); + let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 612).unwrap().to_rgb8(); + // Inside the box (view 300, 100): black. + let p = img.get_pixel(300, 100); + assert!(p.0.iter().all(|&c| c < 16), "box not black: {p:?}"); + // "PUBLIC-LINE" at PDF (72, 300) → view y ≈ 492: some dark pixels remain in that band. + let dark = (480..500).flat_map(|y| (72..160).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100).count(); + assert!(dark > 20, "the text outside the box disappeared ({dark} dark pixels)"); +} + +#[test] +fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() { + let input = secret_pdf(&Options::default()); + let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap(); + assert!( + pictor_pdf::redact(engine(), &locked, None, &[Redaction { page: 0, rects: vec![secret_box()] }], &Default::default()) + .is_err(), + "redacted without the password" + ); + let out = pictor_pdf::redact( + engine(), + &locked, + Some("open-sesame"), + &[Redaction { page: 0, rects: vec![secret_box()] }], + &Default::default(), + ) + .unwrap(); + assert_no_secrets(&out.bytes); +} + +#[test] +fn no_redaction_box_is_refused() { + let input = secret_pdf(&Options::default()); + assert!(pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()).is_err()); + assert!( + pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 9, rects: vec![secret_box()] }], &Default::default()) + .is_err(), + "a page that does not exist was accepted" + ); +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 2b24528..4796f4e 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,86 +1,88 @@ -# Dependencies and their licences - -Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. -The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the -OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. - -## The allowed set, as checked by `scripts/deps.mjs` - -| Licence (SPDX) | Why it is allowed | -| :-- | :-- | -| MIT, MIT-0 | named in the brief | -| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | -| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | -| Zlib | named in the brief | -| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | -| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | -| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | -| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | - -An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the -script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). - -## Direct dependencies - -| Crate | Version | Licence | Used by | For | -| :-- | :-- | :-- | :-- | :-- | -| thiserror | 2 | MIT OR Apache-2.0 | all | error types | -| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | -| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | -| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | -| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | -| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | -| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | -| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | -| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | -| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | -| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | -| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | -| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | -| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | - -## Binaries (fetched, never in git) - -| Binary | Licence | Fetched by | -| :-- | :-- | :-- | -| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | - -### pdfium - -Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 -`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches -pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside -the dll (the app's installer copies them). Read from those files on 2026-11-16: - -| Component inside pdfium.dll | Licence | In the allowed set? | -| :-- | :-- | :-- | -| the binary build (bblanchon/pdfium-binaries) | MIT | yes | -| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | -| abseil, highway | Apache-2.0 | yes | -| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | -| fast_float, simdutf | MIT | yes | -| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | -| OpenJPEG | BSD-2-Clause | yes | -| zlib | Zlib | yes | -| HarfBuzz | "Old MIT" | yes (MIT family) | -| ICU | Unicode-3.0 | **interpretation** (see above) | -| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | -| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | -| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | - -None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked -"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF -support depends on pdfium, which the brief chose). - -## OS codecs (not bundled) - -| Codec | Provided by | Used for | -| :-- | :-- | :-- | -| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | - -## Every crate in Cargo.lock - -Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. - - - +# Dependencies and their licences + +Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. +The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the +OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. + +## The allowed set, as checked by `scripts/deps.mjs` + +| Licence (SPDX) | Why it is allowed | +| :-- | :-- | +| MIT, MIT-0 | named in the brief | +| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | +| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | +| Zlib | named in the brief | +| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | +| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | +| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | +| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | + +An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the +script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). + +## Direct dependencies + +| Crate | Version | Licence | Used by | For | +| :-- | :-- | :-- | :-- | :-- | +| thiserror | 2 | MIT OR Apache-2.0 | all | error types | +| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | +| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | +| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | +| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | +| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | +| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | +| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | +| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | +| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | +| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | +| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | +| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | +| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | + +## Binaries (fetched, never in git) + +| Binary | Licence | Fetched by | +| :-- | :-- | :-- | +| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | + +### pdfium + +Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 +`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches +pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside +the dll (the app's installer copies them). Read from those files on 2026-11-16: + +| Component inside pdfium.dll | Licence | In the allowed set? | +| :-- | :-- | :-- | +| the binary build (bblanchon/pdfium-binaries) | MIT | yes | +| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | +| abseil, highway | Apache-2.0 | yes | +| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | +| fast_float, simdutf | MIT | yes | +| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | +| OpenJPEG | BSD-2-Clause | yes | +| zlib | Zlib | yes | +| HarfBuzz | "Old MIT" | yes (MIT family) | +| ICU | Unicode-3.0 | **interpretation** (see above) | +| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | +| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | +| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | + +None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked +"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF +support depends on pdfium, which the brief chose). + +## OS codecs (not bundled) + +| Codec | Provided by | Used for | +| :-- | :-- | :-- | +| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | + +## Every crate in Cargo.lock + +Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. + + + From ede068f7c9f837a50d3ea8efad62d48c4bcead94 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:27:47 +0100 Subject: [PATCH 05/13] [meta] Metadata: read and strip EXIF/GPS/XMP/IPTC (JPEG, PNG, WebP, GIF, TIFF) and PDF info/XMP --- crates/meta/Cargo.toml | 18 ++ crates/meta/src/exif_items.rs | 225 ++++++++++++++++++++++ crates/meta/src/gif.rs | 200 ++++++++++++++++++++ crates/meta/src/iptc.rs | 101 ++++++++++ crates/meta/src/jpeg.rs | 249 +++++++++++++++++++++++++ crates/meta/src/lib.rs | 321 ++++++++++++++++++++++++++++++++ crates/meta/src/pdf.rs | 158 ++++++++++++++++ crates/meta/src/png.rs | 171 +++++++++++++++++ crates/meta/src/text.rs | 187 +++++++++++++++++++ crates/meta/src/tiff.rs | 75 ++++++++ crates/meta/src/webp.rs | 105 +++++++++++ crates/meta/src/xmp.rs | 138 ++++++++++++++ crates/meta/tests/common/mod.rs | 283 ++++++++++++++++++++++++++++ crates/meta/tests/hostile.rs | 196 +++++++++++++++++++ crates/meta/tests/images.rs | 219 ++++++++++++++++++++++ crates/meta/tests/pdf.rs | 180 ++++++++++++++++++ docs/DEPENDENCIES.md | 176 ++++++++--------- 17 files changed, 2914 insertions(+), 88 deletions(-) create mode 100644 crates/meta/Cargo.toml create mode 100644 crates/meta/src/exif_items.rs create mode 100644 crates/meta/src/gif.rs create mode 100644 crates/meta/src/iptc.rs create mode 100644 crates/meta/src/jpeg.rs create mode 100644 crates/meta/src/lib.rs create mode 100644 crates/meta/src/pdf.rs create mode 100644 crates/meta/src/png.rs create mode 100644 crates/meta/src/text.rs create mode 100644 crates/meta/src/tiff.rs create mode 100644 crates/meta/src/webp.rs create mode 100644 crates/meta/src/xmp.rs create mode 100644 crates/meta/tests/common/mod.rs create mode 100644 crates/meta/tests/hostile.rs create mode 100644 crates/meta/tests/images.rs create mode 100644 crates/meta/tests/pdf.rs diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml new file mode 100644 index 0000000..c04c7b2 --- /dev/null +++ b/crates/meta/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "pictor-meta" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true +kamadak-exif.workspace = true +lopdf.workspace = true + +[dev-dependencies] +# Used only to build WebP and PNG fixtures in tests; the library walks containers itself. +img-parts.workspace = true diff --git a/crates/meta/src/exif_items.rs b/crates/meta/src/exif_items.rs new file mode 100644 index 0000000..edc7065 --- /dev/null +++ b/crates/meta/src/exif_items.rs @@ -0,0 +1,225 @@ +//! EXIF (a TIFF-structured block) to report items, through kamadak-exif. + +use exif::{Context, Exif, Field, In, Reader, Tag, Value}; + +use crate::{Ctx, Group, guarded}; + +/// Lists the fields of a raw EXIF block (starting at the TIFF header) and returns the Orientation (1..=8) if one +/// could be read. Damage becomes a warning, never an error. +pub(crate) fn read_block(raw: &[u8], ctx: &mut Ctx) -> Option { + ctx.push(Group::Exif, "EXIF block", crate::bytes_label(raw.len())); + let parsed = guarded(|| { + let mut reader = Reader::new(); + reader.continue_on_error(true); + match reader.read_raw(raw.to_vec()) { + Ok(exif) => Ok((exif, false)), + Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)), + } + }); + let exif = match parsed { + Some(Ok((exif, partial))) => { + if partial { + ctx.warn("Part of the EXIF data is damaged; what could be read is listed. All of it is removed."); + } + exif + } + Some(Err(_)) | None => { + ctx.warn("The EXIF data is damaged and could not be read. It is removed all the same."); + return None; + } + }; + list(&exif, ctx) +} + +/// Lists an already parsed EXIF (also used for TIFF files, whose own tags are EXIF-structured). +pub(crate) fn list(exif: &Exif, ctx: &mut Ctx) -> Option { + let mut orientation = None; + let mut lat = None; + let mut lon = None; + let mut make = None; + let mut model = None; + let mut thumbnail = false; + let mut rest: Vec<(Group, String, String)> = Vec::new(); + + for field in exif.fields() { + if field.ifd_num != In::PRIMARY { + thumbnail = true; + continue; + } + let tag = field.tag; + if is_structural(tag) { + continue; + } + match tag { + Tag::Orientation => { + orientation = + field.value.get_uint(0).and_then(|v| u16::try_from(v).ok()).filter(|v| (1..=8).contains(v)) + } + Tag::GPSLatitude => lat = dms(&field.value), + Tag::GPSLongitude => lon = dms(&field.value), + Tag::Make => make = ascii(&field.value), + Tag::Model => model = ascii(&field.value), + _ => {} + } + rest.push((group_of(tag), tag.to_string(), value_text(field, exif))); + } + + let negative = |ref_tag: Tag, neg: u8| { + exif.get_field(ref_tag, In::PRIMARY) + .and_then(|f| ascii(&f.value)) + .is_some_and(|s| s.as_bytes().first().is_some_and(|c| c.eq_ignore_ascii_case(&neg))) + }; + if let (Some(la), Some(lo)) = (lat, lon) { + let (ns, ew) = ( + if negative(Tag::GPSLatitudeRef, b'S') { "S" } else { "N" }, + if negative(Tag::GPSLongitudeRef, b'W') { "W" } else { "E" }, + ); + ctx.push(Group::Gps, "Location", format!("{} {ns}, {} {ew}", coord(la), coord(lo))); + } + let camera = match (make.as_deref(), model.as_deref()) { + (Some(ma), Some(mo)) if mo.to_lowercase().starts_with(&ma.to_lowercase()) => Some(mo.to_string()), + (Some(ma), Some(mo)) => Some(format!("{ma} {mo}")), + (Some(x), None) | (None, Some(x)) => Some(x.to_string()), + (None, None) => None, + }; + if let Some(c) = camera.filter(|c| !c.is_empty()) { + ctx.push(Group::Camera, "Camera", c); + } + for (g, name, value) in rest { + ctx.push(g, name, value); + } + if thumbnail { + ctx.push(Group::Exif, "Embedded thumbnail", "yes (a small copy of the picture)"); + } + orientation +} + +fn group_of(tag: Tag) -> Group { + match tag.context() { + Context::Gps => return Group::Gps, + Context::Tiff | Context::Exif => {} + _ => return Group::Exif, + } + match tag { + Tag::Make | Tag::Model | Tag::BodySerialNumber | Tag::LensSpecification | Tag::LensMake | Tag::LensModel => { + Group::Camera + } + Tag::LensSerialNumber => Group::Camera, + Tag::Artist | Tag::Copyright | Tag::CameraOwnerName => Group::Author, + Tag::Software => Group::Software, + Tag::DateTime + | Tag::DateTimeOriginal + | Tag::DateTimeDigitized + | Tag::OffsetTime + | Tag::OffsetTimeOriginal + | Tag::OffsetTimeDigitized + | Tag::SubSecTime + | Tag::SubSecTimeOriginal + | Tag::SubSecTimeDigitized => Group::Dates, + Tag::UserComment | Tag::ImageDescription => Group::Comment, + _ => match (tag.context(), tag.number()) { + // HostComputer, ProcessingSoftware + (Context::Tiff, 0x013C | 0x000B) => Group::Software, + // XPTitle, XPComment, XPAuthor, XPKeywords, XPSubject (Windows) + (Context::Tiff, 0x9C9B..=0x9C9F) => Group::Comment, + _ => Group::Exif, + }, + } +} + +/// Tags that describe the pixel layout, not the picture's story; not listed. +fn is_structural(tag: Tag) -> bool { + if tag.context() != Context::Tiff { + return false; + } + matches!( + tag.number(), + 0x00FE..=0x0103 + | 0x0106 + | 0x0107 + | 0x010A + | 0x0111 + | 0x0115..=0x011C + | 0x0128 + | 0x013D..=0x0140 + | 0x0142..=0x0145 + | 0x014A + | 0x0152 + | 0x0153 + | 0x0201 + | 0x0202 + | 0x0211..=0x0214 + | 0x8769 + | 0x8773 + | 0x8825 + | 0xA005 + ) +} + +fn value_text(field: &Field, exif: &Exif) -> String { + match &field.value { + Value::Ascii(_) => ascii(&field.value).unwrap_or_default(), + Value::Undefined(v, _) if field.tag == Tag::MakerNote => { + format!("{} (the camera maker's private data)", crate::bytes_label(v.len())) + } + Value::Byte(v) | Value::Undefined(v, _) if v.len() > 64 && !is_text_like(field.tag) => { + crate::bytes_label(v.len()) + } + v if value_len(v) > 64 => format!("{} values", value_len(v)), + _ => guarded(|| field.display_value().with_unit(exif).to_string()).unwrap_or_default(), + } +} + +fn is_text_like(tag: Tag) -> bool { + tag == Tag::UserComment || (tag.context() == Context::Tiff && (0x9C9B..=0x9C9F).contains(&tag.number())) +} + +fn value_len(v: &Value) -> usize { + match v { + Value::Byte(x) | Value::Undefined(x, _) => x.len(), + Value::Ascii(x) => x.len(), + Value::Short(x) => x.len(), + Value::Long(x) => x.len(), + Value::Rational(x) => x.len(), + Value::SByte(x) => x.len(), + Value::SShort(x) => x.len(), + Value::SLong(x) => x.len(), + Value::SRational(x) => x.len(), + Value::Float(x) => x.len(), + Value::Double(x) => x.len(), + Value::Unknown(..) => 0, + } +} + +fn ascii(v: &Value) -> Option { + match v { + Value::Ascii(parts) => { + let s: Vec = + parts.iter().map(|p| crate::text::lossy(p).trim().to_string()).filter(|p| !p.is_empty()).collect(); + Some(s.join("; ")) + } + _ => None, + } +} + +/// Degrees, minutes, seconds as rationals to decimal degrees. +fn dms(v: &Value) -> Option { + let Value::Rational(parts) = v else { return None }; + if parts.is_empty() { + return None; + } + let mut deg = 0.0; + for (r, scale) in parts.iter().zip([1.0, 60.0, 3600.0]) { + if r.denom == 0 { + return None; + } + deg += f64::from(r.num) / f64::from(r.denom) / scale; + } + (deg.is_finite() && deg <= 180.0).then_some(deg) +} + +fn coord(v: f64) -> String { + let s = format!("{v:.5}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + s.to_string() +} diff --git a/crates/meta/src/gif.rs b/crates/meta/src/gif.rs new file mode 100644 index 0000000..c33e7cd --- /dev/null +++ b/crates/meta/src/gif.rs @@ -0,0 +1,200 @@ +//! GIF at the block level: every frame (and the animation) is copied byte for byte; comment extensions and +//! application extensions other than looping and ICC colour are dropped. + +use crate::{Ctx, Group, MetaError, text, xmp}; + +const MAX_BLOCKS: usize = 1_000_000; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum BlockKind { + /// Header, screen descriptor, global colour table. + Head, + Image, + Comment, + /// An application extension and its 11-byte identifier. + App([u8; 11]), + /// Graphic control, plain text and unknown extensions. + OtherExtension, +} + +struct Block { + kind: BlockKind, + span: (usize, usize), + /// For extensions: where the data sub-blocks start. + body: usize, +} + +struct Parsed { + blocks: Vec, + trailer_end: Option, + error: Option, +} + +/// Skips data sub-blocks from `pos`; returns the position after the zero-length terminator. +fn skip_sub_blocks(b: &[u8], mut pos: usize) -> Option { + loop { + let n = usize::from(*b.get(pos)?); + pos += 1; + if n == 0 { + return Some(pos); + } + pos += n; + if pos > b.len() { + return None; + } + } +} + +fn parse(b: &[u8]) -> Parsed { + let mut p = Parsed { blocks: Vec::new(), trailer_end: None, error: None }; + let Some(&packed) = b.get(10) else { + p.error = Some(MetaError::truncated()); + return p; + }; + let mut pos = 13; + if packed & 0x80 != 0 { + pos += 3 << ((packed & 7) + 1); + } + if pos > b.len() { + p.error = Some(MetaError::truncated()); + return p; + } + p.blocks.push(Block { kind: BlockKind::Head, span: (0, pos), body: pos }); + loop { + if p.blocks.len() >= MAX_BLOCKS { + p.error = Some(MetaError::Damaged("it has too many blocks".into())); + break; + } + let start = pos; + let Some(&intro) = b.get(pos) else { + p.error = Some(MetaError::truncated()); + break; + }; + let parsed = match intro { + 0x3B => { + p.trailer_end = Some(pos + 1); + break; + } + 0x21 => { + let label = b.get(pos + 1).copied(); + let body = pos + 2; + let kind = match label { + Some(0xFE) => Some(BlockKind::Comment), + Some(0xFF) => match (b.get(body), b.get(body + 1..body + 12)) { + (Some(11), Some(id)) => { + let mut a = [0u8; 11]; + a.copy_from_slice(id); + Some(BlockKind::App(a)) + } + _ => Some(BlockKind::App([0; 11])), + }, + Some(_) => Some(BlockKind::OtherExtension), + None => None, + }; + kind.and_then(|k| skip_sub_blocks(b, body).map(|end| (k, end, body))) + } + 0x2C => { + let after_descriptor = pos + 10; + b.get(pos + 9).and_then(|&packed| { + let mut q = after_descriptor; + if packed & 0x80 != 0 { + q += 3 << ((packed & 7) + 1); + } + // LZW minimum code size, then the image data sub-blocks. + q += 1; + if q > b.len() { + return None; + } + skip_sub_blocks(b, q).map(|end| (BlockKind::Image, end, q)) + }) + } + _ => { + p.error = Some(MetaError::Damaged("a block has an unknown type".into())); + break; + } + }; + let Some((kind, end, body)) = parsed else { + p.error = Some(MetaError::truncated()); + break; + }; + p.blocks.push(Block { kind, span: (start, end), body }); + pos = end; + } + p +} + +/// Kept application extensions: animation looping and the ICC colour profile. +fn app_kept(id: &[u8; 11]) -> bool { + id == b"NETSCAPE2.0" || id == b"ANIMEXTS1.0" || id == b"ICCRGBG1012" +} + +/// The bytes of an extension's sub-blocks, joined (without the length bytes). +fn joined(b: &[u8], from: usize, to: usize) -> Vec { + let mut out = Vec::new(); + let mut pos = from; + while let Some(&n) = b.get(pos) { + let n = usize::from(n); + if n == 0 || pos + 1 + n > to { + break; + } + out.extend_from_slice(&b[pos + 1..pos + 1 + n]); + pos += 1 + n; + } + out +} + +pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> { + let parsed = parse(b); + let mut frames = 0usize; + for blk in &parsed.blocks { + match blk.kind { + BlockKind::Image => frames += 1, + BlockKind::Comment => ctx.push(Group::Comment, "Comment", text::lossy(&joined(b, blk.body, blk.span.1))), + BlockKind::App(id) if &id == b"XMP DataXMP" => { + // XMP is stored raw (its bytes double as sub-block lengths), followed by a 258-byte "magic trailer". + let raw = &b[(blk.body + 12).min(blk.span.1)..blk.span.1]; + let packet = &raw[..raw.len().saturating_sub(258)]; + xmp::read_packet(packet, Group::Xmp, "XMP packet", ctx); + } + BlockKind::App(id) if !app_kept(&id) => { + let name = text::latin1(&id[..8]).trim().to_string(); + let label = + if name.is_empty() { "Application data".into() } else { format!("Application data ({name})") }; + ctx.push(Group::Other, label, crate::bytes_label(blk.span.1 - blk.span.0)); + } + _ => {} + } + } + if let Some(end) = parsed.trailer_end + && b.len() > end + { + ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end)); + } + if let Some(e) = parsed.error { + if frames == 0 && parsed.blocks.len() <= 1 { + return Err(e); + } + ctx.warn(format!("{e} Only part of it could be read.")); + } + Ok(()) +} + +pub(crate) fn strip(b: &[u8]) -> Result, MetaError> { + let parsed = parse(b); + if let Some(e) = parsed.error { + return Err(e); + } + let mut out = Vec::with_capacity(b.len()); + for blk in &parsed.blocks { + let keep = match blk.kind { + BlockKind::Head | BlockKind::Image | BlockKind::OtherExtension => true, + BlockKind::Comment => false, + BlockKind::App(id) => app_kept(&id), + }; + if keep { + out.extend_from_slice(&b[blk.span.0..blk.span.1]); + } + } + out.push(0x3B); + Ok(out) +} diff --git a/crates/meta/src/iptc.rs b/crates/meta/src/iptc.rs new file mode 100644 index 0000000..912abd3 --- /dev/null +++ b/crates/meta/src/iptc.rs @@ -0,0 +1,101 @@ +//! Photoshop image resource blocks ("Photoshop 3.0", 8BIM) and the IPTC-IIM records inside them. + +use crate::{Ctx, Group, text}; + +pub(crate) const PHOTOSHOP_SIGNATURE: &[u8] = b"Photoshop 3.0\0"; + +/// Reads an APP13 payload (starting with "Photoshop 3.0\0"). +pub(crate) fn read_photoshop(payload: &[u8], ctx: &mut Ctx) { + ctx.push(Group::Iptc, "Photoshop block", crate::bytes_label(payload.len())); + let Some(mut b) = payload.strip_prefix(PHOTOSHOP_SIGNATURE) else { + ctx.warn("A Photoshop block has an unknown layout; it is removed all the same."); + return; + }; + let mut others = 0usize; + while b.len() >= 4 { + if &b[..4] != b"8BIM" { + ctx.warn("Part of the Photoshop block is damaged; it is removed all the same."); + break; + } + let Some(id) = text::be16(b, 4) else { break }; + let Some(&name_len) = b.get(6) else { break }; + // Pascal string, the whole (length byte + name) padded to an even size. + let name_total = (1 + usize::from(name_len) + 1) & !1; + let size_at = 6 + name_total; + let Some(size) = text::be32(b, size_at) else { break }; + let data_at = size_at + 4; + let Some(data) = usize::try_from(size).ok().and_then(|s| b.get(data_at..data_at.checked_add(s)?)) else { + ctx.warn("A Photoshop block ends too early; it is removed all the same."); + break; + }; + match id { + 0x0404 => read_iim(data, ctx), + 0x0409 | 0x040C => ctx.push(Group::Other, "Photoshop thumbnail", crate::bytes_label(data.len())), + 0x0422 | 0x0423 => { + crate::exif_items::read_block(data, ctx); + } + 0x0424 => crate::xmp::read_packet(data, Group::Xmp, "XMP packet (in Photoshop block)", ctx), + _ => others += 1, + } + let next = data_at + data.len() + (data.len() & 1); + b = b.get(next..).unwrap_or(&[]); + } + if others > 0 { + ctx.push(Group::Other, "Photoshop resources", format!("{others}")); + } +} + +/// IPTC-IIM datasets: 0x1C, record, dataset, length (u16, or an extended length), data. +pub(crate) fn read_iim(mut b: &[u8], ctx: &mut Ctx) { + while let [0x1C, record, dataset, ..] = *b { + let Some(len) = text::be16(b, 3) else { break }; + let (len, head) = if len & 0x8000 != 0 { + // Extended dataset: the low 15 bits give how many bytes the real length takes. + let n = usize::from(len & 0x7FFF); + if n == 0 || n > 4 { + break; + } + let Some(bytes) = b.get(5..5 + n) else { break }; + (bytes.iter().fold(0usize, |acc, &x| (acc << 8) | usize::from(x)), 5 + n) + } else { + (usize::from(len), 5) + }; + let Some(data) = b.get(head..head.saturating_add(len)) else { + ctx.warn("The IPTC data ends too early; it is removed all the same."); + break; + }; + if record == 2 && dataset != 0 { + let name = dataset_name(dataset).map_or_else(|| format!("IPTC 2:{dataset}"), str::to_string); + ctx.push(Group::Iptc, name, text::lossy(data)); + } + b = &b[head + len..]; + } +} + +fn dataset_name(d: u8) -> Option<&'static str> { + Some(match d { + 5 => "Object name", + 25 => "Keyword", + 40 => "Special instructions", + 55 => "Date created", + 60 => "Time created", + 62 => "Digital creation date", + 65 => "Originating program", + 80 => "By-line (author)", + 85 => "By-line title", + 90 => "City", + 92 => "Sub-location", + 95 => "Province or state", + 100 => "Country code", + 101 => "Country", + 103 => "Transmission reference", + 105 => "Headline", + 110 => "Credit", + 115 => "Source", + 116 => "Copyright notice", + 118 => "Contact", + 120 => "Caption", + 122 => "Caption writer", + _ => return None, + }) +} diff --git a/crates/meta/src/jpeg.rs b/crates/meta/src/jpeg.rs new file mode 100644 index 0000000..d03ddf2 --- /dev/null +++ b/crates/meta/src/jpeg.rs @@ -0,0 +1,249 @@ +//! JPEG at the segment level: the image data (tables, frame header, scans) is copied byte for byte. + +use crate::{Ctx, Group, MetaError, exif_items, iptc, text, xmp}; + +const EXIF_SIG: &[u8] = b"Exif\0"; +const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; +const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0"; +const ICC_SIG: &[u8] = b"ICC_PROFILE\0"; +const JFIF_SIG: &[u8] = b"JFIF\0"; +const ADOBE_SIG: &[u8] = b"Adobe"; +/// A file with more segments than this is refused (each costs a few bytes of memory). +const MAX_SEGMENTS: usize = 100_000; + +struct Segment { + marker: u8, + /// The whole segment in the file, from its 0xFF to the end of its payload (and, for SOS, its scan data). + span: (usize, usize), + /// The payload after the two length bytes (empty for markers without one). + payload: (usize, usize), +} + +#[derive(Default)] +struct Parsed { + segments: Vec, + /// The position just after the end-of-image marker, if there is one. + eoi_end: Option, + /// A segment header runs past the end of the file. + truncated: bool, + /// Something other than a marker where a marker must be, or too many segments. + damaged: Option<&'static str>, +} + +fn parse(b: &[u8]) -> Parsed { + let mut p = Parsed::default(); + let len = b.len(); + let mut pos = 2; + loop { + if p.segments.len() >= MAX_SEGMENTS { + p.damaged = Some("it has too many segments"); + break; + } + if pos >= len { + p.truncated = true; + break; + } + if b[pos] != 0xFF { + p.damaged = Some("a segment does not start where it should"); + break; + } + let start = pos; + while pos < len && b[pos] == 0xFF { + pos += 1; + } + let Some(&marker) = b.get(pos) else { + p.truncated = true; + break; + }; + pos += 1; + match marker { + 0xD9 => { + p.eoi_end = Some(pos); + break; + } + 0x01 | 0xD0..=0xD7 => p.segments.push(Segment { marker, span: (start, pos), payload: (pos, pos) }), + 0x00 | 0xD8 => { + p.damaged = Some("a segment marker is invalid"); + break; + } + _ => { + let Some(seg_len) = text::be16(b, pos) else { + p.truncated = true; + break; + }; + let seg_len = usize::from(seg_len); + if seg_len < 2 { + p.damaged = Some("a segment length is invalid"); + break; + } + let end = pos + seg_len; + if end > len { + p.truncated = true; + break; + } + let payload = (pos + 2, end); + pos = end; + if marker == 0xDA { + pos = scan_end(b, pos); + } + p.segments.push(Segment { marker, span: (start, pos), payload }); + if pos >= len { + // The scan data runs to the end: a file cut off inside the image data. Kept as it is. + break; + } + } + } + } + p +} + +/// The end of entropy-coded data: the next 0xFF that starts a marker other than a restart marker. +fn scan_end(b: &[u8], mut i: usize) -> usize { + while i + 1 < b.len() { + if b[i] == 0xFF { + match b[i + 1] { + 0x00 | 0xD0..=0xD7 => { + i += 2; + continue; + } + 0xFF => { + i += 1; + continue; + } + _ => return i, + } + } + i += 1; + } + b.len() +} + +fn payload<'a>(b: &'a [u8], s: &Segment) -> &'a [u8] { + b.get(s.payload.0..s.payload.1).unwrap_or(&[]) +} + +/// The raw EXIF (TIFF header onwards) of an APP1 Exif payload. +fn exif_raw(p: &[u8]) -> Option<&[u8]> { + if p.starts_with(EXIF_SIG) { p.get(6..) } else { None } +} + +pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> { + let parsed = parse(b); + for s in &parsed.segments { + let p = payload(b, s); + match s.marker { + 0xE0 if p.starts_with(JFIF_SIG) => { + if p.get(12).copied().unwrap_or(0) != 0 && p.get(13).copied().unwrap_or(0) != 0 { + ctx.push(Group::Other, "JFIF thumbnail", crate::bytes_label(p.len().saturating_sub(14))); + } + } + 0xE1 if p.starts_with(EXIF_SIG) => { + exif_items::read_block(exif_raw(p).unwrap_or(&[]), ctx); + } + 0xE1 if p.starts_with(XMP_SIG) => xmp::read_packet(&p[XMP_SIG.len()..], Group::Xmp, "XMP packet", ctx), + 0xE1 if p.starts_with(XMP_EXT_SIG) => { + ctx.push(Group::Xmp, "Extended XMP part", crate::bytes_label(p.len())) + } + 0xE2 if p.starts_with(ICC_SIG) => {} + 0xE2 if p.starts_with(b"MPF\0") => { + ctx.push(Group::Other, "Multi-picture index (MPF)", crate::bytes_label(p.len())) + } + 0xED if p.starts_with(iptc::PHOTOSHOP_SIGNATURE) => iptc::read_photoshop(p, ctx), + 0xEE if p.starts_with(ADOBE_SIG) => {} + 0xE0..=0xEF => { + let n = s.marker - 0xE0; + let id = block_id(p); + let name = if id.is_empty() { format!("APP{n} block") } else { format!("APP{n} block ({id})") }; + ctx.push(Group::Other, name, crate::bytes_label(p.len())); + } + 0xFE => ctx.push(Group::Comment, "Comment", text::lossy(p)), + _ => {} + } + } + if let Some(end) = parsed.eoi_end + && b.len() > end + { + ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end)); + } + if parsed.truncated { + ctx.warn("The file ends too early (truncated); only part of it could be read."); + } + if let Some(why) = parsed.damaged { + ctx.warn(format!("The file is damaged ({why}); only part of it could be read.")); + } + Ok(()) +} + +/// The printable ASCII name at the start of an APPn payload, e.g. "Ducky". +fn block_id(p: &[u8]) -> String { + p.iter().take(24).take_while(|c| c.is_ascii_graphic() || **c == b' ').map(|&c| c as char).collect() +} + +pub(crate) fn strip(b: &[u8]) -> Result, MetaError> { + let parsed = parse(b); + if parsed.truncated { + return Err(MetaError::truncated()); + } + if let Some(why) = parsed.damaged { + return Err(MetaError::Damaged(why.into())); + } + // The orientation of the first EXIF block, if it can be read; a damaged block gives none. + let orientation = parsed + .segments + .iter() + .filter(|s| s.marker == 0xE1) + .find_map(|s| exif_raw(payload(b, s))) + .and_then(|raw| exif_items::read_block(raw, &mut Ctx::default())) + .filter(|&o| o != 1); + + let mut out = Vec::with_capacity(b.len()); + out.extend_from_slice(&[0xFF, 0xD8]); + let mut orientation_pending = orientation; + for s in &parsed.segments { + let p = payload(b, s); + let is_jfif = s.marker == 0xE0 && p.starts_with(JFIF_SIG); + let keep = match s.marker { + 0xE2 => p.starts_with(ICC_SIG), + 0xEE => p.starts_with(ADOBE_SIG), + 0xE0 => is_jfif, + 0xE1 | 0xE3..=0xED | 0xEF | 0xFE => false, + _ => true, + }; + if !keep { + continue; + } + // The orientation block goes after JFIF (which must come first) and before everything else kept. + if !is_jfif && let Some(o) = orientation_pending.take() { + out.extend_from_slice(&orientation_segment(o)); + } + if is_jfif && p.len() > 14 { + // Rewrite without the thumbnail: version, units and density stay. + out.extend_from_slice(&[0xFF, 0xE0, 0x00, 16]); + out.extend_from_slice(&p[..12]); + out.extend_from_slice(&[0, 0]); + } else { + out.extend_from_slice(&b[s.span.0..s.span.1]); + } + } + if let Some(o) = orientation_pending { + out.extend_from_slice(&orientation_segment(o)); + } + if parsed.eoi_end.is_some() { + out.extend_from_slice(&[0xFF, 0xD9]); + } + Ok(out) +} + +/// A minimal APP1 Exif segment holding only the Orientation tag (big-endian TIFF, one IFD, one entry). +fn orientation_segment(o: u16) -> Vec { + let mut s = Vec::with_capacity(36); + s.extend_from_slice(&[0xFF, 0xE1, 0x00, 34]); + s.extend_from_slice(b"Exif\0\0"); + s.extend_from_slice(b"MM\0\x2A\0\0\0\x08"); + s.extend_from_slice(&[0x00, 0x01]); + s.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01]); + s.extend_from_slice(&o.to_be_bytes()); + s.extend_from_slice(&[0, 0]); + s.extend_from_slice(&[0, 0, 0, 0]); + s +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs new file mode 100644 index 0000000..1dbbd78 --- /dev/null +++ b/crates/meta/src/lib.rs @@ -0,0 +1,321 @@ +//! pictor-meta: read and strip metadata (EXIF, GPS, XMP, IPTC, comments) from photos, and document info and XMP +//! from PDFs. +//! +//! This is the Toolbox's "Metadata" face: [`read`] shows what is in a file, [`strip`] returns a cleaned copy. +//! Bytes go in and bytes come out; the original is never touched. +//! +//! Every input is treated as hostile: the parsers here never index without a bounds check, never allocate from a +//! size read out of the file without a cap, and third-party parsers are run behind a panic guard. +//! +//! What is kept, per format: +//! - JPEG: container-level, the image data is copied byte for byte. Kept: JFIF APP0 (its thumbnail removed), +//! ICC_PROFILE APP2, Adobe APP14, every non-APP segment. Everything after the end-of-image marker is dropped +//! (MPF secondary images, vendor trailers). An EXIF Orientation other than 1 is written back as a minimal EXIF. +//! - PNG: container-level. Dropped: eXIf, tEXt, zTXt, iTXt, tIME and anything after IEND. +//! - WebP: container-level. Dropped: EXIF and XMP chunks; the VP8X flags are cleared to match. +//! - GIF: container-level (every frame and the animation survive). Dropped: comment extensions, XMP and other +//! application extensions except looping (NETSCAPE2.0, ANIMEXTS1.0) and ICC colour (ICCRGBG1012). +//! - TIFF: decoded and re-encoded (uncompressed) with the `image` crate; single-page only. +//! - PDF: trailer /Info, every /Metadata and /PieceInfo removed, orphaned objects pruned, saved fresh by lopdf. + +mod exif_items; +mod gif; +mod iptc; +mod jpeg; +mod pdf; +mod png; +mod text; +mod tiff; +mod webp; +mod xmp; + +use serde::Serialize; + +/// Inputs larger than this are refused (512 MiB). +pub const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024; + +/// A report never holds more items than this; the rest is summarised in a warning. +pub const MAX_ITEMS: usize = 5000; + +/// Caps applied while reading and stripping. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Inputs larger than this are refused with [`MetaError::TooLarge`]. + pub max_input_bytes: u64, + /// The most memory a decoded image (TIFF re-encode) may take. + pub max_decoded_bytes: u64, + /// The most bytes a single PDF stream may decompress to while loading or reading XMP. + pub max_pdf_stream_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + max_input_bytes: MAX_INPUT_BYTES, + max_decoded_bytes: 1024 * 1024 * 1024, + max_pdf_stream_bytes: 64 * 1024 * 1024, + } + } +} + +/// The file type, detected from the content (magic bytes), never from the file name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum Kind { + Jpeg, + Png, + WebP, + Tiff, + Gif, + Pdf, +} + +/// What a metadata item is about; the UI shows one heading per group. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +pub enum Group { + /// Technical EXIF fields (exposure, lens settings, thumbnails, ...). + Exif, + /// Location: GPS coordinates, altitude, direction. The summary item is named "Location". + Gps, + /// The device: make, model, serial numbers, lens. The summary item is named "Camera". + Camera, + /// Who made it: artist, author, copyright, owner. + Author, + /// Which program made or edited it. + Software, + /// When it was made or changed. + Dates, + /// An XMP packet in an image and the values found in it. + Xmp, + /// IPTC / Photoshop information (caption, by-line, keywords, ...). + Iptc, + /// Free-text comments and descriptions. + Comment, + /// A PDF's document information dictionary (title, subject, keywords, custom keys). + PdfInfo, + /// XMP metadata streams inside a PDF. + PdfXmp, + /// Anything else that is not image data: vendor blocks, trailing data, private application data. + Other, +} + +impl Group { + /// Every group, in display order. + pub const ALL: [Group; 12] = [ + Group::Gps, + Group::Camera, + Group::Author, + Group::Software, + Group::Dates, + Group::Exif, + Group::Xmp, + Group::Iptc, + Group::Comment, + Group::PdfInfo, + Group::PdfXmp, + Group::Other, + ]; + + /// A plain-English heading for the UI. + pub fn label(self) -> &'static str { + match self { + Group::Exif => "EXIF", + Group::Gps => "Location (GPS)", + Group::Camera => "Camera", + Group::Author => "Author", + Group::Software => "Software", + Group::Dates => "Dates", + Group::Xmp => "XMP", + Group::Iptc => "IPTC", + Group::Comment => "Comments", + Group::PdfInfo => "Document information", + Group::PdfXmp => "Document XMP", + Group::Other => "Other", + } + } +} + +/// One piece of metadata. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Item { + pub group: Group, + pub name: String, + pub value: String, +} + +/// What [`read`] found. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Report { + pub kind: Kind, + pub items: Vec, + /// Plain-English notes about damaged or unreadable parts; reading went on past them. + pub warnings: Vec, +} + +impl Report { + /// The groups that have at least one item, in display order. + pub fn groups(&self) -> Vec { + Group::ALL.into_iter().filter(|g| self.items.iter().any(|i| i.group == *g)).collect() + } + + /// The first item with this name in this group. + pub fn find(&self, group: Group, name: &str) -> Option<&Item> { + self.items.iter().find(|i| i.group == group && i.name == name) + } +} + +/// The cleaned file from [`strip`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stripped { + pub bytes: Vec, + /// The groups that had items before and fewer (or none) after, in display order. + pub removed: Vec, +} + +/// Errors shown to the user. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum MetaError { + #[error("The file is empty.")] + Empty, + #[error("The file is too large ({size_mib} MiB); the limit for the metadata tools is {limit_mib} MiB.")] + TooLarge { size_mib: u64, limit_mib: u64 }, + #[error("The metadata tools do not support {0}.")] + Unsupported(String), + #[error("This PDF is password-protected. Unlock it first.")] + Encrypted, + #[error("The file is damaged: {0}.")] + Damaged(String), + #[error("The image is too large to process: {0}.")] + TooBig(String), + #[error("The cleaned file could not be written: {0}.")] + Write(String), +} + +impl MetaError { + pub(crate) fn truncated() -> Self { + MetaError::Damaged("it ends too early (truncated)".into()) + } +} + +/// Reads the metadata in a JPEG, PNG, WebP, TIFF, GIF or PDF, with the default [`Limits`]. +pub fn read(bytes: &[u8]) -> Result { + read_with(bytes, &Limits::default()) +} + +/// Reads the metadata with explicit caps. +pub fn read_with(bytes: &[u8], limits: &Limits) -> Result { + let kind = detect(bytes, limits)?; + let mut ctx = Ctx::default(); + match kind { + Kind::Jpeg => jpeg::read(bytes, &mut ctx)?, + Kind::Png => png::read(bytes, &mut ctx)?, + Kind::WebP => webp::read(bytes, &mut ctx)?, + Kind::Tiff => tiff::read(bytes, &mut ctx)?, + Kind::Gif => gif::read(bytes, &mut ctx)?, + Kind::Pdf => pdf::read(bytes, limits, &mut ctx)?, + } + Ok(ctx.into_report(kind)) +} + +/// Returns a copy without metadata, with the default [`Limits`]. +pub fn strip(bytes: &[u8]) -> Result { + strip_with(bytes, &Limits::default()) +} + +/// Returns a copy without metadata, with explicit caps. +pub fn strip_with(bytes: &[u8], limits: &Limits) -> Result { + let kind = detect(bytes, limits)?; + let out = match kind { + Kind::Jpeg => jpeg::strip(bytes)?, + Kind::Png => png::strip(bytes)?, + Kind::WebP => webp::strip(bytes)?, + Kind::Tiff => tiff::strip(bytes, limits)?, + Kind::Gif => gif::strip(bytes)?, + Kind::Pdf => pdf::strip(bytes, limits)?, + }; + // Which groups went away: compare what a read sees before and after. A read that fails counts as empty. + let before = read_with(bytes, limits).map(|r| r.items).unwrap_or_default(); + let after = read_with(&out, limits).map(|r| r.items).unwrap_or_default(); + let count = |items: &[Item], g: Group| items.iter().filter(|i| i.group == g).count(); + let removed = Group::ALL.into_iter().filter(|g| count(&before, *g) > count(&after, *g)).collect(); + Ok(Stripped { bytes: out, removed }) +} + +/// Detects the kind from magic bytes and applies the size cap. +pub fn detect(bytes: &[u8], limits: &Limits) -> Result { + if bytes.is_empty() { + return Err(MetaError::Empty); + } + let size = bytes.len() as u64; + if size > limits.max_input_bytes { + const MIB: u64 = 1024 * 1024; + return Err(MetaError::TooLarge { size_mib: size.div_ceil(MIB), limit_mib: limits.max_input_bytes / MIB }); + } + let kind = if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Kind::Jpeg + } else if bytes.starts_with(&png::SIGNATURE) { + Kind::Png + } else if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Kind::WebP + } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { + Kind::Tiff + } else if bytes.starts_with(b"II+\0") || bytes.starts_with(b"MM\0+") { + return Err(MetaError::Unsupported("BigTIFF files".into())); + } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { + Kind::Gif + } else if text::find(&bytes[..bytes.len().min(1024)], b"%PDF-").is_some() { + Kind::Pdf + } else { + return Err(MetaError::Unsupported("this kind of file (only JPEG, PNG, WebP, TIFF, GIF and PDF)".into())); + }; + Ok(kind) +} + +/// Collects items and warnings while a format reader runs. +#[derive(Default)] +pub(crate) struct Ctx { + items: Vec, + warnings: Vec, + dropped: usize, +} + +const MAX_VALUE_CHARS: usize = 500; +const MAX_NAME_CHARS: usize = 120; + +impl Ctx { + pub(crate) fn push(&mut self, group: Group, name: impl AsRef, value: impl AsRef) { + if self.items.len() >= MAX_ITEMS { + self.dropped += 1; + return; + } + self.items.push(Item { + group, + name: text::clip(name.as_ref(), MAX_NAME_CHARS), + value: text::clip(value.as_ref(), MAX_VALUE_CHARS), + }); + } + + pub(crate) fn warn(&mut self, msg: impl Into) { + let msg = msg.into(); + if self.warnings.len() < 50 && !self.warnings.contains(&msg) { + self.warnings.push(msg); + } + } + + fn into_report(mut self, kind: Kind) -> Report { + if self.dropped > 0 { + let n = self.dropped; + self.warn(format!("{n} more metadata items were found but are not listed.")); + } + Report { kind, items: self.items, warnings: self.warnings } + } +} + +/// Runs a third-party parser behind a panic guard: a panic becomes `None`. +pub(crate) fn guarded(f: impl FnOnce() -> T) -> Option { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok() +} + +/// Formats a byte count for the UI. +pub(crate) fn bytes_label(n: usize) -> String { + if n == 1 { "1 byte".into() } else { format!("{n} bytes") } +} diff --git a/crates/meta/src/pdf.rs b/crates/meta/src/pdf.rs new file mode 100644 index 0000000..ad251f0 --- /dev/null +++ b/crates/meta/src/pdf.rs @@ -0,0 +1,158 @@ +//! PDF through lopdf: the trailer's /Info dictionary and XMP /Metadata streams. + +use lopdf::{Dictionary, Document, LoadOptions, Object}; + +use crate::{Ctx, Group, Limits, MetaError, guarded, text, xmp}; + +/// Deeper nesting than this is not walked (lopdf's parser already stops at 100). +const MAX_DEPTH: usize = 128; +/// XMP streams are read up to this size for the report. +const MAX_XMP_BYTES: usize = 4 * 1024 * 1024; + +// LoadOptions is non-exhaustive: it cannot be built with a struct literal. +#[allow(clippy::field_reassign_with_default)] +fn load(b: &[u8], limits: &Limits) -> Result { + let mut options = LoadOptions::default(); + options.max_decompressed_size = Some(limits.max_pdf_stream_bytes); + let declares_encryption = || text::find(b, b"/Encrypt").is_some(); + let doc = match guarded(|| Document::load_mem_with_options(b, options)) { + Some(Ok(doc)) => doc, + Some(Err(_)) | None if declares_encryption() => return Err(MetaError::Encrypted), + Some(Err(_)) | None => return Err(MetaError::Damaged("the PDF structure cannot be read".into())), + }; + if doc.was_encrypted() || doc.trailer.has(b"Encrypt") { + return Err(MetaError::Encrypted); + } + if doc.catalog().is_err() { + return Err(MetaError::Damaged("the PDF has no readable document catalog".into())); + } + Ok(doc) +} + +fn deref<'a>(doc: &'a Document, o: &'a Object) -> &'a Object { + match o { + Object::Reference(id) => doc.get_object(*id).unwrap_or(&Object::Null), + other => other, + } +} + +fn value_text(doc: &Document, o: &Object) -> String { + match deref(doc, o) { + Object::String(bytes, _) => text::pdf_text(bytes), + Object::Name(n) => text::lossy(n), + Object::Integer(i) => i.to_string(), + Object::Real(r) => r.to_string(), + Object::Boolean(v) => v.to_string(), + Object::Null => String::new(), + _ => "(complex value)".into(), + } +} + +pub(crate) fn read(b: &[u8], limits: &Limits, ctx: &mut Ctx) -> Result<(), MetaError> { + let doc = load(b, limits)?; + + if let Some(info) = doc.trailer.get(b"Info").ok().map(|o| deref(&doc, o)).and_then(|o| o.as_dict().ok()) { + for (key, value) in info.iter() { + let key = text::lossy(key); + let mut shown = value_text(&doc, value); + let group = match key.as_str() { + "Author" => Group::Author, + "Creator" | "Producer" => Group::Software, + "CreationDate" | "ModDate" => { + shown = text::pdf_date(&shown); + Group::Dates + } + _ => Group::PdfInfo, + }; + ctx.push(group, key, shown); + } + } + + let catalog_xmp = doc.catalog().ok().and_then(|c| c.get(b"Metadata").ok()).map(|o| deref(&doc, o)); + if let Some(Object::Stream(stream)) = catalog_xmp { + let content = if stream.filters().map(|f| f.is_empty()).unwrap_or(true) { + Some(stream.content.clone()) + } else { + guarded(|| stream.decompressed_content_with_limit(MAX_XMP_BYTES)).and_then(Result::ok) + }; + match content { + Some(c) => xmp::read_packet(&c, Group::PdfXmp, "Document XMP packet", ctx), + None => ctx.push(Group::PdfXmp, "Document XMP packet", "present (could not be decompressed)"), + } + } else if catalog_xmp.is_some() { + ctx.push(Group::PdfXmp, "Document XMP packet", "present (damaged)"); + } + + let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).ok(); + let (mut with_xmp, mut with_piece_info) = (0usize, 0usize); + for (id, obj) in &doc.objects { + let mut found = (0, 0); + count_keys(obj, 0, &mut found); + if Some(*id) == catalog_id { + found.0 = found.0.saturating_sub(1); + } + with_xmp += usize::from(found.0 > 0); + with_piece_info += usize::from(found.1 > 0); + } + if with_xmp > 0 { + ctx.push(Group::PdfXmp, "XMP on pages, images or other objects", format!("{with_xmp} objects")); + } + if with_piece_info > 0 { + ctx.push(Group::Other, "Private application data (PieceInfo)", format!("{with_piece_info} objects")); + } + Ok(()) +} + +/// Counts /Metadata and /PieceInfo keys in an object and the dictionaries nested directly in it. +fn count_keys(o: &Object, depth: usize, found: &mut (usize, usize)) { + if depth > MAX_DEPTH { + return; + } + let dict = match o { + Object::Dictionary(d) => d, + Object::Stream(s) => &s.dict, + Object::Array(items) => { + items.iter().for_each(|i| count_keys(i, depth + 1, found)); + return; + } + _ => return, + }; + found.0 += usize::from(dict.has(b"Metadata")); + found.1 += usize::from(dict.has(b"PieceInfo")); + dict.iter().for_each(|(_, v)| count_keys(v, depth + 1, found)); +} + +fn scrub(o: &mut Object, depth: usize) { + if depth > MAX_DEPTH { + return; + } + match o { + Object::Dictionary(d) => scrub_dict(d, depth), + Object::Stream(s) => scrub_dict(&mut s.dict, depth), + Object::Array(items) => items.iter_mut().for_each(|i| scrub(i, depth + 1)), + _ => {} + } +} + +fn scrub_dict(d: &mut Dictionary, depth: usize) { + d.remove(b"Metadata"); + d.remove(b"PieceInfo"); + d.iter_mut().for_each(|(_, v)| scrub(v, depth + 1)); +} + +pub(crate) fn strip(b: &[u8], limits: &Limits) -> Result, MetaError> { + let mut doc = load(b, limits)?; + let out = guarded(move || { + doc.trailer.remove(b"Info"); + scrub_dict(&mut doc.trailer, 0); + doc.objects.values_mut().for_each(|o| scrub(o, 0)); + doc.prune_objects(); + let mut out = Vec::with_capacity(b.len()); + doc.save_to(&mut out).map(|_| out) + }); + match out { + Some(Ok(bytes)) => Ok(bytes), + Some(Err(e)) => Err(MetaError::Write(e.to_string())), + None => Err(MetaError::Write("the PDF writer failed".into())), + } +} diff --git a/crates/meta/src/png.rs b/crates/meta/src/png.rs new file mode 100644 index 0000000..46412d8 --- /dev/null +++ b/crates/meta/src/png.rs @@ -0,0 +1,171 @@ +//! PNG at the chunk level: kept chunks are copied byte for byte (with their CRCs). + +use crate::{Ctx, Group, MetaError, exif_items, text, xmp}; + +pub(crate) const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; +const MAX_CHUNKS: usize = 1_000_000; + +/// Chunks that carry metadata and are dropped. +const DROPPED: [&[u8; 4]; 5] = [b"eXIf", b"tEXt", b"zTXt", b"iTXt", b"tIME"]; + +struct Chunk { + kind: [u8; 4], + /// From the length field to the end of the CRC. + span: (usize, usize), + data: (usize, usize), +} + +#[derive(Default)] +struct Parsed { + chunks: Vec, + /// The position after IEND, if there is one. + iend_end: Option, + error: Option, +} + +fn parse(b: &[u8]) -> Parsed { + let mut p = Parsed::default(); + let mut pos = SIGNATURE.len(); + while pos < b.len() { + if p.chunks.len() >= MAX_CHUNKS { + p.error = Some(MetaError::Damaged("it has too many chunks".into())); + break; + } + let (Some(len), Some(kind)) = (text::be32(b, pos), b.get(pos + 4..pos + 8)) else { + p.error = Some(MetaError::truncated()); + break; + }; + if len > 0x7FFF_FFFF { + p.error = Some(MetaError::Damaged("a chunk has an impossible length".into())); + break; + } + let data_start = pos + 8; + let Some(end) = data_start.checked_add(len as usize).and_then(|e| e.checked_add(4)).filter(|&e| e <= b.len()) + else { + p.error = Some(MetaError::truncated()); + break; + }; + let kind = [kind[0], kind[1], kind[2], kind[3]]; + p.chunks.push(Chunk { kind, span: (pos, end), data: (data_start, end - 4) }); + pos = end; + if &kind == b"IEND" { + p.iend_end = Some(end); + break; + } + } + if p.error.is_none() && p.iend_end.is_none() { + p.error = Some(MetaError::truncated()); + } + p +} + +pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> { + let parsed = parse(b); + for c in &parsed.chunks { + let data = b.get(c.data.0..c.data.1).unwrap_or(&[]); + match &c.kind { + b"eXIf" => { + let raw = if data.starts_with(b"Exif\0\0") { &data[6..] } else { data }; + exif_items::read_block(raw, ctx); + } + b"tEXt" => { + let (key, value) = split_nul(data); + let key = text::latin1(key); + ctx.push(text_group(&key), key_label(&key), text::latin1(value)); + } + b"zTXt" => { + let (key, value) = split_nul(data); + let key = text::latin1(key); + let value = format!("compressed text, {}", crate::bytes_label(value.len().saturating_sub(1))); + ctx.push(text_group(&key), key_label(&key), value); + } + b"iTXt" => read_itxt(data, ctx), + b"tIME" if data.len() >= 7 => { + let year = u16::from_be_bytes([data[0], data[1]]); + let value = + format!("{year:04}-{:02}-{:02} {:02}:{:02}:{:02}", data[2], data[3], data[4], data[5], data[6]); + ctx.push(Group::Dates, "Last modified", value); + } + b"tIME" => ctx.push(Group::Dates, "Last modified", "(damaged)"), + _ => {} + } + } + if let Some(end) = parsed.iend_end + && b.len() > end + { + ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end)); + } + if let Some(e) = parsed.error { + if parsed.chunks.is_empty() { + return Err(e); + } + ctx.warn(format!("{e} Only part of it could be read.")); + } + Ok(()) +} + +fn read_itxt(data: &[u8], ctx: &mut Ctx) { + let (key, rest) = split_nul(data); + let key = text::latin1(key); + let (Some(&compressed), Some(_method)) = (rest.first(), rest.get(1)) else { + ctx.push(text_group(&key), key_label(&key), "(damaged)"); + return; + }; + let rest = rest.get(2..).unwrap_or(&[]); + let (_lang, rest) = split_nul(rest); + let (_translated, value) = split_nul(rest); + if key == "XML:com.adobe.xmp" { + if compressed == 0 { + xmp::read_packet(value, Group::Xmp, "XMP packet", ctx); + } else { + ctx.push(Group::Xmp, "XMP packet (compressed)", crate::bytes_label(value.len())); + } + return; + } + let shown = if compressed == 0 { + String::from_utf8_lossy(value).into_owned() + } else { + format!("compressed text, {}", crate::bytes_label(value.len())) + }; + ctx.push(text_group(&key), key_label(&key), shown); +} + +fn split_nul(b: &[u8]) -> (&[u8], &[u8]) { + match b.iter().position(|&c| c == 0) { + Some(i) => (&b[..i], &b[i + 1..]), + None => (b, &[]), + } +} + +fn key_label(key: &str) -> String { + if key.is_empty() { "Text".into() } else { key.to_string() } +} + +fn text_group(key: &str) -> Group { + match key.to_ascii_lowercase().as_str() { + "author" | "copyright" | "artist" => Group::Author, + "software" => Group::Software, + "source" => Group::Camera, + "creation time" | "date" => Group::Dates, + "title" | "description" | "comment" | "disclaimer" | "warning" => Group::Comment, + "xml:com.adobe.xmp" | "raw profile type xmp" => Group::Xmp, + "raw profile type exif" | "raw profile type app1" => Group::Exif, + "raw profile type iptc" | "raw profile type 8bim" => Group::Iptc, + _ => Group::Other, + } +} + +pub(crate) fn strip(b: &[u8]) -> Result, MetaError> { + let parsed = parse(b); + if let Some(e) = parsed.error { + return Err(e); + } + let mut out = Vec::with_capacity(b.len()); + out.extend_from_slice(&SIGNATURE); + for c in &parsed.chunks { + if !DROPPED.contains(&&c.kind) { + out.extend_from_slice(&b[c.span.0..c.span.1]); + } + } + Ok(out) +} diff --git a/crates/meta/src/text.rs b/crates/meta/src/text.rs new file mode 100644 index 0000000..b13348e --- /dev/null +++ b/crates/meta/src/text.rs @@ -0,0 +1,187 @@ +//! Small byte and text helpers shared by the format readers. + +/// The first position of `needle` in `hay`. +pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() || needle.len() > hay.len() { + return None; + } + hay.windows(needle.len()).position(|w| w == needle) +} + +pub(crate) fn be16(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_be_bytes([s[0], s[1]])) +} + +pub(crate) fn be32(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) +} + +pub(crate) fn le32(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +/// Cuts a string to `max` characters, adding an ellipsis, and replaces control characters with spaces. +pub(crate) fn clip(s: &str, max: usize) -> String { + let mut out = String::with_capacity(s.len().min(max * 4)); + for (n, c) in s.chars().enumerate() { + if n == max { + out.push('…'); + break; + } + out.push(if c.is_control() { ' ' } else { c }); + } + out.trim().to_string() +} + +/// Bytes as text: UTF-8 where valid, otherwise Latin-1; trailing NULs dropped. +pub(crate) fn lossy(b: &[u8]) -> String { + let b = trim_nul(b); + match std::str::from_utf8(b) { + Ok(s) => s.to_string(), + Err(_) => latin1(b), + } +} + +pub(crate) fn latin1(b: &[u8]) -> String { + trim_nul(b).iter().map(|&c| c as char).collect() +} + +fn trim_nul(mut b: &[u8]) -> &[u8] { + while let [rest @ .., 0] = b { + b = rest; + } + b +} + +/// A PDF text string: UTF-16BE (or LE) with a byte order mark, UTF-8 with a BOM, or PDFDocEncoding. +pub(crate) fn pdf_text(b: &[u8]) -> String { + if let Some(rest) = b.strip_prefix(&[0xFE, 0xFF]) { + let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); + return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect(); + } + if let Some(rest) = b.strip_prefix(&[0xFF, 0xFE]) { + let units = rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)); + return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect(); + } + if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + return String::from_utf8_lossy(rest).into_owned(); + } + b.iter().map(|&c| pdf_doc_char(c)).collect() +} + +fn pdf_doc_char(c: u8) -> char { + const LOW: [char; 8] = + ['\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}', '\u{02DC}']; + const HIGH: [char; 33] = [ + '\u{2022}', '\u{2020}', '\u{2021}', '\u{2026}', '\u{2014}', '\u{2013}', '\u{0192}', '\u{2044}', '\u{2039}', + '\u{203A}', '\u{2212}', '\u{2030}', '\u{201E}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{201A}', + '\u{2122}', '\u{FB01}', '\u{FB02}', '\u{0141}', '\u{0152}', '\u{0160}', '\u{0178}', '\u{017D}', '\u{0131}', + '\u{0142}', '\u{0153}', '\u{0161}', '\u{017E}', '\u{FFFD}', '\u{20AC}', + ]; + match c { + 0x18..=0x1F => LOW[usize::from(c - 0x18)], + 0x7F | 0xAD => '\u{FFFD}', + 0x80..=0xA0 => HIGH[usize::from(c - 0x80)], + _ => c as char, + } +} + +/// Makes "D:20240501102030+02'00'" readable as "2024-05-01 10:20:30 +02:00"; anything else is returned as is. +pub(crate) fn pdf_date(s: &str) -> String { + let body = s.strip_prefix("D:").unwrap_or(s); + let digits: String = body.chars().take_while(|c| c.is_ascii_digit()).collect(); + if digits.len() < 4 || !s.starts_with("D:") { + return s.to_string(); + } + let part = |from: usize, to: usize, default: &str| digits.get(from..to).unwrap_or(default).to_string(); + let mut out = format!( + "{}-{}-{} {}:{}:{}", + part(0, 4, "0000"), + part(4, 6, "01"), + part(6, 8, "01"), + part(8, 10, "00"), + part(10, 12, "00"), + part(12, 14, "00") + ); + let rest: String = body.chars().skip(digits.chars().count()).collect(); + let rest = rest.trim(); + if rest.starts_with('Z') { + out.push_str(" UTC"); + } else if rest.starts_with('+') || rest.starts_with('-') { + let tz: String = rest.chars().filter(|c| c.is_ascii_digit()).take(4).collect(); + if tz.len() == 4 { + out.push_str(&format!(" {}{}:{}", &rest[..1], &tz[..2], &tz[2..])); + } + } + out +} + +/// Decodes the five XML entities and numeric character references. +pub(crate) fn xml_unescape(s: &str) -> String { + if !s.contains('&') { + return s.to_string(); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + rest = &rest[i..]; + let end = rest.find(';').filter(|&e| e <= 12); + let decoded = end.and_then(|e| { + let ent = &rest[1..e]; + let c = match ent { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + _ if ent.starts_with("#x") || ent.starts_with("#X") => { + u32::from_str_radix(&ent[2..], 16).ok().and_then(char::from_u32) + } + _ if ent.starts_with('#') => ent[1..].parse::().ok().and_then(char::from_u32), + _ => None, + }; + c.map(|c| (c, e)) + }); + match decoded { + Some((c, e)) => { + out.push(c); + rest = &rest[e + 1..]; + } + None => { + out.push('&'); + rest = &rest[1..]; + } + } + } + out.push_str(rest); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pdf_strings() { + assert_eq!(pdf_text(&[0xFE, 0xFF, 0x00, 0x4A, 0x00, 0xE1]), "Já"); + assert_eq!(pdf_text(b"Caf\xE9 \x84"), "Café —"); + assert_eq!(pdf_date("D:20240501102030+02'00'"), "2024-05-01 10:20:30 +02:00"); + assert_eq!(pdf_date("D:2024"), "2024-01-01 00:00:00"); + assert_eq!(pdf_date("yesterday"), "yesterday"); + } + + #[test] + fn unescape() { + assert_eq!(xml_unescape("a & b AB &bogus; &"), "a & b AB &bogus; &"); + } + + #[test] + fn clipping() { + assert_eq!(clip("abcdef", 3), "abc…"); + assert_eq!(clip("a\nb", 10), "a b"); + } +} diff --git a/crates/meta/src/tiff.rs b/crates/meta/src/tiff.rs new file mode 100644 index 0000000..3cd2787 --- /dev/null +++ b/crates/meta/src/tiff.rs @@ -0,0 +1,75 @@ +//! TIFF: tags read through kamadak-exif (a TIFF file is itself EXIF-structured); stripping decodes the pixels and +//! writes a fresh, uncompressed TIFF with only the layout tags, through the `image` crate. + +use std::io::Cursor; + +use crate::{Ctx, Limits, MetaError, exif_items, guarded, text}; + +/// Whether the first IFD links to a second one (a multi-page TIFF, or one with a thumbnail page). +fn has_second_ifd(b: &[u8]) -> Option { + let le = b.starts_with(b"II"); + let u16_at = |at: usize| -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + }; + let u32_at = |at: usize| -> Option { if le { text::le32(b, at) } else { text::be32(b, at) } }; + let ifd = u32_at(4)? as usize; + let count = usize::from(u16_at(ifd)?); + let next_at = ifd.checked_add(2)?.checked_add(count.checked_mul(12)?)?; + Some(u32_at(next_at)? != 0) +} + +pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> { + if has_second_ifd(b) == Some(true) { + ctx.warn("This TIFF has more than one page; removing metadata works on single-page TIFF files only."); + } + let parsed = guarded(|| { + let mut reader = exif::Reader::new(); + reader.continue_on_error(true); + match reader.read_raw(b.to_vec()) { + Ok(exif) => Ok((exif, false)), + Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)), + } + }); + match parsed { + Some(Ok((exif, partial))) => { + if partial { + ctx.warn("Part of the TIFF tags are damaged; what could be read is listed."); + } + exif_items::list(&exif, ctx); + Ok(()) + } + Some(Err(_)) | None => Err(MetaError::Damaged("its TIFF tags cannot be read".into())), + } +} + +pub(crate) fn strip(b: &[u8], limits: &Limits) -> Result, MetaError> { + match has_second_ifd(b) { + Some(true) => return Err(MetaError::Unsupported("multi-page TIFF files".into())), + Some(false) => {} + None => return Err(MetaError::Damaged("its TIFF structure cannot be read".into())), + } + let decoded = guarded(|| { + let mut reader = image::ImageReader::with_format(Cursor::new(b), image::ImageFormat::Tiff); + let mut l = image::Limits::default(); + l.max_alloc = Some(limits.max_decoded_bytes); + reader.limits(l); + reader.decode() + }) + .ok_or_else(|| MetaError::Damaged("the image data cannot be decoded".into()))?; + let img = decoded.map_err(|e| match e { + image::ImageError::Limits(_) => MetaError::TooBig("it needs more memory than allowed".into()), + image::ImageError::Unsupported(_) => MetaError::Unsupported("this kind of TIFF image".into()), + _ => MetaError::Damaged("the image data cannot be decoded".into()), + })?; + let mut out = Cursor::new(Vec::new()); + guarded(|| img.write_to(&mut out, image::ImageFormat::Tiff)) + .ok_or_else(|| MetaError::Write("the TIFF encoder failed".into()))? + .map_err(|e| match e { + image::ImageError::Unsupported(_) => { + MetaError::Unsupported("this kind of TIFF image (pixel format)".into()) + } + other => MetaError::Write(other.to_string()), + })?; + Ok(out.into_inner()) +} diff --git a/crates/meta/src/webp.rs b/crates/meta/src/webp.rs new file mode 100644 index 0000000..11ce600 --- /dev/null +++ b/crates/meta/src/webp.rs @@ -0,0 +1,105 @@ +//! WebP at the RIFF chunk level: EXIF and XMP chunks are dropped, VP8X flags cleared to match, the rest copied. + +use crate::{Ctx, Group, MetaError, exif_items, text, xmp}; + +const MAX_CHUNKS: usize = 1_000_000; +const FLAG_EXIF: u8 = 0x08; +const FLAG_XMP: u8 = 0x04; + +struct Chunk { + id: [u8; 4], + /// From the id to the end of the data, including the pad byte when there is one. + span: (usize, usize), + data: (usize, usize), +} + +struct Parsed { + chunks: Vec, + /// Bytes after the RIFF container. + trailing: usize, + error: Option, +} + +fn parse(b: &[u8]) -> Parsed { + let mut p = Parsed { chunks: Vec::new(), trailing: 0, error: None }; + let declared = text::le32(b, 4).map_or(0, |s| s as usize).saturating_add(8); + let end = if declared > b.len() { + p.error = Some(MetaError::truncated()); + b.len() + } else { + p.trailing = b.len() - declared; + declared + }; + let mut pos = 12; + while pos < end { + if p.chunks.len() >= MAX_CHUNKS { + p.error = Some(MetaError::Damaged("it has too many chunks".into())); + break; + } + let (Some(id), Some(size)) = (b.get(pos..pos + 4), text::le32(b, pos + 4)) else { + p.error = Some(MetaError::truncated()); + break; + }; + let data_start = pos + 8; + let Some(data_end) = data_start.checked_add(size as usize).filter(|&e| e <= end) else { + p.error = Some(MetaError::truncated()); + break; + }; + // Odd sizes are followed by a pad byte; a missing pad at the very end is tolerated. + let span_end = (data_end + (size as usize & 1)).min(end); + p.chunks.push(Chunk { id: [id[0], id[1], id[2], id[3]], span: (pos, span_end), data: (data_start, data_end) }); + pos = span_end; + } + p +} + +fn is_dropped(id: &[u8; 4]) -> bool { + id == b"EXIF" || id == b"XMP " +} + +pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> { + let parsed = parse(b); + for c in &parsed.chunks { + let data = &b[c.data.0..c.data.1]; + match &c.id { + b"EXIF" => { + let raw = if data.starts_with(b"Exif\0\0") { &data[6..] } else { data }; + exif_items::read_block(raw, ctx); + } + b"XMP " => xmp::read_packet(data, Group::Xmp, "XMP packet", ctx), + _ => {} + } + } + if parsed.trailing > 0 { + ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(parsed.trailing)); + } + if let Some(e) = parsed.error { + if parsed.chunks.is_empty() { + return Err(e); + } + ctx.warn(format!("{e} Only part of it could be read.")); + } + Ok(()) +} + +pub(crate) fn strip(b: &[u8]) -> Result, MetaError> { + let parsed = parse(b); + if let Some(e) = parsed.error { + return Err(e); + } + let mut out = Vec::with_capacity(b.len()); + out.extend_from_slice(b"RIFF\0\0\0\0WEBP"); + for c in parsed.chunks.iter().filter(|c| !is_dropped(&c.id)) { + let start = out.len(); + out.extend_from_slice(&b[c.span.0..c.span.1]); + if &c.id == b"VP8X" && c.data.1 > c.data.0 { + out[start + 8] &= !(FLAG_EXIF | FLAG_XMP); + } + if (c.span.1 - c.span.0) % 2 == 1 { + out.push(0); + } + } + let riff_size = u32::try_from(out.len() - 8).map_err(|_| MetaError::Write("the file is too large".into()))?; + out[4..8].copy_from_slice(&riff_size.to_le_bytes()); + Ok(out) +} diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs new file mode 100644 index 0000000..9fd3048 --- /dev/null +++ b/crates/meta/src/xmp.rs @@ -0,0 +1,138 @@ +//! A small, bounded scan of an XMP packet for the properties people care about. Not an XML parser: it looks for +//! `prefix:name="value"` attributes and `...` elements and takes the text inside. + +use crate::{Ctx, Group, text}; + +const PROPS: &[(&str, &str)] = &[ + ("dc:creator", "Creator"), + ("dc:rights", "Rights"), + ("dc:title", "Title"), + ("dc:description", "Description"), + ("dc:subject", "Keywords"), + ("xmp:CreatorTool", "Creator tool"), + ("xmp:CreateDate", "Created"), + ("xmp:ModifyDate", "Modified"), + ("xmp:MetadataDate", "Metadata date"), + ("pdf:Producer", "Producer"), + ("pdf:Keywords", "Keywords"), + ("photoshop:AuthorsPosition", "Author's position"), + ("photoshop:CaptionWriter", "Caption writer"), + ("photoshop:City", "City"), + ("photoshop:State", "State"), + ("photoshop:Country", "Country"), + ("photoshop:Credit", "Credit"), + ("photoshop:Source", "Source"), + ("photoshop:DateCreated", "Date created"), + ("Iptc4xmpCore:Location", "Location"), + ("xmpRights:Owner", "Rights owner"), + ("exif:GPSLatitude", "GPS latitude"), + ("exif:GPSLongitude", "GPS longitude"), + ("exif:DateTimeOriginal", "Taken"), + ("tiff:Make", "Camera make"), + ("tiff:Model", "Camera model"), + ("tiff:Artist", "Artist"), + ("aux:SerialNumber", "Camera serial number"), + ("aux:Lens", "Lens"), + ("exifEX:BodySerialNumber", "Camera serial number"), + ("xmpMM:DocumentID", "Document ID"), + ("xmpMM:OriginalDocumentID", "Original document ID"), + ("xmpMM:InstanceID", "Instance ID"), + ("stEvt:softwareAgent", "Edited with"), +]; + +/// Adds an item for the packet itself and one per property found. +pub(crate) fn read_packet(packet: &[u8], group: Group, what: &str, ctx: &mut Ctx) { + ctx.push(group, what, crate::bytes_label(packet.len())); + let s = String::from_utf8_lossy(packet); + for &(prop, label) in PROPS { + if let Some(v) = find_value(&s, prop).filter(|v| !v.is_empty()) { + ctx.push(group, format!("{label} ({prop})"), v); + } + } +} + +fn find_value(s: &str, prop: &str) -> Option { + element_value(s, prop).or_else(|| attribute_value(s, prop)) +} + +fn attribute_value(s: &str, prop: &str) -> Option { + let mut from = 0; + while let Some(i) = s.get(from..)?.find(prop) { + let at = from + i; + from = at + prop.len(); + let before_ok = s[..at].chars().next_back().is_some_and(char::is_whitespace); + let after = s[from..].trim_start(); + let Some(after) = after.strip_prefix('=') else { continue }; + let after = after.trim_start(); + let Some(quote) = after.chars().next().filter(|c| *c == '"' || *c == '\'') else { continue }; + if !before_ok { + continue; + } + let body = &after[1..]; + let end = body.find(quote)?; + return Some(text::xml_unescape(body[..end].trim())); + } + None +} + +fn element_value(s: &str, prop: &str) -> Option { + let open = format!("<{prop}"); + let close = format!(""); + let mut from = 0; + while let Some(i) = s.get(from..)?.find(&open) { + let start = from + i + open.len(); + from = start; + let next = s[start..].chars().next()?; + if !(next == '>' || next == '/' || next.is_whitespace()) { + continue; + } + let tag_end = start + s[start..].find('>')?; + if s[..tag_end].ends_with('/') { + // or an empty element: nothing to show here. + continue; + } + let end = tag_end + s[tag_end..].find(&close)?; + let inner = &s[tag_end + 1..end]; + return Some(text_nodes(inner)); + } + None +} + +/// The text between tags, trimmed, joined with "; ". +fn text_nodes(inner: &str) -> String { + let mut parts: Vec = Vec::new(); + let mut rest = inner; + loop { + let (txt, after) = match rest.find('<') { + Some(i) => (&rest[..i], Some(&rest[i..])), + None => (rest, None), + }; + let t = txt.trim(); + if !t.is_empty() { + parts.push(text::xml_unescape(t)); + } + match after.and_then(|a| a.find('>').map(|j| &a[j + 1..])) { + Some(next) => rest = next, + None => break, + } + } + parts.join("; ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_both_forms() { + let x = r#" + JanEva + no"#; + assert_eq!(find_value(x, "dc:creator").as_deref(), Some("Jan; Eva")); + assert_eq!(find_value(x, "xmp:CreatorTool").as_deref(), Some("Tool & Co")); + assert_eq!(find_value(x, "tiff:Make").as_deref(), Some("Apple")); + assert_eq!(find_value(x, "dc:title"), None); + assert_eq!(find_value(" RgbImage { + RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 13 + y * 7) as u8, (x * 31) as u8 ^ (y * 5) as u8, (y * 17) as u8])) +} + +pub fn rgba(w: u32, h: u32) -> RgbaImage { + RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 29) as u8, (y * 41) as u8, (x ^ y) as u8 * 9, 128 + (x as u8)])) +} + +pub fn ascii(tag: Tag, s: &str) -> Field { + Field { tag, ifd_num: In::PRIMARY, value: Value::Ascii(vec![s.as_bytes().to_vec()]) } +} + +pub fn rationals(tag: Tag, v: &[(u32, u32)]) -> Field { + Field { + tag, + ifd_num: In::PRIMARY, + value: Value::Rational(v.iter().map(|&(num, denom)| Rational { num, denom }).collect()), + } +} + +pub fn short(tag: Tag, v: &[u16]) -> Field { + Field { tag, ifd_num: In::PRIMARY, value: Value::Short(v.to_vec()) } +} + +/// GPS 50.08 N, 14.42 E; Apple iPhone 15; software; artist; date taken; Orientation 6. +pub fn photo_fields() -> Vec { + vec![ + ascii(Tag::Make, MAKE), + ascii(Tag::Model, MODEL), + ascii(Tag::Software, SOFTWARE), + ascii(Tag::Artist, AUTHOR), + ascii(Tag::DateTimeOriginal, "2024:05:01 10:20:30"), + short(Tag::Orientation, &[6]), + ascii(Tag::GPSLatitudeRef, "N"), + rationals(Tag::GPSLatitude, &[(50, 1), (4, 1), (48, 1)]), + ascii(Tag::GPSLongitudeRef, "E"), + rationals(Tag::GPSLongitude, &[(14, 1), (25, 1), (12, 1)]), + ] +} + +/// A raw EXIF block (TIFF header onwards). +pub fn exif_tiff(fields: &[Field]) -> Vec { + let mut w = Writer::new(); + for f in fields { + w.push_field(f); + } + let mut c = Cursor::new(Vec::new()); + w.write(&mut c, false).expect("exif writer"); + c.into_inner() +} + +pub fn xmp_packet() -> String { + format!( + r#" + + +{AUTHOR} + +"# + ) +} + +/// Photoshop 3.0 + 8BIM 0x0404 with an IPTC by-line (2:80). +pub fn photoshop_iptc() -> Vec { + let mut iim = vec![0x1C, 2, 80]; + iim.extend_from_slice(&(AUTHOR.len() as u16).to_be_bytes()); + iim.extend_from_slice(AUTHOR.as_bytes()); + let mut p = b"Photoshop 3.0\0".to_vec(); + p.extend_from_slice(b"8BIM"); + p.extend_from_slice(&0x0404u16.to_be_bytes()); + p.extend_from_slice(&[0, 0]); // empty name, padded + p.extend_from_slice(&(iim.len() as u32).to_be_bytes()); + p.extend_from_slice(&iim); + if iim.len() % 2 == 1 { + p.push(0); + } + p +} + +pub fn segment(marker: u8, payload: &[u8]) -> Vec { + let mut s = vec![0xFF, marker]; + s.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + s.extend_from_slice(payload); + s +} + +pub fn plain_jpeg() -> Vec { + let img = rgb(24, 16); + let mut out = Vec::new(); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90) + .write_image(img.as_raw(), 24, 16, image::ExtendedColorType::Rgb8) + .expect("jpeg encode"); + out +} + +/// A JPEG with the given extra segments inserted right after SOI. +pub fn jpeg_with(segments: &[Vec]) -> Vec { + let plain = plain_jpeg(); + let mut out = plain[..2].to_vec(); + for s in segments { + out.extend_from_slice(s); + } + out.extend_from_slice(&plain[2..]); + out +} + +pub fn exif_app1(raw: &[u8]) -> Vec { + let mut p = b"Exif\0\0".to_vec(); + p.extend_from_slice(raw); + segment(0xE1, &p) +} + +pub fn xmp_app1() -> Vec { + let mut p = b"http://ns.adobe.com/xap/1.0/\0".to_vec(); + p.extend_from_slice(xmp_packet().as_bytes()); + segment(0xE1, &p) +} + +/// The full test photo: EXIF (GPS, camera, author, software, date, Orientation 6), XMP, IPTC, a comment. +pub fn photo_jpeg() -> Vec { + jpeg_with(&[ + exif_app1(&exif_tiff(&photo_fields())), + xmp_app1(), + segment(0xED, &photoshop_iptc()), + segment(0xFE, COMMENT.as_bytes()), + ]) +} + +pub fn plain_png() -> Vec { + let img = rgba(9, 7); + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new(&mut out) + .write_image(img.as_raw(), 9, 7, image::ExtendedColorType::Rgba8) + .expect("png encode"); + out +} + +/// PNG with eXIf, iTXt XMP, tEXt Author and Software, tIME. +pub fn photo_png() -> Vec { + use img_parts::Bytes; + use img_parts::png::{Png, PngChunk}; + let mut png = Png::from_bytes(Bytes::from(plain_png())).expect("png parse"); + let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec(); + itxt.extend_from_slice(xmp_packet().as_bytes()); + let mut author = b"Author\0".to_vec(); + author.extend_from_slice(AUTHOR.as_bytes()); + let mut software = b"Software\0".to_vec(); + software.extend_from_slice(SOFTWARE.as_bytes()); + let chunks = [ + PngChunk::new(*b"eXIf", Bytes::from(exif_tiff(&photo_fields()))), + PngChunk::new(*b"iTXt", Bytes::from(itxt)), + PngChunk::new(*b"tEXt", Bytes::from(author)), + PngChunk::new(*b"tEXt", Bytes::from(software)), + PngChunk::new(*b"tIME", Bytes::from_static(&[0x07, 0xE8, 5, 1, 10, 20, 30])), + ]; + for (i, c) in chunks.into_iter().enumerate() { + png.chunks_mut().insert(1 + i, c); + } + png.encoder().bytes().to_vec() +} + +pub fn plain_webp() -> Vec { + let img = rgba(10, 6); + let mut out = Vec::new(); + image::codecs::webp::WebPEncoder::new_lossless(&mut out) + .write_image(img.as_raw(), 10, 6, image::ExtendedColorType::Rgba8) + .expect("webp encode"); + out +} + +/// VP8X WebP with EXIF and XMP chunks (built with img-parts, which also sets the VP8X flags). +pub fn photo_webp() -> Vec { + use img_parts::riff::{RiffChunk, RiffContent}; + use img_parts::webp::{CHUNK_XMP, WebP}; + use img_parts::{Bytes, ImageEXIF}; + let mut webp = WebP::from_bytes(Bytes::from(plain_webp())).expect("webp parse"); + webp.chunks_mut().push(RiffChunk::new(CHUNK_XMP, RiffContent::Data(Bytes::from(xmp_packet().into_bytes())))); + webp.set_exif(Some(Bytes::from(exif_tiff(&photo_fields())))); + webp.encoder().bytes().to_vec() +} + +/// A 5x4 RGB TIFF written by the EXIF writer, with Make, Model, Software and Artist tags. +pub fn photo_tiff() -> (Vec, RgbImage) { + let (w, h) = (5u32, 4u32); + let img = rgb(w, h); + let fields = vec![ + Field { tag: Tag::ImageWidth, ifd_num: In::PRIMARY, value: Value::Long(vec![w]) }, + Field { tag: Tag::ImageLength, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) }, + short(Tag::BitsPerSample, &[8, 8, 8]), + short(Tag::Compression, &[1]), + short(Tag::PhotometricInterpretation, &[2]), + short(Tag::SamplesPerPixel, &[3]), + Field { tag: Tag::RowsPerStrip, ifd_num: In::PRIMARY, value: Value::Long(vec![h]) }, + short(Tag::PlanarConfiguration, &[1]), + ascii(Tag::Make, MAKE), + ascii(Tag::Model, MODEL), + ascii(Tag::Software, SOFTWARE), + ascii(Tag::Artist, AUTHOR), + ]; + let strip: &[u8] = img.as_raw(); + let strips = [strip]; + let mut wr = Writer::new(); + for f in &fields { + wr.push_field(f); + } + wr.set_strips(&strips, In::PRIMARY); + let mut c = Cursor::new(Vec::new()); + wr.write(&mut c, false).expect("tiff writer"); + (c.into_inner(), img) +} + +/// A two-frame looping GIF with a comment extension and an XMP application extension. +pub fn photo_gif() -> Vec { + use image::codecs::gif::{GifEncoder, Repeat}; + use image::{Delay, Frame}; + let mut out = Vec::new(); + { + let mut enc = GifEncoder::new(&mut out); + enc.set_repeat(Repeat::Infinite).expect("repeat"); + let a = RgbaImage::from_fn(6, 5, |x, y| { + if (x + y) % 2 == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) } + }); + let b = RgbaImage::from_fn(6, 5, |x, _| { + if x < 3 { image::Rgba([0, 255, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) } + }); + let d = Delay::from_numer_denom_ms(100, 1); + enc.encode_frames(vec![Frame::from_parts(a, 0, 0, d), Frame::from_parts(b, 0, 0, d)]).expect("gif encode"); + } + assert_eq!(out.last(), Some(&0x3B)); + out.pop(); + // Comment extension. + out.extend_from_slice(&[0x21, 0xFE, COMMENT.len() as u8]); + out.extend_from_slice(COMMENT.as_bytes()); + out.push(0); + // XMP application extension: raw packet plus the 258-byte magic trailer. + out.extend_from_slice(&[0x21, 0xFF, 11]); + out.extend_from_slice(b"XMP DataXMP"); + out.extend_from_slice(xmp_packet().as_bytes()); + out.push(1); + out.extend((0..=255u8).rev()); + out.push(0); + out.push(0x3B); + out +} + +pub fn contains(hay: &[u8], needle: &[u8]) -> bool { + hay.windows(needle.len()).any(|w| w == needle) +} + +/// A deterministic xorshift generator. +pub struct XorShift(pub u64); + +impl XorShift { + pub fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + pub fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { (self.next() % n as u64) as usize } + } +} diff --git a/crates/meta/tests/hostile.rs b/crates/meta/tests/hostile.rs new file mode 100644 index 0000000..3a352ba --- /dev/null +++ b/crates/meta/tests/hostile.rs @@ -0,0 +1,196 @@ +mod common; + +use common::*; +use pictor_meta::{Group, MetaError, read, strip}; + +fn malformed_exif_blocks() -> Vec<(&'static str, Vec)> { + let mut truncated_ifd = b"MM\0*\0\0\0\x08\0\x05".to_vec(); + truncated_ifd.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00]); // half an entry + let offset_beyond = b"MM\0*\xFF\xFF\xFF\x00".to_vec(); + let mut huge_count = b"II*\0\x08\0\0\0\xFF\xFF".to_vec(); + huge_count.extend_from_slice(&[0x0F, 0x01, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x10, 0x00, 0x00, 0x00]); + let mut value_beyond = b"MM\0*\0\0\0\x08\0\x01".to_vec(); + value_beyond.extend_from_slice(&[0x01, 0x0F, 0x00, 0x02, 0x7F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x10, 0x00]); + value_beyond.extend_from_slice(&[0, 0, 0, 0]); + vec![ + ("truncated IFD", truncated_ifd), + ("IFD offset beyond the segment", offset_beyond), + ("huge entry count", huge_count), + ("value offset beyond the segment", value_beyond), + ("not TIFF at all", b"garbage!".to_vec()), + ("empty", Vec::new()), + ] +} + +#[test] +fn malformed_exif_is_reported_and_still_removed() { + let plain = image::load_from_memory(&plain_jpeg()).unwrap().to_rgb8(); + for (what, block) in malformed_exif_blocks() { + let jpeg = jpeg_with(&[exif_app1(&block), segment(0xFE, COMMENT.as_bytes())]); + match read(&jpeg) { + Ok(r) => { + assert!(r.find(Group::Exif, "EXIF block").is_some(), "{what}"); + assert!(!r.warnings.is_empty() || r.items.len() <= 3, "{what}: {:?}", r); + } + Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "{what}: {e:?}"), + } + let s = strip(&jpeg).unwrap_or_else(|e| panic!("{what}: {e}")); + assert!(!contains(&s.bytes, b"Exif\0"), "{what}: EXIF block removed, no orientation kept"); + assert!(!contains(&s.bytes, COMMENT.as_bytes()), "{what}"); + assert!(s.removed.contains(&Group::Exif), "{what}"); + assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), plain, "{what}"); + } +} + +#[test] +fn truncated_jpeg_never_panics() { + let jpeg = photo_jpeg(); + for cut in [3, 4, 5, 20, 100, 300, jpeg.len() / 2, jpeg.len() - 40, jpeg.len() - 2, jpeg.len() - 1] { + let b = &jpeg[..cut]; + let _ = read(b); + match strip(b) { + Ok(s) => { + assert!(!contains(&s.bytes, AUTHOR.as_bytes()), "cut {cut}"); + assert!(!contains(&s.bytes, b"Exif\0\0MM\0*\0\0\0\x08\0\x0b"), "cut {cut}"); + } + Err(e) => assert!(matches!(e, MetaError::Damaged(_)), "cut {cut}: {e:?}"), + } + } +} + +#[test] +fn truncated_png_never_panics() { + let png = photo_png(); + for cut in [8, 9, 12, 20, 33, 60, png.len() / 2, png.len() - 4, png.len() - 1] { + let b = &png[..cut]; + if let Ok(r) = read(b) { + assert!(!r.warnings.is_empty(), "cut {cut}: a truncated PNG gives a warning"); + } + assert!(matches!(strip(b), Err(MetaError::Damaged(_))), "cut {cut}"); + } +} + +#[test] +fn png_chunk_with_impossible_length() { + let mut b = png::SIGNATURE.to_vec(); + b.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]); + b.extend_from_slice(b"tEXt"); + b.extend_from_slice(&[0x41; 32]); + assert!(read(&b).is_err()); + assert!(matches!(strip(&b), Err(MetaError::Damaged(_)))); + + // The same after a valid IHDR. + let mut good = plain_png(); + good.truncate(33); + good.extend_from_slice(&b[8..]); + let r = read(&good).unwrap(); + assert!(!r.warnings.is_empty()); + assert!(matches!(strip(&good), Err(MetaError::Damaged(_)))); +} + +#[test] +fn hostile_container_lengths() { + // WebP: RIFF size and chunk size far beyond the data. + let mut webp = b"RIFF\xF0\xFF\xFF\xFFWEBPVP8X\xFF\xFF\xFF\x7F".to_vec(); + webp.extend_from_slice(&[0; 10]); + let _ = read(&webp); + assert!(strip(&webp).is_err()); + // GIF: a colour table flag with no table, then nothing. + assert!(strip(b"GIF89a\x01\0\x01\0\xF7\0\0").is_err()); + let _ = read(b"GIF89a\x01\0\x01\0\xF7\0\0"); + // GIF: an extension that never ends. + assert!(strip(b"GIF89a\x01\0\x01\0\0\0\0\x21\xFE\xFF\x41\x41").is_err()); + // TIFF: IFD offset beyond the file, huge count. + for t in [&b"II*\0\xFF\xFF\xFF\xFF"[..], b"MM\0*\0\0\0\x08\xFF\xFF\0\0", b"II*\0\x08\0\0\0"] { + let _ = read(t); + assert!(strip(t).is_err()); + } + // JPEG: a segment length below 2, a length past the end, garbage between segments. + for j in [&b"\xFF\xD8\xFF\xE1\x00\x01"[..], b"\xFF\xD8\xFF\xE1\xFF\xFFExif", b"\xFF\xD8\xFF\xE0\x00\x04ab\x13\x37"] + { + let _ = read(j); + assert!(matches!(strip(j), Err(MetaError::Damaged(_)))); + } +} + +#[test] +fn empty_and_random_bytes() { + assert_eq!(read(&[]), Err(MetaError::Empty)); + assert_eq!(strip(&[]), Err(MetaError::Empty)); + let mut rng = XorShift(0x9E37_79B9_7F4A_7C15); + let prefixes: [&[u8]; 7] = + [b"", b"\xFF\xD8\xFF", &png::SIGNATURE, b"RIFF\x40\0\0\0WEBP", b"II*\0", b"GIF89a", b"%PDF-1.7\n"]; + for prefix in prefixes { + for len in [1usize, 7, 64, 4096] { + let mut b = prefix.to_vec(); + b.extend((0..len).map(|_| rng.next() as u8)); + let _ = read(&b); + let _ = strip(&b); + } + } +} + +/// Mutates every fixture a few hundred times (deterministically) and runs read and strip on each. +#[test] +fn mutation_fuzz_never_panics() { + let (tiff, _) = photo_tiff(); + let fixtures: Vec<(&str, Vec)> = vec![ + ("jpeg", photo_jpeg()), + ("png", photo_png()), + ("webp", photo_webp()), + ("tiff", tiff), + ("gif", photo_gif()), + ("pdf", pdf_fixture()), + ]; + let mut rng = XorShift(0x2545_F491_4F6C_DD1D); + for (name, original) in &fixtures { + for round in 0..300 { + let mut b = original.clone(); + for _ in 0..1 + rng.below(8) { + let at = rng.below(b.len()); + match rng.below(4) { + 0 => b[at] = 0xFF, + 1 => b[at] = 0x00, + _ => b[at] = rng.next() as u8, + } + } + if rng.below(5) == 0 { + let keep = rng.below(b.len()).max(1); + b.truncate(keep); + } + if rng.below(8) == 0 && b.len() > 16 { + let at = rng.below(b.len() - 4); + b[at..at + 4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xF0]); + } + let _ = read(&b); + if let Ok(s) = strip(&b) { + assert!(!s.bytes.is_empty(), "{name} round {round}"); + } + } + } +} + +/// A small PDF with /Info, built with lopdf. +fn pdf_fixture() -> Vec { + use lopdf::{Document, Object, Stream, dictionary}; + let mut doc = Document::with_version("1.5"); + let pages_id = doc.new_object_id(); + let xmp = doc.add_object(Stream::new(dictionary! { "Type" => "Metadata" }, xmp_packet().into_bytes())); + let content = doc.add_object(Stream::new(dictionary! {}, b"0 0 m 10 10 l S".to_vec())); + let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => content }); + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }), + ); + let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp }); + let info = doc.add_object(dictionary! { "Author" => Object::string_literal(AUTHOR) }); + doc.trailer.set("Root", catalog); + doc.trailer.set("Info", info); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +mod png { + pub const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; +} diff --git a/crates/meta/tests/images.rs b/crates/meta/tests/images.rs new file mode 100644 index 0000000..39a27d1 --- /dev/null +++ b/crates/meta/tests/images.rs @@ -0,0 +1,219 @@ +mod common; + +use std::io::Cursor; + +use common::*; +use pictor_meta::{Group, Kind, MetaError, read, strip}; + +fn values(r: &pictor_meta::Report, g: Group) -> Vec { + r.items.iter().filter(|i| i.group == g).map(|i| i.value.clone()).collect() +} + +/// What an exiftool-style reader still sees: all EXIF fields in the file, through kamadak-exif. +fn exif_fields(bytes: &[u8]) -> Vec<(exif::Tag, String)> { + match exif::Reader::new().read_from_container(&mut Cursor::new(bytes)) { + Ok(e) => e.fields().map(|f| (f.tag, f.display_value().to_string())).collect(), + Err(_) => Vec::new(), + } +} + +fn assert_no_leaks(bytes: &[u8]) { + for needle in [XMP_NS, "Photoshop 3.0", AUTHOR, MODEL, SOFTWARE, COMMENT, "2024:05:01"] { + assert!(!contains(bytes, needle.as_bytes()), "stripped file still contains {needle:?}"); + } +} + +#[test] +fn jpeg_read_lists_gps_camera_author_software() { + let r = read(&photo_jpeg()).unwrap(); + assert_eq!(r.kind, Kind::Jpeg); + assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E"); + assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15"); + assert!(values(&r, Group::Author).contains(&AUTHOR.to_string())); + assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string())); + assert!(values(&r, Group::Iptc).contains(&AUTHOR.to_string()), "IPTC by-line: {:?}", r.items); + assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "XMP dc:creator: {:?}", r.items); + assert!(values(&r, Group::Comment).contains(&COMMENT.to_string())); + assert!(r.find(Group::Exif, "Orientation").is_some()); + assert!(!values(&r, Group::Dates).is_empty()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn jpeg_strip_keeps_only_orientation_and_pixels() { + let original = photo_jpeg(); + let s = strip(&original).unwrap(); + for g in [ + Group::Gps, + Group::Camera, + Group::Author, + Group::Software, + Group::Dates, + Group::Xmp, + Group::Iptc, + Group::Comment, + ] { + assert!(s.removed.contains(&g), "{g:?} not in removed {:?}", s.removed); + } + let fields = exif_fields(&s.bytes); + assert_eq!(fields.len(), 1, "only Orientation may remain: {fields:?}"); + assert_eq!(fields[0].0, exif::Tag::Orientation); + let exif = exif::Reader::new().read_from_container(&mut Cursor::new(&s.bytes)).unwrap(); + let o = exif.get_field(exif::Tag::Orientation, exif::In::PRIMARY).unwrap(); + assert_eq!(o.value.get_uint(0), Some(6)); + assert_no_leaks(&s.bytes); + assert!(!contains(&s.bytes, MAKE.as_bytes())); + + let before = image::load_from_memory(&original).unwrap().to_rgb8(); + let after = image::load_from_memory(&s.bytes).unwrap().to_rgb8(); + assert_eq!(before, after); + + // The stripped file reads clean, and stripping again changes nothing. + let r = read(&s.bytes).unwrap(); + assert_eq!(r.groups(), vec![Group::Exif], "{:?}", r.items); + assert_eq!(strip(&s.bytes).unwrap().bytes, s.bytes); +} + +#[test] +fn jpeg_without_orientation_gets_no_exif() { + let mut fields = photo_fields(); + fields.retain(|f| f.tag != exif::Tag::Orientation); + let original = jpeg_with(&[exif_app1(&exif_tiff(&fields))]); + let s = strip(&original).unwrap(); + assert!(!contains(&s.bytes, b"Exif\0")); + assert_eq!(s.bytes, plain_jpeg(), "an untouched JPEG body is byte-identical"); +} + +#[test] +fn jpeg_keeps_icc_and_adobe_drops_other_app_segments() { + let mut icc = b"ICC_PROFILE\0\x01\x01".to_vec(); + icc.extend_from_slice(&[7u8; 40]); + let adobe = b"Adobe\0\x64\0\0\0\0\x01".to_vec(); + let original = jpeg_with(&[ + segment(0xE2, &icc), + segment(0xEE, &adobe), + segment(0xEC, b"Ducky\0\x01\x02"), + segment(0xE2, b"MPF\0II*\0"), + segment(0xEF, b"secret"), + ]); + let r = read(&original).unwrap(); + assert!(r.items.iter().any(|i| i.name.contains("Ducky"))); + let s = strip(&original).unwrap(); + assert!(contains(&s.bytes, &icc)); + assert!(contains(&s.bytes, &adobe)); + assert!(!contains(&s.bytes, b"Ducky") && !contains(&s.bytes, b"MPF\0") && !contains(&s.bytes, b"secret")); + assert_eq!(s.removed, vec![Group::Other]); +} + +#[test] +fn jpeg_drops_data_after_end_of_image() { + let mut original = photo_jpeg(); + original.extend_from_slice(b"\xFF\xD8 hidden second image with GPS"); + let r = read(&original).unwrap(); + assert!(r.find(Group::Other, "Data after the end of the image").is_some()); + let s = strip(&original).unwrap(); + assert!(s.bytes.ends_with(&[0xFF, 0xD9])); + assert!(!contains(&s.bytes, b"hidden")); +} + +#[test] +fn png_strip_drops_text_exif_xmp_and_keeps_pixels() { + let original = photo_png(); + let r = read(&original).unwrap(); + assert_eq!(r.kind, Kind::Png); + assert_eq!(r.find(Group::Gps, "Location").unwrap().value, "50.08 N, 14.42 E"); + assert_eq!(r.find(Group::Author, "Author").unwrap().value, AUTHOR); + assert_eq!(r.find(Group::Software, "Software").unwrap().value, SOFTWARE); + assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string())); + assert_eq!(r.find(Group::Dates, "Last modified").unwrap().value, "2024-05-01 10:20:30"); + + let s = strip(&original).unwrap(); + assert_no_leaks(&s.bytes); + for chunk in [b"eXIf", b"tEXt", b"iTXt", b"tIME"] { + assert!(!contains(&s.bytes, chunk)); + } + assert!(exif_fields(&s.bytes).is_empty()); + assert!(read(&s.bytes).unwrap().items.is_empty()); + assert_eq!(s.bytes, plain_png(), "the remaining chunks are copied byte for byte"); + let before = image::load_from_memory(&original).unwrap().to_rgba8(); + let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8(); + assert_eq!(before, after); + for g in [Group::Gps, Group::Camera, Group::Author, Group::Software, Group::Xmp, Group::Dates] { + assert!(s.removed.contains(&g), "{g:?}"); + } +} + +#[test] +fn webp_strip_drops_exif_xmp_and_fixes_flags() { + let original = photo_webp(); + assert!(contains(&original, b"VP8X") && contains(&original, b"EXIF") && contains(&original, b"XMP ")); + let r = read(&original).unwrap(); + assert_eq!(r.kind, Kind::WebP); + assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15"); + assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string())); + + let s = strip(&original).unwrap(); + assert_no_leaks(&s.bytes); + assert!(!contains(&s.bytes, b"EXIF") && !contains(&s.bytes, b"XMP ")); + let vp8x = s.bytes.windows(4).position(|w| w == b"VP8X").expect("VP8X kept"); + let flags = s.bytes[vp8x + 8]; + assert_eq!(flags & 0x0C, 0, "EXIF and XMP flags cleared"); + let riff = u32::from_le_bytes(s.bytes[4..8].try_into().unwrap()) as usize; + assert_eq!(riff + 8, s.bytes.len()); + let before = image::load_from_memory(&original).unwrap().to_rgba8(); + let after = image::load_from_memory(&s.bytes).unwrap().to_rgba8(); + assert_eq!(before, after); + assert_eq!(before, rgba(10, 6), "lossless fixture"); +} + +#[test] +fn tiff_strip_removes_tags_and_keeps_pixels() { + let (original, img) = photo_tiff(); + let r = read(&original).unwrap(); + assert_eq!(r.kind, Kind::Tiff); + assert_eq!(r.find(Group::Camera, "Camera").unwrap().value, "Apple iPhone 15"); + assert!(values(&r, Group::Author).contains(&AUTHOR.to_string())); + assert!(values(&r, Group::Software).contains(&SOFTWARE.to_string())); + assert_eq!(image::load_from_memory(&original).unwrap().to_rgb8(), img); + + let s = strip(&original).unwrap(); + assert_no_leaks(&s.bytes); + assert!(!contains(&s.bytes, MAKE.as_bytes())); + assert_eq!(image::load_from_memory(&s.bytes).unwrap().to_rgb8(), img); + assert!(read(&s.bytes).unwrap().items.is_empty(), "{:?}", read(&s.bytes).unwrap().items); + for g in [Group::Camera, Group::Author, Group::Software] { + assert!(s.removed.contains(&g)); + } +} + +#[test] +fn gif_strip_keeps_every_frame() { + use image::AnimationDecoder; + use image::codecs::gif::GifDecoder; + let original = photo_gif(); + let r = read(&original).unwrap(); + assert_eq!(r.kind, Kind::Gif); + assert!(values(&r, Group::Comment).contains(&COMMENT.to_string())); + assert!(values(&r, Group::Xmp).contains(&AUTHOR.to_string()), "{:?}", r.items); + + let s = strip(&original).unwrap(); + assert_no_leaks(&s.bytes); + assert!(contains(&s.bytes, b"NETSCAPE2.0"), "looping kept"); + let frames = |b: &[u8]| -> Vec { + let d = GifDecoder::new(Cursor::new(b.to_vec())).unwrap(); + d.into_frames().collect_frames().unwrap().into_iter().map(|f| f.into_buffer()).collect() + }; + let (a, b) = (frames(&original), frames(&s.bytes)); + assert_eq!(a.len(), 2); + assert_eq!(a, b); + assert_eq!(s.removed, vec![Group::Xmp, Group::Comment]); +} + +#[test] +fn unknown_and_empty_inputs_are_typed_errors() { + assert_eq!(read(&[]), Err(MetaError::Empty)); + assert!(matches!(read(b"BM\0\0 not supported"), Err(MetaError::Unsupported(_)))); + assert!(matches!(strip(b"hello world"), Err(MetaError::Unsupported(_)))); + let small = pictor_meta::Limits { max_input_bytes: 10, ..Default::default() }; + assert!(matches!(pictor_meta::read_with(&photo_jpeg(), &small), Err(MetaError::TooLarge { .. }))); +} diff --git a/crates/meta/tests/pdf.rs b/crates/meta/tests/pdf.rs new file mode 100644 index 0000000..011a8d0 --- /dev/null +++ b/crates/meta/tests/pdf.rs @@ -0,0 +1,180 @@ +mod common; + +use common::*; +use lopdf::{Document, Object, Stream, StringFormat, dictionary}; +use pictor_meta::{Group, Kind, MetaError, read, strip}; + +const PDF_AUTHOR: &str = "Jan Novák"; + +fn utf16be(s: &str) -> Vec { + let mut v = vec![0xFE, 0xFF]; + s.encode_utf16().for_each(|u| v.extend_from_slice(&u.to_be_bytes())); + v +} + +fn xmp_for_pdf() -> String { + xmp_packet().replace(AUTHOR, PDF_AUTHOR) +} + +/// One page drawing one image XObject; /Info with a UTF-16BE author; XMP on the catalog and on the image; +/// /PieceInfo on the page. +fn build(modern: bool) -> Vec { + let mut doc = Document::with_version("1.5"); + let pages_id = doc.new_object_id(); + let meta = || dictionary! { "Type" => "Metadata", "Subtype" => "XML" }; + let xmp_doc = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false)); + let xmp_img = doc.add_object(Stream::new(meta(), xmp_for_pdf().into_bytes()).with_compression(false)); + let img = doc.add_object(Stream::new( + dictionary! { + "Type" => "XObject", "Subtype" => "Image", "Width" => 2, "Height" => 2, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Metadata" => xmp_img, + }, + vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255], + )); + let content = doc.add_object(Stream::new(dictionary! {}, b"q 100 0 0 100 50 50 cm /Im1 Do Q".to_vec())); + let page = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => content, + "Resources" => dictionary! { "XObject" => dictionary! { "Im1" => img } }, + "MediaBox" => vec![0.into(), 0.into(), 200.into(), 200.into()], + "PieceInfo" => dictionary! { "Illustrator" => dictionary! { "Private" => Object::string_literal("secret private") } }, + }); + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }), + ); + let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp_doc }); + let info = doc.add_object(dictionary! { + "Author" => Object::String(utf16be(PDF_AUTHOR), StringFormat::Hexadecimal), + "Producer" => Object::string_literal("Fixture Producer 1.0"), + "Creator" => Object::string_literal(SOFTWARE), + "Title" => Object::string_literal("Secret plans"), + "CreationDate" => Object::string_literal("D:20240501102030+02'00'"), + "Department" => Object::string_literal("Custom department"), + }); + doc.trailer.set("Root", catalog); + doc.trailer.set("Info", info); + let mut out = Vec::new(); + if modern { + doc.save_modern(&mut out).unwrap() + } else { + doc.save_to(&mut out).unwrap() + } + out +} + +fn any_metadata_key(o: &Object) -> bool { + match o { + Object::Dictionary(d) => { + d.has(b"Metadata") || d.has(b"PieceInfo") || d.iter().any(|(_, v)| any_metadata_key(v)) + } + Object::Stream(s) => { + s.dict.has(b"Metadata") || s.dict.has_type(b"Metadata") || s.dict.iter().any(|(_, v)| any_metadata_key(v)) + } + Object::Array(a) => a.iter().any(any_metadata_key), + _ => false, + } +} + +fn first_page_content(bytes: &[u8]) -> Vec { + let doc = Document::load_mem(bytes).unwrap(); + let page = *doc.get_pages().values().next().unwrap(); + doc.get_page_content(page) +} + +fn assert_clean(bytes: &[u8]) { + let doc = Document::load_mem(bytes).unwrap(); + assert!(!doc.trailer.has(b"Info"), "trailer /Info removed"); + for (id, o) in &doc.objects { + assert!(!any_metadata_key(o), "object {id:?} still has metadata: {o:?}"); + } + let lower = String::from_utf8_lossy(bytes).to_lowercase(); + for needle in [ + "Novák", + "Fixture Producer", + "Secret plans", + "Custom department", + "secret private", + XMP_NS, + "adobe:ns:meta", + SOFTWARE, + ] { + assert!(!contains(bytes, needle.as_bytes()), "raw bytes still contain {needle:?}"); + } + assert!(!contains(bytes, &utf16be("Jan")[2..]), "UTF-16 author"); + assert!(!lower.contains("feff004a"), "hex UTF-16 author"); +} + +#[test] +fn pdf_read_lists_info_and_xmp() { + let original = build(false); + assert!(contains(&original, XMP_NS.as_bytes()), "fixture has XMP"); + let r = read(&original).unwrap(); + assert_eq!(r.kind, Kind::Pdf); + assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR); + assert_eq!(r.find(Group::Software, "Producer").unwrap().value, "Fixture Producer 1.0"); + assert_eq!(r.find(Group::Software, "Creator").unwrap().value, SOFTWARE); + assert_eq!(r.find(Group::PdfInfo, "Title").unwrap().value, "Secret plans"); + assert_eq!(r.find(Group::PdfInfo, "Department").unwrap().value, "Custom department"); + assert_eq!(r.find(Group::Dates, "CreationDate").unwrap().value, "2024-05-01 10:20:30 +02:00"); + assert_eq!(r.find(Group::PdfXmp, "Creator (dc:creator)").unwrap().value, PDF_AUTHOR); + assert_eq!(r.find(Group::PdfXmp, "Creator tool (xmp:CreatorTool)").unwrap().value, SOFTWARE); + assert_eq!(r.find(Group::PdfXmp, "XMP on pages, images or other objects").unwrap().value, "1 objects"); + assert!(r.find(Group::Other, "Private application data (PieceInfo)").is_some()); +} + +#[test] +fn pdf_strip_removes_info_and_every_xmp_stream() { + let original = build(false); + let s = strip(&original).unwrap(); + assert_clean(&s.bytes); + assert_eq!(first_page_content(&original), first_page_content(&s.bytes)); + let doc = Document::load_mem(&s.bytes).unwrap(); + let images = + doc.objects.values().filter(|o| matches!(o, Object::Stream(st) if st.dict.has_type(b"XObject"))).count(); + assert_eq!(images, 1, "the image is kept"); + assert!(read(&s.bytes).unwrap().items.is_empty()); + for g in [Group::Author, Group::Software, Group::Dates, Group::PdfInfo, Group::PdfXmp, Group::Other] { + assert!(s.removed.contains(&g), "{g:?}"); + } +} + +#[test] +fn pdf_with_object_streams_is_stripped_too() { + let original = build(true); + let r = read(&original).unwrap(); + assert_eq!(r.find(Group::Author, "Author").unwrap().value, PDF_AUTHOR); + let s = strip(&original).unwrap(); + assert_clean(&s.bytes); + assert_eq!(first_page_content(&original), first_page_content(&s.bytes)); +} + +#[test] +fn encrypted_pdf_is_refused() { + let mut doc = Document::load_mem(&build(false)).unwrap(); + let enc = doc.add_object(dictionary! { + "Filter" => "Standard", "V" => 1, "R" => 2, "Length" => 40, "P" => -4, + "O" => Object::String(vec![0x11; 32], StringFormat::Hexadecimal), + "U" => Object::String(vec![0x22; 32], StringFormat::Hexadecimal), + }); + doc.trailer.set("Encrypt", enc); + doc.trailer.set( + "ID", + vec![ + Object::String(vec![1; 16], StringFormat::Hexadecimal), + Object::String(vec![1; 16], StringFormat::Hexadecimal), + ], + ); + let mut bytes = Vec::new(); + doc.save_to(&mut bytes).unwrap(); + assert_eq!(read(&bytes), Err(MetaError::Encrypted)); + assert_eq!(strip(&bytes), Err(MetaError::Encrypted)); + assert_eq!(MetaError::Encrypted.to_string(), "This PDF is password-protected. Unlock it first."); +} + +#[test] +fn unparseable_pdf_is_a_typed_error() { + for bytes in [&b"%PDF-1.7\n1 0 obj << /Type /Catalog"[..], b"%PDF-", b"%PDF-1.4\n%%EOF\n"] { + assert!(matches!(read(bytes), Err(MetaError::Damaged(_))), "{:?}", read(bytes)); + assert!(matches!(strip(bytes), Err(MetaError::Damaged(_)))); + } +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 4796f4e..de4ca9d 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,88 +1,88 @@ -# Dependencies and their licences - -Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. -The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the -OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. - -## The allowed set, as checked by `scripts/deps.mjs` - -| Licence (SPDX) | Why it is allowed | -| :-- | :-- | -| MIT, MIT-0 | named in the brief | -| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | -| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | -| Zlib | named in the brief | -| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | -| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | -| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | -| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | - -An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the -script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). - -## Direct dependencies - -| Crate | Version | Licence | Used by | For | -| :-- | :-- | :-- | :-- | :-- | -| thiserror | 2 | MIT OR Apache-2.0 | all | error types | -| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | -| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | -| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | -| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | -| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | -| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | -| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | -| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | -| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | -| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | -| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | -| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | -| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | -| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | -| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | - -## Binaries (fetched, never in git) - -| Binary | Licence | Fetched by | -| :-- | :-- | :-- | -| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | - -### pdfium - -Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 -`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches -pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside -the dll (the app's installer copies them). Read from those files on 2026-11-16: - -| Component inside pdfium.dll | Licence | In the allowed set? | -| :-- | :-- | :-- | -| the binary build (bblanchon/pdfium-binaries) | MIT | yes | -| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | -| abseil, highway | Apache-2.0 | yes | -| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | -| fast_float, simdutf | MIT | yes | -| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | -| OpenJPEG | BSD-2-Clause | yes | -| zlib | Zlib | yes | -| HarfBuzz | "Old MIT" | yes (MIT family) | -| ICU | Unicode-3.0 | **interpretation** (see above) | -| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | -| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | -| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | - -None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked -"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF -support depends on pdfium, which the brief chose). - -## OS codecs (not bundled) - -| Codec | Provided by | Used for | -| :-- | :-- | :-- | -| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | - -## Every crate in Cargo.lock - -Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. - - - +# Dependencies and their licences + +Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. +The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the +OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. + +## The allowed set, as checked by `scripts/deps.mjs` + +| Licence (SPDX) | Why it is allowed | +| :-- | :-- | +| MIT, MIT-0 | named in the brief | +| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | +| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | +| Zlib | named in the brief | +| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | +| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | +| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | +| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | + +An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the +script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). + +## Direct dependencies + +| Crate | Version | Licence | Used by | For | +| :-- | :-- | :-- | :-- | :-- | +| thiserror | 2 | MIT OR Apache-2.0 | all | error types | +| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | +| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | +| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | +| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | +| img-parts | 0.4 (dev) | MIT OR Apache-2.0 | meta tests | building PNG and WebP fixtures (meta walks the containers with its own bounds-checked parsers) | +| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | +| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | +| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | +| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | +| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | +| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | +| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | +| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | + +## Binaries (fetched, never in git) + +| Binary | Licence | Fetched by | +| :-- | :-- | :-- | +| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | + +### pdfium + +Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 +`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches +pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside +the dll (the app's installer copies them). Read from those files on 2026-11-16: + +| Component inside pdfium.dll | Licence | In the allowed set? | +| :-- | :-- | :-- | +| the binary build (bblanchon/pdfium-binaries) | MIT | yes | +| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | +| abseil, highway | Apache-2.0 | yes | +| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | +| fast_float, simdutf | MIT | yes | +| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | +| OpenJPEG | BSD-2-Clause | yes | +| zlib | Zlib | yes | +| HarfBuzz | "Old MIT" | yes (MIT family) | +| ICU | Unicode-3.0 | **interpretation** (see above) | +| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | +| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | +| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | + +None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked +"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF +support depends on pdfium, which the brief chose). + +## OS codecs (not bundled) + +| Codec | Provided by | Used for | +| :-- | :-- | :-- | +| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | + +## Every crate in Cargo.lock + +Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. + + + From ce1e8785d9ceeec0beda975b86277ad2f2edd187 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:30:42 +0100 Subject: [PATCH 06/13] [raster] Toolbox: probe/decode with caps, convert, crop, rotate, resize, presets, compress to size, HEIC via WIC --- crates/raster/Cargo.toml | 18 ++ crates/raster/src/decode.rs | 236 ++++++++++++++++++++ crates/raster/src/encode.rs | 169 +++++++++++++++ crates/raster/src/error.rs | 85 ++++++++ crates/raster/src/format.rs | 151 +++++++++++++ crates/raster/src/isobmff.rs | 208 ++++++++++++++++++ crates/raster/src/lib.rs | 76 +++++++ crates/raster/src/ops.rs | 106 +++++++++ crates/raster/src/preset.rs | 168 +++++++++++++++ crates/raster/src/wic.rs | 347 ++++++++++++++++++++++++++++++ crates/raster/tests/common/mod.rs | 311 ++++++++++++++++++++++++++ crates/raster/tests/heif.rs | 58 +++++ crates/raster/tests/hostile.rs | 190 ++++++++++++++++ crates/raster/tests/roundtrip.rs | 118 ++++++++++ crates/raster/tests/transform.rs | 152 +++++++++++++ docs/DEPENDENCIES.md | 2 +- 16 files changed, 2394 insertions(+), 1 deletion(-) create mode 100644 crates/raster/Cargo.toml create mode 100644 crates/raster/src/decode.rs create mode 100644 crates/raster/src/encode.rs create mode 100644 crates/raster/src/error.rs create mode 100644 crates/raster/src/format.rs create mode 100644 crates/raster/src/isobmff.rs create mode 100644 crates/raster/src/lib.rs create mode 100644 crates/raster/src/ops.rs create mode 100644 crates/raster/src/preset.rs create mode 100644 crates/raster/src/wic.rs create mode 100644 crates/raster/tests/common/mod.rs create mode 100644 crates/raster/tests/heif.rs create mode 100644 crates/raster/tests/hostile.rs create mode 100644 crates/raster/tests/roundtrip.rs create mode 100644 crates/raster/tests/transform.rs diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml new file mode 100644 index 0000000..2c5e78d --- /dev/null +++ b/crates/raster/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "pictor-raster" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_Com", "Win32_Graphics_Imaging", "Win32_UI_Shell_PropertiesSystem", "Win32_System_Variant", "Win32_System_Com_StructuredStorage", "Win32_Media_MediaFoundation"] } + +[dev-dependencies] +proptest.workspace = true diff --git a/crates/raster/src/decode.rs b/crates/raster/src/decode.rs new file mode 100644 index 0000000..f71abc2 --- /dev/null +++ b/crates/raster/src/decode.rs @@ -0,0 +1,236 @@ +use std::io::Cursor; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use image::metadata::Orientation; +use image::{DynamicImage, ImageDecoder, ImageError, ImageReader}; +use serde::{Deserialize, Serialize}; + +use crate::error::{RasterError, Result}; +use crate::{Format, Limits, isobmff}; + +/// What the headers say, read without decoding pixels. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Probe { + pub format: Format, + /// Stored size, before the EXIF orientation is applied (`decode` applies it, so a portrait photo + /// tagged with orientation 6 probes as landscape and decodes as portrait). + pub width: u32, + pub height: u32, + pub has_alpha: bool, + /// Number of frames or icon entries when the header tells it cheaply; `None` when unknown. + pub frames: Option, +} + +/// Read the header only. Refuses empty, oversized and unknown input, but reports a pixel bomb's size +/// rather than refusing it (that is `decode`'s job), so the Toolbox can say how large it is. +pub fn probe(bytes: &[u8], limits: &Limits) -> Result { + let format = check_input(bytes, limits)?; + if format.is_heif_family() { + let info = isobmff::info(bytes) + .ok_or_else(|| RasterError::Corrupt { format, detail: "no readable ispe property".into() })?; + return Ok(Probe { format, width: info.width, height: info.height, has_alpha: info.has_alpha, frames: None }); + } + guarded(format, || { + let decoder = open(bytes, format, header_limits(limits))?; + let (width, height) = decoder.dimensions(); + let has_alpha = decoder.color_type().has_alpha(); + Ok(Probe { format, width, height, has_alpha, frames: count_frames(format, bytes) }) + }) +} + +/// Decode to pixels with every cap applied, then apply the EXIF orientation. +/// +/// Order: input size, format sniff, header-only pixel count (refused above `max_pixels` before any pixel +/// buffer exists), decoder with `image`'s own limits (dimensions and `max_alloc`), output-buffer size check, +/// decode, orientation. HEIC/AVIF go to the Windows codec (see `wic`), elsewhere they are refused. +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + let format = check_input(bytes, limits)?; + if format.is_heif_family() { + return decode_heif(bytes, format, limits); + } + guarded(format, || { + let (width, height) = open(bytes, format, header_limits(limits))?.dimensions(); + check_pixels(width, height, limits)?; + + let mut caps = header_limits(limits); + caps.max_image_width = Some(width); + caps.max_image_height = Some(height); + let mut decoder = open(bytes, format, caps)?; + let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); + let copies = match orientation { + Orientation::Rotate90 + | Orientation::Rotate270 + | Orientation::Rotate90FlipH + | Orientation::Rotate270FlipH => 2, + _ => 1, + }; + let needed = decoder.total_bytes().saturating_mul(copies); + if needed > limits.max_alloc { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + let mut img = DynamicImage::from_decoder(decoder).map_err(|e| map_image_error(format, e, limits))?; + img.apply_orientation(orientation); + Ok(img) + }) +} + +fn decode_heif(bytes: &[u8], format: Format, limits: &Limits) -> Result { + if let Some(info) = isobmff::info(bytes) { + check_pixels(info.width, info.height, limits)?; + } + #[cfg(windows)] + { + crate::wic::decode(bytes, format, limits) + } + #[cfg(not(windows))] + { + let _ = limits; + Err(match format { + Format::Avif => RasterError::AvifCodecMissing, + _ => RasterError::HeifCodecMissing { needs_heif: true }, + }) + } +} + +pub(crate) fn check_input(bytes: &[u8], limits: &Limits) -> Result { + if bytes.is_empty() { + return Err(RasterError::Empty); + } + let len = bytes.len() as u64; + if len > limits.max_input_bytes { + return Err(RasterError::InputTooLarge { bytes: len, limit: limits.max_input_bytes }); + } + Format::sniff(bytes).ok_or(RasterError::UnknownFormat) +} + +pub(crate) fn check_pixels(width: u32, height: u32, limits: &Limits) -> Result<()> { + let pixels = u64::from(width) * u64::from(height); + if pixels > limits.max_pixels { + return Err(RasterError::TooManyPixels { width: width.into(), height: height.into() }); + } + if pixels == 0 { + return Err(RasterError::InvalidSize); + } + Ok(()) +} + +fn header_limits(limits: &Limits) -> image::Limits { + let mut l = image::Limits::default(); + l.max_alloc = Some(limits.max_alloc); + l +} + +fn open(bytes: &[u8], format: Format, caps: image::Limits) -> Result { + let image_format = format.to_image().ok_or(RasterError::UnknownFormat)?; + let mut reader = ImageReader::with_format(Cursor::new(bytes), image_format); + let max_alloc = caps.max_alloc.unwrap_or(u64::MAX); + reader.limits(caps); + reader.into_decoder().map_err(|e| map_image_error_alloc(format, e, max_alloc)) +} + +/// Third-party decoders are not ours to prove panic-free; a panic on hostile bytes becomes `Corrupt`. +pub(crate) fn guarded(format: Format, f: impl FnOnce() -> Result) -> Result { + catch_unwind(AssertUnwindSafe(f)) + .unwrap_or_else(|_| Err(RasterError::Corrupt { format, detail: "the decoder panicked".into() })) +} + +fn map_image_error(format: Format, e: ImageError, limits: &Limits) -> RasterError { + map_image_error_alloc(format, e, limits.max_alloc) +} + +fn map_image_error_alloc(format: Format, e: ImageError, max_alloc: u64) -> RasterError { + match e { + ImageError::Limits(_) => RasterError::TooMuchMemory { limit: max_alloc }, + ImageError::Unsupported(u) => RasterError::UnsupportedFeature { format, detail: u.to_string() }, + other => RasterError::Corrupt { format, detail: other.to_string() }, + } +} + +/// Frame counts that the container states cheaply; never decodes image data. +fn count_frames(format: Format, bytes: &[u8]) -> Option { + match format { + Format::Png => Some(png_frames(bytes).unwrap_or(1)), + Format::Gif => gif_frames(bytes), + Format::Ico => Some(u32::from(u16::from_le_bytes([*bytes.get(4)?, *bytes.get(5)?]))), + Format::WebP => webp_frames(bytes), + Format::Jpeg | Format::Bmp => Some(1), + Format::Tiff | Format::Heif | Format::Avif => None, + } +} + +/// APNG `acTL.num_frames`, if present before the first IDAT. +fn png_frames(bytes: &[u8]) -> Option { + let mut pos = 8usize; + for _ in 0..10_000 { + let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(pos + 4..pos + 8)?; + if kind == b"acTL" { + return Some(u32::from_be_bytes(bytes.get(pos + 8..pos + 12)?.try_into().ok()?)); + } + if kind == b"IDAT" { + return None; + } + pos = pos.checked_add(12)?.checked_add(len)?; + } + None +} + +/// Walk GIF blocks, skipping LZW data by its sub-block lengths, counting image descriptors. +fn gif_frames(bytes: &[u8]) -> Option { + let flags = *bytes.get(10)?; + let mut pos = 13usize; + if flags & 0x80 != 0 { + pos += 3 << ((flags & 7) + 1); + } + let skip_sub_blocks = |mut p: usize| -> Option { + loop { + let n = usize::from(*bytes.get(p)?); + p += 1; + if n == 0 { + return Some(p); + } + p += n; + } + }; + let mut frames = 0u32; + while frames < 1_000_000 { + match bytes.get(pos) { + Some(0x2C) => { + let local = *bytes.get(pos + 9)?; + pos += 10; + if local & 0x80 != 0 { + pos += 3 << ((local & 7) + 1); + } + pos = skip_sub_blocks(pos + 1)?; // LZW minimum code size, then data + frames += 1; + } + Some(0x21) => pos = skip_sub_blocks(pos + 2)?, + Some(0x3B) => return Some(frames), + _ => return (frames > 0).then_some(frames), + } + } + Some(frames) +} + +/// 1 for a still WebP, the number of ANMF chunks for an animated one. +fn webp_frames(bytes: &[u8]) -> Option { + if bytes.get(12..16)? != b"VP8X" { + return Some(1); + } + let animated = bytes.get(20)? & 0x02 != 0; + if !animated { + return Some(1); + } + let mut pos = 12usize; + let mut frames = 0u32; + for _ in 0..1_000_000 { + let Some(kind) = bytes.get(pos..pos + 4) else { break }; + let Some(len) = bytes.get(pos + 4..pos + 8) else { break }; + let len = u32::from_le_bytes(len.try_into().ok()?) as usize; + if kind == b"ANMF" { + frames += 1; + } + pos = pos.checked_add(8)?.checked_add(len)?.checked_add(len & 1)?; + } + Some(frames) +} diff --git a/crates/raster/src/encode.rs b/crates/raster/src/encode.rs new file mode 100644 index 0000000..eeeb182 --- /dev/null +++ b/crates/raster/src/encode.rs @@ -0,0 +1,169 @@ +use std::borrow::Cow; +use std::io::Cursor; + +use image::codecs::bmp::BmpEncoder; +use image::codecs::gif::GifEncoder; +use image::codecs::ico::{IcoEncoder, IcoFrame}; +use image::codecs::jpeg::JpegEncoder; +use image::codecs::png::PngEncoder; +use image::codecs::tiff::TiffEncoder; +use image::codecs::webp::WebPEncoder; +use image::imageops::FilterType; +use image::{DynamicImage, ExtendedColorType, GenericImageView, ImageError, Rgb, RgbImage, RgbaImage}; +use serde::{Deserialize, Serialize}; + +use crate::Format; +use crate::error::{RasterError, Result}; + +/// Encoder settings. Only JPEG is lossy: the WebP encoder in `image` 0.25 writes **lossless** WebP only. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct EncodeOptions { + /// 1..=100 (clamped). + pub jpeg_quality: u8, + /// JPEG has no alpha: transparent pixels are composited onto this colour. + pub jpeg_background: [u8; 3], +} + +impl Default for EncodeOptions { + fn default() -> Self { + Self { jpeg_quality: 88, jpeg_background: [255, 255, 255] } + } +} + +/// The ICO sizes written besides the largest one (each only when smaller than it). +const ICO_SMALL_SIZES: [u32; 3] = [48, 32, 16]; + +/// Encode `img` as `format`. +/// +/// - JPEG: alpha is flattened onto `jpeg_background` (white by default); grey stays grey. +/// - WebP: lossless (the only mode `image` 0.25 can write). +/// - GIF: a single frame, palette by NeuQuant. +/// - ICO: fitted into 256 × 256 (never enlarged), centred on a transparent square, plus 48/32/16 px entries, +/// each stored as PNG. +/// - HEIC/AVIF: [`RasterError::CannotWrite`]. +pub fn encode(img: &DynamicImage, format: Format, options: &EncodeOptions) -> Result> { + if !format.can_encode() { + return Err(RasterError::CannotWrite { format }); + } + let (w, h) = img.dimensions(); + if w == 0 || h == 0 { + return Err(RasterError::InvalidSize); + } + let mut out = Vec::new(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> std::result::Result<(), ImageError> { + match format { + Format::Png => for_png_tiff(img, false).write_with_encoder(PngEncoder::new(&mut out)), + Format::Tiff => { + let mut cursor = Cursor::new(&mut out); + for_png_tiff(img, true).write_with_encoder(TiffEncoder::new(&mut cursor)) + } + Format::Jpeg => { + let flat = flatten(img, options.jpeg_background); + let quality = options.jpeg_quality.clamp(1, 100); + flat.write_with_encoder(JpegEncoder::new_with_quality(&mut out, quality)) + } + Format::WebP => to_8bit(img).write_with_encoder(WebPEncoder::new_lossless(&mut out)), + Format::Bmp => to_8bit(img).write_with_encoder(BmpEncoder::new(&mut out)), + Format::Gif => { + let rgba = img.to_rgba8(); + let mut encoder = GifEncoder::new_with_speed(&mut out, 10); + encoder.encode(rgba.as_raw(), w, h, ExtendedColorType::Rgba8) + } + Format::Ico => encode_ico(img, &mut out), + Format::Heif | Format::Avif => unreachable!("checked above"), + } + })); + match result { + Ok(Ok(())) => Ok(out), + Ok(Err(e)) => Err(RasterError::Encode { format, detail: e.to_string() }), + Err(_) => Err(RasterError::Encode { format, detail: "the encoder panicked".into() }), + } +} + +/// 8/16-bit grey or colour as is; everything else to 8-bit. TIFF has no grey+alpha in `image`'s encoder. +fn for_png_tiff(img: &DynamicImage, tiff: bool) -> Cow<'_, DynamicImage> { + match img { + DynamicImage::ImageLuma8(_) + | DynamicImage::ImageRgb8(_) + | DynamicImage::ImageRgba8(_) + | DynamicImage::ImageLuma16(_) + | DynamicImage::ImageRgb16(_) + | DynamicImage::ImageRgba16(_) => Cow::Borrowed(img), + DynamicImage::ImageLumaA8(_) | DynamicImage::ImageLumaA16(_) if !tiff => Cow::Borrowed(img), + DynamicImage::ImageLumaA16(_) => Cow::Owned(DynamicImage::ImageRgba16(img.to_rgba16())), + _ => to_8bit(img), + } +} + +fn to_8bit(img: &DynamicImage) -> Cow<'_, DynamicImage> { + match img { + DynamicImage::ImageLuma8(_) + | DynamicImage::ImageLumaA8(_) + | DynamicImage::ImageRgb8(_) + | DynamicImage::ImageRgba8(_) => Cow::Borrowed(img), + DynamicImage::ImageLuma16(_) => Cow::Owned(DynamicImage::ImageLuma8(img.to_luma8())), + DynamicImage::ImageLumaA16(_) => Cow::Owned(DynamicImage::ImageLumaA8(img.to_luma_alpha8())), + _ if img.color().has_alpha() => Cow::Owned(DynamicImage::ImageRgba8(img.to_rgba8())), + _ => Cow::Owned(DynamicImage::ImageRgb8(img.to_rgb8())), + } +} + +/// Opaque 8-bit image for JPEG: alpha composited onto `bg`. +fn flatten(img: &DynamicImage, bg: [u8; 3]) -> DynamicImage { + if !img.color().has_alpha() { + return match img { + DynamicImage::ImageLuma8(_) => img.clone(), + DynamicImage::ImageLuma16(_) => DynamicImage::ImageLuma8(img.to_luma8()), + _ => DynamicImage::ImageRgb8(img.to_rgb8()), + }; + } + let rgba = img.to_rgba8(); + let out = RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| { + let [r, g, b, a] = rgba.get_pixel(x, y).0; + let a = u32::from(a); + let mix = |c: u8, bg: u8| ((u32::from(c) * a + u32::from(bg) * (255 - a) + 127) / 255) as u8; + Rgb([mix(r, bg[0]), mix(g, bg[1]), mix(b, bg[2])]) + }); + DynamicImage::ImageRgb8(out) +} + +fn encode_ico(img: &DynamicImage, out: &mut Vec) -> std::result::Result<(), ImageError> { + let (w, h) = img.dimensions(); + let long = w.max(h); + let side = long.min(256); + let fitted = if long > 256 { + let (nw, nh) = fit_within(w, h, 256); + img.resize_exact(nw, nh, FilterType::Lanczos3).to_rgba8() + } else { + img.to_rgba8() + }; + let mut square = RgbaImage::new(side, side); + let (dx, dy) = ((side - fitted.width()) / 2, (side - fitted.height()) / 2); + image::imageops::replace(&mut square, &fitted, i64::from(dx), i64::from(dy)); + + let mut sizes = vec![side]; + sizes.extend(ICO_SMALL_SIZES.iter().copied().filter(|&s| s < side)); + let mut frames = Vec::with_capacity(sizes.len()); + for s in sizes { + let frame = if s == side { + IcoFrame::as_png(square.as_raw(), s, s, ExtendedColorType::Rgba8)? + } else { + let small = image::imageops::resize(&square, s, s, FilterType::Lanczos3); + IcoFrame::as_png(small.as_raw(), s, s, ExtendedColorType::Rgba8)? + }; + frames.push(frame); + } + IcoEncoder::new(out).encode_images(&frames) +} + +/// The largest size with the same aspect ratio whose long edge is `long_edge` (each side at least 1). +pub(crate) fn fit_within(w: u32, h: u32, long_edge: u32) -> (u32, u32) { + let long = w.max(h); + if long <= long_edge { + return (w, h); + } + let scale = f64::from(long_edge) / f64::from(long); + let side = |v: u32| ((f64::from(v) * scale).round() as u32).clamp(1, long_edge); + if w >= h { (long_edge, side(h)) } else { (side(w), long_edge) } +} diff --git a/crates/raster/src/error.rs b/crates/raster/src/error.rs new file mode 100644 index 0000000..de6ae2a --- /dev/null +++ b/crates/raster/src/error.rs @@ -0,0 +1,85 @@ +use crate::Format; + +/// Every failure of this crate. `Display` is a plain-English sentence the Toolbox shows as is; +/// technical detail, when there is any, is kept in a field for the log. +#[derive(Debug, thiserror::Error)] +pub enum RasterError { + #[error("The file is empty.")] + Empty, + + #[error("This file is too large ({}; the limit is {}).", mb(*bytes), mb(*limit))] + InputTooLarge { bytes: u64, limit: u64 }, + + #[error("This file is not an image Pictor can open (PNG, JPG, WebP, BMP, GIF, TIFF, ICO or HEIC).")] + UnknownFormat, + + #[error("This image is too large ({width} × {height} pixels).")] + TooManyPixels { width: u64, height: u64 }, + + #[error("This image would need more memory than the {} allowed.", mb(*limit))] + TooMuchMemory { limit: u64 }, + + #[error("This {} file is damaged or incomplete.", format.name())] + Corrupt { format: Format, detail: String }, + + #[error("This {} file uses a feature Pictor cannot read.", format.name())] + UnsupportedFeature { format: Format, detail: String }, + + #[error("Pictor cannot save {} images. Choose PNG or JPG instead.", format.name())] + CannotWrite { format: Format }, + + #[error("This image could not be saved as {}.", format.name())] + Encode { format: Format, detail: String }, + + /// The HEIF/HEIC container codec or the HEVC decoder is not installed. Windows needs two Microsoft Store + /// extensions for iPhone photos: "HEIF Image Extensions" (free, https://apps.microsoft.com/detail/9PMMSR1CGPWG, + /// the container) and "HEVC Video Extensions" ($0.99, https://apps.microsoft.com/detail/9NMZLZ57R3T7, the + /// image data itself). `needs_heif` is true when the container codec is missing too. + #[error("{}", heif_message(*needs_heif))] + HeifCodecMissing { needs_heif: bool }, + + /// AVIF goes through the same HEIF container codec plus Microsoft's AV1 decoder. + #[error( + "This AVIF image needs Microsoft's \"AV1 Video Extension\" and \"HEIF Image Extensions\" from the \ + Microsoft Store. Install them, then try again." + )] + AvifCodecMissing, + + /// The Windows codec failed for another reason. + #[error("Windows could not open this photo (error {code:#010X}).")] + Os { code: u32, detail: String }, + + #[error("The crop area is outside the image.")] + InvalidCrop, + + #[error("The requested size is not valid.")] + InvalidSize, + + #[error("The image cannot be made smaller than {} even at the lowest quality and size.", size(*smallest_bytes))] + CannotReachTarget { smallest_bytes: u64 }, + + #[error("The target size must be larger than zero.")] + InvalidTarget, +} + +pub type Result = std::result::Result; + +fn heif_message(needs_heif: bool) -> &'static str { + if needs_heif { + "This photo needs two Microsoft codecs that Windows does not have yet. Install \ + \"HEIF Image Extensions\" (https://apps.microsoft.com/detail/9PMMSR1CGPWG) and \"HEVC Video Extensions\" \ + (https://apps.microsoft.com/detail/9NMZLZ57R3T7) from the Microsoft Store, then try again." + } else { + "This photo needs Microsoft's HEVC codec, which Windows does not have yet. Install \"HEVC Video \ + Extensions\" from the Microsoft Store (https://apps.microsoft.com/detail/9NMZLZ57R3T7), then try again." + } +} + +fn mb(bytes: u64) -> String { + let mib = bytes as f64 / (1024.0 * 1024.0); + if mib >= 10.0 { format!("{mib:.0} MB") } else { format!("{mib:.1} MB") } +} + +fn size(bytes: u64) -> String { + if bytes >= 1024 * 1024 { mb(bytes) } else { format!("{} kB", bytes.div_ceil(1024)) } +} diff --git a/crates/raster/src/format.rs b/crates/raster/src/format.rs new file mode 100644 index 0000000..0550ffe --- /dev/null +++ b/crates/raster/src/format.rs @@ -0,0 +1,151 @@ +use serde::{Deserialize, Serialize}; + +use crate::isobmff; + +/// The image formats the Toolbox knows. `Heif` and `Avif` share the ISO-BMFF/HEIF container and are read +/// only through the Windows codec; neither can be written. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Format { + Png, + Jpeg, + WebP, + Bmp, + Gif, + Tiff, + Ico, + /// HEIF/HEIC (brands heic, heix, hevc, heim, heis, hevm, hevs, mif1, msf1). + Heif, + /// AVIF (brands avif, avis): HEIF container with AV1 data. + Avif, +} + +impl Format { + /// Every format, in the order the Toolbox lists them. + pub const ALL: [Format; 9] = [ + Format::Png, + Format::Jpeg, + Format::WebP, + Format::Bmp, + Format::Gif, + Format::Tiff, + Format::Ico, + Format::Heif, + Format::Avif, + ]; + + /// Identify a format by its magic bytes only (never by the file name). + pub fn sniff(bytes: &[u8]) -> Option { + let starts = |sig: &[u8]| bytes.starts_with(sig); + if starts(b"\x89PNG\r\n\x1a\n") { + Some(Format::Png) + } else if starts(&[0xFF, 0xD8, 0xFF]) { + Some(Format::Jpeg) + } else if bytes.len() >= 12 && starts(b"RIFF") && &bytes[8..12] == b"WEBP" { + Some(Format::WebP) + } else if starts(b"GIF87a") || starts(b"GIF89a") { + Some(Format::Gif) + } else if starts(b"II*\0") || starts(b"MM\0*") || starts(b"II+\0") || starts(b"MM\0+") { + Some(Format::Tiff) + } else if bytes.len() >= 14 && starts(b"BM") { + Some(Format::Bmp) + } else if bytes.len() >= 6 && starts(&[0, 0, 1, 0]) && (bytes[4] != 0 || bytes[5] != 0) { + Some(Format::Ico) + } else { + match isobmff::brand(bytes)? { + isobmff::Brand::Heif => Some(Format::Heif), + isobmff::Brand::Avif => Some(Format::Avif), + } + } + } + + /// The usual file extension, without the dot. + pub fn extension(self) -> &'static str { + match self { + Format::Png => "png", + Format::Jpeg => "jpg", + Format::WebP => "webp", + Format::Bmp => "bmp", + Format::Gif => "gif", + Format::Tiff => "tif", + Format::Ico => "ico", + Format::Heif => "heic", + Format::Avif => "avif", + } + } + + /// The name shown to people. + pub fn name(self) -> &'static str { + match self { + Format::Png => "PNG", + Format::Jpeg => "JPG", + Format::WebP => "WebP", + Format::Bmp => "BMP", + Format::Gif => "GIF", + Format::Tiff => "TIFF", + Format::Ico => "ICO", + Format::Heif => "HEIC", + Format::Avif => "AVIF", + } + } + + pub fn mime_type(self) -> &'static str { + match self { + Format::Png => "image/png", + Format::Jpeg => "image/jpeg", + Format::WebP => "image/webp", + Format::Bmp => "image/bmp", + Format::Gif => "image/gif", + Format::Tiff => "image/tiff", + Format::Ico => "image/x-icon", + Format::Heif => "image/heic", + Format::Avif => "image/avif", + } + } + + /// Look a format up by an extension or a file name: `"jpg"`, `".JPEG"`, `"photo.heic"`. + pub fn from_name(name: &str) -> Option { + let ext = name.rsplit('.').next().unwrap_or(name).trim().to_ascii_lowercase(); + Some(match ext.as_str() { + "png" => Format::Png, + "jpg" | "jpeg" | "jpe" | "jfif" => Format::Jpeg, + "webp" => Format::WebP, + "bmp" | "dib" => Format::Bmp, + "gif" => Format::Gif, + "tif" | "tiff" => Format::Tiff, + "ico" => Format::Ico, + "heic" | "heif" | "heics" | "heifs" | "hif" => Format::Heif, + "avif" => Format::Avif, + _ => return None, + }) + } + + /// HEIF container (HEIC or AVIF): decoded by the OS codec. + pub fn is_heif_family(self) -> bool { + matches!(self, Format::Heif | Format::Avif) + } + + /// Whether `encode` can write this format. + pub fn can_encode(self) -> bool { + !self.is_heif_family() + } + + pub(crate) fn to_image(self) -> Option { + Some(match self { + Format::Png => image::ImageFormat::Png, + Format::Jpeg => image::ImageFormat::Jpeg, + Format::WebP => image::ImageFormat::WebP, + Format::Bmp => image::ImageFormat::Bmp, + Format::Gif => image::ImageFormat::Gif, + Format::Tiff => image::ImageFormat::Tiff, + Format::Ico => image::ImageFormat::Ico, + Format::Heif | Format::Avif => return None, + }) + } +} + +impl std::fmt::Display for Format { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.name()) + } +} diff --git a/crates/raster/src/isobmff.rs b/crates/raster/src/isobmff.rs new file mode 100644 index 0000000..d9d6444 --- /dev/null +++ b/crates/raster/src/isobmff.rs @@ -0,0 +1,208 @@ +//! Just enough ISO-BMFF (ISO/IEC 14496-12 / 23008-12) to sniff a HEIF brand and read the primary item's size +//! from its `ispe` property, so a HEIC bomb is refused before the OS codec sees it. Every read is bounds-checked; +//! the walk is iterative and visits a fixed set of box levels. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Brand { + Heif, + Avif, +} + +/// Brands that name HEVC-coded HEIF. +const HEVC_BRANDS: [&[u8; 4]; 8] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs"]; +/// Codec-neutral HEIF structural brands (image and sequence). +const GENERIC_BRANDS: [&[u8; 4]; 2] = [b"mif1", b"msf1"]; +const AVIF_BRANDS: [&[u8; 4]; 2] = [b"avif", b"avis"]; + +/// The brand family named in a leading `ftyp` box. AVIF files also list `mif1`, so an AV1 brand wins over the +/// generic ones; when both an AV1 and an HEVC brand are listed, the major brand decides. +pub(crate) fn brand(bytes: &[u8]) -> Option { + let (kind, body, _) = next_box(bytes, 0)?; + if &kind != b"ftyp" || body.len() < 8 { + return None; + } + let major = &body[0..4]; + let brands = || std::iter::once(major).chain(body[8..].as_chunks::<4>().0.iter().map(|c| &c[..])); + let any = |set: &[&[u8; 4]]| brands().any(|b| set.iter().any(|s| &s[..] == b)); + let avif = any(&AVIF_BRANDS); + let hevc = any(&HEVC_BRANDS); + match (avif, hevc) { + (true, true) if AVIF_BRANDS.iter().any(|s| &s[..] == major) => Some(Brand::Avif), + (true, false) => Some(Brand::Avif), + (_, true) => Some(Brand::Heif), + (false, false) if any(&GENERIC_BRANDS) => Some(Brand::Heif), + _ => None, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Info { + pub width: u32, + pub height: u32, + pub has_alpha: bool, +} + +/// Size of the primary item (falls back to the largest `ispe` when the item associations are unreadable). +pub(crate) fn info(bytes: &[u8]) -> Option { + let meta = find_child(bytes, b"meta")?; + let meta = meta.get(4..)?; // full box + let primary = find_child(meta, b"pitm").and_then(|p| { + let version = *p.first()?; + if version == 0 { be16(p, 4).map(u32::from) } else { be32(p, 4) } + }); + let iprp = find_child(meta, b"iprp")?; + let ipco = find_child(iprp, b"ipco")?; + + let mut props: Vec<([u8; 4], &[u8])> = Vec::new(); + let mut pos = 0; + while let Some((kind, body, next)) = next_box(ipco, pos) { + if props.len() >= 4096 { + break; + } + props.push((kind, body)); + pos = next; + } + let ispe_of = |body: &[u8]| -> Option<(u32, u32)> { Some((be32(body, 4)?, be32(body, 8)?)) }; + let has_alpha = props.iter().any(|(kind, body)| { + &kind[..] == b"auxC" && { + let urn = body.get(4..).unwrap_or(&[]); + let urn = &urn[..urn.iter().position(|&b| b == 0).unwrap_or(urn.len())]; + urn.ends_with(b"auxiliary:alpha") || urn == b"urn:mpeg:hevc:2015:auxid:1" + } + }); + + let from_primary = primary.and_then(|item| { + let ipma = find_child(iprp, b"ipma")?; + primary_props(ipma, item)? + .into_iter() + .filter_map(|index| props.get(index.checked_sub(1)?)) + .find(|(kind, _)| &kind[..] == b"ispe") + .and_then(|(_, body)| ispe_of(body)) + }); + let (width, height) = from_primary.or_else(|| { + props + .iter() + .filter(|(kind, _)| &kind[..] == b"ispe") + .filter_map(|(_, body)| ispe_of(body)) + .max_by_key(|(w, h)| u64::from(*w) * u64::from(*h)) + })?; + Some(Info { width, height, has_alpha }) +} + +/// Property indices (1-based into `ipco`) associated with `item` in an `ipma` box. +fn primary_props(ipma: &[u8], item: u32) -> Option> { + let version = *ipma.first()?; + let flags = be32(ipma, 0)? & 0x00FF_FFFF; + let count = be32(ipma, 4)?; + let mut pos = 8usize; + for _ in 0..count.min(1 << 20) { + let id = if version < 1 { + let v = u32::from(be16(ipma, pos)?); + pos += 2; + v + } else { + let v = be32(ipma, pos)?; + pos += 4; + v + }; + let n = usize::from(*ipma.get(pos)?); + pos += 1; + let mut indices = Vec::with_capacity(n); + for _ in 0..n { + if flags & 1 != 0 { + indices.push(usize::from(be16(ipma, pos)? & 0x7FFF)); + pos += 2; + } else { + indices.push(usize::from(*ipma.get(pos)? & 0x7F)); + pos += 1; + } + } + if id == item { + return Some(indices); + } + } + None +} + +fn find_child<'a>(data: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> { + let mut pos = 0; + let mut guard = 0; + while let Some((kind, body, next)) = next_box(data, pos) { + if &kind == want { + return Some(body); + } + guard += 1; + if guard > 4096 { + return None; + } + pos = next; + } + None +} + +/// The box starting at `pos`: (type, body, offset of the next box). +fn next_box(data: &[u8], pos: usize) -> Option<([u8; 4], &[u8], usize)> { + let size32 = be32(data, pos)?; + let kind: [u8; 4] = data.get(pos + 4..pos + 8)?.try_into().ok()?; + let (header, size) = match size32 { + 0 => (8usize, data.len().checked_sub(pos)?), + 1 => (16, usize::try_from(be64(data, pos + 8)?).ok()?), + n => (8, usize::try_from(n).ok()?), + }; + if size < header { + return None; + } + let end = pos.checked_add(size)?; + let body = data.get(pos + header..end)?; + Some((kind, body, end)) +} + +fn be16(d: &[u8], at: usize) -> Option { + Some(u16::from_be_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?)) +} + +fn be32(d: &[u8], at: usize) -> Option { + Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} + +fn be64(d: &[u8], at: usize) -> Option { + Some(u64::from_be_bytes(d.get(at..at.checked_add(8)?)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ftyp(major: &[u8; 4], compat: &[&[u8; 4]]) -> Vec { + let mut body = major.to_vec(); + body.extend_from_slice(&[0; 4]); + for c in compat { + body.extend_from_slice(&c[..]); + } + let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend_from_slice(b"ftyp"); + out.extend_from_slice(&body); + out + } + + #[test] + fn brands() { + assert_eq!(brand(&ftyp(b"heic", &[b"mif1", b"heic"])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"mif1", &[b"heic"])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"msf1", &[])), Some(Brand::Heif)); + assert_eq!(brand(&ftyp(b"avif", &[b"mif1", b"miaf"])), Some(Brand::Avif)); + assert_eq!(brand(&ftyp(b"mif1", &[b"avif"])), Some(Brand::Avif)); + assert_eq!(brand(&ftyp(b"isom", &[b"mp41"])), None, "an MP4 is not an image"); + assert_eq!(brand(b"\0\0\0\x08ftyp"), None); + assert_eq!(brand(b"\xff\xff\xff\xffftypheic"), None); + } + + #[test] + fn hostile_box_sizes() { + // size 1 with a giant 64-bit size, size smaller than the header, truncated header. + assert!(next_box(b"\0\0\0\x01meta\xff\xff\xff\xff\xff\xff\xff\xff", 0).is_none()); + assert!(next_box(b"\0\0\0\x04meta", 0).is_none()); + assert!(next_box(b"\0\0\0", 0).is_none()); + assert!(info(b"\0\0\0\x0cmeta\0\0\0\0").is_none()); + } +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs new file mode 100644 index 0000000..fbc52fb --- /dev/null +++ b/crates/raster/src/lib.rs @@ -0,0 +1,76 @@ +//! pictor-raster: the image side of Pictor's Toolbox. +//! +//! Decode with caps ([`probe`], [`decode`]), encode ([`encode`]), [`crop`], [`rotate`], [`resize`], batch +//! presets ([`apply_preset`]) and "compress to under N MB" ([`compress_to`]). Formats: PNG, JPG, WebP, BMP, +//! GIF, TIFF and ICO both ways through the `image` crate; HEIC/HEIF (and AVIF) in only, through the Windows +//! Imaging Component and the codecs Microsoft ships in the Store (see [`heif_support`]). No HEVC code is bundled. +//! +//! Every input is treated as hostile: sizes are read from headers and checked against [`Limits`] before any +//! pixel buffer exists, third-party decoder panics are caught, and every error is a [`RasterError`] whose +//! `Display` is a plain-English sentence. + +mod decode; +mod encode; +mod error; +mod format; +mod isobmff; +mod ops; +mod preset; +#[cfg(windows)] +mod wic; + +pub use decode::{Probe, decode, probe}; +pub use encode::{EncodeOptions, encode}; +pub use error::{RasterError, Result}; +pub use format::Format; +pub use image::DynamicImage; +pub use ops::{Fit, Rect, Rotation, crop, resize, rotate}; +pub use preset::{Compressed, Preset, apply_preset, compress_to, has_transparency}; + +use serde::{Deserialize, Serialize}; + +/// Caps applied to every decode. The worker process adds its own memory and time caps on top. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Limits { + /// Largest width × height accepted (default 128 million: a 16000 × 8000 panorama). + pub max_pixels: u64, + /// Largest input file in bytes (default 512 MiB). + pub max_input_bytes: u64, + /// Largest decoded buffer, and the budget handed to the decoders (default 1 GiB). + pub max_alloc: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_pixels: 128_000_000, max_input_bytes: 512 * 1024 * 1024, max_alloc: 1024 * 1024 * 1024 } + } +} + +/// Whether this machine can decode HEIC photos. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HeifSupport { + /// The HEIF container codec and an HEVC decoder are installed. + Ready, + /// "HEIF Image Extensions" is installed, "HEVC Video Extensions" is not. + NeedsHevc, + /// An HEVC decoder exists but "HEIF Image Extensions" is missing. + NeedsHeif, + /// Neither is installed. + NeedsHeifAndHevc, + /// Not Windows: HEIC is never decoded here. + Unavailable, +} + +/// Probe the OS codecs without a file: the WIC HEIF decoder is instantiated by its container GUID, and +/// Media Foundation is asked (`MFTEnumEx`) for a decoder that takes HEVC video. Never fails. +pub fn heif_support() -> HeifSupport { + #[cfg(windows)] + { + wic::heif_support() + } + #[cfg(not(windows))] + { + HeifSupport::Unavailable + } +} diff --git a/crates/raster/src/ops.rs b/crates/raster/src/ops.rs new file mode 100644 index 0000000..e28a77a --- /dev/null +++ b/crates/raster/src/ops.rs @@ -0,0 +1,106 @@ +use image::imageops::FilterType; +use image::{DynamicImage, GenericImageView}; +use serde::{Deserialize, Serialize}; + +use crate::Limits; +use crate::encode::fit_within; +use crate::error::{RasterError, Result}; + +/// A crop rectangle in pixels, origin at the top left. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Rotation { + /// 90° clockwise. + Cw90, + /// 90° counter-clockwise. + Ccw90, + R180, + /// Mirror left-right. + FlipH, + /// Mirror top-bottom. + FlipV, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum Fit { + /// Shrink so the longer side is at most this many pixels; never enlarges. + LongEdge(u32), + /// Exactly this size (aspect ratio not kept; may enlarge, within `Limits`). + Exact(u32, u32), + /// Scale both sides by this percentage (100 = unchanged); each side is at least 1 pixel. + Percent(f32), +} + +/// Cut out `rect`; it must lie fully inside the image and be at least 1 × 1. +pub fn crop(img: &DynamicImage, rect: Rect) -> Result { + let (w, h) = img.dimensions(); + let right = rect.x.checked_add(rect.width).ok_or(RasterError::InvalidCrop)?; + let bottom = rect.y.checked_add(rect.height).ok_or(RasterError::InvalidCrop)?; + if rect.width == 0 || rect.height == 0 || right > w || bottom > h { + return Err(RasterError::InvalidCrop); + } + Ok(img.crop_imm(rect.x, rect.y, rect.width, rect.height)) +} + +pub fn rotate(img: &DynamicImage, rotation: Rotation) -> DynamicImage { + match rotation { + Rotation::Cw90 => img.rotate90(), + Rotation::Ccw90 => img.rotate270(), + Rotation::R180 => img.rotate180(), + Rotation::FlipH => img.fliph(), + Rotation::FlipV => img.flipv(), + } +} + +/// Resize with Lanczos3 when shrinking and Catmull-Rom when enlarging. The result is checked against +/// `limits.max_pixels` and `limits.max_alloc` before any buffer is made. +pub fn resize(img: &DynamicImage, fit: Fit, limits: &Limits) -> Result { + let (w, h) = img.dimensions(); + let (nw, nh) = target_size(w, h, fit)?; + if (nw, nh) == (w, h) { + return Ok(img.clone()); + } + let pixels = u64::from(nw) * u64::from(nh); + if pixels > limits.max_pixels { + return Err(RasterError::TooManyPixels { width: nw.into(), height: nh.into() }); + } + // Output buffer plus `image`'s f32 intermediate (one pass, 4 channels). + let bpp = u64::from(img.color().bytes_per_pixel()); + let needed = + pixels.saturating_mul(bpp).saturating_add(u64::from(nw).saturating_mul(u64::from(h)).saturating_mul(16)); + if needed > limits.max_alloc { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + Ok(resize_exact(img, nw, nh)) +} + +pub(crate) fn resize_exact(img: &DynamicImage, nw: u32, nh: u32) -> DynamicImage { + let (w, h) = img.dimensions(); + let filter = if nw <= w && nh <= h { FilterType::Lanczos3 } else { FilterType::CatmullRom }; + img.resize_exact(nw, nh, filter) +} + +fn target_size(w: u32, h: u32, fit: Fit) -> Result<(u32, u32)> { + match fit { + Fit::LongEdge(0) | Fit::Exact(0, _) | Fit::Exact(_, 0) => Err(RasterError::InvalidSize), + Fit::LongEdge(n) => Ok(fit_within(w, h, n)), + Fit::Exact(nw, nh) => Ok((nw, nh)), + Fit::Percent(p) => { + if !p.is_finite() || p <= 0.0 { + return Err(RasterError::InvalidSize); + } + let side = |v: u32| -> Result { + let s = (f64::from(v) * f64::from(p) / 100.0).round().max(1.0); + if s > f64::from(u32::MAX) { Err(RasterError::InvalidSize) } else { Ok(s as u32) } + }; + Ok((side(w)?, side(h)?)) + } + } +} diff --git a/crates/raster/src/preset.rs b/crates/raster/src/preset.rs new file mode 100644 index 0000000..a2131af --- /dev/null +++ b/crates/raster/src/preset.rs @@ -0,0 +1,168 @@ +use image::{DynamicImage, GenericImageView}; +use serde::{Deserialize, Serialize}; + +use crate::encode::{EncodeOptions, encode, fit_within}; +use crate::error::{RasterError, Result}; +use crate::ops::resize_exact; +use crate::{Format, Limits}; + +/// Batch-resize presets of the Toolbox. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Preset { + /// Long edge 1600 px, JPEG quality 80. + Email, + /// Long edge 2048 px, JPEG quality 85; an image with real transparency is written as PNG instead. + Web, + /// No resize, the source format (HEIC/AVIF, which cannot be written, become JPEG at the default quality). + Original, +} + +/// Apply a preset; returns the encoded bytes and the format they are in. Never enlarges. +pub fn apply_preset(img: &DynamicImage, src_format: Format, preset: Preset) -> Result<(Vec, Format)> { + let shrink = |long: u32| { + let (w, h) = img.dimensions(); + let (nw, nh) = fit_within(w, h, long); + if (nw, nh) == (w, h) { + std::borrow::Cow::Borrowed(img) + } else { + std::borrow::Cow::Owned(resize_exact(img, nw, nh)) + } + }; + let jpeg = |q: u8| EncodeOptions { jpeg_quality: q, ..EncodeOptions::default() }; + match preset { + Preset::Email => Ok((encode(&shrink(1600), Format::Jpeg, &jpeg(80))?, Format::Jpeg)), + Preset::Web => { + let small = shrink(2048); + if has_transparency(&small) { + Ok((encode(&small, Format::Png, &EncodeOptions::default())?, Format::Png)) + } else { + Ok((encode(&small, Format::Jpeg, &jpeg(85))?, Format::Jpeg)) + } + } + Preset::Original => { + let format = if src_format.can_encode() { src_format } else { Format::Jpeg }; + Ok((encode(img, format, &EncodeOptions::default())?, format)) + } + } +} + +/// An alpha channel with at least one pixel that is not fully opaque. +pub fn has_transparency(img: &DynamicImage) -> bool { + match img { + DynamicImage::ImageRgba8(b) => b.pixels().any(|p| p.0[3] < 255), + DynamicImage::ImageLumaA8(b) => b.pixels().any(|p| p.0[1] < 255), + DynamicImage::ImageRgba16(b) => b.pixels().any(|p| p.0[3] < u16::MAX), + DynamicImage::ImageLumaA16(b) => b.pixels().any(|p| p.0[1] < u16::MAX), + other if other.color().has_alpha() => other.to_rgba8().pixels().any(|p| p.0[3] < 255), + _ => false, + } +} + +/// Result of [`compress_to`]. +#[derive(Debug, Clone, PartialEq)] +pub struct Compressed { + pub bytes: Vec, + pub format: Format, + /// JPEG quality used; `None` for lossless formats. + pub quality: Option, + /// Output long edge divided by the input long edge (1.0 = full size). + pub scale: f32, + pub width: u32, + pub height: u32, +} + +const JPEG_MIN_Q: u8 = 40; +const JPEG_MAX_Q: u8 = 92; +const JPEG_SCALED_Q: u8 = 75; +const SCALE_STEP: f64 = 0.85; +const MIN_LONG_EDGE: u32 = 320; + +/// Make the encoded image fit in `target_bytes`. +/// +/// JPEG: the highest quality in 40..=92 that fits at full size (binary search). If even quality 40 is too +/// large, the image is shrunk in 0.85 steps at quality 75 until it fits; the last step that keeps the long edge +/// at 320 px or more is also tried at quality 40. PNG, WebP (lossless) and the other lossless formats: the +/// 0.85 shrink steps only. Below 320 px: [`RasterError::CannotReachTarget`] with the smallest size seen. +pub fn compress_to(img: &DynamicImage, format: Format, target_bytes: u64, limits: &Limits) -> Result { + if !format.can_encode() { + return Err(RasterError::CannotWrite { format }); + } + if target_bytes == 0 { + return Err(RasterError::InvalidTarget); + } + let (w, h) = img.dimensions(); + crate::decode::check_pixels(w, h, limits)?; + let jpeg = format == Format::Jpeg; + let run = |im: &DynamicImage, q: Option| -> Result> { + let options = EncodeOptions { jpeg_quality: q.unwrap_or(88), ..EncodeOptions::default() }; + encode(im, format, &options) + }; + let fits = |b: &[u8]| b.len() as u64 <= target_bytes; + let done = |bytes: Vec, quality: Option, nw: u32, nh: u32| Compressed { + bytes, + format, + quality, + scale: nw.max(nh) as f32 / w.max(h) as f32, + width: nw, + height: nh, + }; + let mut smallest = u64::MAX; + + if jpeg { + let at_max = run(img, Some(JPEG_MAX_Q))?; + if fits(&at_max) { + return Ok(done(at_max, Some(JPEG_MAX_Q), w, h)); + } + let at_min = run(img, Some(JPEG_MIN_Q))?; + smallest = smallest.min(at_min.len() as u64); + if fits(&at_min) { + // Invariant: `lo` fits, `hi` does not. + let (mut lo, mut hi, mut best) = (JPEG_MIN_Q, JPEG_MAX_Q, at_min); + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + let b = run(img, Some(mid))?; + if fits(&b) { + lo = mid; + best = b; + } else { + hi = mid; + } + } + return Ok(done(best, Some(lo), w, h)); + } + } else { + let full = run(img, None)?; + smallest = smallest.min(full.len() as u64); + if fits(&full) { + return Ok(done(full, None, w, h)); + } + } + + let quality = jpeg.then_some(JPEG_SCALED_Q); + let long = w.max(h); + let mut scale = 1.0f64; + let mut last: Option = None; + loop { + scale *= SCALE_STEP; + let new_long = (f64::from(long) * scale).round() as u32; + if new_long < MIN_LONG_EDGE { + break; + } + let (nw, nh) = fit_within(w, h, new_long); + let small = resize_exact(img, nw, nh); + let b = run(&small, quality)?; + smallest = smallest.min(b.len() as u64); + if fits(&b) { + return Ok(done(b, quality, nw, nh)); + } + last = Some(small); + } + if jpeg && let Some(small) = last { + let b = run(&small, Some(JPEG_MIN_Q))?; + smallest = smallest.min(b.len() as u64); + if fits(&b) { + return Ok(done(b, Some(JPEG_MIN_Q), small.width(), small.height())); + } + } + Err(RasterError::CannotReachTarget { smallest_bytes: smallest }) +} diff --git a/crates/raster/src/wic.rs b/crates/raster/src/wic.rs new file mode 100644 index 0000000..402de0c --- /dev/null +++ b/crates/raster/src/wic.rs @@ -0,0 +1,347 @@ +//! HEIC/HEIF (and AVIF) decoding through the Windows Imaging Component. +//! +//! Windows has no HEIF support out of the box. Two Microsoft Store packages provide it: +//! - "HEIF Image Extensions" (free, ): the WIC decoder for the +//! HEIF container. Without it, WIC finds no decoder (`WINCODEC_ERR_COMPONENTNOTFOUND`, 0x88982F50). +//! - "HEVC Video Extensions" ($0.99, ): the Media Foundation +//! HEVC decoder the container codec calls for the pixels. Without it the container opens, the frame size is +//! readable, and the failure appears only when pixels are requested. +//! +//! AVIF uses the same container codec plus the "AV1 Video Extension". Pictor bundles none of these codecs. +//! +//! Every call initialises COM on the calling thread (apartment-threaded; an existing multithreaded apartment +//! is tolerated) and releases every COM object before uninitialising. + +use image::metadata::Orientation; +use image::{DynamicImage, RgbaImage}; +use windows::Win32::Foundation::RPC_E_CHANGED_MODE; +use windows::Win32::Graphics::Imaging::{ + CLSID_WICImagingFactory, GUID_ContainerFormatHeif, GUID_WICPixelFormat32bppRGBA, IWICBitmapFrameDecode, + IWICImagingFactory, WICBitmapDitherTypeNone, WICBitmapPaletteTypeCustom, WICDecodeMetadataCacheOnDemand, +}; +use windows::Win32::Media::MediaFoundation::{ + IMFActivate, MFMediaType_Video, MFT_CATEGORY_VIDEO_DECODER, MFT_ENUM_FLAG, MFT_ENUM_FLAG_ASYNCMFT, + MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_LOCALMFT, MFT_ENUM_FLAG_SORTANDFILTER, MFT_ENUM_FLAG_SYNCMFT, + MFT_FRIENDLY_NAME_Attribute, MFT_REGISTER_TYPE_INFO, MFTEnumEx, MFVideoFormat_AV1, MFVideoFormat_HEVC, +}; +use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear}; +use windows::Win32::System::Com::{ + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, +}; +use windows::Win32::System::Variant::{VT_I2, VT_I4, VT_UI2, VT_UI4}; +use windows::core::{GUID, PWSTR, w}; + +use crate::error::{RasterError, Result}; +use crate::{Format, HeifSupport, Limits}; + +/// No decoder matched the stream (the HEIF container codec is not installed, or the bytes are not HEIF). +const WINCODEC_ERR_COMPONENTNOTFOUND: u32 = 0x8898_2F50; +/// The codec is registered but could not start (e.g. a half-installed Store package). +const WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: u32 = 0x8898_200B; +/// HRESULTs that mean "these bytes are broken" rather than "a codec is missing". +const CORRUPT_CODES: [u32; 6] = [ + 0x8898_2F61, // WINCODEC_ERR_BADHEADER + 0x8898_2F60, // WINCODEC_ERR_BADIMAGE + 0x8898_2F62, // WINCODEC_ERR_BADMETADATAHEADER + 0x8898_2F8A, // WINCODEC_ERR_STREAMREAD + 0x8898_2F8E, // WINCODEC_ERR_STREAMNOTAVAILABLE + 0x8898_2F8F, // WINCODEC_ERR_UNEXPECTEDSIZE +]; + +/// Balances a successful `CoInitializeEx`. Declared before any COM object so it drops last. +struct Com { + uninit: bool, +} + +impl Com { + fn init() -> std::result::Result { + // SAFETY: plain FFI call with no pointers. + let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + if hr == RPC_E_CHANGED_MODE { + // The thread already lives in a multithreaded apartment; WIC works there too. + Ok(Self { uninit: false }) + } else if hr.is_ok() { + // S_OK or S_FALSE (already initialised): both must be balanced. + Ok(Self { uninit: true }) + } else { + Err(hr.into()) + } + } +} + +impl Drop for Com { + fn drop(&mut self) { + if self.uninit { + // SAFETY: balances the successful CoInitializeEx above on this thread. + unsafe { CoUninitialize() }; + } + } +} + +fn factory() -> windows::core::Result { + // SAFETY: creating an in-process COM object; COM is initialised by the caller. + unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Stage { + /// Matching a decoder to the stream: only the container codec is involved. + Open, + /// Frame access and pixel copy: the HEVC/AV1 decoder is involved. + Pixels, +} + +pub(crate) fn decode(bytes: &[u8], format: Format, limits: &Limits) -> Result { + let _com = Com::init().map_err(|e| os_error(&e))?; + decode_with_com(bytes, format, limits) +} + +fn decode_with_com(bytes: &[u8], format: Format, limits: &Limits) -> Result { + if u32::try_from(bytes.len()).is_err() { + return Err(RasterError::InputTooLarge { bytes: bytes.len() as u64, limit: u64::from(u32::MAX) }); + } + let factory = factory().map_err(|e| os_error(&e))?; + // SAFETY: the stream reads `bytes` in place; `bytes` outlives the stream, the decoder and every frame, + // which are all dropped at the end of this function. + let decoder = unsafe { + let stream = factory.CreateStream().map_err(|e| os_error(&e))?; + stream.InitializeFromMemory(bytes).map_err(|e| os_error(&e))?; + factory.CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand) + } + .map_err(|e| classify(&e, format, Stage::Open))?; + + // SAFETY: COM calls on live interfaces; out-pointers point at locals. + let frame = unsafe { decoder.GetFrame(0) }.map_err(|e| classify(&e, format, Stage::Pixels))?; + let (mut width, mut height) = (0u32, 0u32); + unsafe { frame.GetSize(&mut width, &mut height) }.map_err(|e| classify(&e, format, Stage::Pixels))?; + crate::decode::check_pixels(width, height, limits)?; + + let orientation = read_orientation(&frame); + let stride = width.checked_mul(4).ok_or(RasterError::TooMuchMemory { limit: limits.max_alloc })?; + let total = u64::from(stride) * u64::from(height); + let copies = if orientation.is_some_and(|o| o >= 5) { 2 } else { 1 }; + if total.saturating_mul(copies) > limits.max_alloc || total > u64::from(u32::MAX) { + return Err(RasterError::TooMuchMemory { limit: limits.max_alloc }); + } + let total = usize::try_from(total).map_err(|_| RasterError::TooMuchMemory { limit: limits.max_alloc })?; + + let converter = unsafe { factory.CreateFormatConverter() }.map_err(|e| os_error(&e))?; + unsafe { + converter.Initialize( + &frame, + &GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, + None, + 0.0, + WICBitmapPaletteTypeCustom, + ) + } + .map_err(|e| classify(&e, format, Stage::Pixels))?; + + let mut pixels = Vec::new(); + pixels.try_reserve_exact(total).map_err(|_| RasterError::TooMuchMemory { limit: limits.max_alloc })?; + pixels.resize(total, 0); + // SAFETY: `pixels` holds exactly stride × height bytes. + unsafe { converter.CopyPixels(std::ptr::null(), stride, &mut pixels) } + .map_err(|e| classify(&e, format, Stage::Pixels))?; + + let rgba = RgbaImage::from_raw(width, height, pixels) + .ok_or_else(|| RasterError::Corrupt { format, detail: "pixel buffer size mismatch".into() })?; + let mut img = DynamicImage::ImageRgba8(rgba); + if let Some(o) = orientation.and_then(|o| Orientation::from_exif(o as u8)) { + img.apply_orientation(o); + } + Ok(img) +} + +/// EXIF-style orientation (1..=8) from the frame's metadata: the photo policy name first, then the HEIF +/// property (WICHeifOrientation), then the raw EXIF tag 274. Absent or unreadable: `None`. +fn read_orientation(frame: &IWICBitmapFrameDecode) -> Option { + // SAFETY: COM calls on a live frame; every PROPVARIANT is cleared after reading. + unsafe { + let reader = frame.GetMetadataQueryReader().ok()?; + for query in [w!("System.Photo.Orientation"), w!("/heifProps/{ushort=1}"), w!("/ifd/{ushort=274}")] { + let mut value = PROPVARIANT::default(); + if reader.GetMetadataByName(query, &mut value).is_err() { + continue; + } + let inner = &value.Anonymous.Anonymous; + let v = match inner.vt { + VT_UI2 => Some(inner.Anonymous.uiVal), + VT_I2 => u16::try_from(inner.Anonymous.iVal).ok(), + VT_UI4 => u16::try_from(inner.Anonymous.ulVal).ok(), + VT_I4 => u16::try_from(inner.Anonymous.lVal).ok(), + _ => None, + }; + let _ = PropVariantClear(&mut value); + if let Some(v) = v.filter(|v| (1..=8).contains(v)) { + return Some(v); + } + } + None + } +} + +fn os_error(e: &windows::core::Error) -> RasterError { + RasterError::Os { code: e.code().0 as u32, detail: e.message() } +} + +/// Map a WIC failure. A missing codec shows up as `COMPONENTNOTFOUND` / `COMPONENTINITIALIZEFAILURE` when +/// opening; a missing HEVC decoder shows up later, when pixels are requested, with an HRESULT that is not +/// specific to it (on Windows 10 22H2 with only the HEIF extension, `GetFrame` fails with +/// `WINCODEC_ERR_UNSUPPORTEDOPERATION`, 0x88982F81), so a pixel-stage failure is checked against the decoders +/// Media Foundation lists. The probes are only run when needed: instantiating the Store codec costs ~0.3 s. +fn classify(e: &windows::core::Error, format: Format, stage: Stage) -> RasterError { + let code = e.code().0 as u32; + let codec_present = || match format { + Format::Avif => has_video_decoder(MFVideoFormat_AV1), + _ => has_video_decoder(MFVideoFormat_HEVC), + }; + let missing = |needs_heif: bool| match format { + Format::Avif => RasterError::AvifCodecMissing, + _ => RasterError::HeifCodecMissing { needs_heif }, + }; + let not_found = code == WINCODEC_ERR_COMPONENTNOTFOUND || code == WINCODEC_ERR_COMPONENTINITIALIZEFAILURE; + match stage { + Stage::Open if not_found => { + if !heif_container_present() { + missing(true) + } else if format == Format::Avif && !codec_present() { + RasterError::AvifCodecMissing + } else { + RasterError::Corrupt { format, detail: format!("no WIC decoder accepts the stream ({code:#010X})") } + } + } + // The container decoder opened the stream, so only the video decoder can be missing. + Stage::Pixels if not_found || !codec_present() => missing(false), + _ if CORRUPT_CODES.contains(&code) => RasterError::Corrupt { format, detail: format!("{code:#010X}") }, + _ => RasterError::Os { code, detail: e.message() }, + } +} + +pub(crate) fn heif_support() -> HeifSupport { + let _com = Com::init().ok(); + match (heif_container_present(), has_video_decoder(MFVideoFormat_HEVC)) { + (true, true) => HeifSupport::Ready, + (true, false) => HeifSupport::NeedsHevc, + (false, true) => HeifSupport::NeedsHeif, + (false, false) => HeifSupport::NeedsHeifAndHevc, + } +} + +/// The WIC HEIF container decoder can be instantiated by its GUID (needs no file). +fn heif_container_present() -> bool { + let Ok(factory) = factory() else { return false }; + // SAFETY: COM call with a pointer to a constant GUID. + unsafe { factory.CreateDecoder(&GUID_ContainerFormatHeif, std::ptr::null()) }.is_ok() +} + +fn enum_flags() -> MFT_ENUM_FLAG { + MFT_ENUM_FLAG( + MFT_ENUM_FLAG_SYNCMFT.0 + | MFT_ENUM_FLAG_ASYNCMFT.0 + | MFT_ENUM_FLAG_HARDWARE.0 + | MFT_ENUM_FLAG_LOCALMFT.0 + | MFT_ENUM_FLAG_SORTANDFILTER.0, + ) +} + +/// Friendly names of the Media Foundation decoders that accept `subtype` video. +pub(crate) fn video_decoders(subtype: GUID) -> Vec { + let input = MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: subtype }; + let mut list: *mut Option = std::ptr::null_mut(); + let mut count = 0u32; + let mut names = Vec::new(); + // SAFETY: MFTEnumEx hands back a CoTaskMemAlloc'd array of `count` owned interface pointers; each is + // moved out (released on drop) and the array freed. + unsafe { + if MFTEnumEx(MFT_CATEGORY_VIDEO_DECODER, enum_flags(), Some(&input), None, &mut list, &mut count).is_err() { + return names; + } + if list.is_null() { + return names; + } + for i in 0..count as usize { + let activate = std::ptr::read(list.add(i)); + let name = activate.as_ref().and_then(|a| { + let mut s = PWSTR::null(); + let mut len = 0u32; + a.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut s, &mut len).ok()?; + let out = s.to_string().ok(); + CoTaskMemFree(Some(s.0 as *const _)); + out + }); + names.push(name.unwrap_or_else(|| "(unnamed)".into())); + } + CoTaskMemFree(Some(list as *const _)); + } + names +} + +fn has_video_decoder(subtype: GUID) -> bool { + !video_decoders(subtype).is_empty() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn list_codecs() { + let _com = Com::init().ok(); + eprintln!("\nHEIF container decoder: {}", heif_container_present()); + eprintln!("HEVC decoders: {:?}", video_decoders(MFVideoFormat_HEVC)); + eprintln!("AV1 decoders: {:?}", video_decoders(MFVideoFormat_AV1)); + } + + #[path = "../../../tests/common/mod.rs"] + mod common; + + /// Logs the raw HRESULT of each stage for the hand-built HEIC (what a missing HEVC codec produces). + #[test] + fn raw_hresults_of_minimal_heic() { + let bytes = common::minimal_heic(64, 64); + let _com = Com::init().unwrap(); + let factory = factory().unwrap(); + unsafe { + let stream = factory.CreateStream().unwrap(); + stream.InitializeFromMemory(&bytes).unwrap(); + let decoder = + match factory.CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand) { + Ok(d) => d, + Err(e) => return eprintln!("CreateDecoderFromStream: {:#010X} {}", e.code().0, e.message()), + }; + eprintln!("container: {:?}", decoder.GetContainerFormat()); + let frame = match decoder.GetFrame(0) { + Ok(f) => f, + Err(e) => return eprintln!("GetFrame: {:#010X} {}", e.code().0, e.message()), + }; + let (mut w, mut h) = (0, 0); + eprintln!("GetSize: {:?} {w}x{h}", frame.GetSize(&mut w, &mut h)); + let converter = factory.CreateFormatConverter().unwrap(); + let r = converter.Initialize( + &frame, + &GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, + None, + 0.0, + WICBitmapPaletteTypeCustom, + ); + eprintln!( + "converter.Initialize: {:?}", + r.as_ref().map_err(|e| format!("{:#010X} {}", e.code().0, e.message())) + ); + let mut buf = vec![0u8; (w * h * 4) as usize]; + let r = converter.CopyPixels(std::ptr::null(), w * 4, &mut buf); + eprintln!("CopyPixels: {:?}", r.map_err(|e| format!("{:#010X} {}", e.code().0, e.message()))); + } + } + + #[test] + fn com_init_twice_is_balanced() { + let a = Com::init().unwrap(); + let b = Com::init().unwrap(); + drop(b); + drop(a); + } +} diff --git a/crates/raster/tests/common/mod.rs b/crates/raster/tests/common/mod.rs new file mode 100644 index 0000000..37f7e7f --- /dev/null +++ b/crates/raster/tests/common/mod.rs @@ -0,0 +1,311 @@ +//! Fixtures built in code: nothing binary is checked in. +#![allow(dead_code)] + +use image::{DynamicImage, ImageBuffer, Rgb, RgbImage, Rgba, RgbaImage}; + +/// Deterministic xorshift64* generator, so every run mutates the same bytes. +pub struct XorShift(u64); + +impl XorShift { + pub fn new(seed: u64) -> Self { + Self(seed.max(1)) + } + + pub fn next_u64(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + pub fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { (self.next_u64() % n as u64) as usize } + } + + pub fn byte(&mut self) -> u8 { + (self.next_u64() >> 56) as u8 + } +} + +/// A small RGB image with a gradient and a few hard edges. +pub fn sample_rgb(width: u32, height: u32) -> DynamicImage { + let img: RgbImage = ImageBuffer::from_fn(width, height, |x, y| { + let r = (x * 255 / width.max(1)) as u8; + let g = (y * 255 / height.max(1)) as u8; + let b = if (x / 8 + y / 8) % 2 == 0 { 40 } else { 210 }; + Rgb([r, g, b]) + }); + DynamicImage::ImageRgb8(img) +} + +/// A small RGBA image whose alpha varies, including fully transparent pixels. +pub fn sample_rgba(width: u32, height: u32) -> DynamicImage { + let img: RgbaImage = ImageBuffer::from_fn(width, height, |x, y| { + let r = (x * 255 / width.max(1)) as u8; + let g = (y * 255 / height.max(1)) as u8; + let a = if x < width / 4 { 0 } else { ((x + y) * 7 % 256) as u8 }; + Rgba([r, g, 128, a]) + }); + DynamicImage::ImageRgba8(img) +} + +/// A noisy photo-like image: a smooth gradient plus per-pixel noise (hard to compress). +pub fn noisy_rgb(width: u32, height: u32, seed: u64) -> DynamicImage { + let mut rng = XorShift::new(seed); + let mut img = RgbImage::new(width, height); + for (x, y, px) in img.enumerate_pixels_mut() { + let n = rng.next_u64(); + let base_r = (x * 200 / width) as i32; + let base_g = (y * 200 / height) as i32; + let noise = |shift: u32| ((n >> shift) & 0x3F) as i32 - 32; + px.0 = [ + (base_r + noise(0)).clamp(0, 255) as u8, + (base_g + noise(8)).clamp(0, 255) as u8, + (120 + noise(16)).clamp(0, 255) as u8, + ]; + } + DynamicImage::ImageRgb8(img) +} + +pub fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc +} + +pub fn png_chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let mut body = Vec::with_capacity(4 + data.len()); + body.extend_from_slice(kind); + body.extend_from_slice(data); + out.extend_from_slice(&body); + out.extend_from_slice(&crc32(&body).to_be_bytes()); +} + +/// A hand-built PNG with an arbitrary IHDR size (8-bit RGB) and a tiny stored-zlib IDAT. +pub fn png_with_size(width: u32, height: u32) -> Vec { + let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&width.to_be_bytes()); + ihdr.extend_from_slice(&height.to_be_bytes()); + ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); + png_chunk(&mut out, b"IHDR", &ihdr); + // zlib header + one empty stored final block + adler32 of nothing. + let idat = [0x78, 0x01, 0x01, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01]; + png_chunk(&mut out, b"IDAT", &idat); + png_chunk(&mut out, b"IEND", &[]); + out +} + +pub fn encode_with_image(img: &DynamicImage, fmt: image::ImageFormat) -> Vec { + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, fmt).expect("fixture encodes"); + out.into_inner() +} + +pub fn jpeg_fixture(width: u32, height: u32) -> Vec { + encode_with_image(&sample_rgb(width, height), image::ImageFormat::Jpeg) +} + +/// Replace the dimensions in the first SOF0/SOF2 segment of a JPEG. +pub fn patch_jpeg_sof(mut jpeg: Vec, width: u16, height: u16) -> Vec { + let mut i = 2; + while i + 9 < jpeg.len() { + if jpeg[i] != 0xFF { + i += 1; + continue; + } + let marker = jpeg[i + 1]; + let len = u16::from_be_bytes([jpeg[i + 2], jpeg[i + 3]]) as usize; + if matches!(marker, 0xC0..=0xC2) { + jpeg[i + 5..i + 7].copy_from_slice(&height.to_be_bytes()); + jpeg[i + 7..i + 9].copy_from_slice(&width.to_be_bytes()); + return jpeg; + } + i += 2 + len; + } + panic!("no SOF in fixture"); +} + +/// Insert a minimal EXIF APP1 segment (one IFD0 entry: Orientation) right after SOI. +pub fn jpeg_with_orientation(jpeg: &[u8], orientation: u16) -> Vec { + let mut tiff = Vec::new(); + tiff.extend_from_slice(b"II*\0"); + tiff.extend_from_slice(&8u32.to_le_bytes()); + tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry + tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation + tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT + tiff.extend_from_slice(&1u32.to_le_bytes()); // count + tiff.extend_from_slice(&orientation.to_le_bytes()); + tiff.extend_from_slice(&[0, 0]); // padding of the 4-byte value field + tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD + let mut payload = b"Exif\0\0".to_vec(); + payload.extend_from_slice(&tiff); + let mut out = jpeg[..2].to_vec(); + out.extend_from_slice(&[0xFF, 0xE1]); + out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + out.extend_from_slice(&payload); + out.extend_from_slice(&jpeg[2..]); + out +} + +/// GIF89a whose logical screen and image descriptor claim `w × h`, with a tiny LZW stream. +pub fn gif_with_size(width: u16, height: u16) -> Vec { + let mut out = b"GIF89a".to_vec(); + out.extend_from_slice(&width.to_le_bytes()); + out.extend_from_slice(&height.to_le_bytes()); + out.extend_from_slice(&[0x80, 0, 0]); // global colour table of 2 entries + out.extend_from_slice(&[0, 0, 0, 255, 255, 255]); + out.push(0x2C); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&width.to_le_bytes()); + out.extend_from_slice(&height.to_le_bytes()); + out.push(0); + out.push(2); // LZW minimum code size + out.extend_from_slice(&[2, 0x44, 0x01, 0]); // clear, a pixel, end + out.push(0x3B); + out +} + +/// Little-endian baseline TIFF whose IFD claims `w × h` (8-bit grey, one strip of 1 byte). +pub fn tiff_with_size(width: u32, height: u32) -> Vec { + let entries: [(u16, u16, u32, u32); 8] = [ + (256, 4, 1, width), // ImageWidth LONG + (257, 4, 1, height), // ImageLength LONG + (258, 3, 1, 8), // BitsPerSample + (259, 3, 1, 1), // Compression none + (262, 3, 1, 1), // BlackIsZero + (273, 4, 1, 0), // StripOffsets (patched below) + (278, 4, 1, height), // RowsPerStrip + (279, 4, 1, 1), // StripByteCounts + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + let data_offset = 8 + 2 + entries.len() as u32 * 12 + 4; + for (tag, kind, count, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + let v = if tag == 273 { data_offset } else { value }; + if kind == 3 { + out.extend_from_slice(&(v as u16).to_le_bytes()); + out.extend_from_slice(&[0, 0]); + } else { + out.extend_from_slice(&v.to_le_bytes()); + } + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.push(0x80); + out +} + +/// ICO header claiming three entries that point outside the file with silly sizes. +pub fn bogus_ico() -> Vec { + let mut out = vec![0, 0, 1, 0, 3, 0]; + for i in 0..3u32 { + out.extend_from_slice(&[0, 0, 0, 0, 1, 0, 32, 0]); + out.extend_from_slice(&(0xFFFF_FFF0u32 - i).to_le_bytes()); // size + out.extend_from_slice(&(0x7FFF_0000u32 + i).to_le_bytes()); // offset + } + out.extend_from_slice(&[0xAB; 20]); + out +} + +fn bmff_box(kind: &[u8; 4], body: &[u8]) -> Vec { + let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend_from_slice(kind); + out.extend_from_slice(body); + out +} + +fn full_box(kind: &[u8; 4], version: u8, body: &[u8]) -> Vec { + let mut b = vec![version, 0, 0, 0]; + b.extend_from_slice(body); + bmff_box(kind, &b) +} + +/// A syntactically valid HEIF container (ftyp, meta with hdlr/pitm/iinf/iloc/iprp, mdat) holding one +/// `hvc1` item whose HEVC payload is a dummy NAL unit. Written by hand from ISO/IEC 23008-12; the image data +/// itself does not decode, so on a machine with the codecs this still yields a typed error. +pub fn minimal_heic(width: u32, height: u32) -> Vec { + let mut ftyp = b"heic".to_vec(); + ftyp.extend_from_slice(&0u32.to_be_bytes()); + ftyp.extend_from_slice(b"mif1heic"); + let ftyp = bmff_box(b"ftyp", &ftyp); + + let mut hdlr = vec![0; 4]; + hdlr.extend_from_slice(b"pict"); + hdlr.extend_from_slice(&[0; 12]); + hdlr.push(0); + let hdlr = full_box(b"hdlr", 0, &hdlr); + let pitm = full_box(b"pitm", 0, &1u16.to_be_bytes()); + let mut infe = Vec::new(); + infe.extend_from_slice(&1u16.to_be_bytes()); + infe.extend_from_slice(&0u16.to_be_bytes()); + infe.extend_from_slice(b"hvc1"); + infe.push(0); + let infe = full_box(b"infe", 2, &infe); + let mut iinf = 1u16.to_be_bytes().to_vec(); + iinf.extend_from_slice(&infe); + let iinf = full_box(b"iinf", 0, &iinf); + + // hvcC: version 1, Main profile, level 3.0, 4:2:0, 8 bit, 4-byte NAL lengths, no parameter-set arrays. + let hvcc = bmff_box( + b"hvcC", + &[1, 0x01, 0x60, 0, 0, 0, 0x90, 0, 0, 0, 0, 0, 90, 0xF0, 0x00, 0xFC, 0xFD, 0xF8, 0xF8, 0, 0, 0x0F, 0], + ); + let mut ispe = width.to_be_bytes().to_vec(); + ispe.extend_from_slice(&height.to_be_bytes()); + let ispe = full_box(b"ispe", 0, &ispe); + let mut ipco = hvcc; + ipco.extend_from_slice(&ispe); + let ipco = bmff_box(b"ipco", &ipco); + let mut ipma = 1u32.to_be_bytes().to_vec(); + ipma.extend_from_slice(&1u16.to_be_bytes()); + ipma.extend_from_slice(&[2, 0x81, 0x02]); + let ipma = full_box(b"ipma", 0, &ipma); + let mut iprp = ipco; + iprp.extend_from_slice(&ipma); + let iprp = bmff_box(b"iprp", &iprp); + + let payload: Vec = { + let nal = [0x26, 0x01, 0xAF, 0x13, 0x9C, 0x50, 0x00, 0x00]; + let mut p = (nal.len() as u32).to_be_bytes().to_vec(); + p.extend_from_slice(&nal); + p + }; + + // iloc is built twice: once to learn the meta size, once with the real mdat offset. + let build = |offset: u32| { + let mut iloc = vec![0x44, 0x00]; + iloc.extend_from_slice(&1u16.to_be_bytes()); + iloc.extend_from_slice(&1u16.to_be_bytes()); + iloc.extend_from_slice(&0u16.to_be_bytes()); + iloc.extend_from_slice(&1u16.to_be_bytes()); + iloc.extend_from_slice(&offset.to_be_bytes()); + iloc.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + let iloc = full_box(b"iloc", 0, &iloc); + let mut meta = Vec::new(); + for part in [&hdlr, &pitm, &iinf, &iloc, &iprp] { + meta.extend_from_slice(part); + } + full_box(b"meta", 0, &meta) + }; + let meta_len = build(0).len(); + let offset = (ftyp.len() + meta_len + 8) as u32; + let meta = build(offset); + let mut out = ftyp; + out.extend_from_slice(&meta); + out.extend_from_slice(&bmff_box(b"mdat", &payload)); + out +} diff --git a/crates/raster/tests/heif.rs b/crates/raster/tests/heif.rs new file mode 100644 index 0000000..de426db --- /dev/null +++ b/crates/raster/tests/heif.rs @@ -0,0 +1,58 @@ +//! HEIC/HEIF goes through the OS codec. These tests only demand clean, typed outcomes. + +mod common; + +use std::time::{Duration, Instant}; + +use common::minimal_heic; +use pictor_raster::{HeifSupport, Limits, RasterError, decode, heif_support}; + +#[test] +fn heif_support_returns() { + let start = Instant::now(); + let s = heif_support(); + eprintln!("heif_support() = {s:?} in {:?}", start.elapsed()); + #[cfg(not(windows))] + assert_eq!(s, HeifSupport::Unavailable); + #[cfg(windows)] + assert_ne!(s, HeifSupport::Unavailable); +} + +#[test] +fn minimal_heic_gives_a_typed_error() { + let bytes = minimal_heic(64, 64); + let start = Instant::now(); + let result = decode(&bytes, &Limits::default()); + let took = start.elapsed(); + eprintln!("decode(minimal heic) = {:?} in {took:?}", result.as_ref().map(|i| (i.width(), i.height()))); + assert!(took < Duration::from_secs(20), "took {took:?}"); + let err = result.expect_err("the payload is not real HEVC"); + match &err { + RasterError::HeifCodecMissing { .. } => { + assert!(err.to_string().contains("9NMZLZ57R3T7"), "{err}"); + } + RasterError::Corrupt { .. } | RasterError::Os { .. } => { + // A machine with every codec installed rejects the dummy HEVC payload instead. + assert_eq!(heif_support(), HeifSupport::Ready, "{err:?}"); + } + other => panic!("unexpected {other:?}"), + } +} + +#[test] +fn heic_bomb_is_refused_before_the_os_codec() { + let bytes = minimal_heic(100_000, 100_000); + let err = decode(&bytes, &Limits::default()).unwrap_err(); + assert!(matches!(err, RasterError::TooManyPixels { width: 100_000, height: 100_000 }), "{err:?}"); +} + +#[test] +fn truncated_heic_does_not_hang_or_panic() { + let bytes = minimal_heic(64, 64); + for cut in [12, 24, 40, bytes.len() / 2, bytes.len() - 3] { + let start = Instant::now(); + let r = decode(&bytes[..cut], &Limits::default()); + assert!(r.is_err()); + assert!(start.elapsed() < Duration::from_secs(20)); + } +} diff --git a/crates/raster/tests/hostile.rs b/crates/raster/tests/hostile.rs new file mode 100644 index 0000000..b9f19ad --- /dev/null +++ b/crates/raster/tests/hostile.rs @@ -0,0 +1,190 @@ +//! Hostile inputs: bombs, truncation, garbage and mutation. Nothing may panic or allocate from a header. + +mod common; + +use std::time::{Duration, Instant}; + +use common::*; +use pictor_raster::{Format, Limits, RasterError, decode, probe}; + +fn limits() -> Limits { + Limits::default() +} + +#[test] +fn png_bomb_is_refused_by_the_pixel_cap_quickly() { + let bomb = png_with_size(100_000, 100_000); + assert!(bomb.len() < 100); + let start = Instant::now(); + let err = decode(&bomb, &limits()).unwrap_err(); + assert!(start.elapsed() < Duration::from_secs(1), "took {:?}", start.elapsed()); + match &err { + RasterError::TooManyPixels { width, height } => assert_eq!((*width, *height), (100_000, 100_000)), + other => panic!("expected TooManyPixels, got {other:?}"), + } + assert_eq!(err.to_string(), "This image is too large (100000 × 100000 pixels)."); + let p = probe(&bomb, &limits()).unwrap(); + assert_eq!((p.width, p.height, p.format), (100_000, 100_000, Format::Png)); +} + +#[test] +fn jpeg_with_huge_sof_is_refused() { + let bomb = patch_jpeg_sof(jpeg_fixture(32, 32), 65_000, 65_000); + let start = Instant::now(); + let err = decode(&bomb, &limits()).unwrap_err(); + assert!(start.elapsed() < Duration::from_secs(1)); + assert!(matches!(err, RasterError::TooManyPixels { width: 65_000, height: 65_000 }), "{err:?}"); +} + +#[test] +fn gif_bomb_by_header_is_refused() { + let bomb = gif_with_size(65_535, 65_535); + let start = Instant::now(); + let err = decode(&bomb, &limits()).unwrap_err(); + assert!(start.elapsed() < Duration::from_secs(1)); + assert!(matches!(err, RasterError::TooManyPixels { .. } | RasterError::Corrupt { .. }), "{err:?}"); +} + +#[test] +fn tiff_bomb_by_header_is_refused() { + let bomb = tiff_with_size(1_000_000, 1_000_000); + let start = Instant::now(); + let err = decode(&bomb, &limits()).unwrap_err(); + assert!(start.elapsed() < Duration::from_secs(1)); + assert!(matches!(err, RasterError::TooManyPixels { width: 1_000_000, height: 1_000_000 }), "{err:?}"); +} + +#[test] +fn a_tiny_cap_refuses_an_ordinary_image() { + let png = encode_with_image(&sample_rgb(64, 64), image::ImageFormat::Png); + let small = Limits { max_pixels: 1000, ..Limits::default() }; + assert!(matches!(decode(&png, &small), Err(RasterError::TooManyPixels { .. }))); + let tiny_input = Limits { max_input_bytes: 10, ..Limits::default() }; + assert!(matches!(decode(&png, &tiny_input), Err(RasterError::InputTooLarge { .. }))); + let tiny_alloc = Limits { max_alloc: 1000, ..Limits::default() }; + assert!(matches!(decode(&png, &tiny_alloc), Err(RasterError::TooMuchMemory { .. }))); +} + +#[test] +fn truncated_png_errors() { + let png = encode_with_image(&sample_rgb(200, 150), image::ImageFormat::Png); + let cut = &png[..png.len() * 6 / 10]; + let err = decode(cut, &limits()).unwrap_err(); + assert!(matches!(err, RasterError::Corrupt { format: Format::Png, .. }), "{err:?}"); +} + +#[test] +fn truncated_jpeg_does_not_panic() { + let jpeg = jpeg_fixture(200, 150); + let cut = &jpeg[..jpeg.len() * 6 / 10]; + // zune-jpeg may fill the missing part; both outcomes are acceptable as long as nothing panics. + match decode(cut, &limits()) { + Ok(img) => assert_eq!((img.width(), img.height()), (200, 150)), + Err(e) => assert!(matches!(e, RasterError::Corrupt { format: Format::Jpeg, .. }), "{e:?}"), + } +} + +#[test] +fn empty_and_random_inputs_are_typed_errors() { + assert!(matches!(decode(&[], &limits()), Err(RasterError::Empty))); + assert!(matches!(probe(&[], &limits()), Err(RasterError::Empty))); + let mut rng = XorShift::new(7); + for len in [1usize, 3, 16, 100, 4096] { + let junk: Vec = (0..len).map(|_| rng.byte()).collect(); + let err = decode(&junk, &limits()).unwrap_err(); + assert!(matches!(err, RasterError::UnknownFormat | RasterError::Corrupt { .. }), "{err:?}"); + } +} + +#[test] +fn bogus_ico_directory_is_a_typed_error() { + let ico = bogus_ico(); + assert_eq!(Format::sniff(&ico), Some(Format::Ico)); + let err = decode(&ico, &limits()).unwrap_err(); + assert!(matches!(err, RasterError::Corrupt { .. } | RasterError::TooManyPixels { .. }), "{err:?}"); + let _ = probe(&ico, &limits()); +} + +#[test] +fn every_error_message_is_plain_english() { + let samples: Vec = vec![ + decode(&[], &limits()).unwrap_err(), + decode(b"hello world, not an image", &limits()).unwrap_err(), + decode(&png_with_size(100_000, 100_000), &limits()).unwrap_err(), + decode(&bogus_ico(), &limits()).unwrap_err(), + ]; + for e in samples { + let msg = e.to_string(); + assert!(msg.ends_with('.'), "{msg}"); + assert!(!msg.contains("Error") && !msg.contains("{"), "{msg}"); + } +} + +fn valid_fixtures() -> Vec<(&'static str, Vec)> { + let rgb = sample_rgb(24, 16); + let rgba = sample_rgba(24, 16); + vec![ + ("png", encode_with_image(&rgba, image::ImageFormat::Png)), + ("jpeg", encode_with_image(&rgb, image::ImageFormat::Jpeg)), + ("jpeg-exif", jpeg_with_orientation(&encode_with_image(&rgb, image::ImageFormat::Jpeg), 6)), + ("gif", encode_with_image(&rgba, image::ImageFormat::Gif)), + ("bmp", encode_with_image(&rgb, image::ImageFormat::Bmp)), + ("tiff", encode_with_image(&rgba, image::ImageFormat::Tiff)), + ("webp", encode_with_image(&rgba, image::ImageFormat::WebP)), + ("ico", encode_with_image(&rgba, image::ImageFormat::Ico)), + ("heic", minimal_heic(64, 64)), + ] +} + +fn mutate(rng: &mut XorShift, src: &[u8]) -> Vec { + let mut m = src.to_vec(); + match rng.below(5) { + 0 => { + for _ in 0..1 + rng.below(8) { + let i = rng.below(m.len()); + m[i] = rng.byte(); + } + } + 1 => { + let i = rng.below(m.len()); + m[i] ^= 1 << rng.below(8); + } + 2 => m.truncate(rng.below(m.len())), + 3 => { + let i = rng.below(m.len()); + let extra: Vec = (0..1 + rng.below(16)).map(|_| rng.byte()).collect(); + m.splice(i..i, extra); + } + _ => { + // Header fields are where the interesting bugs live: hammer the first 64 bytes with 0xFF / 0x00. + let i = rng.below(m.len().min(64)); + m[i] = if rng.below(2) == 0 { 0xFF } else { 0x00 }; + } + } + m +} + +#[test] +fn mutation_loop_never_panics() { + let limits = Limits { max_pixels: 4_000_000, max_input_bytes: 1 << 20, max_alloc: 64 << 20 }; + let mut rng = XorShift::new(0x5EED_1234_ABCD); + let start = Instant::now(); + for (name, fixture) in valid_fixtures() { + if name != "heic" { + assert!(decode(&fixture, &limits).is_ok(), "fixture {name} must decode"); + } + // Each HEIC attempt activates the Store codec (~0.3 s), so it gets fewer rounds. + let rounds = if name == "heic" { 20 } else { 300 }; + let t = Instant::now(); + for round in 0..rounds { + let m = mutate(&mut rng, &fixture); + let caught = std::panic::catch_unwind(|| { + let _ = probe(&m, &limits); + let _ = decode(&m, &limits); + }); + assert!(caught.is_ok(), "panic on {name} mutation {round}"); + } + eprintln!("{name}: {rounds} mutations in {:?}", t.elapsed()); + } + eprintln!("mutation loop took {:?}", start.elapsed()); +} diff --git a/crates/raster/tests/roundtrip.rs b/crates/raster/tests/roundtrip.rs new file mode 100644 index 0000000..6e2df71 --- /dev/null +++ b/crates/raster/tests/roundtrip.rs @@ -0,0 +1,118 @@ +//! Every writable format encodes and decodes back. + +mod common; + +use common::*; +use image::{DynamicImage, GenericImageView}; +use pictor_raster::{EncodeOptions, Format, Limits, RasterError, decode, encode, probe}; + +fn round(img: &DynamicImage, format: Format) -> DynamicImage { + let bytes = encode(img, format, &EncodeOptions::default()).unwrap_or_else(|e| panic!("{format:?}: {e}")); + assert_eq!(Format::sniff(&bytes), Some(format), "sniff of encoded {format:?}"); + let p = probe(&bytes, &Limits::default()).unwrap(); + assert_eq!(p.format, format); + decode(&bytes, &Limits::default()).unwrap_or_else(|e| panic!("{format:?}: {e}")) +} + +#[test] +fn lossless_formats_are_pixel_identical() { + let rgba = sample_rgba(37, 23); + for format in [Format::Png, Format::Tiff, Format::WebP, Format::Bmp] { + let back = round(&rgba, format); + assert_eq!(back.dimensions(), (37, 23), "{format:?}"); + assert_eq!(back.to_rgba8().as_raw(), rgba.to_rgba8().as_raw(), "{format:?} pixels"); + } + let rgb = sample_rgb(37, 23); + for format in [Format::Png, Format::Tiff, Format::WebP, Format::Bmp] { + let back = round(&rgb, format); + assert_eq!(back.to_rgb8().as_raw(), rgb.to_rgb8().as_raw(), "{format:?} rgb pixels"); + } +} + +#[test] +fn jpeg_is_within_tolerance() { + let rgb = sample_rgb(64, 48); + let back = round(&rgb, Format::Jpeg); + assert_eq!(back.dimensions(), (64, 48)); + let (a, b) = (rgb.to_rgb8(), back.to_rgb8()); + let total: u64 = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| u64::from(x.abs_diff(*y))).sum(); + let mean = total as f64 / a.as_raw().len() as f64; + assert!(mean < 6.0, "mean abs error {mean}"); +} + +#[test] +fn jpeg_flattens_alpha_onto_white() { + let rgba = sample_rgba(32, 32); // the left quarter is fully transparent + let back = round(&rgba, Format::Jpeg).to_rgb8(); + let px = back.get_pixel(2, 16).0; + assert!(px.iter().all(|&c| c > 235), "transparent area should be white, got {px:?}"); +} + +#[test] +fn gif_keeps_dimensions() { + let back = round(&sample_rgba(40, 30), Format::Gif); + assert_eq!(back.dimensions(), (40, 30)); +} + +#[test] +fn ico_fits_256_and_pads_to_square() { + let back = round(&sample_rgba(48, 48), Format::Ico); + assert_eq!(back.dimensions(), (48, 48)); + + let big = sample_rgb(600, 300); + let back = round(&big, Format::Ico); + assert_eq!(back.dimensions(), (256, 256)); + let rgba = back.to_rgba8(); + assert_eq!(rgba.get_pixel(128, 2).0[3], 0, "padding is transparent"); + assert_eq!(rgba.get_pixel(128, 128).0[3], 255, "content is opaque"); +} + +#[test] +fn heif_output_is_a_typed_error() { + let err = encode(&sample_rgb(8, 8), Format::Heif, &EncodeOptions::default()).unwrap_err(); + assert!(matches!(err, RasterError::CannotWrite { format: Format::Heif }), "{err:?}"); + assert!(err.to_string().contains("HEIC")); +} + +#[test] +fn sixteen_bit_images_encode_everywhere() { + let img = DynamicImage::ImageRgba16(sample_rgba(20, 10).to_rgba16()); + for format in [Format::Png, Format::Jpeg, Format::WebP, Format::Bmp, Format::Gif, Format::Tiff, Format::Ico] { + let back = round(&img, format); + assert!(back.width() > 0, "{format:?}"); + } +} + +#[test] +fn sniff_and_names() { + assert_eq!(Format::from_name("jpg"), Some(Format::Jpeg)); + assert_eq!(Format::from_name(".JPEG"), Some(Format::Jpeg)); + assert_eq!(Format::from_name("photo.HEIC"), Some(Format::Heif)); + assert_eq!(Format::from_name("tif"), Some(Format::Tiff)); + assert_eq!(Format::from_name("avif"), Some(Format::Avif)); + assert_eq!(Format::from_name("exe"), None); + assert_eq!(Format::Jpeg.extension(), "jpg"); + assert_eq!(Format::Heif.extension(), "heic"); + assert_eq!(Format::sniff(&minimal_heic(10, 10)), Some(Format::Heif)); + let mut avif = minimal_heic(10, 10); + avif[8..12].copy_from_slice(b"avif"); + avif[16..24].copy_from_slice(b"mif1avif"); + assert_eq!(Format::sniff(&avif), Some(Format::Avif)); + assert!(Format::Avif.is_heif_family()); + assert_eq!(Format::sniff(b"GIF89a"), Some(Format::Gif)); + assert_eq!(Format::sniff(b"BM"), None, "too short to be a BMP"); + assert_eq!(Format::sniff(&[]), None); +} + +#[test] +fn probe_reports_alpha_and_frames() { + let png = encode(&sample_rgba(10, 12), Format::Png, &EncodeOptions::default()).unwrap(); + let p = probe(&png, &Limits::default()).unwrap(); + assert_eq!((p.width, p.height, p.has_alpha, p.frames), (10, 12, true, Some(1))); + let jpg = encode(&sample_rgb(10, 12), Format::Jpeg, &EncodeOptions::default()).unwrap(); + assert!(!probe(&jpg, &Limits::default()).unwrap().has_alpha); + let gif = encode(&sample_rgb(10, 12), Format::Gif, &EncodeOptions::default()).unwrap(); + assert_eq!(probe(&gif, &Limits::default()).unwrap().frames, Some(1)); + let heic = probe(&minimal_heic(4032, 3024), &Limits::default()).unwrap(); + assert_eq!((heic.format, heic.width, heic.height), (Format::Heif, 4032, 3024)); +} diff --git a/crates/raster/tests/transform.rs b/crates/raster/tests/transform.rs new file mode 100644 index 0000000..d0bc8c2 --- /dev/null +++ b/crates/raster/tests/transform.rs @@ -0,0 +1,152 @@ +//! Orientation, crop, rotate, resize, presets, compress-to-size. + +mod common; + +use common::*; +use image::GenericImageView; +use pictor_raster::{ + Fit, Format, Limits, Preset, RasterError, Rect, Rotation, apply_preset, compress_to, crop, decode, probe, resize, + rotate, +}; + +#[test] +fn exif_orientation_6_rotates_on_decode() { + // Left half red, right half blue, 40 × 20. + let mut img = image::RgbImage::new(40, 20); + for (x, _, px) in img.enumerate_pixels_mut() { + px.0 = if x < 20 { [255, 0, 0] } else { [0, 0, 255] }; + } + let jpeg = encode_with_image(&image::DynamicImage::ImageRgb8(img), image::ImageFormat::Jpeg); + let tagged = jpeg_with_orientation(&jpeg, 6); + let out = decode(&tagged, &Limits::default()).unwrap(); + assert_eq!(out.dimensions(), (20, 40), "width and height swap"); + // Orientation 6 means "rotate 90° clockwise to display": the left (red) half ends up on top. + let top = out.get_pixel(10, 5).0; + let bottom = out.get_pixel(10, 35).0; + assert!(top[0] > 200 && top[2] < 60, "top {top:?}"); + assert!(bottom[2] > 200 && bottom[0] < 60, "bottom {bottom:?}"); + // probe reports the stored size, before orientation. + let p = probe(&tagged, &Limits::default()).unwrap(); + assert_eq!((p.width, p.height), (40, 20)); +} + +#[test] +fn crop_checks_bounds() { + let img = sample_rgb(100, 50); + let c = crop(&img, Rect { x: 10, y: 5, width: 30, height: 20 }).unwrap(); + assert_eq!(c.dimensions(), (30, 20)); + assert_eq!(c.get_pixel(0, 0), img.get_pixel(10, 5)); + for bad in [ + Rect { x: 90, y: 0, width: 20, height: 10 }, + Rect { x: 0, y: 0, width: 0, height: 10 }, + Rect { x: u32::MAX, y: 0, width: 2, height: 2 }, + ] { + assert!(matches!(crop(&img, bad), Err(RasterError::InvalidCrop)), "{bad:?}"); + } +} + +#[test] +fn rotations() { + let img = sample_rgb(30, 10); + assert_eq!(rotate(&img, Rotation::Cw90).dimensions(), (10, 30)); + assert_eq!(rotate(&img, Rotation::Ccw90).dimensions(), (10, 30)); + assert_eq!(rotate(&img, Rotation::R180).dimensions(), (30, 10)); + assert_eq!(rotate(&img, Rotation::FlipH).get_pixel(0, 0), img.get_pixel(29, 0)); + assert_eq!(rotate(&img, Rotation::FlipV).get_pixel(0, 0), img.get_pixel(0, 9)); + assert_eq!(rotate(&img, Rotation::Cw90).get_pixel(9, 0), img.get_pixel(0, 0)); +} + +#[test] +fn resize_fits() { + let l = Limits::default(); + let img = sample_rgb(400, 200); + assert_eq!(resize(&img, Fit::LongEdge(100), &l).unwrap().dimensions(), (100, 50)); + assert_eq!(resize(&img, Fit::LongEdge(1000), &l).unwrap().dimensions(), (400, 200), "never upscales"); + assert_eq!(resize(&img, Fit::Exact(50, 70), &l).unwrap().dimensions(), (50, 70)); + assert_eq!(resize(&img, Fit::Percent(50.0), &l).unwrap().dimensions(), (200, 100)); + assert_eq!(resize(&img, Fit::Percent(0.01), &l).unwrap().dimensions(), (1, 1)); + for bad in [Fit::Percent(f32::NAN), Fit::Percent(-5.0), Fit::Percent(f32::INFINITY), Fit::Exact(0, 5)] { + assert!(matches!(resize(&img, bad, &l), Err(RasterError::InvalidSize)), "{bad:?}"); + } + let err = resize(&img, Fit::Exact(100_000, 100_000), &l).unwrap_err(); + assert!(matches!(err, RasterError::TooManyPixels { .. }), "{err:?}"); +} + +#[test] +fn email_preset_long_edge_1600_jpeg() { + let big = sample_rgb(3200, 2000); + let (bytes, format) = apply_preset(&big, Format::Png, Preset::Email).unwrap(); + assert_eq!(format, Format::Jpeg); + let p = probe(&bytes, &Limits::default()).unwrap(); + assert_eq!((p.width, p.height), (1600, 1000)); + + let small = sample_rgb(800, 600); + let (bytes, _) = apply_preset(&small, Format::Jpeg, Preset::Email).unwrap(); + let p = probe(&bytes, &Limits::default()).unwrap(); + assert_eq!((p.width, p.height), (800, 600), "never upscales"); +} + +#[test] +fn web_preset_keeps_alpha_as_png() { + let rgba = sample_rgba(3000, 1000); + let (bytes, format) = apply_preset(&rgba, Format::Png, Preset::Web).unwrap(); + assert_eq!(format, Format::Png); + let p = probe(&bytes, &Limits::default()).unwrap(); + assert_eq!((p.width, p.height), (2048, 683)); + + let (_, format) = apply_preset(&sample_rgb(300, 200), Format::Png, Preset::Web).unwrap(); + assert_eq!(format, Format::Jpeg); +} + +#[test] +fn original_preset_keeps_size_and_format() { + let img = sample_rgb(321, 123); + let (bytes, format) = apply_preset(&img, Format::Bmp, Preset::Original).unwrap(); + assert_eq!(format, Format::Bmp); + assert_eq!(decode(&bytes, &Limits::default()).unwrap().dimensions(), (321, 123)); + let (_, format) = apply_preset(&img, Format::Heif, Preset::Original).unwrap(); + assert_eq!(format, Format::Jpeg, "HEIC cannot be written, so Original falls back to JPEG"); +} + +#[test] +fn compress_noisy_photo_under_500_kb() { + let img = noisy_rgb(3000, 2000, 42); + let target = 500_000; + let c = compress_to(&img, Format::Jpeg, target, &Limits::default()).unwrap(); + eprintln!("compressed: {} bytes, q {:?}, scale {}, {}×{}", c.bytes.len(), c.quality, c.scale, c.width, c.height); + assert!(c.bytes.len() as u64 <= target); + let back = decode(&c.bytes, &Limits::default()).unwrap(); + assert_eq!(back.dimensions(), (c.width, c.height)); + assert!(c.width >= 320); +} + +#[test] +fn compress_easy_target_keeps_full_size() { + let img = sample_rgb(800, 600); + let c = compress_to(&img, Format::Jpeg, 2_000_000, &Limits::default()).unwrap(); + assert_eq!((c.width, c.height, c.scale), (800, 600, 1.0)); + assert_eq!(c.quality, Some(92)); +} + +#[test] +fn compress_impossible_target_reports_smallest() { + let img = noisy_rgb(1200, 800, 9); + match compress_to(&img, Format::Jpeg, 1_000, &Limits::default()) { + Err(RasterError::CannotReachTarget { smallest_bytes }) => assert!(smallest_bytes > 1_000), + other => panic!("expected CannotReachTarget, got {:?}", other.map(|c| c.bytes.len())), + } + match compress_to(&img, Format::Png, 1_000, &Limits::default()) { + Err(RasterError::CannotReachTarget { smallest_bytes }) => assert!(smallest_bytes > 1_000), + other => panic!("expected CannotReachTarget, got {:?}", other.map(|c| c.bytes.len())), + } +} + +#[test] +fn compress_png_scales_down() { + let img = noisy_rgb(1000, 800, 3); + let c = compress_to(&img, Format::Png, 600_000, &Limits::default()).unwrap(); + assert!(c.bytes.len() <= 600_000); + assert!(c.scale < 1.0); + assert_eq!(c.quality, None); + assert_eq!(c.format, Format::Png); +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index de4ca9d..b96f932 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -37,7 +37,7 @@ script exit 1, and the feature that needs it waits (the brief: "it never gets a | sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | | getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | | flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | -| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects | | rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | | proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | From 249c19ea614229acc60f582c118a87c376275490 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:30:42 +0100 Subject: [PATCH 07/13] [pdf] Pages: reorder, rotate, delete, blank, split, merge, images <-> PDF; text from rotated pages --- crates/pdf/src/pages.rs | 300 +++++++++++++++++++++++++++++++- crates/pdf/src/reader.rs | 354 ++++++++++++++++++++------------------ crates/pdf/src/redact.rs | 4 + crates/pdf/tests/pages.rs | 164 ++++++++++++++++++ 4 files changed, 651 insertions(+), 171 deletions(-) create mode 100644 crates/pdf/tests/pages.rs diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index e63a04d..59fa886 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -1 +1,299 @@ -//! Page operations, merge, split, images to PDF, PDF to images (pdfium). +//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form, +//! bookmarks and everything else of the document stay; merge with pdfium's page import; images → PDF with lopdf +//! (a JPEG goes in as it is, without re-encoding); PDF → images with pdfium. +use crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page}; +use image::{DynamicImage, GenericImageView}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; + +/// One page of the new order. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PageSpec { + /// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90). + Existing { + index: usize, + #[serde(default)] + rotate: i32, + }, + /// A blank page of this size in points. + Blank { width: f32, height: f32 }, +} + +const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"]; + +/// Copies inherited attributes down onto each page, so pages can be moved freely. +fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) { + for &page in pages { + for key in INHERITABLE { + if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) { + continue; + } + let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok()); + let mut depth = 0; + let mut value = None; + while let Some(id) = current { + depth += 1; + if depth > 64 { + break; + } + let Ok(d) = doc.get_dictionary(id) else { break }; + if let Ok(v) = d.get(key) { + value = Some(v.clone()); + break; + } + current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + } + if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) { + d.set(key, v); + } + } + } +} + +fn pages_root(doc: &Document) -> Result { + doc.catalog() + .ok() + .and_then(|c| c.get(b"Pages").ok()) + .and_then(|p| p.as_reference().ok()) + .ok_or_else(|| PdfError::Damaged("it has no page tree".into())) +} + +/// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields +/// that only lived on them. +pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, password)?; + reorganise_doc(&mut doc, specs)?; + doc.prune_objects(); + lopdf_save(&mut doc) +} + +pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> { + if specs.is_empty() { + return Err(PdfError::Invalid("A PDF needs at least one page.".into())); + } + let pages: Vec = doc.get_pages().values().copied().collect(); + materialise_inherited(doc, &pages); + let root = pages_root(doc)?; + let mut used = HashSet::new(); + let mut kids = Vec::new(); + for spec in specs { + match *spec { + PageSpec::Existing { index, rotate } => { + let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?; + if rotate % 90 != 0 { + return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into())); + } + // The same page twice: the second is a shallow copy (its content and resources are shared). + let id = if used.insert(src) { + src + } else { + let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + let mut copy = copy; + copy.remove(b"Annots"); + doc.add_object(copy) + }; + let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?; + let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0); + d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64); + d.set("Parent", root); + kids.push(Object::Reference(id)); + } + PageSpec::Blank { width, height } => { + if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) { + return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into())); + } + let content = doc.add_object(Stream::new(dictionary! {}, Vec::new())); + let id = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {}, + "MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)], + }); + kids.push(Object::Reference(id)); + } + } + } + // Annotations of deleted pages, and the fields that only lived there. + let mut removed = HashSet::new(); + for p in pages.iter().filter(|p| !used.contains(*p)) { + if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) { + removed.extend(a.iter().filter_map(|o| o.as_reference().ok())); + } + } + crate::redact::prune_form_pub(doc, &removed); + // Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead + // nowhere, which every viewer tolerates); so do their annotations. + for p in pages.iter().filter(|p| !used.contains(*p)) { + doc.objects.remove(p); + } + for a in &removed { + doc.objects.remove(a); + } + let count = kids.len() as i64; + let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + for key in INHERITABLE { + root_dict.remove(key); + } + root_dict.set("Kids", kids); + root_dict.set("Count", count); + root_dict.remove(b"Parent"); + doc.objects.insert(root, Object::Dictionary(root_dict)); + Ok(()) +} + +/// One document per range; `ranges` are 0-based inclusive page index pairs. +pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result>, PdfError> { + let mut out = Vec::new(); + for &(a, b) in ranges { + if a > b { + return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1))); + } + let specs: Vec = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect(); + out.push(reorganise(bytes, password, &specs)?); + } + Ok(out) +} + +/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages. +pub fn parse_ranges(text: &str, pages: usize) -> Result, PdfError> { + let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-.")); + let mut out = Vec::new(); + for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { + let (a, b) = match part.split_once(['-', '–']) { + Some((a, b)) => { + let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? }; + let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? }; + (a, b) + } + None => { + let n: usize = part.parse().map_err(|_| bad())?; + (n, n) + } + }; + if a == 0 || b == 0 || a > pages || b > pages { + return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them."))); + } + if a > b { + return Err(bad()); + } + out.push((a - 1, b - 1)); + } + if out.is_empty() { + return Err(bad()); + } + Ok(out) +} + +/// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look +/// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over. +pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result, PdfError> { + if inputs.len() < 2 { + return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into())); + } + let mut target = engine.new_document()?; + for (i, (bytes, password)) in inputs.iter().enumerate() { + let source = engine.open(bytes, *password).map_err(|e| match e { + PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)), + other => other, + })?; + target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?; + } + crate::engine::pdfium_save(&target) +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PageFit { + /// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one). + Image, + /// A4 portrait or landscape (whichever suits the image), with a margin. + A4, + Letter, +} + +/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly. +pub fn images_to_pdf(images: &[(Vec, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result, PdfError> { + if images.is_empty() { + return Err(PdfError::Invalid("Choose at least one image.".into())); + } + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let mut kids = Vec::new(); + for (bytes, img) in images { + let (w, h) = img.dimensions(); + let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]); + let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) { + let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" }; + let mut s = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"}, + bytes.clone(), + ); + s.allows_compression = false; + doc.add_object(s) + } else { + let rgba = img.to_rgba8(); + let has_alpha = rgba.pixels().any(|p| p.0[3] != 255); + let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); + let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, + "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}; + if has_alpha { + let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); + let mut smask = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, + alpha, + ); + let _ = smask.compress(); + dict.set("SMask", doc.add_object(smask)); + } + let mut s = Stream::new(dict, rgb); + let _ = s.compress(); + doc.add_object(s) + }; + let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75); + let (pw, ph) = match fit { + PageFit::Image => (iw, ih), + PageFit::A4 | PageFit::Letter => { + let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) }; + if w > h { (b, a) } else { (a, b) } + } + }; + let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) }; + let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image { 1.0 } else { f32::MAX }); + let (dw, dh) = (iw * scale, ih * scale); + let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0); + let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes(); + let content_id = doc.add_object(Stream::new(dictionary! {}, content)); + let page = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => content_id, + "MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)], + "Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])}, + }); + kids.push(Object::Reference(page)); + } + let count = kids.len() as i64; + doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count})); + let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); + doc.trailer.set("Root", catalog); + lopdf_save(&mut doc) +} + +/// Renders the chosen pages (0-based) at `dpi`. +pub fn pages_to_images( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + pages: &[usize], + dpi: u32, +) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for &i in pages { + let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?; + let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32; + drop(page); + out.push(render_doc_page(&doc, i, width, true)?); + } + Ok(out) +} diff --git a/crates/pdf/src/reader.rs b/crates/pdf/src/reader.rs index 5a49583..e4699f9 100644 --- a/crates/pdf/src/reader.rs +++ b/crates/pdf/src/reader.rs @@ -1,170 +1,184 @@ -//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a -//! file Edge opens, Pictor opens). -use crate::{Engine, PdfError, ViewRect}; -use image::DynamicImage; -use pdfium_render::prelude::*; -use serde::Serialize; - -/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). -pub const MAX_RENDER_PIXELS: i64 = 50_000_000; - -#[derive(Debug, Clone, Serialize)] -pub struct DocInfo { - pub pages: Vec, - pub outline: Vec, - pub has_form: bool, - pub encrypted: bool, -} - -#[derive(Debug, Clone, Serialize)] -pub struct PageInfo { - /// Displayed size in points. - pub width: f32, - pub height: f32, - pub label: Option, -} - -#[derive(Debug, Clone, Serialize)] -pub struct OutlineItem { - pub title: String, - pub page: Option, - pub depth: u32, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SearchHit { - pub page: usize, - /// The hit's boxes in view space. - pub rects: Vec, -} - -pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { - let doc = engine.open(bytes, password)?; - let mut pages = Vec::new(); - for page in doc.pages().iter() { - pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); - } - let mut outline = Vec::new(); - fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { - if *budget == 0 || depth > 32 { - return; - } - *budget -= 1; - let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); - out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); - if let Some(child) = b.first_child() { - let mut next = Some(child); - while let Some(c) = next { - next = c.next_sibling(); - walk(c, depth + 1, out, budget); - } - } - } - let mut budget = 5000; - let mut next = doc.bookmarks().root(); - while let Some(b) = next { - next = b.next_sibling(); - walk(b, 0, &mut outline, &mut budget); - } - let has_form = doc.form().is_some(); - Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) -} - -/// The displayed size of every page, in points. -pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { - let doc = engine.open(bytes, password)?; - Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) -} - -pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result { - let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; - let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); - let width = width_px.clamp(1, 20_000) as i64; - let height = ((width as f32) * h / w).ceil().max(1.0) as i64; - if width * height > MAX_RENDER_PIXELS { - return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); - } - let cfg = PdfRenderConfig::new() - .set_target_size(width as i32, height as i32) - .render_form_data(forms) - .render_annotations(true) - .set_clear_color(PdfColor::WHITE); - page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) -} - -/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. -pub fn render_page( - engine: &Engine, - bytes: &[u8], - password: Option<&str>, - index: usize, - width_px: u32, -) -> Result { - let doc = engine.open(bytes, password)?; - render_doc_page(&doc, index, width_px, true) -} - -/// The text of every page, in order. -pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { - let doc = engine.open(bytes, password)?; - let mut out = Vec::new(); - for page in doc.pages().iter() { - out.push(page.text().map(|t| t.all()).map_err(PdfError::from_pdfium)?); - } - Ok(out) -} - -/// Case-insensitive search over every page; at most `limit` hits. -pub fn search( - engine: &Engine, - bytes: &[u8], - password: Option<&str>, - query: &str, - limit: usize, -) -> Result, PdfError> { - if query.trim().is_empty() { - return Ok(Vec::new()); - } - let doc = engine.open(bytes, password)?; - let mut hits = Vec::new(); - for (i, page) in doc.pages().iter().enumerate() { - let frame = page_frame(&page); - let text = page.text().map_err(PdfError::from_pdfium)?; - let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; - while let Some(segments) = search.find_next() { - let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); - hits.push(SearchHit { page: i, rects }); - if hits.len() >= limit { - return Ok(hits); - } - } - } - Ok(hits) -} - -pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { - let crop = page.boundaries().crop().or_else(|_| page.boundaries().media()).map(|b| b.bounds).unwrap_or(PdfRect::ZERO); - let rotate = match page.rotation() { - Ok(PdfPageRenderRotation::Degrees90) => 90, - Ok(PdfPageRenderRotation::Degrees180) => 180, - Ok(PdfPageRenderRotation::Degrees270) => 270, - _ => 0, - }; - let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; - crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } -} - -impl crate::geometry::PageFrame { - /// A user-space rectangle → view space. - pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { - let [x0, y0, x1, y1] = self.crop; - let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); - let (vx0, vy0, vx1, vy1) = match self.rotate { - 90 => (b - y0, l - x0, t - y0, rt - x0), - 180 => (x1 - rt, b - y0, x1 - l, t - y0), - 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), - _ => (l - x0, y1 - t, rt - x0, y1 - b), - }; - ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } - } -} +//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a +//! file Edge opens, Pictor opens). +use crate::{Engine, PdfError, ViewRect}; +use image::DynamicImage; +use pdfium_render::prelude::*; +use serde::Serialize; + +/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). +pub const MAX_RENDER_PIXELS: i64 = 50_000_000; + +#[derive(Debug, Clone, Serialize)] +pub struct DocInfo { + pub pages: Vec, + pub outline: Vec, + pub has_form: bool, + pub encrypted: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PageInfo { + /// Displayed size in points. + pub width: f32, + pub height: f32, + pub label: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct OutlineItem { + pub title: String, + pub page: Option, + pub depth: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SearchHit { + pub page: usize, + /// The hit's boxes in view space. + pub rects: Vec, +} + +pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { + let doc = engine.open(bytes, password)?; + let mut pages = Vec::new(); + for page in doc.pages().iter() { + pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); + } + let mut outline = Vec::new(); + fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { + if *budget == 0 || depth > 32 { + return; + } + *budget -= 1; + let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); + out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); + if let Some(child) = b.first_child() { + let mut next = Some(child); + while let Some(c) = next { + next = c.next_sibling(); + walk(c, depth + 1, out, budget); + } + } + } + let mut budget = 5000; + let mut next = doc.bookmarks().root(); + while let Some(b) = next { + next = b.next_sibling(); + walk(b, 0, &mut outline, &mut budget); + } + let has_form = doc.form().is_some(); + Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) +} + +/// The displayed size of every page, in points. +pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) +} + +pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result { + let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; + let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); + let width = width_px.clamp(1, 20_000) as i64; + let height = ((width as f32) * h / w).ceil().max(1.0) as i64; + if width * height > MAX_RENDER_PIXELS { + return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); + } + let cfg = PdfRenderConfig::new() + .set_target_size(width as i32, height as i32) + .render_form_data(forms) + .render_annotations(true) + .set_clear_color(PdfColor::WHITE); + page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) +} + +/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. +pub fn render_page( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + index: usize, + width_px: u32, +) -> Result { + let doc = engine.open(bytes, password)?; + render_doc_page(&doc, index, width_px, true) +} + +/// The text of every page, in order. +pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for page in doc.pages().iter() { + out.push(page_text(&page)?); + } + Ok(out) +} + +/// Case-insensitive search over every page; at most `limit` hits. +pub fn search( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + query: &str, + limit: usize, +) -> Result, PdfError> { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + let doc = engine.open(bytes, password)?; + let mut hits = Vec::new(); + for (i, page) in doc.pages().iter().enumerate() { + let frame = page_frame(&page); + let text = page.text().map_err(PdfError::from_pdfium)?; + let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; + while let Some(segments) = search.find_next() { + let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); + hits.push(SearchHit { page: i, rects }); + if hits.len() >= limit { + return Ok(hits); + } + } + } + Ok(hits) +} + +/// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with +/// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.) +pub(crate) fn page_text(page: &PdfPage) -> Result { + let text = page.text().map_err(PdfError::from_pdfium)?; + Ok(text.inside_rect(PdfRect::new_from_values(-1.0e6, -1.0e6, 1.0e6, 1.0e6))) +} + +pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { + // `bounding` is pdfium's effective crop box (inherited boxes included); crop/media only read the page itself. + let crop = page + .boundaries() + .bounding() + .or_else(|_| page.boundaries().crop()) + .or_else(|_| page.boundaries().media()) + .map(|b| b.bounds) + .unwrap_or(PdfRect::ZERO); + let rotate = match page.rotation() { + Ok(PdfPageRenderRotation::Degrees90) => 90, + Ok(PdfPageRenderRotation::Degrees180) => 180, + Ok(PdfPageRenderRotation::Degrees270) => 270, + _ => 0, + }; + let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; + crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } +} + +impl crate::geometry::PageFrame { + /// A user-space rectangle → view space. + pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { + let [x0, y0, x1, y1] = self.crop; + let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); + let (vx0, vy0, vx1, vy1) = match self.rotate { + 90 => (b - y0, l - x0, t - y0, rt - x0), + 180 => (x1 - rt, b - y0, x1 - l, t - y0), + 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), + _ => (l - x0, y1 - t, rt - x0, y1 - b), + }; + ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } + } +} diff --git a/crates/pdf/src/redact.rs b/crates/pdf/src/redact.rs index 02045c7..ebe4a4d 100644 --- a/crates/pdf/src/redact.rs +++ b/crates/pdf/src/redact.rs @@ -212,6 +212,10 @@ fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSe } } +pub(crate) fn prune_form_pub(doc: &mut Document, removed: &HashSet) { + prune_form(doc, removed) +} + fn prune_form(doc: &mut Document, removed: &HashSet) { let Ok(catalog) = doc.catalog() else { return }; let acroform = match catalog.get(b"AcroForm") { diff --git a/crates/pdf/tests/pages.rs b/crates/pdf/tests/pages.rs new file mode 100644 index 0000000..662e35e --- /dev/null +++ b/crates/pdf/tests/pages.rs @@ -0,0 +1,164 @@ +//! Page operations, merge and split, images ↔ PDF, password on and off. +mod common; +use common::*; +use pictor_pdf::{PageFit, PageSpec, PdfError}; + +fn texts(bytes: &[u8], password: Option<&str>) -> Vec { + pictor_pdf::extract_text(engine(), bytes, password).unwrap().into_iter().map(|t| t.trim().to_string()).collect() +} + +#[test] +fn reorder_rotate_delete_and_insert_blank() { + let input = numbered_pdf(4, "Doc"); + let out = pictor_pdf::reorganise( + &input, + None, + &[ + PageSpec::Existing { index: 3, rotate: 0 }, + PageSpec::Blank { width: 595.0, height: 842.0 }, + PageSpec::Existing { index: 0, rotate: 90 }, + ], + ) + .unwrap(); + assert_eq!(texts(&out, None), ["Doc page 4", "", "Doc page 1"]); + let sizes = pictor_pdf::page_sizes(engine(), &out, None).unwrap(); + assert_eq!(sizes[2], (842.0, 595.0), "page 1 was not turned"); + // Deleted pages are gone from the file, not just from the page list. + for blob in scan_objects(&out) { + assert!(!contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"), "a deleted page survived in the file"); + } +} + +#[test] +fn rotation_accumulates_and_wraps() { + let input = numbered_pdf(1, "R"); + let once = pictor_pdf::reorganise(&input, None, &[PageSpec::Existing { index: 0, rotate: 270 }]).unwrap(); + let twice = pictor_pdf::reorganise(&once, None, &[PageSpec::Existing { index: 0, rotate: 180 }]).unwrap(); + let doc = lopdf::Document::load_mem(&twice).unwrap(); + let p = page_ids(&doc)[0]; + assert_eq!(doc.get_dictionary(p).unwrap().get(b"Rotate").unwrap().as_i64().unwrap(), 90); + assert!(pictor_pdf::reorganise(&input, None, &[PageSpec::Existing { index: 0, rotate: 45 }]).is_err()); +} + +#[test] +fn bad_page_specs_are_refused() { + let input = numbered_pdf(2, "X"); + assert!(matches!(pictor_pdf::reorganise(&input, None, &[]), Err(PdfError::Invalid(_)))); + assert!(matches!( + pictor_pdf::reorganise(&input, None, &[PageSpec::Existing { index: 2, rotate: 0 }]), + Err(PdfError::NoSuchPage(3)) + )); + assert!(pictor_pdf::reorganise(&input, None, &[PageSpec::Blank { width: 0.0, height: 10.0 }]).is_err()); +} + +#[test] +fn a_form_survives_reordering_and_loses_fields_of_deleted_pages() { + let input = secret_pdf(&Options::default()); + // Keep both pages, swapped: the field (on page 1) stays. + let swapped = pictor_pdf::reorganise( + &input, + None, + &[PageSpec::Existing { index: 1, rotate: 0 }, PageSpec::Existing { index: 0, rotate: 0 }], + ) + .unwrap(); + let doc = lopdf::Document::load_mem(&swapped).unwrap(); + assert!(doc.catalog().unwrap().get(b"AcroForm").is_ok(), "the form was lost by reordering"); + // Delete page 1: its field goes too. + let deleted = pictor_pdf::reorganise(&input, None, &[PageSpec::Existing { index: 1, rotate: 0 }]).unwrap(); + for blob in scan_objects(&deleted) { + assert!(!contains(&blob, "FORM-SECRET"), "the field of a deleted page survived"); + } +} + +#[test] +fn split_by_ranges_and_parse_them() { + let input = numbered_pdf(5, "S"); + let ranges = pictor_pdf::parse_ranges("1-2, 4, 5-", 5).unwrap(); + assert_eq!(ranges, [(0, 1), (3, 3), (4, 4)]); + let parts = pictor_pdf::split(&input, None, &ranges).unwrap(); + assert_eq!(parts.len(), 3); + assert_eq!(texts(&parts[0], None), ["S page 1", "S page 2"]); + assert_eq!(texts(&parts[1], None), ["S page 4"]); + assert_eq!(texts(&parts[2], None), ["S page 5"]); + for bad in ["", "0", "6", "3-2", "a-b", "1-9"] { + assert!(pictor_pdf::parse_ranges(bad, 5).is_err(), "{bad:?} was accepted"); + } +} + +#[test] +fn merge_keeps_order_and_needs_passwords() { + let a = numbered_pdf(2, "A"); + let b = numbered_pdf(1, "B"); + let out = pictor_pdf::merge(engine(), &[(&a, None), (&b, None)]).unwrap(); + assert_eq!(texts(&out, None), ["A page 1", "A page 2", "B page 1"]); + let locked = pictor_pdf::protect(&b, None, "pw", None).unwrap(); + assert!(pictor_pdf::merge(engine(), &[(&a, None), (&locked, None)]).is_err()); + let out = pictor_pdf::merge(engine(), &[(&a, None), (&locked, Some("pw"))]).unwrap(); + assert_eq!(texts(&out, None).len(), 3); + assert!(pictor_pdf::merge(engine(), &[(&a, None)]).is_err(), "merging one file was accepted"); +} + +#[test] +fn password_on_and_off() { + let input = numbered_pdf(1, "Locked"); + let locked = pictor_pdf::protect(&input, None, "Heslo123 ř", None).unwrap(); + assert!(pictor_pdf::is_encrypted(&locked)); + assert!(!pictor_pdf::is_encrypted(&input)); + // The text is not readable in the file and pdfium refuses it without the password. + assert!(!contains(&locked, "Locked page 1")); + assert!(matches!(pictor_pdf::extract_text(engine(), &locked, None), Err(PdfError::NeedsPassword))); + assert!(matches!(pictor_pdf::extract_text(engine(), &locked, Some("nope")), Err(PdfError::WrongPassword))); + assert_eq!(texts(&locked, Some("Heslo123 ř")), ["Locked page 1"]); + // Unlock needs the right password, then the file opens without one. + assert!(pictor_pdf::unlock(&locked, "nope").is_err()); + let open = pictor_pdf::unlock(&locked, "Heslo123 ř").unwrap(); + assert!(!pictor_pdf::is_encrypted(&open)); + assert_eq!(texts(&open, None), ["Locked page 1"]); + assert!(pictor_pdf::protect(&input, None, "", None).is_err(), "an empty password was accepted"); +} + +#[test] +fn images_to_pdf_and_back() { + let mut jpeg = Vec::new(); + let photo = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(400, 300, |x, y| image::Rgb([x as u8, y as u8, 128]))); + photo.write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap(); + let logo = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 200, |x, _| image::Rgba([255, 0, 0, if x < 50 { 255 } else { 0 }]))); + let mut png = Vec::new(); + logo.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pdf = pictor_pdf::images_to_pdf(&[(jpeg.clone(), photo.clone()), (png, logo)], PageFit::A4, 36.0).unwrap(); + // The JPEG is embedded byte for byte. + assert!(pdf.windows(jpeg.len()).any(|w| w == jpeg.as_slice()), "the JPEG was re-encoded"); + let sizes = pictor_pdf::page_sizes(engine(), &pdf, None).unwrap(); + assert_eq!(sizes.len(), 2); + assert!(sizes[0].0 > sizes[0].1, "a landscape photo should get a landscape A4 page"); + assert!(sizes[1].0 < sizes[1].1); + let back = pictor_pdf::pages_to_images(engine(), &pdf, None, &[0, 1], 72).unwrap(); + assert_eq!(back.len(), 2); + assert_eq!(back[0].width(), 842); + // Image-size pages: 400 × 300 px at 96 dpi = 300 × 225 pt. + let own = pictor_pdf::images_to_pdf(&[(jpeg, photo)], PageFit::Image, 0.0).unwrap(); + assert_eq!(pictor_pdf::page_sizes(engine(), &own, None).unwrap()[0], (300.0, 225.0)); + assert!(pictor_pdf::pages_to_images(engine(), &own, None, &[3], 72).is_err()); +} + +#[test] +fn search_finds_hits_in_view_space() { + let input = numbered_pdf(3, "Find"); + let hits = pictor_pdf::search(engine(), &input, None, "page 2", 10).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].page, 1); + let r = hits[0].rects[0]; + // The text sits at PDF y 700 on an 842 pt page → view y ≈ 142 minus the glyph height. + assert!(r.y > 100.0 && r.y < 145.0 && r.x > 72.0, "{r:?}"); + assert!(pictor_pdf::search(engine(), &input, None, " ", 10).unwrap().is_empty()); +} + +#[test] +fn info_lists_pages_and_outline() { + let input = secret_pdf(&Options::default()); + let info = pictor_pdf::info(engine(), &input, None).unwrap(); + assert_eq!(info.pages.len(), 2); + assert_eq!(info.outline.len(), 1); + assert_eq!(info.outline[0].page, Some(0)); + assert!(info.has_form); +} From 66aa2a1f18347d20e7ac2be88b38b2f90d789318 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:36:30 +0100 Subject: [PATCH 08/13] [pdf] Edits: form fill, annotations with their own appearances, signature stamps, flatten, password kept --- crates/pdf/Cargo.toml | 1 + crates/pdf/src/edit.rs | 970 ++++++++++++++++++++++++++++++++++++++- crates/pdf/tests/edit.rs | 274 +++++++++++ 3 files changed, 1244 insertions(+), 1 deletion(-) create mode 100644 crates/pdf/tests/edit.rs diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index ee43f81..33217d5 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -17,3 +17,4 @@ getrandom.workspace = true [dev-dependencies] flate2.workspace = true +serde_json.workspace = true diff --git a/crates/pdf/src/edit.rs b/crates/pdf/src/edit.rs index 6354e9c..a40f88f 100644 --- a/crates/pdf/src/edit.rs +++ b/crates/pdf/src/edit.rs @@ -1 +1,969 @@ -//! The edit pipeline (form fill, annotations, stamps, flatten, security). +//! The edit pipeline, in this order: pages → form values → annotations and stamps → flatten → redaction → +//! password. Page indices in every edit refer to the page order *after* the page step. +//! +//! - Form values (lopdf): `/V` on the field, the checkbox and radio states through `/AS`; text and choice fields +//! get `NeedAppearances` and pdfium then builds their appearance when the document is loaded with its form +//! (which `flatten` relies on; see the forms test). +//! - Annotations and stamps (lopdf): every annotation is written with its own appearance stream, so it looks the +//! same in every viewer; a stamp (the visual signature) goes into the page content itself. +//! - Flatten (pdfium `FPDFPage_Flatten`), then lopdf drops the form and every orphaned object. +use crate::geometry::{PageFrame, ViewPoint, ViewRect, normalise_rotate}; +use crate::{Engine, PdfError, PageSpec, Redaction, RedactOptions, lopdf_load, lopdf_save}; +use image::DynamicImage; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, StringFormat, dictionary}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Edits { + #[serde(default)] + pub pages: Option>, + #[serde(default)] + pub form: Vec, + #[serde(default)] + pub annotations: Vec, + #[serde(default)] + pub stamps: Vec, + #[serde(default)] + pub flatten: bool, + #[serde(default)] + pub redactions: Vec, + #[serde(default)] + pub security: Security, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Security { + /// A protected document stays protected with the password it was opened with. + #[default] + Keep, + Remove, + Set { password: String }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FieldValue { + /// The fully qualified field name ("parent.child"). + pub name: String, + pub value: FieldInput, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum FieldInput { + Text(String), + Check(bool), + /// A radio button's or a list's chosen option. + Choice(String), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Annotation { + pub page: usize, + #[serde(flatten)] + pub shape: Shape, + /// RGB, 0..1. + #[serde(default = "default_color")] + pub color: [f32; 3], + #[serde(default = "one")] + pub opacity: f32, + #[serde(default)] + pub contents: Option, +} + +fn default_color() -> [f32; 3] { + [1.0, 0.85, 0.0] +} +fn one() -> f32 { + 1.0 +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Shape { + Highlight { rects: Vec }, + Underline { rects: Vec }, + Strike { rects: Vec }, + /// A sticky note at a point; its text is `contents`. + Note { at: ViewPoint }, + FreeText { rect: ViewRect, text: String, size: f32 }, + Ink { strokes: Vec>, width: f32 }, + Rectangle { rect: ViewRect, width: f32 }, + Ellipse { rect: ViewRect, width: f32 }, + Line { from: ViewPoint, to: ViewPoint, width: f32, arrow: bool }, +} + +/// An image burned into a page (the visual signature): PNG or JPEG bytes, placed upright in `rect`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Stamp { + pub page: usize, + pub rect: ViewRect, + #[serde(with = "b64")] + pub image: Vec, +} + +mod b64 { + use serde::{Deserialize, Deserializer, Serializer}; + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + pub fn serialize(v: &[u8], s: S) -> Result { + let mut out = String::with_capacity(v.len().div_ceil(3) * 4); + for c in v.chunks(3) { + let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; + for i in 0..4 { + if i <= c.len() { + out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + s.serialize_str(&out) + } + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let s = String::deserialize(d)?; + let mut out = Vec::with_capacity(s.len() / 4 * 3); + let (mut acc, mut bits) = (0u32, 0); + for ch in s.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=') { + let v = T.iter().position(|&t| t == ch).ok_or_else(|| serde::de::Error::custom("bad base64"))? as u32; + acc = acc << 6 | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + Ok(out) + } +} + +#[derive(Debug, Clone)] +pub struct Applied { + pub bytes: Vec, + pub warnings: Vec, +} + +/// Applies `edits` to the document and returns the new file. +pub fn apply(engine: &Engine, bytes: &[u8], password: Option<&str>, edits: &Edits) -> Result { + let mut warnings = Vec::new(); + let mut cur: Vec = match password { + Some(p) => crate::unlock(bytes, p)?, + None => bytes.to_vec(), + }; + if let Some(specs) = &edits.pages { + cur = crate::reorganise(&cur, None, specs)?; + } + if !edits.form.is_empty() { + cur = fill_form(engine, &cur, &edits.form)?; + } + if !edits.annotations.is_empty() || !edits.stamps.is_empty() { + let mut doc = lopdf_load(&cur, None)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + for a in &edits.annotations { + let &page = pages.get(a.page).ok_or(PdfError::NoSuchPage(a.page + 1))?; + add_annotation(&mut doc, page, a)?; + } + for (i, s) in edits.stamps.iter().enumerate() { + let &page = pages.get(s.page).ok_or(PdfError::NoSuchPage(s.page + 1))?; + add_stamp(&mut doc, page, s, i)?; + } + cur = lopdf_save(&mut doc)?; + } + if edits.flatten { + cur = flatten(engine, &cur)?; + } + if !edits.redactions.is_empty() { + let r = crate::redact(engine, &cur, None, &edits.redactions, &RedactOptions::default())?; + warnings.extend(r.warnings); + cur = r.bytes; + } + match (&edits.security, password) { + (Security::Set { password }, _) => cur = crate::protect(&cur, None, password, None)?, + (Security::Keep, Some(p)) => { + cur = crate::protect(&cur, None, p, None)?; + } + _ => {} + } + Ok(Applied { bytes: cur, warnings }) +} + +// --------------------------------------------------------------------------------------------------------------- +// Geometry from lopdf (boxes and rotation, inherited ones included). + +fn inherited<'a>(doc: &'a Document, page: ObjectId, key: &[u8]) -> Option<&'a Object> { + let mut id = page; + for _ in 0..64 { + let d = doc.get_dictionary(id).ok()?; + if let Ok(v) = d.get(key) { + return Some(match v { + Object::Reference(r) => doc.get_object(*r).ok()?, + v => v, + }); + } + id = d.get(b"Parent").ok()?.as_reference().ok()?; + } + None +} + +fn number(o: &Object) -> Option { + match o { + Object::Integer(i) => Some(*i as f32), + Object::Real(r) => Some(*r), + _ => None, + } +} + +fn rect_of(o: Option<&Object>) -> Option<[f32; 4]> { + let a = o?.as_array().ok()?; + if a.len() != 4 { + return None; + } + let v: Vec = a.iter().filter_map(number).collect(); + (v.len() == 4).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) +} + +pub(crate) fn lopdf_frame(doc: &Document, page: ObjectId) -> PageFrame { + let media = rect_of(inherited(doc, page, b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]); + let crop = rect_of(inherited(doc, page, b"CropBox")) + .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])]) + .filter(|c| c[2] > c[0] && c[3] > c[1]) + .unwrap_or(media); + let rotate = inherited(doc, page, b"Rotate").and_then(|o| o.as_i64().ok()).map(normalise_rotate).unwrap_or(0); + PageFrame { crop, rotate } +} + +/// The matrix that draws a unit-less upright box (origin bottom-left, x right, y up, in points) at the view +/// rectangle `r`, whatever the page's rotation: [a b c d e f]. +fn upright_matrix(frame: &PageFrame, r: ViewRect) -> [f32; 6] { + let o = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h }); + let xr = frame.to_user(ViewPoint { x: r.x + 1.0, y: r.y + r.h }); + let yu = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h - 1.0 }); + [xr.0 - o.0, xr.1 - o.1, yu.0 - o.0, yu.1 - o.1, o.0, o.1] +} + +fn fmt(v: f32) -> String { + let s = format!("{v:.3}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +fn arr(v: &[f32]) -> Object { + Object::Array(v.iter().map(|&x| Object::Real(x)).collect()) +} + +/// A PDF text string: PDFDocEncoding when it is plain ASCII, else UTF-16BE with a BOM. +pub(crate) fn text_string(s: &str) -> Object { + if s.chars().all(|c| (' '..='~').contains(&c) || c == '\n') { + Object::String(s.as_bytes().to_vec(), StringFormat::Literal) + } else { + let mut v = vec![0xFE, 0xFF]; + for u in s.encode_utf16() { + v.extend_from_slice(&u.to_be_bytes()); + } + Object::String(v, StringFormat::Hexadecimal) + } +} + +fn add_to_annots(doc: &mut Document, page: ObjectId, annot: ObjectId) -> Result<(), PdfError> { + let existing = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Annots") { + Ok(Object::Array(a)) => a.clone(), + Ok(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), + _ => Vec::new(), + }; + let mut list = existing; + list.push(Object::Reference(annot)); + doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?.set("Annots", list); + Ok(()) +} + +// --------------------------------------------------------------------------------------------------------------- +// Annotations. + +/// Helvetica with WinAnsi plus the Czech and other Central European letters WinAnsi lacks (mapped into the unused +/// codes 1..31 through /Differences). Characters outside both become "?". +struct Latin2Font { + codes: Vec<(char, u8, &'static str)>, +} + +const EXTRA_GLYPHS: &[(char, &str)] = &[ + ('Á', "Aacute"), ('Č', "Ccaron"), ('č', "ccaron"), ('Ď', "Dcaron"), ('ď', "dcaron"), ('Ě', "Ecaron"), + ('ě', "ecaron"), ('Ň', "Ncaron"), ('ň', "ncaron"), ('Ř', "Rcaron"), ('ř', "rcaron"), ('Ť', "Tcaron"), + ('ť', "tcaron"), ('Ů', "Uring"), ('ů', "uring"), ('Ľ', "Lcaron"), ('ľ', "lcaron"), ('Ĺ', "Lacute"), + ('ĺ', "lacute"), ('Ŕ', "Racute"), ('ŕ', "racute"), ('Ą', "Aogonek"), ('ą', "aogonek"), ('Ę', "Eogonek"), + ('ę', "eogonek"), ('Ł', "Lslash"), ('ł', "lslash"), ('Ś', "Sacute"), ('ś', "sacute"), ('Ź', "Zacute"), + ('ź', "zacute"), ('Ż', "Zdotaccent"), ('ż', "zdotaccent"), ('Ć', "Cacute"), ('ć', "cacute"), ('Ń', "Nacute"), + ('ń', "nacute"), ('Ő', "Ohungarumlaut"), ('ő', "ohungarumlaut"), ('Ű', "Uhungarumlaut"), ('ű', "uhungarumlaut"), +]; + +fn winansi(c: char) -> Option { + let u = c as u32; + if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) { + return Some(u as u8); + } + const HIGH: &[(char, u8)] = &[ + ('€', 0x80), ('‚', 0x82), ('ƒ', 0x83), ('„', 0x84), ('…', 0x85), ('†', 0x86), ('‡', 0x87), ('ˆ', 0x88), + ('‰', 0x89), ('Š', 0x8A), ('‹', 0x8B), ('Œ', 0x8C), ('Ž', 0x8E), ('‘', 0x91), ('’', 0x92), ('“', 0x93), + ('”', 0x94), ('•', 0x95), ('–', 0x96), ('—', 0x97), ('˜', 0x98), ('™', 0x99), ('š', 0x9A), ('›', 0x9B), + ('œ', 0x9C), ('ž', 0x9E), ('Ÿ', 0x9F), + ]; + HIGH.iter().find(|(h, _)| *h == c).map(|(_, b)| *b) +} + +impl Latin2Font { + fn for_text(text: &str) -> Latin2Font { + let mut codes = Vec::new(); + let mut next = 1u8; + for c in text.chars() { + if winansi(c).is_some() || codes.iter().any(|(x, _, _)| *x == c) || next > 31 { + continue; + } + if let Some((_, name)) = EXTRA_GLYPHS.iter().find(|(g, _)| *g == c) { + codes.push((c, next, *name)); + next += 1; + } + } + Latin2Font { codes } + } + fn encode(&self, text: &str) -> Vec { + text.chars() + .map(|c| winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?')) + .collect() + } + fn dict(&self) -> Dictionary { + let mut enc = dictionary! {"Type" => "Encoding", "BaseEncoding" => "WinAnsiEncoding"}; + if !self.codes.is_empty() { + let mut diffs = Vec::new(); + for (_, code, name) in &self.codes { + diffs.push(Object::Integer(*code as i64)); + diffs.push(Object::Name(name.as_bytes().to_vec())); + } + enc.set("Differences", diffs); + } + dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => enc} + } +} + +fn pdf_string_bytes(b: &[u8]) -> String { + let mut s = String::from("("); + for &c in b { + match c { + b'(' | b')' | b'\\' => { + s.push('\\'); + s.push(c as char); + } + 32..=126 => s.push(c as char), + _ => s.push_str(&format!("\\{c:03o}")), + } + } + s.push(')'); + s +} + +/// Approximate Helvetica advance widths (per 1000 em) for wrapping free text. +fn helvetica_width(c: char) -> f32 { + match c { + 'i' | 'j' | 'l' | '\'' | '.' | ',' | ':' | ';' | '!' | '|' => 260.0, + 'f' | 't' | 'r' | 'I' | ' ' | '(' | ')' | '[' | ']' | '-' => 320.0, + 'm' | 'w' | 'M' | 'W' => 850.0, + 'A'..='Z' | 'Č' | 'Ř' | 'Š' | 'Ž' | 'Ů' | 'Ď' | 'Ť' | 'Ň' | 'Ě' => 680.0, + _ => 556.0, + } +} + +fn wrap(text: &str, size: f32, width: f32) -> Vec { + let mut lines = Vec::new(); + for para in text.split('\n') { + let mut line = String::new(); + let mut w = 0.0; + for word in para.split(' ') { + let ww: f32 = word.chars().map(helvetica_width).sum::() * size / 1000.0; + let space = if line.is_empty() { 0.0 } else { 320.0 * size / 1000.0 }; + if !line.is_empty() && w + space + ww > width { + lines.push(std::mem::take(&mut line)); + w = 0.0; + } else if !line.is_empty() { + line.push(' '); + w += space; + } + line.push_str(word); + w += ww; + } + lines.push(line); + } + lines +} + +fn check_view_rect(r: &ViewRect) -> Result<(), PdfError> { + if r.is_empty() || r.w > 1.0e5 || r.h > 1.0e5 { + return Err(PdfError::Invalid("An annotation has no size.".into())); + } + Ok(()) +} + +fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<(), PdfError> { + let frame = lopdf_frame(doc, page); + let [r, g, b] = a.color.map(|c| c.clamp(0.0, 1.0)); + let opacity = a.opacity.clamp(0.05, 1.0); + let rgb = format!("{} {} {}", fmt(r), fmt(g), fmt(b)); + let mut gs = dictionary! {"Type" => "ExtGState", "CA" => Object::Real(opacity), "ca" => Object::Real(opacity)}; + let (subtype, rect, content, extra): (&str, [f32; 4], String, Dictionary) = match &a.shape { + Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => { + if rects.is_empty() { + return Err(PdfError::Invalid("Mark some text first.".into())); + } + let mut quads = Vec::new(); + let mut ops = String::new(); + let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for vr in rects { + check_view_rect(vr)?; + // QuadPoints order: top-left, top-right, bottom-left, bottom-right (as the eye sees the text). + let tl = frame.to_user(ViewPoint { x: vr.x, y: vr.y }); + let tr = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y }); + let bl = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h }); + let br = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h }); + for p in [tl, tr, bl, br] { + quads.push(p.0); + quads.push(p.1); + bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; + } + match &a.shape { + Shape::Highlight { .. } => ops.push_str(&format!( + "{} {} m {} {} l {} {} l {} {} l h f\n", + fmt(tl.0), fmt(tl.1), fmt(tr.0), fmt(tr.1), fmt(br.0), fmt(br.1), fmt(bl.0), fmt(bl.1) + )), + _ => { + let t = if matches!(a.shape, Shape::Underline { .. }) { 0.93 } else { 0.55 }; + let lw = (vr.h * 0.07).max(0.8); + let p0 = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h * t }); + let p1 = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h * t }); + ops.push_str(&format!( + "{} w {} {} m {} {} l S\n", + fmt(lw), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1) + )); + } + } + } + let (sub, content) = match &a.shape { + Shape::Highlight { .. } => { + gs.set("BM", "Multiply"); + ("Highlight", format!("/GS0 gs {rgb} rg\n{ops}")) + } + Shape::Underline { .. } => ("Underline", format!("/GS0 gs {rgb} RG\n{ops}")), + _ => ("StrikeOut", format!("/GS0 gs {rgb} RG\n{ops}")), + }; + (sub, bounds, content, dictionary! {"QuadPoints" => arr(&quads)}) + } + Shape::Note { at } => { + let p = frame.to_user(*at); + let rect = [p.0, p.1 - 20.0, p.0 + 20.0, p.1]; + let [x, y] = [rect[0], rect[1]]; + let content = format!( + "/GS0 gs {rgb} rg 0.25 0.2 0.1 RG 1 w {x0} {y0} 18 18 re B\n0.25 0.2 0.1 RG 1 w {lx} {l1} m {rx} {l1} l {lx} {l2} m {rx} {l2} l {lx} {l3} m {rx2} {l3} l S\n", + x0 = fmt(x + 1.0), y0 = fmt(y + 1.0), lx = fmt(x + 4.0), rx = fmt(x + 16.0), rx2 = fmt(x + 12.0), + l1 = fmt(y + 14.0), l2 = fmt(y + 10.0), l3 = fmt(y + 6.0) + ); + ("Text", rect, content, dictionary! {"Name" => "Comment", "Open" => false}) + } + Shape::FreeText { rect: vr, text, size } => { + check_view_rect(vr)?; + let size = size.clamp(4.0, 144.0); + let font = Latin2Font::for_text(text); + let m = upright_matrix(&frame, *vr); + let mut ops = format!( + "/GS0 gs q {} {} {} {} {} {} cm BT /Helv {} Tf {rgb} rg {} TL\n", + fmt(m[0]), fmt(m[1]), fmt(m[2]), fmt(m[3]), fmt(m[4]), fmt(m[5]), fmt(size), fmt(size * 1.2) + ); + ops.push_str(&format!("2 {} Td\n", fmt(vr.h - size))); + for (i, line) in wrap(text, size, vr.w - 4.0).iter().enumerate() { + if (i as f32 + 1.0) * size * 1.2 > vr.h + size { + break; + } + if i > 0 { + ops.push_str("T*\n"); + } + ops.push_str(&pdf_string_bytes(&font.encode(line))); + ops.push_str(" Tj\n"); + } + ops.push_str("ET Q\n"); + let user = frame.rect_to_user(*vr); + let extra = dictionary! { + "DA" => Object::String(format!("/Helv {} Tf {rgb} rg", fmt(size)).into_bytes(), StringFormat::Literal), + "Contents" => text_string(text), + "PictorFont" => font.dict(), + }; + ("FreeText", user, ops, extra) + } + Shape::Ink { strokes, width } => { + let w = width.clamp(0.25, 72.0); + let mut ink = Vec::new(); + let mut ops = format!("/GS0 gs {rgb} RG {} w 1 J 1 j\n", fmt(w)); + let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for stroke in strokes.iter().filter(|s| !s.is_empty()).take(2000) { + let pts: Vec<(f32, f32)> = stroke.iter().take(20_000).map(|p| frame.to_user(*p)).collect(); + let mut flat = Vec::new(); + for (i, p) in pts.iter().enumerate() { + flat.push(p.0); + flat.push(p.1); + bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; + ops.push_str(&format!("{} {} {}\n", fmt(p.0), fmt(p.1), if i == 0 { "m" } else { "l" })); + } + if pts.len() == 1 { + ops.push_str(&format!("{} {} l\n", fmt(pts[0].0 + 0.01), fmt(pts[0].1))); + } + ops.push_str("S\n"); + ink.push(arr(&flat)); + } + if ink.is_empty() { + return Err(PdfError::Invalid("Draw something first.".into())); + } + let pad = w; + let rect = [bounds[0] - pad, bounds[1] - pad, bounds[2] + pad, bounds[3] + pad]; + ( + "Ink", + rect, + ops, + dictionary! {"InkList" => Object::Array(ink), "BS" => dictionary! {"W" => Object::Real(w)}}, + ) + } + Shape::Rectangle { rect: vr, width } | Shape::Ellipse { rect: vr, width } => { + check_view_rect(vr)?; + let w = width.clamp(0.25, 72.0); + let u = frame.rect_to_user(*vr); + let [x0, y0, x1, y1] = [u[0] + w / 2.0, u[1] + w / 2.0, u[2] - w / 2.0, u[3] - w / 2.0]; + let path = if matches!(a.shape, Shape::Rectangle { .. }) { + format!("{} {} {} {} re S\n", fmt(x0), fmt(y0), fmt(x1 - x0), fmt(y1 - y0)) + } else { + let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0, (y1 - y0) / 2.0); + let k = 0.552_284_8; + format!( + "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c S\n", + fmt(cx + rx), fmt(cy), + fmt(cx + rx), fmt(cy + k * ry), fmt(cx + k * rx), fmt(cy + ry), fmt(cx), fmt(cy + ry), + fmt(cx - k * rx), fmt(cy + ry), fmt(cx - rx), fmt(cy + k * ry), fmt(cx - rx), fmt(cy), + fmt(cx - rx), fmt(cy - k * ry), fmt(cx - k * rx), fmt(cy - ry), fmt(cx), fmt(cy - ry), + fmt(cx + k * rx), fmt(cy - ry), fmt(cx + rx), fmt(cy - k * ry), fmt(cx + rx), fmt(cy) + ) + }; + let sub = if matches!(a.shape, Shape::Rectangle { .. }) { "Square" } else { "Circle" }; + (sub, u, format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)), dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}}) + } + Shape::Line { from, to, width, arrow } => { + let w = width.clamp(0.25, 72.0); + let p0 = frame.to_user(*from); + let p1 = frame.to_user(*to); + let mut ops = format!("/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n", fmt(w), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1)); + let head = (w * 4.0).max(8.0); + if *arrow { + let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); + let len = (dx * dx + dy * dy).sqrt().max(0.001); + let (ux, uy) = (dx / len, dy / len); + let (bx, by) = (p1.0 - ux * head, p1.1 - uy * head); + let (px, py) = (-uy * head * 0.5, ux * head * 0.5); + ops.push_str(&format!( + "{} {} m {} {} l {} {} l h f\n", + fmt(p1.0), fmt(p1.1), fmt(bx + px), fmt(by + py), fmt(bx - px), fmt(by - py) + )); + } + let pad = head + w; + let rect = [p0.0.min(p1.0) - pad, p0.1.min(p1.1) - pad, p0.0.max(p1.0) + pad, p0.1.max(p1.1) + pad]; + let mut extra = dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}}; + if *arrow { + extra.set("LE", vec![Object::Name(b"None".to_vec()), Object::Name(b"OpenArrow".to_vec())]); + } + ("Line", rect, ops, extra) + } + }; + if !rect.iter().all(|v| v.is_finite()) { + return Err(PdfError::Invalid("An annotation lies outside the page.".into())); + } + let mut resources = dictionary! {"ExtGState" => dictionary! {"GS0" => gs}}; + let mut extra = extra; + if let Some(Object::Dictionary(font)) = extra.remove(b"PictorFont") { + resources.set("Font", dictionary! {"Helv" => font}); + } + let ap = doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => arr(&rect), "Resources" => resources}, + content.into_bytes(), + )); + let mut annot = dictionary! { + "Type" => "Annot", "Subtype" => subtype, "Rect" => arr(&rect), "C" => arr(&[r, g, b]), + "F" => if subtype == "Text" { 28 } else { 4 }, "P" => page, + "AP" => dictionary! {"N" => ap}, + "NM" => Object::String(format!("pictor-{}", doc.max_id + 1).into_bytes(), StringFormat::Literal), + "T" => Object::String(b"Pictor".to_vec(), StringFormat::Literal), + }; + if let Some(c) = &a.contents { + annot.set("Contents", text_string(c)); + } + for (k, v) in extra.into_iter() { + annot.set(k, v); + } + let id = doc.add_object(annot); + add_to_annots(doc, page, id) +} + +// --------------------------------------------------------------------------------------------------------------- +// Stamps (the visual signature): an image drawn into the page content. + +fn add_stamp(doc: &mut Document, page: ObjectId, s: &Stamp, n: usize) -> Result<(), PdfError> { + check_view_rect(&s.rect)?; + if s.image.len() > 32 << 20 { + return Err(PdfError::TooLarge("the signature image is over 32 MB".into())); + } + let img: DynamicImage = image::load_from_memory(&s.image) + .map_err(|_| PdfError::Invalid("The signature image could not be read.".into()))?; + if (img.width() as u64) * (img.height() as u64) > 25_000_000 { + return Err(PdfError::TooLarge("the signature image is too large".into())); + } + let rgba = img.to_rgba8(); + let (w, h) = rgba.dimensions(); + let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); + let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); + let mut smask = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, + alpha, + ); + let _ = smask.compress(); + let smask = doc.add_object(smask); + let mut im = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "SMask" => smask}, + rgb, + ); + let _ = im.compress(); + let im = doc.add_object(im); + // Fit the image into the box, keeping its aspect ratio, centred. + let scale = (s.rect.w / w as f32).min(s.rect.h / h as f32); + let (dw, dh) = (w as f32 * scale, h as f32 * scale); + let r = ViewRect { x: s.rect.x + (s.rect.w - dw) / 2.0, y: s.rect.y + (s.rect.h - dh) / 2.0, w: dw, h: dh }; + let frame = lopdf_frame(doc, page); + let m = upright_matrix(&frame, r); + let name = format!("PictorStamp{n}"); + let ops = format!( + "q {} {} {} {} {} {} cm /{name} Do Q\n", + fmt(m[0] * dw), fmt(m[1] * dw), fmt(m[2] * dh), fmt(m[3] * dh), fmt(m[4]), fmt(m[5]) + ); + // Resources: a page-local copy (it may have been shared or inherited), with the image added. + let resources = match inherited(doc, page, b"Resources") { + Some(Object::Dictionary(d)) => d.clone(), + _ => Dictionary::new(), + }; + let mut resources = resources; + let mut xobjects = match resources.get(b"XObject") { + Ok(Object::Dictionary(d)) => d.clone(), + Ok(Object::Reference(r)) => doc.get_dictionary(*r).cloned().unwrap_or_default(), + _ => Dictionary::new(), + }; + xobjects.set(name.as_bytes(), im); + resources.set("XObject", xobjects); + // Contents: the old content wrapped in q … Q so its graphics state cannot leak into the stamp. + let old = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Contents") { + Ok(Object::Array(a)) => a.clone(), + Ok(Object::Reference(r)) => match doc.get_object(*r) { + Ok(Object::Array(a)) => a.clone(), + _ => vec![Object::Reference(*r)], + }, + _ => Vec::new(), + }; + let open = doc.add_object(Stream::new(dictionary! {}, b"q\n".to_vec())); + let close = doc.add_object(Stream::new(dictionary! {}, format!("\nQ\n{ops}").into_bytes())); + let mut contents = vec![Object::Reference(open)]; + contents.extend(old); + contents.push(Object::Reference(close)); + let d = doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?; + d.set("Resources", resources); + d.set("Contents", contents); + Ok(()) +} + +// --------------------------------------------------------------------------------------------------------------- +// Forms. + +#[derive(Debug, Clone, Serialize)] +pub struct FormField { + pub name: String, + /// "text", "checkbox", "radio", "choice", "signature" or "button". + pub kind: String, + pub value: String, + pub options: Vec, + pub page: Option, + pub rect: Option, + pub read_only: bool, + pub multiline: bool, +} + +struct Terminal { + name: String, + id: ObjectId, + widgets: Vec, +} + +fn field_tree(doc: &Document) -> Vec { + let Some(fields) = doc + .catalog() + .ok() + .and_then(|c| c.get(b"AcroForm").ok()) + .and_then(|f| match f { + Object::Reference(r) => doc.get_dictionary(*r).ok(), + Object::Dictionary(d) => Some(d), + _ => None, + }) + .and_then(|f| f.get(b"Fields").ok()) + .and_then(|f| match f { + Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_array().ok()), + Object::Array(a) => Some(a), + _ => None, + }) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); + fn walk(doc: &Document, id: ObjectId, prefix: &str, out: &mut Vec, seen: &mut std::collections::HashSet, depth: u32) { + if depth > 32 || !seen.insert(id) || out.len() > 10_000 { + return; + } + let Ok(d) = doc.get_dictionary(id) else { return }; + let own = d.get(b"T").ok().and_then(|t| t.as_str().ok()).map(decode_text); + let name = match (&own, prefix.is_empty()) { + (Some(t), true) => t.clone(), + (Some(t), false) => format!("{prefix}.{t}"), + (None, _) => prefix.to_string(), + }; + let kids: Vec = match d.get(b"Kids") { + Ok(Object::Array(a)) => a.iter().filter_map(|k| k.as_reference().ok()).collect(), + _ => Vec::new(), + }; + // Kids with their own /T are fields; kids without are this field's widgets. + let (fields, widgets): (Vec, Vec) = + kids.iter().partition(|k| doc.get_dictionary(**k).map(|d| d.has(b"T")).unwrap_or(false)); + if fields.is_empty() { + let widgets = if widgets.is_empty() { vec![id] } else { widgets }; + out.push(Terminal { name, id, widgets }); + } else { + for f in fields { + walk(doc, f, &name, out, seen, depth + 1); + } + } + } + for f in fields.iter().filter_map(|f| f.as_reference().ok()) { + walk(doc, f, "", &mut out, &mut seen, 0); + } + out +} + +pub(crate) fn decode_text(b: &[u8]) -> String { + if b.starts_with(&[0xFE, 0xFF]) { + let u: Vec = b[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&u) + } else { + b.iter().map(|&c| c as char).collect() + } +} + +fn field_attr<'a>(doc: &'a Document, id: ObjectId, key: &[u8]) -> Option<&'a Object> { + inherited(doc, id, key) +} + +fn on_state(doc: &Document, widget: ObjectId) -> Option> { + let ap = doc.get_dictionary(widget).ok()?.get(b"AP").ok()?; + let ap = match ap { + Object::Reference(r) => doc.get_dictionary(*r).ok()?, + Object::Dictionary(d) => d, + _ => return None, + }; + let n = match ap.get(b"N").ok()? { + Object::Reference(r) => doc.get_dictionary(*r).ok()?, + Object::Dictionary(d) => d, + _ => return None, + }; + n.iter().map(|(k, _)| k.clone()).find(|k| k != b"Off") +} + +/// The fields of the document's form, for the UI's form panel. +pub fn form_fields(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = lopdf_load(bytes, password)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + let mut out = Vec::new(); + for t in field_tree(&doc) { + let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b""); + let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); + let kind = match ft { + b"Tx" => "text", + b"Btn" if flags & (1 << 16) != 0 => "button", + b"Btn" if flags & (1 << 15) != 0 => "radio", + b"Btn" => "checkbox", + b"Ch" => "choice", + b"Sig" => "signature", + _ => continue, + }; + let value = match field_attr(&doc, t.id, b"V") { + Some(Object::String(s, _)) => decode_text(s), + Some(Object::Name(n)) => String::from_utf8_lossy(n).into_owned(), + _ => String::new(), + }; + let mut options = Vec::new(); + if kind == "choice" + && let Some(Object::Array(opts)) = field_attr(&doc, t.id, b"Opt") + { + for o in opts.iter().take(1000) { + let o = match o { + Object::Array(pair) => pair.get(1).cloned().unwrap_or(Object::Null), + o => o.clone(), + }; + if let Object::String(s, _) = o { + options.push(decode_text(&s)); + } + } + } + if kind == "radio" { + for w in &t.widgets { + if let Some(s) = on_state(&doc, *w) { + options.push(String::from_utf8_lossy(&s).into_owned()); + } + } + } + let first = t.widgets.first().copied(); + let page = first.and_then(|w| { + let p = doc.get_dictionary(w).ok()?.get(b"P").ok()?.as_reference().ok()?; + pages.iter().position(|x| *x == p) + }); + let page = page.or_else(|| { + first.and_then(|w| { + pages.iter().position(|p| match doc.get_dictionary(*p).ok().and_then(|d| d.get(b"Annots").ok()) { + Some(Object::Array(a)) => a.iter().any(|x| x.as_reference().ok() == Some(w)), + _ => false, + }) + }) + }); + let rect = match (page, first) { + (Some(p), Some(w)) => rect_of(doc.get_dictionary(w).ok().and_then(|d| d.get(b"Rect").ok())).map(|r| { + let f = lopdf_frame(&doc, pages[p]); + let pr = pdfium_render::prelude::PdfRect::new_from_values(r[1], r[0], r[3], r[2]); + f.user_to_view(pr) + }), + _ => None, + }; + out.push(FormField { + name: t.name, + kind: kind.into(), + value, + options, + page, + rect, + read_only: flags & 1 != 0, + multiline: kind == "text" && flags & (1 << 12) != 0, + }); + } + let _ = engine; + Ok(out) +} + +fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, None)?; + let tree = field_tree(&doc); + let mut needs_appearances = false; + for v in values { + let t = tree + .iter() + .find(|t| t.name == v.name) + .ok_or_else(|| PdfError::Invalid(format!("This PDF has no field named \"{}\".", v.name)))?; + let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b"").to_vec(); + let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); + if flags & 1 != 0 { + return Err(PdfError::Invalid(format!("The field \"{}\" is read-only.", v.name))); + } + let set = |doc: &mut Document, id: ObjectId, key: &str, val: Object| { + if let Ok(d) = doc.get_dictionary_mut(id) { + d.set(key, val); + } + }; + match (&ft[..], &v.value) { + (b"Tx", FieldInput::Text(s)) | (b"Ch", FieldInput::Choice(s)) | (b"Ch", FieldInput::Text(s)) => { + set(&mut doc, t.id, "V", text_string(s)); + for w in &t.widgets { + if let Ok(d) = doc.get_dictionary_mut(*w) { + d.remove(b"AP"); + } + } + needs_appearances = true; + } + (b"Btn", FieldInput::Check(on)) if flags & (3 << 15) == 0 => { + for w in &t.widgets { + let state = if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() }; + set(&mut doc, *w, "AS", Object::Name(state.clone())); + set(&mut doc, t.id, "V", Object::Name(state)); + } + } + (b"Btn", FieldInput::Choice(choice)) if flags & (1 << 15) != 0 => { + let mut found = false; + for w in &t.widgets { + let on = on_state(&doc, *w); + let this = on.as_deref() == Some(choice.as_bytes()); + found |= this; + set(&mut doc, *w, "AS", Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() })); + } + if !found { + return Err(PdfError::Invalid(format!("\"{choice}\" is not an option of \"{}\".", v.name))); + } + set(&mut doc, t.id, "V", Object::Name(choice.as_bytes().to_vec())); + } + _ => return Err(PdfError::Invalid(format!("That value does not fit the field \"{}\".", v.name))), + } + } + if needs_appearances { + let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?; + let form = doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"AcroForm").ok()).cloned(); + match form { + Some(Object::Reference(r)) => { + if let Ok(d) = doc.get_dictionary_mut(r) { + d.set("NeedAppearances", true); + } + } + Some(Object::Dictionary(mut d)) => { + d.set("NeedAppearances", true); + if let Ok(c) = doc.get_dictionary_mut(catalog_id) { + c.set("AcroForm", d); + } + } + _ => {} + } + } + let plain = lopdf_save(&mut doc)?; + if !needs_appearances { + return Ok(plain); + } + // Let pdfium build the missing appearances (it does so when it loads a form with NeedAppearances), so viewers + // that ignore the flag show the values too. + regenerate_appearances(engine, &plain) +} + +fn regenerate_appearances(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { + let doc = engine.open(bytes, None)?; + for page in doc.pages().iter() { + // Rendering with the form draws every widget, which makes pdfium create its appearance stream. + let cfg = pdfium_render::prelude::PdfRenderConfig::new().set_target_width(64).render_form_data(true); + let _ = page.render_with_config(&cfg); + } + crate::engine::pdfium_save(&doc) +} + +/// Flattens annotations and form fields into the page content, then drops the form and every orphaned object. +pub fn flatten(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { + let mut doc = engine.open(bytes, None)?; + let n = doc.pages().len(); + for i in 0..n { + let mut page = doc.pages_mut().get(i).map_err(PdfError::from_pdfium)?; + page.flatten().map_err(PdfError::from_pdfium)?; + } + let flat = crate::engine::pdfium_save(&doc)?; + drop(doc); + let mut doc = lopdf_load(&flat, None)?; + if let Ok(catalog_id) = doc.trailer.get(b"Root").and_then(Object::as_reference) + && let Ok(c) = doc.get_dictionary_mut(catalog_id) + { + c.remove(b"AcroForm"); + } + doc.prune_objects(); + lopdf_save(&mut doc) +} diff --git a/crates/pdf/tests/edit.rs b/crates/pdf/tests/edit.rs new file mode 100644 index 0000000..f263b47 --- /dev/null +++ b/crates/pdf/tests/edit.rs @@ -0,0 +1,274 @@ +//! The edit pipeline: form values, annotations, the signature stamp, flatten, and the password kept. +mod common; +use common::*; +use lopdf::{Document, Object, Stream, StringFormat, dictionary}; +use pictor_pdf::{Annotation, Edits, FieldInput, FieldValue, Security, Shape, Stamp, ViewPoint, ViewRect}; + +fn s(t: &str) -> Object { + Object::String(t.as_bytes().to_vec(), StringFormat::Literal) +} + +/// One A4 page with a text field, a checkbox whose on-state is "Ano", a radio pair (A, B) and a combo box. +fn form_pdf() -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let page_id = doc.new_object_id(); + let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"}); + let zadb = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "ZapfDingbats"}); + let ap = |doc: &mut Document, body: &[u8]| { + doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 20.into(), 20.into()], + "Resources" => dictionary! {"Font" => dictionary! {"ZaDb" => zadb}}}, + body.to_vec(), + )) + }; + let on = ap(&mut doc, b"q 0 g BT /ZaDb 14 Tf 3 4 Td (4) Tj ET Q"); + let off = ap(&mut doc, b""); + let name = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Tx", "T" => s("name"), "DA" => s("/Helv 12 Tf 0 g"), + "Rect" => vec![100.into(), 700.into(), 400.into(), 724.into()], "F" => 4, "P" => page_id, + }); + let agree = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Btn", "T" => s("agree"), "V" => "Off", "AS" => "Off", + "Rect" => vec![100.into(), 650.into(), 120.into(), 670.into()], "F" => 4, "P" => page_id, + "AP" => dictionary! {"N" => dictionary! {"Ano" => on, "Off" => off}}, + }); + let radio_id = doc.new_object_id(); + let mut kids = Vec::new(); + for (i, st) in ["A", "B"].iter().enumerate() { + let on = ap(&mut doc, b"q 0 g BT /ZaDb 14 Tf 3 4 Td (l) Tj ET Q"); + let off = ap(&mut doc, b""); + let x = 100 + i as i64 * 40; + kids.push(Object::Reference(doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "Parent" => radio_id, "AS" => "Off", "F" => 4, "P" => page_id, + "Rect" => vec![x.into(), 600.into(), (x + 20).into(), 620.into()], + "AP" => dictionary! {"N" => lopdf::Dictionary::from_iter([(st.as_bytes().to_vec(), Object::Reference(on)), (b"Off".to_vec(), Object::Reference(off))])}, + }))); + } + doc.objects.insert( + radio_id, + Object::Dictionary(dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()}), + ); + let city = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"), + "Opt" => vec![s("Brno"), s("Praha")], "DA" => s("/Helv 12 Tf 0 g"), + "Rect" => vec![100.into(), 540.into(), 300.into(), 564.into()], "F" => 4, "P" => page_id, + }); + let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 12 Tf 72 780 Td (Form) Tj ET".to_vec())); + let mut annots = vec![name.into(), agree.into(), city.into()]; + annots.extend(kids); + doc.objects.insert(page_id, Object::Dictionary(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}}, + })); + doc.objects.insert(pages_id, Object::Dictionary(dictionary! { + "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + })); + let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id, + "AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()], + "DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}}); + doc.trailer.set("Root", catalog); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +fn fill() -> Edits { + Edits { + form: vec![ + FieldValue { name: "name".into(), value: FieldInput::Text("Jan Novák Řehoř".into()) }, + FieldValue { name: "agree".into(), value: FieldInput::Check(true) }, + FieldValue { name: "size".into(), value: FieldInput::Choice("B".into()) }, + FieldValue { name: "city".into(), value: FieldInput::Choice("Praha".into()) }, + ], + ..Default::default() + } +} + +fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize { + let (x0, y0) = ((r.x * scale) as u32, (r.y * scale) as u32); + let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32); + (y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::() < 300).count() +} + +#[test] +fn form_fields_are_listed_and_filled() { + let input = form_pdf(); + let fields = pictor_pdf::form_fields(engine(), &input, None).unwrap(); + let names: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["name", "agree", "size", "city"]); + assert_eq!(fields[2].options, ["A", "B"]); + assert_eq!(fields[3].options, ["Brno", "Praha"]); + assert_eq!(fields[0].page, Some(0)); + let out = pictor_pdf::apply(engine(), &input, None, &fill()).unwrap().bytes; + let after = pictor_pdf::form_fields(engine(), &out, None).unwrap(); + let value = |n: &str| after.iter().find(|f| f.name == n).unwrap().value.clone(); + assert_eq!(value("name"), "Jan Novák Řehoř"); + assert_eq!(value("agree"), "Ano", "the checkbox's own on-state must be used, not \"Yes\""); + assert_eq!(value("size"), "B"); + assert_eq!(value("city"), "Praha"); + // The text value is drawn (pdfium built its appearance). + let img = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8(); + assert!(dark_pixels(&img, after[0].rect.unwrap(), 1.0) > 20, "the filled text is not visible"); +} + +#[test] +fn a_filled_form_flattens_into_page_text() { + let mut edits = fill(); + edits.flatten = true; + let out = pictor_pdf::apply(engine(), &form_pdf(), None, &edits).unwrap().bytes; + let text = pictor_pdf::extract_text(engine(), &out, None).unwrap().concat(); + assert!(text.contains("Jan Novák Řehoř"), "flattened text field value missing: {text:?}"); + assert!(text.contains("Praha"), "flattened choice value missing: {text:?}"); + let doc = Document::load_mem(&out).unwrap(); + assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening"); + let p = page_ids(&doc)[0]; + assert!(doc.get_dictionary(p).unwrap().get(b"Annots").map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false)).unwrap_or(true)); +} + +#[test] +fn bad_form_values_are_refused() { + let input = form_pdf(); + for (name, value) in [ + ("nope", FieldInput::Text("x".into())), + ("size", FieldInput::Choice("C".into())), + ("agree", FieldInput::Text("x".into())), + ] { + let edits = Edits { form: vec![FieldValue { name: name.into(), value }], ..Default::default() }; + assert!(pictor_pdf::apply(engine(), &input, None, &edits).is_err(), "{name} accepted a bad value"); + } +} + +fn every_annotation() -> Vec { + let r = |x, y, w, h| ViewRect { x, y, w, h }; + let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None }; + vec![ + Annotation { color: [1.0, 0.9, 0.0], opacity: 0.5, ..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] }) }, + a(Shape::Underline { rects: vec![r(60.0, 150.0, 200.0, 20.0)] }), + a(Shape::Strike { rects: vec![r(60.0, 190.0, 200.0, 20.0)] }), + Annotation { contents: Some("Zkontrolovat čísla".into()), ..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } }) }, + a(Shape::FreeText { rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0 }), + a(Shape::Ink { strokes: vec![vec![ViewPoint { x: 60.0, y: 330.0 }, ViewPoint { x: 160.0, y: 380.0 }, ViewPoint { x: 260.0, y: 330.0 }]], width: 3.0 }), + a(Shape::Rectangle { rect: r(300.0, 330.0, 100.0, 50.0), width: 2.0 }), + a(Shape::Ellipse { rect: r(420.0, 330.0, 100.0, 50.0), width: 2.0 }), + a(Shape::Line { from: ViewPoint { x: 60.0, y: 420.0 }, to: ViewPoint { x: 300.0, y: 460.0 }, width: 3.0, arrow: true }), + ] +} + +#[test] +fn every_annotation_kind_is_written_with_an_appearance_and_shows() { + let input = numbered_pdf(1, "Annotated"); + let before = pictor_pdf::render_page(engine(), &input, None, 0, 595).unwrap().to_rgb8(); + let edits = Edits { annotations: every_annotation(), ..Default::default() }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let doc = Document::load_mem(&out).unwrap(); + let p = page_ids(&doc)[0]; + let annots = doc.get_dictionary(p).unwrap().get(b"Annots").unwrap().as_array().unwrap().clone(); + let subtypes: Vec = annots + .iter() + .map(|a| { + let d = doc.get_dictionary(a.as_reference().unwrap()).unwrap(); + assert!(d.get(b"AP").is_ok(), "an annotation without an appearance"); + String::from_utf8(d.get(b"Subtype").unwrap().as_name().unwrap().to_vec()).unwrap() + }) + .collect(); + assert_eq!(subtypes, ["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]); + let after = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8(); + for a in every_annotation() { + let r = match &a.shape { + Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => rects[0], + Shape::Note { at } => ViewRect { x: at.x, y: at.y, w: 20.0, h: 20.0 }, + Shape::FreeText { rect, .. } | Shape::Rectangle { rect, .. } | Shape::Ellipse { rect, .. } => *rect, + Shape::Ink { .. } => ViewRect { x: 60.0, y: 330.0, w: 200.0, h: 50.0 }, + Shape::Line { .. } => ViewRect { x: 60.0, y: 420.0, w: 240.0, h: 40.0 }, + }; + let changed = (r.y as u32..(r.y + r.h) as u32) + .flat_map(|y| (r.x as u32..(r.x + r.w) as u32).map(move |x| (x, y))) + .filter(|&(x, y)| before.get_pixel(x, y) != after.get_pixel(x, y)) + .count(); + assert!(changed > 10, "{:?} did not show ({changed} pixels changed)", a.shape); + } + // The free text's Czech letters survive as text once flattened. + let flat = pictor_pdf::flatten(engine(), &out).unwrap(); + let text = pictor_pdf::extract_text(engine(), &flat, None).unwrap().concat(); + assert!(text.contains("Příliš žluťoučký kůň"), "free text lost its letters: {text:?}"); +} + +#[test] +fn a_free_text_on_a_rotated_page_lands_where_it_was_drawn() { + let input = pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }]).unwrap(); + let rect = ViewRect { x: 100.0, y: 300.0, w: 300.0, h: 40.0 }; + let edits = Edits { + annotations: vec![Annotation { + page: 0, + shape: Shape::FreeText { rect, text: "MMMMMMMMMMMM".into(), size: 24.0 }, + color: [0.0, 0.0, 0.0], + opacity: 1.0, + contents: None, + }], + ..Default::default() + }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let img = pictor_pdf::render_page(engine(), &out, None, 0, 842).unwrap().to_rgb8(); + assert!(dark_pixels(&img, rect, 1.0) > 200, "the text is not inside its box on a rotated page"); + // Upright: the ink is spread wide (horizontally), not tall. + let rows_with_ink = (rect.y as u32..(rect.y + rect.h) as u32) + .filter(|&y| (rect.x as u32..(rect.x + rect.w) as u32).any(|x| img.get_pixel(x, y).0[0] < 100)) + .count(); + assert!(rows_with_ink < 40, "the text looks rotated"); +} + +fn signature_png() -> Vec { + let img = image::RgbaImage::from_fn(300, 100, |x, y| { + let on = ((y as i32 - 50) - ((x as f32 / 20.0).sin() * 30.0) as i32).abs() < 4; + if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) } + }); + let mut out = Vec::new(); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn a_signature_stamp_is_burned_into_the_page() { + let input = numbered_pdf(2, "Contract"); + let rect = ViewRect { x: 300.0, y: 700.0, w: 200.0, h: 80.0 }; + let edits = Edits { stamps: vec![Stamp { page: 1, rect, image: signature_png() }], ..Default::default() }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let img = pictor_pdf::render_page(engine(), &out, None, 1, 595).unwrap().to_rgb8(); + let red = (700..780).flat_map(|y| (300..500).map(move |x| (x, y))).filter(|&(x, y)| { + let p = img.get_pixel(x, y).0; + p[0] > 150 && p[1] < 80 + }).count(); + assert!(red > 100, "the signature is not visible ({red} red pixels)"); + // Transparent parts stay transparent: the page is white just above the signature's line. + assert_eq!(img.get_pixel(305, 702).0, [255, 255, 255]); + // The page's own text is untouched, and the stamp is page content, not an annotation. + assert_eq!(pictor_pdf::extract_text(engine(), &out, None).unwrap()[1].trim(), "Contract page 2"); + let doc = Document::load_mem(&out).unwrap(); + assert!(doc.get_dictionary(page_ids(&doc)[1]).unwrap().get(b"Annots").is_err()); + // A broken image is refused. + let bad = Edits { stamps: vec![Stamp { page: 0, rect, image: b"not a png".to_vec() }], ..Default::default() }; + assert!(pictor_pdf::apply(engine(), &input, None, &bad).is_err()); +} + +#[test] +fn a_protected_document_stays_protected_with_its_password() { + let locked = pictor_pdf::protect(&numbered_pdf(1, "Secret"), None, "pw", None).unwrap(); + let edits = Edits { annotations: vec![every_annotation().remove(0)], ..Default::default() }; + let out = pictor_pdf::apply(engine(), &locked, Some("pw"), &edits).unwrap().bytes; + assert!(pictor_pdf::is_encrypted(&out)); + assert_eq!(pictor_pdf::extract_text(engine(), &out, Some("pw")).unwrap()[0].trim(), "Secret page 1"); + let removed = pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() }).unwrap().bytes; + assert!(!pictor_pdf::is_encrypted(&removed)); + assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err()); +} + +#[test] +fn edits_serialise_for_the_worker() { + let edits = Edits { annotations: every_annotation(), stamps: vec![Stamp { page: 0, rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 }, image: vec![0, 1, 2, 250, 255] }], ..Default::default() }; + let json = serde_json::to_string(&edits).unwrap(); + let back: Edits = serde_json::from_str(&json).unwrap(); + assert_eq!(back.annotations.len(), 9); + assert_eq!(back.stamps[0].image, vec![0, 1, 2, 250, 255]); +} From 81628d4b511d76e3f1be25c885f87e13e935dcbf Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:53:44 +0100 Subject: [PATCH 09/13] [worker] pictor-worker: JSON-lines ops, Job Object memory cap, time caps, hostile PDF tests --- Cargo.lock | 1605 ++++++++++++++++++++++++++++ crates/worker/Cargo.toml | 35 + crates/worker/src/client.rs | 312 ++++++ crates/worker/src/lib.rs | 93 ++ crates/worker/src/main.rs | 54 + crates/worker/src/ops.rs | 443 ++++++++ crates/worker/tests/hostile_pdf.rs | 294 +++++ 7 files changed, 2836 insertions(+) create mode 100644 Cargo.lock create mode 100644 crates/worker/Cargo.toml create mode 100644 crates/worker/src/client.rs create mode 100644 crates/worker/src/lib.rs create mode 100644 crates/worker/src/main.rs create mode 100644 crates/worker/src/ops.rs create mode 100644 crates/worker/tests/hostile_pdf.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0369da4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1605 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "console_log" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" +dependencies = [ + "log", + "web-sys", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "g2gen" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5a7e0eb46f83a20260b850117d204366674e85d3a908d90865c78df9a6b1dfc" +dependencies = [ + "g2poly", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "g2p" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539e2644c030d3bf4cd208cb842d2ce2f80e82e6e8472390bcef83ceba0d80ad" +dependencies = [ + "g2gen", + "g2poly", +] + +[[package]] +name = "g2poly" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312d2295c7302019c395cfb90dacd00a82a2eabd700429bba9c7a3f38dbbe11b" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error 2.0.1", +] + +[[package]] +name = "img-parts" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93567ea8788640e566a8992a28f4ff64a89b88a369ad05c4198ea6dc8a42ce2b" +dependencies = [ + "bytes", + "crc32fast", + "miniz_oxide 0.9.1", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kamadak-exif" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8772c92c0f41c4a672cbdee6728253e5ae8fcc1c5eb5c6c676579565684bbf68" +dependencies = [ + "mutate_once", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lopdf" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6ad532ff9262dd4bfd6e085400cbb39959d48cb8d08518b01b68f77bdf6feca" +dependencies = [ + "aes", + "bitflags", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand", + "rangemap", + "sha2", + "stringprep", + "thiserror", + "weezl 0.2.1", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "serde", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "mutate_once" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pdfium-render" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" +dependencies = [ + "bitflags", + "bytemuck", + "bytes", + "chrono", + "console_error_panic_hook", + "console_log", + "image", + "itertools", + "js-sys", + "libloading", + "log", + "maybe-owned", + "once_cell", + "utf16string", + "vecmath", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "pictor-meta" +version = "0.1.0" +dependencies = [ + "image", + "img-parts", + "kamadak-exif", + "lopdf", + "serde", + "thiserror", +] + +[[package]] +name = "pictor-pdf" +version = "0.1.0" +dependencies = [ + "flate2", + "getrandom", + "image", + "lopdf", + "pdfium-render", + "pictor-meta", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pictor-qr" +version = "0.1.0" +dependencies = [ + "image", + "qrcode", + "rqrr", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pictor-raster" +version = "0.1.0" +dependencies = [ + "image", + "proptest", + "serde", + "thiserror", + "windows", +] + +[[package]] +name = "pictor-save" +version = "0.1.0" +dependencies = [ + "tempfile", + "thiserror", +] + +[[package]] +name = "pictor-worker" +version = "0.1.0" +dependencies = [ + "base64", + "flate2", + "image", + "lopdf", + "pictor-meta", + "pictor-pdf", + "pictor-qr", + "pictor-raster", + "pictor-save", + "serde", + "serde_json", + "tempfile", + "thiserror", + "windows", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piston-float" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rqrr" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d084c50c5cfa397a081850da329566c8667b0b6c4e81da16abff1fef27de93b" +dependencies = [ + "g2p", + "image", + "lru", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error 2.0.1", + "weezl 0.1.12", + "zune-jpeg", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "utf16string" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" +dependencies = [ + "byteorder", +] + +[[package]] +name = "vecmath" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +dependencies = [ + "piston-float", +] + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml new file mode 100644 index 0000000..f5e4e16 --- /dev/null +++ b/crates/worker/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "pictor-worker" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lib] +name = "pictor_worker" +path = "src/lib.rs" + +[[bin]] +name = "pictor-worker" +path = "src/main.rs" + +[dependencies] +thiserror.workspace = true +serde.workspace = true +serde_json.workspace = true +base64.workspace = true +image.workspace = true +pictor-raster.workspace = true +pictor-pdf.workspace = true +pictor-meta.workspace = true +pictor-qr.workspace = true +pictor-save.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] } + +[dev-dependencies] +tempfile.workspace = true +lopdf.workspace = true +flate2.workspace = true diff --git a/crates/worker/src/client.rs b/crates/worker/src/client.rs new file mode 100644 index 0000000..7909bfb --- /dev/null +++ b/crates/worker/src/client.rs @@ -0,0 +1,312 @@ +//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does. +//! +//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so +//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts +//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`). +use crate::{OpError, PROTOCOL}; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +#[derive(Debug, Clone)] +pub struct WorkerOptions { + pub exe: PathBuf, + /// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR). + pub pdfium_dir: Option, + /// The worker's memory cap. + pub memory_mb: u64, + /// Enables the debug.* operations (tests). + pub debug: bool, +} + +impl WorkerOptions { + pub fn new(exe: impl Into) -> WorkerOptions { + WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum WorkerError { + /// The operation failed cleanly (bad file, wrong password, …): show `message`. + #[error("{0}")] + Op(OpError), + #[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")] + TimedOut(u64), + #[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")] + OutOfMemory, + #[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")] + Crashed(String), + #[error("Pictor's file reader could not start: {0}")] + Spawn(String), +} + +impl WorkerError { + /// A short machine-readable kind, like [`OpError::kind`]. + pub fn kind(&self) -> &str { + match self { + WorkerError::Op(e) => &e.kind, + WorkerError::TimedOut(_) => "timed_out", + WorkerError::OutOfMemory => "out_of_memory", + WorkerError::Crashed(_) => "crashed", + WorkerError::Spawn(_) => "spawn", + } + } +} + +struct Running { + child: Child, + stdin: ChildStdin, + lines: Receiver, + stderr: Arc>, + #[cfg(windows)] + _job: job::Job, +} + +pub struct Worker { + opts: WorkerOptions, + running: Option, + next_id: u64, + /// Set when the worker had to be restarted since the caller last asked (open documents are gone). + restarted: bool, +} + +impl Worker { + pub fn new(opts: WorkerOptions) -> Worker { + Worker { opts, running: None, next_id: 1, restarted: false } + } + + pub fn exe(&self) -> &Path { + &self.opts.exe + } + + /// True once after the worker was restarted (its open documents are gone). + pub fn take_restarted(&mut self) -> bool { + std::mem::take(&mut self.restarted) + } + + fn spawn(&mut self) -> Result<(), WorkerError> { + let mut cmd = Command::new(&self.opts.exe); + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + if let Some(d) = &self.opts.pdfium_dir { + cmd.env("PICTOR_PDFIUM_DIR", d); + } + if self.opts.debug { + cmd.env("PICTOR_WORKER_DEBUG", "1"); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?; + #[cfg(windows)] + let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) { + Ok(j) => j, + Err(e) => { + let _ = child.kill(); + return Err(WorkerError::Spawn(format!("job object: {e}"))); + } + }; + let stdin = child.stdin.take().expect("piped"); + let stdout = child.stdout.take().expect("piped"); + let stderr_pipe = child.stderr.take().expect("piped"); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut r = BufReader::new(stdout); + loop { + let mut line = String::new(); + match r.read_line(&mut line) { + Ok(0) | Err(_) => return, + Ok(_) => { + if tx.send(line).is_err() { + return; + } + } + } + } + }); + let stderr = Arc::new(Mutex::new(String::new())); + let sink = stderr.clone(); + std::thread::spawn(move || { + let mut r = BufReader::new(stderr_pipe); + let mut line = String::new(); + while let Ok(n) = r.read_line(&mut line) { + if n == 0 { + return; + } + let mut s = sink.lock().unwrap_or_else(|p| p.into_inner()); + if s.len() < 16 << 10 { + s.push_str(&line); + } + line.clear(); + } + }); + let mut running = Running { + child, + stdin, + lines: rx, + stderr, + #[cfg(windows)] + _job: job, + }; + let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| { + let _ = running.child.kill(); + WorkerError::Spawn("it did not answer".into()) + })?; + let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?; + if hello["protocol"].as_u64() != Some(PROTOCOL as u64) { + let _ = running.child.kill(); + return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"]))); + } + self.running = Some(running); + Ok(()) + } + + fn kill(&mut self) { + if let Some(mut r) = self.running.take() { + let _ = r.child.kill(); + let _ = r.child.wait(); + self.restarted = true; + } + } + + /// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed. + pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result { + if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) { + self.kill(); + } + if self.running.is_none() { + self.spawn()?; + } + let id = self.next_id; + self.next_id += 1; + let r = self.running.as_mut().expect("spawned"); + let line = json!({"id": id, "op": op, "args": args}).to_string(); + if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() { + return Err(self.died()); + } + let deadline = std::time::Instant::now() + timeout; + loop { + let r = self.running.as_mut().expect("spawned"); + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match r.lines.recv_timeout(left) { + Ok(text) => { + let v: Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(_) => continue, + }; + if v["id"].as_u64() != Some(id) { + continue; // a late answer to a request that already timed out + } + if let Some(ok) = v.get("ok") { + return Ok(ok.clone()); + } + let err: OpError = serde_json::from_value(v["err"].clone()) + .unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer.")); + return Err(WorkerError::Op(err)); + } + Err(RecvTimeoutError::Timeout) => { + self.kill(); + return Err(WorkerError::TimedOut(timeout.as_secs().max(1))); + } + Err(RecvTimeoutError::Disconnected) => return Err(self.died()), + } + } + } + + fn died(&mut self) -> WorkerError { + let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default(); + // Give the stderr thread a moment to collect the last words. + std::thread::sleep(Duration::from_millis(50)); + let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr); + // pdfium aborts without a word when an allocation fails; the job's peak memory tells that story. + #[cfg(windows)] + let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9); + #[cfg(not(windows))] + let hit_cap = false; + self.kill(); + if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") { + WorkerError::OutOfMemory + } else { + WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string()) + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.kill(); + } +} + +#[cfg(windows)] +mod job { + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::System::JobObjects::*; + use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; + + pub struct Job(HANDLE); + unsafe impl Send for Job {} + + impl Job { + pub fn new(memory_mb: u64) -> Result { + unsafe { + let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?; + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20; + SetInformationJobObject( + h, + JobObjectExtendedLimitInformation, + &info as *const _ as *const _, + std::mem::size_of::() as u32, + ) + .map_err(|e| { + let _ = CloseHandle(h); + e.to_string() + })?; + Ok(Job(h)) + } + } + + pub fn assign(&self, child: &std::process::Child) -> Result<(), String> { + unsafe { + let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?; + let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string()); + let _ = CloseHandle(p); + r + } + } + } + + impl Job { + /// The most memory the worker ever committed, in bytes. + pub fn peak_bytes(&self) -> Option { + unsafe { + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + QueryInformationJobObject( + Some(self.0), + JobObjectExtendedLimitInformation, + &mut info as *mut _ as *mut _, + std::mem::size_of::() as u32, + None, + ) + .ok()?; + Some(info.PeakProcessMemoryUsed as u64) + } + } + } + + impl Drop for Job { + fn drop(&mut self) { + unsafe { + let _ = CloseHandle(self.0); + } + } + } +} diff --git a/crates/worker/src/lib.rs b/crates/worker/src/lib.rs new file mode 100644 index 0000000..1247fe3 --- /dev/null +++ b/crates/worker/src/lib.rs @@ -0,0 +1,93 @@ +//! `pictor-worker`: the only Pictor process that parses outside files. +//! +//! The app (the tray process) starts it, sends one JSON request per line on stdin and reads one JSON response per +//! line on stdout (the protocol is in `docs/FORMATS.md`). [`client::Worker`] does that from the app's side: it puts +//! the worker in a Windows Job Object with a memory cap, gives every request a time cap, and kills and restarts the +//! worker when it hangs or crashes — so a hostile PDF can take down a worker, never the tray. +pub mod client; +pub mod ops; + +use serde::Serialize; + +/// The protocol version in the worker's hello line; the client refuses another. +pub const PROTOCOL: u32 = 1; + +/// A typed error the UI can act on (`kind`) with a plain sentence for the user (`message`). +#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)] +pub struct OpError { + pub kind: String, + pub message: String, +} + +impl OpError { + pub fn new(kind: &str, message: impl Into) -> OpError { + OpError { kind: kind.into(), message: message.into() } + } +} + +impl std::fmt::Display for OpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl From for OpError { + fn from(e: pictor_pdf::PdfError) -> Self { + use pictor_pdf::PdfError as E; + let kind = match &e { + E::EngineMissing(_) => "engine_missing", + E::NeedsPassword => "needs_password", + E::WrongPassword => "wrong_password", + E::Damaged(_) => "damaged", + E::Unsupported(_) => "unsupported", + E::NoSuchPage(_) | E::Invalid(_) => "invalid", + E::Write(_) => "io", + E::TooLarge(_) => "too_large", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_raster::RasterError) -> Self { + let text = format!("{e:?}"); + let kind = match text.split([' ', '{', '(']).next().unwrap_or("") { + "HeifCodecMissing" | "AvifCodecMissing" => "codec_missing", + "InputTooLarge" | "TooManyPixels" | "TooMuchMemory" => "too_large", + "UnknownFormat" | "UnsupportedFeature" | "CannotWrite" => "unsupported", + "CannotReachTarget" => "cannot_reach_target", + "Empty" | "InvalidCrop" | "InvalidSize" | "InvalidTarget" => "invalid", + _ => "damaged", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_meta::MetaError) -> Self { + use pictor_meta::MetaError as E; + let kind = match &e { + E::Encrypted => "needs_password", + E::Unsupported(_) => "unsupported", + E::TooLarge { .. } | E::TooBig(_) => "too_large", + E::Write(_) => "io", + _ => "damaged", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_qr::QrError) -> Self { + OpError::new("invalid", e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_save::SaveError) -> Self { + match e { + pictor_save::SaveError::Exists(_) => OpError::new("exists", e.to_string()), + _ => OpError::new("io", e.to_string()), + } + } +} diff --git a/crates/worker/src/main.rs b/crates/worker/src/main.rs new file mode 100644 index 0000000..48161fa --- /dev/null +++ b/crates/worker/src/main.rs @@ -0,0 +1,54 @@ +//! pictor-worker.exe: reads one JSON request per line on stdin, writes one JSON response per line on stdout. +//! → {"id": 1, "op": "pdf.open", "args": {...}} +//! ← {"id": 1, "ok": {...}} or {"id": 1, "err": {"kind": "...", "message": "..."}} +//! The first line it writes is {"hello": "pictor-worker", "protocol": 1, "version": "..."}. +//! Environment: PICTOR_PDFIUM_DIR (where pdfium.dll is; default: next to this exe), PICTOR_WORKER_DEBUG=1 (tests). +use pictor_worker::{OpError, PROTOCOL, ops}; +use serde_json::{Value, json}; +use std::io::{BufRead, Read, Write}; + +fn main() { + let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())); + let pdfium_dir = std::env::var_os("PICTOR_PDFIUM_DIR").map(Into::into).or(exe_dir); + let debug = std::env::var("PICTOR_WORKER_DEBUG").as_deref() == Ok("1"); + let mut state = ops::State::new(pdfium_dir, debug); + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + let hello = json!({"hello": "pictor-worker", "protocol": PROTOCOL, "version": env!("CARGO_PKG_VERSION")}); + if writeln!(out, "{hello}").and_then(|_| out.flush()).is_err() { + return; + } + let stdin = std::io::stdin(); + let mut line = String::new(); + let mut input = stdin.lock(); + loop { + line.clear(); + // Requests are small (paths and edits); refuse absurd lines instead of buffering them. + match input.by_ref().take(64 << 20).read_line(&mut line) { + Ok(0) | Err(_) => return, + Ok(_) => {} + } + let req: Value = match serde_json::from_str(line.trim_end()) { + Ok(v) => v, + Err(e) => { + let _ = writeln!(out, "{}", json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))})); + let _ = out.flush(); + continue; + } + }; + let id = req.get("id").cloned().unwrap_or(Value::Null); + let op = req.get("op").and_then(Value::as_str).unwrap_or("").to_string(); + let args = req.get("args").cloned().unwrap_or(json!({})); + // A panic inside a library becomes a typed error, not a dead worker (an abort still kills it; the client + // reports that as a crash). + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ops::dispatch(&mut state, &op, args))) + .unwrap_or_else(|_| Err(OpError::new("damaged", "Pictor could not read this file (it is damaged)."))); + let resp = match result { + Ok(v) => json!({"id": id, "ok": v}), + Err(e) => json!({"id": id, "err": e}), + }; + if writeln!(out, "{resp}").and_then(|_| out.flush()).is_err() { + return; + } + } +} diff --git a/crates/worker/src/ops.rs b/crates/worker/src/ops.rs new file mode 100644 index 0000000..18a35b5 --- /dev/null +++ b/crates/worker/src/ops.rs @@ -0,0 +1,443 @@ +//! The worker's operations. Each takes the request's JSON arguments and returns JSON or an [`OpError`]. +//! Files are read and written here (the paths come from the app); open PDFs stay in memory as sessions. +use crate::OpError; +use base64::Engine as _; +use pictor_pdf::{Edits, Engine, PageFit, PageSpec}; +use pictor_raster::{Format, Limits}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// Largest outside file the worker reads at all. +pub const MAX_FILE_BYTES: u64 = 1 << 30; + +pub struct State { + engine: Option<&'static Engine>, + pdfium_dir: Option, + docs: HashMap, + next_doc: u32, + debug: bool, +} + +struct Doc { + bytes: Vec, + password: Option, +} + +impl State { + pub fn new(pdfium_dir: Option, debug: bool) -> State { + State { engine: None, pdfium_dir, docs: HashMap::new(), next_doc: 1, debug } + } + + fn engine(&mut self) -> Result<&'static Engine, OpError> { + if let Some(e) = self.engine { + return Ok(e); + } + let e = Engine::load(self.pdfium_dir.as_deref())?; + self.engine = Some(e); + Ok(e) + } + + fn doc(&self, id: u32) -> Result<&Doc, OpError> { + self.docs.get(&id).ok_or_else(|| OpError::new("not_open", "That PDF is no longer open. Open it again.")) + } +} + +fn b64(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +fn read_file(path: &str) -> Result, OpError> { + let meta = std::fs::metadata(path).map_err(|e| OpError::new("io", format!("Pictor could not open {path}: {e}")))?; + if !meta.is_file() { + return Err(OpError::new("io", format!("{path} is not a file."))); + } + if meta.len() > MAX_FILE_BYTES { + return Err(OpError::new("too_large", "This file is larger than 1 GB, which Pictor does not open.")); + } + std::fs::read(path).map_err(|e| OpError::new("io", format!("Pictor could not read {path}: {e}"))) +} + +fn args Deserialize<'de>>(v: Value) -> Result { + serde_json::from_value(v).map_err(|e| OpError::new("invalid", format!("bad request: {e}"))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum SaveMode { + /// A new file; refuses to replace one. + New, + /// Replace the file, keeping a .bak. + Overwrite, +} + +fn write_out(path: &str, bytes: &[u8], mode: SaveMode) -> Result { + let p = Path::new(path); + match mode { + SaveMode::New => { + pictor_save::save_new(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) + } + SaveMode::Overwrite => { + let bak = pictor_save::save_overwrite(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len(), "bak": bak.exists().then(|| bak.display().to_string())})) + } + } +} + +fn png(img: &image::DynamicImage) -> Result, OpError> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new_with_quality( + &mut out, + image::codecs::png::CompressionType::Fast, + image::codecs::png::FilterType::Sub, + ) + .write_image(img.as_bytes(), img.width(), img.height(), img.color().into()) + .map_err(|e| OpError::new("io", e.to_string()))?; + Ok(out) +} + +use image::ImageEncoder; + +pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result { + match op { + // ---- PDF sessions ------------------------------------------------------------------------------------- + "pdf.open" => { + #[derive(Deserialize)] + struct A { + path: String, + password: Option, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let engine = state.engine()?; + let info = pictor_pdf::info(engine, &bytes, a.password.as_deref())?; + let id = state.next_doc; + state.next_doc += 1; + state.docs.insert(id, Doc { bytes, password: a.password }); + Ok(json!({"doc": id, "info": info})) + } + "pdf.close" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + state.docs.remove(&a.doc); + Ok(json!({})) + } + "pdf.render" => { + #[derive(Deserialize)] + struct A { + doc: u32, + page: usize, + width: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let img = pictor_pdf::render_page(engine, &d.bytes, d.password.as_deref(), a.page, a.width)?; + Ok(json!({"png": b64(&png(&img)?), "width": img.width(), "height": img.height()})) + } + "pdf.text" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"pages": pictor_pdf::extract_text(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.search" => { + #[derive(Deserialize)] + struct A { + doc: u32, + query: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"hits": pictor_pdf::search(engine, &d.bytes, d.password.as_deref(), &a.query, 2000)?})) + } + "pdf.form" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"fields": pictor_pdf::form_fields(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.save" => { + #[derive(Deserialize)] + struct A { + doc: u32, + edits: Edits, + output: String, + mode: SaveMode, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let applied = pictor_pdf::apply(engine, &d.bytes, d.password.as_deref(), &a.edits)?; + let mut out = write_out(&a.output, &applied.bytes, a.mode)?; + out["warnings"] = json!(applied.warnings); + Ok(out) + } + "pdf.extract" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + output: String, + } + let a: A = args(a)?; + let d = state.doc(a.doc)?; + let specs: Vec = a.pages.iter().map(|&index| PageSpec::Existing { index, rotate: 0 }).collect(); + let bytes = pictor_pdf::reorganise(&d.bytes, d.password.as_deref(), &specs)?; + write_out(&a.output, &bytes, SaveMode::New) + } + "pdf.to_images" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + dpi: u32, + format: String, + /// Output path pattern with `{n}` for the 1-based page number. + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose PNG or JPG."))?; + let mut paths = Vec::new(); + for &p in &a.pages { + let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[p], a.dpi)?.remove(0); + let bytes = pictor_raster::encode(&img, format, &Default::default())?; + let path = a.output.replace("{n}", &(p + 1).to_string()); + pictor_save::save_new(Path::new(&path), &bytes)?; + paths.push(path); + } + Ok(json!({"paths": paths})) + } + // ---- PDF files ---------------------------------------------------------------------------------------- + "pdf.merge" => { + #[derive(Deserialize)] + struct Input { + path: String, + password: Option, + } + #[derive(Deserialize)] + struct A { + inputs: Vec