Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bf0bb1db5d | |||
| 0cba2be2b2 | |||
| 17db54fdbf | |||
| e46cbe3547 | |||
| 45f1d40c5b | |||
| 47576bd6e0 | |||
| 6efc835d24 | |||
| f1f0234ffb | |||
| fcc9840fdc | |||
| a400ff88a6 | |||
| 27d7e12a51 | |||
| c5a81eafbf | |||
| 74292ae819 | |||
| a06e3f9b73 | |||
| 196802863a | |||
| 81628d4b51 | |||
| 66aa2a1f18 | |||
| 249c19ea61 | |||
| ce1e8785d9 | |||
| ede068f7c9 | |||
| 2c1611b34a | |||
| b554d760e2 |
@@ -0,0 +1,19 @@
|
||||
# Pictor's core: every test, on the Windows runner (Fabrica on Mark's PC), in the background. pdfium is fetched by
|
||||
# its pinned script; the optional hostile corpus too. LibreOffice, when installed, is used by the PDF-to-Word test.
|
||||
name: test
|
||||
on:
|
||||
push: [main]
|
||||
manual: true
|
||||
runner: windows
|
||||
env:
|
||||
RUST_BACKTRACE: "1"
|
||||
steps:
|
||||
- id: pdfium
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/fetch-pdfium.ps1
|
||||
- id: corpus
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File fixtures-fetch/fetch.ps1
|
||||
- id: test
|
||||
needs: [pdfium, corpus]
|
||||
run: cargo test --workspace --release
|
||||
- id: licences
|
||||
run: node --test scripts/deps.test.mjs && node scripts/deps.mjs --check
|
||||
Generated
+2192
File diff suppressed because it is too large
Load Diff
+42
-38
@@ -1,39 +1,43 @@
|
||||
[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" }
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/doc", "crates/worker"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public"
|
||||
rust-version = "1.88"
|
||||
|
||||
# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used.
|
||||
[workspace.dependencies]
|
||||
pictor-raster = { path = "crates/raster" }
|
||||
pictor-pdf = { path = "crates/pdf" }
|
||||
pictor-meta = { path = "crates/meta" }
|
||||
pictor-qr = { path = "crates/qr" }
|
||||
pictor-save = { path = "crates/save" }
|
||||
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] }
|
||||
kamadak-exif = "0.6"
|
||||
img-parts = "0.4"
|
||||
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
||||
lopdf = { version = "0.47", default-features = false }
|
||||
pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] }
|
||||
tempfile = "3"
|
||||
sha2 = "0.11"
|
||||
windows = "0.62"
|
||||
|
||||
# dev-only
|
||||
rqrr = "0.11"
|
||||
proptest = "1"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
pictor-doc = { path = "crates/doc" }
|
||||
|
||||
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"
|
||||
docx-rs = { version = "0.4.22", default-features = false }
|
||||
flate2 = "1"
|
||||
windows = "0.62"
|
||||
|
||||
# dev-only
|
||||
rqrr = "0.11"
|
||||
proptest = "1"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "pictor-doc"
|
||||
description = "Pictor's document model: pages, layers, vector objects and bitmaps; operations with exact undo; the .pictor format; text, rendering and export"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
thiserror.workspace = true
|
||||
serde = { workspace = true, features = ["rc"] }
|
||||
serde_json.workspace = true
|
||||
base64.workspace = true
|
||||
image.workspace = true
|
||||
sha2.workspace = true
|
||||
tiny-skia = "0.12"
|
||||
usvg = { version = "0.50", default-features = false, features = ["text", "system-fonts", "memmap-fonts"] }
|
||||
fontdb = { version = "0.24", default-features = false, features = ["fs", "memmap"] }
|
||||
rustybuzz = "0.20"
|
||||
ttf-parser = "0.25"
|
||||
pdf-writer = "0.15"
|
||||
subsetter = "0.2"
|
||||
flate2.workspace = true
|
||||
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest.workspace = true
|
||||
pictor-pdf.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,697 @@
|
||||
//! Pixel tools on a bitmap layer's raster: brush, pencil, eraser, fill bucket, magic wand, rectangle and lasso
|
||||
//! selections, delete and copy, adjustments, blur, sharpen, invert, clone stamp, and applying a matte (background
|
||||
//! removal). Each returns the rectangle it changed, so the caller can record one exact undo patch.
|
||||
use crate::model::{Document, PixelRect, Raster};
|
||||
use crate::ops::Op;
|
||||
|
||||
/// A selection: one coverage byte per pixel of the raster it belongs to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Mask {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Mask {
|
||||
pub fn empty(width: u32, height: u32) -> Mask {
|
||||
Mask { width, height, data: vec![0; width as usize * height as usize] }
|
||||
}
|
||||
|
||||
pub fn rect(width: u32, height: u32, r: PixelRect) -> Mask {
|
||||
let mut m = Mask::empty(width, height);
|
||||
let r = r.clamp(width, height);
|
||||
for y in r.y..r.y + r.h {
|
||||
let row = y as usize * width as usize;
|
||||
m.data[row + r.x as usize..row + (r.x + r.w) as usize].fill(255);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// A polygon (lasso), anti-aliased at its edge.
|
||||
pub fn polygon(width: u32, height: u32, points: &[(f32, f32)]) -> Mask {
|
||||
let mut m = Mask::empty(width, height);
|
||||
if points.len() < 3 {
|
||||
return m;
|
||||
}
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
pb.move_to(points[0].0, points[0].1);
|
||||
for p in &points[1..] {
|
||||
pb.line_to(p.0, p.1);
|
||||
}
|
||||
pb.close();
|
||||
let (Some(path), Some(mut sm)) = (pb.finish(), tiny_skia::Mask::new(width, height)) else { return m };
|
||||
sm.fill_path(&path, tiny_skia::FillRule::EvenOdd, true, tiny_skia::Transform::identity());
|
||||
m.data.copy_from_slice(sm.data());
|
||||
m
|
||||
}
|
||||
|
||||
pub fn get(&self, x: u32, y: u32) -> u8 {
|
||||
self.data[y as usize * self.width as usize + x as usize]
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.iter().all(|v| *v == 0)
|
||||
}
|
||||
|
||||
pub fn bbox(&self) -> PixelRect {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
|
||||
for y in 0..self.height {
|
||||
for x in 0..self.width {
|
||||
if self.get(x, y) > 0 {
|
||||
x0 = x0.min(x);
|
||||
y0 = y0.min(y);
|
||||
x1 = x1.max(x + 1);
|
||||
y1 = y1.max(y + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if x0 == u32::MAX {
|
||||
PixelRect { x: 0, y: 0, w: 0, h: 0 }
|
||||
} else {
|
||||
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invert(&mut self) {
|
||||
for v in &mut self.data {
|
||||
*v = 255 - *v;
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection's edge as path data (pixel edges between inside and outside), for the marching ants.
|
||||
pub fn outline(&self) -> String {
|
||||
use std::fmt::Write;
|
||||
let inside = |x: i64, y: i64| {
|
||||
x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64 && self.get(x as u32, y as u32) >= 128
|
||||
};
|
||||
let mut d = String::new();
|
||||
// Horizontal edges, merged along each row.
|
||||
for y in 0..=self.height as i64 {
|
||||
let mut start: Option<i64> = None;
|
||||
for x in 0..=self.width as i64 {
|
||||
let edge = x < self.width as i64 && inside(x, y) != inside(x, y - 1);
|
||||
match (edge, start) {
|
||||
(true, None) => start = Some(x),
|
||||
(false, Some(s)) => {
|
||||
let _ = write!(d, "M{s} {y}H{x}");
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for x in 0..=self.width as i64 {
|
||||
let mut start: Option<i64> = None;
|
||||
for y in 0..=self.height as i64 {
|
||||
let edge = y < self.height as i64 && inside(x, y) != inside(x - 1, y);
|
||||
match (edge, start) {
|
||||
(true, None) => start = Some(y),
|
||||
(false, Some(s)) => {
|
||||
let _ = write!(d, "M{x} {s}V{y}");
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
fn sel(mask: Option<&Mask>, x: u32, y: u32) -> f32 {
|
||||
mask.map(|m| m.get(x, y) as f32 / 255.0).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
/// Source-over in straight alpha: `src` (straight RGBA) with extra coverage `cov` onto `dst`.
|
||||
fn blend(dst: &mut [u8], src: [u8; 4], cov: f32) {
|
||||
let sa = src[3] as f32 / 255.0 * cov;
|
||||
if sa <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let da = dst[3] as f32 / 255.0;
|
||||
let oa = sa + da * (1.0 - sa);
|
||||
if oa <= 0.0 {
|
||||
dst.copy_from_slice(&[0, 0, 0, 0]);
|
||||
return;
|
||||
}
|
||||
for i in 0..3 {
|
||||
let v = (src[i] as f32 * sa + dst[i] as f32 * da * (1.0 - sa)) / oa;
|
||||
dst[i] = v.round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
dst[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Brush {
|
||||
/// Radius in pixels at full pressure.
|
||||
pub radius: f32,
|
||||
/// 0 = soft to the centre, 1 = a hard edge.
|
||||
pub hardness: f32,
|
||||
pub color: [u8; 4],
|
||||
/// 0..1 for the whole stroke (a stroke never builds up over itself).
|
||||
pub opacity: f32,
|
||||
pub erase: bool,
|
||||
}
|
||||
|
||||
/// Stroke coverage (0..1) over a rectangle: dabs along the points, the maximum where they overlap.
|
||||
struct Coverage {
|
||||
rect: PixelRect,
|
||||
cov: Vec<f32>,
|
||||
}
|
||||
|
||||
fn coverage(width: u32, height: u32, points: &[(f32, f32, f32)], radius: f32, hardness: f32) -> Coverage {
|
||||
let r = radius.max(0.5);
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||
for (x, y, _) in points {
|
||||
x0 = x0.min(x - r - 1.0);
|
||||
y0 = y0.min(y - r - 1.0);
|
||||
x1 = x1.max(x + r + 1.0);
|
||||
y1 = y1.max(y + r + 1.0);
|
||||
}
|
||||
let rect = PixelRect {
|
||||
x: x0.max(0.0) as u32,
|
||||
y: y0.max(0.0) as u32,
|
||||
w: (x1.min(width as f32).max(0.0) - x0.max(0.0)).max(0.0).ceil() as u32,
|
||||
h: (y1.min(height as f32).max(0.0) - y0.max(0.0)).max(0.0).ceil() as u32,
|
||||
}
|
||||
.clamp(width, height);
|
||||
let mut cov = vec![0f32; rect.w as usize * rect.h as usize];
|
||||
let hard = hardness.clamp(0.0, 0.99);
|
||||
let mut dab = |cx: f32, cy: f32, pr: f32| {
|
||||
let rr = (r * pr.clamp(0.05, 1.0)).max(0.5);
|
||||
let bx0 = ((cx - rr - 1.0).floor().max(rect.x as f32)) as u32;
|
||||
let by0 = ((cy - rr - 1.0).floor().max(rect.y as f32)) as u32;
|
||||
let bx1 = ((cx + rr + 1.0).ceil().min((rect.x + rect.w) as f32)) as u32;
|
||||
let by1 = ((cy + rr + 1.0).ceil().min((rect.y + rect.h) as f32)) as u32;
|
||||
for y in by0..by1 {
|
||||
for x in bx0..bx1 {
|
||||
let d = (((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt()) / rr;
|
||||
// A hard core, then a smooth fall to the edge; half a pixel of anti-aliasing at any size.
|
||||
let edge = 1.0 - (d * rr - rr + 0.5).clamp(0.0, 1.0);
|
||||
let a = if d <= hard {
|
||||
edge
|
||||
} else {
|
||||
let t = ((d - hard) / (1.0 - hard)).clamp(0.0, 1.0);
|
||||
(1.0 - t * t * (3.0 - 2.0 * t)).min(edge)
|
||||
};
|
||||
let i = (y - rect.y) as usize * rect.w as usize + (x - rect.x) as usize;
|
||||
if a > cov[i] {
|
||||
cov[i] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(&(x, y, p)) = points.first() {
|
||||
dab(x, y, p);
|
||||
}
|
||||
for w in points.windows(2) {
|
||||
let (ax, ay, ap) = w[0];
|
||||
let (bx, by, bp) = w[1];
|
||||
let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt();
|
||||
let step = (r * ap.min(bp).clamp(0.05, 1.0) * 0.25).max(0.5);
|
||||
let n = (len / step).ceil().max(1.0) as usize;
|
||||
for i in 1..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
dab(ax + (bx - ax) * t, ay + (by - ay) * t, ap + (bp - ap) * t);
|
||||
}
|
||||
}
|
||||
Coverage { rect, cov }
|
||||
}
|
||||
|
||||
/// Brush or eraser along `points` (x, y, pressure 0..1).
|
||||
pub fn brush(r: &mut Raster, points: &[(f32, f32, f32)], b: &Brush, mask: Option<&Mask>) -> PixelRect {
|
||||
if points.is_empty() {
|
||||
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
}
|
||||
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||
for y in 0..c.rect.h {
|
||||
for x in 0..c.rect.w {
|
||||
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||
let dst = &mut r.rgba[i..i + 4];
|
||||
if b.erase {
|
||||
let a = dst[3] as f32 * (1.0 - k * b.color[3] as f32 / 255.0);
|
||||
dst[3] = a.round() as u8;
|
||||
} else {
|
||||
blend(dst, b.color, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.rect
|
||||
}
|
||||
|
||||
/// Pencil: hard square pixels of `size` along the points, no anti-aliasing.
|
||||
pub fn pencil(
|
||||
r: &mut Raster,
|
||||
points: &[(f32, f32)],
|
||||
size: u32,
|
||||
color: [u8; 4],
|
||||
erase: bool,
|
||||
mask: Option<&Mask>,
|
||||
) -> PixelRect {
|
||||
let mut dirty = PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
let s = size.max(1) as i64;
|
||||
let mut put = |x: i64, y: i64, r: &mut Raster| {
|
||||
let x0 = x - (s - 1) / 2;
|
||||
let y0 = y - (s - 1) / 2;
|
||||
for yy in y0..y0 + s {
|
||||
for xx in x0..x0 + s {
|
||||
if xx < 0 || yy < 0 || xx >= r.width as i64 || yy >= r.height as i64 {
|
||||
continue;
|
||||
}
|
||||
let k = sel(mask, xx as u32, yy as u32);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||
if erase {
|
||||
r.rgba[i + 3] = (r.rgba[i + 3] as f32 * (1.0 - k)).round() as u8;
|
||||
} else if k >= 1.0 {
|
||||
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||
} else {
|
||||
blend(&mut r.rgba[i..i + 4], color, k);
|
||||
}
|
||||
dirty = dirty.union(PixelRect { x: xx as u32, y: yy as u32, w: 1, h: 1 });
|
||||
}
|
||||
}
|
||||
};
|
||||
let pts: Vec<(i64, i64)> = points.iter().map(|(x, y)| (x.floor() as i64, y.floor() as i64)).collect();
|
||||
if let Some(&(x, y)) = pts.first() {
|
||||
put(x, y, r);
|
||||
}
|
||||
for w in pts.windows(2) {
|
||||
// Bresenham.
|
||||
let (mut x0, mut y0) = w[0];
|
||||
let (x1, y1) = w[1];
|
||||
let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs());
|
||||
let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 });
|
||||
let mut err = dx + dy;
|
||||
loop {
|
||||
put(x0, y0, r);
|
||||
if x0 == x1 && y0 == y1 {
|
||||
break;
|
||||
}
|
||||
let e2 = 2 * err;
|
||||
if e2 >= dy {
|
||||
err += dy;
|
||||
x0 += sx;
|
||||
}
|
||||
if e2 <= dx {
|
||||
err += dx;
|
||||
y0 += sy;
|
||||
}
|
||||
}
|
||||
}
|
||||
dirty
|
||||
}
|
||||
|
||||
/// Whether a pixel belongs with the seed: transparent with transparent (by alpha), visible with visible by colour
|
||||
/// alone, so a stroke's soft, half-transparent edge goes with the stroke.
|
||||
fn close(a: &[u8], b: [u8; 4], tol: u8) -> bool {
|
||||
if b[3] == 0 {
|
||||
return a[3] <= tol;
|
||||
}
|
||||
if a[3] == 0 {
|
||||
return false;
|
||||
}
|
||||
(0..3).all(|i| (a[i] as i16 - b[i] as i16).unsigned_abs() <= tol as u16)
|
||||
}
|
||||
|
||||
/// The region around (x, y) whose pixels are within `tol` of its colour (4-connected).
|
||||
pub fn region(r: &Raster, x: u32, y: u32, tol: u8) -> Mask {
|
||||
let mut m = Mask::empty(r.width, r.height);
|
||||
if x >= r.width || y >= r.height {
|
||||
return m;
|
||||
}
|
||||
let seed = r.pixel(x, y);
|
||||
let w = r.width as usize;
|
||||
let mut stack = vec![(x, y)];
|
||||
while let Some((sx, sy)) = stack.pop() {
|
||||
// Scanline fill: walk left and right, then queue the rows above and below.
|
||||
let row = sy as usize * w;
|
||||
if m.data[row + sx as usize] != 0 {
|
||||
continue;
|
||||
}
|
||||
let px = |xx: u32| &r.rgba[(row + xx as usize) * 4..(row + xx as usize) * 4 + 4];
|
||||
let mut l = sx;
|
||||
while l > 0 && m.data[row + l as usize - 1] == 0 && close(px(l - 1), seed, tol) {
|
||||
l -= 1;
|
||||
}
|
||||
let mut rr = sx;
|
||||
while rr + 1 < r.width && m.data[row + rr as usize + 1] == 0 && close(px(rr + 1), seed, tol) {
|
||||
rr += 1;
|
||||
}
|
||||
for xx in l..=rr {
|
||||
m.data[row + xx as usize] = 255;
|
||||
}
|
||||
for ny in [sy.wrapping_sub(1), sy + 1] {
|
||||
if ny >= r.height {
|
||||
continue;
|
||||
}
|
||||
let nrow = ny as usize * w;
|
||||
let mut xx = l;
|
||||
while xx <= rr {
|
||||
let i = nrow + xx as usize;
|
||||
if m.data[i] == 0 && close(&r.rgba[i * 4..i * 4 + 4], seed, tol) {
|
||||
stack.push((xx, ny));
|
||||
// Skip the rest of this run; it is filled from the pushed seed.
|
||||
while xx <= rr && close(&r.rgba[(nrow + xx as usize) * 4..(nrow + xx as usize) * 4 + 4], seed, tol)
|
||||
{
|
||||
xx += 1;
|
||||
}
|
||||
} else {
|
||||
xx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Fill bucket: the region around (x, y) becomes `color` (inside the selection, if any).
|
||||
pub fn fill(r: &mut Raster, x: u32, y: u32, tol: u8, color: [u8; 4], mask: Option<&Mask>) -> PixelRect {
|
||||
let reg = region(r, x, y, tol);
|
||||
let b = reg.bbox();
|
||||
for yy in b.y..b.y + b.h {
|
||||
for xx in b.x..b.x + b.w {
|
||||
if reg.get(xx, yy) == 0 {
|
||||
continue;
|
||||
}
|
||||
let k = sel(mask, xx, yy);
|
||||
let i = (yy as usize * r.width as usize + xx as usize) * 4;
|
||||
if k >= 1.0 {
|
||||
r.rgba[i..i + 4].copy_from_slice(&color);
|
||||
} else if k > 0.0 {
|
||||
let old: [u8; 4] = r.rgba[i..i + 4].try_into().unwrap();
|
||||
for c in 0..4 {
|
||||
r.rgba[i + c] = (old[c] as f32 + (color[c] as f32 - old[c] as f32) * k).round() as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Delete: the selected pixels (or all) become transparent.
|
||||
pub fn clear(r: &mut Raster, mask: Option<&Mask>) -> PixelRect {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||
for y in b.y..b.y + b.h {
|
||||
for x in b.x..b.x + b.w {
|
||||
let k = sel(mask, x, y);
|
||||
let i = (y as usize * r.width as usize + x as usize) * 4 + 3;
|
||||
r.rgba[i] = (r.rgba[i] as f32 * (1.0 - k)).round() as u8;
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Copy: the selected pixels (alpha × selection) in their bounding box, and where that box is.
|
||||
pub fn copy(r: &Raster, mask: Option<&Mask>) -> (Raster, PixelRect) {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: r.width, h: r.height });
|
||||
let mut out = r.crop(b);
|
||||
if let Some(m) = mask {
|
||||
for y in 0..b.h {
|
||||
for x in 0..b.w {
|
||||
let i = (y as usize * b.w as usize + x as usize) * 4 + 3;
|
||||
out.rgba[i] = (out.rgba[i] as u32 * m.get(b.x + x, b.y + y) as u32 / 255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, b)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Adjust {
|
||||
/// −100..100.
|
||||
Brightness {
|
||||
amount: f32,
|
||||
},
|
||||
/// −100..100.
|
||||
Contrast {
|
||||
amount: f32,
|
||||
},
|
||||
/// Input black and white points (0..255), gamma (0.1..10), output black and white.
|
||||
Levels {
|
||||
in_black: f32,
|
||||
in_white: f32,
|
||||
gamma: f32,
|
||||
out_black: f32,
|
||||
out_white: f32,
|
||||
},
|
||||
/// Hue in degrees, saturation and lightness −100..100.
|
||||
HueSaturation {
|
||||
hue: f32,
|
||||
saturation: f32,
|
||||
lightness: f32,
|
||||
},
|
||||
Invert,
|
||||
/// Radius in pixels.
|
||||
Blur {
|
||||
radius: f32,
|
||||
},
|
||||
/// Amount 0..5, radius in pixels.
|
||||
Sharpen {
|
||||
amount: f32,
|
||||
radius: f32,
|
||||
},
|
||||
}
|
||||
|
||||
fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let l = (max + min) / 2.0;
|
||||
if max == min {
|
||||
return (0.0, 0.0, l);
|
||||
}
|
||||
let d = max - min;
|
||||
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
(h * 60.0, s, l)
|
||||
}
|
||||
|
||||
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
|
||||
if s == 0.0 {
|
||||
return (l, l, l);
|
||||
}
|
||||
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
|
||||
let p = 2.0 * l - q;
|
||||
let hue = |mut t: f32| {
|
||||
t = t.rem_euclid(1.0);
|
||||
if t < 1.0 / 6.0 {
|
||||
p + (q - p) * 6.0 * t
|
||||
} else if t < 0.5 {
|
||||
q
|
||||
} else if t < 2.0 / 3.0 {
|
||||
p + (q - p) * (2.0 / 3.0 - t) * 6.0
|
||||
} else {
|
||||
p
|
||||
}
|
||||
};
|
||||
let h = h / 360.0;
|
||||
(hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0))
|
||||
}
|
||||
|
||||
/// A box blur of premultiplied RGBA, three passes (close to a Gaussian).
|
||||
fn blurred(src: &Raster, radius: f32) -> Vec<f32> {
|
||||
let (w, h) = (src.width as usize, src.height as usize);
|
||||
let mut buf: Vec<f32> = Vec::with_capacity(w * h * 4);
|
||||
for p in src.rgba.as_chunks::<4>().0 {
|
||||
let a = p[3] as f32 / 255.0;
|
||||
buf.extend_from_slice(&[p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, p[3] as f32]);
|
||||
}
|
||||
let r = ((radius / 3.0f32.sqrt()).round() as usize).max(1);
|
||||
let mut tmp = vec![0f32; buf.len()];
|
||||
for _ in 0..3 {
|
||||
for horizontal in [true, false] {
|
||||
let (n, m) = if horizontal { (h, w) } else { (w, h) };
|
||||
for line in 0..n {
|
||||
let idx = |k: usize| if horizontal { (line * w + k) * 4 } else { (k * w + line) * 4 };
|
||||
let mut acc = [0f32; 4];
|
||||
let count = (2 * r + 1) as f32;
|
||||
// Edge pixels repeat beyond the border.
|
||||
for k in 0..(2 * r + 1) {
|
||||
let kk = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||
for c in 0..4 {
|
||||
acc[c] += buf[idx(kk) + c];
|
||||
}
|
||||
}
|
||||
for k in 0..m {
|
||||
for c in 0..4 {
|
||||
tmp[idx(k) + c] = acc[c] / count;
|
||||
}
|
||||
let out = (k as isize - r as isize).clamp(0, m as isize - 1) as usize;
|
||||
let inn = (k as isize + r as isize + 1).clamp(0, m as isize - 1) as usize;
|
||||
for c in 0..4 {
|
||||
acc[c] += buf[idx(inn) + c] - buf[idx(out) + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut buf, &mut tmp);
|
||||
}
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// Writes the adjustment of `src` into `dst` (the same size), inside the selection; `dst` may start as a copy of
|
||||
/// `src` (a live preview re-runs this from the untouched original).
|
||||
pub fn adjust(src: &Raster, dst: &mut Raster, a: &Adjust, mask: Option<&Mask>) -> PixelRect {
|
||||
let b = mask.map(|m| m.bbox()).unwrap_or(PixelRect { x: 0, y: 0, w: src.width, h: src.height });
|
||||
let blur = match a {
|
||||
Adjust::Blur { radius } | Adjust::Sharpen { radius, .. } => Some(blurred(src, radius.max(0.5))),
|
||||
_ => None,
|
||||
};
|
||||
let lut = |f: &dyn Fn(f32) -> f32| -> [u8; 256] {
|
||||
let mut t = [0u8; 256];
|
||||
for (i, v) in t.iter_mut().enumerate() {
|
||||
*v = f(i as f32).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
t
|
||||
};
|
||||
let table: Option<[u8; 256]> = match *a {
|
||||
Adjust::Brightness { amount } => Some(lut(&|v| v + amount * 2.55)),
|
||||
Adjust::Contrast { amount } => {
|
||||
let c = amount.clamp(-100.0, 100.0) * 2.55;
|
||||
let f = (259.0 * (c + 255.0)) / (255.0 * (259.0 - c));
|
||||
Some(lut(&|v| f * (v - 128.0) + 128.0))
|
||||
}
|
||||
Adjust::Levels { in_black, in_white, gamma, out_black, out_white } => {
|
||||
let span = (in_white - in_black).max(1.0);
|
||||
let g = gamma.clamp(0.1, 10.0);
|
||||
Some(lut(&|v| {
|
||||
let t = ((v - in_black) / span).clamp(0.0, 1.0).powf(1.0 / g);
|
||||
out_black + t * (out_white - out_black)
|
||||
}))
|
||||
}
|
||||
Adjust::Invert => Some(lut(&|v| 255.0 - v)),
|
||||
_ => None,
|
||||
};
|
||||
for y in b.y..b.y + b.h {
|
||||
for x in b.x..b.x + b.w {
|
||||
let k = sel(mask, x, y);
|
||||
let i = (y as usize * src.width as usize + x as usize) * 4;
|
||||
let s: [u8; 4] = src.rgba[i..i + 4].try_into().unwrap();
|
||||
let out: [u8; 4] = match (a, &table, &blur) {
|
||||
(_, Some(t), _) => [t[s[0] as usize], t[s[1] as usize], t[s[2] as usize], s[3]],
|
||||
(Adjust::HueSaturation { hue, saturation, lightness }, _, _) => {
|
||||
let (h, sat, l) = rgb_to_hsl(s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0);
|
||||
let sat = (sat * (1.0 + saturation / 100.0)).clamp(0.0, 1.0);
|
||||
let l = if *lightness >= 0.0 {
|
||||
l + (1.0 - l) * lightness / 100.0
|
||||
} else {
|
||||
l * (1.0 + lightness / 100.0)
|
||||
};
|
||||
let (r, g, bb) = hsl_to_rgb(h + hue, sat, l.clamp(0.0, 1.0));
|
||||
[(r * 255.0).round() as u8, (g * 255.0).round() as u8, (bb * 255.0).round() as u8, s[3]]
|
||||
}
|
||||
(Adjust::Blur { .. }, _, Some(bl)) => {
|
||||
let a = bl[i + 3];
|
||||
if a <= 0.0 {
|
||||
[0, 0, 0, 0]
|
||||
} else {
|
||||
let f = 255.0 / a;
|
||||
[
|
||||
(bl[i] * f).round().min(255.0) as u8,
|
||||
(bl[i + 1] * f).round().min(255.0) as u8,
|
||||
(bl[i + 2] * f).round().min(255.0) as u8,
|
||||
a.round() as u8,
|
||||
]
|
||||
}
|
||||
}
|
||||
(Adjust::Sharpen { amount, .. }, _, Some(bl)) => {
|
||||
let a = (bl[i + 3] / 255.0).max(1e-3);
|
||||
let mut o = [0u8; 4];
|
||||
for c in 0..3 {
|
||||
let blur_c = bl[i + c] / a;
|
||||
o[c] = (s[c] as f32 + amount * (s[c] as f32 - blur_c)).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
o[3] = s[3];
|
||||
o
|
||||
}
|
||||
_ => s,
|
||||
};
|
||||
let d = &mut dst.rgba[i..i + 4];
|
||||
if k >= 1.0 {
|
||||
d.copy_from_slice(&out);
|
||||
} else if k > 0.0 {
|
||||
for c in 0..4 {
|
||||
d[c] = (s[c] as f32 + (out[c] as f32 - s[c] as f32) * k).round() as u8;
|
||||
}
|
||||
} else {
|
||||
d.copy_from_slice(&s);
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Clone stamp: dabs that copy from `source` (the layer as it was when the stroke began) at an offset.
|
||||
pub fn clone_stamp(
|
||||
r: &mut Raster,
|
||||
source: &Raster,
|
||||
offset: (f32, f32),
|
||||
points: &[(f32, f32, f32)],
|
||||
b: &Brush,
|
||||
mask: Option<&Mask>,
|
||||
) -> PixelRect {
|
||||
if points.is_empty() {
|
||||
return PixelRect { x: 0, y: 0, w: 0, h: 0 };
|
||||
}
|
||||
let c = coverage(r.width, r.height, points, b.radius, b.hardness);
|
||||
for y in 0..c.rect.h {
|
||||
for x in 0..c.rect.w {
|
||||
let (px, py) = (c.rect.x + x, c.rect.y + y);
|
||||
let k = c.cov[(y * c.rect.w + x) as usize] * b.opacity.clamp(0.0, 1.0) * sel(mask, px, py);
|
||||
if k <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let sx = px as f32 + offset.0;
|
||||
let sy = py as f32 + offset.1;
|
||||
if sx < 0.0 || sy < 0.0 || sx >= source.width as f32 || sy >= source.height as f32 {
|
||||
continue;
|
||||
}
|
||||
let s = source.pixel(sx as u32, sy as u32);
|
||||
let i = (py as usize * r.width as usize + px as usize) * 4;
|
||||
blend(&mut r.rgba[i..i + 4], s, k);
|
||||
}
|
||||
}
|
||||
c.rect
|
||||
}
|
||||
|
||||
/// Multiplies the alpha by a matte (0..255 per pixel, the raster's size): background removal as a layer action.
|
||||
pub fn apply_matte(r: &mut Raster, matte: &[u8]) -> PixelRect {
|
||||
for (p, m) in r.rgba.as_chunks_mut::<4>().0.iter_mut().zip(matte) {
|
||||
p[3] = (p[3] as u32 * *m as u32 / 255) as u8;
|
||||
}
|
||||
PixelRect { x: 0, y: 0, w: r.width, h: r.height }
|
||||
}
|
||||
|
||||
/// Runs a pixel edit on an asset and returns the operation and its inverse (already applied), for
|
||||
/// `History::record`; none when nothing changed or the asset is missing.
|
||||
pub fn edit(doc: &mut Document, asset: &str, f: impl FnOnce(&mut Raster) -> PixelRect) -> Option<(Op, Op)> {
|
||||
let r = doc.assets.get_mut(asset)?;
|
||||
let before = r.clone();
|
||||
let rect = f(r).clamp(r.width, r.height);
|
||||
if rect.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let after = r.crop(rect);
|
||||
let old = before.crop(rect);
|
||||
if after == old {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: after.rgba },
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: old.rgba },
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
//! The display list: what a page looks like, as fill, stroke, image and glyph commands in page coordinates. The core's
|
||||
//! tiny-skia painter (`render`), the face's canvas painter and the PDF and SVG exports all walk this one list, so the
|
||||
//! screen and the export agree. Text is laid out here and enters as glyph outlines (each glyph defined once).
|
||||
use crate::model::*;
|
||||
use crate::path::{self, Seg};
|
||||
use crate::text::{self, FontBook, FontKey};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type Tf = [f32; 6];
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct DisplayList {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub background: Option<[u8; 4]>,
|
||||
/// Glyph outlines in font units (y up), referred to by index from `Text` items.
|
||||
pub glyphs: Vec<GlyphDef>,
|
||||
pub items: Vec<Item>,
|
||||
/// Every top-level object of every visible vector layer, for selection and snapping in the face.
|
||||
pub objects: Vec<ObjectInfo>,
|
||||
/// Pixel sizes of the assets the list uses.
|
||||
pub assets: Vec<AssetInfo>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct GlyphDef {
|
||||
pub d: Arc<str>,
|
||||
pub upem: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct AssetInfo {
|
||||
pub id: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ObjectInfo {
|
||||
pub id: Id,
|
||||
pub layer: Id,
|
||||
pub kind: &'static str,
|
||||
/// The object's own box (x, y, w, h) before its transform.
|
||||
pub local: [f32; 4],
|
||||
pub transform: Tf,
|
||||
/// The four corners of the box on the page (clockwise from the box's top left).
|
||||
pub corners: [[f32; 2]; 4],
|
||||
/// The axis-aligned bounds on the page: x0, y0, x1, y1.
|
||||
pub bounds: [f32; 4],
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(tag = "k", rename_all = "snake_case")]
|
||||
pub enum Item {
|
||||
Fill {
|
||||
d: String,
|
||||
t: Tf,
|
||||
paint: DPaint,
|
||||
even_odd: bool,
|
||||
layer: Id,
|
||||
obj: Option<Id>,
|
||||
},
|
||||
Stroke {
|
||||
d: String,
|
||||
t: Tf,
|
||||
paint: DPaint,
|
||||
width: f32,
|
||||
cap: Cap,
|
||||
join: Join,
|
||||
dash: Vec<f32>,
|
||||
layer: Id,
|
||||
obj: Option<Id>,
|
||||
},
|
||||
/// The asset's pixels (0..width, 0..height) through `t`, clipped to `clip` (path data through `clip_t`).
|
||||
Image {
|
||||
asset: String,
|
||||
t: Tf,
|
||||
clip: Option<String>,
|
||||
clip_t: Tf,
|
||||
smooth: bool,
|
||||
layer: Id,
|
||||
obj: Option<Id>,
|
||||
},
|
||||
Text {
|
||||
t: Tf,
|
||||
color: [u8; 4],
|
||||
size: f32,
|
||||
glyphs: Vec<DGlyph>,
|
||||
#[serde(skip)]
|
||||
family: String,
|
||||
#[serde(skip)]
|
||||
weight: u16,
|
||||
#[serde(skip)]
|
||||
italic: bool,
|
||||
layer: Id,
|
||||
obj: Option<Id>,
|
||||
},
|
||||
/// Everything up to the matching `Pop` is drawn into its own layer, then composited at `opacity`.
|
||||
Push {
|
||||
opacity: f32,
|
||||
},
|
||||
Pop,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct DGlyph {
|
||||
/// Index into `DisplayList::glyphs` (none for an empty glyph such as a space).
|
||||
pub g: Option<u32>,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
#[serde(skip)]
|
||||
pub font: FontKey,
|
||||
#[serde(skip)]
|
||||
pub gid: u16,
|
||||
#[serde(skip)]
|
||||
pub advance: f32,
|
||||
#[serde(skip)]
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum DPaint {
|
||||
Solid { c: [u8; 4] },
|
||||
Linear { x1: f32, y1: f32, x2: f32, y2: f32, stops: Vec<(f32, [u8; 4])> },
|
||||
Radial { cx: f32, cy: f32, r: f32, stops: Vec<(f32, [u8; 4])> },
|
||||
}
|
||||
|
||||
pub fn mul(a: Tf, b: Tf) -> Tf {
|
||||
// a after b: (a ∘ b)(p) = a(b(p)).
|
||||
[
|
||||
a[0] * b[0] + a[2] * b[1],
|
||||
a[1] * b[0] + a[3] * b[1],
|
||||
a[0] * b[2] + a[2] * b[3],
|
||||
a[1] * b[2] + a[3] * b[3],
|
||||
a[0] * b[4] + a[2] * b[5] + a[4],
|
||||
a[1] * b[4] + a[3] * b[5] + a[5],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn apply_tf(t: Tf, x: f32, y: f32) -> [f32; 2] {
|
||||
[t[0] * x + t[2] * y + t[4], t[1] * x + t[3] * y + t[5]]
|
||||
}
|
||||
|
||||
pub fn translate(x: f32, y: f32) -> Tf {
|
||||
[1.0, 0.0, 0.0, 1.0, x, y]
|
||||
}
|
||||
|
||||
pub fn scale(sx: f32, sy: f32) -> Tf {
|
||||
[sx, 0.0, 0.0, sy, 0.0, 0.0]
|
||||
}
|
||||
|
||||
/// Inverse of an affine transform (identity when it is singular).
|
||||
pub fn invert(t: Tf) -> Tf {
|
||||
let det = t[0] * t[3] - t[1] * t[2];
|
||||
if det.abs() < 1e-12 {
|
||||
return identity();
|
||||
}
|
||||
let (a, b, c, d) = (t[3] / det, -t[1] / det, -t[2] / det, t[0] / det);
|
||||
[a, b, c, d, -(a * t[4] + c * t[5]), -(b * t[4] + d * t[5])]
|
||||
}
|
||||
|
||||
fn dpaint(p: &Paint, bx: [f32; 4]) -> DPaint {
|
||||
let [x, y, w, h] = bx;
|
||||
let stops = |s: &[Stop]| s.iter().map(|s| (s.offset.clamp(0.0, 1.0), s.color.0)).collect();
|
||||
match p {
|
||||
Paint::Solid { color } => DPaint::Solid { c: color.0 },
|
||||
Paint::Linear { x1, y1, x2, y2, stops: s } => {
|
||||
DPaint::Linear { x1: x + x1 * w, y1: y + y1 * h, x2: x + x2 * w, y2: y + y2 * h, stops: stops(s) }
|
||||
}
|
||||
Paint::Radial { cx, cy, r, stops: s } => {
|
||||
DPaint::Radial { cx: x + cx * w, cy: y + cy * h, r: (r * w.abs().max(h.abs())).max(0.01), stops: stops(s) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's own box: x, y, w, h before its transform. Text needs the layout, so it is passed in.
|
||||
pub fn local_box(o: &Object, book: &FontBook) -> [f32; 4] {
|
||||
match &o.shape {
|
||||
Shape::Rect { w, h, .. } | Shape::Ellipse { w, h } | Shape::Image { w, h, .. } => [0.0, 0.0, *w, *h],
|
||||
Shape::Line { x1, y1, x2, y2, .. } => [x1.min(*x2), y1.min(*y2), (x2 - x1).abs(), (y2 - y1).abs()],
|
||||
Shape::Path { d } => {
|
||||
let b = path::parse(d).ok().and_then(|s| path::bounds(&s)).unwrap_or([0.0; 4]);
|
||||
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
|
||||
}
|
||||
Shape::Text { w, text, style } => {
|
||||
let l = text::layout(book, text, style, *w);
|
||||
[0.0, 0.0, l.width.max(if *w > 0.0 { *w } else { 1.0 }), l.height]
|
||||
}
|
||||
Shape::Group { objects } => {
|
||||
let mut b: Option<[f32; 4]> = None;
|
||||
for c in objects {
|
||||
let lb = local_box(c, book);
|
||||
for (px, py) in
|
||||
[(lb[0], lb[1]), (lb[0] + lb[2], lb[1]), (lb[0] + lb[2], lb[1] + lb[3]), (lb[0], lb[1] + lb[3])]
|
||||
{
|
||||
let [x, y] = apply_tf(c.transform, px, py);
|
||||
b = Some(match b {
|
||||
None => [x, y, x, y],
|
||||
Some([a, c2, d, e]) => [a.min(x), c2.min(y), d.max(x), e.max(y)],
|
||||
});
|
||||
}
|
||||
}
|
||||
let b = b.unwrap_or([0.0; 4]);
|
||||
[b[0], b[1], b[2] - b[0], b[3] - b[1]]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Builder<'a> {
|
||||
book: &'a FontBook,
|
||||
doc: &'a Document,
|
||||
glyph_index: HashMap<(FontKey, u16), Option<u32>>,
|
||||
glyphs: Vec<GlyphDef>,
|
||||
items: Vec<Item>,
|
||||
assets: Vec<AssetInfo>,
|
||||
}
|
||||
|
||||
impl Builder<'_> {
|
||||
fn asset(&mut self, id: &str) -> Option<(u32, u32)> {
|
||||
let r = self.doc.assets.get(id)?;
|
||||
if !self.assets.iter().any(|a| a.id == id) {
|
||||
self.assets.push(AssetInfo { id: id.to_string(), width: r.width, height: r.height });
|
||||
}
|
||||
Some((r.width, r.height))
|
||||
}
|
||||
|
||||
fn glyph(&mut self, font: FontKey, gid: u16) -> Option<u32> {
|
||||
if let Some(g) = self.glyph_index.get(&(font, gid)) {
|
||||
return *g;
|
||||
}
|
||||
let g = self.book.outline(font, gid).filter(|d| !d.is_empty()).map(|d| {
|
||||
self.glyphs.push(GlyphDef { d, upem: self.book.font(font).units_per_em });
|
||||
(self.glyphs.len() - 1) as u32
|
||||
});
|
||||
self.glyph_index.insert((font, gid), g);
|
||||
g
|
||||
}
|
||||
|
||||
fn object(&mut self, o: &Object, parent: Tf, layer: Id, top: Option<Id>) {
|
||||
if !o.visible {
|
||||
return;
|
||||
}
|
||||
let t = mul(parent, o.transform);
|
||||
let obj = top.or(Some(o.id));
|
||||
let group = o.opacity < 0.999;
|
||||
if group {
|
||||
self.items.push(Item::Push { opacity: o.opacity.max(0.0) });
|
||||
}
|
||||
let bx = local_box(o, self.book);
|
||||
let fill = |b: &mut Self, segs: &[Seg]| {
|
||||
if let Some(p) = &o.fill {
|
||||
b.items.push(Item::Fill { d: path::write(segs), t, paint: dpaint(p, bx), even_odd: false, layer, obj });
|
||||
}
|
||||
};
|
||||
let stroke = |b: &mut Self, segs: &[Seg]| {
|
||||
if let Some(s) = &o.stroke
|
||||
&& s.width > 0.0
|
||||
{
|
||||
b.items.push(Item::Stroke {
|
||||
d: path::write(segs),
|
||||
t,
|
||||
paint: dpaint(&s.paint, bx),
|
||||
width: s.width,
|
||||
cap: s.cap,
|
||||
join: s.join,
|
||||
dash: s.dash.clone(),
|
||||
layer,
|
||||
obj,
|
||||
});
|
||||
}
|
||||
};
|
||||
match &o.shape {
|
||||
Shape::Rect { w, h, radius } => {
|
||||
let segs = path::rect(*w, *h, *radius);
|
||||
fill(self, &segs);
|
||||
stroke(self, &segs);
|
||||
}
|
||||
Shape::Ellipse { w, h } => {
|
||||
let segs = path::ellipse(*w, *h);
|
||||
fill(self, &segs);
|
||||
stroke(self, &segs);
|
||||
}
|
||||
Shape::Path { d } => {
|
||||
if let Ok(segs) = path::parse(d) {
|
||||
fill(self, &segs);
|
||||
stroke(self, &segs);
|
||||
}
|
||||
}
|
||||
Shape::Line { x1, y1, x2, y2, arrow_start, arrow_end } => {
|
||||
let w = o.stroke.as_ref().map(|s| s.width).unwrap_or(1.0);
|
||||
let (mut a, mut b) = ((*x1, *y1), (*x2, *y2));
|
||||
if *arrow_end {
|
||||
b = path::shorten(*x1, *y1, *x2, *y2, w);
|
||||
}
|
||||
if *arrow_start {
|
||||
a = path::shorten(*x2, *y2, *x1, *y1, w);
|
||||
}
|
||||
stroke(self, &[Seg::Move(a.0, a.1), Seg::Line(b.0, b.1)]);
|
||||
if let Some(s) = &o.stroke {
|
||||
for (on, (fx, fy, tx, ty)) in
|
||||
[(*arrow_end, (*x1, *y1, *x2, *y2)), (*arrow_start, (*x2, *y2, *x1, *y1))]
|
||||
{
|
||||
if on {
|
||||
let head = path::arrow_head(fx, fy, tx, ty, w);
|
||||
self.items.push(Item::Fill {
|
||||
d: path::write(&head),
|
||||
t,
|
||||
paint: dpaint(&s.paint, bx),
|
||||
even_odd: false,
|
||||
layer,
|
||||
obj,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Shape::Image { asset, w, h, crop } => {
|
||||
let frame = path::rect(*w, *h, 0.0);
|
||||
fill(self, &frame);
|
||||
if let Some((pw, ph)) = self.asset(asset) {
|
||||
let it = mul(t, mul(translate(crop.x, crop.y), scale(crop.w / pw as f32, crop.h / ph as f32)));
|
||||
self.items.push(Item::Image {
|
||||
asset: asset.clone(),
|
||||
t: it,
|
||||
clip: Some(path::write(&frame)),
|
||||
clip_t: t,
|
||||
smooth: true,
|
||||
layer,
|
||||
obj,
|
||||
});
|
||||
}
|
||||
stroke(self, &frame);
|
||||
}
|
||||
Shape::Text { w, text, style } => {
|
||||
let l = text::layout(self.book, text, style, *w);
|
||||
let mut glyphs = Vec::new();
|
||||
for line in &l.lines {
|
||||
for g in &line.glyphs {
|
||||
let def = self.glyph(g.font, g.gid);
|
||||
glyphs.push(DGlyph {
|
||||
g: def,
|
||||
x: g.x,
|
||||
y: line.baseline,
|
||||
font: g.font,
|
||||
gid: g.gid,
|
||||
advance: g.advance,
|
||||
text: g.text.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
let frame = path::rect(bx[2], bx[3], 0.0);
|
||||
fill(self, &frame);
|
||||
self.items.push(Item::Text {
|
||||
t,
|
||||
color: style.color.0,
|
||||
size: style.size,
|
||||
glyphs,
|
||||
family: style.family.clone(),
|
||||
weight: style.weight,
|
||||
italic: style.italic,
|
||||
layer,
|
||||
obj,
|
||||
});
|
||||
stroke(self, &frame);
|
||||
}
|
||||
Shape::Group { objects } => {
|
||||
for c in objects {
|
||||
self.object(c, t, layer, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
if group {
|
||||
self.items.push(Item::Pop);
|
||||
}
|
||||
}
|
||||
|
||||
fn layers(&mut self, ls: &[Layer], objects: &mut Vec<ObjectInfo>) {
|
||||
for l in ls {
|
||||
if !l.visible {
|
||||
continue;
|
||||
}
|
||||
let group = l.opacity < 0.999;
|
||||
if group {
|
||||
self.items.push(Item::Push { opacity: l.opacity.max(0.0) });
|
||||
}
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects: os } => {
|
||||
for o in os {
|
||||
self.object(o, identity(), l.id, None);
|
||||
if o.visible {
|
||||
objects.push(info(o, l.id, l.locked, self.book));
|
||||
}
|
||||
}
|
||||
}
|
||||
LayerKind::Bitmap { asset, x, y, w, h } => {
|
||||
if let Some((pw, ph)) = self.asset(asset) {
|
||||
let t = mul(translate(*x, *y), scale(w / pw as f32, h / ph as f32));
|
||||
let exact = (w - pw as f32).abs() < 1e-3 && (h - ph as f32).abs() < 1e-3;
|
||||
self.items.push(Item::Image {
|
||||
asset: asset.clone(),
|
||||
t,
|
||||
clip: None,
|
||||
clip_t: identity(),
|
||||
smooth: !exact,
|
||||
layer: l.id,
|
||||
obj: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
LayerKind::Group { layers } => self.layers(layers, objects),
|
||||
}
|
||||
if group {
|
||||
self.items.push(Item::Pop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn info(o: &Object, layer: Id, layer_locked: bool, book: &FontBook) -> ObjectInfo {
|
||||
let b = local_box(o, book);
|
||||
let pts = [[b[0], b[1]], [b[0] + b[2], b[1]], [b[0] + b[2], b[1] + b[3]], [b[0], b[1] + b[3]]];
|
||||
let corners = pts.map(|[x, y]| apply_tf(o.transform, x, y));
|
||||
let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
|
||||
for [x, y] in corners {
|
||||
bounds = [bounds[0].min(x), bounds[1].min(y), bounds[2].max(x), bounds[3].max(y)];
|
||||
}
|
||||
let kind = match o.shape {
|
||||
Shape::Rect { .. } => "rect",
|
||||
Shape::Ellipse { .. } => "ellipse",
|
||||
Shape::Line { .. } => "line",
|
||||
Shape::Path { .. } => "path",
|
||||
Shape::Text { .. } => "text",
|
||||
Shape::Image { .. } => "image",
|
||||
Shape::Group { .. } => "group",
|
||||
};
|
||||
ObjectInfo {
|
||||
id: o.id,
|
||||
layer,
|
||||
kind,
|
||||
local: b,
|
||||
transform: o.transform,
|
||||
corners,
|
||||
bounds,
|
||||
locked: o.locked || layer_locked,
|
||||
}
|
||||
}
|
||||
|
||||
/// The display list of one page.
|
||||
pub fn build(doc: &Document, page: &Page, book: &FontBook) -> DisplayList {
|
||||
let mut b =
|
||||
Builder { book, doc, glyph_index: HashMap::new(), glyphs: Vec::new(), items: Vec::new(), assets: Vec::new() };
|
||||
let mut objects = Vec::new();
|
||||
b.layers(&page.layers, &mut objects);
|
||||
DisplayList {
|
||||
width: page.width,
|
||||
height: page.height,
|
||||
background: page.background.map(|c| c.0),
|
||||
glyphs: b.glyphs,
|
||||
items: b.items,
|
||||
objects,
|
||||
assets: b.assets,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,934 @@
|
||||
//! Exports: PNG at a scale, JPG on white, SVG (vector layers as SVG, pixels embedded as PNG) and PDF with pdf-writer
|
||||
//! (vectors stay vectors, text is real text in subset fonts with a ToUnicode map, each page at its exact size).
|
||||
//! All of them walk the display list (`display::build`), the same one the screen is painted from.
|
||||
use crate::display::{self, DGlyph, DPaint, DisplayList, Item, Tf};
|
||||
use crate::model::*;
|
||||
use crate::path;
|
||||
use crate::text::{Embedding, FontBook, FontKey};
|
||||
use pdf_writer::{Content, Filter, Finish, Name, Pdf, Rect as PRect, Ref, Str};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExportError {
|
||||
#[error("The font \u{201c}{family}\u{201d} cannot be put in a PDF: {reason}. Choose another font for that text.")]
|
||||
FontNotEmbeddable { family: String, reason: &'static str },
|
||||
#[error("The font \u{201c}{0}\u{201d} could not be prepared for the PDF.")]
|
||||
FontBroken(String),
|
||||
#[error("The picture is too large to export at this scale.")]
|
||||
TooLarge,
|
||||
#[error("Could not encode the picture: {0}")]
|
||||
Encode(String),
|
||||
}
|
||||
|
||||
/// A page as PNG at `scale` pixels per point.
|
||||
pub fn png(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Vec<u8>, ExportError> {
|
||||
let r = raster(doc, page, book, scale)?;
|
||||
crate::format::encode_png(&r).map_err(|e| ExportError::Encode(e.to_string()))
|
||||
}
|
||||
|
||||
/// A page as JPG (quality 0–100) at `scale`, on white where the page is transparent.
|
||||
pub fn jpg(doc: &Document, page: &Page, book: &FontBook, scale: f32, quality: u8) -> Result<Vec<u8>, ExportError> {
|
||||
use image::ImageEncoder;
|
||||
let r = raster(doc, page, book, scale)?;
|
||||
let mut rgb = Vec::with_capacity(r.rgba.len() / 4 * 3);
|
||||
for p in r.rgba.as_chunks::<4>().0 {
|
||||
let a = p[3] as u32;
|
||||
for c in &p[..3] {
|
||||
rgb.push(((*c as u32 * a + 255 * (255 - a) + 127) / 255) as u8);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100))
|
||||
.write_image(&rgb, r.width, r.height, image::ExtendedColorType::Rgb8)
|
||||
.map_err(|e| ExportError::Encode(e.to_string()))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn raster(doc: &Document, page: &Page, book: &FontBook, scale: f32) -> Result<Raster, ExportError> {
|
||||
let px = (page.width * scale) as u64 * (page.height * scale) as u64;
|
||||
if scale.is_nan() || scale <= 0.0 || px > 200_000_000 {
|
||||
return Err(ExportError::TooLarge);
|
||||
}
|
||||
crate::render::page(doc, page, book, scale).ok_or(ExportError::TooLarge)
|
||||
}
|
||||
|
||||
// ---- SVG ----------------------------------------------------------------------------------------------------------
|
||||
|
||||
fn hex(c: [u8; 4]) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
|
||||
}
|
||||
|
||||
fn mat(t: Tf) -> String {
|
||||
format!("matrix({} {} {} {} {} {})", t[0], t[1], t[2], t[3], t[4], t[5])
|
||||
}
|
||||
|
||||
/// A page as SVG. Text is written as `<text>` with each character's x, so it stays text.
|
||||
pub fn svg(doc: &Document, page: &Page, book: &FontBook) -> String {
|
||||
use base64::Engine as _;
|
||||
let list = display::build(doc, page, book);
|
||||
let mut defs = String::new();
|
||||
let mut body = String::new();
|
||||
let mut n = 0;
|
||||
let mut paint = |p: &DPaint, defs: &mut String| -> (String, Option<f32>) {
|
||||
match p {
|
||||
DPaint::Solid { c } => (hex(*c), (c[3] < 255).then_some(c[3] as f32 / 255.0)),
|
||||
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||
n += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<linearGradient id="g{n}" gradientUnits="userSpaceOnUse" x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}">"#
|
||||
);
|
||||
for (o, c) in stops {
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||
hex(*c),
|
||||
c[3] as f32 / 255.0
|
||||
);
|
||||
}
|
||||
defs.push_str("</linearGradient>");
|
||||
(format!("url(#g{n})"), None)
|
||||
}
|
||||
DPaint::Radial { cx, cy, r, stops } => {
|
||||
n += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<radialGradient id="g{n}" gradientUnits="userSpaceOnUse" cx="{cx}" cy="{cy}" r="{r}">"#
|
||||
);
|
||||
for (o, c) in stops {
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<stop offset="{o}" stop-color="{}" stop-opacity="{}"/>"#,
|
||||
hex(*c),
|
||||
c[3] as f32 / 255.0
|
||||
);
|
||||
}
|
||||
defs.push_str("</radialGradient>");
|
||||
(format!("url(#g{n})"), None)
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut clips = 0;
|
||||
let mut pngs: HashMap<&str, String> = HashMap::new();
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => {
|
||||
let _ = write!(body, r#"<g opacity="{opacity}">"#);
|
||||
}
|
||||
Item::Pop => body.push_str("</g>"),
|
||||
Item::Fill { d, t, paint: p, even_odd, .. } => {
|
||||
let (f, a) = paint(p, &mut defs);
|
||||
let _ = write!(body, r#"<path d="{d}" transform="{}" fill="{f}""#, mat(*t));
|
||||
if let Some(a) = a {
|
||||
let _ = write!(body, r#" fill-opacity="{a}""#);
|
||||
}
|
||||
if *even_odd {
|
||||
body.push_str(r#" fill-rule="evenodd""#);
|
||||
}
|
||||
body.push_str("/>");
|
||||
}
|
||||
Item::Stroke { d, t, paint: p, width, cap, join, dash, .. } => {
|
||||
let (s, a) = paint(p, &mut defs);
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<path d="{d}" transform="{}" fill="none" stroke="{s}" stroke-width="{width}""#,
|
||||
mat(*t)
|
||||
);
|
||||
if let Some(a) = a {
|
||||
let _ = write!(body, r#" stroke-opacity="{a}""#);
|
||||
}
|
||||
let cap = match cap {
|
||||
Cap::Butt => "butt",
|
||||
Cap::Round => "round",
|
||||
Cap::Square => "square",
|
||||
};
|
||||
let join = match join {
|
||||
Join::Miter => "miter",
|
||||
Join::Round => "round",
|
||||
Join::Bevel => "bevel",
|
||||
};
|
||||
let _ = write!(body, r#" stroke-linecap="{cap}" stroke-linejoin="{join}""#);
|
||||
if !dash.is_empty() {
|
||||
let d: Vec<String> = dash.iter().map(|v| v.to_string()).collect();
|
||||
let _ = write!(body, r#" stroke-dasharray="{}""#, d.join(" "));
|
||||
}
|
||||
body.push_str("/>");
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||
let Some(r) = doc.assets.get(asset) else { continue };
|
||||
let href = pngs.entry(asset.as_str()).or_insert_with(|| {
|
||||
let png = crate::format::encode_png(r).unwrap_or_default();
|
||||
format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(png))
|
||||
});
|
||||
if let Some(cd) = clip {
|
||||
clips += 1;
|
||||
let _ = write!(
|
||||
defs,
|
||||
r#"<clipPath id="c{clips}"><path d="{cd}" transform="{}"/></clipPath>"#,
|
||||
mat(*clip_t)
|
||||
);
|
||||
let _ = write!(body, r#"<g clip-path="url(#c{clips})">"#);
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<image href="{href}" width="{}" height="{}" transform="{}" preserveAspectRatio="none"/>"#,
|
||||
r.width,
|
||||
r.height,
|
||||
mat(*t)
|
||||
);
|
||||
if clip.is_some() {
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
Item::Text { t, color, size, glyphs, family, weight, italic, .. } => {
|
||||
// One <text> per line (glyphs that share a baseline), every character placed at its glyph's x.
|
||||
let mut lines: BTreeMap<i64, Vec<&DGlyph>> = BTreeMap::new();
|
||||
for g in glyphs {
|
||||
lines.entry((g.y * 100.0) as i64).or_default().push(g);
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<g transform="{}" font-family="{}" font-size="{size}" font-weight="{weight}"{} fill="{}"{}>"#,
|
||||
mat(*t),
|
||||
esc(family),
|
||||
if *italic { r#" font-style="italic""# } else { "" },
|
||||
hex(*color),
|
||||
if color[3] < 255 {
|
||||
format!(r#" fill-opacity="{}""#, color[3] as f32 / 255.0)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
for gs in lines.values() {
|
||||
let mut xs = Vec::new();
|
||||
let mut s = String::new();
|
||||
for g in gs {
|
||||
for (i, ch) in g.text.chars().enumerate() {
|
||||
xs.push(format!(
|
||||
"{}",
|
||||
g.x + if i == 0 { 0.0 } else { g.advance * i as f32 / g.text.chars().count() as f32 }
|
||||
));
|
||||
s.push(ch);
|
||||
}
|
||||
}
|
||||
if s.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(
|
||||
body,
|
||||
r#"<text xml:space="preserve" x="{}" y="{}">{}</text>"#,
|
||||
xs.join(" "),
|
||||
gs[0].y,
|
||||
esc(&s)
|
||||
);
|
||||
}
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}pt" height="{h}pt" viewBox="0 0 {w} {h}">"#,
|
||||
w = list.width,
|
||||
h = list.height
|
||||
);
|
||||
if !defs.is_empty() {
|
||||
let _ = write!(out, "<defs>{defs}</defs>");
|
||||
}
|
||||
if let Some(bg) = list.background {
|
||||
let _ = write!(out, r#"<rect width="{}" height="{}" fill="{}"/>"#, list.width, list.height, hex(bg));
|
||||
}
|
||||
out.push_str(&body);
|
||||
out.push_str("</svg>");
|
||||
out
|
||||
}
|
||||
|
||||
// ---- PDF ----------------------------------------------------------------------------------------------------------
|
||||
|
||||
fn deflate(data: &[u8]) -> Vec<u8> {
|
||||
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6));
|
||||
let _ = e.write_all(data);
|
||||
e.finish().unwrap_or_default()
|
||||
}
|
||||
|
||||
struct FontUse {
|
||||
name: String,
|
||||
/// Subset fonts are addressed by the subset's glyph ids (CID = new gid); others by their own ids.
|
||||
subset: bool,
|
||||
remapper: subsetter::GlyphRemapper,
|
||||
/// CID → (original glyph id, the text it stands for).
|
||||
glyphs: BTreeMap<u16, (u16, String)>,
|
||||
}
|
||||
|
||||
/// The fonts a set of display lists uses, and whether each may be embedded.
|
||||
pub fn check_fonts(lists: &[DisplayList], book: &FontBook) -> Result<(), ExportError> {
|
||||
for l in lists {
|
||||
for it in &l.items {
|
||||
if let Item::Text { glyphs, .. } = it {
|
||||
for g in glyphs {
|
||||
let f = book.font(g.font);
|
||||
if let Embedding::Forbidden(reason) = f.embedding {
|
||||
return Err(ExportError::FontNotEmbeddable { family: f.family.clone(), reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Writer<'a> {
|
||||
pdf: Pdf,
|
||||
next: i32,
|
||||
book: &'a FontBook,
|
||||
fonts: BTreeMap<FontKey, (Ref, FontUse)>,
|
||||
images: BTreeMap<String, (Ref, String)>,
|
||||
alphas: BTreeMap<(u8, u8), (Ref, String)>,
|
||||
patterns: Vec<(Ref, String, DPaint, Tf)>,
|
||||
forms: Vec<(Ref, String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
fn alloc(&mut self) -> Ref {
|
||||
self.next += 1;
|
||||
Ref::new(self.next)
|
||||
}
|
||||
|
||||
fn alpha(&mut self, fill: u8, stroke: u8) -> String {
|
||||
if let Some((_, n)) = self.alphas.get(&(fill, stroke)) {
|
||||
return n.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("A{}", self.alphas.len());
|
||||
self.alphas.insert((fill, stroke), (r, n.clone()));
|
||||
n
|
||||
}
|
||||
|
||||
fn pattern(&mut self, p: &DPaint, full: Tf) -> String {
|
||||
let r = self.alloc();
|
||||
let n = format!("P{}", self.patterns.len());
|
||||
self.patterns.push((r, n.clone(), p.clone(), full));
|
||||
n
|
||||
}
|
||||
|
||||
fn image(&mut self, asset: &str) -> String {
|
||||
if let Some((_, n)) = self.images.get(asset) {
|
||||
return n.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("Im{}", self.images.len());
|
||||
self.images.insert(asset.to_string(), (r, n.clone()));
|
||||
n
|
||||
}
|
||||
|
||||
fn font(&mut self, key: FontKey) -> String {
|
||||
if let Some((_, u)) = self.fonts.get(&key) {
|
||||
return u.name.clone();
|
||||
}
|
||||
let r = self.alloc();
|
||||
let n = format!("F{}", self.fonts.len());
|
||||
let f = self.book.font(key);
|
||||
let subset = ttf_parser::Face::parse(&f.data, f.index).map(|fc| fc.is_subsetting_allowed()).unwrap_or(false);
|
||||
let u = FontUse { name: n.clone(), subset, remapper: subsetter::GlyphRemapper::new(), glyphs: BTreeMap::new() };
|
||||
self.fonts.insert(key, (r, u));
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a page or form refers to, copied out of the writer so the PDF can be written while they are used.
|
||||
#[derive(Default)]
|
||||
struct ResTable {
|
||||
fonts: Vec<(String, Ref)>,
|
||||
xobjects: Vec<(String, Ref)>,
|
||||
states: Vec<(String, Ref)>,
|
||||
patterns: Vec<(String, Ref)>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
fn table(&self) -> ResTable {
|
||||
ResTable {
|
||||
fonts: self.fonts.values().map(|(r, u)| (u.name.clone(), *r)).collect(),
|
||||
xobjects: self
|
||||
.images
|
||||
.values()
|
||||
.map(|(r, n)| (n.clone(), *r))
|
||||
.chain(self.forms.iter().map(|(r, n, _)| (n.clone(), *r)))
|
||||
.collect(),
|
||||
states: self.alphas.values().map(|(r, n)| (n.clone(), *r)).collect(),
|
||||
patterns: self.patterns.iter().map(|(r, n, _, _)| (n.clone(), *r)).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_resources(t: &ResTable, res: &mut pdf_writer::writers::Resources) {
|
||||
let mut f = res.fonts();
|
||||
for (n, r) in &t.fonts {
|
||||
f.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
f.finish();
|
||||
let mut x = res.x_objects();
|
||||
for (n, r) in &t.xobjects {
|
||||
x.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
x.finish();
|
||||
let mut g = res.ext_g_states();
|
||||
for (n, r) in &t.states {
|
||||
g.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
g.finish();
|
||||
let mut p = res.patterns();
|
||||
for (n, r) in &t.patterns {
|
||||
p.pair(Name(n.as_bytes()), *r);
|
||||
}
|
||||
p.finish();
|
||||
}
|
||||
|
||||
fn path_ops(c: &mut Content, d: &str) {
|
||||
let Ok(segs) = path::parse(d) else { return };
|
||||
let (mut cx, mut cy) = (0.0f32, 0.0f32);
|
||||
for s in segs {
|
||||
match s {
|
||||
path::Seg::Move(x, y) => {
|
||||
c.move_to(x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Line(x, y) => {
|
||||
c.line_to(x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Quad(a, b, x, y) => {
|
||||
// Quadratic → cubic.
|
||||
let (c1x, c1y) = (cx + 2.0 / 3.0 * (a - cx), cy + 2.0 / 3.0 * (b - cy));
|
||||
let (c2x, c2y) = (x + 2.0 / 3.0 * (a - x), y + 2.0 / 3.0 * (b - y));
|
||||
c.cubic_to(c1x, c1y, c2x, c2y, x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Cubic(a, b, e, f, x, y) => {
|
||||
c.cubic_to(a, b, e, f, x, y);
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
path::Seg::Close => {
|
||||
c.close_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(c: [u8; 4]) -> (f32, f32, f32) {
|
||||
(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// The alpha a paint is drawn with (a gradient's stops share one: the average of theirs).
|
||||
fn paint_alpha(p: &DPaint) -> u8 {
|
||||
match p {
|
||||
DPaint::Solid { c } => c[3],
|
||||
DPaint::Linear { stops, .. } | DPaint::Radial { stops, .. } => {
|
||||
if stops.is_empty() {
|
||||
255
|
||||
} else {
|
||||
(stops.iter().map(|(_, c)| c[3] as u32).sum::<u32>() / stops.len() as u32) as u8
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_paint(w: &mut Writer, c: &mut Content, p: &DPaint, full: Tf, stroke: bool) {
|
||||
match p {
|
||||
DPaint::Solid { c: col } => {
|
||||
let (r, g, b) = rgb(*col);
|
||||
if stroke {
|
||||
c.set_stroke_rgb(r, g, b);
|
||||
} else {
|
||||
c.set_fill_rgb(r, g, b);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let n = w.pattern(p, full);
|
||||
if stroke {
|
||||
c.set_stroke_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||
c.set_stroke_pattern(None, Name(n.as_bytes()));
|
||||
} else {
|
||||
c.set_fill_color_space(pdf_writer::types::ColorSpaceOperand::Pattern);
|
||||
c.set_fill_pattern(None, Name(n.as_bytes()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The document as PDF: every page at its size, vectors as vectors, real text, pictures with their alpha.
|
||||
pub fn pdf(doc: &Document, book: &FontBook) -> Result<Vec<u8>, ExportError> {
|
||||
let lists: Vec<DisplayList> = doc.pages.iter().map(|p| display::build(doc, p, book)).collect();
|
||||
check_fonts(&lists, book)?;
|
||||
let mut w = Writer {
|
||||
pdf: Pdf::new(),
|
||||
next: 0,
|
||||
book,
|
||||
fonts: BTreeMap::new(),
|
||||
images: BTreeMap::new(),
|
||||
alphas: BTreeMap::new(),
|
||||
patterns: Vec::new(),
|
||||
forms: Vec::new(),
|
||||
};
|
||||
let catalog = w.alloc();
|
||||
let pages_id = w.alloc();
|
||||
let mut page_refs = Vec::new();
|
||||
let mut contents = Vec::new();
|
||||
for list in &lists {
|
||||
let flip: Tf = [1.0, 0.0, 0.0, -1.0, 0.0, list.height];
|
||||
let mut stack: Vec<(Content, f32)> = vec![(Content::new(), 1.0)];
|
||||
{
|
||||
let c = &mut stack[0].0;
|
||||
c.transform(flip);
|
||||
if let Some(bg) = list.background {
|
||||
let (r, g, b) = rgb(bg);
|
||||
c.set_fill_rgb(r, g, b);
|
||||
c.rect(0.0, 0.0, list.width, list.height);
|
||||
c.fill_nonzero();
|
||||
}
|
||||
}
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => stack.push((Content::new(), *opacity)),
|
||||
Item::Pop => {
|
||||
if stack.len() > 1 {
|
||||
let (inner, opacity) = stack.pop().unwrap();
|
||||
let r = w.alloc();
|
||||
let n = format!("X{}", w.forms.len());
|
||||
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
}
|
||||
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||
let full = display::mul(flip, *t);
|
||||
let alpha = paint_alpha(paint);
|
||||
let a = (alpha < 255).then(|| w.alpha(alpha, 255));
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if let Some(a) = &a {
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
set_paint(&mut w, &mut c, paint, full, false);
|
||||
path_ops(&mut c, d);
|
||||
if *even_odd {
|
||||
c.fill_even_odd();
|
||||
} else {
|
||||
c.fill_nonzero();
|
||||
}
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||
let full = display::mul(flip, *t);
|
||||
let alpha = paint_alpha(paint);
|
||||
let a = (alpha < 255).then(|| w.alpha(255, alpha));
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if let Some(a) = &a {
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
set_paint(&mut w, &mut c, paint, full, true);
|
||||
c.set_line_width(*width);
|
||||
c.set_line_cap(match cap {
|
||||
Cap::Butt => pdf_writer::types::LineCapStyle::ButtCap,
|
||||
Cap::Round => pdf_writer::types::LineCapStyle::RoundCap,
|
||||
Cap::Square => pdf_writer::types::LineCapStyle::ProjectingSquareCap,
|
||||
});
|
||||
c.set_line_join(match join {
|
||||
Join::Miter => pdf_writer::types::LineJoinStyle::MiterJoin,
|
||||
Join::Round => pdf_writer::types::LineJoinStyle::RoundJoin,
|
||||
Join::Bevel => pdf_writer::types::LineJoinStyle::BevelJoin,
|
||||
});
|
||||
c.set_miter_limit(10.0);
|
||||
if dash.len() >= 2 && dash.iter().any(|v| *v > 0.0) {
|
||||
c.set_dash_pattern(dash.iter().copied(), 0.0);
|
||||
}
|
||||
path_ops(&mut c, d);
|
||||
c.stroke();
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, .. } => {
|
||||
let Some(r) = doc.assets.get(asset) else { continue };
|
||||
let (pw, ph) = (r.width as f32, r.height as f32);
|
||||
let n = w.image(asset);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
let rel = match clip {
|
||||
Some(cd) => {
|
||||
c.transform(*clip_t);
|
||||
path_ops(c, cd);
|
||||
c.clip_nonzero();
|
||||
c.end_path();
|
||||
display::mul(display::invert(*clip_t), *t)
|
||||
}
|
||||
None => *t,
|
||||
};
|
||||
c.transform(rel);
|
||||
// The image's unit square, its first row at the top (the page runs y down here).
|
||||
c.transform([pw, 0.0, 0.0, -ph, 0.0, ph]);
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
Item::Text { t, color, size, glyphs, .. } => {
|
||||
let mut c = std::mem::replace(&mut stack.last_mut().unwrap().0, Content::new());
|
||||
c.save_state();
|
||||
if color[3] < 255 {
|
||||
let a = w.alpha(color[3], 255);
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
}
|
||||
c.transform(*t);
|
||||
let (r, g, b) = rgb(*color);
|
||||
c.set_fill_rgb(r, g, b);
|
||||
c.begin_text();
|
||||
// Runs of glyphs that share a line and a font.
|
||||
let mut i = 0;
|
||||
while i < glyphs.len() {
|
||||
let font = glyphs[i].font;
|
||||
let y = glyphs[i].y;
|
||||
let mut j = i + 1;
|
||||
while j < glyphs.len() && glyphs[j].font == font && glyphs[j].y == y {
|
||||
j += 1;
|
||||
}
|
||||
let run = &glyphs[i..j];
|
||||
let fname = w.font(font);
|
||||
let f = book.font(font);
|
||||
let face = ttf_parser::Face::parse(&f.data, f.index).ok();
|
||||
let width_of = |gid: u16| -> f32 {
|
||||
face.as_ref()
|
||||
.and_then(|fc| fc.glyph_hor_advance(ttf_parser::GlyphId(gid)))
|
||||
.map(|a| a as f32 * 1000.0 / f.units_per_em)
|
||||
.unwrap_or(0.0)
|
||||
};
|
||||
let cids: Vec<u16> = {
|
||||
let u = &mut w.fonts.get_mut(&font).unwrap().1;
|
||||
run.iter()
|
||||
.map(|g| {
|
||||
let cid = if u.subset { u.remapper.remap(g.gid) } else { g.gid };
|
||||
let e = u.glyphs.entry(cid).or_insert_with(|| (g.gid, String::new()));
|
||||
if e.1.is_empty() {
|
||||
e.1.push_str(&g.text);
|
||||
}
|
||||
cid
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
c.set_font(Name(fname.as_bytes()), *size);
|
||||
c.set_text_matrix([1.0, 0.0, 0.0, -1.0, run[0].x, y]);
|
||||
let mut items_buf: Vec<(Vec<u8>, f32)> = Vec::new();
|
||||
let mut x = run[0].x;
|
||||
for (k, g) in run.iter().enumerate() {
|
||||
// Where the PDF would put the next glyph vs where the layout put it.
|
||||
let adv = width_of(g.gid) * size / 1000.0;
|
||||
let next_x = run.get(k + 1).map(|n| n.x).unwrap_or(x + adv);
|
||||
let adjust = (next_x - (x + adv)) * 1000.0 / size;
|
||||
items_buf.push((cids[k].to_be_bytes().to_vec(), adjust));
|
||||
x = next_x;
|
||||
}
|
||||
{
|
||||
let mut sp = c.show_positioned();
|
||||
let mut its = sp.items();
|
||||
for (bytes, adjust) in &items_buf {
|
||||
its.show(Str(bytes));
|
||||
if adjust.abs() > 0.01 {
|
||||
its.adjust(-adjust);
|
||||
}
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
c.end_text();
|
||||
c.restore_state();
|
||||
stack.last_mut().unwrap().0 = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
while stack.len() > 1 {
|
||||
let (inner, opacity) = stack.pop().unwrap();
|
||||
let r = w.alloc();
|
||||
let n = format!("X{}", w.forms.len());
|
||||
w.forms.push((r, n.clone(), inner.finish().to_vec()));
|
||||
let a = w.alpha((opacity * 255.0).round() as u8, (opacity * 255.0).round() as u8);
|
||||
let c = &mut stack.last_mut().unwrap().0;
|
||||
c.save_state();
|
||||
c.set_parameters(Name(a.as_bytes()));
|
||||
c.x_object(Name(n.as_bytes()));
|
||||
c.restore_state();
|
||||
}
|
||||
let page_ref = w.alloc();
|
||||
let content_ref = w.alloc();
|
||||
page_refs.push(page_ref);
|
||||
contents.push((page_ref, content_ref, stack.pop().unwrap().0.finish().to_vec(), list.width, list.height));
|
||||
}
|
||||
|
||||
type FontJob = (FontKey, Ref, bool, subsetter::GlyphRemapper, BTreeMap<u16, (u16, String)>);
|
||||
let font_list: Vec<FontJob> =
|
||||
w.fonts.iter().map(|(k, (r, u))| (*k, *r, u.subset, u.remapper.clone(), u.glyphs.clone())).collect();
|
||||
for (key, type0, subset, remapper, glyphs) in font_list {
|
||||
write_font(&mut w, key, type0, subset, &remapper, &glyphs)?;
|
||||
}
|
||||
|
||||
let images: Vec<(String, Ref)> = w.images.iter().map(|(a, (r, _))| (a.clone(), *r)).collect();
|
||||
for (asset, r) in images {
|
||||
let raster = &doc.assets[&asset];
|
||||
let mut rgb_data = Vec::with_capacity(raster.rgba.len() / 4 * 3);
|
||||
let mut alpha = Vec::with_capacity(raster.rgba.len() / 4);
|
||||
for p in raster.rgba.as_chunks::<4>().0 {
|
||||
rgb_data.extend_from_slice(&p[..3]);
|
||||
alpha.push(p[3]);
|
||||
}
|
||||
let has_alpha = alpha.iter().any(|a| *a < 255);
|
||||
let mask_ref = has_alpha.then(|| w.alloc());
|
||||
let data = deflate(&rgb_data);
|
||||
let mut im = w.pdf.image_xobject(r, &data);
|
||||
im.filter(Filter::FlateDecode);
|
||||
im.width(raster.width as i32);
|
||||
im.height(raster.height as i32);
|
||||
im.color_space().device_rgb();
|
||||
im.bits_per_component(8);
|
||||
if let Some(m) = mask_ref {
|
||||
im.s_mask(m);
|
||||
}
|
||||
im.finish();
|
||||
if let Some(m) = mask_ref {
|
||||
let data = deflate(&alpha);
|
||||
let mut sm = w.pdf.image_xobject(m, &data);
|
||||
sm.filter(Filter::FlateDecode);
|
||||
sm.width(raster.width as i32);
|
||||
sm.height(raster.height as i32);
|
||||
sm.color_space().device_gray();
|
||||
sm.bits_per_component(8);
|
||||
sm.finish();
|
||||
}
|
||||
}
|
||||
|
||||
let alphas: Vec<((u8, u8), Ref)> = w.alphas.iter().map(|(k, (r, _))| (*k, *r)).collect();
|
||||
for ((fa, sa), r) in alphas {
|
||||
w.pdf.ext_graphics(r).non_stroking_alpha(fa as f32 / 255.0).stroking_alpha(sa as f32 / 255.0);
|
||||
}
|
||||
|
||||
let patterns = std::mem::take(&mut w.patterns);
|
||||
for (r, _, p, full) in &patterns {
|
||||
let shading = w.alloc();
|
||||
let func = w.alloc();
|
||||
let (stops, kind, coords): (&Vec<(f32, [u8; 4])>, _, Vec<f32>) = match p {
|
||||
DPaint::Linear { x1, y1, x2, y2, stops } => {
|
||||
(stops, pdf_writer::types::FunctionShadingType::Axial, vec![*x1, *y1, *x2, *y2])
|
||||
}
|
||||
DPaint::Radial { cx, cy, r, stops } => {
|
||||
(stops, pdf_writer::types::FunctionShadingType::Radial, vec![*cx, *cy, 0.0, *cx, *cy, *r])
|
||||
}
|
||||
DPaint::Solid { .. } => continue,
|
||||
};
|
||||
write_stops(&mut w, func, stops);
|
||||
{
|
||||
let mut sh = w.pdf.function_shading(shading);
|
||||
sh.shading_type(kind);
|
||||
sh.color_space().device_rgb();
|
||||
sh.coords(coords);
|
||||
sh.function(func);
|
||||
sh.extend([true, true]);
|
||||
}
|
||||
let mut pat = w.pdf.shading_pattern(*r);
|
||||
pat.pair(Name(b"Shading"), shading);
|
||||
pat.matrix(*full);
|
||||
}
|
||||
w.patterns = patterns;
|
||||
|
||||
let table = w.table();
|
||||
let forms = std::mem::take(&mut w.forms);
|
||||
let (pw, ph) = lists.first().map(|l| (l.width, l.height)).unwrap_or((1.0, 1.0));
|
||||
for (r, _, content) in &forms {
|
||||
let data = deflate(content);
|
||||
let mut f = w.pdf.form_xobject(*r, &data);
|
||||
f.filter(Filter::FlateDecode);
|
||||
let maxw = lists.iter().map(|l| l.width).fold(pw, f32::max);
|
||||
let maxh = lists.iter().map(|l| l.height).fold(ph, f32::max);
|
||||
f.bbox(PRect::new(-1.0, -1.0, maxw + 1.0, maxh + 1.0));
|
||||
f.group().transparency().isolated(true);
|
||||
let mut res = f.resources();
|
||||
write_resources(&table, &mut res);
|
||||
res.finish();
|
||||
f.finish();
|
||||
}
|
||||
w.forms = forms;
|
||||
|
||||
for (page_ref, content_ref, content, width, height) in &contents {
|
||||
let data = deflate(content);
|
||||
w.pdf.stream(*content_ref, &data).filter(Filter::FlateDecode);
|
||||
let mut page = w.pdf.page(*page_ref);
|
||||
page.media_box(PRect::new(0.0, 0.0, *width, *height));
|
||||
page.parent(pages_id);
|
||||
page.contents(*content_ref);
|
||||
let mut res = page.resources();
|
||||
write_resources(&table, &mut res);
|
||||
res.finish();
|
||||
page.finish();
|
||||
}
|
||||
w.pdf.pages(pages_id).kids(page_refs.iter().copied()).count(page_refs.len() as i32);
|
||||
w.pdf.catalog(catalog).pages(pages_id);
|
||||
let info = w.alloc();
|
||||
w.pdf.document_info(info).producer(pdf_writer::TextStr("Pictor"));
|
||||
Ok(w.pdf.finish())
|
||||
}
|
||||
|
||||
fn write_stops(w: &mut Writer, func: Ref, stops: &[(f32, [u8; 4])]) {
|
||||
let col = |c: [u8; 4]| {
|
||||
let (r, g, b) = rgb(c);
|
||||
[r, g, b]
|
||||
};
|
||||
let mut stops: Vec<(f32, [u8; 4])> = stops.to_vec();
|
||||
if stops.is_empty() {
|
||||
stops.push((0.0, [0, 0, 0, 255]));
|
||||
}
|
||||
if stops.len() == 1 {
|
||||
stops.push(stops[0]);
|
||||
}
|
||||
if stops.len() == 2 {
|
||||
w.pdf.exponential_function(func).domain([0.0, 1.0]).c0(col(stops[0].1)).c1(col(stops[1].1)).n(1.0);
|
||||
return;
|
||||
}
|
||||
// Stitch one exponential function per pair of stops.
|
||||
let mut parts = Vec::new();
|
||||
for pair in stops.windows(2) {
|
||||
let r = w.alloc();
|
||||
w.pdf.exponential_function(r).domain([0.0, 1.0]).c0(col(pair[0].1)).c1(col(pair[1].1)).n(1.0);
|
||||
parts.push(r);
|
||||
}
|
||||
let bounds: Vec<f32> = stops[1..stops.len() - 1].iter().map(|s| s.0).collect();
|
||||
let encode: Vec<f32> = parts.iter().flat_map(|_| [0.0, 1.0]).collect();
|
||||
let mut s = w.pdf.stitching_function(func);
|
||||
s.domain([0.0, 1.0]);
|
||||
s.functions(parts);
|
||||
s.bounds(bounds);
|
||||
s.encode(encode);
|
||||
}
|
||||
|
||||
/// Writes a Type 0 font: the font program (a subset when its licence allows), its descriptor, widths and the
|
||||
/// ToUnicode map. CIDs are the subset's glyph ids (or the font's own when it is embedded whole), so CIDToGIDMap is
|
||||
/// the identity.
|
||||
fn write_font(
|
||||
w: &mut Writer,
|
||||
key: FontKey,
|
||||
type0: Ref,
|
||||
subset: bool,
|
||||
remapper: &subsetter::GlyphRemapper,
|
||||
glyphs: &BTreeMap<u16, (u16, String)>,
|
||||
) -> Result<(), ExportError> {
|
||||
let f = w.book.font(key);
|
||||
let face = ttf_parser::Face::parse(&f.data, f.index).map_err(|_| ExportError::FontBroken(f.family.clone()))?;
|
||||
let program: Vec<u8> = if subset {
|
||||
subsetter::subset(&f.data, f.index, remapper).map_err(|_| ExportError::FontBroken(f.family.clone()))?
|
||||
} else {
|
||||
f.data.to_vec()
|
||||
};
|
||||
let cid_ref = w.alloc();
|
||||
let desc_ref = w.alloc();
|
||||
let file_ref = w.alloc();
|
||||
let cmap_ref = w.alloc();
|
||||
// A subset tag from the glyph set, so two subsets of one font get different names.
|
||||
let tag: String = {
|
||||
use sha2::Digest;
|
||||
let mut h = sha2::Sha256::new();
|
||||
for (cid, (gid, _)) in glyphs {
|
||||
h.update(cid.to_be_bytes());
|
||||
h.update(gid.to_be_bytes());
|
||||
}
|
||||
h.update(f.post_script_name.as_bytes());
|
||||
h.finalize().iter().take(6).map(|b| (b'A' + b % 26) as char).collect()
|
||||
};
|
||||
let ps: String = f.post_script_name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
|
||||
let ps = if ps.is_empty() { "Font".to_string() } else { ps };
|
||||
let base = if subset { format!("{tag}+{ps}") } else { ps };
|
||||
let s = 1000.0 / f.units_per_em;
|
||||
|
||||
w.pdf
|
||||
.type0_font(type0)
|
||||
.base_font(Name(base.as_bytes()))
|
||||
.encoding_predefined(Name(b"Identity-H"))
|
||||
.descendant_font(cid_ref)
|
||||
.to_unicode(cmap_ref);
|
||||
|
||||
{
|
||||
let mut cid = w.pdf.cid_font(cid_ref);
|
||||
cid.subtype(if f.cff { pdf_writer::types::CidFontType::Type0 } else { pdf_writer::types::CidFontType::Type2 });
|
||||
cid.base_font(Name(base.as_bytes()));
|
||||
cid.system_info(pdf_writer::types::SystemInfo {
|
||||
registry: Str(b"Adobe"),
|
||||
ordering: Str(b"Identity"),
|
||||
supplement: 0,
|
||||
});
|
||||
cid.font_descriptor(desc_ref);
|
||||
cid.default_width(0.0);
|
||||
if !f.cff {
|
||||
cid.cid_to_gid_map_predefined(Name(b"Identity"));
|
||||
}
|
||||
{
|
||||
let mut ws = cid.widths();
|
||||
for (cid_v, (gid, _)) in glyphs {
|
||||
let adv = face.glyph_hor_advance(ttf_parser::GlyphId(*gid)).unwrap_or(0) as f32 * s;
|
||||
ws.consecutive(*cid_v, [adv]);
|
||||
}
|
||||
}
|
||||
cid.finish();
|
||||
}
|
||||
|
||||
let bbox = face.global_bounding_box();
|
||||
{
|
||||
let mut fd = w.pdf.font_descriptor(desc_ref);
|
||||
fd.name(Name(base.as_bytes()));
|
||||
let mut flags = pdf_writer::types::FontFlags::SYMBOLIC;
|
||||
if f.italic {
|
||||
flags |= pdf_writer::types::FontFlags::ITALIC;
|
||||
}
|
||||
fd.flags(flags);
|
||||
fd.bbox(PRect::new(bbox.x_min as f32 * s, bbox.y_min as f32 * s, bbox.x_max as f32 * s, bbox.y_max as f32 * s));
|
||||
fd.italic_angle(face.italic_angle());
|
||||
fd.ascent(f.ascender * s);
|
||||
fd.descent(f.descender * s);
|
||||
fd.cap_height(f.cap_height * s);
|
||||
fd.stem_v(80.0 + (f.weight as f32 - 400.0).max(0.0) / 5.0);
|
||||
if f.cff {
|
||||
fd.font_file3(file_ref);
|
||||
} else {
|
||||
fd.font_file2(file_ref);
|
||||
}
|
||||
fd.finish();
|
||||
}
|
||||
{
|
||||
let data = deflate(&program);
|
||||
let mut st = w.pdf.stream(file_ref, &data);
|
||||
st.filter(Filter::FlateDecode);
|
||||
if f.cff {
|
||||
st.pair(Name(b"Subtype"), Name(b"OpenType"));
|
||||
} else {
|
||||
st.pair(Name(b"Length1"), program.len() as i32);
|
||||
}
|
||||
st.finish();
|
||||
}
|
||||
{
|
||||
let mut cmap = pdf_writer::types::UnicodeCmap::new(
|
||||
Name(b"Custom"),
|
||||
pdf_writer::types::SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"UCS"), supplement: 0 },
|
||||
);
|
||||
for (cid, (_, text)) in glyphs {
|
||||
if !text.is_empty() {
|
||||
cmap.pair_with_multiple(*cid, text.chars());
|
||||
}
|
||||
}
|
||||
let data = cmap.finish();
|
||||
w.pdf.cmap(cmap_ref, &data);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Fixture documents: the format round trip, the undo property test, the core's renders and the app's fidelity test
|
||||
//! (the face's canvas painter against the core's PNG) all use these.
|
||||
use crate::model::*;
|
||||
|
||||
fn obj(doc: &mut Document, shape: Shape) -> Object {
|
||||
Object {
|
||||
id: doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn at(mut o: Object, x: f32, y: f32) -> Object {
|
||||
o.transform[4] = x;
|
||||
o.transform[5] = y;
|
||||
o
|
||||
}
|
||||
|
||||
fn rgb(hex: &str) -> Rgba {
|
||||
Rgba::hex(hex).expect("a hex colour")
|
||||
}
|
||||
|
||||
/// A generated picture (no files): a gradient with a disc, `w` × `h`.
|
||||
pub fn picture(w: u32, h: u32) -> Raster {
|
||||
let mut r = Raster::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32);
|
||||
let d = ((fx - 0.6).powi(2) + (fy - 0.4).powi(2)).sqrt();
|
||||
let disc = d < 0.22;
|
||||
r.rgba[i] = if disc { 242 } else { (40.0 + 180.0 * fx) as u8 };
|
||||
r.rgba[i + 1] = if disc { 122 } else { (60.0 + 120.0 * fy) as u8 };
|
||||
r.rgba[i + 2] = if disc { 185 } else { 150 };
|
||||
r.rgba[i + 3] = 255;
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn vector_layer(doc: &mut Document, name: &str, objects: Vec<Object>) -> Layer {
|
||||
let mut l = Layer::vector(doc.new_id(), name);
|
||||
l.kind = LayerKind::Vector { objects };
|
||||
l
|
||||
}
|
||||
|
||||
/// Shapes: rounded rectangle with a stroke, an ellipse with a linear gradient, a dashed path with curves, an arrow,
|
||||
/// a half-transparent group, a rotated rectangle.
|
||||
pub fn shapes() -> Document {
|
||||
let mut d = Document::with_page(400.0, 300.0, Some(Rgba::WHITE));
|
||||
let mut r = at(obj(&mut d, Shape::Rect { w: 140.0, h: 90.0, radius: 14.0 }), 20.0, 20.0);
|
||||
r.fill = Some(Paint::solid(rgb("1f2a44")));
|
||||
r.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("b08d57")),
|
||||
width: 4.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Round,
|
||||
});
|
||||
let mut e = at(obj(&mut d, Shape::Ellipse { w: 150.0, h: 100.0 }), 200.0, 20.0);
|
||||
e.fill = Some(Paint::Linear {
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
x2: 1.0,
|
||||
y2: 1.0,
|
||||
stops: vec![Stop { offset: 0.0, color: rgb("f27ab9") }, Stop { offset: 1.0, color: rgb("d3d98f") }],
|
||||
});
|
||||
let mut p = at(
|
||||
obj(&mut d, Shape::Path { d: "M0 60 C40 0 80 120 120 60 Q150 20 180 60 L180 90 L0 90 Z".into() }),
|
||||
20.0,
|
||||
150.0,
|
||||
);
|
||||
p.fill = Some(Paint::solid(Rgba([74, 163, 255, 160])));
|
||||
p.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("111111")),
|
||||
width: 2.0,
|
||||
dash: vec![8.0, 4.0],
|
||||
cap: Cap::Round,
|
||||
join: Join::Miter,
|
||||
});
|
||||
let mut a =
|
||||
obj(&mut d, Shape::Line { x1: 230.0, y1: 280.0, x2: 370.0, y2: 160.0, arrow_start: false, arrow_end: true });
|
||||
a.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("ff3b3b")),
|
||||
width: 5.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Round,
|
||||
join: Join::Round,
|
||||
});
|
||||
let mut g1 = at(obj(&mut d, Shape::Rect { w: 60.0, h: 60.0, radius: 0.0 }), 0.0, 0.0);
|
||||
g1.fill = Some(Paint::solid(rgb("3ad07a")));
|
||||
let mut g2 = at(obj(&mut d, Shape::Ellipse { w: 60.0, h: 60.0 }), 30.0, 20.0);
|
||||
g2.fill = Some(Paint::solid(rgb("ffd23f")));
|
||||
let mut g = at(obj(&mut d, Shape::Group { objects: vec![g1, g2] }), 220.0, 150.0);
|
||||
g.opacity = 0.5;
|
||||
let mut rot = obj(&mut d, Shape::Rect { w: 50.0, h: 30.0, radius: 4.0 });
|
||||
let (s, c) = 0.5f32.sin_cos();
|
||||
rot.transform = [c, s, -s, c, 330.0, 240.0];
|
||||
rot.fill = Some(Paint::Radial {
|
||||
cx: 0.5,
|
||||
cy: 0.5,
|
||||
r: 0.6,
|
||||
stops: vec![Stop { offset: 0.0, color: rgb("ffffff") }, Stop { offset: 1.0, color: rgb("1f2a44") }],
|
||||
});
|
||||
let layer = vector_layer(&mut d, "Shapes", vec![r, e, p, a, g, rot]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
/// Text: wrapped, centred, right-aligned and justified boxes, bold and italic, letter spacing, Czech letters.
|
||||
pub fn text() -> Document {
|
||||
let mut d = Document::with_page(420.0, 300.0, Some(Rgba::WHITE));
|
||||
let style = |family: &str, weight: u16, italic: bool, size: f32, color: &str, align: Align| TextStyle {
|
||||
family: family.into(),
|
||||
weight,
|
||||
italic,
|
||||
size,
|
||||
color: rgb(color),
|
||||
align,
|
||||
line_height: 1.25,
|
||||
letter_spacing: 0.0,
|
||||
};
|
||||
let t1 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 0.0,
|
||||
text: "Monika Nováková".into(),
|
||||
style: style("Georgia", 700, false, 26.0, "1f2a44", Align::Left),
|
||||
},
|
||||
),
|
||||
20.0,
|
||||
16.0,
|
||||
);
|
||||
let mut s2 = style("Arial", 400, false, 9.0, "b08d57", Align::Left);
|
||||
s2.letter_spacing = 2.0;
|
||||
let t2 = at(obj(&mut d, Shape::Text { w: 0.0, text: "PROJEKTOVÁ MANAŽERKA".into(), style: s2 }), 22.0, 52.0);
|
||||
let body = "Pictor lays text out in the core: shaping, line breaks and alignment, so the screen and the PDF agree. Příliš žluťoučký kůň úpěl ďábelské ódy.";
|
||||
let t3 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: body.into(),
|
||||
style: style("Segoe UI", 400, false, 10.0, "222222", Align::Justify),
|
||||
},
|
||||
),
|
||||
20.0,
|
||||
80.0,
|
||||
);
|
||||
let t4 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: "Centred\nin two lines".into(),
|
||||
style: style("Segoe UI", 600, false, 12.0, "1f2a44", Align::Center),
|
||||
},
|
||||
),
|
||||
220.0,
|
||||
80.0,
|
||||
);
|
||||
let t5 = at(
|
||||
obj(
|
||||
&mut d,
|
||||
Shape::Text {
|
||||
w: 180.0,
|
||||
text: "Right, italic".into(),
|
||||
style: style("Georgia", 400, true, 12.0, "7a2e4d", Align::Right),
|
||||
},
|
||||
),
|
||||
220.0,
|
||||
140.0,
|
||||
);
|
||||
let layer = vector_layer(&mut d, "Text", vec![t1, t2, t3, t4, t5]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
/// A photo-like bitmap layer at 70 % with a vector layer above (a half-transparent rectangle and an outline).
|
||||
pub fn bitmap() -> Document {
|
||||
let mut d = Document::from_image(picture(240, 160), "Photo");
|
||||
let mut r = at(obj(&mut d, Shape::Rect { w: 100.0, h: 60.0, radius: 6.0 }), 20.0, 80.0);
|
||||
r.fill = Some(Paint::solid(Rgba([255, 255, 255, 120])));
|
||||
r.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("1f2a44")),
|
||||
width: 3.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
});
|
||||
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[1].kind {
|
||||
objects.push(r);
|
||||
}
|
||||
d.pages[0].layers[0].opacity = 0.7;
|
||||
d
|
||||
}
|
||||
|
||||
/// A placed picture cropped inside its frame, with a border, over a radial gradient background shape.
|
||||
pub fn image() -> Document {
|
||||
let mut d = Document::with_page(300.0, 220.0, Some(Rgba::WHITE));
|
||||
let asset = "i1".to_string();
|
||||
d.assets.insert(asset.clone(), picture(200, 140));
|
||||
let mut bg = obj(&mut d, Shape::Rect { w: 300.0, h: 220.0, radius: 0.0 });
|
||||
bg.fill = Some(Paint::Radial {
|
||||
cx: 0.3,
|
||||
cy: 0.3,
|
||||
r: 0.9,
|
||||
stops: vec![
|
||||
Stop { offset: 0.0, color: rgb("d3d98f") },
|
||||
Stop { offset: 0.5, color: rgb("f27ab9") },
|
||||
Stop { offset: 1.0, color: rgb("1f2a44") },
|
||||
],
|
||||
});
|
||||
let mut im = at(
|
||||
obj(&mut d, Shape::Image { asset, w: 120.0, h: 120.0, crop: Rect { x: -60.0, y: -10.0, w: 200.0, h: 140.0 } }),
|
||||
90.0,
|
||||
50.0,
|
||||
);
|
||||
im.stroke = Some(Stroke {
|
||||
paint: Paint::solid(rgb("ffffff")),
|
||||
width: 4.0,
|
||||
dash: vec![],
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
});
|
||||
let layer = vector_layer(&mut d, "Picture", vec![bg, im]);
|
||||
d.pages[0].layers = vec![layer];
|
||||
d
|
||||
}
|
||||
|
||||
pub fn all() -> Vec<(&'static str, Document)> {
|
||||
vec![("shapes", shapes()), ("text", text()), ("bitmap", bitmap()), ("image", image())]
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
//! The .pictor file: a zip with `document.json`, `assets/<id>.png` and `fonts/<sha256>.<ttf|otf>`
|
||||
//! (docs/FORMATS.md, "The .pictor document"). Reading is strict: entries are read by known name with a size cap and
|
||||
//! never extracted to disk, every name is checked, every referenced asset must be there and match its size, and a
|
||||
//! newer format is refused before anything else is read.
|
||||
use crate::model::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum FormatError {
|
||||
#[error("This is not a Pictor document (it is not a zip with document.json).")]
|
||||
NotPictor,
|
||||
#[error(
|
||||
"This file was made by a newer Pictor (format {0}); this one reads format {FORMAT}. Update Pictor to open it."
|
||||
)]
|
||||
Newer(u32),
|
||||
#[error("The document is damaged: {0}")]
|
||||
Damaged(String),
|
||||
#[error("The document is too large to open safely: {0}")]
|
||||
TooLarge(String),
|
||||
#[error("The document has an unsafe entry name: {0}")]
|
||||
UnsafeName(String),
|
||||
#[error("The document refers to a missing picture: {0}")]
|
||||
MissingAsset(String),
|
||||
#[error("Could not write the document: {0}")]
|
||||
Write(String),
|
||||
}
|
||||
|
||||
/// Caps for reading a .pictor from outside.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub max_entries: usize,
|
||||
pub max_json_bytes: u64,
|
||||
pub max_entry_bytes: u64,
|
||||
pub max_total_bytes: u64,
|
||||
/// Uncompressed size ÷ compressed size, per entry.
|
||||
pub max_ratio: u64,
|
||||
pub max_pixels: u64,
|
||||
pub max_total_pixels: u64,
|
||||
pub max_page_side_pt: f32,
|
||||
pub max_depth: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
max_entries: 4096,
|
||||
max_json_bytes: 64 << 20,
|
||||
max_entry_bytes: 256 << 20,
|
||||
max_total_bytes: 1 << 30,
|
||||
max_ratio: 1000,
|
||||
max_pixels: 100_000_000,
|
||||
max_total_pixels: 400_000_000,
|
||||
max_page_side_pt: 14_400.0,
|
||||
max_depth: 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font stored in a document.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FontFile {
|
||||
pub family: String,
|
||||
pub weight: u16,
|
||||
pub italic: bool,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct AssetEntry {
|
||||
id: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct FontEntry {
|
||||
family: String,
|
||||
weight: u16,
|
||||
italic: bool,
|
||||
file: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct OnDisk {
|
||||
#[serde(flatten)]
|
||||
doc: Document,
|
||||
#[serde(default)]
|
||||
assets: Vec<AssetEntry>,
|
||||
#[serde(default)]
|
||||
fonts: Vec<FontEntry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VersionOnly {
|
||||
format: u32,
|
||||
}
|
||||
|
||||
/// Asset ids are short letters, digits, `-` and `_` (they become file names).
|
||||
pub fn valid_asset_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document, fonts: &[FontFile]) -> Result<Vec<u8>, FormatError> {
|
||||
use sha2::Digest;
|
||||
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
let used = used_assets(doc);
|
||||
let mut assets = Vec::new();
|
||||
for (id, r) in &doc.assets {
|
||||
if !used.contains(id) {
|
||||
continue;
|
||||
}
|
||||
if !valid_asset_id(id) {
|
||||
return Err(FormatError::Write(format!("asset id {id:?}")));
|
||||
}
|
||||
assets.push(AssetEntry { id: id.clone(), width: r.width, height: r.height });
|
||||
let png = encode_png(r)?;
|
||||
zip.start_file(format!("assets/{id}.png"), stored).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&png).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
let mut font_entries = Vec::new();
|
||||
for f in fonts {
|
||||
let ext = if f.data.get(0..4) == Some(b"OTTO") { "otf" } else { "ttf" };
|
||||
let hex: String = sha2::Sha256::digest(&f.data).iter().map(|b| format!("{b:02x}")).collect();
|
||||
let name = format!("fonts/{hex}.{ext}");
|
||||
if !font_entries.iter().any(|e: &FontEntry| e.file == name) {
|
||||
zip.start_file(name.clone(), deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&f.data).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
font_entries.push(FontEntry { family: f.family.clone(), weight: f.weight, italic: f.italic, file: name });
|
||||
}
|
||||
let on_disk = OnDisk { doc: doc.clone(), assets, fonts: font_entries };
|
||||
let json = serde_json::to_vec(&on_disk).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.start_file("document.json", deflate).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
zip.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
let out = zip.finish().map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
pub fn encode_png(r: &Raster) -> Result<Vec<u8>, FormatError> {
|
||||
use image::ImageEncoder;
|
||||
let mut png = Vec::new();
|
||||
image::codecs::png::PngEncoder::new_with_quality(
|
||||
&mut png,
|
||||
image::codecs::png::CompressionType::Fast,
|
||||
image::codecs::png::FilterType::Adaptive,
|
||||
)
|
||||
.write_image(&r.rgba, r.width, r.height, image::ExtendedColorType::Rgba8)
|
||||
.map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
/// The asset ids the pages refer to.
|
||||
pub fn used_assets(doc: &Document) -> std::collections::BTreeSet<String> {
|
||||
let mut out = std::collections::BTreeSet::new();
|
||||
fn objects(os: &[Object], out: &mut std::collections::BTreeSet<String>) {
|
||||
for o in os {
|
||||
match &o.shape {
|
||||
Shape::Image { asset, .. } => {
|
||||
out.insert(asset.clone());
|
||||
}
|
||||
Shape::Group { objects: g } => objects(g, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn layers(ls: &[Layer], out: &mut std::collections::BTreeSet<String>) {
|
||||
for l in ls {
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects: os } => objects(os, out),
|
||||
LayerKind::Bitmap { asset, .. } => {
|
||||
out.insert(asset.clone());
|
||||
}
|
||||
LayerKind::Group { layers: g } => layers(g, out),
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in &doc.pages {
|
||||
layers(&p.layers, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn safe_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 200
|
||||
&& !name.starts_with('/')
|
||||
&& !name.contains('\\')
|
||||
&& !name.contains(':')
|
||||
&& !name.split('/').any(|part| part.is_empty() || part == ".." || part == ".")
|
||||
}
|
||||
|
||||
fn read_entry<R: Read + std::io::Seek>(
|
||||
zip: &mut zip::ZipArchive<R>,
|
||||
name: &str,
|
||||
cap: u64,
|
||||
limits: &Limits,
|
||||
total: &mut u64,
|
||||
) -> Result<Vec<u8>, FormatError> {
|
||||
let mut f = zip.by_name(name).map_err(|_| FormatError::MissingAsset(name.to_string()))?;
|
||||
let declared = f.size();
|
||||
let compressed = f.compressed_size().max(1);
|
||||
if declared > cap {
|
||||
return Err(FormatError::TooLarge(format!("{name} is {declared} bytes")));
|
||||
}
|
||||
if declared / compressed > limits.max_ratio && declared > 1 << 20 {
|
||||
return Err(FormatError::TooLarge(format!("{name} expands {}×", declared / compressed)));
|
||||
}
|
||||
let mut out = Vec::with_capacity(declared.min(cap) as usize);
|
||||
(&mut f).take(cap + 1).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
if out.len() as u64 > cap || out.len() as u64 != declared {
|
||||
return Err(FormatError::TooLarge(format!("{name} is larger than it says")));
|
||||
}
|
||||
*total += out.len() as u64;
|
||||
if *total > limits.max_total_bytes {
|
||||
return Err(FormatError::TooLarge("the entries together".into()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reads a .pictor. Fonts come back as data for the font book; the document's assets are decoded.
|
||||
pub fn read(bytes: &[u8], limits: &Limits) -> Result<(Document, Vec<FontFile>), FormatError> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|_| FormatError::NotPictor)?;
|
||||
if zip.len() > limits.max_entries {
|
||||
return Err(FormatError::TooLarge(format!("{} entries", zip.len())));
|
||||
}
|
||||
for i in 0..zip.len() {
|
||||
let f = zip.by_index_raw(i).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||
let name = f.name().to_string();
|
||||
if !safe_name(&name) {
|
||||
return Err(FormatError::UnsafeName(name));
|
||||
}
|
||||
if f.is_dir() || f.is_symlink() {
|
||||
return Err(FormatError::UnsafeName(name));
|
||||
}
|
||||
}
|
||||
if zip.index_for_name("document.json").is_none() {
|
||||
return Err(FormatError::NotPictor);
|
||||
}
|
||||
let mut total = 0u64;
|
||||
let json = read_entry(&mut zip, "document.json", limits.max_json_bytes, limits, &mut total)?;
|
||||
// The version first: a newer document is refused before its schema is trusted.
|
||||
let v: VersionOnly =
|
||||
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||
if v.format > FORMAT {
|
||||
return Err(FormatError::Newer(v.format));
|
||||
}
|
||||
if v.format == 0 {
|
||||
return Err(FormatError::Damaged("format 0".into()));
|
||||
}
|
||||
let on_disk: OnDisk =
|
||||
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
|
||||
let mut doc = on_disk.doc;
|
||||
validate(&doc, limits)?;
|
||||
let used = used_assets(&doc);
|
||||
let mut pixels = 0u64;
|
||||
for a in &on_disk.assets {
|
||||
if !valid_asset_id(&a.id) {
|
||||
return Err(FormatError::UnsafeName(a.id.clone()));
|
||||
}
|
||||
let px = a.width as u64 * a.height as u64;
|
||||
if px == 0 || px > limits.max_pixels {
|
||||
return Err(FormatError::TooLarge(format!("picture {} is {}×{}", a.id, a.width, a.height)));
|
||||
}
|
||||
pixels += px;
|
||||
if pixels > limits.max_total_pixels {
|
||||
return Err(FormatError::TooLarge("the pictures together".into()));
|
||||
}
|
||||
let name = format!("assets/{}.png", a.id);
|
||||
let png = read_entry(&mut zip, &name, limits.max_entry_bytes, limits, &mut total)?;
|
||||
let raster =
|
||||
decode_png(&png, a.width, a.height, limits).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
doc.assets.insert(a.id.clone(), raster);
|
||||
}
|
||||
for id in &used {
|
||||
if !doc.assets.contains_key(id) {
|
||||
return Err(FormatError::MissingAsset(id.clone()));
|
||||
}
|
||||
}
|
||||
let mut fonts = Vec::new();
|
||||
for f in &on_disk.fonts {
|
||||
if !safe_name(&f.file) || !f.file.starts_with("fonts/") {
|
||||
return Err(FormatError::UnsafeName(f.file.clone()));
|
||||
}
|
||||
let data = read_entry(&mut zip, &f.file, limits.max_entry_bytes, limits, &mut total)?;
|
||||
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||
return Err(FormatError::Damaged(format!("{} is not a font", f.file)));
|
||||
}
|
||||
fonts.push(FontFile { family: f.family.clone(), weight: f.weight, italic: f.italic, data });
|
||||
}
|
||||
Ok((doc, fonts))
|
||||
}
|
||||
|
||||
pub fn decode_png(png: &[u8], width: u32, height: u32, limits: &Limits) -> Result<Raster, String> {
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
|
||||
let mut l = image::Limits::default();
|
||||
l.max_image_width = Some(width);
|
||||
l.max_image_height = Some(height);
|
||||
l.max_alloc = Some((limits.max_pixels * 8).min(u64::MAX / 2));
|
||||
reader.limits(l);
|
||||
let img = reader.decode().map_err(|e| e.to_string())?;
|
||||
if img.width() != width || img.height() != height {
|
||||
return Err(format!("is {}×{}, not {width}×{height}", img.width(), img.height()));
|
||||
}
|
||||
Ok(Raster { width, height, rgba: img.into_rgba8().into_raw() })
|
||||
}
|
||||
|
||||
/// Structural checks of a parsed document: sizes, numbers, ids, paths, depth.
|
||||
pub fn validate(doc: &Document, limits: &Limits) -> Result<(), FormatError> {
|
||||
let bad = |s: String| Err(FormatError::Damaged(s));
|
||||
if doc.pages.is_empty() {
|
||||
return bad("no pages".into());
|
||||
}
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
let mut check_id = |id: Id| -> Result<(), FormatError> {
|
||||
if id == 0 || id >= doc.next_id || !ids.insert(id) {
|
||||
return Err(FormatError::Damaged(format!("id {id} is repeated or out of range")));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let fin = |v: f32, what: &str| -> Result<(), FormatError> {
|
||||
if v.is_finite() && v.abs() <= 1e6 { Ok(()) } else { Err(FormatError::Damaged(format!("{what} is {v}"))) }
|
||||
};
|
||||
fn obj(
|
||||
o: &Object,
|
||||
depth: usize,
|
||||
limits: &Limits,
|
||||
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||
) -> Result<(), FormatError> {
|
||||
if depth > limits.max_depth {
|
||||
return Err(FormatError::TooLarge("groups nested too deep".into()));
|
||||
}
|
||||
check_id(o.id)?;
|
||||
for v in o.transform {
|
||||
fin(v, "a transform")?;
|
||||
}
|
||||
if !(0.0..=1.0).contains(&o.opacity) {
|
||||
return Err(FormatError::Damaged(format!("opacity {}", o.opacity)));
|
||||
}
|
||||
if let Some(s) = &o.stroke {
|
||||
fin(s.width, "a stroke width")?;
|
||||
if s.dash.len() > 64 {
|
||||
return Err(FormatError::Damaged("a dash pattern is too long".into()));
|
||||
}
|
||||
}
|
||||
match &o.shape {
|
||||
Shape::Rect { w, h, radius } => {
|
||||
fin(*w, "a width")?;
|
||||
fin(*h, "a height")?;
|
||||
fin(*radius, "a radius")?
|
||||
}
|
||||
Shape::Ellipse { w, h } => {
|
||||
fin(*w, "a width")?;
|
||||
fin(*h, "a height")?
|
||||
}
|
||||
Shape::Line { x1, y1, x2, y2, .. } => {
|
||||
for v in [x1, y1, x2, y2] {
|
||||
fin(*v, "a line end")?;
|
||||
}
|
||||
}
|
||||
Shape::Path { d } => {
|
||||
let segs = crate::path::parse(d).map_err(|e| FormatError::Damaged(e.to_string()))?;
|
||||
if !matches!(segs.first(), None | Some(crate::path::Seg::Move(..))) {
|
||||
return Err(FormatError::Damaged("a path starts with M".into()));
|
||||
}
|
||||
}
|
||||
Shape::Text { w, text, style } => {
|
||||
fin(*w, "a text width")?;
|
||||
if text.len() > 1 << 20 {
|
||||
return Err(FormatError::TooLarge("a text box".into()));
|
||||
}
|
||||
if !(0.5..=2000.0).contains(&style.size) || !(0.5..=10.0).contains(&style.line_height) {
|
||||
return Err(FormatError::Damaged("a text size".into()));
|
||||
}
|
||||
fin(style.letter_spacing, "letter spacing")?;
|
||||
}
|
||||
Shape::Image { asset, w, h, crop } => {
|
||||
if !valid_asset_id(asset) {
|
||||
return Err(FormatError::UnsafeName(asset.clone()));
|
||||
}
|
||||
for v in [w, h, &crop.x, &crop.y, &crop.w, &crop.h] {
|
||||
fin(*v, "an image frame")?;
|
||||
}
|
||||
}
|
||||
Shape::Group { objects } => {
|
||||
for c in objects {
|
||||
obj(c, depth + 1, limits, check_id, fin)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn layers(
|
||||
ls: &[Layer],
|
||||
depth: usize,
|
||||
limits: &Limits,
|
||||
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
|
||||
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
|
||||
) -> Result<(), FormatError> {
|
||||
if depth > limits.max_depth {
|
||||
return Err(FormatError::TooLarge("layers nested too deep".into()));
|
||||
}
|
||||
for l in ls {
|
||||
check_id(l.id)?;
|
||||
if !(0.0..=1.0).contains(&l.opacity) {
|
||||
return Err(FormatError::Damaged(format!("opacity {}", l.opacity)));
|
||||
}
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects } => {
|
||||
for o in objects {
|
||||
obj(o, depth + 1, limits, check_id, fin)?;
|
||||
}
|
||||
}
|
||||
LayerKind::Bitmap { asset, x, y, w, h } => {
|
||||
if !valid_asset_id(asset) {
|
||||
return Err(FormatError::UnsafeName(asset.clone()));
|
||||
}
|
||||
for v in [x, y, w, h] {
|
||||
fin(*v, "a layer's place")?;
|
||||
}
|
||||
}
|
||||
LayerKind::Group { layers: g } => layers(g, depth + 1, limits, check_id, fin)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
for p in &doc.pages {
|
||||
check_id(p.id)?;
|
||||
if !(p.width >= 1.0
|
||||
&& p.width <= limits.max_page_side_pt
|
||||
&& p.height >= 1.0
|
||||
&& p.height <= limits.max_page_side_pt)
|
||||
{
|
||||
return bad(format!("a page is {} × {} pt", p.width, p.height));
|
||||
}
|
||||
for m in p.margins {
|
||||
fin(m, "a margin")?;
|
||||
}
|
||||
if p.guides.len() > 1000 {
|
||||
return bad("too many guides".into());
|
||||
}
|
||||
layers(&p.layers, 0, limits, &mut check_id, &fin)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Pictor's document: pages of layers (vector objects, bitmaps, groups), operations with exact undo, the .pictor
|
||||
//! file, text layout, the display list both painters draw, the tiny-skia render, bitmap tools, SVG import and the
|
||||
//! PNG / JPG / SVG / PDF exports. Pure: no network, no processes, no registry; fonts come from the caller's font book.
|
||||
pub mod bitmap;
|
||||
pub mod display;
|
||||
pub mod export;
|
||||
pub mod fixtures;
|
||||
pub mod format;
|
||||
pub mod model;
|
||||
pub mod ops;
|
||||
pub mod path;
|
||||
pub mod render;
|
||||
pub mod svg;
|
||||
pub mod text;
|
||||
|
||||
pub use format::{FontFile, FormatError, Limits};
|
||||
pub use model::*;
|
||||
pub use ops::{History, Op, OpError, apply};
|
||||
pub use text::FontBook;
|
||||
@@ -0,0 +1,580 @@
|
||||
//! The document: pages, layers, objects. Everything here is plain data that serialises to `document.json`
|
||||
//! (docs/FORMATS.md, "The .pictor document"). Pixels live in [`Raster`] assets, outside the JSON.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The format version this code writes and the newest it reads.
|
||||
pub const FORMAT: u32 = 1;
|
||||
|
||||
pub type Id = u64;
|
||||
|
||||
/// Points per millimetre (1 pt = 1/72 in).
|
||||
pub const PT_PER_MM: f32 = 72.0 / 25.4;
|
||||
/// A4 in points.
|
||||
pub const A4: (f32, f32) = (595.276, 841.89);
|
||||
/// US Letter in points.
|
||||
pub const LETTER: (f32, f32) = (612.0, 792.0);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
pub format: u32,
|
||||
/// The next free id for pages, layers and objects.
|
||||
pub next_id: Id,
|
||||
pub pages: Vec<Page>,
|
||||
/// Pixels of bitmap layers and placed images, by asset id. Written as PNG files beside `document.json`.
|
||||
#[serde(skip)]
|
||||
pub assets: BTreeMap<String, Raster>,
|
||||
}
|
||||
|
||||
/// Straight (not premultiplied) RGBA, 8 bits per channel, rows top to bottom.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Raster {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Raster {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Raster({}×{})", self.width, self.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl Raster {
|
||||
pub fn new(width: u32, height: u32) -> Raster {
|
||||
Raster { width, height, rgba: vec![0; width as usize * height as usize * 4] }
|
||||
}
|
||||
pub fn filled(width: u32, height: u32, rgba: [u8; 4]) -> Raster {
|
||||
let mut r = Raster::new(width, height);
|
||||
for px in r.rgba.as_chunks_mut::<4>().0 {
|
||||
px.copy_from_slice(&rgba);
|
||||
}
|
||||
r
|
||||
}
|
||||
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = (y as usize * self.width as usize + x as usize) * 4;
|
||||
[self.rgba[i], self.rgba[i + 1], self.rgba[i + 2], self.rgba[i + 3]]
|
||||
}
|
||||
/// A copy of a rectangle (clamped to the raster).
|
||||
pub fn crop(&self, r: PixelRect) -> Raster {
|
||||
let r = r.clamp(self.width, self.height);
|
||||
let mut out = Raster::new(r.w, r.h);
|
||||
for y in 0..r.h {
|
||||
let src = ((r.y + y) as usize * self.width as usize + r.x as usize) * 4;
|
||||
let dst = y as usize * r.w as usize * 4;
|
||||
out.rgba[dst..dst + r.w as usize * 4].copy_from_slice(&self.rgba[src..src + r.w as usize * 4]);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Writes `src` at (x, y) (clamped).
|
||||
pub fn put(&mut self, x: u32, y: u32, src: &Raster) {
|
||||
let w = src.width.min(self.width.saturating_sub(x));
|
||||
let h = src.height.min(self.height.saturating_sub(y));
|
||||
for row in 0..h {
|
||||
let s = row as usize * src.width as usize * 4;
|
||||
let d = ((y + row) as usize * self.width as usize + x as usize) * 4;
|
||||
self.rgba[d..d + w as usize * 4].copy_from_slice(&src.rgba[s..s + w as usize * 4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle of whole pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PixelRect {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
|
||||
impl PixelRect {
|
||||
pub fn clamp(self, width: u32, height: u32) -> PixelRect {
|
||||
let x = self.x.min(width);
|
||||
let y = self.y.min(height);
|
||||
PixelRect { x, y, w: self.w.min(width - x), h: self.h.min(height - y) }
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.w == 0 || self.h == 0
|
||||
}
|
||||
pub fn union(self, o: PixelRect) -> PixelRect {
|
||||
if self.is_empty() {
|
||||
return o;
|
||||
}
|
||||
if o.is_empty() {
|
||||
return self;
|
||||
}
|
||||
let x0 = self.x.min(o.x);
|
||||
let y0 = self.y.min(o.y);
|
||||
let x1 = (self.x + self.w).max(o.x + o.w);
|
||||
let y1 = (self.y + self.h).max(o.y + o.h);
|
||||
PixelRect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Page {
|
||||
pub id: Id,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Top, right, bottom, left, in points.
|
||||
#[serde(default)]
|
||||
pub margins: [f32; 4],
|
||||
#[serde(default)]
|
||||
pub guides: Vec<Guide>,
|
||||
/// The paper colour; none = transparent (an image document).
|
||||
#[serde(default)]
|
||||
pub background: Option<Rgba>,
|
||||
pub layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
pub vertical: bool,
|
||||
pub at: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Layer {
|
||||
pub id: Id,
|
||||
pub name: String,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default = "one")]
|
||||
pub opacity: f32,
|
||||
#[serde(flatten)]
|
||||
pub kind: LayerKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum LayerKind {
|
||||
Vector {
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
/// Pixels (the asset, at its own size) placed on the page in the rectangle x, y, w, h (points).
|
||||
Bitmap {
|
||||
asset: String,
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
},
|
||||
Group {
|
||||
layers: Vec<Layer>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Object {
|
||||
pub id: Id,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
/// a b c d e f: x' = a·x + c·y + e, y' = b·x + d·y + f (the canvas and SVG order).
|
||||
#[serde(default = "identity")]
|
||||
pub transform: [f32; 6],
|
||||
#[serde(default = "one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub fill: Option<Paint>,
|
||||
#[serde(default)]
|
||||
pub stroke: Option<Stroke>,
|
||||
pub shape: Shape,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Shape {
|
||||
Rect {
|
||||
w: f32,
|
||||
h: f32,
|
||||
#[serde(default)]
|
||||
radius: f32,
|
||||
},
|
||||
Ellipse {
|
||||
w: f32,
|
||||
h: f32,
|
||||
},
|
||||
Line {
|
||||
x1: f32,
|
||||
y1: f32,
|
||||
x2: f32,
|
||||
y2: f32,
|
||||
#[serde(default)]
|
||||
arrow_start: bool,
|
||||
#[serde(default)]
|
||||
arrow_end: bool,
|
||||
},
|
||||
/// SVG path data, absolute M L C Q Z only (`crate::path`).
|
||||
Path {
|
||||
d: String,
|
||||
},
|
||||
/// A text box `w` points wide (0 = no wrapping); its height follows from the text.
|
||||
Text {
|
||||
w: f32,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
},
|
||||
/// A picture in a frame `w` × `h`; `crop` is where the whole picture lies, in the frame's coordinates.
|
||||
Image {
|
||||
asset: String,
|
||||
w: f32,
|
||||
h: f32,
|
||||
crop: Rect,
|
||||
},
|
||||
Group {
|
||||
objects: Vec<Object>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextStyle {
|
||||
pub family: String,
|
||||
#[serde(default = "regular")]
|
||||
pub weight: u16,
|
||||
#[serde(default)]
|
||||
pub italic: bool,
|
||||
pub size: f32,
|
||||
pub color: Rgba,
|
||||
#[serde(default)]
|
||||
pub align: Align,
|
||||
/// A multiple of the size.
|
||||
#[serde(default = "line_height")]
|
||||
pub line_height: f32,
|
||||
/// Extra space after each character, in points.
|
||||
#[serde(default)]
|
||||
pub letter_spacing: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Align {
|
||||
#[default]
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Justify,
|
||||
}
|
||||
|
||||
/// sRGB, straight alpha.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rgba(pub [u8; 4]);
|
||||
|
||||
impl Rgba {
|
||||
pub const BLACK: Rgba = Rgba([0, 0, 0, 255]);
|
||||
pub const WHITE: Rgba = Rgba([255, 255, 255, 255]);
|
||||
pub fn hex(s: &str) -> Option<Rgba> {
|
||||
let s = s.trim_start_matches('#');
|
||||
let v = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
|
||||
match s.len() {
|
||||
6 => Some(Rgba([v(0)?, v(2)?, v(4)?, 255])),
|
||||
8 => Some(Rgba([v(0)?, v(2)?, v(4)?, v(6)?])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Paint {
|
||||
Solid {
|
||||
color: Rgba,
|
||||
},
|
||||
/// From (x1, y1) to (x2, y2), as fractions of the shape's box (0..1).
|
||||
Linear {
|
||||
x1: f32,
|
||||
y1: f32,
|
||||
x2: f32,
|
||||
y2: f32,
|
||||
stops: Vec<Stop>,
|
||||
},
|
||||
/// Centre and radius as fractions of the shape's box (the radius of its width).
|
||||
Radial {
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
r: f32,
|
||||
stops: Vec<Stop>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub fn solid(c: Rgba) -> Paint {
|
||||
Paint::Solid { color: c }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stop {
|
||||
pub offset: f32,
|
||||
pub color: Rgba,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Stroke {
|
||||
pub paint: Paint,
|
||||
pub width: f32,
|
||||
#[serde(default)]
|
||||
pub dash: Vec<f32>,
|
||||
#[serde(default)]
|
||||
pub cap: Cap,
|
||||
#[serde(default)]
|
||||
pub join: Join,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Cap {
|
||||
#[default]
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Join {
|
||||
#[default]
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
fn regular() -> u16 {
|
||||
400
|
||||
}
|
||||
fn line_height() -> f32 {
|
||||
1.2
|
||||
}
|
||||
pub fn identity() -> [f32; 6] {
|
||||
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
Document { format: FORMAT, next_id: 1, pages: Vec::new(), assets: BTreeMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn new_id(&mut self) -> Id {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
id
|
||||
}
|
||||
|
||||
/// A blank page of the given size with one empty vector layer.
|
||||
pub fn with_page(width: f32, height: f32, background: Option<Rgba>) -> Document {
|
||||
let mut d = Document::default();
|
||||
let pid = d.new_id();
|
||||
let lid = d.new_id();
|
||||
d.pages.push(Page {
|
||||
id: pid,
|
||||
width,
|
||||
height,
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background,
|
||||
layers: vec![Layer::vector(lid, "Layer 1")],
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
/// An A4 page, white, with 15 mm margins.
|
||||
pub fn a4() -> Document {
|
||||
let mut d = Document::with_page(A4.0, A4.1, Some(Rgba::WHITE));
|
||||
d.pages[0].margins = [15.0 * PT_PER_MM; 4];
|
||||
d
|
||||
}
|
||||
|
||||
/// An image document: the page is the image's size (1 pt = 1 px), the image a bitmap layer, an empty vector
|
||||
/// layer above it.
|
||||
pub fn from_image(raster: Raster, name: &str) -> Document {
|
||||
let (w, h) = (raster.width as f32, raster.height as f32);
|
||||
let mut d = Document::default();
|
||||
let pid = d.new_id();
|
||||
let bid = d.new_id();
|
||||
let vid = d.new_id();
|
||||
let asset = format!("b{bid}");
|
||||
d.assets.insert(asset.clone(), raster);
|
||||
d.pages.push(Page {
|
||||
id: pid,
|
||||
width: w,
|
||||
height: h,
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background: None,
|
||||
layers: vec![
|
||||
Layer {
|
||||
id: bid,
|
||||
name: name.to_string(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Bitmap { asset, x: 0.0, y: 0.0, w, h },
|
||||
},
|
||||
Layer::vector(vid, "Layer 2"),
|
||||
],
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
pub fn page(&self, id: Id) -> Option<&Page> {
|
||||
self.pages.iter().find(|p| p.id == id)
|
||||
}
|
||||
pub fn page_mut(&mut self, id: Id) -> Option<&mut Page> {
|
||||
self.pages.iter_mut().find(|p| p.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
pub fn vector(id: Id, name: &str) -> Layer {
|
||||
Layer {
|
||||
id,
|
||||
name: name.to_string(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Vector { objects: Vec::new() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// The layer with this id, at any depth.
|
||||
pub fn layer(&self, id: Id) -> Option<&Layer> {
|
||||
fn find(ls: &[Layer], id: Id) -> Option<&Layer> {
|
||||
for l in ls {
|
||||
if l.id == id {
|
||||
return Some(l);
|
||||
}
|
||||
if let LayerKind::Group { layers } = &l.kind
|
||||
&& let Some(f) = find(layers, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&self.layers, id)
|
||||
}
|
||||
|
||||
/// The list that holds layers: the page's own (`parent` none) or a group layer's.
|
||||
pub fn layer_list_mut(&mut self, parent: Option<Id>) -> Option<&mut Vec<Layer>> {
|
||||
match parent {
|
||||
None => Some(&mut self.layers),
|
||||
Some(pid) => {
|
||||
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Vec<Layer>> {
|
||||
for l in ls {
|
||||
if let LayerKind::Group { layers } = &mut l.kind {
|
||||
if l.id == id {
|
||||
return Some(layers);
|
||||
}
|
||||
if let Some(f) = find(layers, id) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&mut self.layers, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn layer_mut(&mut self, id: Id) -> Option<&mut Layer> {
|
||||
fn find(ls: &mut [Layer], id: Id) -> Option<&mut Layer> {
|
||||
for l in ls {
|
||||
if l.id == id {
|
||||
return Some(l);
|
||||
}
|
||||
if let LayerKind::Group { layers } = &mut l.kind
|
||||
&& let Some(f) = find(layers, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(&mut self.layers, id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The list that holds objects: a vector layer's own (`parent` none) or a group object's.
|
||||
pub fn object_list_mut(layer: &mut Layer, parent: Option<Id>) -> Option<&mut Vec<Object>> {
|
||||
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||
match parent {
|
||||
None => Some(objects),
|
||||
Some(pid) => {
|
||||
fn find(os: &mut [Object], id: Id) -> Option<&mut Vec<Object>> {
|
||||
for o in os {
|
||||
if let Shape::Group { objects } = &mut o.shape {
|
||||
if o.id == id {
|
||||
return Some(objects);
|
||||
}
|
||||
if let Some(f) = find(objects, id) {
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The object with this id, at any depth of a vector layer.
|
||||
pub fn find_object_mut(layer: &mut Layer, id: Id) -> Option<&mut Object> {
|
||||
let LayerKind::Vector { objects } = &mut layer.kind else { return None };
|
||||
fn find(os: &mut [Object], id: Id) -> Option<&mut Object> {
|
||||
for o in os {
|
||||
if o.id == id {
|
||||
return Some(o);
|
||||
}
|
||||
if let Shape::Group { objects } = &mut o.shape
|
||||
&& let Some(f) = find(objects, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, id)
|
||||
}
|
||||
|
||||
pub fn find_object(layer: &Layer, id: Id) -> Option<&Object> {
|
||||
let LayerKind::Vector { objects } = &layer.kind else { return None };
|
||||
fn find(os: &[Object], id: Id) -> Option<&Object> {
|
||||
for o in os {
|
||||
if o.id == id {
|
||||
return Some(o);
|
||||
}
|
||||
if let Shape::Group { objects } = &o.shape
|
||||
&& let Some(f) = find(objects, id)
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
find(objects, id)
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! Every edit is an [`Op`]. Applying one returns its exact inverse, so undo is applying inverses back; the
|
||||
//! [`History`] keeps both without a limit within a session.
|
||||
use crate::model::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case")]
|
||||
pub enum Op {
|
||||
InsertPage {
|
||||
index: usize,
|
||||
page: Page,
|
||||
},
|
||||
RemovePage {
|
||||
index: usize,
|
||||
},
|
||||
/// Size, margins, guides and paper colour (the layers are untouched).
|
||||
SetPage {
|
||||
page: Id,
|
||||
width: f32,
|
||||
height: f32,
|
||||
margins: [f32; 4],
|
||||
guides: Vec<Guide>,
|
||||
background: Option<Rgba>,
|
||||
},
|
||||
/// Into the page's layers (`parent` none) or a group layer's, at `index`.
|
||||
InsertLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
layer: Layer,
|
||||
},
|
||||
RemoveLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// Name, visibility, lock, opacity and, for a bitmap layer, its placement (not its children).
|
||||
SetLayer {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
name: String,
|
||||
visible: bool,
|
||||
locked: bool,
|
||||
opacity: f32,
|
||||
place: Option<Rect>,
|
||||
},
|
||||
InsertObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
object: Object,
|
||||
},
|
||||
RemoveObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// The whole object with this id, replaced (a move, scale, colour or text change).
|
||||
ReplaceObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
object: Object,
|
||||
},
|
||||
/// Pixels of an asset: `rect` gets `pixels` (w × h RGBA).
|
||||
Patch {
|
||||
asset: String,
|
||||
rect: PixelRect,
|
||||
#[serde(skip)]
|
||||
pixels: Vec<u8>,
|
||||
},
|
||||
/// Adds (`raster` some), replaces or removes (none) an asset.
|
||||
PutAsset {
|
||||
asset: String,
|
||||
#[serde(skip)]
|
||||
raster: Option<Raster>,
|
||||
},
|
||||
Batch {
|
||||
ops: Vec<Op>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum OpError {
|
||||
#[error("there is no page {0}")]
|
||||
NoPage(Id),
|
||||
#[error("there is no layer {0}")]
|
||||
NoLayer(Id),
|
||||
#[error("there is no object {0}")]
|
||||
NoObject(Id),
|
||||
#[error("there is no asset {0}")]
|
||||
NoAsset(String),
|
||||
#[error("index {0} is out of range")]
|
||||
Index(usize),
|
||||
#[error("layer {0} does not hold objects")]
|
||||
NotVector(Id),
|
||||
#[error("the pixels do not fit the rectangle")]
|
||||
PatchSize,
|
||||
}
|
||||
|
||||
/// Applies `op` and returns its inverse. On an error the document is unchanged.
|
||||
pub fn apply(doc: &mut Document, op: Op) -> Result<Op, OpError> {
|
||||
match op {
|
||||
Op::InsertPage { index, page } => {
|
||||
if index > doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
doc.pages.insert(index, page);
|
||||
Ok(Op::RemovePage { index })
|
||||
}
|
||||
Op::RemovePage { index } => {
|
||||
if index >= doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let page = doc.pages.remove(index);
|
||||
Ok(Op::InsertPage { index, page })
|
||||
}
|
||||
Op::SetPage { page, width, height, margins, guides, background } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let inv = Op::SetPage {
|
||||
page,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
margins: p.margins,
|
||||
guides: std::mem::take(&mut p.guides),
|
||||
background: p.background,
|
||||
};
|
||||
p.width = width;
|
||||
p.height = height;
|
||||
p.margins = margins;
|
||||
p.guides = guides;
|
||||
p.background = background;
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertLayer { page, parent, index, layer } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, layer);
|
||||
Ok(Op::RemoveLayer { page, parent, index })
|
||||
}
|
||||
Op::RemoveLayer { page, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let layer = list.remove(index);
|
||||
Ok(Op::InsertLayer { page, parent, index, layer })
|
||||
}
|
||||
Op::SetLayer { page, layer, name, visible, locked, opacity, place } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let old_place = match &mut l.kind {
|
||||
LayerKind::Bitmap { x, y, w, h, .. } => {
|
||||
let old = Rect { x: *x, y: *y, w: *w, h: *h };
|
||||
if let Some(r) = place {
|
||||
(*x, *y, *w, *h) = (r.x, r.y, r.w, r.h);
|
||||
}
|
||||
Some(old)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let inv = Op::SetLayer {
|
||||
page,
|
||||
layer,
|
||||
name: std::mem::replace(&mut l.name, name),
|
||||
visible: std::mem::replace(&mut l.visible, visible),
|
||||
locked: std::mem::replace(&mut l.locked, locked),
|
||||
opacity: std::mem::replace(&mut l.opacity, opacity),
|
||||
place: if place.is_some() { old_place } else { None },
|
||||
};
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertObject { page, layer, parent, index, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, object);
|
||||
Ok(Op::RemoveObject { page, layer, parent, index })
|
||||
}
|
||||
Op::RemoveObject { page, layer, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let object = list.remove(index);
|
||||
Ok(Op::InsertObject { page, layer, parent, index, object })
|
||||
}
|
||||
Op::ReplaceObject { page, layer, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let o = find_object_mut(l, object.id).ok_or(OpError::NoObject(object.id))?;
|
||||
let old = std::mem::replace(o, object);
|
||||
Ok(Op::ReplaceObject { page, layer, object: old })
|
||||
}
|
||||
Op::Patch { asset, rect, pixels } => {
|
||||
let r = doc.assets.get_mut(&asset).ok_or_else(|| OpError::NoAsset(asset.clone()))?;
|
||||
if rect.clamp(r.width, r.height) != rect || pixels.len() != rect.w as usize * rect.h as usize * 4 {
|
||||
return Err(OpError::PatchSize);
|
||||
}
|
||||
let before = r.crop(rect);
|
||||
r.put(rect.x, rect.y, &Raster { width: rect.w, height: rect.h, rgba: pixels });
|
||||
Ok(Op::Patch { asset, rect, pixels: before.rgba })
|
||||
}
|
||||
Op::PutAsset { asset, raster } => {
|
||||
let old = match raster {
|
||||
Some(r) => doc.assets.insert(asset.clone(), r),
|
||||
None => doc.assets.remove(&asset),
|
||||
};
|
||||
Ok(Op::PutAsset { asset, raster: old })
|
||||
}
|
||||
Op::Batch { ops } => {
|
||||
let mut done: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
match apply(doc, op) {
|
||||
Ok(inv) => done.push(inv),
|
||||
Err(e) => {
|
||||
// Roll back what was done, so a failed batch leaves no trace.
|
||||
for inv in done.into_iter().rev() {
|
||||
let _ = apply(doc, inv);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
done.reverse();
|
||||
Ok(Op::Batch { ops: done })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A patch op for the rectangle `rect` that turns `before` into `after` (both the whole asset).
|
||||
pub fn patch_between(asset: &str, after: &Raster, rect: PixelRect) -> Op {
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: after.crop(rect).rgba }
|
||||
}
|
||||
|
||||
/// Done and undone operations, each with its inverse.
|
||||
#[derive(Default)]
|
||||
pub struct History {
|
||||
done: Vec<(Op, Op)>,
|
||||
undone: Vec<(Op, Op)>,
|
||||
/// Bumped on every change, so the face and "unsaved changes" can tell.
|
||||
pub revision: u64,
|
||||
saved_revision: u64,
|
||||
}
|
||||
|
||||
impl History {
|
||||
/// Applies an operation and records it.
|
||||
pub fn apply(&mut self, doc: &mut Document, op: Op) -> Result<(), OpError> {
|
||||
let inv = apply(doc, op.clone())?;
|
||||
self.done.push((op, inv));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records an operation that was applied outside (`op` was applied, `inverse` undoes it).
|
||||
pub fn record(&mut self, op: Op, inverse: Op) {
|
||||
self.done.push((op, inverse));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.done.pop() else { return Ok(false) };
|
||||
match apply(doc, inv.clone()) {
|
||||
Ok(_) => {
|
||||
self.undone.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.done.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.undone.pop() else { return Ok(false) };
|
||||
match apply(doc, op.clone()) {
|
||||
Ok(_) => {
|
||||
self.done.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.undone.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.done.is_empty()
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.undone.is_empty()
|
||||
}
|
||||
pub fn mark_saved(&mut self) {
|
||||
self.saved_revision = self.revision;
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.revision != self.saved_revision
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Path data: the subset of SVG path syntax Pictor writes and reads (M L H V C Q Z, absolute or relative; numbers in
|
||||
//! plain or exponent form). Parsed into absolute segments; arcs are not accepted (SVG import turns them into curves).
|
||||
use std::fmt::Write;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Seg {
|
||||
Move(f32, f32),
|
||||
Line(f32, f32),
|
||||
Quad(f32, f32, f32, f32),
|
||||
Cubic(f32, f32, f32, f32, f32, f32),
|
||||
Close,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
#[error("path data is not understood at {at}: {why}")]
|
||||
pub struct PathError {
|
||||
pub at: usize,
|
||||
pub why: &'static str,
|
||||
}
|
||||
|
||||
/// The most segments one path may have (a hostile document could otherwise ask for any amount of work).
|
||||
pub const MAX_SEGMENTS: usize = 200_000;
|
||||
|
||||
pub fn parse(d: &str) -> Result<Vec<Seg>, PathError> {
|
||||
let b = d.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut out = Vec::new();
|
||||
let (mut cx, mut cy, mut sx, mut sy) = (0f32, 0f32, 0f32, 0f32);
|
||||
let mut cmd = 0u8;
|
||||
let skip = |i: &mut usize| {
|
||||
while *i < b.len() && (b[*i].is_ascii_whitespace() || b[*i] == b',') {
|
||||
*i += 1;
|
||||
}
|
||||
};
|
||||
let num = |i: &mut usize| -> Result<f32, PathError> {
|
||||
skip(i);
|
||||
let start = *i;
|
||||
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||
*i += 1;
|
||||
}
|
||||
let mut dot = false;
|
||||
let mut digits = false;
|
||||
while *i < b.len() && (b[*i].is_ascii_digit() || (b[*i] == b'.' && !dot)) {
|
||||
if b[*i] == b'.' {
|
||||
dot = true;
|
||||
} else {
|
||||
digits = true;
|
||||
}
|
||||
*i += 1;
|
||||
}
|
||||
if *i < b.len() && (b[*i] == b'e' || b[*i] == b'E') && digits {
|
||||
*i += 1;
|
||||
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
|
||||
*i += 1;
|
||||
}
|
||||
while *i < b.len() && b[*i].is_ascii_digit() {
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
if !digits {
|
||||
return Err(PathError { at: start, why: "a number was expected" });
|
||||
}
|
||||
let v: f32 = d[start..*i].parse().map_err(|_| PathError { at: start, why: "a number was expected" })?;
|
||||
if !v.is_finite() {
|
||||
return Err(PathError { at: start, why: "the number is too large" });
|
||||
}
|
||||
Ok(v)
|
||||
};
|
||||
loop {
|
||||
skip(&mut i);
|
||||
if i >= b.len() {
|
||||
break;
|
||||
}
|
||||
if b[i].is_ascii_alphabetic() {
|
||||
cmd = b[i];
|
||||
i += 1;
|
||||
if cmd == b'Z' || cmd == b'z' {
|
||||
out.push(Seg::Close);
|
||||
cx = sx;
|
||||
cy = sy;
|
||||
cmd = 0;
|
||||
continue;
|
||||
}
|
||||
} else if cmd == 0 {
|
||||
return Err(PathError { at: i, why: "a command was expected" });
|
||||
}
|
||||
let rel = cmd.is_ascii_lowercase();
|
||||
let (ox, oy) = if rel { (cx, cy) } else { (0.0, 0.0) };
|
||||
match cmd.to_ascii_uppercase() {
|
||||
b'M' => {
|
||||
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||
out.push(Seg::Move(x, y));
|
||||
(cx, cy, sx, sy) = (x, y, x, y);
|
||||
cmd = if rel { b'l' } else { b'L' };
|
||||
}
|
||||
b'L' => {
|
||||
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
|
||||
out.push(Seg::Line(x, y));
|
||||
(cx, cy) = (x, y);
|
||||
}
|
||||
b'H' => {
|
||||
let x = num(&mut i)? + ox;
|
||||
out.push(Seg::Line(x, cy));
|
||||
cx = x;
|
||||
}
|
||||
b'V' => {
|
||||
let y = num(&mut i)? + oy;
|
||||
out.push(Seg::Line(cx, y));
|
||||
cy = y;
|
||||
}
|
||||
b'C' => {
|
||||
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||
let s = Seg::Cubic(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy, v[4] + ox, v[5] + oy);
|
||||
out.push(s);
|
||||
(cx, cy) = (v[4] + ox, v[5] + oy);
|
||||
}
|
||||
b'Q' => {
|
||||
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
|
||||
out.push(Seg::Quad(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy));
|
||||
(cx, cy) = (v[2] + ox, v[3] + oy);
|
||||
}
|
||||
_ => return Err(PathError { at: i.saturating_sub(1), why: "only M L H V C Q Z are allowed" }),
|
||||
}
|
||||
if out.len() > MAX_SEGMENTS {
|
||||
return Err(PathError { at: i, why: "the path has too many segments" });
|
||||
}
|
||||
if !matches!(out.first(), Some(Seg::Move(..))) {
|
||||
return Err(PathError { at: 0, why: "a path starts with M" });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes segments as compact absolute path data.
|
||||
pub fn write(segs: &[Seg]) -> String {
|
||||
let mut s = String::new();
|
||||
let n = |v: f32| -> String {
|
||||
let r = (v * 1000.0).round() / 1000.0;
|
||||
if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") }
|
||||
};
|
||||
for seg in segs {
|
||||
if !s.is_empty() {
|
||||
s.push(' ');
|
||||
}
|
||||
let _ = match *seg {
|
||||
Seg::Move(x, y) => write!(s, "M{} {}", n(x), n(y)),
|
||||
Seg::Line(x, y) => write!(s, "L{} {}", n(x), n(y)),
|
||||
Seg::Quad(a, b, x, y) => write!(s, "Q{} {} {} {}", n(a), n(b), n(x), n(y)),
|
||||
Seg::Cubic(a, b, c, d, x, y) => write!(s, "C{} {} {} {} {} {}", n(a), n(b), n(c), n(d), n(x), n(y)),
|
||||
Seg::Close => write!(s, "Z"),
|
||||
};
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The control-point box (contains the curve).
|
||||
pub fn bounds(segs: &[Seg]) -> Option<[f32; 4]> {
|
||||
let mut b: Option<[f32; 4]> = None;
|
||||
let mut add = |x: f32, y: f32| {
|
||||
b = Some(match b {
|
||||
None => [x, y, x, y],
|
||||
Some([a, c, d, e]) => [a.min(x), c.min(y), d.max(x), e.max(y)],
|
||||
})
|
||||
};
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(x, y) | Seg::Line(x, y) => add(x, y),
|
||||
Seg::Quad(a, c, x, y) => {
|
||||
add(a, c);
|
||||
add(x, y)
|
||||
}
|
||||
Seg::Cubic(a, c, d, e, x, y) => {
|
||||
add(a, c);
|
||||
add(d, e);
|
||||
add(x, y)
|
||||
}
|
||||
Seg::Close => {}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
pub fn to_skia(segs: &[Seg]) -> Option<tiny_skia::Path> {
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(x, y) => pb.move_to(x, y),
|
||||
Seg::Line(x, y) => pb.line_to(x, y),
|
||||
Seg::Quad(a, b, x, y) => pb.quad_to(a, b, x, y),
|
||||
Seg::Cubic(a, b, c, d, x, y) => pb.cubic_to(a, b, c, d, x, y),
|
||||
Seg::Close => pb.close(),
|
||||
}
|
||||
}
|
||||
pb.finish()
|
||||
}
|
||||
|
||||
/// Bézier constant for a quarter circle.
|
||||
const K: f32 = 0.552_284_8;
|
||||
|
||||
pub fn rect(w: f32, h: f32, radius: f32) -> Vec<Seg> {
|
||||
let r = radius.max(0.0).min(w.abs() / 2.0).min(h.abs() / 2.0);
|
||||
if r <= 0.0 {
|
||||
return vec![Seg::Move(0.0, 0.0), Seg::Line(w, 0.0), Seg::Line(w, h), Seg::Line(0.0, h), Seg::Close];
|
||||
}
|
||||
let k = r * (1.0 - K);
|
||||
vec![
|
||||
Seg::Move(r, 0.0),
|
||||
Seg::Line(w - r, 0.0),
|
||||
Seg::Cubic(w - k, 0.0, w, k, w, r),
|
||||
Seg::Line(w, h - r),
|
||||
Seg::Cubic(w, h - k, w - k, h, w - r, h),
|
||||
Seg::Line(r, h),
|
||||
Seg::Cubic(k, h, 0.0, h - k, 0.0, h - r),
|
||||
Seg::Line(0.0, r),
|
||||
Seg::Cubic(0.0, k, k, 0.0, r, 0.0),
|
||||
Seg::Close,
|
||||
]
|
||||
}
|
||||
|
||||
pub fn ellipse(w: f32, h: f32) -> Vec<Seg> {
|
||||
let (rx, ry) = (w / 2.0, h / 2.0);
|
||||
let (cx, cy) = (rx, ry);
|
||||
let (kx, ky) = (rx * K, ry * K);
|
||||
vec![
|
||||
Seg::Move(cx + rx, cy),
|
||||
Seg::Cubic(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry),
|
||||
Seg::Cubic(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy),
|
||||
Seg::Cubic(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry),
|
||||
Seg::Cubic(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy),
|
||||
Seg::Close,
|
||||
]
|
||||
}
|
||||
|
||||
/// An arrow head at (x2, y2) pointing away from (x1, y1), for a line of width `w`.
|
||||
pub fn arrow_head(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> Vec<Seg> {
|
||||
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||
let (ux, uy) = (dx / len, dy / len);
|
||||
let size = (w * 4.0).max(8.0);
|
||||
let (bx, by) = (x2 - ux * size, y2 - uy * size);
|
||||
let (px, py) = (-uy * size * 0.5, ux * size * 0.5);
|
||||
vec![Seg::Move(x2, y2), Seg::Line(bx + px, by + py), Seg::Line(bx - px, by - py), Seg::Close]
|
||||
}
|
||||
|
||||
/// Where a line meets its arrow head (so the stroke stops under the head instead of poking through its tip).
|
||||
pub fn shorten(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> (f32, f32) {
|
||||
let (dx, dy) = (x2 - x1, y2 - y1);
|
||||
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
|
||||
let size = (w * 4.0).max(8.0) * 0.8;
|
||||
let t = (size / len).min(1.0);
|
||||
(x2 - dx * t, y2 - dy * t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_relative_and_writes_absolute() {
|
||||
let s = parse("m10 10 l5 0 h5 v-5 c1 1 2 2 3 3 q1 1 2 2 z").unwrap();
|
||||
assert_eq!(s[0], Seg::Move(10.0, 10.0));
|
||||
assert_eq!(s[1], Seg::Line(15.0, 10.0));
|
||||
assert_eq!(s[2], Seg::Line(20.0, 10.0));
|
||||
assert_eq!(s[3], Seg::Line(20.0, 5.0));
|
||||
assert_eq!(s[4], Seg::Cubic(21.0, 6.0, 22.0, 7.0, 23.0, 8.0));
|
||||
assert_eq!(write(&parse(&write(&s)).unwrap()), write(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_arcs_garbage_and_huge_numbers() {
|
||||
assert!(parse("M0 0 A 5 5 0 0 1 10 10").is_err());
|
||||
assert!(parse("M0 0 L x 1").is_err());
|
||||
assert!(parse("L 1 1").is_err());
|
||||
assert!(parse("M 1e39 0").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The core's painter: a display list to pixels with tiny-skia (PNG and JPG export, thumbnails, the fidelity
|
||||
//! reference). The face's canvas painter (`apps/desktop/src/editor/paint.ts`) follows the same rules.
|
||||
use crate::display::*;
|
||||
use crate::model::*;
|
||||
use crate::path;
|
||||
use std::collections::HashMap;
|
||||
use tiny_skia as sk;
|
||||
|
||||
fn tf(t: Tf) -> sk::Transform {
|
||||
sk::Transform::from_row(t[0], t[1], t[2], t[3], t[4], t[5])
|
||||
}
|
||||
|
||||
fn color(c: [u8; 4]) -> sk::Color {
|
||||
sk::Color::from_rgba8(c[0], c[1], c[2], c[3])
|
||||
}
|
||||
|
||||
fn shader(p: &DPaint) -> Option<sk::Shader<'static>> {
|
||||
let stops = |s: &[(f32, [u8; 4])]| s.iter().map(|(o, c)| sk::GradientStop::new(*o, color(*c))).collect::<Vec<_>>();
|
||||
match p {
|
||||
DPaint::Solid { c } => Some(sk::Shader::SolidColor(color(*c))),
|
||||
DPaint::Linear { x1, y1, x2, y2, stops: s } => sk::LinearGradient::new(
|
||||
sk::Point::from_xy(*x1, *y1),
|
||||
sk::Point::from_xy(*x2, *y2),
|
||||
stops(s),
|
||||
sk::SpreadMode::Pad,
|
||||
sk::Transform::identity(),
|
||||
)
|
||||
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||
DPaint::Radial { cx, cy, r, stops: s } => sk::RadialGradient::new(
|
||||
sk::Point::from_xy(*cx, *cy),
|
||||
0.0,
|
||||
sk::Point::from_xy(*cx, *cy),
|
||||
*r,
|
||||
stops(s),
|
||||
sk::SpreadMode::Pad,
|
||||
sk::Transform::identity(),
|
||||
)
|
||||
.or_else(|| s.last().map(|(_, c)| sk::Shader::SolidColor(color(*c)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Straight RGBA → a premultiplied pixmap.
|
||||
pub fn pixmap_of(r: &Raster) -> Option<sk::Pixmap> {
|
||||
let mut pm = sk::Pixmap::new(r.width, r.height)?;
|
||||
for (dst, src) in pm.pixels_mut().iter_mut().zip(r.rgba.as_chunks::<4>().0) {
|
||||
*dst = sk::ColorU8::from_rgba(src[0], src[1], src[2], src[3]).premultiply();
|
||||
}
|
||||
Some(pm)
|
||||
}
|
||||
|
||||
/// A premultiplied pixmap → straight RGBA.
|
||||
pub fn raster_of(pm: &sk::Pixmap) -> Raster {
|
||||
let mut rgba = Vec::with_capacity(pm.data().len());
|
||||
for p in pm.pixels() {
|
||||
let c = p.demultiply();
|
||||
rgba.extend_from_slice(&[c.red(), c.green(), c.blue(), c.alpha()]);
|
||||
}
|
||||
Raster { width: pm.width(), height: pm.height(), rgba }
|
||||
}
|
||||
|
||||
/// Paints a display list at `scale` pixels per point. `assets` are the document's pixels.
|
||||
pub fn paint(
|
||||
list: &DisplayList,
|
||||
assets: &std::collections::BTreeMap<String, Raster>,
|
||||
scale: f32,
|
||||
) -> Option<sk::Pixmap> {
|
||||
let w = (list.width * scale).round().max(1.0) as u32;
|
||||
let h = (list.height * scale).round().max(1.0) as u32;
|
||||
let mut stack: Vec<(sk::Pixmap, f32)> = vec![(sk::Pixmap::new(w, h)?, 1.0)];
|
||||
if let Some(bg) = list.background {
|
||||
stack[0].0.fill(color(bg));
|
||||
}
|
||||
let base: Tf = [scale, 0.0, 0.0, scale, 0.0, 0.0];
|
||||
let mut images: HashMap<&str, sk::Pixmap> = HashMap::new();
|
||||
let glyph_paths: Vec<Option<sk::Path>> =
|
||||
list.glyphs.iter().map(|g| path::parse(&g.d).ok().and_then(|s| path::to_skia(&s))).collect();
|
||||
for item in &list.items {
|
||||
match item {
|
||||
Item::Push { opacity } => stack.push((sk::Pixmap::new(w, h)?, *opacity)),
|
||||
Item::Pop => {
|
||||
if stack.len() > 1 {
|
||||
let (top, opacity) = stack.pop()?;
|
||||
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||
}
|
||||
}
|
||||
Item::Fill { d, t, paint, even_odd, .. } => {
|
||||
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let Some(sh) = shader(paint) else { continue };
|
||||
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||
let rule = if *even_odd { sk::FillRule::EvenOdd } else { sk::FillRule::Winding };
|
||||
stack.last_mut()?.0.fill_path(&p, &pt, rule, tf(mul(base, *t)), None);
|
||||
}
|
||||
Item::Stroke { d, t, paint, width, cap, join, dash, .. } => {
|
||||
let Some(p) = path::parse(d).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let Some(sh) = shader(paint) else { continue };
|
||||
let pt = sk::Paint { shader: sh, anti_alias: true, ..Default::default() };
|
||||
let stroke = sk::Stroke {
|
||||
width: *width,
|
||||
line_cap: match cap {
|
||||
Cap::Butt => sk::LineCap::Butt,
|
||||
Cap::Round => sk::LineCap::Round,
|
||||
Cap::Square => sk::LineCap::Square,
|
||||
},
|
||||
line_join: match join {
|
||||
Join::Miter => sk::LineJoin::Miter,
|
||||
Join::Round => sk::LineJoin::Round,
|
||||
Join::Bevel => sk::LineJoin::Bevel,
|
||||
},
|
||||
miter_limit: 10.0,
|
||||
dash: if dash.len() >= 2 && dash.iter().all(|v| *v >= 0.0) && dash.iter().any(|v| *v > 0.0) {
|
||||
let mut d = dash.clone();
|
||||
if d.len() % 2 == 1 {
|
||||
d.extend_from_within(..);
|
||||
}
|
||||
sk::StrokeDash::new(d, 0.0)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
stack.last_mut()?.0.stroke_path(&p, &pt, &stroke, tf(mul(base, *t)), None);
|
||||
}
|
||||
Item::Image { asset, t, clip, clip_t, smooth, .. } => {
|
||||
let Some(r) = assets.get(asset) else { continue };
|
||||
if !images.contains_key(asset.as_str()) {
|
||||
images.insert(asset.as_str(), pixmap_of(r)?);
|
||||
}
|
||||
let img = &images[asset.as_str()];
|
||||
let full = mul(base, *t);
|
||||
let exact = !*smooth
|
||||
&& full[1] == 0.0
|
||||
&& full[2] == 0.0
|
||||
&& (full[0] - 1.0).abs() < 1e-4
|
||||
&& (full[3] - 1.0).abs() < 1e-4;
|
||||
let quality = if exact { sk::FilterQuality::Nearest } else { sk::FilterQuality::Bilinear };
|
||||
let mask = match clip {
|
||||
Some(cd) => {
|
||||
let Some(cp) = path::parse(cd).ok().and_then(|s| path::to_skia(&s)) else { continue };
|
||||
let mut m = sk::Mask::new(w, h)?;
|
||||
m.fill_path(&cp, sk::FillRule::Winding, true, tf(mul(base, *clip_t)));
|
||||
Some(m)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let pt = sk::Paint {
|
||||
shader: sk::Pattern::new(
|
||||
img.as_ref(),
|
||||
sk::SpreadMode::Pad,
|
||||
quality,
|
||||
1.0,
|
||||
sk::Transform::identity(),
|
||||
),
|
||||
anti_alias: true,
|
||||
..Default::default()
|
||||
};
|
||||
let rect = sk::Rect::from_xywh(0.0, 0.0, img.width() as f32, img.height() as f32)?;
|
||||
stack.last_mut()?.0.fill_rect(rect, &pt, tf(full), mask.as_ref());
|
||||
}
|
||||
Item::Text { t, color: c, size, glyphs, .. } => {
|
||||
let pt =
|
||||
sk::Paint { shader: sk::Shader::SolidColor(color(*c)), anti_alias: true, ..Default::default() };
|
||||
for g in glyphs {
|
||||
let Some(gi) = g.g else { continue };
|
||||
let Some(Some(p)) = glyph_paths.get(gi as usize) else { continue };
|
||||
let upem = list.glyphs[gi as usize].upem;
|
||||
let s = size / upem;
|
||||
let gt = mul(base, mul(*t, [s, 0.0, 0.0, -s, g.x, g.y]));
|
||||
stack.last_mut()?.0.fill_path(p, &pt, sk::FillRule::Winding, tf(gt), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while stack.len() > 1 {
|
||||
let (top, opacity) = stack.pop()?;
|
||||
let pp = sk::PixmapPaint { opacity, ..Default::default() };
|
||||
stack.last_mut()?.0.draw_pixmap(0, 0, top.as_ref(), &pp, sk::Transform::identity(), None);
|
||||
}
|
||||
stack.pop().map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// A page rendered to straight RGBA at `scale` pixels per point.
|
||||
pub fn page(doc: &Document, page: &Page, book: &crate::text::FontBook, scale: f32) -> Option<Raster> {
|
||||
let list = build(doc, page, book);
|
||||
paint(&list, &doc.assets, scale).map(|p| raster_of(&p))
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! SVG import with usvg: paths (with their fills, strokes and gradients), images and text (as outlines) become vector
|
||||
//! objects in one group, scaled from CSS pixels to points. Runs in the worker: an SVG is an outside file.
|
||||
use crate::model::*;
|
||||
use crate::path::{self, Seg};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SvgError {
|
||||
#[error("This SVG could not be read: {0}")]
|
||||
Parse(String),
|
||||
#[error("This SVG is too large to import.")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// The most objects one import makes.
|
||||
const MAX_OBJECTS: usize = 50_000;
|
||||
|
||||
struct Ctx {
|
||||
doc: Document,
|
||||
count: usize,
|
||||
images: u32,
|
||||
}
|
||||
|
||||
fn rgba(c: usvg::Color, opacity: f32) -> Rgba {
|
||||
Rgba([c.red, c.green, c.blue, (opacity.clamp(0.0, 1.0) * 255.0).round() as u8])
|
||||
}
|
||||
|
||||
fn paint(p: &usvg::Paint, opacity: f32, ts: tiny_skia::Transform, bbox: [f32; 4]) -> Option<Paint> {
|
||||
let [bx, by, bw, bh] = bbox;
|
||||
let frac = |x: f32, y: f32| -> (f32, f32) {
|
||||
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||
ts.map_point(&mut pt);
|
||||
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||
};
|
||||
let stops = |s: &[usvg::Stop]| {
|
||||
s.iter()
|
||||
.map(|s| Stop { offset: s.offset().get(), color: rgba(s.color(), s.opacity().get() * opacity) })
|
||||
.collect()
|
||||
};
|
||||
match p {
|
||||
usvg::Paint::Color(c) => Some(Paint::Solid { color: rgba(*c, opacity) }),
|
||||
usvg::Paint::LinearGradient(g) => {
|
||||
let t = ts.pre_concat(g.transform());
|
||||
let frac = |x: f32, y: f32| {
|
||||
let mut pt = tiny_skia::Point::from_xy(x, y);
|
||||
t.map_point(&mut pt);
|
||||
((pt.x - bx) / bw.max(1e-3), (pt.y - by) / bh.max(1e-3))
|
||||
};
|
||||
let (x1, y1) = frac(g.x1(), g.y1());
|
||||
let (x2, y2) = frac(g.x2(), g.y2());
|
||||
Some(Paint::Linear { x1, y1, x2, y2, stops: stops(g.stops()) })
|
||||
}
|
||||
usvg::Paint::RadialGradient(g) => {
|
||||
let t = ts.pre_concat(g.transform());
|
||||
let mut c = tiny_skia::Point::from_xy(g.cx(), g.cy());
|
||||
t.map_point(&mut c);
|
||||
let (sx, sy) = t.get_scale();
|
||||
let r = g.r().get() * sx.max(sy);
|
||||
let _ = frac;
|
||||
Some(Paint::Radial {
|
||||
cx: (c.x - bx) / bw.max(1e-3),
|
||||
cy: (c.y - by) / bh.max(1e-3),
|
||||
r: r / bw.abs().max(bh.abs()).max(1e-3),
|
||||
stops: stops(g.stops()),
|
||||
})
|
||||
}
|
||||
// Patterns are not kept: their first colour stands in.
|
||||
usvg::Paint::Pattern(_) => Some(Paint::Solid { color: Rgba([128, 128, 128, (opacity * 255.0) as u8]) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(ctx: &mut Ctx, shape: Shape) -> Object {
|
||||
Object {
|
||||
id: ctx.doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
fn group(ctx: &mut Ctx, g: &usvg::Group, out: &mut Vec<Object>) -> Result<(), SvgError> {
|
||||
for node in g.children() {
|
||||
ctx.count += 1;
|
||||
if ctx.count > MAX_OBJECTS {
|
||||
return Err(SvgError::TooLarge);
|
||||
}
|
||||
match node {
|
||||
usvg::Node::Group(child) => {
|
||||
if child.opacity().get() < 0.999 {
|
||||
let mut inner = Vec::new();
|
||||
group(ctx, child, &mut inner)?;
|
||||
let mut o = object(ctx, Shape::Group { objects: inner });
|
||||
o.opacity = child.opacity().get();
|
||||
out.push(o);
|
||||
} else {
|
||||
group(ctx, child, out)?;
|
||||
}
|
||||
}
|
||||
usvg::Node::Path(p) => {
|
||||
if !p.is_visible() {
|
||||
continue;
|
||||
}
|
||||
let ts = p.abs_transform();
|
||||
let mut segs = Vec::new();
|
||||
for s in p.data().segments() {
|
||||
let map = |pt: tiny_skia::Point| {
|
||||
let mut q = pt;
|
||||
ts.map_point(&mut q);
|
||||
(q.x, q.y)
|
||||
};
|
||||
segs.push(match s {
|
||||
tiny_skia::PathSegment::MoveTo(a) => {
|
||||
let (x, y) = map(a);
|
||||
Seg::Move(x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::LineTo(a) => {
|
||||
let (x, y) = map(a);
|
||||
Seg::Line(x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::QuadTo(a, b) => {
|
||||
let ((ax, ay), (x, y)) = (map(a), map(b));
|
||||
Seg::Quad(ax, ay, x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::CubicTo(a, b, c) => {
|
||||
let ((ax, ay), (bx, by), (x, y)) = (map(a), map(b), map(c));
|
||||
Seg::Cubic(ax, ay, bx, by, x, y)
|
||||
}
|
||||
tiny_skia::PathSegment::Close => Seg::Close,
|
||||
});
|
||||
}
|
||||
let Some(b) = path::bounds(&segs) else { continue };
|
||||
let bbox = [b[0], b[1], b[2] - b[0], b[3] - b[1]];
|
||||
let mut o = object(ctx, Shape::Path { d: path::write(&segs) });
|
||||
if let Some(f) = p.fill() {
|
||||
o.fill = paint(f.paint(), f.opacity().get(), ts, bbox);
|
||||
}
|
||||
if let Some(s) = p.stroke() {
|
||||
let (sx, sy) = ts.get_scale();
|
||||
let k = (sx * sy).abs().sqrt();
|
||||
o.stroke = paint(s.paint(), s.opacity().get(), ts, bbox).map(|pt| Stroke {
|
||||
paint: pt,
|
||||
width: s.width().get() * k,
|
||||
dash: s.dasharray().map(|d| d.iter().map(|v| v * k).collect()).unwrap_or_default(),
|
||||
cap: match s.linecap() {
|
||||
usvg::LineCap::Butt => Cap::Butt,
|
||||
usvg::LineCap::Round => Cap::Round,
|
||||
usvg::LineCap::Square => Cap::Square,
|
||||
},
|
||||
join: match s.linejoin() {
|
||||
usvg::LineJoin::Round => Join::Round,
|
||||
usvg::LineJoin::Bevel => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
},
|
||||
});
|
||||
}
|
||||
if o.fill.is_some() || o.stroke.is_some() {
|
||||
out.push(o);
|
||||
}
|
||||
}
|
||||
usvg::Node::Image(im) => {
|
||||
if !im.is_visible() {
|
||||
continue;
|
||||
}
|
||||
let data: Option<&Arc<Vec<u8>>> = match im.kind() {
|
||||
usvg::ImageKind::PNG(d)
|
||||
| usvg::ImageKind::JPEG(d)
|
||||
| usvg::ImageKind::GIF(d)
|
||||
| usvg::ImageKind::WEBP(d) => Some(d),
|
||||
_ => None,
|
||||
};
|
||||
let Some(data) = data else { continue };
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(data.as_slice()));
|
||||
reader = match reader.with_guessed_format() {
|
||||
Ok(r) => r,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let mut l = image::Limits::default();
|
||||
l.max_image_width = Some(12_000);
|
||||
l.max_image_height = Some(12_000);
|
||||
l.max_alloc = Some(600 << 20);
|
||||
reader.limits(l);
|
||||
let Ok(img) = reader.decode() else { continue };
|
||||
let rgba_img = img.into_rgba8();
|
||||
ctx.images += 1;
|
||||
let asset = format!("s{}", ctx.images);
|
||||
let (pw, ph) = (rgba_img.width(), rgba_img.height());
|
||||
ctx.doc.assets.insert(asset.clone(), Raster { width: pw, height: ph, rgba: rgba_img.into_raw() });
|
||||
let size = im.size();
|
||||
let t = im.abs_transform();
|
||||
let mut o = object(
|
||||
ctx,
|
||||
Shape::Image {
|
||||
asset,
|
||||
w: size.width(),
|
||||
h: size.height(),
|
||||
crop: Rect { x: 0.0, y: 0.0, w: size.width(), h: size.height() },
|
||||
},
|
||||
);
|
||||
o.transform = [t.sx, t.ky, t.kx, t.sy, t.tx, t.ty];
|
||||
out.push(o);
|
||||
}
|
||||
usvg::Node::Text(t) => group(ctx, t.flattened(), out)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The SVG as a document: one page of the SVG's size (in points), one vector layer holding one group.
|
||||
pub fn import(data: &[u8], fontdb: Arc<fontdb::Database>) -> Result<Document, SvgError> {
|
||||
if data.len() > 64 << 20 {
|
||||
return Err(SvgError::TooLarge);
|
||||
}
|
||||
let opt = usvg::Options { fontdb, ..Default::default() };
|
||||
let tree = usvg::Tree::from_data(data, &opt).map_err(|e| SvgError::Parse(e.to_string()))?;
|
||||
let size = tree.size();
|
||||
let px_to_pt = 0.75;
|
||||
let mut ctx = Ctx { doc: Document::default(), count: 0, images: 0 };
|
||||
let mut objects = Vec::new();
|
||||
group(&mut ctx, tree.root(), &mut objects)?;
|
||||
let mut g = object(&mut ctx, Shape::Group { objects });
|
||||
g.name = "SVG".into();
|
||||
g.transform = [px_to_pt, 0.0, 0.0, px_to_pt, 0.0, 0.0];
|
||||
let pid = ctx.doc.new_id();
|
||||
let lid = ctx.doc.new_id();
|
||||
let mut layer = Layer::vector(lid, "SVG");
|
||||
layer.kind = LayerKind::Vector { objects: vec![g] };
|
||||
ctx.doc.pages.push(Page {
|
||||
id: pid,
|
||||
width: (size.width() * px_to_pt).clamp(1.0, 14_400.0),
|
||||
height: (size.height() * px_to_pt).clamp(1.0, 14_400.0),
|
||||
margins: [0.0; 4],
|
||||
guides: Vec::new(),
|
||||
background: None,
|
||||
layers: vec![layer],
|
||||
});
|
||||
Ok(ctx.doc)
|
||||
}
|
||||
|
||||
/// The system fonts as usvg wants them (for SVG text).
|
||||
pub fn system_fontdb() -> Arc<fontdb::Database> {
|
||||
let mut db = fontdb::Database::new();
|
||||
db.load_system_fonts();
|
||||
Arc::new(db)
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Text: the font book (system fonts through fontdb, plus fonts stored in documents), shaping with rustybuzz, line
|
||||
//! breaking and alignment, glyph outlines with ttf-parser. Both painters and every export use the same layout.
|
||||
use crate::model::{Align, TextStyle};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// A loaded font face: its data, where it came from and what its licence allows.
|
||||
pub struct Font {
|
||||
pub data: Arc<Vec<u8>>,
|
||||
pub index: u32,
|
||||
pub family: String,
|
||||
pub post_script_name: String,
|
||||
pub weight: u16,
|
||||
pub italic: bool,
|
||||
pub units_per_em: f32,
|
||||
pub ascender: f32,
|
||||
pub descender: f32,
|
||||
pub cap_height: f32,
|
||||
pub embedding: Embedding,
|
||||
/// The file is OpenType with CFF outlines (else TrueType).
|
||||
pub cff: bool,
|
||||
}
|
||||
|
||||
/// What the font's OS/2 `fsType` allows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Embedding {
|
||||
/// Installable or editable: may be stored in a document and embedded in a PDF.
|
||||
Editable,
|
||||
/// Preview and print: may be embedded in a PDF, not stored for editing.
|
||||
PrintOnly,
|
||||
/// Restricted licence, or bitmap-only embedding: may not be embedded.
|
||||
Forbidden(&'static str),
|
||||
}
|
||||
|
||||
pub type FontKey = usize;
|
||||
|
||||
/// A glyph's outline as path data, or none for an empty glyph.
|
||||
type Outlined = Option<Arc<str>>;
|
||||
|
||||
/// The fonts Pictor can use. Cheap to share between threads.
|
||||
pub struct FontBook {
|
||||
db: RwLock<fontdb::Database>,
|
||||
loaded: RwLock<Vec<Arc<Font>>>,
|
||||
by_id: RwLock<HashMap<fontdb::ID, FontKey>>,
|
||||
outlines: RwLock<HashMap<(FontKey, u16), Outlined>>,
|
||||
}
|
||||
|
||||
/// Fallbacks for characters the chosen font lacks, in order.
|
||||
const FALLBACKS: &[&str] =
|
||||
&["Segoe UI", "Arial", "Segoe UI Symbol", "Segoe UI Emoji", "DejaVu Sans", "Liberation Sans"];
|
||||
|
||||
impl Default for FontBook {
|
||||
fn default() -> Self {
|
||||
FontBook::empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl FontBook {
|
||||
pub fn empty() -> FontBook {
|
||||
FontBook {
|
||||
db: RwLock::new(fontdb::Database::new()),
|
||||
loaded: RwLock::new(Vec::new()),
|
||||
by_id: RwLock::new(HashMap::new()),
|
||||
outlines: RwLock::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The system's fonts (Windows: the Fonts folder and the per-user fonts folder).
|
||||
pub fn system() -> FontBook {
|
||||
let book = FontBook::empty();
|
||||
{
|
||||
let mut db = book.db.write().unwrap();
|
||||
db.load_system_fonts();
|
||||
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
|
||||
let user = std::path::Path::new(&local).join("Microsoft").join("Windows").join("Fonts");
|
||||
if user.is_dir() {
|
||||
db.load_fonts_dir(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
book
|
||||
}
|
||||
|
||||
/// Adds a font from memory (a font stored in a document). Returns false when it is not a font.
|
||||
pub fn add(&self, data: Vec<u8>) -> bool {
|
||||
if ttf_parser::Face::parse(&data, 0).is_err() {
|
||||
return false;
|
||||
}
|
||||
self.db.write().unwrap().load_font_data(data);
|
||||
true
|
||||
}
|
||||
|
||||
/// Family names, sorted, without duplicates.
|
||||
pub fn families(&self) -> Vec<String> {
|
||||
let db = self.db.read().unwrap();
|
||||
let mut v: Vec<String> = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).collect();
|
||||
v.sort_by_key(|s| s.to_lowercase());
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// The closest face of a family (none when the family is not installed).
|
||||
pub fn find(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||
let id = {
|
||||
let db = self.db.read().unwrap();
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(family)],
|
||||
weight: fontdb::Weight(weight),
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
let id = db.query(&q)?;
|
||||
// fontdb falls back to any face when nothing matches the name; insist on the family.
|
||||
let face = db.face(id)?;
|
||||
if !face.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(family)) {
|
||||
return None;
|
||||
}
|
||||
id
|
||||
};
|
||||
self.load(id)
|
||||
}
|
||||
|
||||
/// The face for a style, falling back to Segoe UI, then Arial, then any face.
|
||||
pub fn resolve(&self, family: &str, weight: u16, italic: bool) -> Option<FontKey> {
|
||||
self.find(family, weight, italic)
|
||||
.or_else(|| FALLBACKS.iter().find_map(|f| self.find(f, weight, italic)))
|
||||
.or_else(|| {
|
||||
let id = self.db.read().unwrap().faces().next().map(|f| f.id)?;
|
||||
self.load(id)
|
||||
})
|
||||
}
|
||||
|
||||
fn load(&self, id: fontdb::ID) -> Option<FontKey> {
|
||||
if let Some(k) = self.by_id.read().unwrap().get(&id) {
|
||||
return Some(*k);
|
||||
}
|
||||
let (data, index, family, psn) = {
|
||||
let db = self.db.read().unwrap();
|
||||
let info = db.face(id)?;
|
||||
let family = info.families.first().map(|(n, _)| n.clone()).unwrap_or_default();
|
||||
let psn = info.post_script_name.clone();
|
||||
let index = info.index;
|
||||
let data = db.with_face_data(id, |d, _| d.to_vec())?;
|
||||
(data, index, family, psn)
|
||||
};
|
||||
let face = ttf_parser::Face::parse(&data, index).ok()?;
|
||||
let embedding = if !face.is_outline_embedding_allowed() {
|
||||
Embedding::Forbidden("its licence allows only bitmap embedding")
|
||||
} else {
|
||||
match face.permissions() {
|
||||
Some(ttf_parser::Permissions::Restricted) => {
|
||||
Embedding::Forbidden("its licence forbids embedding (fsType: restricted)")
|
||||
}
|
||||
Some(ttf_parser::Permissions::PreviewAndPrint) => Embedding::PrintOnly,
|
||||
_ => Embedding::Editable,
|
||||
}
|
||||
};
|
||||
let font = Font {
|
||||
index,
|
||||
family,
|
||||
post_script_name: psn,
|
||||
weight: face.weight().to_number(),
|
||||
italic: face.is_italic(),
|
||||
units_per_em: face.units_per_em() as f32,
|
||||
ascender: face.ascender() as f32,
|
||||
descender: face.descender() as f32,
|
||||
cap_height: face.capital_height().unwrap_or(face.ascender()) as f32,
|
||||
cff: face.tables().cff.is_some(),
|
||||
embedding,
|
||||
data: Arc::new(data),
|
||||
};
|
||||
let mut loaded = self.loaded.write().unwrap();
|
||||
let key = loaded.len();
|
||||
loaded.push(Arc::new(font));
|
||||
self.by_id.write().unwrap().insert(id, key);
|
||||
Some(key)
|
||||
}
|
||||
|
||||
pub fn font(&self, key: FontKey) -> Arc<Font> {
|
||||
self.loaded.read().unwrap()[key].clone()
|
||||
}
|
||||
|
||||
fn has_glyph(&self, key: FontKey, c: char) -> bool {
|
||||
let f = self.font(key);
|
||||
ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| face.glyph_index(c)).is_some()
|
||||
}
|
||||
|
||||
/// A glyph's outline as path data in font units (y up), or none for an empty glyph (a space).
|
||||
pub fn outline(&self, key: FontKey, gid: u16) -> Option<Arc<str>> {
|
||||
if let Some(o) = self.outlines.read().unwrap().get(&(key, gid)) {
|
||||
return o.clone();
|
||||
}
|
||||
let f = self.font(key);
|
||||
let out = ttf_parser::Face::parse(&f.data, f.index).ok().and_then(|face| {
|
||||
let mut b = Outline(String::new());
|
||||
face.outline_glyph(ttf_parser::GlyphId(gid), &mut b)?;
|
||||
Some(Arc::<str>::from(b.0))
|
||||
});
|
||||
self.outlines.write().unwrap().insert((key, gid), out.clone());
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
struct Outline(String);
|
||||
|
||||
impl ttf_parser::OutlineBuilder for Outline {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "M{x} {y}");
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "L{x} {y}");
|
||||
}
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "Q{x1} {y1} {x} {y}");
|
||||
}
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
|
||||
let _ = write!(self.0, "C{x1} {y1} {x2} {y2} {x} {y}");
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.0.push('Z');
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph placed in a text box: `x` from the box's left, on its line's baseline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Glyph {
|
||||
pub font: FontKey,
|
||||
pub gid: u16,
|
||||
pub x: f32,
|
||||
pub advance: f32,
|
||||
/// The characters this glyph stands for (the whole cluster on its first glyph, empty on the rest).
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Line {
|
||||
pub baseline: f32,
|
||||
pub glyphs: Vec<Glyph>,
|
||||
/// From the first glyph to the end of the last visible one.
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Layout {
|
||||
pub lines: Vec<Line>,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub size: f32,
|
||||
/// The face the style asked for (or its fallback): the one the box's metrics come from.
|
||||
pub primary: Option<FontKey>,
|
||||
}
|
||||
|
||||
struct Shaped {
|
||||
font: FontKey,
|
||||
gid: u16,
|
||||
advance: f32,
|
||||
/// Index of the cluster's first char in the paragraph.
|
||||
cluster: usize,
|
||||
}
|
||||
|
||||
/// Lays out a text box `w` points wide (0 = no wrapping).
|
||||
pub fn layout(book: &FontBook, text: &str, style: &TextStyle, w: f32) -> Layout {
|
||||
let size = style.size;
|
||||
let primary = book.resolve(&style.family, style.weight, style.italic);
|
||||
let line_box = size * style.line_height;
|
||||
let (asc, desc) = match primary {
|
||||
Some(k) => {
|
||||
let f = book.font(k);
|
||||
(f.ascender * size / f.units_per_em, -f.descender * size / f.units_per_em)
|
||||
}
|
||||
None => (size * 0.8, size * 0.2),
|
||||
};
|
||||
let baseline_in_box = (line_box - (asc + desc)) / 2.0 + asc;
|
||||
let mut lines = Vec::new();
|
||||
for para in text.split('\n') {
|
||||
let para = para.strip_suffix('\r').unwrap_or(para);
|
||||
let chars: Vec<char> = para.chars().collect();
|
||||
let shaped = match primary {
|
||||
Some(p) => shape(book, &chars, p, style),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let mut start = 0;
|
||||
let is_space = |g: &Shaped| chars.get(g.cluster).is_some_and(|c| c.is_whitespace());
|
||||
let breaks_after = |g: &Shaped| {
|
||||
chars.get(g.cluster).is_some_and(|c| c.is_whitespace() || *c == '-' || *c == '\u{2010}' || *c == '/')
|
||||
};
|
||||
let mut para_lines: Vec<(usize, usize)> = Vec::new();
|
||||
while start < shaped.len() {
|
||||
let mut x = 0.0;
|
||||
let mut end = shaped.len();
|
||||
let mut last_break: Option<usize> = None;
|
||||
for (i, g) in shaped.iter().enumerate().skip(start) {
|
||||
let fits = w <= 0.0 || x + g.advance <= w + 0.01 || is_space(g);
|
||||
if !fits {
|
||||
end = match last_break {
|
||||
Some(b) => b + 1,
|
||||
None if i > start => i,
|
||||
None => i + 1,
|
||||
};
|
||||
break;
|
||||
}
|
||||
x += g.advance;
|
||||
if breaks_after(g) {
|
||||
last_break = Some(i);
|
||||
}
|
||||
}
|
||||
// A break never splits a cluster.
|
||||
while end < shaped.len() && end > start + 1 && shaped[end].cluster == shaped[end - 1].cluster {
|
||||
end -= 1;
|
||||
}
|
||||
para_lines.push((start, end));
|
||||
start = end;
|
||||
}
|
||||
if para_lines.is_empty() {
|
||||
para_lines.push((0, 0));
|
||||
}
|
||||
let n = para_lines.len();
|
||||
for (li, (s, e)) in para_lines.into_iter().enumerate() {
|
||||
let slice = &shaped[s..e];
|
||||
let visible_end = slice.iter().rposition(|g| !is_space(g)).map(|i| i + 1).unwrap_or(0);
|
||||
let natural: f32 = slice[..visible_end].iter().map(|g| g.advance).sum();
|
||||
let spaces = slice[..visible_end].iter().filter(|g| is_space(g)).count();
|
||||
let last = li + 1 == n;
|
||||
let (offset, extra) = match style.align {
|
||||
_ if w <= 0.0 => (0.0, 0.0),
|
||||
Align::Left => (0.0, 0.0),
|
||||
Align::Center => ((w - natural) / 2.0, 0.0),
|
||||
Align::Right => (w - natural, 0.0),
|
||||
Align::Justify if !last && spaces > 0 => (0.0, (w - natural) / spaces as f32),
|
||||
Align::Justify => (0.0, 0.0),
|
||||
};
|
||||
let mut x = offset;
|
||||
let mut glyphs = Vec::with_capacity(slice.len());
|
||||
for (i, g) in slice.iter().enumerate() {
|
||||
let first_of_cluster = i == 0 || slice[i - 1].cluster != g.cluster;
|
||||
let next =
|
||||
slice.get(i + 1..).and_then(|r| r.iter().find(|n| n.cluster != g.cluster)).map(|n| n.cluster);
|
||||
let next = next.unwrap_or_else(|| shaped.get(e).map(|n| n.cluster).unwrap_or(chars.len()));
|
||||
let text: String = if first_of_cluster && next > g.cluster {
|
||||
chars[g.cluster..next].iter().collect()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let mut advance = g.advance;
|
||||
if extra > 0.0 && i < visible_end && is_space(g) {
|
||||
advance += extra;
|
||||
}
|
||||
glyphs.push(Glyph { font: g.font, gid: g.gid, x, advance, text });
|
||||
x += advance;
|
||||
}
|
||||
let width = if visible_end == 0 {
|
||||
0.0
|
||||
} else {
|
||||
glyphs[visible_end - 1].x + glyphs[visible_end - 1].advance - offset
|
||||
};
|
||||
let baseline = lines.len() as f32 * line_box + baseline_in_box;
|
||||
lines.push(Line { baseline, glyphs, width });
|
||||
}
|
||||
}
|
||||
let width = if w > 0.0 { w } else { lines.iter().map(|l| l.width).fold(0.0, f32::max) };
|
||||
Layout { height: lines.len() as f32 * line_box, lines, width, size, primary }
|
||||
}
|
||||
|
||||
/// Shapes a paragraph, splitting it into runs by the font that has each character.
|
||||
fn shape(book: &FontBook, chars: &[char], primary: FontKey, style: &TextStyle) -> Vec<Shaped> {
|
||||
let mut fonts: Vec<FontKey> = Vec::with_capacity(chars.len());
|
||||
let mut fallback_cache: HashMap<char, FontKey> = HashMap::new();
|
||||
for &c in chars {
|
||||
let k = if c.is_whitespace() || c.is_control() || book.has_glyph(primary, c) {
|
||||
primary
|
||||
} else {
|
||||
*fallback_cache.entry(c).or_insert_with(|| {
|
||||
FALLBACKS
|
||||
.iter()
|
||||
.filter_map(|f| book.find(f, style.weight, style.italic))
|
||||
.find(|k| book.has_glyph(*k, c))
|
||||
.unwrap_or(primary)
|
||||
})
|
||||
};
|
||||
fonts.push(k);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let k = fonts[i];
|
||||
let mut j = i + 1;
|
||||
while j < chars.len() && fonts[j] == k {
|
||||
j += 1;
|
||||
}
|
||||
let run: String = chars[i..j].iter().collect();
|
||||
// Byte offset in the run → char index in the paragraph.
|
||||
let mut byte_to_char = vec![0usize; run.len() + 1];
|
||||
for (ci, (b, _)) in run.char_indices().enumerate() {
|
||||
byte_to_char[b] = i + ci;
|
||||
}
|
||||
let f = book.font(k);
|
||||
if let Some(face) = rustybuzz::Face::from_slice(&f.data, f.index) {
|
||||
let mut buf = rustybuzz::UnicodeBuffer::new();
|
||||
buf.push_str(&run);
|
||||
buf.set_direction(rustybuzz::Direction::LeftToRight);
|
||||
buf.guess_segment_properties();
|
||||
let shaped = rustybuzz::shape(&face, &[], buf);
|
||||
let scale = style.size / f.units_per_em;
|
||||
let infos = shaped.glyph_infos();
|
||||
for (gi, (info, pos)) in infos.iter().zip(shaped.glyph_positions()).enumerate() {
|
||||
let cluster = byte_to_char[info.cluster as usize];
|
||||
let starts_cluster = gi == 0 || infos[gi - 1].cluster != info.cluster;
|
||||
let mut advance = pos.x_advance as f32 * scale;
|
||||
if starts_cluster {
|
||||
advance += style.letter_spacing;
|
||||
}
|
||||
out.push(Shaped { font: k, gid: info.glyph_id as u16, advance, cluster });
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! Bitmap tools: fill tolerance, magic wand, lasso, delete, brush clipped by a selection, adjustments' identities,
|
||||
//! the clone stamp, and exact undo of a pixel edit.
|
||||
use pictor_doc::bitmap::{self, Adjust, Brush, Mask};
|
||||
use pictor_doc::ops::History;
|
||||
use pictor_doc::*;
|
||||
|
||||
/// Left half red, right half a slightly different red, with a black wall at x = 30.
|
||||
fn two_reds() -> Raster {
|
||||
let mut r = Raster::new(60, 40);
|
||||
for y in 0..40 {
|
||||
for x in 0..60 {
|
||||
let i = (y * 60 + x) * 4;
|
||||
let c = if x == 30 {
|
||||
[0, 0, 0, 255]
|
||||
} else if x < 30 {
|
||||
[200, 20, 20, 255]
|
||||
} else {
|
||||
[206, 24, 20, 255]
|
||||
};
|
||||
r.rgba[i..i + 4].copy_from_slice(&c);
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_respects_tolerance_and_walls() {
|
||||
let mut r = two_reds();
|
||||
bitmap::fill(&mut r, 5, 5, 0, [0, 0, 255, 255], None);
|
||||
assert_eq!(r.pixel(29, 39), [0, 0, 255, 255]);
|
||||
assert_eq!(r.pixel(30, 5), [0, 0, 0, 255], "the wall stays");
|
||||
assert_eq!(r.pixel(40, 5), [206, 24, 20, 255], "behind the wall nothing changes");
|
||||
// Without the wall, tolerance 10 takes the near red too, tolerance 0 does not.
|
||||
let mut r = two_reds();
|
||||
for y in 0..40 {
|
||||
let i = (y * 60 + 30) * 4;
|
||||
r.rgba[i..i + 4].copy_from_slice(&[203, 22, 20, 255]);
|
||||
}
|
||||
let mut strict = r.clone();
|
||||
bitmap::fill(&mut strict, 5, 5, 0, [0, 255, 0, 255], None);
|
||||
assert_eq!(strict.pixel(45, 5), [206, 24, 20, 255]);
|
||||
bitmap::fill(&mut r, 5, 5, 10, [0, 255, 0, 255], None);
|
||||
assert_eq!(r.pixel(45, 5), [0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wand_selects_a_region_and_delete_clears_only_it() {
|
||||
let mut r = two_reds();
|
||||
let m = bitmap::region(&r, 5, 5, 0);
|
||||
assert_eq!(m.bbox(), PixelRect { x: 0, y: 0, w: 30, h: 40 });
|
||||
bitmap::clear(&mut r, Some(&m));
|
||||
assert_eq!(r.pixel(10, 10)[3], 0);
|
||||
assert_eq!(r.pixel(30, 10), [0, 0, 0, 255]);
|
||||
assert_eq!(r.pixel(50, 10), [206, 24, 20, 255]);
|
||||
assert!(!m.outline().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wand_and_delete_take_a_stroke_with_its_soft_edge() {
|
||||
let mut r = Raster::new(120, 60);
|
||||
let b = Brush { radius: 8.0, hardness: 0.3, color: [31, 42, 68, 255], opacity: 1.0, erase: false };
|
||||
bitmap::brush(&mut r, &[(10.0, 30.0, 1.0), (110.0, 30.0, 1.0)], &b, None);
|
||||
assert!(r.rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 0 && p[3] < 255), "the stroke has a soft edge");
|
||||
let m = bitmap::region(&r, 60, 30, 24);
|
||||
bitmap::clear(&mut r, Some(&m));
|
||||
assert!(r.rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 0), "pixels of the stroke were left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_and_rect_masks() {
|
||||
let m = Mask::polygon(100, 100, &[(10.0, 10.0), (90.0, 10.0), (10.0, 90.0)]);
|
||||
assert_eq!(m.get(20, 20), 255);
|
||||
assert_eq!(m.get(80, 80), 0);
|
||||
let r = Mask::rect(50, 50, PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||
assert_eq!(r.bbox(), PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||
let o = r.outline();
|
||||
assert_eq!(o.matches('M').count(), 4, "{o}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brush_stroke_paints_along_its_path_inside_the_selection() {
|
||||
let mut r = Raster::filled(100, 60, [255, 255, 255, 255]);
|
||||
let sel = Mask::rect(100, 60, PixelRect { x: 0, y: 0, w: 50, h: 60 });
|
||||
let b = Brush { radius: 6.0, hardness: 0.8, color: [0, 0, 0, 255], opacity: 1.0, erase: false };
|
||||
let dirty = bitmap::brush(&mut r, &[(10.0, 30.0, 1.0), (90.0, 30.0, 1.0)], &b, Some(&sel));
|
||||
assert!(dirty.w > 70);
|
||||
assert_eq!(r.pixel(30, 30), [0, 0, 0, 255], "painted on the line");
|
||||
assert_eq!(r.pixel(30, 5), [255, 255, 255, 255], "away from the line");
|
||||
assert_eq!(r.pixel(70, 30), [255, 255, 255, 255], "outside the selection");
|
||||
// The eraser takes the alpha.
|
||||
bitmap::brush(&mut r, &[(30.0, 30.0, 1.0)], &Brush { erase: true, ..b }, None);
|
||||
assert_eq!(r.pixel(30, 30)[3], 0);
|
||||
// A pencil sets exact pixels.
|
||||
bitmap::pencil(&mut r, &[(0.0, 0.0), (5.0, 0.0)], 1, [1, 2, 3, 255], false, None);
|
||||
assert_eq!(r.pixel(3, 0), [1, 2, 3, 255]);
|
||||
assert_eq!(r.pixel(3, 1), [255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_adjustments_change_nothing_and_invert_twice_returns() {
|
||||
let src = fixtures::picture(64, 48);
|
||||
for a in [
|
||||
Adjust::Brightness { amount: 0.0 },
|
||||
Adjust::Contrast { amount: 0.0 },
|
||||
Adjust::Levels { in_black: 0.0, in_white: 255.0, gamma: 1.0, out_black: 0.0, out_white: 255.0 },
|
||||
Adjust::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0 },
|
||||
Adjust::Sharpen { amount: 0.0, radius: 2.0 },
|
||||
] {
|
||||
let mut dst = src.clone();
|
||||
bitmap::adjust(&src, &mut dst, &a, None);
|
||||
let worst = src.rgba.iter().zip(&dst.rgba).map(|(a, b)| (*a as i16 - *b as i16).abs()).max().unwrap();
|
||||
assert!(worst <= 1, "{a:?} changed a pixel by {worst}");
|
||||
}
|
||||
let mut once = src.clone();
|
||||
bitmap::adjust(&src, &mut once, &Adjust::Invert, None);
|
||||
assert_ne!(once, src);
|
||||
let mut twice = once.clone();
|
||||
bitmap::adjust(&once, &mut twice, &Adjust::Invert, None);
|
||||
assert_eq!(twice, src);
|
||||
// Brightness +50 makes a mid grey lighter; a blur smooths an edge.
|
||||
let grey = Raster::filled(4, 4, [100, 100, 100, 255]);
|
||||
let mut lighter = grey.clone();
|
||||
bitmap::adjust(&grey, &mut lighter, &Adjust::Brightness { amount: 50.0 }, None);
|
||||
assert!(lighter.pixel(0, 0)[0] > 200);
|
||||
let mut edge = Raster::filled(20, 1, [0, 0, 0, 255]);
|
||||
for x in 10..20 {
|
||||
edge.rgba[x * 4..x * 4 + 3].copy_from_slice(&[255, 255, 255]);
|
||||
}
|
||||
let mut soft = edge.clone();
|
||||
bitmap::adjust(&edge, &mut soft, &Adjust::Blur { radius: 3.0 }, None);
|
||||
let mid = soft.pixel(10, 0)[0];
|
||||
assert!(mid > 40 && mid < 230, "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clone_stamp_copies_from_its_offset() {
|
||||
let src = fixtures::picture(80, 80);
|
||||
let mut r = src.clone();
|
||||
let b = Brush { radius: 4.0, hardness: 1.0, color: [0; 4], opacity: 1.0, erase: false };
|
||||
bitmap::clone_stamp(&mut r, &src, (30.0, 10.0), &[(20.0, 20.0, 1.0)], &b, None);
|
||||
assert_eq!(r.pixel(20, 20), src.pixel(50, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pixel_edit_undoes_exactly() {
|
||||
let mut doc = fixtures::bitmap();
|
||||
let original = doc.clone();
|
||||
let asset = doc.assets.keys().next().unwrap().clone();
|
||||
let b = Brush { radius: 10.0, hardness: 0.3, color: [10, 200, 30, 255], opacity: 0.8, erase: false };
|
||||
let (op, inv) =
|
||||
bitmap::edit(&mut doc, &asset, |r| bitmap::brush(r, &[(20.0, 20.0, 1.0), (200.0, 140.0, 0.5)], &b, None))
|
||||
.unwrap();
|
||||
let mut h = History::default();
|
||||
h.record(op, inv);
|
||||
assert_ne!(doc, original);
|
||||
assert!(h.undo(&mut doc).unwrap());
|
||||
assert_eq!(doc, original);
|
||||
assert!(h.redo(&mut doc).unwrap());
|
||||
assert_ne!(doc, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_import_makes_objects() {
|
||||
let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 200 100">
|
||||
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#f27ab9"/><stop offset="1" stop-color="#1f2a44"/></linearGradient></defs>
|
||||
<rect x="10" y="10" width="80" height="40" rx="6" fill="url(#g)" stroke="#000" stroke-width="2"/>
|
||||
<g opacity="0.5"><circle cx="150" cy="50" r="30" fill="#3ad07a"/></g>
|
||||
<path d="M10 90 A 20 20 0 0 1 50 90" fill="none" stroke="red" stroke-width="3" stroke-dasharray="4 2"/>
|
||||
<text x="100" y="95" font-family="Arial" font-size="12">Hello</text>
|
||||
</svg>"##;
|
||||
let doc = svg::import(svg, svg::system_fontdb()).unwrap();
|
||||
assert!((doc.pages[0].width - 150.0).abs() < 0.01, "200 px = 150 pt");
|
||||
let LayerKind::Vector { objects } = &doc.pages[0].layers[0].kind else { panic!() };
|
||||
let Shape::Group { objects: inner } = &objects[0].shape else { panic!() };
|
||||
assert!(inner.len() >= 4, "{}", inner.len());
|
||||
assert!(inner.iter().any(|o| matches!(o.fill, Some(Paint::Linear { .. }))));
|
||||
assert!(inner.iter().any(|o| matches!(o.shape, Shape::Group { .. }) && o.opacity < 0.6));
|
||||
assert!(inner.iter().any(|o| o.stroke.as_ref().is_some_and(|s| !s.dash.is_empty())));
|
||||
// It renders and round-trips through the format.
|
||||
let book = FontBook::system();
|
||||
assert!(render::page(&doc, &doc.pages[0], &book, 1.0).is_some());
|
||||
let bytes = format::write(&doc, &[]).unwrap();
|
||||
assert_eq!(format::read(&bytes, &Limits::default()).unwrap().0, doc);
|
||||
assert!(svg::import(b"<svg><g", svg::system_fontdb()).is_err());
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Day 3 mandatory test 3 (the PDF half): a PDF export keeps its text extractable in reading order and every page at
|
||||
//! its exact size; pdfium draws it like the core's own render. Also PNG at a scale, JPG and SVG.
|
||||
use pictor_doc::{Document, FontBook, export, fixtures, render};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
fn book() -> &'static FontBook {
|
||||
static B: OnceLock<FontBook> = OnceLock::new();
|
||||
B.get_or_init(FontBook::system)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
/// An A4 page with the text fixture's boxes on it, plus a second page of another size.
|
||||
fn a4_with_text() -> Document {
|
||||
let mut d = fixtures::text();
|
||||
d.pages[0].width = pictor_doc::A4.0;
|
||||
d.pages[0].height = pictor_doc::A4.1;
|
||||
let mut second = fixtures::shapes().pages.remove(0);
|
||||
second.id = d.new_id();
|
||||
for l in &mut second.layers {
|
||||
l.id = d.new_id();
|
||||
if let pictor_doc::LayerKind::Vector { objects } = &mut l.kind {
|
||||
for o in objects {
|
||||
o.id = d.new_id();
|
||||
}
|
||||
}
|
||||
}
|
||||
d.pages.push(second);
|
||||
d
|
||||
}
|
||||
|
||||
fn squash(s: &str) -> String {
|
||||
s.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_text_is_extractable_in_order_and_pages_are_exact() {
|
||||
let doc = a4_with_text();
|
||||
let pdf = export::pdf(&doc, book()).unwrap();
|
||||
std::fs::write(format!("{}/export-text.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||
let sizes = pictor_pdf::page_sizes(engine(), &pdf, None).unwrap();
|
||||
assert_eq!(sizes.len(), 2);
|
||||
assert!((sizes[0].0 - 595.276).abs() < 0.01 && (sizes[0].1 - 841.89).abs() < 0.01, "A4 is {sizes:?}");
|
||||
assert!((sizes[1].0 - 400.0).abs() < 0.01 && (sizes[1].1 - 300.0).abs() < 0.01, "{sizes:?}");
|
||||
let text = pictor_pdf::extract_text(engine(), &pdf, None).unwrap();
|
||||
let t = squash(&text[0]);
|
||||
let mut at = 0;
|
||||
for w in [
|
||||
"Monika Nováková",
|
||||
"Pictor lays text out in the core: shaping,",
|
||||
"line breaks and alignment, so the screen",
|
||||
"Příliš žluťoučký kůň",
|
||||
"úpěl ďábelské ódy.",
|
||||
"Centred",
|
||||
"in two lines",
|
||||
"Right, italic",
|
||||
] {
|
||||
match t[at..].find(w) {
|
||||
Some(i) => at += i + w.len(),
|
||||
None => panic!("{w:?} missing or out of order in:\n{t}"),
|
||||
}
|
||||
}
|
||||
// Letter-spaced capitals: pdfium may read the tracking as spaces; the letters are all there, in order.
|
||||
assert!(t.replace(' ', "").contains("PROJEKTOVÁMANAŽERKA"), "{t}");
|
||||
// The fonts are embedded subsets.
|
||||
let raw = String::from_utf8_lossy(&pdf);
|
||||
assert!(raw.contains("/FontFile2") || raw.contains("/FontFile3"), "no embedded font program");
|
||||
assert!(raw.contains("/ToUnicode"));
|
||||
}
|
||||
|
||||
fn diff(a: &image::RgbaImage, b: &pictor_doc::Raster) -> f64 {
|
||||
assert_eq!((a.width(), a.height()), (b.width, b.height));
|
||||
let mut sum = 0u64;
|
||||
for (p, q) in a.as_raw().as_chunks::<4>().0.iter().zip(b.rgba.as_chunks::<4>().0) {
|
||||
// The core's pixels over white paper, as pdfium draws them.
|
||||
let a = q[3] as i32;
|
||||
for i in 0..3 {
|
||||
let over_white = (q[i] as i32 * a + 255 * (255 - a)) / 255;
|
||||
sum += (p[i] as i32 - over_white).unsigned_abs() as u64;
|
||||
}
|
||||
}
|
||||
sum as f64 / (a.width() as f64 * a.height() as f64 * 3.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdfium_draws_the_pdf_like_the_core_does() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let pdf = export::pdf(&doc, book()).unwrap();
|
||||
std::fs::write(format!("{}/export-{name}.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||
let page = &doc.pages[0];
|
||||
let scale = 2.0;
|
||||
let core = render::page(&doc, page, book(), scale).unwrap();
|
||||
let theirs = pictor_pdf::render_page(engine(), &pdf, None, 0, core.width).unwrap().into_rgba8();
|
||||
let theirs = image::imageops::resize(&theirs, core.width, core.height, image::imageops::FilterType::Triangle);
|
||||
let d = diff(&theirs, &core);
|
||||
theirs.save(format!("{}/export-{name}-pdfium.png", env!("CARGO_TARGET_TMPDIR"))).unwrap();
|
||||
// Anti-aliasing and image filtering differ; a misplaced shape or a missing glyph run costs far more.
|
||||
assert!(d < 3.0, "{name}: mean difference {d:.2} per channel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_jpg_and_svg() {
|
||||
let doc = fixtures::shapes();
|
||||
let page = &doc.pages[0];
|
||||
let png = export::png(&doc, page, book(), 3.0).unwrap();
|
||||
let img = image::load_from_memory(&png).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (1200, 900));
|
||||
let jpg = export::jpg(&doc, page, book(), 1.0, 90).unwrap();
|
||||
let img = image::load_from_memory(&jpg).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (400, 300));
|
||||
for (name, doc) in fixtures::all() {
|
||||
let svg = export::svg(&doc, &doc.pages[0], book());
|
||||
std::fs::write(format!("{}/export-{name}.svg", env!("CARGO_TARGET_TMPDIR")), &svg).unwrap();
|
||||
let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert!(tree.root().has_children(), "{name}: empty SVG");
|
||||
}
|
||||
let svg = export::svg(&fixtures::text(), &fixtures::text().pages[0], book());
|
||||
assert!(svg.contains(">Monika Nováková</text>"), "text is not text in the SVG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_png_is_refused() {
|
||||
let doc = fixtures::shapes();
|
||||
assert!(matches!(export::png(&doc, &doc.pages[0], book(), 100.0), Err(export::ExportError::TooLarge)));
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Day 3 mandatory test 4: a font whose licence forbids embedding (OS/2 fsType) is refused for PDF export, and the
|
||||
//! error names the font and the reason. The test font is a system font with its fsType patched in memory.
|
||||
use pictor_doc::export::{self, ExportError};
|
||||
use pictor_doc::text::Embedding;
|
||||
use pictor_doc::*;
|
||||
|
||||
fn system_font() -> Vec<u8> {
|
||||
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||
if let Ok(d) = std::fs::read(p) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
panic!("no system font to patch");
|
||||
}
|
||||
|
||||
/// The font with OS/2 fsType set to `fs_type` (and version ≥ 2 so the bits mean what they say).
|
||||
fn with_fs_type(mut data: Vec<u8>, fs_type: u16) -> Vec<u8> {
|
||||
let n = u16::from_be_bytes([data[4], data[5]]) as usize;
|
||||
for i in 0..n {
|
||||
let rec = 12 + i * 16;
|
||||
if &data[rec..rec + 4] == b"OS/2" {
|
||||
let off = u32::from_be_bytes(data[rec + 8..rec + 12].try_into().unwrap()) as usize;
|
||||
let version = u16::from_be_bytes([data[off], data[off + 1]]);
|
||||
assert!(version >= 2, "the OS/2 table is too old for this test");
|
||||
data[off + 8..off + 10].copy_from_slice(&fs_type.to_be_bytes());
|
||||
return data;
|
||||
}
|
||||
}
|
||||
panic!("no OS/2 table");
|
||||
}
|
||||
|
||||
fn family_of(data: &[u8]) -> String {
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(data.to_vec()));
|
||||
book.families().remove(0)
|
||||
}
|
||||
|
||||
fn doc_with_text(family: &str) -> Document {
|
||||
let mut d = Document::a4();
|
||||
let id = d.new_id();
|
||||
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[0].kind {
|
||||
objects.push(Object {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 50.0, 50.0],
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape: Shape::Text {
|
||||
w: 0.0,
|
||||
text: "Embedding test".into(),
|
||||
style: TextStyle {
|
||||
family: family.into(),
|
||||
weight: 400,
|
||||
italic: false,
|
||||
size: 14.0,
|
||||
color: Rgba::BLACK,
|
||||
align: Align::Left,
|
||||
line_height: 1.2,
|
||||
letter_spacing: 0.0,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn export_with(font: Vec<u8>) -> (String, Result<Vec<u8>, ExportError>) {
|
||||
let family = family_of(&font);
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(font));
|
||||
let r = export::pdf(&doc_with_text(&family), &book);
|
||||
(family, r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restricted_font_is_refused_with_its_name_and_the_reason() {
|
||||
let (family, r) = export_with(with_fs_type(system_font(), 0x0002));
|
||||
match r {
|
||||
Err(e @ ExportError::FontNotEmbeddable { .. }) => {
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains(&family), "{msg}");
|
||||
assert!(msg.contains("forbids embedding"), "{msg}");
|
||||
}
|
||||
other => panic!("a restricted font was embedded: {:?}", other.map(|b| b.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bitmap_only_font_is_refused() {
|
||||
let (_, r) = export_with(with_fs_type(system_font(), 0x0200));
|
||||
assert!(matches!(r, Err(ExportError::FontNotEmbeddable { reason, .. }) if reason.contains("bitmap")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installable_editable_and_print_fonts_are_embedded() {
|
||||
for fs in [0x0000u16, 0x0004, 0x0008] {
|
||||
let (_, r) = export_with(with_fs_type(system_font(), fs));
|
||||
let pdf = r.unwrap_or_else(|e| panic!("fsType {fs:#06x}: {e}"));
|
||||
assert!(String::from_utf8_lossy(&pdf).contains("/FontFile2"));
|
||||
}
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(with_fs_type(system_font(), 0x0004)));
|
||||
let k = book.resolve(&book.families()[0], 400, false).unwrap();
|
||||
assert_eq!(book.font(k).embedding, Embedding::PrintOnly);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Day 3 mandatory test 1: the .pictor format. Fixture documents round-trip without loss; hostile zips (zip slip,
|
||||
//! bombs, a huge picture, too many entries, a missing asset, broken JSON) are refused cleanly; a newer format is
|
||||
//! refused with its message.
|
||||
use pictor_doc::format::{self, FormatError, Limits};
|
||||
use pictor_doc::{FontFile, fixtures};
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
fn zip_of(entries: &[(&str, &[u8])], method: zip::CompressionMethod) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(method);
|
||||
for (name, data) in entries {
|
||||
z.start_file(*name, opts).unwrap();
|
||||
z.write_all(data).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A valid document.json for a one-page document with no assets.
|
||||
fn plain_json() -> Vec<u8> {
|
||||
let bytes = format::write(&pictor_doc::Document::a4(), &[]).unwrap();
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut s = Vec::new();
|
||||
std::io::Read::read_to_end(&mut z.by_name("document.json").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_round_trip_without_loss() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let font = FontFile { family: "Fixture".into(), weight: 400, italic: false, data: fake_font() };
|
||||
let bytes = format::write(&doc, std::slice::from_ref(&font)).unwrap();
|
||||
let (back, fonts) = format::read(&bytes, &Limits::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(back, doc, "{name} changed in the round trip");
|
||||
assert_eq!(fonts, vec![font], "{name}: fonts");
|
||||
// Writing again gives the same bytes' content (stable).
|
||||
let again = format::write(&back, &fonts).unwrap();
|
||||
assert_eq!(format::read(&again, &Limits::default()).unwrap().0, doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest font ttf-parser accepts is a real one: take any system font if there is one, else skip the font part.
|
||||
fn fake_font() -> Vec<u8> {
|
||||
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||
if let Ok(d) = std::fs::read(p) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
panic!("no system font to embed in the fixture");
|
||||
}
|
||||
|
||||
fn err(bytes: &[u8]) -> FormatError {
|
||||
match format::read(bytes, &Limits::default()) {
|
||||
Ok(_) => panic!("a hostile file was accepted"),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_slip_and_odd_names_are_refused() {
|
||||
let json = plain_json();
|
||||
for bad in ["../evil.txt", "assets/../../evil.png", "/etc/passwd", "C:/Windows/x.dll", "assets\\x.png", "a//b"] {
|
||||
let z = zip_of(&[("document.json", &json), (bad, b"x")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::UnsafeName(_)), "{bad} was not refused as unsafe");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bomb_is_refused_by_size_and_ratio() {
|
||||
// 300 MB of zeros, compressed to a few hundred KB: refused by its declared size before anything is inflated.
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts =
|
||||
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true);
|
||||
z.start_file("document.json", opts).unwrap();
|
||||
let block = vec![b' '; 1 << 20];
|
||||
for _ in 0..300 {
|
||||
z.write_all(&block).unwrap();
|
||||
}
|
||||
let bomb = z.finish().unwrap().into_inner();
|
||||
assert!(bomb.len() < 2 << 20, "the bomb itself is small ({} bytes)", bomb.len());
|
||||
assert!(matches!(err(&bomb), FormatError::TooLarge(_)));
|
||||
|
||||
// A 5 MB asset of zeros compresses over 1000×: refused for its ratio.
|
||||
let json = String::from_utf8(plain_json()).unwrap();
|
||||
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":1000,\"height\":1250}]", 1);
|
||||
let zeros = vec![0u8; 5 << 20];
|
||||
let z = zip_of(&[("document.json", json.as_bytes()), ("assets/b9.png", &zeros)], zip::CompressionMethod::Deflated);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_picture_is_refused_before_decoding() {
|
||||
let json = String::from_utf8(plain_json()).unwrap();
|
||||
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":50000,\"height\":50000}]", 1);
|
||||
let z = zip_of(
|
||||
&[("document.json", json.as_bytes()), ("assets/b9.png", b"not even a png")],
|
||||
zip::CompressionMethod::Stored,
|
||||
);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_entries_are_refused() {
|
||||
let json = plain_json();
|
||||
let names: Vec<String> = (0..5000).map(|i| format!("extra/{i}")).collect();
|
||||
let mut entries: Vec<(&str, &[u8])> = vec![("document.json", &json)];
|
||||
entries.extend(names.iter().map(|n| (n.as_str(), b"" as &[u8])));
|
||||
let z = zip_of(&entries, zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_wrong_asset_is_refused() {
|
||||
// The bitmap fixture without its picture.
|
||||
let bytes = format::write(&fixtures::bitmap(), &[]).unwrap();
|
||||
let mut src = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut json = Vec::new();
|
||||
std::io::Read::read_to_end(&mut src.by_name("document.json").unwrap(), &mut json).unwrap();
|
||||
let z = zip_of(&[("document.json", &json)], zip::CompressionMethod::Deflated);
|
||||
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||
// A picture that is not the size the document says.
|
||||
let wrong = format::encode_png(&fixtures::picture(10, 10)).unwrap();
|
||||
let asset = src.file_names().find(|n| n.starts_with("assets/")).unwrap().to_string();
|
||||
let z = zip_of(&[("document.json", &json), (&asset, &wrong)], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::Damaged(_)), "{:?}", err(&z));
|
||||
// An asset referenced by a layer but not listed.
|
||||
let json2 = String::from_utf8(json.clone()).unwrap();
|
||||
let start = json2.find("\"assets\":[").unwrap();
|
||||
let end = json2[start..].find(']').unwrap() + start + 1;
|
||||
let json2 = format!("{}\"assets\":[]{}", &json2[..start], &json2[end..]);
|
||||
let z = zip_of(&[("document.json", json2.as_bytes())], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_json_and_non_zips_are_refused() {
|
||||
let z = zip_of(&[("document.json", b"{\"format\":1,\"pages\":[{")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::Damaged(_)));
|
||||
assert!(matches!(err(b"%PDF-1.7 not a zip"), FormatError::NotPictor));
|
||||
let z = zip_of(&[("readme.txt", b"hi")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::NotPictor));
|
||||
// Valid JSON with lies in it: a repeated id, a NaN-like size, a bad path, an asset id with a slash.
|
||||
let good = String::from_utf8(plain_json()).unwrap();
|
||||
for (from, to) in [
|
||||
("\"next_id\":3", "\"next_id\":1"),
|
||||
("\"width\":595.276", "\"width\":-5"),
|
||||
(
|
||||
"\"layers\":[{",
|
||||
"\"layers\":[{\"kind\":\"bitmap\",\"asset\":\"../x\",\"x\":0,\"y\":0,\"w\":1,\"h\":1,\"id\":9,\"name\":\"x\"},{",
|
||||
),
|
||||
] {
|
||||
assert!(good.contains(from), "fixture json lacks {from}: {good}");
|
||||
let bad = good.replacen(from, to, 1);
|
||||
let z = zip_of(&[("document.json", bad.as_bytes())], zip::CompressionMethod::Stored);
|
||||
let e = err(&z);
|
||||
assert!(matches!(e, FormatError::Damaged(_) | FormatError::UnsafeName(_)), "{from} → {to}: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_format_is_refused_with_its_message() {
|
||||
let z = zip_of(&[("document.json", b"{\"format\":2,\"anything\":\"new\"}")], zip::CompressionMethod::Stored);
|
||||
let e = err(&z);
|
||||
assert!(matches!(e, FormatError::Newer(2)), "{e:?}");
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains("newer Pictor") && msg.contains("format 2") && msg.contains("format 1"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_path_is_refused() {
|
||||
let good = String::from_utf8(plain_json()).unwrap();
|
||||
let mut doc = pictor_doc::Document::a4();
|
||||
let id = doc.new_id();
|
||||
if let pictor_doc::LayerKind::Vector { objects } = &mut doc.pages[0].layers[0].kind {
|
||||
objects.push(pictor_doc::Object {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: pictor_doc::identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape: pictor_doc::Shape::Path { d: "M0 0 A 1 1 0 0 1 5 5".into() },
|
||||
});
|
||||
}
|
||||
let bytes = format::write(&doc, &[]).unwrap();
|
||||
assert!(matches!(format::read(&bytes, &Limits::default()), Err(FormatError::Damaged(_))));
|
||||
drop(good);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! The core's painter: fixture documents render to what they say (spot colours at known places), and every fixture
|
||||
//! is written to `target/tmp/render-<name>.png` for a look.
|
||||
use pictor_doc::{FontBook, fixtures, render};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub fn book() -> &'static FontBook {
|
||||
static B: OnceLock<FontBook> = OnceLock::new();
|
||||
B.get_or_init(FontBook::system)
|
||||
}
|
||||
|
||||
fn near(a: [u8; 4], b: [u8; 4], tol: i32) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (*x as i32 - y as i32).abs() <= tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_render_and_are_written_for_a_look() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 2.0).expect("renders");
|
||||
assert_eq!(
|
||||
(r.width, r.height),
|
||||
((doc.pages[0].width * 2.0).round() as u32, (doc.pages[0].height * 2.0).round() as u32)
|
||||
);
|
||||
let png = pictor_doc::format::encode_png(&r).unwrap();
|
||||
std::fs::write(format!("{}/render-{name}.png", env!("CARGO_TARGET_TMPDIR")), png).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_land_where_the_document_says() {
|
||||
let doc = fixtures::shapes();
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||
// Inside the navy rounded rectangle (20,20 140×90), away from its brass stroke.
|
||||
assert!(near(r.pixel(90, 65), [0x1f, 0x2a, 0x44, 255], 2), "{:?}", r.pixel(90, 65));
|
||||
// On its brass stroke (top edge at y = 20).
|
||||
assert!(near(r.pixel(90, 20), [0xb0, 0x8d, 0x57, 255], 30), "{:?}", r.pixel(90, 20));
|
||||
// The white paper outside everything.
|
||||
assert_eq!(r.pixel(390, 5), [255, 255, 255, 255]);
|
||||
// The group at 50 %: green over white is a light green.
|
||||
let g = r.pixel(225, 155);
|
||||
assert!(near(g, [0x9c, 0xe7, 0xbc, 255], 6), "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bitmap_layer_at_scale_one_keeps_its_pixels() {
|
||||
let mut doc = fixtures::bitmap();
|
||||
doc.pages[0].layers[0].opacity = 1.0;
|
||||
doc.pages[0].layers.truncate(1);
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||
assert_eq!(r, doc.assets.values().next().unwrap().clone());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_drawn_in_its_colour() {
|
||||
let doc = fixtures::text();
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 2.0).unwrap();
|
||||
// Somewhere in the title's band there is navy ink.
|
||||
let navy = (40..140)
|
||||
.flat_map(|x| (36..90).map(move |y| (x, y)))
|
||||
.any(|(x, y)| near(r.pixel(x, y), [0x1f, 0x2a, 0x44, 255], 20));
|
||||
assert!(navy, "no navy title ink");
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Day 3 mandatory test 2: undo is exact. Any random sequence of operations followed by the same number of undos
|
||||
//! returns the document to its original state, and as many redos return the edited one.
|
||||
use pictor_doc::ops::History;
|
||||
use pictor_doc::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// What a random step does; turned into a concrete operation against the document as it is at that moment.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Step {
|
||||
AddRect { x: f32, y: f32, w: f32, h: f32, color: [u8; 4] },
|
||||
AddText { text: String, size: f32 },
|
||||
RemoveObject { pick: usize },
|
||||
MoveObject { pick: usize, dx: f32, dy: f32 },
|
||||
Recolour { pick: usize, color: [u8; 4] },
|
||||
AddLayer { at: usize },
|
||||
RemoveLayer { pick: usize },
|
||||
HideLayer { pick: usize, opacity: f32 },
|
||||
Resize { w: f32, h: f32 },
|
||||
Paint { x: u32, y: u32, w: u32, h: u32, color: [u8; 4] },
|
||||
NewBitmap { w: u32, h: u32 },
|
||||
Group { pick: usize },
|
||||
AddPage,
|
||||
RemovePage { pick: usize },
|
||||
}
|
||||
|
||||
fn step() -> impl Strategy<Value = Step> {
|
||||
let color = any::<[u8; 4]>();
|
||||
let f = -500.0f32..500.0;
|
||||
prop_oneof![
|
||||
(f.clone(), f.clone(), 1.0f32..300.0, 1.0f32..300.0, color).prop_map(|(x, y, w, h, color)| Step::AddRect {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color
|
||||
}),
|
||||
("[a-zA-Zá-ž ]{0,30}", 4.0f32..60.0).prop_map(|(text, size)| Step::AddText { text, size }),
|
||||
any::<usize>().prop_map(|pick| Step::RemoveObject { pick }),
|
||||
(any::<usize>(), f.clone(), f.clone()).prop_map(|(pick, dx, dy)| Step::MoveObject { pick, dx, dy }),
|
||||
(any::<usize>(), color).prop_map(|(pick, color)| Step::Recolour { pick, color }),
|
||||
any::<usize>().prop_map(|at| Step::AddLayer { at }),
|
||||
any::<usize>().prop_map(|pick| Step::RemoveLayer { pick }),
|
||||
(any::<usize>(), 0.0f32..=1.0).prop_map(|(pick, opacity)| Step::HideLayer { pick, opacity }),
|
||||
(1.0f32..2000.0, 1.0f32..2000.0).prop_map(|(w, h)| Step::Resize { w, h }),
|
||||
(0u32..300, 0u32..200, 1u32..120, 1u32..120, color).prop_map(|(x, y, w, h, color)| Step::Paint {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color
|
||||
}),
|
||||
(1u32..64, 1u32..64).prop_map(|(w, h)| Step::NewBitmap { w, h }),
|
||||
any::<usize>().prop_map(|pick| Step::Group { pick }),
|
||||
Just(Step::AddPage),
|
||||
any::<usize>().prop_map(|pick| Step::RemovePage { pick }),
|
||||
]
|
||||
}
|
||||
|
||||
fn object(doc: &mut Document, shape: Shape, fill: Option<Paint>) -> Object {
|
||||
Object {
|
||||
id: doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every (page, vector layer, object) in the document.
|
||||
fn all_objects(doc: &Document) -> Vec<(Id, Id, Object)> {
|
||||
let mut out = Vec::new();
|
||||
for p in &doc.pages {
|
||||
fn walk(p: Id, ls: &[Layer], out: &mut Vec<(Id, Id, Object)>) {
|
||||
for l in ls {
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects } => out.extend(objects.iter().map(|o| (p, l.id, o.clone()))),
|
||||
LayerKind::Group { layers } => walk(p, layers, out),
|
||||
LayerKind::Bitmap { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(p.id, &p.layers, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn first_vector_layer(doc: &Document) -> Option<(Id, Id)> {
|
||||
doc.pages
|
||||
.iter()
|
||||
.find_map(|p| p.layers.iter().find(|l| matches!(l.kind, LayerKind::Vector { .. })).map(|l| (p.id, l.id)))
|
||||
}
|
||||
|
||||
/// The operation for a step, or none when the document has nothing for it to act on. `doc` is only read, except
|
||||
/// that taking new ids moves `next_id` (which the operation does not undo, as in the app).
|
||||
fn op_for(doc: &mut Document, s: &Step) -> Option<Op> {
|
||||
let objs = all_objects(doc);
|
||||
let pick = |n: usize, len: usize| if len == 0 { None } else { Some(n % len) };
|
||||
Some(match s {
|
||||
Step::AddRect { x, y, w, h, color } => {
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let mut o = object(doc, Shape::Rect { w: *w, h: *h, radius: 0.0 }, Some(Paint::solid(Rgba(*color))));
|
||||
o.transform[4] = *x;
|
||||
o.transform[5] = *y;
|
||||
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||
}
|
||||
Step::AddText { text, size } => {
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let style = TextStyle {
|
||||
family: "Arial".into(),
|
||||
weight: 400,
|
||||
italic: false,
|
||||
size: *size,
|
||||
color: Rgba::BLACK,
|
||||
align: Align::Left,
|
||||
line_height: 1.2,
|
||||
letter_spacing: 0.0,
|
||||
};
|
||||
let o = object(doc, Shape::Text { w: 100.0, text: text.clone(), style }, None);
|
||||
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||
}
|
||||
Step::RemoveObject { pick: n } => {
|
||||
let (page, layer, o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
let index = layer_objects(doc, page, layer).iter().position(|x| x.id == o.id)?;
|
||||
Op::RemoveObject { page, layer, parent: None, index }
|
||||
}
|
||||
Step::MoveObject { pick: n, dx, dy } => {
|
||||
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
o.transform[4] += dx;
|
||||
o.transform[5] += dy;
|
||||
Op::ReplaceObject { page, layer, object: o }
|
||||
}
|
||||
Step::Recolour { pick: n, color } => {
|
||||
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
o.fill = Some(Paint::solid(Rgba(*color)));
|
||||
Op::ReplaceObject { page, layer, object: o }
|
||||
}
|
||||
Step::AddLayer { at } => {
|
||||
let page = doc.pages.first()?.id;
|
||||
let len = doc.pages[0].layers.len();
|
||||
let id = doc.new_id();
|
||||
Op::InsertLayer { page, parent: None, index: at % (len + 1), layer: Layer::vector(id, "New") }
|
||||
}
|
||||
Step::RemoveLayer { pick: n } => {
|
||||
let p = doc.pages.first()?;
|
||||
Op::RemoveLayer { page: p.id, parent: None, index: pick(*n, p.layers.len())? }
|
||||
}
|
||||
Step::HideLayer { pick: n, opacity } => {
|
||||
let p = doc.pages.first()?;
|
||||
let l = &p.layers[pick(*n, p.layers.len())?];
|
||||
Op::SetLayer {
|
||||
page: p.id,
|
||||
layer: l.id,
|
||||
name: format!("{} *", l.name),
|
||||
visible: !l.visible,
|
||||
locked: !l.locked,
|
||||
opacity: *opacity,
|
||||
place: match l.kind {
|
||||
LayerKind::Bitmap { .. } => Some(Rect { x: 1.0, y: 2.0, w: 30.0, h: 40.0 }),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
Step::Resize { w, h } => {
|
||||
let p = doc.pages.first()?;
|
||||
Op::SetPage {
|
||||
page: p.id,
|
||||
width: *w,
|
||||
height: *h,
|
||||
margins: [w / 20.0; 4],
|
||||
guides: vec![Guide { vertical: true, at: w / 2.0 }],
|
||||
background: Some(Rgba::WHITE),
|
||||
}
|
||||
}
|
||||
Step::Paint { x, y, w, h, color } => {
|
||||
let (asset, r) = doc.assets.iter().next()?;
|
||||
let rect = PixelRect { x: *x, y: *y, w: *w, h: *h }.clamp(r.width, r.height);
|
||||
if rect.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let pixels = std::iter::repeat_n(*color, (rect.w * rect.h) as usize).flatten().collect();
|
||||
Op::Patch { asset: asset.clone(), rect, pixels }
|
||||
}
|
||||
Step::NewBitmap { w, h } => {
|
||||
let page = doc.pages.first()?.id;
|
||||
let id = doc.new_id();
|
||||
let asset = format!("b{id}");
|
||||
let layer = Layer {
|
||||
id,
|
||||
name: "Paint".into(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Bitmap { asset: asset.clone(), x: 0.0, y: 0.0, w: *w as f32, h: *h as f32 },
|
||||
};
|
||||
Op::Batch {
|
||||
ops: vec![
|
||||
Op::PutAsset { asset, raster: Some(Raster::filled(*w, *h, [9, 8, 7, 6])) },
|
||||
Op::InsertLayer { page, parent: None, index: 0, layer },
|
||||
],
|
||||
}
|
||||
}
|
||||
Step::Group { pick: n } => {
|
||||
// Group two objects of one layer: remove both, insert a group holding them.
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let list = layer_objects(doc, page, layer);
|
||||
if list.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let i = n % (list.len() - 1);
|
||||
let (a, b) = (list[i].clone(), list[i + 1].clone());
|
||||
let g = object(doc, Shape::Group { objects: vec![a, b] }, None);
|
||||
Op::Batch {
|
||||
ops: vec![
|
||||
Op::RemoveObject { page, layer, parent: None, index: i + 1 },
|
||||
Op::RemoveObject { page, layer, parent: None, index: i },
|
||||
Op::InsertObject { page, layer, parent: None, index: i, object: g },
|
||||
],
|
||||
}
|
||||
}
|
||||
Step::AddPage => {
|
||||
let pid = doc.new_id();
|
||||
let lid = doc.new_id();
|
||||
let page = Page {
|
||||
id: pid,
|
||||
width: 100.0,
|
||||
height: 100.0,
|
||||
margins: [0.0; 4],
|
||||
guides: vec![],
|
||||
background: None,
|
||||
layers: vec![Layer::vector(lid, "Layer")],
|
||||
};
|
||||
Op::InsertPage { index: doc.pages.len(), page }
|
||||
}
|
||||
Step::RemovePage { pick: n } => {
|
||||
if doc.pages.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Op::RemovePage { index: n % doc.pages.len() }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn layer_objects(doc: &Document, page: Id, layer: Id) -> Vec<Object> {
|
||||
match doc.page(page).and_then(|p| p.layer(layer)).map(|l| &l.kind) {
|
||||
Some(LayerKind::Vector { objects }) => objects.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, .. ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn random_edits_then_as_many_undos_restore_the_document(
|
||||
start in 0usize..4,
|
||||
steps in proptest::collection::vec(step(), 1..60),
|
||||
) {
|
||||
let mut doc = fixtures::all().swap_remove(start).1;
|
||||
let mut history = History::default();
|
||||
let mut n = 0;
|
||||
for s in &steps {
|
||||
if let Some(op) = op_for(&mut doc, s) {
|
||||
history.apply(&mut doc, op).expect("a well-formed operation applies");
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
// next_id only grows (ids are never reused); compare everything else.
|
||||
let edited = doc.clone();
|
||||
let mut original = fixtures::all().swap_remove(start).1;
|
||||
original.next_id = doc.next_id;
|
||||
for _ in 0..n {
|
||||
prop_assert!(history.undo(&mut doc).unwrap());
|
||||
}
|
||||
prop_assert!(!history.undo(&mut doc).unwrap(), "more undos than edits");
|
||||
prop_assert_eq!(&doc, &original);
|
||||
for _ in 0..n {
|
||||
prop_assert!(history.redo(&mut doc).unwrap());
|
||||
}
|
||||
prop_assert_eq!(&doc, &edited);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_batch_leaves_nothing_behind() {
|
||||
let mut doc = fixtures::shapes();
|
||||
let before = doc.clone();
|
||||
let page = doc.pages[0].id;
|
||||
let layer = doc.pages[0].layers[0].id;
|
||||
let bad = Op::Batch {
|
||||
ops: vec![
|
||||
Op::RemoveObject { page, layer, parent: None, index: 0 },
|
||||
Op::RemoveObject { page, layer, parent: None, index: 99 },
|
||||
],
|
||||
};
|
||||
let mut h = History::default();
|
||||
assert!(h.apply(&mut doc, bad).is_err());
|
||||
assert_eq!(doc, before);
|
||||
assert!(!h.can_undo());
|
||||
}
|
||||
@@ -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,23 @@
|
||||
[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
|
||||
docx-rs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
flate2.workspace = true
|
||||
serde_json.workspace = true
|
||||
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Compress presets (Day 2): images are downsampled to the preset's resolution and re-encoded as JPEG, every stream
|
||||
//! is Flate-compressed, unreferenced objects are dropped and the file is written with object streams. Text, fonts,
|
||||
//! vector content and the page structure are not touched, so all text stays extractable.
|
||||
//!
|
||||
//! "Resolution" needs no content-stream analysis: an image is never shown larger than the largest page, so its
|
||||
//! pixel size is capped at (largest page side in inches × the preset's dpi). Images Pictor cannot decode safely
|
||||
//! (JPEG 2000, CCITT, JBIG2, indexed or 16-bit colour, masks) are left as they are. Fonts are not subset (a gap,
|
||||
//! recorded in docs/02_v1-1.md of the app).
|
||||
use crate::{PdfError, lopdf_load};
|
||||
use image::{DynamicImage, GenericImageView};
|
||||
use lopdf::{Dictionary, Document, Object, Stream};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CompressPreset {
|
||||
/// Small enough to attach to an e-mail: target 5 MB or less.
|
||||
Email,
|
||||
/// For the web and the screen.
|
||||
Web,
|
||||
/// Good enough to print.
|
||||
Print,
|
||||
}
|
||||
|
||||
/// The E-mail preset's target.
|
||||
pub const EMAIL_TARGET: usize = 5 << 20;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Compressed {
|
||||
pub bytes: Vec<u8>,
|
||||
pub before: usize,
|
||||
pub after: usize,
|
||||
pub images_changed: usize,
|
||||
/// Plain sentences (for example: the E-mail target could not be reached).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
struct Step {
|
||||
dpi: f32,
|
||||
quality: u8,
|
||||
}
|
||||
|
||||
fn steps(preset: CompressPreset) -> &'static [Step] {
|
||||
match preset {
|
||||
CompressPreset::Email => {
|
||||
&[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }]
|
||||
}
|
||||
CompressPreset::Web => &[Step { dpi: 150.0, quality: 72 }],
|
||||
CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }],
|
||||
}
|
||||
}
|
||||
|
||||
/// Compresses a document with a preset. A protected document stays protected with the same password.
|
||||
pub fn compress(bytes: &[u8], password: Option<&str>, preset: CompressPreset) -> Result<Compressed, PdfError> {
|
||||
let mut last = None;
|
||||
for (i, step) in steps(preset).iter().enumerate() {
|
||||
let r = compress_step(bytes, password, step)?;
|
||||
let done = preset != CompressPreset::Email || r.after <= EMAIL_TARGET || i + 1 == steps(preset).len();
|
||||
last = Some(r);
|
||||
if done {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut r = last.expect("at least one step");
|
||||
if preset == CompressPreset::Email && r.after > EMAIL_TARGET {
|
||||
r.warnings.push(format!(
|
||||
"Pictor got it down to {:.1} MB; the rest is text, fonts and drawings it does not change.",
|
||||
r.after as f64 / 1048576.0
|
||||
));
|
||||
}
|
||||
// Never hand back something bigger than the original.
|
||||
if r.after >= r.before {
|
||||
r.bytes = bytes.to_vec();
|
||||
r.after = r.before;
|
||||
r.images_changed = 0;
|
||||
r.warnings.push("This PDF is already as small as Pictor can make it.".into());
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn compress_step(bytes: &[u8], password: Option<&str>, step: &Step) -> Result<Compressed, PdfError> {
|
||||
let mut doc = lopdf_load(bytes, password)?;
|
||||
let largest_side_in = largest_page_side(&doc) / 72.0;
|
||||
let max_px = (largest_side_in * step.dpi).ceil().max(64.0) as u32;
|
||||
let ids: Vec<_> = doc.objects.keys().copied().collect();
|
||||
let masks = soft_masks(&doc);
|
||||
let mut changed = 0;
|
||||
for id in ids {
|
||||
if masks.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
let Some(Object::Stream(s)) = doc.objects.get(&id) else { continue };
|
||||
if !is_image(&s.dict) {
|
||||
continue;
|
||||
}
|
||||
let Some(new) = recompress(&doc, s, max_px, step.quality) else { continue };
|
||||
if let Some(Object::Stream(s)) = doc.objects.get_mut(&id) {
|
||||
*s = new;
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
doc.compress();
|
||||
doc.prune_objects();
|
||||
let opts = lopdf::SaveOptions::builder().use_object_streams(true).use_xref_streams(true).build();
|
||||
let mut out = Vec::new();
|
||||
match password {
|
||||
Some(p) => {
|
||||
let plain = {
|
||||
let mut v = Vec::new();
|
||||
doc.save_with_options(&mut v, opts).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||
v
|
||||
};
|
||||
out = crate::protect(&plain, None, p, None)?;
|
||||
}
|
||||
None => doc.save_with_options(&mut out, opts).map_err(|e| PdfError::Write(e.to_string()))?,
|
||||
}
|
||||
Ok(Compressed { before: bytes.len(), after: out.len(), bytes: out, images_changed: changed, warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn largest_page_side(doc: &Document) -> f32 {
|
||||
let mut side: f32 = 0.0;
|
||||
for page in doc.get_pages().values() {
|
||||
let f = crate::edit::lopdf_frame(doc, *page);
|
||||
side = side.max(f.crop[2] - f.crop[0]).max(f.crop[3] - f.crop[1]);
|
||||
}
|
||||
if side <= 0.0 { 842.0 } else { side.min(14_400.0) }
|
||||
}
|
||||
|
||||
/// Images used as another image's soft mask: left alone (their size must stay what their parent expects).
|
||||
fn soft_masks(doc: &Document) -> std::collections::HashSet<lopdf::ObjectId> {
|
||||
doc.objects
|
||||
.values()
|
||||
.filter_map(|o| match o {
|
||||
Object::Stream(s) => s.dict.get(b"SMask").ok().and_then(|m| m.as_reference().ok()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_image(d: &Dictionary) -> bool {
|
||||
matches!(d.get(b"Subtype"), Ok(Object::Name(n)) if n == b"Image")
|
||||
&& !matches!(d.get(b"ImageMask"), Ok(Object::Boolean(true)))
|
||||
}
|
||||
|
||||
fn name_or_first(o: Option<&Object>) -> Option<Vec<u8>> {
|
||||
match o? {
|
||||
Object::Name(n) => Some(n.clone()),
|
||||
Object::Array(a) if a.len() == 1 => a[0].as_name().ok().map(|n| n.to_vec()),
|
||||
Object::Array(a) if a.is_empty() => Some(Vec::new()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Channels of a colour space Pictor can re-encode as JPEG: DeviceGray, DeviceRGB, or ICCBased with N 1 or 3.
|
||||
fn channels(doc: &Document, cs: Option<&Object>) -> Option<u8> {
|
||||
let cs = match cs? {
|
||||
Object::Reference(r) => doc.get_object(*r).ok()?,
|
||||
o => o,
|
||||
};
|
||||
match cs {
|
||||
Object::Name(n) if n == b"DeviceGray" => Some(1),
|
||||
Object::Name(n) if n == b"DeviceRGB" => Some(3),
|
||||
Object::Array(a) if a.len() == 2 && a[0].as_name().ok() == Some(b"ICCBased") => {
|
||||
let s = match &a[1] {
|
||||
Object::Reference(r) => doc.get_object(*r).ok()?.as_stream().ok()?,
|
||||
_ => return None,
|
||||
};
|
||||
match s.dict.get(b"N").ok()?.as_i64().ok()? {
|
||||
1 => Some(1),
|
||||
3 => Some(3),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<Stream> {
|
||||
let d = &s.dict;
|
||||
let w = d.get(b"Width").ok()?.as_i64().ok()? as u32;
|
||||
let h = d.get(b"Height").ok()?.as_i64().ok()? as u32;
|
||||
if w == 0 || h == 0 || (w as u64) * (h as u64) > 150_000_000 {
|
||||
return None;
|
||||
}
|
||||
if d.get(b"BitsPerComponent").ok().and_then(|b| b.as_i64().ok()) != Some(8) || d.has(b"Decode") {
|
||||
return None;
|
||||
}
|
||||
let n = channels(doc, d.get(b"ColorSpace").ok())?;
|
||||
let filter = name_or_first(d.get(b"Filter").ok()).unwrap_or_default();
|
||||
let img: DynamicImage = match &filter[..] {
|
||||
b"DCTDecode" => {
|
||||
let i = image::load_from_memory_with_format(&s.content, image::ImageFormat::Jpeg).ok()?;
|
||||
// CMYK JPEGs (Adobe) and odd channel counts are left alone.
|
||||
if i.color().channel_count() != n {
|
||||
return None;
|
||||
}
|
||||
i
|
||||
}
|
||||
b"FlateDecode" | b"" => {
|
||||
let raw = if filter.is_empty() {
|
||||
s.content.clone()
|
||||
} else {
|
||||
s.decompressed_content_with_limit(600 << 20).ok()?
|
||||
};
|
||||
let need = (w as usize) * (h as usize) * n as usize;
|
||||
if raw.len() < need {
|
||||
return None;
|
||||
}
|
||||
match n {
|
||||
1 => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||
_ => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let (iw, ih) = img.dimensions();
|
||||
let img = if iw.max(ih) > max_px + max_px / 10 {
|
||||
let k = max_px as f32 / iw.max(ih) as f32;
|
||||
img.resize_exact(
|
||||
((iw as f32 * k).round() as u32).max(1),
|
||||
((ih as f32 * k).round() as u32).max(1),
|
||||
image::imageops::FilterType::Lanczos3,
|
||||
)
|
||||
} else {
|
||||
img
|
||||
};
|
||||
let mut jpeg = Vec::new();
|
||||
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality);
|
||||
match n {
|
||||
1 => img.to_luma8().write_with_encoder(enc).ok()?,
|
||||
_ => img.to_rgb8().write_with_encoder(enc).ok()?,
|
||||
}
|
||||
let old = s.content.len();
|
||||
if jpeg.len() as f64 > old as f64 * 0.9 {
|
||||
return None;
|
||||
}
|
||||
let mut dict = d.clone();
|
||||
dict.set("Width", img.width() as i64);
|
||||
dict.set("Height", img.height() as i64);
|
||||
dict.set("Filter", "DCTDecode");
|
||||
dict.remove(b"DecodeParms");
|
||||
dict.remove(b"Length");
|
||||
let mut out = Stream::new(dict, jpeg);
|
||||
out.allows_compression = false;
|
||||
Some(out)
|
||||
}
|
||||
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,55 @@
|
||||
//! 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 compress;
|
||||
mod edit;
|
||||
mod engine;
|
||||
mod error;
|
||||
pub mod geometry;
|
||||
mod pages;
|
||||
mod reader;
|
||||
mod redact;
|
||||
mod security;
|
||||
mod word;
|
||||
|
||||
pub use compress::{CompressPreset, Compressed, EMAIL_TARGET, compress};
|
||||
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};
|
||||
pub use word::{WordOptions, WordResult, to_word};
|
||||
|
||||
/// 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,504 @@
|
||||
//! PDF to Word (Day 2): editable text with its structure, not a pixel copy ("Layout is approximate").
|
||||
//!
|
||||
//! pdfium gives every character with its box, size, weight and slant. Pictor rebuilds, per page, top to bottom:
|
||||
//! lines (characters on one baseline), segments (pieces of a line split by a wide gap), tables (two or more
|
||||
//! consecutive lines whose segments start at the same columns), paragraphs (consecutive single-segment lines of the
|
||||
//! same size and left edge, close together), headings (clearly larger or bold-and-short text, measured against the
|
||||
//! document's body size) and images (each image object, at its place). The .docx is written by docx-rs.
|
||||
//!
|
||||
//! A page with (almost) no text but an image is a scan: it is listed in `scanned_pages`, and text recognised
|
||||
//! elsewhere (Fundamentum's Lector, through the app) can be passed back in `WordOptions::ocr` for those pages.
|
||||
use crate::{Engine, PdfError};
|
||||
use docx_rs::{BreakType, Docx, Paragraph, Pic, Run, RunFonts, Style, StyleType, Table, TableCell, TableRow};
|
||||
use pdfium_render::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WordOptions {
|
||||
/// Recognised text for scanned pages (0-based page → text; blank lines separate paragraphs).
|
||||
pub ocr: HashMap<usize, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WordResult {
|
||||
pub bytes: Vec<u8>,
|
||||
pub pages: usize,
|
||||
/// Pages with no text layer (scans) that had no OCR text given.
|
||||
pub scanned_pages: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Ch {
|
||||
c: char,
|
||||
x0: f32,
|
||||
x1: f32,
|
||||
y0: f32,
|
||||
y1: f32,
|
||||
size: f32,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Line {
|
||||
chars: Vec<Ch>,
|
||||
top: f32,
|
||||
bottom: f32,
|
||||
size: f32,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
fn left(&self) -> f32 {
|
||||
self.chars.first().map(|c| c.x0).unwrap_or(0.0)
|
||||
}
|
||||
/// Pieces of the line separated by a gap wider than 2.2 × the font size.
|
||||
fn segments(&self) -> Vec<Vec<Ch>> {
|
||||
let mut out: Vec<Vec<Ch>> = Vec::new();
|
||||
let mut cur: Vec<Ch> = Vec::new();
|
||||
for ch in &self.chars {
|
||||
if let Some(prev) = cur.iter().rev().find(|c| !c.c.is_whitespace())
|
||||
&& ch.x0 - prev.x1 > 2.2 * self.size.max(1.0)
|
||||
&& !ch.c.is_whitespace()
|
||||
{
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
cur.push(ch.clone());
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
out.push(cur);
|
||||
}
|
||||
out.into_iter().map(trim).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn trim(mut v: Vec<Ch>) -> Vec<Ch> {
|
||||
while v.first().is_some_and(|c| c.c.is_whitespace()) {
|
||||
v.remove(0);
|
||||
}
|
||||
while v.last().is_some_and(|c| c.c.is_whitespace()) {
|
||||
v.pop();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
enum Item {
|
||||
Lines(Vec<Line>),
|
||||
Image { top: f32, png: Vec<u8>, w_px: u32, h_px: u32, w_pt: f32, h_pt: f32 },
|
||||
}
|
||||
|
||||
fn item_top(i: &Item) -> f32 {
|
||||
match i {
|
||||
Item::Lines(l) => l.first().map(|l| l.top).unwrap_or(0.0),
|
||||
Item::Image { top, .. } => *top,
|
||||
}
|
||||
}
|
||||
|
||||
fn page_chars(page: &PdfPage) -> Result<Vec<Ch>, PdfError> {
|
||||
let text = page.text().map_err(PdfError::from_pdfium)?;
|
||||
let mut out = Vec::new();
|
||||
for ch in text.chars().iter() {
|
||||
let Some(c) = ch.unicode_char() else { continue };
|
||||
if c == '\r' || c == '\n' || c == '\u{2}' || c == '\u{fffe}' {
|
||||
continue;
|
||||
}
|
||||
let Ok(b) = ch.loose_bounds() else { continue };
|
||||
let name = ch.font_name().to_ascii_lowercase();
|
||||
let weight = matches!(ch.font_weight(), Some(w) if matches!(w, PdfFontWeight::Weight600 | PdfFontWeight::Weight700Bold | PdfFontWeight::Weight800 | PdfFontWeight::Weight900 | PdfFontWeight::Custom(600..)));
|
||||
out.push(Ch {
|
||||
c,
|
||||
x0: b.left().value,
|
||||
x1: b.right().value,
|
||||
y0: b.bottom().value,
|
||||
y1: b.top().value,
|
||||
size: ch.scaled_font_size().value.max(1.0),
|
||||
bold: weight || name.contains("bold") || name.contains("black") || name.contains("heavy"),
|
||||
italic: ch.font_is_italic() || name.contains("italic") || name.contains("oblique"),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The median gap between neighbouring visible characters of a line (sorted by x), not below 0; 0 for short lines.
|
||||
fn median_gap(chars: &[Ch]) -> f32 {
|
||||
let visible: Vec<&Ch> = chars.iter().filter(|c| !c.c.is_whitespace()).collect();
|
||||
let mut gaps: Vec<f32> = visible.windows(2).map(|w| w[1].x0 - w[0].x1).collect();
|
||||
if gaps.len() < 4 {
|
||||
return 0.0;
|
||||
}
|
||||
gaps.sort_by(f32::total_cmp);
|
||||
gaps[gaps.len() / 2].max(0.0)
|
||||
}
|
||||
|
||||
/// Characters in pdfium's order → lines, top to bottom (PDF y grows upwards).
|
||||
fn lines(chars: Vec<Ch>) -> Vec<Line> {
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
for ch in chars {
|
||||
let mid = (ch.y0 + ch.y1) / 2.0;
|
||||
let found = lines.iter_mut().rev().take(3).find(|l| {
|
||||
let lmid = (l.top + l.bottom) / 2.0;
|
||||
(mid - lmid).abs() < 0.45 * l.size.max(ch.size)
|
||||
});
|
||||
match found {
|
||||
Some(l) => {
|
||||
l.top = l.top.max(ch.y1);
|
||||
l.bottom = l.bottom.min(ch.y0);
|
||||
if !ch.c.is_whitespace() {
|
||||
l.size = l.size.max(ch.size);
|
||||
}
|
||||
l.chars.push(ch);
|
||||
}
|
||||
None => {
|
||||
let size = ch.size;
|
||||
lines.push(Line { top: ch.y1, bottom: ch.y0, size, chars: vec![ch] });
|
||||
}
|
||||
}
|
||||
}
|
||||
for l in &mut lines {
|
||||
l.chars.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
// Spaces come from the gaps between letters, not from pdfium's whitespace: many PDFs have no space glyphs,
|
||||
// and pdfium then invents zero-width spaces, some of them inside a word where the producer split it into
|
||||
// two text objects ("Dichotomou" + "s"). A whitespace character only lowers the gap a space needs.
|
||||
// The gap is measured against the line's own letter spacing (its median gap: most neighbours are letters of
|
||||
// one word), so justified text with narrow word gaps (0.14 em) is spaced and tracked-out headings are not
|
||||
// split into letters.
|
||||
let letter_gap = median_gap(&l.chars);
|
||||
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
|
||||
let mut whitespace_seen = false;
|
||||
for ch in std::mem::take(&mut l.chars) {
|
||||
if ch.c.is_whitespace() {
|
||||
whitespace_seen = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(prev) = with_spaces.last() {
|
||||
let gap = ch.x0 - prev.x1 - letter_gap;
|
||||
let size = ch.size.max(prev.size);
|
||||
if gap > 0.1 * size || (whitespace_seen && gap > 0.05 * size) {
|
||||
let mut sp = prev.clone();
|
||||
sp.c = ' ';
|
||||
with_spaces.push(sp);
|
||||
}
|
||||
}
|
||||
whitespace_seen = false;
|
||||
with_spaces.push(ch);
|
||||
}
|
||||
l.chars = with_spaces;
|
||||
}
|
||||
lines.retain(|l| l.chars.iter().any(|c| !c.c.is_whitespace()));
|
||||
lines.sort_by(|a, b| b.top.total_cmp(&a.top));
|
||||
lines
|
||||
}
|
||||
|
||||
fn body_size(all: &[Vec<Line>]) -> f32 {
|
||||
let mut counts: HashMap<u32, usize> = HashMap::new();
|
||||
for l in all.iter().flatten() {
|
||||
*counts.entry((l.size * 2.0).round() as u32).or_default() += l.chars.len();
|
||||
}
|
||||
counts.into_iter().max_by_key(|(_, n)| *n).map(|(s, _)| s as f32 / 2.0).unwrap_or(11.0)
|
||||
}
|
||||
|
||||
fn heading_level(chars: &[Ch], size: f32, body: f32) -> Option<usize> {
|
||||
let len = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
||||
let bold = chars.iter().filter(|c| !c.c.is_whitespace()).all(|c| c.bold);
|
||||
if size >= body * 1.8 {
|
||||
Some(1)
|
||||
} else if size >= body * 1.25 {
|
||||
Some(2)
|
||||
} else if bold && len <= 80 && size >= body * 1.05 {
|
||||
Some(3)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn runs(chars: &[Ch]) -> Vec<Run> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let (b, it, sz) = (chars[i].bold, chars[i].italic, (chars[i].size * 2.0).round() as usize);
|
||||
let mut j = i;
|
||||
let mut s = String::new();
|
||||
while j < chars.len() && chars[j].bold == b && chars[j].italic == it {
|
||||
s.push(chars[j].c);
|
||||
j += 1;
|
||||
}
|
||||
let mut r = Run::new().add_text(s).size(sz.clamp(8, 144));
|
||||
if b {
|
||||
r = r.bold();
|
||||
}
|
||||
if it {
|
||||
r = r.italic();
|
||||
}
|
||||
out.push(r);
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One page's lines → paragraphs and tables, in order.
|
||||
fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
// A table: two or more consecutive lines with ≥ 2 segments whose starts line up.
|
||||
let segs = lines[i].segments();
|
||||
if segs.len() >= 2 {
|
||||
let cols: Vec<f32> = segs.iter().map(|s| s[0].x0).collect();
|
||||
let mut rows = vec![segs];
|
||||
let mut j = i + 1;
|
||||
while j < lines.len() {
|
||||
let s = lines[j].segments();
|
||||
let fits = s.len() == cols.len()
|
||||
&& s.iter().zip(&cols).all(|(seg, x)| (seg[0].x0 - x).abs() < 0.8 * lines[j].size.max(6.0));
|
||||
let close = lines[j - 1].bottom - lines[j].top < 2.5 * lines[j].size;
|
||||
if !fits || !close {
|
||||
break;
|
||||
}
|
||||
rows.push(s);
|
||||
j += 1;
|
||||
}
|
||||
if rows.len() >= 2 {
|
||||
let table = Table::new(
|
||||
rows.iter()
|
||||
.map(|r| {
|
||||
TableRow::new(
|
||||
r.iter()
|
||||
.map(|cell| {
|
||||
TableCell::new().add_paragraph(
|
||||
runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
out = out.add_table(table);
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// A paragraph: join following lines of the same size and left edge that sit close below.
|
||||
let first = &lines[i];
|
||||
let mut chars: Vec<Ch> = first.chars.clone();
|
||||
let mut j = i + 1;
|
||||
while j < lines.len() {
|
||||
let (prev, next) = (&lines[j - 1], &lines[j]);
|
||||
let same_size = (next.size - first.size).abs() < 0.6;
|
||||
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
|
||||
let close = prev.bottom - next.top < 1.0 * first.size;
|
||||
if !(same_size && same_left && close)
|
||||
|| next.segments().len() > 1
|
||||
|| heading_level(&first.chars, first.size, body).is_some()
|
||||
{
|
||||
break;
|
||||
}
|
||||
// A hyphen at a line end joins the word; else a space.
|
||||
if chars.last().is_some_and(|c| c.c == '-' || c.c == '\u{ad}') {
|
||||
chars.pop();
|
||||
} else {
|
||||
let mut sp = chars.last().cloned().expect("non-empty");
|
||||
sp.c = ' ';
|
||||
chars.push(sp);
|
||||
}
|
||||
chars.extend(next.chars.iter().cloned());
|
||||
j += 1;
|
||||
}
|
||||
let chars = trim(chars);
|
||||
let mut p = runs(&chars).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r));
|
||||
if let Some(level) = heading_level(&chars, first.size, body) {
|
||||
p = p.style(&format!("Heading{level}"));
|
||||
}
|
||||
out = out.add_paragraph(p);
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn styles(doc: Docx) -> Docx {
|
||||
doc.add_style(Style::new("Heading1", StyleType::Paragraph).name("heading 1").size(40).bold().outline_lvl(0))
|
||||
.add_style(Style::new("Heading2", StyleType::Paragraph).name("heading 2").size(30).bold().outline_lvl(1))
|
||||
.add_style(Style::new("Heading3", StyleType::Paragraph).name("heading 3").size(24).bold().outline_lvl(2))
|
||||
.default_fonts(RunFonts::new().ascii("Calibri").hi_ansi("Calibri").cs("Calibri").east_asia("Calibri"))
|
||||
.default_size(22)
|
||||
}
|
||||
|
||||
/// Converts a PDF to a .docx.
|
||||
pub fn to_word(
|
||||
engine: &Engine,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
opts: &WordOptions,
|
||||
) -> Result<WordResult, PdfError> {
|
||||
let doc = engine.open(bytes, password)?;
|
||||
let n = doc.pages().len() as usize;
|
||||
if n > 2000 {
|
||||
return Err(PdfError::TooLarge(format!("{n} pages")));
|
||||
}
|
||||
let mut per_page: Vec<Vec<Item>> = Vec::with_capacity(n);
|
||||
let mut all_lines: Vec<Vec<Line>> = Vec::with_capacity(n);
|
||||
let mut scanned = Vec::new();
|
||||
for (i, page) in doc.pages().iter().enumerate() {
|
||||
let chars = page_chars(&page)?;
|
||||
let visible = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
||||
let mut items = Vec::new();
|
||||
let mut images = 0;
|
||||
for obj in page.objects().iter() {
|
||||
let Some(img) = obj.as_image_object() else { continue };
|
||||
let Ok(b) = obj.bounds() else { continue };
|
||||
let Ok(raw) = img.get_raw_image() else { continue };
|
||||
let (w_pt, h_pt) = (b.width().value, b.height().value);
|
||||
if w_pt < 8.0 || h_pt < 8.0 {
|
||||
continue;
|
||||
}
|
||||
images += 1;
|
||||
// Keep pictures a sensible size in the document (at most 1600 px on the long side).
|
||||
let raw = if raw.width().max(raw.height()) > 1600 {
|
||||
raw.resize(1600, 1600, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let mut png = Vec::new();
|
||||
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
|
||||
continue;
|
||||
}
|
||||
items.push(Item::Image { top: b.top().value, png, w_px: raw.width(), h_px: raw.height(), w_pt, h_pt });
|
||||
}
|
||||
let page_lines = lines(chars);
|
||||
if visible < 10 && images > 0 {
|
||||
if opts.ocr.contains_key(&i) {
|
||||
items.clear(); // the recognised text replaces the scan
|
||||
} else {
|
||||
scanned.push(i);
|
||||
}
|
||||
}
|
||||
all_lines.push(page_lines);
|
||||
per_page.push(items);
|
||||
}
|
||||
let body = body_size(&all_lines);
|
||||
let mut docx = styles(Docx::new());
|
||||
for (i, (page_lines, images)) in all_lines.into_iter().zip(per_page).enumerate() {
|
||||
if i > 0 {
|
||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
|
||||
}
|
||||
if let Some(t) = opts.ocr.get(&i) {
|
||||
for para in
|
||||
t.split("\n\n").map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty())
|
||||
{
|
||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
|
||||
}
|
||||
}
|
||||
// Interleave text runs and images by their top edge.
|
||||
let mut items: Vec<Item> = images;
|
||||
let mut group: Vec<Line> = Vec::new();
|
||||
let mut groups: Vec<Item> = Vec::new();
|
||||
let tops: Vec<f32> = items.iter().map(item_top).collect();
|
||||
for l in page_lines {
|
||||
if tops.iter().any(|t| *t < (group.last().map(|g: &Line| g.top).unwrap_or(f32::MAX)) && *t >= l.top)
|
||||
&& !group.is_empty()
|
||||
{
|
||||
groups.push(Item::Lines(std::mem::take(&mut group)));
|
||||
}
|
||||
group.push(l);
|
||||
}
|
||||
if !group.is_empty() {
|
||||
groups.push(Item::Lines(group));
|
||||
}
|
||||
items.extend(groups);
|
||||
items.sort_by(|a, b| item_top(b).total_cmp(&item_top(a)));
|
||||
for item in items {
|
||||
match item {
|
||||
Item::Lines(ls) => docx = blocks(ls, body, docx),
|
||||
Item::Image { png, w_px, h_px, w_pt, h_pt, .. } => {
|
||||
// Size in EMU (1 pt = 12 700 EMU), at most 6.5 inches wide.
|
||||
let k = (468.0 / w_pt).min(1.0);
|
||||
let pic = Pic::new_with_dimensions(png, w_px, h_px)
|
||||
.size((w_pt * k * 12_700.0) as u32, (h_pt * k * 12_700.0) as u32);
|
||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
docx.build().pack(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||
Ok(WordResult { bytes: out.into_inner(), pages: n, scanned_pages: scanned })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ch(c: char, x0: f32, x1: f32, size: f32) -> Ch {
|
||||
Ch { c, x0, x1, y0: 700.0, y1: 700.0 + size, size, bold: false, italic: false }
|
||||
}
|
||||
|
||||
fn text(line: &Line) -> String {
|
||||
line.chars.iter().map(|c| c.c).collect()
|
||||
}
|
||||
|
||||
/// The characters pdfium gave for a WPS Writer PDF (no space glyphs, words split over text objects): a
|
||||
/// zero-width space of size 1 between the touching "u" and "s" of "Dichotomous", and a misplaced one in the
|
||||
/// real 4 pt gap before "Segmentation".
|
||||
#[test]
|
||||
fn invented_spaces_inside_a_word_are_dropped_and_gaps_make_spaces() {
|
||||
let s = 15.9;
|
||||
let chars = vec![
|
||||
ch('o', 277.86, 285.83, s),
|
||||
ch('u', 285.86, 294.72, s),
|
||||
ch(' ', 292.53, 292.53, 1.0),
|
||||
ch('s', 294.75, 300.96, s),
|
||||
ch('I', 304.92, 311.12, s),
|
||||
ch('m', 311.15, 324.43, s),
|
||||
ch('e', 324.47, 332.45, s),
|
||||
ch(' ', 326.0, 326.0, 1.0),
|
||||
ch('S', 336.60, 345.47, s),
|
||||
];
|
||||
let l = lines(chars);
|
||||
assert_eq!(l.len(), 1);
|
||||
assert_eq!(text(&l[0]), "ous Ime S");
|
||||
}
|
||||
|
||||
/// A PDF with real space glyphs keeps one space per gap, and a narrow space (a condensed font) still counts.
|
||||
#[test]
|
||||
fn real_space_glyphs_still_make_spaces() {
|
||||
let s = 10.0;
|
||||
let chars = vec![
|
||||
ch('a', 0.0, 5.0, s),
|
||||
ch(' ', 5.0, 6.2, s),
|
||||
ch('b', 6.2, 11.0, s),
|
||||
ch(' ', 11.0, 11.5, s),
|
||||
ch(' ', 11.5, 14.0, s),
|
||||
ch('c', 14.0, 19.0, s),
|
||||
ch('d', 19.02, 24.0, s),
|
||||
];
|
||||
assert_eq!(text(&lines(chars)[0]), "a b cd");
|
||||
}
|
||||
|
||||
/// Lays a line out from words: letters `track` apart, words `space` apart (in points), no space glyphs.
|
||||
fn laid_out(words: &[&str], size: f32, track: f32, space: f32) -> Vec<Ch> {
|
||||
let mut x = 0.0;
|
||||
let mut out = Vec::new();
|
||||
for (i, w) in words.iter().enumerate() {
|
||||
if i > 0 {
|
||||
x += space - track;
|
||||
}
|
||||
for c in w.chars() {
|
||||
out.push(ch(c, x, x + 0.5 * size, size));
|
||||
x += 0.5 * size + track;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Justified text from the same WPS PDF: "of personal" is 1.55 pt apart at 11 pt (0.14 em).
|
||||
#[test]
|
||||
fn narrow_justified_word_gaps_are_spaces() {
|
||||
let chars = laid_out(&["terms", "of", "personal", "data"], 11.05, 0.03, 1.55);
|
||||
assert_eq!(text(&lines(chars)[0]), "terms of personal data");
|
||||
}
|
||||
|
||||
/// A heading tracked out to 0.15 em between letters is not split into letters.
|
||||
#[test]
|
||||
fn tracked_out_letters_stay_one_word() {
|
||||
let chars = laid_out(&["CHAPTER", "ONE"], 20.0, 3.0, 12.0);
|
||||
assert_eq!(text(&lines(chars)[0]), "CHAPTER ONE");
|
||||
}
|
||||
}
|
||||
@@ -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,127 @@
|
||||
//! Day 2 mandatory test 5: compress presets. The output is smaller, opens in pdfium, keeps every page and keeps all
|
||||
//! text extractable; the E-mail preset reaches its 5 MB target for a heavy scan-like PDF.
|
||||
mod common;
|
||||
use common::*;
|
||||
use lopdf::{Document, Object, Stream, dictionary};
|
||||
use pictor_pdf::CompressPreset;
|
||||
|
||||
/// `pages` A4 pages, each with a line of text and a noisy `px` × `px` photo (Flate RGB, or JPEG at q95).
|
||||
fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> 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();
|
||||
let mut seed = 0x1234_5678u32;
|
||||
for p in 0..pages {
|
||||
let img = image::RgbImage::from_fn(px, px, |x, y| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
let n = (seed & 0x1f) as u8;
|
||||
image::Rgb([(x * 255 / px) as u8 ^ n, (y * 255 / px) as u8, 120u8.wrapping_add(n)])
|
||||
});
|
||||
let stream = if jpeg {
|
||||
let mut out = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95).encode_image(&img).unwrap();
|
||||
let mut s = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||
out,
|
||||
);
|
||||
s.allows_compression = false;
|
||||
s
|
||||
} else {
|
||||
let mut s = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||
img.into_raw(),
|
||||
);
|
||||
s.compress().unwrap();
|
||||
s
|
||||
};
|
||||
let im = doc.add_object(stream);
|
||||
let content = format!(
|
||||
"BT /F1 18 Tf 72 780 Td (Invoice page {} of the compress test) Tj ET q 450 0 0 450 72 250 cm /Im0 Do Q",
|
||||
p + 1
|
||||
);
|
||||
let c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||||
let page = doc.add_object(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => c,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}, "XObject" => dictionary! {"Im0" => im}},
|
||||
});
|
||||
kids.push(Object::Reference(page));
|
||||
}
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", cat);
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn texts(bytes: &[u8]) -> Vec<String> {
|
||||
pictor_pdf::extract_text(engine(), bytes, None).unwrap().into_iter().map(|t| t.trim().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_makes_it_smaller_and_keeps_the_text() {
|
||||
let input = heavy_pdf(3, 2400, false);
|
||||
let before = texts(&input);
|
||||
for preset in [CompressPreset::Email, CompressPreset::Web, CompressPreset::Print] {
|
||||
let out = pictor_pdf::compress(&input, None, preset).unwrap();
|
||||
assert!(out.bytes.len() < input.len(), "{preset:?} did not shrink ({} → {})", input.len(), out.bytes.len());
|
||||
assert_eq!(out.before, input.len());
|
||||
assert_eq!(out.after, out.bytes.len());
|
||||
assert_eq!(texts(&out.bytes), before, "{preset:?} lost text");
|
||||
let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap();
|
||||
assert_eq!(sizes.len(), 3);
|
||||
assert!(out.images_changed >= 3, "{preset:?}: {} images changed", out.images_changed);
|
||||
// It still renders: the photo is there (not white) in the middle of the page.
|
||||
let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 595).unwrap().to_rgb8();
|
||||
let p = img.get_pixel(297, 400).0;
|
||||
assert!(p != [255, 255, 255], "{preset:?}: the photo disappeared");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_are_ordered_email_smallest_print_largest() {
|
||||
let input = heavy_pdf(2, 2400, true);
|
||||
let email = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap().after;
|
||||
let web = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap().after;
|
||||
let print = pictor_pdf::compress(&input, None, CompressPreset::Print).unwrap().after;
|
||||
assert!(email <= web && web <= print, "email {email}, web {web}, print {print}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn email_reaches_five_megabytes() {
|
||||
let input = heavy_pdf(8, 3000, false);
|
||||
assert!(input.len() > 20 << 20, "fixture too small: {}", input.len());
|
||||
let out = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap();
|
||||
assert!(out.after <= 5 << 20, "E-mail preset left {} bytes", out.after);
|
||||
assert_eq!(texts(&out.bytes).len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_with_nothing_to_shrink_is_left_alone_and_says_so() {
|
||||
let input = numbered_pdf(2, "Plain");
|
||||
let out = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap();
|
||||
assert_eq!(out.images_changed, 0);
|
||||
assert!(out.after <= out.before + 64, "grew from {} to {}", out.before, out.after);
|
||||
assert_eq!(texts(&out.bytes), ["Plain page 1", "Plain page 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_protected_pdf_needs_its_password_and_stays_readable() {
|
||||
let locked = pictor_pdf::protect(&heavy_pdf(1, 1600, false), None, "pw", None).unwrap();
|
||||
assert!(pictor_pdf::compress(&locked, None, CompressPreset::Web).is_err());
|
||||
let out = pictor_pdf::compress(&locked, Some("pw"), CompressPreset::Web).unwrap();
|
||||
assert!(out.after < out.before);
|
||||
// Still protected, with the same password.
|
||||
assert!(pictor_pdf::is_encrypted(&out.bytes));
|
||||
let text = pictor_pdf::extract_text(engine(), &out.bytes, Some("pw")).unwrap();
|
||||
assert_eq!(text[0].trim(), "Invoice page 1 of the compress test");
|
||||
}
|
||||
@@ -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,305 @@
|
||||
//! Day 2 mandatory test 4 (core part): PDF to Word. A PDF with a title, headings, a wrapped paragraph, a table and
|
||||
//! an image becomes a .docx with every word in reading order, heading styles, one table of 4 rows and the image.
|
||||
//! LibreOffice (when installed) reads the same text back. "Opens in Scriptum" is checked in the app repository
|
||||
//! (Scriptum's engine, Prelum, is private): Pictor/apps/desktop/src-tauri/tests/word_scriptum.rs.
|
||||
mod common;
|
||||
use common::*;
|
||||
use lopdf::{Document, Object, Stream, dictionary};
|
||||
use std::io::Read;
|
||||
|
||||
const BODY: &[&str] = &[
|
||||
"Pictor turns this PDF into a document you can edit.",
|
||||
"The paragraph wraps over three lines on purpose, so",
|
||||
"that the converter has to join the lines back together.",
|
||||
];
|
||||
|
||||
pub fn report_pdf() -> Vec<u8> {
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages_id = doc.new_object_id();
|
||||
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
||||
let bold = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica-Bold", "Encoding" => "WinAnsiEncoding"});
|
||||
let img = image::RgbImage::from_fn(120, 80, |x, y| image::Rgb([(x * 2) as u8, (y * 3) as u8, 200]));
|
||||
let mut im = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||
img.into_raw(),
|
||||
);
|
||||
im.compress().unwrap();
|
||||
let im = doc.add_object(im);
|
||||
let mut c1 = String::new();
|
||||
c1 += "BT /F2 26 Tf 72 770 Td (Quarterly report) Tj ET\n";
|
||||
c1 += "BT /F2 16 Tf 72 730 Td (Summary) Tj ET\n";
|
||||
for (i, line) in BODY.iter().enumerate() {
|
||||
c1 += &format!("BT /F1 11 Tf 72 {} Td ({line}) Tj ET\n", 705 - i as i32 * 14);
|
||||
}
|
||||
c1 += "BT /F2 16 Tf 72 640 Td (Figures) Tj ET\n";
|
||||
let rows = [
|
||||
["Month", "Sales", "Notes"],
|
||||
["January", "1200", "cold"],
|
||||
["February", "1350", "better"],
|
||||
["March", "1600", "best"],
|
||||
];
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, cell) in row.iter().enumerate() {
|
||||
let font = if r == 0 { "/F2" } else { "/F1" };
|
||||
c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18);
|
||||
}
|
||||
}
|
||||
c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n";
|
||||
c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n";
|
||||
let c2 = "BT /F2 16 Tf 72 770 Td (Next steps) Tj ET\nBT /F1 11 Tf 72 745 Td (Page two closes the report.) Tj ET\n";
|
||||
let res =
|
||||
|| dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}};
|
||||
let mut kids = Vec::new();
|
||||
for c in [c1, c2.to_string()] {
|
||||
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||||
kids.push(Object::Reference(doc.add_object(
|
||||
dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()},
|
||||
)));
|
||||
}
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", cat);
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn part(docx: &[u8], name: &str) -> Option<Vec<u8>> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
let mut f = z.by_name(name).ok()?;
|
||||
let mut v = Vec::new();
|
||||
f.read_to_end(&mut v).unwrap();
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn entries(docx: &[u8]) -> Vec<String> {
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||
z.file_names().map(String::from).collect()
|
||||
}
|
||||
|
||||
/// The text of word/document.xml: every w:t, a newline per paragraph.
|
||||
fn text_of(xml: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = xml;
|
||||
while let Some(i) = rest.find('<') {
|
||||
let tag_end = rest[i..].find('>').map(|j| i + j).unwrap_or(rest.len() - 1);
|
||||
let tag = &rest[i + 1..tag_end];
|
||||
if tag.starts_with("w:t") && !tag.ends_with('/') && (tag == "w:t" || tag.starts_with("w:t ")) {
|
||||
let body = &rest[tag_end + 1..];
|
||||
let end = body.find("</w:t>").unwrap_or(0);
|
||||
out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">"));
|
||||
} else if tag == "/w:p" {
|
||||
out.push('\n');
|
||||
}
|
||||
rest = &rest[tag_end + 1..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_in_order(text: &str, words: &[&str]) {
|
||||
let mut at = 0;
|
||||
for w in words {
|
||||
match text[at..].find(w) {
|
||||
Some(i) => at += i + w.len(),
|
||||
None => panic!("{w:?} missing or out of order in:\n{text}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ORDER: &[&str] = &[
|
||||
"Quarterly report",
|
||||
"Summary",
|
||||
"Pictor turns",
|
||||
"edit.",
|
||||
"wraps over three lines",
|
||||
"join the lines back together.",
|
||||
"Figures",
|
||||
"Month",
|
||||
"Sales",
|
||||
"Notes",
|
||||
"January",
|
||||
"1200",
|
||||
"cold",
|
||||
"March",
|
||||
"1600",
|
||||
"best",
|
||||
"A picture of the gradient",
|
||||
"Next steps",
|
||||
"Page two closes the report.",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn headings_paragraphs_table_and_image_come_out_in_order() {
|
||||
let r = pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap();
|
||||
assert!(r.scanned_pages.is_empty(), "{:?}", r.scanned_pages);
|
||||
let xml = String::from_utf8(part(&r.bytes, "word/document.xml").expect("document.xml")).unwrap();
|
||||
let text = text_of(&xml);
|
||||
assert_in_order(&text, ORDER);
|
||||
// The wrapped paragraph is one paragraph, not three.
|
||||
assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}");
|
||||
// Headings: the title and the section heads carry heading styles.
|
||||
assert!(xml.matches("w:pStyle w:val=\"Heading1\"").count() >= 1, "no Heading 1");
|
||||
assert!(xml.matches("w:pStyle w:val=\"Heading2\"").count() >= 3, "fewer than 3 Heading 2");
|
||||
// One table of 4 rows × 3 cells.
|
||||
assert_eq!(xml.matches("<w:tbl>").count(), 1, "tables");
|
||||
assert_eq!(xml.matches("<w:tr").count() - xml.matches("<w:trPr").count(), 4, "rows");
|
||||
// The image is embedded.
|
||||
assert!(xml.contains("<w:drawing>"), "no picture");
|
||||
assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part");
|
||||
// A page break between the two pages.
|
||||
assert!(xml.contains("w:type=\"page\""), "no page break");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() {
|
||||
// A "scan": one page that is only an image.
|
||||
let input = pictor_pdf::images_to_pdf(
|
||||
&[(
|
||||
Vec::new(),
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))),
|
||||
)],
|
||||
pictor_pdf::PageFit::A4,
|
||||
0.0,
|
||||
)
|
||||
.unwrap();
|
||||
let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap();
|
||||
assert_eq!(r.scanned_pages, vec![0]);
|
||||
let mut opts = pictor_pdf::WordOptions::default();
|
||||
opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into());
|
||||
let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap();
|
||||
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
||||
assert_in_order(&text, &["Recognised line one", "Second paragraph from OCR"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libreoffice_reads_every_word_in_order() {
|
||||
let soffice = std::path::Path::new(r"C:\Program Files\LibreOffice\program\soffice.com");
|
||||
if !soffice.exists() {
|
||||
println!("LibreOffice is not installed here: skipped");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
let docx = dir.path().join("report.docx");
|
||||
std::fs::write(&docx, pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap().bytes)
|
||||
.unwrap();
|
||||
let profile = format!("file:///{}", dir.path().join("lo-profile").display().to_string().replace('\\', "/"));
|
||||
// A fresh LibreOffice profile makes the first start exit with 1 while it restarts itself and still converts:
|
||||
// wait for the file rather than trusting the exit code (one retry if nothing comes).
|
||||
let out = dir.path().join("report.txt");
|
||||
for _ in 0..2 {
|
||||
let _ = std::process::Command::new(soffice)
|
||||
.args([
|
||||
&format!("-env:UserInstallation={profile}"),
|
||||
"--headless",
|
||||
"--invisible",
|
||||
"--norestore",
|
||||
"--nolockcheck",
|
||||
])
|
||||
.args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"])
|
||||
.arg(dir.path())
|
||||
.arg(&docx)
|
||||
.status();
|
||||
let start = std::time::Instant::now();
|
||||
while !out.exists() && start.elapsed() < std::time::Duration::from_secs(60) {
|
||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||
}
|
||||
if out.exists() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx");
|
||||
assert_in_order(&text, ORDER);
|
||||
}
|
||||
|
||||
/// A PDF written like many real ones (Word's own export among them): no space glyphs between words, only gaps, and
|
||||
/// a word split over two text objects where the line was justified ("Dichotomou" | "s"). pdfium invents a
|
||||
/// zero-width space at such a split; the .docx must not break the word there, and must still space the words.
|
||||
fn no_space_glyphs_pdf() -> Vec<u8> {
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages_id = doc.new_object_id();
|
||||
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
||||
// Helvetica advance widths (AFM, /1000 em) for the pieces, so each piece starts exactly where the last ended.
|
||||
let w = |s: &str| -> f32 {
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
'D' => 722.0,
|
||||
'I' | 'i' | 'l' | 'j' => 222.0,
|
||||
'c' | 'k' | 's' | 'v' | 'x' | 'y' | 'z' => 500.0,
|
||||
'f' | 't' => 278.0,
|
||||
'm' => 833.0,
|
||||
'r' => 333.0,
|
||||
'w' => 722.0,
|
||||
'S' | 'H' | 'A' | 'E' => 667.0,
|
||||
_ => 556.0,
|
||||
})
|
||||
.sum::<f32>()
|
||||
* 16.0
|
||||
/ 1000.0
|
||||
};
|
||||
let mut c = String::new();
|
||||
// Line 1: words as separate objects, a 4 pt gap between them, "Dichotomous" split in two touching objects.
|
||||
let mut x = 72.0;
|
||||
for (piece, gap_after) in [
|
||||
("Highly", 4.0),
|
||||
("Accurate", 4.0),
|
||||
("Dichotomou", 0.0),
|
||||
("s", 4.0),
|
||||
("Image", 4.0),
|
||||
("Segmentat", 0.0),
|
||||
("ion", 0.0),
|
||||
] {
|
||||
c += &format!("BT /F1 16 Tf {x:.2} 700 Td ({piece}) Tj ET\n");
|
||||
x += w(piece) + gap_after;
|
||||
}
|
||||
// Line 2: the same inside one text object, moved with Td (the other common way).
|
||||
c += "BT /F1 16 Tf 72 670 Td (evalu) Tj ";
|
||||
c += &format!("{:.2} 0 Td (ation) Tj {:.2} 0 Td (of) Tj ET\n", w("evalu"), w("ation") + 4.0);
|
||||
// Line 3, as WPS Writer writes it: the page flipped (y down), each word a text object with a flipped Tm at
|
||||
// 319 pt × 0.05, and every glyph its own Tj moved by TD in glyph widths.
|
||||
c += "q 1 0 0 -1 0 842 cm
|
||||
";
|
||||
let mut x = 72.0;
|
||||
for word in ["Dichotomous", "Image", "Segmentation", "Dataset"] {
|
||||
c += &format!("q BT /F1 319 Tf 0.05 0 0 -0.05 {x:.3} 230 Tm ");
|
||||
for (i, ch) in word.chars().enumerate() {
|
||||
if i > 0 {
|
||||
let prev = word.chars().nth(i - 1).unwrap().to_string();
|
||||
c += &format!("{:.3} -0 TD ", w(&prev) / 16.0 * 319.0);
|
||||
}
|
||||
c += &format!("({ch}) Tj ");
|
||||
}
|
||||
c += "ET Q
|
||||
";
|
||||
x += w(word) / 16.0 * 319.0 * 0.05 + 4.0;
|
||||
}
|
||||
c += "Q
|
||||
";
|
||||
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||||
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => reg}}});
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", cat);
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_split_over_text_objects_stay_whole() {
|
||||
let r = pictor_pdf::to_word(engine(), &no_space_glyphs_pdf(), None, &Default::default()).unwrap();
|
||||
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
||||
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
assert!(flat.contains("Highly Accurate Dichotomous Image Segmentation"), "{flat:?}");
|
||||
assert!(flat.contains("evaluation of"), "{flat:?}");
|
||||
assert!(flat.contains("Dichotomous Image Segmentation Dataset"), "{flat:?}");
|
||||
}
|
||||
@@ -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,37 @@
|
||||
[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
|
||||
pictor-doc.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
|
||||
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||
@@ -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,545 @@
|
||||
//! 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;
|
||||
|
||||
fn doc_error(e: impl std::fmt::Display + std::fmt::Debug) -> OpError {
|
||||
let msg = e.to_string();
|
||||
let code = if msg.contains("newer Pictor") {
|
||||
"newer"
|
||||
} else if msg.contains("too large") {
|
||||
"too_large"
|
||||
} else {
|
||||
"damaged"
|
||||
};
|
||||
OpError::new(code, msg)
|
||||
}
|
||||
|
||||
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.compress" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
doc: u32,
|
||||
preset: pictor_pdf::CompressPreset,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let d = state.doc(a.doc)?;
|
||||
let r = pictor_pdf::compress(&d.bytes, d.password.as_deref(), a.preset)?;
|
||||
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||
out["before"] = json!(r.before);
|
||||
out["after"] = json!(r.after);
|
||||
out["images_changed"] = json!(r.images_changed);
|
||||
out["warnings"] = json!(r.warnings);
|
||||
Ok(out)
|
||||
}
|
||||
"pdf.to_word" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
doc: u32,
|
||||
output: String,
|
||||
/// Recognised text for scanned pages: {"0": "text", …}.
|
||||
#[serde(default)]
|
||||
ocr: std::collections::HashMap<usize, String>,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let engine = state.engine()?;
|
||||
let d = state.doc(a.doc)?;
|
||||
let r =
|
||||
pictor_pdf::to_word(engine, &d.bytes, d.password.as_deref(), &pictor_pdf::WordOptions { ocr: a.ocr })?;
|
||||
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||
out["pages"] = json!(r.pages);
|
||||
out["scanned_pages"] = json!(r.scanned_pages);
|
||||
Ok(out)
|
||||
}
|
||||
"pdf.page_png" => {
|
||||
// A page as a PNG file (for OCR of a scanned page by Fundamentum's Lector, through the app).
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
doc: u32,
|
||||
page: usize,
|
||||
dpi: u32,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let engine = state.engine()?;
|
||||
let d = state.doc(a.doc)?;
|
||||
let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[a.page], a.dpi)?.remove(0);
|
||||
let bytes = png(&img)?;
|
||||
write_out(&a.output, &bytes, SaveMode::Overwrite)
|
||||
}
|
||||
// ---- 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}))
|
||||
}
|
||||
// ---- Documents (.pictor, SVG) ------------------------------------------------------------------------
|
||||
// An outside .pictor or SVG is read here, with caps, and written back as a clean .pictor of the worker's
|
||||
// own making; the tray process opens only that copy.
|
||||
"doc.open" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
input: String,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let src = read_file(&a.input)?;
|
||||
let (doc, fonts) = pictor_doc::format::read(&src, &pictor_doc::Limits::default()).map_err(doc_error)?;
|
||||
let clean = pictor_doc::format::write(&doc, &fonts).map_err(doc_error)?;
|
||||
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
|
||||
Ok(json!({"path": a.output, "pages": doc.pages.len(), "format": doc.format}))
|
||||
}
|
||||
"doc.import_svg" => {
|
||||
#[derive(Deserialize)]
|
||||
struct A {
|
||||
input: String,
|
||||
output: String,
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let src = read_file(&a.input)?;
|
||||
if src.len() > 64 << 20 {
|
||||
return Err(OpError::new("too_large", "This SVG is larger than 64 MB, which Pictor does not import."));
|
||||
}
|
||||
let doc = pictor_doc::svg::import(&src, pictor_doc::svg::system_fontdb()).map_err(doc_error)?;
|
||||
let clean = pictor_doc::format::write(&doc, &[]).map_err(doc_error)?;
|
||||
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
|
||||
Ok(json!({"path": a.output, "width": doc.pages[0].width, "height": doc.pages[0].height}))
|
||||
}
|
||||
"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,70 @@
|
||||
//! The worker's side of documents: `doc.open` turns a good .pictor into a clean copy and refuses hostile ones
|
||||
//! (zip slip, a bomb, a newer format) with a clear error, staying alive for the next request; `doc.import_svg`
|
||||
//! turns an SVG into a .pictor.
|
||||
use pictor_worker::client::{Worker, WorkerOptions};
|
||||
use serde_json::json;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
const CAP: Duration = Duration::from_secs(30);
|
||||
|
||||
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 zip_of(entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for (n, d) in entries {
|
||||
z.start_file(*n, opts).unwrap();
|
||||
z.write_all(d).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_open_cleans_good_files_and_refuses_hostile_ones() {
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
let mut w = worker();
|
||||
let good = dir.path().join("good.pictor");
|
||||
std::fs::write(&good, pictor_doc::format::write(&pictor_doc::fixtures::bitmap(), &[]).unwrap()).unwrap();
|
||||
let out = dir.path().join("clean.pictor");
|
||||
let r = w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("a good document opens");
|
||||
assert_eq!(r["pages"], 1);
|
||||
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
|
||||
assert_eq!(doc, pictor_doc::fixtures::bitmap());
|
||||
|
||||
let json = br#"{"format":1,"next_id":3,"pages":[{"id":1,"width":100,"height":100,"layers":[]}]}"#;
|
||||
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
|
||||
("slip", zip_of(&[("document.json", json), ("../../evil.dll", b"MZ")]), "damaged"),
|
||||
("newer", zip_of(&[("document.json", br#"{"format":9}"#)]), "newer"),
|
||||
("not a zip", b"hello".to_vec(), "damaged"),
|
||||
];
|
||||
for (name, bytes, code) in cases {
|
||||
let p = dir.path().join(format!("{}.pictor", name.replace(' ', "-")));
|
||||
std::fs::write(&p, bytes).unwrap();
|
||||
let e = w.call("doc.open", json!({"input": p, "output": dir.path().join("x.pictor")}), CAP).expect_err(name);
|
||||
let msg = format!("{e:?}");
|
||||
assert!(msg.contains(code), "{name}: {msg}");
|
||||
assert!(!dir.path().join("evil.dll").exists() && !dir.path().parent().unwrap().join("evil.dll").exists());
|
||||
}
|
||||
// Still alive for the next request.
|
||||
w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("the worker survives hostile files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_import_svg_writes_a_document() {
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
let svg = dir.path().join("logo.svg");
|
||||
std::fs::write(&svg, br##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="#f27ab9"/></svg>"##).unwrap();
|
||||
let out = dir.path().join("logo.pictor");
|
||||
let r = worker().call("doc.import_svg", json!({"input": svg, "output": out}), CAP).unwrap();
|
||||
assert_eq!(r["width"], 30.0);
|
||||
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
|
||||
assert_eq!(doc.pages.len(), 1);
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
+328
-85
@@ -1,86 +1,329 @@
|
||||
# Dependencies and their licences
|
||||
|
||||
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
|
||||
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
|
||||
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
|
||||
|
||||
## The allowed set, as checked by `scripts/deps.mjs`
|
||||
|
||||
| Licence (SPDX) | Why it is allowed |
|
||||
| :-- | :-- |
|
||||
| MIT, MIT-0 | named in the brief |
|
||||
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
|
||||
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
|
||||
| Zlib | named in the brief |
|
||||
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
|
||||
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
|
||||
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
|
||||
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
|
||||
|
||||
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
|
||||
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
|
||||
|
||||
## Direct dependencies
|
||||
|
||||
| Crate | Version | Licence | Used by | For |
|
||||
| :-- | :-- | :-- | :-- | :-- |
|
||||
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
|
||||
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
|
||||
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
|
||||
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
|
||||
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
|
||||
| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding |
|
||||
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
|
||||
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
|
||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
|
||||
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
|
||||
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
|
||||
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects |
|
||||
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
|
||||
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
|
||||
|
||||
## Binaries (fetched, never in git)
|
||||
|
||||
| Binary | Licence | Fetched by |
|
||||
| :-- | :-- | :-- |
|
||||
| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned |
|
||||
|
||||
### pdfium
|
||||
|
||||
Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256
|
||||
`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches
|
||||
pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside
|
||||
the dll (the app's installer copies them). Read from those files on 2026-11-16:
|
||||
|
||||
| Component inside pdfium.dll | Licence | In the allowed set? |
|
||||
| :-- | :-- | :-- |
|
||||
| the binary build (bblanchon/pdfium-binaries) | MIT | yes |
|
||||
| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes |
|
||||
| abseil, highway | Apache-2.0 | yes |
|
||||
| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes |
|
||||
| fast_float, simdutf | MIT | yes |
|
||||
| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) |
|
||||
| OpenJPEG | BSD-2-Clause | yes |
|
||||
| zlib | Zlib | yes |
|
||||
| HarfBuzz | "Old MIT" | yes (MIT family) |
|
||||
| ICU | Unicode-3.0 | **interpretation** (see above) |
|
||||
| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive |
|
||||
| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) |
|
||||
| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." |
|
||||
|
||||
None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked
|
||||
"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF
|
||||
support depends on pdfium, which the brief chose).
|
||||
|
||||
## OS codecs (not bundled)
|
||||
|
||||
| Codec | Provided by | Used for |
|
||||
| :-- | :-- | :-- |
|
||||
| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled |
|
||||
|
||||
## Every crate in Cargo.lock
|
||||
|
||||
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
||||
|
||||
# Dependencies and their licences
|
||||
|
||||
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
|
||||
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
|
||||
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
|
||||
|
||||
## The allowed set, as checked by `scripts/deps.mjs`
|
||||
|
||||
| Licence (SPDX) | Why it is allowed |
|
||||
| :-- | :-- |
|
||||
| MIT, MIT-0 | named in the brief |
|
||||
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
|
||||
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
|
||||
| Zlib | named in the brief |
|
||||
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
|
||||
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
|
||||
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
|
||||
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
|
||||
|
||||
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
|
||||
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
|
||||
|
||||
## Direct dependencies
|
||||
|
||||
| Crate | Version | Licence | Used by | For |
|
||||
| :-- | :-- | :-- | :-- | :-- |
|
||||
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
|
||||
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
|
||||
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
|
||||
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
|
||||
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
|
||||
| img-parts | 0.4 (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) |
|
||||
| docx-rs | 0.4 | MIT | pdf | PDF to Word: writing the .docx (headings, runs, tables, inline images) |
|
||||
| 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 | MIT OR Apache-2.0 | doc (and pdf tests) | compressing PDF export streams; 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 |
|
||||
| tiny-skia | 0.12 | BSD-3-Clause | doc | the core's 2D painter: PNG/JPG export, thumbnails, brush dabs, the fidelity reference |
|
||||
| usvg | 0.50 | Apache-2.0 OR MIT | doc | SVG import into vector layers (text as outlines); brings fontdb and the same ttf-parser |
|
||||
| fontdb | 0.24 | MIT | doc | the system font list (C:\Windows\Fonts, the per-user fonts folder) and the fonts inside a .pictor |
|
||||
| rustybuzz | 0.20 | MIT | doc | text shaping (a harfbuzz port in safe Rust) |
|
||||
| ttf-parser | 0.25 | MIT OR Apache-2.0 | doc | glyph outlines, metrics and the OS/2 fsType embedding flags |
|
||||
| pdf-writer | 0.15 | MIT OR Apache-2.0 | doc | PDF export of a document: vectors, shadings, images with SMask, Type 0 fonts with ToUnicode |
|
||||
| subsetter | 0.2 | MIT OR Apache-2.0 | doc | subsetting the embedded fonts of a PDF export (TrueType and CFF) |
|
||||
| zip | 8 | MIT | doc | reading and writing .pictor files (deflate only, no default features) |
|
||||
|
||||
## 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 -->
|
||||
<!-- deps:end -->
|
||||
228 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 |
|
||||
| android_system_properties | 0.1.6 | MIT OR Apache-2.0 | yes |
|
||||
| arrayref | 0.3.9 | BSD-2-Clause | yes |
|
||||
| arrayvec | 0.7.8 | MIT OR Apache-2.0 | yes |
|
||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||
| base64 | 0.23.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 |
|
||||
| bumpalo | 3.20.4 | MIT OR Apache-2.0 | yes |
|
||||
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| bytemuck_derive | 1.12.1 | 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 |
|
||||
| cc | 1.11.2 | 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 |
|
||||
| console_error_panic_hook | 0.1.7 | Apache-2.0/MIT | yes |
|
||||
| console_log | 1.1.0 | MIT/Apache-2.0 | yes |
|
||||
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
||||
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
||||
| core_maths | 0.1.1 | MIT | yes |
|
||||
| core-foundation-sys | 0.8.7 | MIT OR 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 |
|
||||
| crunchy | 0.2.4 | MIT | yes |
|
||||
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
||||
| data-url | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||
| docx-rs | 0.4.22 | MIT | 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 |
|
||||
| errno | 0.3.15 | MIT OR Apache-2.0 | yes |
|
||||
| euclid | 0.22.14 | MIT OR Apache-2.0 | 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 |
|
||||
| find-msvc-tools | 0.1.15 | MIT OR Apache-2.0 | yes |
|
||||
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
||||
| float-cmp | 0.9.0 | MIT | yes |
|
||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||
| foldhash | 0.2.0 | Zlib | yes |
|
||||
| font-types | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||
| font-types | 0.12.7 | MIT OR Apache-2.0 | yes |
|
||||
| fontconfig-parser | 0.5.8 | MIT | yes |
|
||||
| fontdb | 0.24.0 | MIT | yes |
|
||||
| futures-core | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||
| futures-task | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||
| futures-util | 0.3.34 | MIT OR Apache-2.0 | 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 |
|
||||
| harfrust | 0.15.0 | MIT | yes |
|
||||
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
||||
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
||||
| iana-time-zone | 0.1.65 | MIT OR Apache-2.0 | yes |
|
||||
| iana-time-zone-haiku | 0.1.2 | 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 |
|
||||
| imagesize | 0.15.0 | MIT | 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 |
|
||||
| js-sys | 0.3.107 | MIT OR Apache-2.0 | yes |
|
||||
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
||||
| kurbo | 0.13.1 | Apache-2.0 OR MIT | yes |
|
||||
| libc | 0.2.191 | MIT OR Apache-2.0 | yes |
|
||||
| libloading | 0.9.1 | ISC | yes |
|
||||
| libm | 0.2.16 | MIT | yes |
|
||||
| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | 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 |
|
||||
| memmap2 | 0.9.12 | MIT OR Apache-2.0 | 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 |
|
||||
| pdf-writer | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
||||
| pico-args | 0.5.0 | MIT | yes |
|
||||
| pin-project-lite | 0.2.17 | Apache-2.0 OR MIT | yes |
|
||||
| piston-float | 1.0.1 | MIT | yes |
|
||||
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
||||
| polycool | 0.4.0 | 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 |
|
||||
| quick-xml | 0.41.0 | MIT | yes |
|
||||
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
||||
| r-efi | 6.0.0 | MIT OR Apache-2.0 OR LGPL-2.1-or-later | 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 |
|
||||
| read-fonts | 0.39.2 | MIT OR Apache-2.0 | yes |
|
||||
| read-fonts | 0.46.0 | MIT OR Apache-2.0 | yes |
|
||||
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
||||
| roxmltree | 0.20.0 | MIT OR Apache-2.0 | yes |
|
||||
| roxmltree | 0.21.2 | MIT OR Apache-2.0 | yes |
|
||||
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
||||
| rustc-hash | 2.1.3 | Apache-2.0 OR MIT | yes |
|
||||
| rustix | 1.1.6 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
||||
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
||||
| rustybuzz | 0.20.1 | MIT | yes |
|
||||
| ryu | 1.0.23 | Apache-2.0 OR BSL-1.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 |
|
||||
| shlex | 2.0.1 | MIT OR Apache-2.0 | yes |
|
||||
| simd-adler32 | 0.3.10 | MIT | yes |
|
||||
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
||||
| simplecss | 0.2.2 | Apache-2.0 OR MIT | yes |
|
||||
| siphasher | 1.0.4 | MIT OR Apache-2.0 | yes |
|
||||
| skrifa | 0.42.1 | MIT OR Apache-2.0 | yes |
|
||||
| skrifa | 0.49.0 | MIT OR Apache-2.0 | yes |
|
||||
| slab | 0.4.12 | MIT | yes |
|
||||
| slotmap | 1.1.1 | Zlib | yes |
|
||||
| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes |
|
||||
| stable_deref_trait | 1.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| strict-num | 0.1.1 | MIT | yes |
|
||||
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
||||
| subsetter | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||
| svgtypes | 0.16.2 | Apache-2.0 OR MIT | yes |
|
||||
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||
| synstructure | 0.14.0 | MIT | 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 |
|
||||
| tiny-skia | 0.12.0 | BSD-3-Clause | yes |
|
||||
| tiny-skia-path | 0.12.0 | BSD-3-Clause | yes |
|
||||
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| tokio | 1.54.1 | 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 |
|
||||
| ttf-parser | 0.25.1 | MIT OR Apache-2.0 | yes |
|
||||
| typed-path | 0.12.4 | 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-bidi-mirroring | 0.4.0 | MIT/Apache-2.0 | yes |
|
||||
| unicode-ccc | 0.4.0 | MIT/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 |
|
||||
| unicode-script | 0.5.9 | MIT OR Apache-2.0 | yes |
|
||||
| unicode-vo | 0.1.0 | MIT/Apache-2.0 | yes |
|
||||
| usvg | 0.50.0 | Apache-2.0 OR MIT | yes |
|
||||
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
||||
| vecmath | 1.0.0 | MIT | yes |
|
||||
| version_check | 0.9.5 | MIT/Apache-2.0 | yes |
|
||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||
| wasm-bindgen | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||
| wasm-bindgen-futures | 0.4.80 | MIT OR Apache-2.0 | yes |
|
||||
| wasm-bindgen-macro | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||
| wasm-bindgen-macro-support | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||
| wasm-bindgen-shared | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||
| web-sys | 0.3.107 | MIT OR 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 |
|
||||
| write-fonts | 0.48.1 | MIT OR Apache-2.0 | yes |
|
||||
| xmlwriter | 0.1.0 | MIT | yes |
|
||||
| yoke | 0.8.4 | Unicode-3.0 | yes |
|
||||
| yoke-derive | 0.8.4 | Unicode-3.0 | 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 |
|
||||
| zerofrom | 0.1.8 | Unicode-3.0 | yes |
|
||||
| zerofrom-derive | 0.1.8 | Unicode-3.0 | yes |
|
||||
| zip | 8.6.0 | MIT | yes |
|
||||
| zlib-rs | 0.6.8 | Zlib | yes |
|
||||
| zmij | 1.0.23 | MIT | yes |
|
||||
| zopfli | 0.8.4 | Apache-2.0 | 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 -->
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
# 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) | |
|
||||
| compress presets (Day 2) | lopdf: images capped at the largest page side × the preset's dpi and re-encoded as JPEG (E-mail 120 → 96 → 72 dpi until ≤ 5 MB, Web 150, Print 300); Flate everywhere; object streams | text, fonts and vectors untouched, so text stays extractable; fonts are not subset (gap) |
|
||||
| PDF to Word (Day 2) | pdfium characters (box, size, weight, slant) → lines, segments, tables, paragraphs, headings; images at their place; docx-rs writes the .docx | "Layout is approximate"; spaces come from the gaps between letters (measured against the line's own letter spacing), never from pdfium's invented whitespace, so PDFs without space glyphs keep whole words; glyphs without a Unicode mapping stay U+FFFD; scanned pages are reported, and OCR text from Fundamentum's Lector can be passed in |
|
||||
|
||||
### 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 .pictor document (crates/doc), format 1
|
||||
|
||||
A `.pictor` file is a zip:
|
||||
|
||||
| Entry | What |
|
||||
| :-- | :-- |
|
||||
| `document.json` | the document (below), compressed |
|
||||
| `assets/<id>.png` | the pixels of each bitmap layer and placed picture, RGBA, stored (PNG is already compressed) |
|
||||
| `fonts/<sha256>.ttf` / `.otf` | the fonts the document uses whose licence allows embedding (OS/2 `fsType` installable or editable) |
|
||||
|
||||
`document.json` (every length in points, 1/72 in; a document made from an image has 1 pt = 1 px):
|
||||
|
||||
```
|
||||
{ "format": 1, "next_id": 12,
|
||||
"pages": [ { "id": 1, "width": 595.276, "height": 841.89, "margins": [t, r, b, l], "guides": [{"vertical": true, "at": 297.6}],
|
||||
"background": [255, 255, 255, 255] | null,
|
||||
"layers": [ { "id": 2, "name": "Layer 1", "visible": true, "locked": false, "opacity": 1,
|
||||
"kind": "vector", "objects": [ … ] }
|
||||
| { …, "kind": "bitmap", "asset": "b3", "x": 0, "y": 0, "w": 800, "h": 600 }
|
||||
| { …, "kind": "group", "layers": [ … ] } ] } ],
|
||||
"assets": [ { "id": "b3", "width": 800, "height": 600 } ],
|
||||
"fonts": [ { "family": "Georgia", "weight": 700, "italic": false, "file": "fonts/<sha256>.ttf" } ] }
|
||||
```
|
||||
|
||||
An object is `{ "id", "name", "transform": [a, b, c, d, e, f], "opacity", "visible", "locked", "fill", "stroke",
|
||||
"shape" }` with `shape.type` one of `rect {w, h, radius}`, `ellipse {w, h}`, `line {x1, y1, x2, y2, arrow_start,
|
||||
arrow_end}`, `path {d}` (absolute or relative M L H V C Q Z; no arcs), `text {w, text, style}` (style: `family,
|
||||
weight, italic, size, color, align` left / center / right / justify, `line_height` as a multiple of the size,
|
||||
`letter_spacing` in points), `image {asset, w, h, crop {x, y, w, h}}` (the whole picture's place inside the frame)
|
||||
or `group {objects}`. A paint is `{"type": "solid", "color": [r, g, b, a]}`, `linear {x1, y1, x2, y2, stops}` or
|
||||
`radial {cx, cy, r, stops}` with coordinates as fractions of the shape's box; a stroke is `{paint, width, dash, cap,
|
||||
join}`. Colours are sRGB with straight alpha.
|
||||
|
||||
**Reading is strict** (`format::read`, `Limits`): at most 4096 entries; every entry name relative, without `..`,
|
||||
`\`, `:` or empty parts, no directories or links (refused even when unused); entries are read by known name, never
|
||||
extracted; `document.json` at most 64 MB and any entry 256 MB, the whole 1 GB, and no entry over 1 MB may expand
|
||||
more than 1000×; the declared size must be the real one; `format` is read first and a newer one is refused
|
||||
("made by a newer Pictor"); ids unique and below `next_id`, numbers finite, pages 1–14 400 pt, opacities 0–1, paths
|
||||
parsed, nesting at most 32 deep; every picture at most 100 MP (400 MP together), decoded with its declared size as
|
||||
the limit, and every asset a layer or object refers to must be present. A font must parse.
|
||||
|
||||
**Undo** is an operation log (`ops::Op`, `ops::History`): insert / remove / set a page, layer or object, replace an
|
||||
object, patch an asset's pixels, put an asset, a batch. Applying an operation returns its exact inverse.
|
||||
|
||||
**Rendering** goes through one display list (`display::build`): fills, strokes, images (with a clip), glyph runs
|
||||
(glyph outlines in font units, defined once) and opacity groups. The core paints it with tiny-skia; the app's
|
||||
canvas painter follows the same rules; the PDF and SVG exports walk it too.
|
||||
|
||||
**PDF export** (`export::pdf`): pdf-writer; vectors as paths, gradients as shading patterns (a gradient's stops
|
||||
share one alpha, their average), opacity as ExtGState alpha or an isolated transparency group, pictures as
|
||||
FlateDecode RGB with an SMask, text as Type 0 fonts (Identity-H, CIDs are the subset's glyph ids, CIDToGIDMap
|
||||
Identity) with a ToUnicode map and widths, so the layout's positions are kept with TJ adjustments; a font whose
|
||||
`fsType` is restricted or bitmap-only is refused with its name and the reason; fonts that forbid subsetting are
|
||||
embedded whole. Each page's MediaBox is its exact size.
|
||||
|
||||
## 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`, `newer` (a .pictor from a newer Pictor), `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.compress` | `doc`, `preset` (`email` ≤ 5 MB / `web` / `print`), `output` | `path`, `before`, `after`, `images_changed`, `warnings` |
|
||||
| `pdf.to_word` | `doc`, `output` (.docx), `ocr?` ({page: text} for scanned pages) | `path`, `pages`, `scanned_pages` |
|
||||
| `pdf.page_png` | `doc`, `page`, `dpi`, `output` | `path` (a page for OCR) |
|
||||
| `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` |
|
||||
| `doc.open` | `input`, `output` | `path`, `pages`, `format` (a clean .pictor of the worker's making at `output`) |
|
||||
| `doc.import_svg` | `input`, `output` | `path`, `width`, `height` (the SVG as a one-page .pictor; text as outlines) |
|
||||
| `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"
|
||||
+4
-3
@@ -32,11 +32,12 @@ export function allowed(expr) {
|
||||
}
|
||||
|
||||
function main() {
|
||||
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked', '--filter-platform', 'x86_64-pc-windows-msvc'], {
|
||||
// Every package in Cargo.lock (all platforms): a crate that is locked must be listed, whatever it is built for.
|
||||
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked'], {
|
||||
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.
|
||||
// resolve.nodes lists every package the lockfile resolves (all targets).
|
||||
|
||||
const used = new Set(meta.resolve.nodes.map((n) => n.id));
|
||||
const workspace = new Set(meta.workspace_members);
|
||||
const rows = meta.packages
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// The licence rule's SPDX evaluator (scripts/deps.mjs). Run: node --test scripts/deps.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { allowed } from './deps.mjs';
|
||||
|
||||
test('the allowed licences pass', () => {
|
||||
for (const l of ['MIT', 'Apache-2.0', 'BSD-3-Clause', 'Zlib', 'MPL-2.0', 'ISC', 'Unicode-3.0', 'MIT OR Apache-2.0', 'MIT/Apache-2.0', '(MIT OR Apache-2.0) AND Unicode-3.0', 'Apache-2.0 WITH LLVM-exception'])
|
||||
assert.ok(allowed(l), l);
|
||||
});
|
||||
|
||||
test('copyleft, non-commercial and missing licences fail', () => {
|
||||
for (const l of ['GPL-3.0', 'AGPL-3.0-only', 'LGPL-2.1', 'CC-BY-NC-4.0', 'MIT AND GPL-2.0', '', undefined, 'SSPL-1.0', 'OpenSSL'])
|
||||
assert.equal(allowed(l), false, String(l));
|
||||
});
|
||||
|
||||
test('OR needs one allowed branch, AND needs all', () => {
|
||||
assert.ok(allowed('GPL-2.0 OR MIT'));
|
||||
assert.equal(allowed('GPL-2.0 AND MIT'), false);
|
||||
assert.ok(allowed('(GPL-2.0 OR MIT) AND Apache-2.0'));
|
||||
});
|
||||
Reference in New Issue
Block a user