[repo] Merge: feature/v1 (V1 core: raster, meta, qr, pdf, save, worker; PR #1)
This commit is contained in:
@@ -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 <name>-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: `[<crate>] <Feature>: <description>`, 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.
|
||||
Generated
+1605
File diff suppressed because it is too large
Load Diff
+41
@@ -0,0 +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"
|
||||
getrandom = "0.4"
|
||||
flate2 = "1"
|
||||
windows = "0.62"
|
||||
|
||||
# dev-only
|
||||
rqrr = "0.11"
|
||||
proptest = "1"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
@@ -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
|
||||
@@ -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<u16> {
|
||||
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<u16> {
|
||||
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<String> {
|
||||
match v {
|
||||
Value::Ascii(parts) => {
|
||||
let s: Vec<String> =
|
||||
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<f64> {
|
||||
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()
|
||||
}
|
||||
@@ -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<Block>,
|
||||
trailer_end: Option<usize>,
|
||||
error: Option<MetaError>,
|
||||
}
|
||||
|
||||
/// Skips data sub-blocks from `pos`; returns the position after the zero-length terminator.
|
||||
fn skip_sub_blocks(b: &[u8], mut pos: usize) -> Option<usize> {
|
||||
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<u8> {
|
||||
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<Vec<u8>, 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)
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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<Segment>,
|
||||
/// The position just after the end-of-image marker, if there is one.
|
||||
eoi_end: Option<usize>,
|
||||
/// 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<Vec<u8>, 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<u8> {
|
||||
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
|
||||
}
|
||||
@@ -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<Item>,
|
||||
/// Plain-English notes about damaged or unreadable parts; reading went on past them.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// The groups that have at least one item, in display order.
|
||||
pub fn groups(&self) -> Vec<Group> {
|
||||
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<u8>,
|
||||
/// The groups that had items before and fewer (or none) after, in display order.
|
||||
pub removed: Vec<Group>,
|
||||
}
|
||||
|
||||
/// 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<Report, MetaError> {
|
||||
read_with(bytes, &Limits::default())
|
||||
}
|
||||
|
||||
/// Reads the metadata with explicit caps.
|
||||
pub fn read_with(bytes: &[u8], limits: &Limits) -> Result<Report, MetaError> {
|
||||
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<Stripped, MetaError> {
|
||||
strip_with(bytes, &Limits::default())
|
||||
}
|
||||
|
||||
/// Returns a copy without metadata, with explicit caps.
|
||||
pub fn strip_with(bytes: &[u8], limits: &Limits) -> Result<Stripped, MetaError> {
|
||||
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<Kind, MetaError> {
|
||||
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<Item>,
|
||||
warnings: Vec<String>,
|
||||
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<str>, value: impl AsRef<str>) {
|
||||
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<String>) {
|
||||
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<T>(f: impl FnOnce() -> T) -> Option<T> {
|
||||
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") }
|
||||
}
|
||||
@@ -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<Document, MetaError> {
|
||||
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<Vec<u8>, 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())),
|
||||
}
|
||||
}
|
||||
@@ -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<Chunk>,
|
||||
/// The position after IEND, if there is one.
|
||||
iend_end: Option<usize>,
|
||||
error: Option<MetaError>,
|
||||
}
|
||||
|
||||
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<Vec<u8>, 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)
|
||||
}
|
||||
@@ -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<usize> {
|
||||
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<u16> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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::<u32>().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");
|
||||
}
|
||||
}
|
||||
@@ -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<bool> {
|
||||
let le = b.starts_with(b"II");
|
||||
let u16_at = |at: usize| -> Option<u16> {
|
||||
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<u32> { 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<Vec<u8>, 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())
|
||||
}
|
||||
@@ -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<Chunk>,
|
||||
/// Bytes after the RIFF container.
|
||||
trailing: usize,
|
||||
error: Option<MetaError>,
|
||||
}
|
||||
|
||||
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<Vec<u8>, 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)
|
||||
}
|
||||
@@ -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 `<prefix:name>...</prefix:name>` 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<String> {
|
||||
element_value(s, prop).or_else(|| attribute_value(s, prop))
|
||||
}
|
||||
|
||||
fn attribute_value(s: &str, prop: &str) -> Option<String> {
|
||||
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<String> {
|
||||
let open = format!("<{prop}");
|
||||
let close = format!("</{prop}>");
|
||||
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('/') {
|
||||
// <prefix:name rdf:resource="..."/> 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<String> = 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#"<rdf:Description xmp:CreatorTool="Tool & Co" tiff:Make='Apple'>
|
||||
<dc:creator><rdf:Seq><rdf:li>Jan</rdf:li><rdf:li>Eva</rdf:li></rdf:Seq></dc:creator>
|
||||
<dc:creatorX>no</dc:creatorX></rdf:Description>"#;
|
||||
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("<dc:creator", "dc:creator"), None);
|
||||
assert_eq!(find_value(" dc:creator=", "dc:creator"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Fixtures built in code: nothing binary lives in git.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use exif::experimental::Writer;
|
||||
use exif::{Field, In, Rational, Tag, Value};
|
||||
use image::{ImageEncoder, RgbImage, RgbaImage};
|
||||
|
||||
pub const AUTHOR: &str = "Jan Novak Fixtureauthor";
|
||||
pub const MAKE: &str = "Apple";
|
||||
pub const MODEL: &str = "iPhone 15";
|
||||
pub const SOFTWARE: &str = "PhotoEditor 17.1 Fixture";
|
||||
pub const COMMENT: &str = "Holiday at the secret cottage";
|
||||
pub const XMP_NS: &str = "http://ns.adobe.com/xap";
|
||||
|
||||
pub fn rgb(w: u32, h: u32) -> 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<Field> {
|
||||
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<u8> {
|
||||
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#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
|
||||
<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xmp="{XMP_NS}/1.0/"
|
||||
xmp:CreatorTool="{SOFTWARE}">
|
||||
<dc:creator><rdf:Seq><rdf:li>{AUTHOR}</rdf:li></rdf:Seq></dc:creator>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>
|
||||
<?xpacket end="w"?>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Photoshop 3.0 + 8BIM 0x0404 with an IPTC by-line (2:80).
|
||||
pub fn photoshop_iptc() -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8>]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
let mut p = b"Exif\0\0".to_vec();
|
||||
p.extend_from_slice(raw);
|
||||
segment(0xE1, &p)
|
||||
}
|
||||
|
||||
pub fn xmp_app1() -> Vec<u8> {
|
||||
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<u8> {
|
||||
jpeg_with(&[
|
||||
exif_app1(&exif_tiff(&photo_fields())),
|
||||
xmp_app1(),
|
||||
segment(0xED, &photoshop_iptc()),
|
||||
segment(0xFE, COMMENT.as_bytes()),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn plain_png() -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8>, 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<u8> {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use pictor_meta::{Group, MetaError, read, strip};
|
||||
|
||||
fn malformed_exif_blocks() -> Vec<(&'static str, Vec<u8>)> {
|
||||
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<u8>)> = 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<u8> {
|
||||
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];
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<image::RgbaImage> {
|
||||
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 { .. })));
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[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
|
||||
serde_json.workspace = true
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
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<Engine> = 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<PdfDocument<'a>, 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<PdfDocument<'_>, PdfError> {
|
||||
self.pdfium.create_new_pdf().map_err(PdfError::from_pdfium)
|
||||
}
|
||||
}
|
||||
|
||||
/// pdfium's save (flags 0: an encrypted document would keep its security handler). Pictor only calls it on
|
||||
/// unencrypted documents (the edit pipeline unlocks first) and on new ones (merge); lopdf writes encryption.
|
||||
pub(crate) fn pdfium_save(doc: &PdfDocument) -> Result<Vec<u8>, PdfError> {
|
||||
doc.save_to_bytes().map_err(|e| PdfError::Write(e.to_string()))
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.rem_euclid(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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! 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::{ViewPoint, ViewRect};
|
||||
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<lopdf::Document, PdfError> {
|
||||
let mut opts = lopdf::LoadOptions { max_decompressed_size: Some(256 << 20), ..Default::default() };
|
||||
if let Some(p) = password {
|
||||
opts.password = Some(p.to_owned());
|
||||
}
|
||||
match lopdf::Document::load_mem_with_options(bytes, opts) {
|
||||
// Protected only by an owner password (permissions): it opens with the empty user password, as in pdfium.
|
||||
Ok(doc) if doc.is_encrypted() && password.is_none() => match lopdf_load(bytes, Some("")) {
|
||||
Err(PdfError::WrongPassword) => Err(PdfError::NeedsPassword),
|
||||
other => other,
|
||||
},
|
||||
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<Vec<u8>, PdfError> {
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 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<ObjectId, PdfError> {
|
||||
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<Vec<u8>, 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<ObjectId> = 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<Vec<Vec<u8>>, 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<PageSpec> = (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<Vec<(usize, usize)>, 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<Vec<u8>, 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<u8>, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result<Vec<u8>, 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<u8> = 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<u8> = 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<Vec<DynamicImage>, 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)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! 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<PageInfo>,
|
||||
pub outline: Vec<OutlineItem>,
|
||||
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<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct OutlineItem {
|
||||
pub title: String,
|
||||
pub page: Option<usize>,
|
||||
pub depth: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SearchHit {
|
||||
pub page: usize,
|
||||
/// The hit's boxes in view space.
|
||||
pub rects: Vec<ViewRect>,
|
||||
}
|
||||
|
||||
pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> {
|
||||
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<OutlineItem>, 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<Vec<(f32, f32)>, 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<DynamicImage, PdfError> {
|
||||
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<DynamicImage, PdfError> {
|
||||
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<Vec<String>, 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<Vec<SearchHit>, 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<String, PdfError> {
|
||||
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() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
//! 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<ViewRect>,
|
||||
}
|
||||
|
||||
#[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<u8>,
|
||||
/// Plain sentences for the user (for example, hidden layers left on pages that were not redacted).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
const IMAGE_NAME: &[u8] = b"PictorRedacted";
|
||||
|
||||
pub fn redact(
|
||||
engine: &Engine,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
redactions: &[Redaction],
|
||||
opts: &RedactOptions,
|
||||
) -> Result<Redacted, PdfError> {
|
||||
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<u8>, 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<ViewRect> =
|
||||
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<ObjectId> = 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<ObjectId> = HashSet::new();
|
||||
let redacted_pages: HashSet<ObjectId> = 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<ObjectId>) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prune_form_pub(doc: &mut Document, removed: &HashSet<ObjectId>) {
|
||||
prune_form(doc, removed)
|
||||
}
|
||||
|
||||
fn prune_form(doc: &mut Document, removed: &HashSet<ObjectId>) {
|
||||
let Ok(catalog) = doc.catalog() else { return };
|
||||
let acroform = match catalog.get(b"AcroForm") {
|
||||
Ok(Object::Reference(id)) => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
let fields: Vec<Object> = {
|
||||
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<ObjectId>, 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<Object> = 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<Object> = 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<ObjectId>, warnings: &mut Vec<String>) {
|
||||
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<ObjectId> = 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::<Vec<_>>().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
|
||||
}
|
||||
@@ -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<Vec<u8>, 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<dyn CryptFilter> = 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<Vec<u8>, PdfError> {
|
||||
let mut doc = lopdf_load(bytes, Some(password))?;
|
||||
doc.trailer.remove(b"Encrypt");
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! 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)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
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"<x:xmpmeta xmlns:x='adobe:ns:meta/'><rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\
|
||||
<rdf:Description xmlns:dc='http://purl.org/dc/elements/1.1/'><dc:title>XMP-SECRET</dc:title></rdf:Description>\
|
||||
</rdf:RDF></x:xmpmeta>"
|
||||
.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<u8> {
|
||||
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<Vec<u8>> {
|
||||
let doc = Document::load_mem(bytes).expect("lopdf reloads the output");
|
||||
let mut found = Vec::new();
|
||||
fn walk(o: &Object, found: &mut Vec<Vec<u8>>) {
|
||||
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<ObjectId> {
|
||||
doc.get_pages().values().copied().collect()
|
||||
}
|
||||
|
||||
/// A page's content, decompressed and concatenated.
|
||||
pub fn page_content(doc: &Document, page: ObjectId) -> Vec<u8> {
|
||||
doc.get_page_content(page)
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! 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<u8> {
|
||||
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::<u32>() < 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<Annotation> {
|
||||
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<String> = 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<u8> {
|
||||
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]);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! 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<String> {
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owner_password_only_document_opens_and_edits_without_a_password() {
|
||||
use lopdf::encryption::crypt_filters::{Aes256CryptFilter, CryptFilter};
|
||||
let mut doc = lopdf::Document::load_mem(&numbered_pdf(1, "Statement")).unwrap();
|
||||
let filter: std::sync::Arc<dyn CryptFilter> = std::sync::Arc::new(Aes256CryptFilter);
|
||||
let state = lopdf::EncryptionState::try_from(lopdf::EncryptionVersion::V5 {
|
||||
encrypt_metadata: true,
|
||||
crypt_filters: std::collections::BTreeMap::from([(b"StdCF".to_vec(), filter)]),
|
||||
file_encryption_key: &[9u8; 32],
|
||||
stream_filter: b"StdCF".to_vec(),
|
||||
string_filter: b"StdCF".to_vec(),
|
||||
owner_password: "bank-owner",
|
||||
user_password: "",
|
||||
permissions: lopdf::Permissions::PRINTABLE,
|
||||
})
|
||||
.unwrap();
|
||||
doc.encrypt(&state).unwrap();
|
||||
let mut locked = Vec::new();
|
||||
doc.save_to(&mut locked).unwrap();
|
||||
assert!(!pictor_pdf::is_encrypted(&locked), "an owner-only PDF needs no password to open");
|
||||
assert_eq!(texts(&locked, None), ["Statement page 1"]);
|
||||
let edited = pictor_pdf::reorganise(&locked, None, &[PageSpec::Existing { index: 0, rotate: 90 }]).unwrap();
|
||||
assert_eq!(texts(&edited, None), ["Statement page 1"]);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! 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<ViewRect>) -> 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::<Vec<_>>()
|
||||
};
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> = 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"
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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<bool>,
|
||||
}
|
||||
|
||||
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<Matrix, QrError> {
|
||||
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<QrCode> {
|
||||
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<Geometry, QrError> {
|
||||
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))
|
||||
}
|
||||
@@ -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."
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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] }
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
#[serde(default)]
|
||||
email: Option<String>,
|
||||
#[serde(default)]
|
||||
organisation: Option<String>,
|
||||
#[serde(default)]
|
||||
url: Option<String>,
|
||||
#[serde(default)]
|
||||
address: Option<String>,
|
||||
#[serde(default)]
|
||||
note: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// 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<String, QrError> {
|
||||
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<String>| 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<String, QrError> {
|
||||
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:<ssid>;P:<password>;H:true;;`), with `\ ; , : "` backslash-escaped.
|
||||
fn wifi(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> Result<String, QrError> {
|
||||
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<String>,
|
||||
email: Option<String>,
|
||||
organisation: Option<String>,
|
||||
url: Option<String>,
|
||||
address: Option<String>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// 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::<Vec<_>>().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<String, QrError> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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<Rendered, QrError> {
|
||||
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<Vec<u8>, 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<Vec<u8>, 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<u8>, dst: Rgba<u8>) -> Rgba<u8> {
|
||||
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])
|
||||
}
|
||||
@@ -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 `<path>` 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 `<image>` data URI.
|
||||
pub fn render_svg(text: &str, level: Level, style: &Style, logo_png: Option<&[u8]>) -> Result<String, QrError> {
|
||||
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,
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" \
|
||||
width=\"{size}\" height=\"{size}\" viewBox=\"0 0 {total} {total}\" shape-rendering=\"crispEdges\">\n"
|
||||
);
|
||||
if style.light[3] > 0 {
|
||||
let _ = writeln!(svg, "<rect width=\"{total}\" height=\"{total}\"{}/>", fill(style.light));
|
||||
}
|
||||
let _ = write!(svg, "<path{} d=\"", fill(style.dark));
|
||||
for my in 0..g.modules {
|
||||
let mut mx = 0;
|
||||
while mx < g.modules {
|
||||
let on = |x: u32| matrix.is_dark(x, my) && !plate.as_ref().is_some_and(|p| p.contains(x, my));
|
||||
if !on(mx) {
|
||||
mx += 1;
|
||||
continue;
|
||||
}
|
||||
let start = mx;
|
||||
while mx < g.modules && on(mx) {
|
||||
mx += 1;
|
||||
}
|
||||
let n = mx - start;
|
||||
let _ = write!(svg, "M{} {}h{n}v1h-{n}z", g.quiet + start, g.quiet + my);
|
||||
}
|
||||
}
|
||||
svg.push_str("\"/>\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,
|
||||
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" \
|
||||
xlink:href=\"data:image/png;base64,{}\"/>",
|
||||
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("</svg>\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() }
|
||||
}
|
||||
@@ -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<u8> {
|
||||
pictor_qr::encode_png(&logo(w, h)).expect("logo PNG")
|
||||
}
|
||||
@@ -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(_))));
|
||||
}
|
||||
@@ -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::<Payload>(&json).unwrap(), p);
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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("<svg "), "{}", &svg[..40]);
|
||||
assert!(svg.trim_end().ends_with("</svg>"));
|
||||
assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\""));
|
||||
assert_eq!(svg.matches("<path").count(), 1);
|
||||
assert!(!svg.contains("<image"));
|
||||
|
||||
// Same geometry as the raster output, and as many dark modules as the raster has.
|
||||
let r = render_rgba(text, Level::M, &style, None).unwrap();
|
||||
assert_eq!(view_box_size(&svg), r.modules + 8);
|
||||
assert!(svg.contains(&format!("width=\"{}\" height=\"{}\"", r.size_px, r.size_px)));
|
||||
let dark_svg: u32 = runs(&svg).iter().map(|r| r.2).sum();
|
||||
let mut dark_png = 0;
|
||||
for my in 0..r.modules + 8 {
|
||||
for mx in 0..r.modules + 8 {
|
||||
let p = r.image.get_pixel(mx * r.module_px + r.module_px / 2, my * r.module_px + r.module_px / 2);
|
||||
if p.0[0] < 128 {
|
||||
dark_png += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(dark_svg, dark_png);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_rasterised_decodes_at_all_levels() {
|
||||
let text = "WIFI:T:WPA;S:Domov\\;5G;P:heslo\\:x;;";
|
||||
for level in [Level::L, Level::M, Level::Q, Level::H] {
|
||||
let svg = render_svg(text, level, &Style::default(), None).unwrap();
|
||||
assert_eq!(decode_gray(rasterise(&svg, 6)).0, text, "{level:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_colours() {
|
||||
let style = Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 128], ..Style::default() };
|
||||
let svg = render_svg("colour", Level::M, &style, None).unwrap();
|
||||
assert!(svg.contains("fill=\"#102060\""), "{svg}");
|
||||
assert!(svg.contains("fill=\"#fffae1\" fill-opacity=\"0.502\""), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_with_logo_embeds_data_uri_and_clears_modules() {
|
||||
let text = "https://example.cz/logo";
|
||||
let png = logo_png(120, 60);
|
||||
let with = render_svg(text, Level::L, &Style::default(), Some(&png)).unwrap();
|
||||
let without_h = render_svg(text, Level::H, &Style::default(), None).unwrap();
|
||||
assert_eq!(with.matches("<image").count(), 1);
|
||||
assert!(with.contains("xlink:href=\"data:image/png;base64,iVBORw0KGgo"), "a base64 PNG data URI");
|
||||
assert!(with.contains("preserveAspectRatio=\"xMidYMid meet\""));
|
||||
// Level H was used (same module count as an H code without a logo), and modules under the plate are gone.
|
||||
assert_eq!(view_box_size(&with), view_box_size(&without_h));
|
||||
let dark_with: u32 = runs(&with).iter().map(|r| r.2).sum();
|
||||
let dark_without: u32 = runs(&without_h).iter().map(|r| r.2).sum();
|
||||
assert!(dark_with < dark_without);
|
||||
// The cleared code (without drawing the logo) still decodes.
|
||||
assert_eq!(decode_gray(rasterise(&with, 6)).0, text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_rejects_a_broken_logo() {
|
||||
let err = render_svg("x", Level::M, &Style::default(), Some(b"not a png")).unwrap_err();
|
||||
assert!(matches!(err, QrError::Logo(_)), "{err:?}");
|
||||
}
|
||||
@@ -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
|
||||
@@ -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<u32>,
|
||||
}
|
||||
|
||||
/// 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<Probe> {
|
||||
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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<Format> {
|
||||
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<impl ImageDecoder + '_> {
|
||||
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<T>(format: Format, f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<usize> {
|
||||
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<u32> {
|
||||
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)
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
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<u8>) -> 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) }
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, RasterError>;
|
||||
|
||||
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)) }
|
||||
}
|
||||
@@ -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<Format> {
|
||||
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<Format> {
|
||||
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<image::ImageFormat> {
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -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<Brand> {
|
||||
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<Info> {
|
||||
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<Vec<usize>> {
|
||||
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<u16> {
|
||||
Some(u16::from_be_bytes(d.get(at..at.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn be32(d: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(d.get(at..at.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn be64(d: &[u8], at: usize) -> Option<u64> {
|
||||
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<u8> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<u32> {
|
||||
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)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8>,
|
||||
pub format: Format,
|
||||
/// JPEG quality used; `None` for lossless formats.
|
||||
pub quality: Option<u8>,
|
||||
/// 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<Compressed> {
|
||||
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<u8>| -> Result<Vec<u8>> {
|
||||
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<u8>, quality: Option<u8>, 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<DynamicImage> = 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 })
|
||||
}
|
||||
@@ -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, <https://apps.microsoft.com/detail/9PMMSR1CGPWG>): the WIC decoder for the
|
||||
//! HEIF container. Without it, WIC finds no decoder (`WINCODEC_ERR_COMPONENTNOTFOUND`, 0x88982F50).
|
||||
//! - "HEVC Video Extensions" ($0.99, <https://apps.microsoft.com/detail/9NMZLZ57R3T7>): 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<Self, windows::core::Error> {
|
||||
// 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<IWICImagingFactory> {
|
||||
// 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<DynamicImage> {
|
||||
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<DynamicImage> {
|
||||
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<u16> {
|
||||
// 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<String> {
|
||||
let input = MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: subtype };
|
||||
let mut list: *mut Option<IMFActivate> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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<u8>, 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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8>, width: u16, height: u16) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> = {
|
||||
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
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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<u8> = (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<RasterError> = 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<u8>)> {
|
||||
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<u8> {
|
||||
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<u8> = (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());
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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: `<name>-edited.pdf`).
|
||||
//! - [`save_overwrite`] replaces a file, first keeping the current version as `<file>.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::NamedTempFile, SaveError> {
|
||||
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 `<target>.bak` first. Returns the `.bak` path
|
||||
/// (which does not exist if `target` did not exist).
|
||||
pub fn save_overwrite(target: &Path, bytes: &[u8]) -> Result<PathBuf, SaveError> {
|
||||
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<PathBuf, SaveError> {
|
||||
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)
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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());
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,323 @@
|
||||
//! 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<PathBuf>,
|
||||
/// 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<PathBuf>) -> 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<String>,
|
||||
stderr: Arc<Mutex<String>>,
|
||||
#[cfg(windows)]
|
||||
_job: job::Job,
|
||||
}
|
||||
|
||||
pub struct Worker {
|
||||
opts: WorkerOptions,
|
||||
running: Option<Running>,
|
||||
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<Value, WorkerError> {
|
||||
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<Job, String> {
|
||||
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::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() 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<u64> {
|
||||
unsafe {
|
||||
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
QueryInformationJobObject(
|
||||
Some(self.0),
|
||||
JobObjectExtendedLimitInformation,
|
||||
&mut info as *mut _ as *mut _,
|
||||
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
|
||||
None,
|
||||
)
|
||||
.ok()?;
|
||||
Some(info.PeakProcessMemoryUsed as u64)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Job {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
let _ = CloseHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String>) -> 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<pictor_pdf::PdfError> 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<pictor_raster::RasterError> 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<pictor_meta::MetaError> 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<pictor_qr::QrError> for OpError {
|
||||
fn from(e: pictor_qr::QrError) -> Self {
|
||||
OpError::new("invalid", e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pictor_save::SaveError> 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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
//! 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<PathBuf>,
|
||||
docs: HashMap<u32, Doc>,
|
||||
next_doc: u32,
|
||||
debug: bool,
|
||||
}
|
||||
|
||||
struct Doc {
|
||||
bytes: Vec<u8>,
|
||||
password: Option<String>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn new(pdfium_dir: Option<PathBuf>, 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<Vec<u8>, 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<T: for<'de> Deserialize<'de>>(v: Value) -> Result<T, OpError> {
|
||||
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<Value, OpError> {
|
||||
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<Vec<u8>, 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<Value, OpError> {
|
||||
match op {
|
||||
// ---- PDF sessions -------------------------------------------------------------------------------------
|
||||
"pdf.open" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
path: String,
|
||||
password: Option<String>,
|
||||
}
|
||||
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<usize>,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let d = state.doc(a.doc)?;
|
||||
let specs: Vec<PageSpec> = 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<usize>,
|
||||
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<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
inputs: Vec<Input>,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let engine = state.engine()?;
|
||||
let files: Vec<(Vec<u8>, Option<String>)> = a
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| read_file(&i.path).map(|b| (b, i.password.clone())))
|
||||
.collect::<Result<_, _>>()?;
|
||||
let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect();
|
||||
let bytes = pictor_pdf::merge(engine, &refs)?;
|
||||
write_out(&a.output, &bytes, SaveMode::New)
|
||||
}
|
||||
"pdf.split" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
path: String,
|
||||
password: Option<String>,
|
||||
ranges: String,
|
||||
/// Output path pattern with `{n}` for the part number.
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let engine = state.engine()?;
|
||||
let bytes = read_file(&a.path)?;
|
||||
let pages = pictor_pdf::page_sizes(engine, &bytes, a.password.as_deref())?.len();
|
||||
let ranges = pictor_pdf::parse_ranges(&a.ranges, pages)?;
|
||||
let parts = pictor_pdf::split(&bytes, a.password.as_deref(), &ranges)?;
|
||||
let mut paths = Vec::new();
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
let path = a.output.replace("{n}", &(i + 1).to_string());
|
||||
pictor_save::save_new(Path::new(&path), part)?;
|
||||
paths.push(path);
|
||||
}
|
||||
Ok(json!({"paths": paths}))
|
||||
}
|
||||
"pdf.from_images" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
inputs: Vec<String>,
|
||||
output: String,
|
||||
fit: PageFit,
|
||||
#[serde(default)]
|
||||
margin: f32,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let limits = Limits::default();
|
||||
let mut images = Vec::new();
|
||||
for p in &a.inputs {
|
||||
let bytes = read_file(p)?;
|
||||
let img = pictor_raster::decode(&bytes, &limits)?;
|
||||
images.push((bytes, img));
|
||||
}
|
||||
let bytes = pictor_pdf::images_to_pdf(&images, a.fit, a.margin)?;
|
||||
write_out(&a.output, &bytes, SaveMode::New)
|
||||
}
|
||||
// ---- Images -------------------------------------------------------------------------------------------
|
||||
"image.probe" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
path: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let bytes = read_file(&a.path)?;
|
||||
let p = pictor_raster::probe(&bytes, &Limits::default())?;
|
||||
Ok(json!({"format": p.format, "width": p.width, "height": p.height, "has_alpha": p.has_alpha,
|
||||
"frames": p.frames, "bytes": bytes.len()}))
|
||||
}
|
||||
"image.thumb" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
path: String,
|
||||
max: u32,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let bytes = read_file(&a.path)?;
|
||||
let img = pictor_raster::decode(&bytes, &Limits::default())?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let t =
|
||||
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
|
||||
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
|
||||
}
|
||||
"image.convert" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
input: String,
|
||||
output: String,
|
||||
format: String,
|
||||
#[serde(default)]
|
||||
quality: Option<u8>,
|
||||
#[serde(default)]
|
||||
crop: Option<pictor_raster::Rect>,
|
||||
#[serde(default)]
|
||||
rotate: Option<pictor_raster::Rotation>,
|
||||
#[serde(default)]
|
||||
resize: Option<pictor_raster::Fit>,
|
||||
#[serde(default)]
|
||||
preset: Option<pictor_raster::Preset>,
|
||||
#[serde(default)]
|
||||
target_bytes: Option<u64>,
|
||||
#[serde(default)]
|
||||
overwrite: bool,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let limits = Limits::default();
|
||||
let src = read_file(&a.input)?;
|
||||
let src_format = pictor_raster::probe(&src, &limits)?.format;
|
||||
let mut img = pictor_raster::decode(&src, &limits)?;
|
||||
if let Some(c) = a.crop {
|
||||
img = pictor_raster::crop(&img, c)?;
|
||||
}
|
||||
if let Some(r) = a.rotate {
|
||||
img = pictor_raster::rotate(&img, r);
|
||||
}
|
||||
if let Some(f) = a.resize {
|
||||
img = pictor_raster::resize(&img, f, &limits)?;
|
||||
}
|
||||
let format =
|
||||
Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
|
||||
let (bytes, format) = if let Some(target) = a.target_bytes {
|
||||
let c = pictor_raster::compress_to(&img, format, target, &limits)?;
|
||||
(c.bytes, c.format)
|
||||
} else if let Some(p) = a.preset {
|
||||
let _ = src_format;
|
||||
pictor_raster::apply_preset(&img, format, p)?
|
||||
} else {
|
||||
let mut o = pictor_raster::EncodeOptions::default();
|
||||
if let Some(q) = a.quality {
|
||||
o.jpeg_quality = q.clamp(10, 100);
|
||||
}
|
||||
(pictor_raster::encode(&img, format, &o)?, format)
|
||||
};
|
||||
let mut out = write_out(&a.output, &bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
|
||||
out["format"] = json!(format);
|
||||
out["width"] = json!(img.width());
|
||||
out["height"] = json!(img.height());
|
||||
Ok(out)
|
||||
}
|
||||
"image.heif_support" => Ok(json!({"support": pictor_raster::heif_support()})),
|
||||
// ---- Metadata -----------------------------------------------------------------------------------------
|
||||
"meta.read" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
path: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let bytes = read_file(&a.path)?;
|
||||
let report = pictor_meta::read(&bytes)?;
|
||||
let groups: Vec<_> = report.groups().into_iter().map(|g| json!({"group": g, "label": g.label()})).collect();
|
||||
Ok(json!({"report": report, "groups": groups}))
|
||||
}
|
||||
"meta.strip" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
input: String,
|
||||
output: String,
|
||||
#[serde(default)]
|
||||
overwrite: bool,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let bytes = read_file(&a.input)?;
|
||||
let stripped = pictor_meta::strip(&bytes)?;
|
||||
let mut out =
|
||||
write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
|
||||
out["removed"] = json!(stripped.removed);
|
||||
Ok(out)
|
||||
}
|
||||
// ---- QR -----------------------------------------------------------------------------------------------
|
||||
"qr.render" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
payload: pictor_qr::Payload,
|
||||
#[serde(default)]
|
||||
level: pictor_qr::Level,
|
||||
style: pictor_qr::Style,
|
||||
#[serde(default)]
|
||||
logo: Option<String>,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let text = pictor_qr::payload_string(&a.payload)?;
|
||||
let logo_bytes = match &a.logo {
|
||||
Some(p) => Some(read_file(p)?),
|
||||
None => None,
|
||||
};
|
||||
let logo = match &logo_bytes {
|
||||
Some(b) => Some(pictor_raster::decode(b, &Limits::default())?.to_rgba8()),
|
||||
None => None,
|
||||
};
|
||||
let r = pictor_qr::render_rgba(&text, a.level, &a.style, logo.as_ref())?;
|
||||
let png = pictor_qr::encode_png(&r.image)?;
|
||||
let logo_png = match &logo {
|
||||
Some(l) => Some(pictor_qr::encode_png(l)?),
|
||||
None => None,
|
||||
};
|
||||
let svg = pictor_qr::render_svg(&text, a.level, &a.style, logo_png.as_deref())?;
|
||||
Ok(json!({"png": b64(&png), "svg": svg, "level_used": r.level_used, "size": r.size_px, "text": text}))
|
||||
}
|
||||
// ---- Tests only (PICTOR_WORKER_DEBUG=1) ---------------------------------------------------------------
|
||||
"debug.crash" if state.debug => std::process::abort(),
|
||||
"debug.sleep" if state.debug => {
|
||||
std::thread::sleep(std::time::Duration::from_secs(a["secs"].as_u64().unwrap_or(60)));
|
||||
Ok(json!({}))
|
||||
}
|
||||
"debug.alloc" if state.debug => {
|
||||
let mb = a["mb"].as_u64().unwrap_or(4096) as usize;
|
||||
let mut v: Vec<u8> = Vec::new();
|
||||
v.try_reserve_exact(mb << 20).map_err(|_| OpError::new("too_large", "out of memory"))?;
|
||||
v.resize(mb << 20, 1);
|
||||
Ok(json!({"len": v.len()}))
|
||||
}
|
||||
_ => Err(OpError::new("invalid", format!("unknown operation {op}"))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text,
|
||||
//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap;
|
||||
//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the
|
||||
//! tray: it must never crash, and the next request after a bad file must work.
|
||||
//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
|
||||
use flate2::{Compression, write::ZlibEncoder};
|
||||
use lopdf::{Document, Object, Stream, dictionary};
|
||||
use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
|
||||
use serde_json::json;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const CAP: Duration = Duration::from_secs(15);
|
||||
|
||||
fn worker() -> Worker {
|
||||
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
|
||||
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
|
||||
o.memory_mb = 1024;
|
||||
o.debug = true;
|
||||
Worker::new(o)
|
||||
}
|
||||
|
||||
fn base_doc(content: &[u8]) -> Document {
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages = doc.new_object_id();
|
||||
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
|
||||
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
|
||||
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
|
||||
doc.objects.insert(
|
||||
pages,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||||
doc.trailer.set("Root", cat);
|
||||
doc
|
||||
}
|
||||
|
||||
fn save(mut doc: Document) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
doc.save_to(&mut v).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
fn valid() -> Vec<u8> {
|
||||
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
|
||||
}
|
||||
|
||||
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
|
||||
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
|
||||
[&hay[..i], to, &hay[i + from.len()..]].concat()
|
||||
}
|
||||
|
||||
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
|
||||
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
|
||||
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
|
||||
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
|
||||
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
|
||||
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
|
||||
let font = doc.add_object(
|
||||
dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
|
||||
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc},
|
||||
);
|
||||
let page = *doc.get_pages().values().next().unwrap();
|
||||
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
|
||||
save(doc)
|
||||
}
|
||||
|
||||
fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
|
||||
let v = valid();
|
||||
let mut out: Vec<(&str, Vec<u8>)> = vec![
|
||||
("empty file", Vec::new()),
|
||||
("header only", b"%PDF-1.7\n".to_vec()),
|
||||
("truncated at 10%", v[..v.len() / 10].to_vec()),
|
||||
("truncated at 50%", v[..v.len() / 2].to_vec()),
|
||||
("truncated before the trailer", v[..v.len() - 40].to_vec()),
|
||||
("random bytes after a header", {
|
||||
let mut x = b"%PDF-1.7\n".to_vec();
|
||||
let mut s = 0x2545_4446u32;
|
||||
for _ in 0..20_000 {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
x.push(s as u8);
|
||||
}
|
||||
x
|
||||
}),
|
||||
];
|
||||
// Broken xref: startxref points nowhere, then the table itself is garbage.
|
||||
let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
|
||||
out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
|
||||
// lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
|
||||
let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
|
||||
let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
|
||||
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
|
||||
let mut garbled = v.clone();
|
||||
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
|
||||
let end = (data + 40).min(garbled.len());
|
||||
for b in garbled[data..end].iter_mut() {
|
||||
*b = b.wrapping_mul(31).wrapping_add(7);
|
||||
}
|
||||
out.push(("garbled xref table", garbled));
|
||||
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
|
||||
// Recursive references.
|
||||
{
|
||||
let mut doc = base_doc(b"");
|
||||
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
|
||||
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
|
||||
out.push(("page tree that contains itself", save(doc)));
|
||||
}
|
||||
{
|
||||
let mut doc = base_doc(b"");
|
||||
let page = *doc.get_pages().values().next().unwrap();
|
||||
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
|
||||
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
|
||||
out.push(("parent loop", save(doc)));
|
||||
}
|
||||
out.push((
|
||||
"object that is a reference to itself",
|
||||
replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R")
|
||||
.into_iter()
|
||||
.chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied())
|
||||
.collect(),
|
||||
));
|
||||
out.push(("deeply nested arrays", {
|
||||
let mut deep = vec![b'['; 200_000];
|
||||
deep.extend(vec![b']'; 200_000]);
|
||||
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
|
||||
}));
|
||||
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
|
||||
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
|
||||
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
|
||||
{
|
||||
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
|
||||
let bytes = save(doc);
|
||||
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
|
||||
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
|
||||
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
|
||||
}
|
||||
{
|
||||
let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
|
||||
let zeros = vec![b' '; 1 << 20];
|
||||
for _ in 0..1024 {
|
||||
z.write_all(&zeros).unwrap();
|
||||
}
|
||||
let bomb = z.finish().unwrap();
|
||||
let mut doc = base_doc(b"");
|
||||
let page = *doc.get_pages().values().next().unwrap();
|
||||
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false));
|
||||
doc.get_dictionary_mut(page).unwrap().set("Contents", c);
|
||||
out.push(("content stream that inflates to 1 GiB", save(doc)));
|
||||
}
|
||||
// Malformed fonts.
|
||||
out.push((
|
||||
"TrueType font of garbage",
|
||||
font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()),
|
||||
));
|
||||
out.push((
|
||||
"TrueType claiming 65535 tables",
|
||||
font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()),
|
||||
));
|
||||
out.push((
|
||||
"truncated Type 1 font",
|
||||
font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec()),
|
||||
));
|
||||
// Encryption with a handler that does not exist.
|
||||
out.push((
|
||||
"unknown security handler",
|
||||
replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"),
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
fn fetched() -> Vec<(String, Vec<u8>)> {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
|
||||
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
|
||||
let mut v: Vec<(String, Vec<u8>)> = rd
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
|
||||
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct Tally {
|
||||
ok: usize,
|
||||
typed_error: usize,
|
||||
timed_out: usize,
|
||||
out_of_memory: usize,
|
||||
crashed: usize,
|
||||
}
|
||||
|
||||
fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
|
||||
let start = Instant::now();
|
||||
let r = w.call(op, args, CAP);
|
||||
let took = start.elapsed();
|
||||
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
|
||||
let outcome = match &r {
|
||||
Ok(_) => {
|
||||
tally.ok += 1;
|
||||
"ok".to_string()
|
||||
}
|
||||
Err(WorkerError::Op(e)) => {
|
||||
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
|
||||
tally.typed_error += 1;
|
||||
format!("{} ({})", e.kind, e.message)
|
||||
}
|
||||
Err(WorkerError::TimedOut(_)) => {
|
||||
tally.timed_out += 1;
|
||||
"timed out".into()
|
||||
}
|
||||
Err(WorkerError::OutOfMemory) => {
|
||||
tally.out_of_memory += 1;
|
||||
"out of memory".into()
|
||||
}
|
||||
Err(WorkerError::Crashed(m)) => {
|
||||
tally.crashed += 1;
|
||||
format!("crashed: {m}")
|
||||
}
|
||||
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
|
||||
};
|
||||
println!("{name:40} {op:10} {took:>8.2?} {outcome}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
let mut w = worker();
|
||||
let mut tally = Tally::default();
|
||||
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
|
||||
all.extend(fetched());
|
||||
let annotation =
|
||||
json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
|
||||
for (i, (name, bytes)) in all.iter().enumerate() {
|
||||
let path = dir.path().join(format!("f{i}.pdf"));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let p = path.to_string_lossy().to_string();
|
||||
let start = Instant::now();
|
||||
let opened = w.call("pdf.open", json!({"path": p}), CAP);
|
||||
let took = start.elapsed();
|
||||
let doc = match &opened {
|
||||
Ok(v) => {
|
||||
tally.ok += 1;
|
||||
println!(
|
||||
"{name:40} {:10} {took:>8.2?} ok, {} pages",
|
||||
"open",
|
||||
v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0)
|
||||
);
|
||||
v["doc"].as_u64()
|
||||
}
|
||||
Err(e) => {
|
||||
match e {
|
||||
WorkerError::Op(_) => tally.typed_error += 1,
|
||||
WorkerError::TimedOut(_) => tally.timed_out += 1,
|
||||
WorkerError::OutOfMemory => tally.out_of_memory += 1,
|
||||
WorkerError::Crashed(_) => tally.crashed += 1,
|
||||
WorkerError::Spawn(e) => panic!("{e}"),
|
||||
}
|
||||
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(doc) = doc {
|
||||
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
|
||||
if w.take_restarted() {
|
||||
continue;
|
||||
}
|
||||
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
|
||||
if w.take_restarted() {
|
||||
continue;
|
||||
}
|
||||
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
|
||||
run(
|
||||
&mut w,
|
||||
&mut tally,
|
||||
name,
|
||||
"pdf.save",
|
||||
json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}),
|
||||
);
|
||||
}
|
||||
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
|
||||
w.take_restarted();
|
||||
// The tray carries on: a normal request right after works.
|
||||
let good = dir.path().join("good.pdf");
|
||||
std::fs::write(&good, valid()).unwrap();
|
||||
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one");
|
||||
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap();
|
||||
}
|
||||
println!("{} fixtures: {tally:?}", all.len());
|
||||
assert!(all.len() >= 21);
|
||||
assert_eq!(tally.timed_out, 0, "a fixture hung");
|
||||
assert_eq!(tally.crashed, 0, "a worker died without a known cause");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_survives_crash_hang_and_memory_blowup() {
|
||||
let mut w = worker();
|
||||
let crash = w.call("debug.crash", json!({}), CAP);
|
||||
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}");
|
||||
assert!(w.take_restarted());
|
||||
let start = Instant::now();
|
||||
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2));
|
||||
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}");
|
||||
assert!(start.elapsed() < Duration::from_secs(10));
|
||||
let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP);
|
||||
// try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory.
|
||||
assert!(
|
||||
matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))),
|
||||
"the 1 GB memory cap did not hold: {oom:?}"
|
||||
);
|
||||
// And it works again.
|
||||
let ok = w.call("image.heif_support", json!({}), CAP).unwrap();
|
||||
assert!(ok["support"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_operations_and_bad_arguments_are_typed_errors() {
|
||||
let mut w = worker();
|
||||
for (op, args) in [
|
||||
("nope", json!({})),
|
||||
("pdf.open", json!({"wrong": 1})),
|
||||
("pdf.render", json!({"doc": 77, "page": 0, "width": 10})),
|
||||
] {
|
||||
match w.call(op, args, CAP) {
|
||||
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"),
|
||||
other => panic!("{op}: {other:?}"),
|
||||
}
|
||||
}
|
||||
let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP);
|
||||
assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}");
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
# 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), 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 |
|
||||
|
||||
## 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.
|
||||
|
||||
<!-- deps:begin -->
|
||||
141 crates; 0 outside the allowed set.
|
||||
|
||||
| Crate | Version | Licence | Allowed |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes |
|
||||
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
||||
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
||||
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
||||
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
||||
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
||||
| block-buffer | 0.12.1 | MIT OR Apache-2.0 | yes |
|
||||
| block-padding | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
||||
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
||||
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
||||
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
||||
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
||||
| bytes | 1.12.1 | MIT | yes |
|
||||
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| cfg_aliases | 0.2.2 | MIT | yes |
|
||||
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
||||
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
||||
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
||||
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
||||
| color_quant | 1.1.0 | MIT | yes |
|
||||
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
||||
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
||||
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
||||
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
||||
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
||||
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
||||
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
||||
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
||||
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
||||
| fax | 0.2.7 | MIT | yes |
|
||||
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
||||
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||
| foldhash | 0.2.0 | Zlib | yes |
|
||||
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes |
|
||||
| gif | 0.14.2 | MIT OR Apache-2.0 | yes |
|
||||
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
||||
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
||||
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
||||
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
||||
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
||||
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
||||
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
||||
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
||||
| libloading | 0.9.1 | ISC | yes |
|
||||
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
||||
| lopdf | 0.47.0 | MIT | yes |
|
||||
| lru | 0.18.5 | MIT | yes |
|
||||
| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes |
|
||||
| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes |
|
||||
| memchr | 2.8.3 | Unlicense OR MIT | yes |
|
||||
| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||
| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||
| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes |
|
||||
| multiversion_no_op | 1.0.0 | Apache-2.0 OR MIT | yes |
|
||||
| mutate_once | 0.1.2 | BSD-2-Clause | yes |
|
||||
| nom | 8.0.0 | MIT | yes |
|
||||
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
||||
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
||||
| piston-float | 1.0.1 | MIT | yes |
|
||||
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
||||
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
||||
| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes |
|
||||
| proptest | 1.12.0 | MIT OR Apache-2.0 | yes |
|
||||
| pxfm | 0.1.30 | BSD-3-Clause OR Apache-2.0 | yes |
|
||||
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
||||
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
||||
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
||||
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
||||
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
||||
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
||||
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
||||
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
||||
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
||||
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
||||
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
||||
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
||||
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
||||
| serde | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
||||
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
||||
| simd-adler32 | 0.3.10 | MIT | yes |
|
||||
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
||||
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
||||
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
||||
| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||
| tiff | 0.11.3 | MIT | yes |
|
||||
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
||||
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
||||
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
||||
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
||||
| vecmath | 1.0.0 | MIT | yes |
|
||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
||||
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-collections | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-core | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-future | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-implement | 0.60.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-interface | 0.59.3 | MIT OR Apache-2.0 | yes |
|
||||
| windows-link | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-numerics | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-result | 0.4.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-strings | 0.5.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| winnow | 1.0.5 | MIT | yes |
|
||||
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||
| zlib-rs | 0.6.8 | Zlib | yes |
|
||||
| zmij | 1.0.23 | MIT | yes |
|
||||
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||
<!-- deps:end -->
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Formats and the worker protocol
|
||||
|
||||
What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to
|
||||
`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own
|
||||
section here.
|
||||
|
||||
## Images (crates/raster, crates/meta)
|
||||
|
||||
| Format | Read | Write | Metadata strip |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical |
|
||||
| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical |
|
||||
| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed |
|
||||
| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) |
|
||||
| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused |
|
||||
| BMP | yes | yes | (no metadata) |
|
||||
| ICO | yes | 256/48/32/16 px | — |
|
||||
| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first |
|
||||
| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — |
|
||||
|
||||
Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`):
|
||||
128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding.
|
||||
|
||||
HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video
|
||||
Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing.
|
||||
|
||||
## PDF (crates/pdf)
|
||||
|
||||
Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the
|
||||
page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space.
|
||||
|
||||
| Operation | Library | Why |
|
||||
| :-- | :-- | :-- |
|
||||
| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens |
|
||||
| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) |
|
||||
| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over |
|
||||
| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask |
|
||||
| PDF → PNG/JPG | pdfium | rendering |
|
||||
| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too |
|
||||
| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` |
|
||||
| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation |
|
||||
| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | |
|
||||
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
||||
| password off | lopdf decrypting load + plain save | |
|
||||
| true redaction | pdfium render + lopdf rebuild (below) | |
|
||||
|
||||
### True redaction
|
||||
|
||||
Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted
|
||||
black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept,
|
||||
`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page
|
||||
tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and
|
||||
`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and
|
||||
non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they
|
||||
stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is
|
||||
written fresh (no incremental history). The other pages' objects are written back byte for byte.
|
||||
|
||||
Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only
|
||||
what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form
|
||||
XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests
|
||||
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
||||
and decompressed), and a raw byte grep.
|
||||
|
||||
## The worker protocol (crates/worker), version 1
|
||||
|
||||
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
||||
`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol.
|
||||
|
||||
```
|
||||
→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}}
|
||||
← {"id": 7, "ok": {"png": "<base64>", "width": 1200, "height": 1553}}
|
||||
← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}}
|
||||
```
|
||||
|
||||
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
||||
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
||||
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
||||
|
||||
| Operation | Arguments | Result |
|
||||
| :-- | :-- | :-- |
|
||||
| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) |
|
||||
| `pdf.close` | `doc` | — |
|
||||
| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` |
|
||||
| `pdf.text` | `doc` | `pages`: text per page |
|
||||
| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) |
|
||||
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
||||
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
||||
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
||||
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
||||
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
||||
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
||||
| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` |
|
||||
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
||||
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
||||
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
||||
| `image.heif_support` | — | `support` |
|
||||
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
||||
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
||||
| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` |
|
||||
|
||||
Saving: `mode: new` refuses to replace a file (the app picks `<name>-edited.pdf`); `overwrite` writes
|
||||
`<file>.bak` first, then replaces the file in one rename (`crates/save`).
|
||||
|
||||
Caps: files over 1 GB are refused; the client runs the worker in a Job Object (2 GB by default, killed with the
|
||||
app) and gives each request a time cap; a worker that hangs or dies is replaced on the next request (open documents
|
||||
must then be opened again).
|
||||
@@ -0,0 +1,28 @@
|
||||
# Fetches real-world hostile PDFs for the worker's hostile test (crates/worker/tests/hostile_pdf.rs) into
|
||||
# fixtures/fetched/. Never in git. Every file is pinned by sha256 and by the source commit; a mismatch is deleted
|
||||
# and the script fails. The generated fixtures in the test need nothing; these add files other tools broke on.
|
||||
# Source: the pdf.js test corpus (mozilla/pdf.js, test/pdfs), commit bb1539a2c9b5b76d070284cca9091717133d8bf1.
|
||||
# Usage: powershell -File fixtures-fetch/fetch.ps1
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Commit = 'bb1539a2c9b5b76d070284cca9091717133d8bf1'
|
||||
$Base = "https://raw.githubusercontent.com/mozilla/pdf.js/$Commit/test/pdfs"
|
||||
$Files = [ordered]@{
|
||||
'GHOSTSCRIPT-698804-1-fuzzed.pdf' = '62e518ca7894e8b8b8ed9927da3007cdc5e9ccc5b111bbb22d6101d4a8d7490e'
|
||||
'PDFBOX-3148-2-fuzzed.pdf' = '1c780335b494ac52eae9fa4d05f1bba88c18ca6b24e6e302b9f271de05e256aa'
|
||||
'bad-PageLabels.pdf' = 'eff0ee7d1cf2e1a7ccfb25a8fc4c2bbea0ec23c838b61a199a57dbb732ddeaad'
|
||||
'boundingBox_invalid.pdf' = 'f85be7aaf217f8f1864b910501d4aeea53f3d7a503df5b81dd6aaa267e5968ad'
|
||||
'checkbox-bad-appearance.pdf' = '0cd13bf7375a2b6b9b01bb694aefcfe9dac225105cb9ad7e03798783b3318ad9'
|
||||
'helloworld-bad.pdf' = 'c3e22ea5d7e6f5b7218d76abce4284728889df516a93c1b74a82c4fd69aa1639'
|
||||
}
|
||||
$Dest = Join-Path $PSScriptRoot '..\fixtures\fetched'
|
||||
New-Item -ItemType Directory -Force $Dest | Out-Null
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
foreach ($name in $Files.Keys) {
|
||||
$path = Join-Path $Dest $name
|
||||
if ((Test-Path $path) -and ((Get-FileHash -Algorithm SHA256 $path).Hash.ToLowerInvariant() -eq $Files[$name])) { continue }
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$Base/$name" -OutFile $path
|
||||
$got = (Get-FileHash -Algorithm SHA256 $path).Hash.ToLowerInvariant()
|
||||
if ($got -ne $Files[$name]) { Remove-Item $path; throw "$name sha256 mismatch: expected $($Files[$name]), got $got" }
|
||||
Write-Host "fetched $name"
|
||||
}
|
||||
Write-Host "$($Files.Count) hostile PDFs in $Dest"
|
||||
@@ -0,0 +1,2 @@
|
||||
max_width = 120
|
||||
use_small_heuristics = "Max"
|
||||
@@ -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(/<!-- deps:begin -->[\s\S]*<!-- deps:end -->/, `<!-- deps:begin -->\n${table}\n<!-- deps:end -->`);
|
||||
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();
|
||||
@@ -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 <folder>]
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user