diff --git a/crates/pdf/src/edit.rs b/crates/pdf/src/edit.rs index 19b96b1..d5070d3 100644 --- a/crates/pdf/src/edit.rs +++ b/crates/pdf/src/edit.rs @@ -1,972 +1,1141 @@ -//! The edit pipeline, in this order: pages → form values → annotations and stamps → flatten → redaction → -//! password. Page indices in every edit refer to the page order *after* the page step. -//! -//! - Form values (lopdf): `/V` on the field, the checkbox and radio states through `/AS`; text and choice fields -//! get `NeedAppearances` and pdfium then builds their appearance when the document is loaded with its form -//! (which `flatten` relies on; see the forms test). -//! - Annotations and stamps (lopdf): every annotation is written with its own appearance stream, so it looks the -//! same in every viewer; a stamp (the visual signature) goes into the page content itself. -//! - Flatten (pdfium `FPDFPage_Flatten`), then lopdf drops the form and every orphaned object. -use crate::geometry::{PageFrame, ViewPoint, ViewRect, normalise_rotate}; -use crate::{Engine, PdfError, PageSpec, Redaction, RedactOptions, lopdf_load, lopdf_save}; -use image::DynamicImage; -use lopdf::{Dictionary, Document, Object, ObjectId, Stream, StringFormat, dictionary}; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct Edits { - #[serde(default)] - pub pages: Option>, - #[serde(default)] - pub form: Vec, - #[serde(default)] - pub annotations: Vec, - #[serde(default)] - pub stamps: Vec, - #[serde(default)] - pub flatten: bool, - #[serde(default)] - pub redactions: Vec, - #[serde(default)] - pub security: Security, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Security { - /// A protected document stays protected with the password it was opened with. - #[default] - Keep, - Remove, - Set { password: String }, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FieldValue { - /// The fully qualified field name ("parent.child"). - pub name: String, - pub value: FieldInput, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub enum FieldInput { - Text(String), - Check(bool), - /// A radio button's or a list's chosen option. - Choice(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Annotation { - pub page: usize, - #[serde(flatten)] - pub shape: Shape, - /// RGB, 0..1. - #[serde(default = "default_color")] - pub color: [f32; 3], - #[serde(default = "one")] - pub opacity: f32, - #[serde(default)] - pub contents: Option, -} - -fn default_color() -> [f32; 3] { - [1.0, 0.85, 0.0] -} -fn one() -> f32 { - 1.0 -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Shape { - Highlight { rects: Vec }, - Underline { rects: Vec }, - Strike { rects: Vec }, - /// A sticky note at a point; its text is `contents`. - Note { at: ViewPoint }, - FreeText { rect: ViewRect, text: String, size: f32 }, - Ink { strokes: Vec>, width: f32 }, - Rectangle { rect: ViewRect, width: f32 }, - Ellipse { rect: ViewRect, width: f32 }, - Line { from: ViewPoint, to: ViewPoint, width: f32, arrow: bool }, -} - -/// An image burned into a page (the visual signature): PNG or JPEG bytes, placed upright in `rect`. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Stamp { - pub page: usize, - pub rect: ViewRect, - #[serde(with = "b64")] - pub image: Vec, -} - -mod b64 { - use serde::{Deserialize, Deserializer, Serializer}; - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - pub fn serialize(v: &[u8], s: S) -> Result { - let mut out = String::with_capacity(v.len().div_ceil(3) * 4); - for c in v.chunks(3) { - let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; - for i in 0..4 { - if i <= c.len() { - out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - s.serialize_str(&out) - } - pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { - let s = String::deserialize(d)?; - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let (mut acc, mut bits) = (0u32, 0); - for ch in s.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=') { - let v = T.iter().position(|&t| t == ch).ok_or_else(|| serde::de::Error::custom("bad base64"))? as u32; - acc = acc << 6 | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - } - } - Ok(out) - } -} - -#[derive(Debug, Clone)] -pub struct Applied { - pub bytes: Vec, - pub warnings: Vec, -} - -/// Applies `edits` to the document and returns the new file. -pub fn apply(engine: &Engine, bytes: &[u8], password: Option<&str>, edits: &Edits) -> Result { - let mut warnings = Vec::new(); - let mut cur: Vec = match password { - Some(p) => crate::unlock(bytes, p)?, - None => bytes.to_vec(), - }; - if let Some(specs) = &edits.pages { - cur = crate::reorganise(&cur, None, specs)?; - } - if !edits.form.is_empty() { - cur = fill_form(engine, &cur, &edits.form)?; - } - if !edits.annotations.is_empty() || !edits.stamps.is_empty() { - let mut doc = lopdf_load(&cur, None)?; - let pages: Vec = doc.get_pages().values().copied().collect(); - if pages.is_empty() { - return Err(PdfError::Damaged("its page tree is damaged, so Pictor cannot add to its pages safely".into())); - } - for a in &edits.annotations { - let &page = pages.get(a.page).ok_or(PdfError::NoSuchPage(a.page + 1))?; - add_annotation(&mut doc, page, a)?; - } - for (i, s) in edits.stamps.iter().enumerate() { - let &page = pages.get(s.page).ok_or(PdfError::NoSuchPage(s.page + 1))?; - add_stamp(&mut doc, page, s, i)?; - } - cur = lopdf_save(&mut doc)?; - } - if edits.flatten { - cur = flatten(engine, &cur)?; - } - if !edits.redactions.is_empty() { - let r = crate::redact(engine, &cur, None, &edits.redactions, &RedactOptions::default())?; - warnings.extend(r.warnings); - cur = r.bytes; - } - match (&edits.security, password) { - (Security::Set { password }, _) => cur = crate::protect(&cur, None, password, None)?, - (Security::Keep, Some(p)) => { - cur = crate::protect(&cur, None, p, None)?; - } - _ => {} - } - Ok(Applied { bytes: cur, warnings }) -} - -// --------------------------------------------------------------------------------------------------------------- -// Geometry from lopdf (boxes and rotation, inherited ones included). - -fn inherited<'a>(doc: &'a Document, page: ObjectId, key: &[u8]) -> Option<&'a Object> { - let mut id = page; - for _ in 0..64 { - let d = doc.get_dictionary(id).ok()?; - if let Ok(v) = d.get(key) { - return Some(match v { - Object::Reference(r) => doc.get_object(*r).ok()?, - v => v, - }); - } - id = d.get(b"Parent").ok()?.as_reference().ok()?; - } - None -} - -fn number(o: &Object) -> Option { - match o { - Object::Integer(i) => Some(*i as f32), - Object::Real(r) => Some(*r), - _ => None, - } -} - -fn rect_of(o: Option<&Object>) -> Option<[f32; 4]> { - let a = o?.as_array().ok()?; - if a.len() != 4 { - return None; - } - let v: Vec = a.iter().filter_map(number).collect(); - (v.len() == 4).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) -} - -pub(crate) fn lopdf_frame(doc: &Document, page: ObjectId) -> PageFrame { - let media = rect_of(inherited(doc, page, b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]); - let crop = rect_of(inherited(doc, page, b"CropBox")) - .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])]) - .filter(|c| c[2] > c[0] && c[3] > c[1]) - .unwrap_or(media); - let rotate = inherited(doc, page, b"Rotate").and_then(|o| o.as_i64().ok()).map(normalise_rotate).unwrap_or(0); - PageFrame { crop, rotate } -} - -/// The matrix that draws a unit-less upright box (origin bottom-left, x right, y up, in points) at the view -/// rectangle `r`, whatever the page's rotation: [a b c d e f]. -fn upright_matrix(frame: &PageFrame, r: ViewRect) -> [f32; 6] { - let o = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h }); - let xr = frame.to_user(ViewPoint { x: r.x + 1.0, y: r.y + r.h }); - let yu = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h - 1.0 }); - [xr.0 - o.0, xr.1 - o.1, yu.0 - o.0, yu.1 - o.1, o.0, o.1] -} - -fn fmt(v: f32) -> String { - let s = format!("{v:.3}"); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" { "0".into() } else { s.into() } -} - -fn arr(v: &[f32]) -> Object { - Object::Array(v.iter().map(|&x| Object::Real(x)).collect()) -} - -/// A PDF text string: PDFDocEncoding when it is plain ASCII, else UTF-16BE with a BOM. -pub(crate) fn text_string(s: &str) -> Object { - if s.chars().all(|c| (' '..='~').contains(&c) || c == '\n') { - Object::String(s.as_bytes().to_vec(), StringFormat::Literal) - } else { - let mut v = vec![0xFE, 0xFF]; - for u in s.encode_utf16() { - v.extend_from_slice(&u.to_be_bytes()); - } - Object::String(v, StringFormat::Hexadecimal) - } -} - -fn add_to_annots(doc: &mut Document, page: ObjectId, annot: ObjectId) -> Result<(), PdfError> { - let existing = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Annots") { - Ok(Object::Array(a)) => a.clone(), - Ok(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), - _ => Vec::new(), - }; - let mut list = existing; - list.push(Object::Reference(annot)); - doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?.set("Annots", list); - Ok(()) -} - -// --------------------------------------------------------------------------------------------------------------- -// Annotations. - -/// Helvetica with WinAnsi plus the Czech and other Central European letters WinAnsi lacks (mapped into the unused -/// codes 1..31 through /Differences). Characters outside both become "?". -struct Latin2Font { - codes: Vec<(char, u8, &'static str)>, -} - -const EXTRA_GLYPHS: &[(char, &str)] = &[ - ('Á', "Aacute"), ('Č', "Ccaron"), ('č', "ccaron"), ('Ď', "Dcaron"), ('ď', "dcaron"), ('Ě', "Ecaron"), - ('ě', "ecaron"), ('Ň', "Ncaron"), ('ň', "ncaron"), ('Ř', "Rcaron"), ('ř', "rcaron"), ('Ť', "Tcaron"), - ('ť', "tcaron"), ('Ů', "Uring"), ('ů', "uring"), ('Ľ', "Lcaron"), ('ľ', "lcaron"), ('Ĺ', "Lacute"), - ('ĺ', "lacute"), ('Ŕ', "Racute"), ('ŕ', "racute"), ('Ą', "Aogonek"), ('ą', "aogonek"), ('Ę', "Eogonek"), - ('ę', "eogonek"), ('Ł', "Lslash"), ('ł', "lslash"), ('Ś', "Sacute"), ('ś', "sacute"), ('Ź', "Zacute"), - ('ź', "zacute"), ('Ż', "Zdotaccent"), ('ż', "zdotaccent"), ('Ć', "Cacute"), ('ć', "cacute"), ('Ń', "Nacute"), - ('ń', "nacute"), ('Ő', "Ohungarumlaut"), ('ő', "ohungarumlaut"), ('Ű', "Uhungarumlaut"), ('ű', "uhungarumlaut"), -]; - -fn winansi(c: char) -> Option { - let u = c as u32; - if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) { - return Some(u as u8); - } - const HIGH: &[(char, u8)] = &[ - ('€', 0x80), ('‚', 0x82), ('ƒ', 0x83), ('„', 0x84), ('…', 0x85), ('†', 0x86), ('‡', 0x87), ('ˆ', 0x88), - ('‰', 0x89), ('Š', 0x8A), ('‹', 0x8B), ('Œ', 0x8C), ('Ž', 0x8E), ('‘', 0x91), ('’', 0x92), ('“', 0x93), - ('”', 0x94), ('•', 0x95), ('–', 0x96), ('—', 0x97), ('˜', 0x98), ('™', 0x99), ('š', 0x9A), ('›', 0x9B), - ('œ', 0x9C), ('ž', 0x9E), ('Ÿ', 0x9F), - ]; - HIGH.iter().find(|(h, _)| *h == c).map(|(_, b)| *b) -} - -impl Latin2Font { - fn for_text(text: &str) -> Latin2Font { - let mut codes = Vec::new(); - let mut next = 1u8; - for c in text.chars() { - if winansi(c).is_some() || codes.iter().any(|(x, _, _)| *x == c) || next > 31 { - continue; - } - if let Some((_, name)) = EXTRA_GLYPHS.iter().find(|(g, _)| *g == c) { - codes.push((c, next, *name)); - next += 1; - } - } - Latin2Font { codes } - } - fn encode(&self, text: &str) -> Vec { - text.chars() - .map(|c| winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?')) - .collect() - } - fn dict(&self) -> Dictionary { - let mut enc = dictionary! {"Type" => "Encoding", "BaseEncoding" => "WinAnsiEncoding"}; - if !self.codes.is_empty() { - let mut diffs = Vec::new(); - for (_, code, name) in &self.codes { - diffs.push(Object::Integer(*code as i64)); - diffs.push(Object::Name(name.as_bytes().to_vec())); - } - enc.set("Differences", diffs); - } - dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => enc} - } -} - -fn pdf_string_bytes(b: &[u8]) -> String { - let mut s = String::from("("); - for &c in b { - match c { - b'(' | b')' | b'\\' => { - s.push('\\'); - s.push(c as char); - } - 32..=126 => s.push(c as char), - _ => s.push_str(&format!("\\{c:03o}")), - } - } - s.push(')'); - s -} - -/// Approximate Helvetica advance widths (per 1000 em) for wrapping free text. -fn helvetica_width(c: char) -> f32 { - match c { - 'i' | 'j' | 'l' | '\'' | '.' | ',' | ':' | ';' | '!' | '|' => 260.0, - 'f' | 't' | 'r' | 'I' | ' ' | '(' | ')' | '[' | ']' | '-' => 320.0, - 'm' | 'w' | 'M' | 'W' => 850.0, - 'A'..='Z' | 'Č' | 'Ř' | 'Š' | 'Ž' | 'Ů' | 'Ď' | 'Ť' | 'Ň' | 'Ě' => 680.0, - _ => 556.0, - } -} - -fn wrap(text: &str, size: f32, width: f32) -> Vec { - let mut lines = Vec::new(); - for para in text.split('\n') { - let mut line = String::new(); - let mut w = 0.0; - for word in para.split(' ') { - let ww: f32 = word.chars().map(helvetica_width).sum::() * size / 1000.0; - let space = if line.is_empty() { 0.0 } else { 320.0 * size / 1000.0 }; - if !line.is_empty() && w + space + ww > width { - lines.push(std::mem::take(&mut line)); - w = 0.0; - } else if !line.is_empty() { - line.push(' '); - w += space; - } - line.push_str(word); - w += ww; - } - lines.push(line); - } - lines -} - -fn check_view_rect(r: &ViewRect) -> Result<(), PdfError> { - if r.is_empty() || r.w > 1.0e5 || r.h > 1.0e5 { - return Err(PdfError::Invalid("An annotation has no size.".into())); - } - Ok(()) -} - -fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<(), PdfError> { - let frame = lopdf_frame(doc, page); - let [r, g, b] = a.color.map(|c| c.clamp(0.0, 1.0)); - let opacity = a.opacity.clamp(0.05, 1.0); - let rgb = format!("{} {} {}", fmt(r), fmt(g), fmt(b)); - let mut gs = dictionary! {"Type" => "ExtGState", "CA" => Object::Real(opacity), "ca" => Object::Real(opacity)}; - let (subtype, rect, content, extra): (&str, [f32; 4], String, Dictionary) = match &a.shape { - Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => { - if rects.is_empty() { - return Err(PdfError::Invalid("Mark some text first.".into())); - } - let mut quads = Vec::new(); - let mut ops = String::new(); - let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; - for vr in rects { - check_view_rect(vr)?; - // QuadPoints order: top-left, top-right, bottom-left, bottom-right (as the eye sees the text). - let tl = frame.to_user(ViewPoint { x: vr.x, y: vr.y }); - let tr = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y }); - let bl = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h }); - let br = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h }); - for p in [tl, tr, bl, br] { - quads.push(p.0); - quads.push(p.1); - bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; - } - match &a.shape { - Shape::Highlight { .. } => ops.push_str(&format!( - "{} {} m {} {} l {} {} l {} {} l h f\n", - fmt(tl.0), fmt(tl.1), fmt(tr.0), fmt(tr.1), fmt(br.0), fmt(br.1), fmt(bl.0), fmt(bl.1) - )), - _ => { - let t = if matches!(a.shape, Shape::Underline { .. }) { 0.93 } else { 0.55 }; - let lw = (vr.h * 0.07).max(0.8); - let p0 = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h * t }); - let p1 = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h * t }); - ops.push_str(&format!( - "{} w {} {} m {} {} l S\n", - fmt(lw), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1) - )); - } - } - } - let (sub, content) = match &a.shape { - Shape::Highlight { .. } => { - gs.set("BM", "Multiply"); - ("Highlight", format!("/GS0 gs {rgb} rg\n{ops}")) - } - Shape::Underline { .. } => ("Underline", format!("/GS0 gs {rgb} RG\n{ops}")), - _ => ("StrikeOut", format!("/GS0 gs {rgb} RG\n{ops}")), - }; - (sub, bounds, content, dictionary! {"QuadPoints" => arr(&quads)}) - } - Shape::Note { at } => { - let p = frame.to_user(*at); - let rect = [p.0, p.1 - 20.0, p.0 + 20.0, p.1]; - let [x, y] = [rect[0], rect[1]]; - let content = format!( - "/GS0 gs {rgb} rg 0.25 0.2 0.1 RG 1 w {x0} {y0} 18 18 re B\n0.25 0.2 0.1 RG 1 w {lx} {l1} m {rx} {l1} l {lx} {l2} m {rx} {l2} l {lx} {l3} m {rx2} {l3} l S\n", - x0 = fmt(x + 1.0), y0 = fmt(y + 1.0), lx = fmt(x + 4.0), rx = fmt(x + 16.0), rx2 = fmt(x + 12.0), - l1 = fmt(y + 14.0), l2 = fmt(y + 10.0), l3 = fmt(y + 6.0) - ); - ("Text", rect, content, dictionary! {"Name" => "Comment", "Open" => false}) - } - Shape::FreeText { rect: vr, text, size } => { - check_view_rect(vr)?; - let size = size.clamp(4.0, 144.0); - let font = Latin2Font::for_text(text); - let m = upright_matrix(&frame, *vr); - let mut ops = format!( - "/GS0 gs q {} {} {} {} {} {} cm BT /Helv {} Tf {rgb} rg {} TL\n", - fmt(m[0]), fmt(m[1]), fmt(m[2]), fmt(m[3]), fmt(m[4]), fmt(m[5]), fmt(size), fmt(size * 1.2) - ); - ops.push_str(&format!("2 {} Td\n", fmt(vr.h - size))); - for (i, line) in wrap(text, size, vr.w - 4.0).iter().enumerate() { - if (i as f32 + 1.0) * size * 1.2 > vr.h + size { - break; - } - if i > 0 { - ops.push_str("T*\n"); - } - ops.push_str(&pdf_string_bytes(&font.encode(line))); - ops.push_str(" Tj\n"); - } - ops.push_str("ET Q\n"); - let user = frame.rect_to_user(*vr); - let extra = dictionary! { - "DA" => Object::String(format!("/Helv {} Tf {rgb} rg", fmt(size)).into_bytes(), StringFormat::Literal), - "Contents" => text_string(text), - "PictorFont" => font.dict(), - }; - ("FreeText", user, ops, extra) - } - Shape::Ink { strokes, width } => { - let w = width.clamp(0.25, 72.0); - let mut ink = Vec::new(); - let mut ops = format!("/GS0 gs {rgb} RG {} w 1 J 1 j\n", fmt(w)); - let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; - for stroke in strokes.iter().filter(|s| !s.is_empty()).take(2000) { - let pts: Vec<(f32, f32)> = stroke.iter().take(20_000).map(|p| frame.to_user(*p)).collect(); - let mut flat = Vec::new(); - for (i, p) in pts.iter().enumerate() { - flat.push(p.0); - flat.push(p.1); - bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; - ops.push_str(&format!("{} {} {}\n", fmt(p.0), fmt(p.1), if i == 0 { "m" } else { "l" })); - } - if pts.len() == 1 { - ops.push_str(&format!("{} {} l\n", fmt(pts[0].0 + 0.01), fmt(pts[0].1))); - } - ops.push_str("S\n"); - ink.push(arr(&flat)); - } - if ink.is_empty() { - return Err(PdfError::Invalid("Draw something first.".into())); - } - let pad = w; - let rect = [bounds[0] - pad, bounds[1] - pad, bounds[2] + pad, bounds[3] + pad]; - ( - "Ink", - rect, - ops, - dictionary! {"InkList" => Object::Array(ink), "BS" => dictionary! {"W" => Object::Real(w)}}, - ) - } - Shape::Rectangle { rect: vr, width } | Shape::Ellipse { rect: vr, width } => { - check_view_rect(vr)?; - let w = width.clamp(0.25, 72.0); - let u = frame.rect_to_user(*vr); - let [x0, y0, x1, y1] = [u[0] + w / 2.0, u[1] + w / 2.0, u[2] - w / 2.0, u[3] - w / 2.0]; - let path = if matches!(a.shape, Shape::Rectangle { .. }) { - format!("{} {} {} {} re S\n", fmt(x0), fmt(y0), fmt(x1 - x0), fmt(y1 - y0)) - } else { - let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0, (y1 - y0) / 2.0); - let k = 0.552_284_8; - format!( - "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c S\n", - fmt(cx + rx), fmt(cy), - fmt(cx + rx), fmt(cy + k * ry), fmt(cx + k * rx), fmt(cy + ry), fmt(cx), fmt(cy + ry), - fmt(cx - k * rx), fmt(cy + ry), fmt(cx - rx), fmt(cy + k * ry), fmt(cx - rx), fmt(cy), - fmt(cx - rx), fmt(cy - k * ry), fmt(cx - k * rx), fmt(cy - ry), fmt(cx), fmt(cy - ry), - fmt(cx + k * rx), fmt(cy - ry), fmt(cx + rx), fmt(cy - k * ry), fmt(cx + rx), fmt(cy) - ) - }; - let sub = if matches!(a.shape, Shape::Rectangle { .. }) { "Square" } else { "Circle" }; - (sub, u, format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)), dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}}) - } - Shape::Line { from, to, width, arrow } => { - let w = width.clamp(0.25, 72.0); - let p0 = frame.to_user(*from); - let p1 = frame.to_user(*to); - let mut ops = format!("/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n", fmt(w), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1)); - let head = (w * 4.0).max(8.0); - if *arrow { - let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); - let len = (dx * dx + dy * dy).sqrt().max(0.001); - let (ux, uy) = (dx / len, dy / len); - let (bx, by) = (p1.0 - ux * head, p1.1 - uy * head); - let (px, py) = (-uy * head * 0.5, ux * head * 0.5); - ops.push_str(&format!( - "{} {} m {} {} l {} {} l h f\n", - fmt(p1.0), fmt(p1.1), fmt(bx + px), fmt(by + py), fmt(bx - px), fmt(by - py) - )); - } - let pad = head + w; - let rect = [p0.0.min(p1.0) - pad, p0.1.min(p1.1) - pad, p0.0.max(p1.0) + pad, p0.1.max(p1.1) + pad]; - let mut extra = dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}}; - if *arrow { - extra.set("LE", vec![Object::Name(b"None".to_vec()), Object::Name(b"OpenArrow".to_vec())]); - } - ("Line", rect, ops, extra) - } - }; - if !rect.iter().all(|v| v.is_finite()) { - return Err(PdfError::Invalid("An annotation lies outside the page.".into())); - } - let mut resources = dictionary! {"ExtGState" => dictionary! {"GS0" => gs}}; - let mut extra = extra; - if let Some(Object::Dictionary(font)) = extra.remove(b"PictorFont") { - resources.set("Font", dictionary! {"Helv" => font}); - } - let ap = doc.add_object(Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => arr(&rect), "Resources" => resources}, - content.into_bytes(), - )); - let mut annot = dictionary! { - "Type" => "Annot", "Subtype" => subtype, "Rect" => arr(&rect), "C" => arr(&[r, g, b]), - "F" => if subtype == "Text" { 28 } else { 4 }, "P" => page, - "AP" => dictionary! {"N" => ap}, - "NM" => Object::String(format!("pictor-{}", doc.max_id + 1).into_bytes(), StringFormat::Literal), - "T" => Object::String(b"Pictor".to_vec(), StringFormat::Literal), - }; - if let Some(c) = &a.contents { - annot.set("Contents", text_string(c)); - } - for (k, v) in extra.into_iter() { - annot.set(k, v); - } - let id = doc.add_object(annot); - add_to_annots(doc, page, id) -} - -// --------------------------------------------------------------------------------------------------------------- -// Stamps (the visual signature): an image drawn into the page content. - -fn add_stamp(doc: &mut Document, page: ObjectId, s: &Stamp, n: usize) -> Result<(), PdfError> { - check_view_rect(&s.rect)?; - if s.image.len() > 32 << 20 { - return Err(PdfError::TooLarge("the signature image is over 32 MB".into())); - } - let img: DynamicImage = image::load_from_memory(&s.image) - .map_err(|_| PdfError::Invalid("The signature image could not be read.".into()))?; - if (img.width() as u64) * (img.height() as u64) > 25_000_000 { - return Err(PdfError::TooLarge("the signature image is too large".into())); - } - let rgba = img.to_rgba8(); - let (w, h) = rgba.dimensions(); - let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); - let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); - let mut smask = Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, - "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, - alpha, - ); - let _ = smask.compress(); - let smask = doc.add_object(smask); - let mut im = Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, - "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "SMask" => smask}, - rgb, - ); - let _ = im.compress(); - let im = doc.add_object(im); - // Fit the image into the box, keeping its aspect ratio, centred. - let scale = (s.rect.w / w as f32).min(s.rect.h / h as f32); - let (dw, dh) = (w as f32 * scale, h as f32 * scale); - let r = ViewRect { x: s.rect.x + (s.rect.w - dw) / 2.0, y: s.rect.y + (s.rect.h - dh) / 2.0, w: dw, h: dh }; - let frame = lopdf_frame(doc, page); - let m = upright_matrix(&frame, r); - let name = format!("PictorStamp{n}"); - let ops = format!( - "q {} {} {} {} {} {} cm /{name} Do Q\n", - fmt(m[0] * dw), fmt(m[1] * dw), fmt(m[2] * dh), fmt(m[3] * dh), fmt(m[4]), fmt(m[5]) - ); - // Resources: a page-local copy (it may have been shared or inherited), with the image added. - let resources = match inherited(doc, page, b"Resources") { - Some(Object::Dictionary(d)) => d.clone(), - _ => Dictionary::new(), - }; - let mut resources = resources; - let mut xobjects = match resources.get(b"XObject") { - Ok(Object::Dictionary(d)) => d.clone(), - Ok(Object::Reference(r)) => doc.get_dictionary(*r).cloned().unwrap_or_default(), - _ => Dictionary::new(), - }; - xobjects.set(name.as_bytes(), im); - resources.set("XObject", xobjects); - // Contents: the old content wrapped in q … Q so its graphics state cannot leak into the stamp. - let old = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Contents") { - Ok(Object::Array(a)) => a.clone(), - Ok(Object::Reference(r)) => match doc.get_object(*r) { - Ok(Object::Array(a)) => a.clone(), - _ => vec![Object::Reference(*r)], - }, - _ => Vec::new(), - }; - let open = doc.add_object(Stream::new(dictionary! {}, b"q\n".to_vec())); - let close = doc.add_object(Stream::new(dictionary! {}, format!("\nQ\n{ops}").into_bytes())); - let mut contents = vec![Object::Reference(open)]; - contents.extend(old); - contents.push(Object::Reference(close)); - let d = doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?; - d.set("Resources", resources); - d.set("Contents", contents); - Ok(()) -} - -// --------------------------------------------------------------------------------------------------------------- -// Forms. - -#[derive(Debug, Clone, Serialize)] -pub struct FormField { - pub name: String, - /// "text", "checkbox", "radio", "choice", "signature" or "button". - pub kind: String, - pub value: String, - pub options: Vec, - pub page: Option, - pub rect: Option, - pub read_only: bool, - pub multiline: bool, -} - -struct Terminal { - name: String, - id: ObjectId, - widgets: Vec, -} - -fn field_tree(doc: &Document) -> Vec { - let Some(fields) = doc - .catalog() - .ok() - .and_then(|c| c.get(b"AcroForm").ok()) - .and_then(|f| match f { - Object::Reference(r) => doc.get_dictionary(*r).ok(), - Object::Dictionary(d) => Some(d), - _ => None, - }) - .and_then(|f| f.get(b"Fields").ok()) - .and_then(|f| match f { - Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_array().ok()), - Object::Array(a) => Some(a), - _ => None, - }) - else { - return Vec::new(); - }; - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - fn walk(doc: &Document, id: ObjectId, prefix: &str, out: &mut Vec, seen: &mut std::collections::HashSet, depth: u32) { - if depth > 32 || !seen.insert(id) || out.len() > 10_000 { - return; - } - let Ok(d) = doc.get_dictionary(id) else { return }; - let own = d.get(b"T").ok().and_then(|t| t.as_str().ok()).map(decode_text); - let name = match (&own, prefix.is_empty()) { - (Some(t), true) => t.clone(), - (Some(t), false) => format!("{prefix}.{t}"), - (None, _) => prefix.to_string(), - }; - let kids: Vec = match d.get(b"Kids") { - Ok(Object::Array(a)) => a.iter().filter_map(|k| k.as_reference().ok()).collect(), - _ => Vec::new(), - }; - // Kids with their own /T are fields; kids without are this field's widgets. - let (fields, widgets): (Vec, Vec) = - kids.iter().partition(|k| doc.get_dictionary(**k).map(|d| d.has(b"T")).unwrap_or(false)); - if fields.is_empty() { - let widgets = if widgets.is_empty() { vec![id] } else { widgets }; - out.push(Terminal { name, id, widgets }); - } else { - for f in fields { - walk(doc, f, &name, out, seen, depth + 1); - } - } - } - for f in fields.iter().filter_map(|f| f.as_reference().ok()) { - walk(doc, f, "", &mut out, &mut seen, 0); - } - out -} - -pub(crate) fn decode_text(b: &[u8]) -> String { - if b.starts_with(&[0xFE, 0xFF]) { - let u: Vec = b[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - String::from_utf16_lossy(&u) - } else { - b.iter().map(|&c| c as char).collect() - } -} - -fn field_attr<'a>(doc: &'a Document, id: ObjectId, key: &[u8]) -> Option<&'a Object> { - inherited(doc, id, key) -} - -fn on_state(doc: &Document, widget: ObjectId) -> Option> { - let ap = doc.get_dictionary(widget).ok()?.get(b"AP").ok()?; - let ap = match ap { - Object::Reference(r) => doc.get_dictionary(*r).ok()?, - Object::Dictionary(d) => d, - _ => return None, - }; - let n = match ap.get(b"N").ok()? { - Object::Reference(r) => doc.get_dictionary(*r).ok()?, - Object::Dictionary(d) => d, - _ => return None, - }; - n.iter().map(|(k, _)| k.clone()).find(|k| k != b"Off") -} - -/// The fields of the document's form, for the UI's form panel. -pub fn form_fields(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { - let doc = lopdf_load(bytes, password)?; - let pages: Vec = doc.get_pages().values().copied().collect(); - let mut out = Vec::new(); - for t in field_tree(&doc) { - let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b""); - let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); - let kind = match ft { - b"Tx" => "text", - b"Btn" if flags & (1 << 16) != 0 => "button", - b"Btn" if flags & (1 << 15) != 0 => "radio", - b"Btn" => "checkbox", - b"Ch" => "choice", - b"Sig" => "signature", - _ => continue, - }; - let value = match field_attr(&doc, t.id, b"V") { - Some(Object::String(s, _)) => decode_text(s), - Some(Object::Name(n)) => String::from_utf8_lossy(n).into_owned(), - _ => String::new(), - }; - let mut options = Vec::new(); - if kind == "choice" - && let Some(Object::Array(opts)) = field_attr(&doc, t.id, b"Opt") - { - for o in opts.iter().take(1000) { - let o = match o { - Object::Array(pair) => pair.get(1).cloned().unwrap_or(Object::Null), - o => o.clone(), - }; - if let Object::String(s, _) = o { - options.push(decode_text(&s)); - } - } - } - if kind == "radio" { - for w in &t.widgets { - if let Some(s) = on_state(&doc, *w) { - options.push(String::from_utf8_lossy(&s).into_owned()); - } - } - } - let first = t.widgets.first().copied(); - let page = first.and_then(|w| { - let p = doc.get_dictionary(w).ok()?.get(b"P").ok()?.as_reference().ok()?; - pages.iter().position(|x| *x == p) - }); - let page = page.or_else(|| { - first.and_then(|w| { - pages.iter().position(|p| match doc.get_dictionary(*p).ok().and_then(|d| d.get(b"Annots").ok()) { - Some(Object::Array(a)) => a.iter().any(|x| x.as_reference().ok() == Some(w)), - _ => false, - }) - }) - }); - let rect = match (page, first) { - (Some(p), Some(w)) => rect_of(doc.get_dictionary(w).ok().and_then(|d| d.get(b"Rect").ok())).map(|r| { - let f = lopdf_frame(&doc, pages[p]); - let pr = pdfium_render::prelude::PdfRect::new_from_values(r[1], r[0], r[3], r[2]); - f.user_to_view(pr) - }), - _ => None, - }; - out.push(FormField { - name: t.name, - kind: kind.into(), - value, - options, - page, - rect, - read_only: flags & 1 != 0, - multiline: kind == "text" && flags & (1 << 12) != 0, - }); - } - let _ = engine; - Ok(out) -} - -fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result, PdfError> { - let mut doc = lopdf_load(bytes, None)?; - let tree = field_tree(&doc); - let mut needs_appearances = false; - for v in values { - let t = tree - .iter() - .find(|t| t.name == v.name) - .ok_or_else(|| PdfError::Invalid(format!("This PDF has no field named \"{}\".", v.name)))?; - let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b"").to_vec(); - let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); - if flags & 1 != 0 { - return Err(PdfError::Invalid(format!("The field \"{}\" is read-only.", v.name))); - } - let set = |doc: &mut Document, id: ObjectId, key: &str, val: Object| { - if let Ok(d) = doc.get_dictionary_mut(id) { - d.set(key, val); - } - }; - match (&ft[..], &v.value) { - (b"Tx", FieldInput::Text(s)) | (b"Ch", FieldInput::Choice(s)) | (b"Ch", FieldInput::Text(s)) => { - set(&mut doc, t.id, "V", text_string(s)); - for w in &t.widgets { - if let Ok(d) = doc.get_dictionary_mut(*w) { - d.remove(b"AP"); - } - } - needs_appearances = true; - } - (b"Btn", FieldInput::Check(on)) if flags & (3 << 15) == 0 => { - for w in &t.widgets { - let state = if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() }; - set(&mut doc, *w, "AS", Object::Name(state.clone())); - set(&mut doc, t.id, "V", Object::Name(state)); - } - } - (b"Btn", FieldInput::Choice(choice)) if flags & (1 << 15) != 0 => { - let mut found = false; - for w in &t.widgets { - let on = on_state(&doc, *w); - let this = on.as_deref() == Some(choice.as_bytes()); - found |= this; - set(&mut doc, *w, "AS", Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() })); - } - if !found { - return Err(PdfError::Invalid(format!("\"{choice}\" is not an option of \"{}\".", v.name))); - } - set(&mut doc, t.id, "V", Object::Name(choice.as_bytes().to_vec())); - } - _ => return Err(PdfError::Invalid(format!("That value does not fit the field \"{}\".", v.name))), - } - } - if needs_appearances { - let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?; - let form = doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"AcroForm").ok()).cloned(); - match form { - Some(Object::Reference(r)) => { - if let Ok(d) = doc.get_dictionary_mut(r) { - d.set("NeedAppearances", true); - } - } - Some(Object::Dictionary(mut d)) => { - d.set("NeedAppearances", true); - if let Ok(c) = doc.get_dictionary_mut(catalog_id) { - c.set("AcroForm", d); - } - } - _ => {} - } - } - let plain = lopdf_save(&mut doc)?; - if !needs_appearances { - return Ok(plain); - } - // Let pdfium build the missing appearances (it does so when it loads a form with NeedAppearances), so viewers - // that ignore the flag show the values too. - regenerate_appearances(engine, &plain) -} - -fn regenerate_appearances(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { - let doc = engine.open(bytes, None)?; - for page in doc.pages().iter() { - // Rendering with the form draws every widget, which makes pdfium create its appearance stream. - let cfg = pdfium_render::prelude::PdfRenderConfig::new().set_target_width(64).render_form_data(true); - let _ = page.render_with_config(&cfg); - } - crate::engine::pdfium_save(&doc) -} - -/// Flattens annotations and form fields into the page content, then drops the form and every orphaned object. -pub fn flatten(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { - let mut doc = engine.open(bytes, None)?; - let n = doc.pages().len(); - for i in 0..n { - let mut page = doc.pages_mut().get(i).map_err(PdfError::from_pdfium)?; - page.flatten().map_err(PdfError::from_pdfium)?; - } - let flat = crate::engine::pdfium_save(&doc)?; - drop(doc); - let mut doc = lopdf_load(&flat, None)?; - if let Ok(catalog_id) = doc.trailer.get(b"Root").and_then(Object::as_reference) - && let Ok(c) = doc.get_dictionary_mut(catalog_id) - { - c.remove(b"AcroForm"); - } - doc.prune_objects(); - lopdf_save(&mut doc) -} +//! The edit pipeline, in this order: pages → form values → annotations and stamps → flatten → redaction → +//! password. Page indices in every edit refer to the page order *after* the page step. +//! +//! - Form values (lopdf): `/V` on the field, the checkbox and radio states through `/AS`; text and choice fields +//! get `NeedAppearances` and pdfium then builds their appearance when the document is loaded with its form +//! (which `flatten` relies on; see the forms test). +//! - Annotations and stamps (lopdf): every annotation is written with its own appearance stream, so it looks the +//! same in every viewer; a stamp (the visual signature) goes into the page content itself. +//! - Flatten (pdfium `FPDFPage_Flatten`), then lopdf drops the form and every orphaned object. +use crate::geometry::{PageFrame, ViewPoint, ViewRect, normalise_rotate}; +use crate::{Engine, PageSpec, PdfError, RedactOptions, Redaction, lopdf_load, lopdf_save}; +use image::DynamicImage; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, StringFormat, dictionary}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Edits { + #[serde(default)] + pub pages: Option>, + #[serde(default)] + pub form: Vec, + #[serde(default)] + pub annotations: Vec, + #[serde(default)] + pub stamps: Vec, + #[serde(default)] + pub flatten: bool, + #[serde(default)] + pub redactions: Vec, + #[serde(default)] + pub security: Security, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Security { + /// A protected document stays protected with the password it was opened with. + #[default] + Keep, + Remove, + Set { + password: String, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FieldValue { + /// The fully qualified field name ("parent.child"). + pub name: String, + pub value: FieldInput, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum FieldInput { + Text(String), + Check(bool), + /// A radio button's or a list's chosen option. + Choice(String), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Annotation { + pub page: usize, + #[serde(flatten)] + pub shape: Shape, + /// RGB, 0..1. + #[serde(default = "default_color")] + pub color: [f32; 3], + #[serde(default = "one")] + pub opacity: f32, + #[serde(default)] + pub contents: Option, +} + +fn default_color() -> [f32; 3] { + [1.0, 0.85, 0.0] +} +fn one() -> f32 { + 1.0 +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Shape { + Highlight { + rects: Vec, + }, + Underline { + rects: Vec, + }, + Strike { + rects: Vec, + }, + /// A sticky note at a point; its text is `contents`. + Note { + at: ViewPoint, + }, + FreeText { + rect: ViewRect, + text: String, + size: f32, + }, + Ink { + strokes: Vec>, + width: f32, + }, + Rectangle { + rect: ViewRect, + width: f32, + }, + Ellipse { + rect: ViewRect, + width: f32, + }, + Line { + from: ViewPoint, + to: ViewPoint, + width: f32, + arrow: bool, + }, +} + +/// An image burned into a page (the visual signature): PNG or JPEG bytes, placed upright in `rect`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Stamp { + pub page: usize, + pub rect: ViewRect, + #[serde(with = "b64")] + pub image: Vec, +} + +mod b64 { + use serde::{Deserialize, Deserializer, Serializer}; + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + pub fn serialize(v: &[u8], s: S) -> Result { + let mut out = String::with_capacity(v.len().div_ceil(3) * 4); + for c in v.chunks(3) { + let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; + for i in 0..4 { + if i <= c.len() { + out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + s.serialize_str(&out) + } + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let s = String::deserialize(d)?; + let mut out = Vec::with_capacity(s.len() / 4 * 3); + let (mut acc, mut bits) = (0u32, 0); + for ch in s.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=') { + let v = T.iter().position(|&t| t == ch).ok_or_else(|| serde::de::Error::custom("bad base64"))? as u32; + acc = acc << 6 | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + Ok(out) + } +} + +#[derive(Debug, Clone)] +pub struct Applied { + pub bytes: Vec, + pub warnings: Vec, +} + +/// Applies `edits` to the document and returns the new file. +pub fn apply(engine: &Engine, bytes: &[u8], password: Option<&str>, edits: &Edits) -> Result { + let mut warnings = Vec::new(); + let mut cur: Vec = match password { + Some(p) => crate::unlock(bytes, p)?, + None => bytes.to_vec(), + }; + if let Some(specs) = &edits.pages { + cur = crate::reorganise(&cur, None, specs)?; + } + if !edits.form.is_empty() { + cur = fill_form(engine, &cur, &edits.form)?; + } + if !edits.annotations.is_empty() || !edits.stamps.is_empty() { + let mut doc = lopdf_load(&cur, None)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + if pages.is_empty() { + return Err(PdfError::Damaged("its page tree is damaged, so Pictor cannot add to its pages safely".into())); + } + for a in &edits.annotations { + let &page = pages.get(a.page).ok_or(PdfError::NoSuchPage(a.page + 1))?; + add_annotation(&mut doc, page, a)?; + } + for (i, s) in edits.stamps.iter().enumerate() { + let &page = pages.get(s.page).ok_or(PdfError::NoSuchPage(s.page + 1))?; + add_stamp(&mut doc, page, s, i)?; + } + cur = lopdf_save(&mut doc)?; + } + if edits.flatten { + cur = flatten(engine, &cur)?; + } + if !edits.redactions.is_empty() { + let r = crate::redact(engine, &cur, None, &edits.redactions, &RedactOptions::default())?; + warnings.extend(r.warnings); + cur = r.bytes; + } + match (&edits.security, password) { + (Security::Set { password }, _) => cur = crate::protect(&cur, None, password, None)?, + (Security::Keep, Some(p)) => { + cur = crate::protect(&cur, None, p, None)?; + } + _ => {} + } + Ok(Applied { bytes: cur, warnings }) +} + +// --------------------------------------------------------------------------------------------------------------- +// Geometry from lopdf (boxes and rotation, inherited ones included). + +fn inherited<'a>(doc: &'a Document, page: ObjectId, key: &[u8]) -> Option<&'a Object> { + let mut id = page; + for _ in 0..64 { + let d = doc.get_dictionary(id).ok()?; + if let Ok(v) = d.get(key) { + return Some(match v { + Object::Reference(r) => doc.get_object(*r).ok()?, + v => v, + }); + } + id = d.get(b"Parent").ok()?.as_reference().ok()?; + } + None +} + +fn number(o: &Object) -> Option { + match o { + Object::Integer(i) => Some(*i as f32), + Object::Real(r) => Some(*r), + _ => None, + } +} + +fn rect_of(o: Option<&Object>) -> Option<[f32; 4]> { + let a = o?.as_array().ok()?; + if a.len() != 4 { + return None; + } + let v: Vec = a.iter().filter_map(number).collect(); + (v.len() == 4).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) +} + +pub(crate) fn lopdf_frame(doc: &Document, page: ObjectId) -> PageFrame { + let media = rect_of(inherited(doc, page, b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]); + let crop = rect_of(inherited(doc, page, b"CropBox")) + .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])]) + .filter(|c| c[2] > c[0] && c[3] > c[1]) + .unwrap_or(media); + let rotate = inherited(doc, page, b"Rotate").and_then(|o| o.as_i64().ok()).map(normalise_rotate).unwrap_or(0); + PageFrame { crop, rotate } +} + +/// The matrix that draws a unit-less upright box (origin bottom-left, x right, y up, in points) at the view +/// rectangle `r`, whatever the page's rotation: [a b c d e f]. +fn upright_matrix(frame: &PageFrame, r: ViewRect) -> [f32; 6] { + let o = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h }); + let xr = frame.to_user(ViewPoint { x: r.x + 1.0, y: r.y + r.h }); + let yu = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h - 1.0 }); + [xr.0 - o.0, xr.1 - o.1, yu.0 - o.0, yu.1 - o.1, o.0, o.1] +} + +fn fmt(v: f32) -> String { + let s = format!("{v:.3}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +fn arr(v: &[f32]) -> Object { + Object::Array(v.iter().map(|&x| Object::Real(x)).collect()) +} + +/// A PDF text string: PDFDocEncoding when it is plain ASCII, else UTF-16BE with a BOM. +pub(crate) fn text_string(s: &str) -> Object { + if s.chars().all(|c| (' '..='~').contains(&c) || c == '\n') { + Object::String(s.as_bytes().to_vec(), StringFormat::Literal) + } else { + let mut v = vec![0xFE, 0xFF]; + for u in s.encode_utf16() { + v.extend_from_slice(&u.to_be_bytes()); + } + Object::String(v, StringFormat::Hexadecimal) + } +} + +fn add_to_annots(doc: &mut Document, page: ObjectId, annot: ObjectId) -> Result<(), PdfError> { + let existing = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Annots") { + Ok(Object::Array(a)) => a.clone(), + Ok(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), + _ => Vec::new(), + }; + let mut list = existing; + list.push(Object::Reference(annot)); + doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?.set("Annots", list); + Ok(()) +} + +// --------------------------------------------------------------------------------------------------------------- +// Annotations. + +/// Helvetica with WinAnsi plus the Czech and other Central European letters WinAnsi lacks (mapped into the unused +/// codes 1..31 through /Differences). Characters outside both become "?". +struct Latin2Font { + codes: Vec<(char, u8, &'static str)>, +} + +const EXTRA_GLYPHS: &[(char, &str)] = &[ + ('Á', "Aacute"), + ('Č', "Ccaron"), + ('č', "ccaron"), + ('Ď', "Dcaron"), + ('ď', "dcaron"), + ('Ě', "Ecaron"), + ('ě', "ecaron"), + ('Ň', "Ncaron"), + ('ň', "ncaron"), + ('Ř', "Rcaron"), + ('ř', "rcaron"), + ('Ť', "Tcaron"), + ('ť', "tcaron"), + ('Ů', "Uring"), + ('ů', "uring"), + ('Ľ', "Lcaron"), + ('ľ', "lcaron"), + ('Ĺ', "Lacute"), + ('ĺ', "lacute"), + ('Ŕ', "Racute"), + ('ŕ', "racute"), + ('Ą', "Aogonek"), + ('ą', "aogonek"), + ('Ę', "Eogonek"), + ('ę', "eogonek"), + ('Ł', "Lslash"), + ('ł', "lslash"), + ('Ś', "Sacute"), + ('ś', "sacute"), + ('Ź', "Zacute"), + ('ź', "zacute"), + ('Ż', "Zdotaccent"), + ('ż', "zdotaccent"), + ('Ć', "Cacute"), + ('ć', "cacute"), + ('Ń', "Nacute"), + ('ń', "nacute"), + ('Ő', "Ohungarumlaut"), + ('ő', "ohungarumlaut"), + ('Ű', "Uhungarumlaut"), + ('ű', "uhungarumlaut"), +]; + +fn winansi(c: char) -> Option { + let u = c as u32; + if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) { + return Some(u as u8); + } + const HIGH: &[(char, u8)] = &[ + ('€', 0x80), + ('‚', 0x82), + ('ƒ', 0x83), + ('„', 0x84), + ('…', 0x85), + ('†', 0x86), + ('‡', 0x87), + ('ˆ', 0x88), + ('‰', 0x89), + ('Š', 0x8A), + ('‹', 0x8B), + ('Œ', 0x8C), + ('Ž', 0x8E), + ('‘', 0x91), + ('’', 0x92), + ('“', 0x93), + ('”', 0x94), + ('•', 0x95), + ('–', 0x96), + ('—', 0x97), + ('˜', 0x98), + ('™', 0x99), + ('š', 0x9A), + ('›', 0x9B), + ('œ', 0x9C), + ('ž', 0x9E), + ('Ÿ', 0x9F), + ]; + HIGH.iter().find(|(h, _)| *h == c).map(|(_, b)| *b) +} + +impl Latin2Font { + fn for_text(text: &str) -> Latin2Font { + let mut codes = Vec::new(); + let mut next = 1u8; + for c in text.chars() { + if winansi(c).is_some() || codes.iter().any(|(x, _, _)| *x == c) || next > 31 { + continue; + } + if let Some((_, name)) = EXTRA_GLYPHS.iter().find(|(g, _)| *g == c) { + codes.push((c, next, *name)); + next += 1; + } + } + Latin2Font { codes } + } + fn encode(&self, text: &str) -> Vec { + text.chars() + .map(|c| { + winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?') + }) + .collect() + } + fn dict(&self) -> Dictionary { + let mut enc = dictionary! {"Type" => "Encoding", "BaseEncoding" => "WinAnsiEncoding"}; + if !self.codes.is_empty() { + let mut diffs = Vec::new(); + for (_, code, name) in &self.codes { + diffs.push(Object::Integer(*code as i64)); + diffs.push(Object::Name(name.as_bytes().to_vec())); + } + enc.set("Differences", diffs); + } + dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => enc} + } +} + +fn pdf_string_bytes(b: &[u8]) -> String { + let mut s = String::from("("); + for &c in b { + match c { + b'(' | b')' | b'\\' => { + s.push('\\'); + s.push(c as char); + } + 32..=126 => s.push(c as char), + _ => s.push_str(&format!("\\{c:03o}")), + } + } + s.push(')'); + s +} + +/// Approximate Helvetica advance widths (per 1000 em) for wrapping free text. +fn helvetica_width(c: char) -> f32 { + match c { + 'i' | 'j' | 'l' | '\'' | '.' | ',' | ':' | ';' | '!' | '|' => 260.0, + 'f' | 't' | 'r' | 'I' | ' ' | '(' | ')' | '[' | ']' | '-' => 320.0, + 'm' | 'w' | 'M' | 'W' => 850.0, + 'A'..='Z' | 'Č' | 'Ř' | 'Š' | 'Ž' | 'Ů' | 'Ď' | 'Ť' | 'Ň' | 'Ě' => 680.0, + _ => 556.0, + } +} + +fn wrap(text: &str, size: f32, width: f32) -> Vec { + let mut lines = Vec::new(); + for para in text.split('\n') { + let mut line = String::new(); + let mut w = 0.0; + for word in para.split(' ') { + let ww: f32 = word.chars().map(helvetica_width).sum::() * size / 1000.0; + let space = if line.is_empty() { 0.0 } else { 320.0 * size / 1000.0 }; + if !line.is_empty() && w + space + ww > width { + lines.push(std::mem::take(&mut line)); + w = 0.0; + } else if !line.is_empty() { + line.push(' '); + w += space; + } + line.push_str(word); + w += ww; + } + lines.push(line); + } + lines +} + +fn check_view_rect(r: &ViewRect) -> Result<(), PdfError> { + if r.is_empty() || r.w > 1.0e5 || r.h > 1.0e5 { + return Err(PdfError::Invalid("An annotation has no size.".into())); + } + Ok(()) +} + +fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<(), PdfError> { + let frame = lopdf_frame(doc, page); + let [r, g, b] = a.color.map(|c| c.clamp(0.0, 1.0)); + let opacity = a.opacity.clamp(0.05, 1.0); + let rgb = format!("{} {} {}", fmt(r), fmt(g), fmt(b)); + let mut gs = dictionary! {"Type" => "ExtGState", "CA" => Object::Real(opacity), "ca" => Object::Real(opacity)}; + let (subtype, rect, content, extra): (&str, [f32; 4], String, Dictionary) = match &a.shape { + Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => { + if rects.is_empty() { + return Err(PdfError::Invalid("Mark some text first.".into())); + } + let mut quads = Vec::new(); + let mut ops = String::new(); + let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for vr in rects { + check_view_rect(vr)?; + // QuadPoints order: top-left, top-right, bottom-left, bottom-right (as the eye sees the text). + let tl = frame.to_user(ViewPoint { x: vr.x, y: vr.y }); + let tr = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y }); + let bl = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h }); + let br = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h }); + for p in [tl, tr, bl, br] { + quads.push(p.0); + quads.push(p.1); + bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; + } + match &a.shape { + Shape::Highlight { .. } => ops.push_str(&format!( + "{} {} m {} {} l {} {} l {} {} l h f\n", + fmt(tl.0), + fmt(tl.1), + fmt(tr.0), + fmt(tr.1), + fmt(br.0), + fmt(br.1), + fmt(bl.0), + fmt(bl.1) + )), + _ => { + let t = if matches!(a.shape, Shape::Underline { .. }) { 0.93 } else { 0.55 }; + let lw = (vr.h * 0.07).max(0.8); + let p0 = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h * t }); + let p1 = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h * t }); + ops.push_str(&format!( + "{} w {} {} m {} {} l S\n", + fmt(lw), + fmt(p0.0), + fmt(p0.1), + fmt(p1.0), + fmt(p1.1) + )); + } + } + } + let (sub, content) = match &a.shape { + Shape::Highlight { .. } => { + gs.set("BM", "Multiply"); + ("Highlight", format!("/GS0 gs {rgb} rg\n{ops}")) + } + Shape::Underline { .. } => ("Underline", format!("/GS0 gs {rgb} RG\n{ops}")), + _ => ("StrikeOut", format!("/GS0 gs {rgb} RG\n{ops}")), + }; + (sub, bounds, content, dictionary! {"QuadPoints" => arr(&quads)}) + } + Shape::Note { at } => { + let p = frame.to_user(*at); + let rect = [p.0, p.1 - 20.0, p.0 + 20.0, p.1]; + let [x, y] = [rect[0], rect[1]]; + let content = format!( + "/GS0 gs {rgb} rg 0.25 0.2 0.1 RG 1 w {x0} {y0} 18 18 re B\n0.25 0.2 0.1 RG 1 w {lx} {l1} m {rx} {l1} l {lx} {l2} m {rx} {l2} l {lx} {l3} m {rx2} {l3} l S\n", + x0 = fmt(x + 1.0), + y0 = fmt(y + 1.0), + lx = fmt(x + 4.0), + rx = fmt(x + 16.0), + rx2 = fmt(x + 12.0), + l1 = fmt(y + 14.0), + l2 = fmt(y + 10.0), + l3 = fmt(y + 6.0) + ); + ("Text", rect, content, dictionary! {"Name" => "Comment", "Open" => false}) + } + Shape::FreeText { rect: vr, text, size } => { + check_view_rect(vr)?; + let size = size.clamp(4.0, 144.0); + let font = Latin2Font::for_text(text); + let m = upright_matrix(&frame, *vr); + let mut ops = format!( + "/GS0 gs q {} {} {} {} {} {} cm BT /Helv {} Tf {rgb} rg {} TL\n", + fmt(m[0]), + fmt(m[1]), + fmt(m[2]), + fmt(m[3]), + fmt(m[4]), + fmt(m[5]), + fmt(size), + fmt(size * 1.2) + ); + ops.push_str(&format!("2 {} Td\n", fmt(vr.h - size))); + for (i, line) in wrap(text, size, vr.w - 4.0).iter().enumerate() { + if (i as f32 + 1.0) * size * 1.2 > vr.h + size { + break; + } + if i > 0 { + ops.push_str("T*\n"); + } + ops.push_str(&pdf_string_bytes(&font.encode(line))); + ops.push_str(" Tj\n"); + } + ops.push_str("ET Q\n"); + let user = frame.rect_to_user(*vr); + let extra = dictionary! { + "DA" => Object::String(format!("/Helv {} Tf {rgb} rg", fmt(size)).into_bytes(), StringFormat::Literal), + "Contents" => text_string(text), + "PictorFont" => font.dict(), + }; + ("FreeText", user, ops, extra) + } + Shape::Ink { strokes, width } => { + let w = width.clamp(0.25, 72.0); + let mut ink = Vec::new(); + let mut ops = format!("/GS0 gs {rgb} RG {} w 1 J 1 j\n", fmt(w)); + let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for stroke in strokes.iter().filter(|s| !s.is_empty()).take(2000) { + let pts: Vec<(f32, f32)> = stroke.iter().take(20_000).map(|p| frame.to_user(*p)).collect(); + let mut flat = Vec::new(); + for (i, p) in pts.iter().enumerate() { + flat.push(p.0); + flat.push(p.1); + bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; + ops.push_str(&format!("{} {} {}\n", fmt(p.0), fmt(p.1), if i == 0 { "m" } else { "l" })); + } + if pts.len() == 1 { + ops.push_str(&format!("{} {} l\n", fmt(pts[0].0 + 0.01), fmt(pts[0].1))); + } + ops.push_str("S\n"); + ink.push(arr(&flat)); + } + if ink.is_empty() { + return Err(PdfError::Invalid("Draw something first.".into())); + } + let pad = w; + let rect = [bounds[0] - pad, bounds[1] - pad, bounds[2] + pad, bounds[3] + pad]; + ( + "Ink", + rect, + ops, + dictionary! {"InkList" => Object::Array(ink), "BS" => dictionary! {"W" => Object::Real(w)}}, + ) + } + Shape::Rectangle { rect: vr, width } | Shape::Ellipse { rect: vr, width } => { + check_view_rect(vr)?; + let w = width.clamp(0.25, 72.0); + let u = frame.rect_to_user(*vr); + let [x0, y0, x1, y1] = [u[0] + w / 2.0, u[1] + w / 2.0, u[2] - w / 2.0, u[3] - w / 2.0]; + let path = if matches!(a.shape, Shape::Rectangle { .. }) { + format!("{} {} {} {} re S\n", fmt(x0), fmt(y0), fmt(x1 - x0), fmt(y1 - y0)) + } else { + let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0, (y1 - y0) / 2.0); + let k = 0.552_284_8; + format!( + "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c S\n", + fmt(cx + rx), + fmt(cy), + fmt(cx + rx), + fmt(cy + k * ry), + fmt(cx + k * rx), + fmt(cy + ry), + fmt(cx), + fmt(cy + ry), + fmt(cx - k * rx), + fmt(cy + ry), + fmt(cx - rx), + fmt(cy + k * ry), + fmt(cx - rx), + fmt(cy), + fmt(cx - rx), + fmt(cy - k * ry), + fmt(cx - k * rx), + fmt(cy - ry), + fmt(cx), + fmt(cy - ry), + fmt(cx + k * rx), + fmt(cy - ry), + fmt(cx + rx), + fmt(cy - k * ry), + fmt(cx + rx), + fmt(cy) + ) + }; + let sub = if matches!(a.shape, Shape::Rectangle { .. }) { "Square" } else { "Circle" }; + ( + sub, + u, + format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)), + dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}}, + ) + } + Shape::Line { from, to, width, arrow } => { + let w = width.clamp(0.25, 72.0); + let p0 = frame.to_user(*from); + let p1 = frame.to_user(*to); + let mut ops = format!( + "/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n", + fmt(w), + fmt(p0.0), + fmt(p0.1), + fmt(p1.0), + fmt(p1.1) + ); + let head = (w * 4.0).max(8.0); + if *arrow { + let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); + let len = (dx * dx + dy * dy).sqrt().max(0.001); + let (ux, uy) = (dx / len, dy / len); + let (bx, by) = (p1.0 - ux * head, p1.1 - uy * head); + let (px, py) = (-uy * head * 0.5, ux * head * 0.5); + ops.push_str(&format!( + "{} {} m {} {} l {} {} l h f\n", + fmt(p1.0), + fmt(p1.1), + fmt(bx + px), + fmt(by + py), + fmt(bx - px), + fmt(by - py) + )); + } + let pad = head + w; + let rect = [p0.0.min(p1.0) - pad, p0.1.min(p1.1) - pad, p0.0.max(p1.0) + pad, p0.1.max(p1.1) + pad]; + let mut extra = + dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}}; + if *arrow { + extra.set("LE", vec![Object::Name(b"None".to_vec()), Object::Name(b"OpenArrow".to_vec())]); + } + ("Line", rect, ops, extra) + } + }; + if !rect.iter().all(|v| v.is_finite()) { + return Err(PdfError::Invalid("An annotation lies outside the page.".into())); + } + let mut resources = dictionary! {"ExtGState" => dictionary! {"GS0" => gs}}; + let mut extra = extra; + if let Some(Object::Dictionary(font)) = extra.remove(b"PictorFont") { + resources.set("Font", dictionary! {"Helv" => font}); + } + let ap = doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => arr(&rect), "Resources" => resources}, + content.into_bytes(), + )); + let mut annot = dictionary! { + "Type" => "Annot", "Subtype" => subtype, "Rect" => arr(&rect), "C" => arr(&[r, g, b]), + "F" => if subtype == "Text" { 28 } else { 4 }, "P" => page, + "AP" => dictionary! {"N" => ap}, + "NM" => Object::String(format!("pictor-{}", doc.max_id + 1).into_bytes(), StringFormat::Literal), + "T" => Object::String(b"Pictor".to_vec(), StringFormat::Literal), + }; + if let Some(c) = &a.contents { + annot.set("Contents", text_string(c)); + } + for (k, v) in extra.into_iter() { + annot.set(k, v); + } + let id = doc.add_object(annot); + add_to_annots(doc, page, id) +} + +// --------------------------------------------------------------------------------------------------------------- +// Stamps (the visual signature): an image drawn into the page content. + +fn add_stamp(doc: &mut Document, page: ObjectId, s: &Stamp, n: usize) -> Result<(), PdfError> { + check_view_rect(&s.rect)?; + if s.image.len() > 32 << 20 { + return Err(PdfError::TooLarge("the signature image is over 32 MB".into())); + } + let img: DynamicImage = image::load_from_memory(&s.image) + .map_err(|_| PdfError::Invalid("The signature image could not be read.".into()))?; + if (img.width() as u64) * (img.height() as u64) > 25_000_000 { + return Err(PdfError::TooLarge("the signature image is too large".into())); + } + let rgba = img.to_rgba8(); + let (w, h) = rgba.dimensions(); + let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); + let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); + let mut smask = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, + alpha, + ); + let _ = smask.compress(); + let smask = doc.add_object(smask); + let mut im = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "SMask" => smask}, + rgb, + ); + let _ = im.compress(); + let im = doc.add_object(im); + // Fit the image into the box, keeping its aspect ratio, centred. + let scale = (s.rect.w / w as f32).min(s.rect.h / h as f32); + let (dw, dh) = (w as f32 * scale, h as f32 * scale); + let r = ViewRect { x: s.rect.x + (s.rect.w - dw) / 2.0, y: s.rect.y + (s.rect.h - dh) / 2.0, w: dw, h: dh }; + let frame = lopdf_frame(doc, page); + let m = upright_matrix(&frame, r); + let name = format!("PictorStamp{n}"); + let ops = format!( + "q {} {} {} {} {} {} cm /{name} Do Q\n", + fmt(m[0] * dw), + fmt(m[1] * dw), + fmt(m[2] * dh), + fmt(m[3] * dh), + fmt(m[4]), + fmt(m[5]) + ); + // Resources: a page-local copy (it may have been shared or inherited), with the image added. + let resources = match inherited(doc, page, b"Resources") { + Some(Object::Dictionary(d)) => d.clone(), + _ => Dictionary::new(), + }; + let mut resources = resources; + let mut xobjects = match resources.get(b"XObject") { + Ok(Object::Dictionary(d)) => d.clone(), + Ok(Object::Reference(r)) => doc.get_dictionary(*r).cloned().unwrap_or_default(), + _ => Dictionary::new(), + }; + xobjects.set(name.as_bytes(), im); + resources.set("XObject", xobjects); + // Contents: the old content wrapped in q … Q so its graphics state cannot leak into the stamp. + let old = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Contents") { + Ok(Object::Array(a)) => a.clone(), + Ok(Object::Reference(r)) => match doc.get_object(*r) { + Ok(Object::Array(a)) => a.clone(), + _ => vec![Object::Reference(*r)], + }, + _ => Vec::new(), + }; + let open = doc.add_object(Stream::new(dictionary! {}, b"q\n".to_vec())); + let close = doc.add_object(Stream::new(dictionary! {}, format!("\nQ\n{ops}").into_bytes())); + let mut contents = vec![Object::Reference(open)]; + contents.extend(old); + contents.push(Object::Reference(close)); + let d = doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?; + d.set("Resources", resources); + d.set("Contents", contents); + Ok(()) +} + +// --------------------------------------------------------------------------------------------------------------- +// Forms. + +#[derive(Debug, Clone, Serialize)] +pub struct FormField { + pub name: String, + /// "text", "checkbox", "radio", "choice", "signature" or "button". + pub kind: String, + pub value: String, + pub options: Vec, + pub page: Option, + pub rect: Option, + pub read_only: bool, + pub multiline: bool, +} + +struct Terminal { + name: String, + id: ObjectId, + widgets: Vec, +} + +fn field_tree(doc: &Document) -> Vec { + let Some(fields) = doc + .catalog() + .ok() + .and_then(|c| c.get(b"AcroForm").ok()) + .and_then(|f| match f { + Object::Reference(r) => doc.get_dictionary(*r).ok(), + Object::Dictionary(d) => Some(d), + _ => None, + }) + .and_then(|f| f.get(b"Fields").ok()) + .and_then(|f| match f { + Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_array().ok()), + Object::Array(a) => Some(a), + _ => None, + }) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); + fn walk( + doc: &Document, + id: ObjectId, + prefix: &str, + out: &mut Vec, + seen: &mut std::collections::HashSet, + depth: u32, + ) { + if depth > 32 || !seen.insert(id) || out.len() > 10_000 { + return; + } + let Ok(d) = doc.get_dictionary(id) else { return }; + let own = d.get(b"T").ok().and_then(|t| t.as_str().ok()).map(decode_text); + let name = match (&own, prefix.is_empty()) { + (Some(t), true) => t.clone(), + (Some(t), false) => format!("{prefix}.{t}"), + (None, _) => prefix.to_string(), + }; + let kids: Vec = match d.get(b"Kids") { + Ok(Object::Array(a)) => a.iter().filter_map(|k| k.as_reference().ok()).collect(), + _ => Vec::new(), + }; + // Kids with their own /T are fields; kids without are this field's widgets. + let (fields, widgets): (Vec, Vec) = + kids.iter().partition(|k| doc.get_dictionary(**k).map(|d| d.has(b"T")).unwrap_or(false)); + if fields.is_empty() { + let widgets = if widgets.is_empty() { vec![id] } else { widgets }; + out.push(Terminal { name, id, widgets }); + } else { + for f in fields { + walk(doc, f, &name, out, seen, depth + 1); + } + } + } + for f in fields.iter().filter_map(|f| f.as_reference().ok()) { + walk(doc, f, "", &mut out, &mut seen, 0); + } + out +} + +pub(crate) fn decode_text(b: &[u8]) -> String { + if b.starts_with(&[0xFE, 0xFF]) { + let u: Vec = b[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&u) + } else { + b.iter().map(|&c| c as char).collect() + } +} + +fn field_attr<'a>(doc: &'a Document, id: ObjectId, key: &[u8]) -> Option<&'a Object> { + inherited(doc, id, key) +} + +fn on_state(doc: &Document, widget: ObjectId) -> Option> { + let ap = doc.get_dictionary(widget).ok()?.get(b"AP").ok()?; + let ap = match ap { + Object::Reference(r) => doc.get_dictionary(*r).ok()?, + Object::Dictionary(d) => d, + _ => return None, + }; + let n = match ap.get(b"N").ok()? { + Object::Reference(r) => doc.get_dictionary(*r).ok()?, + Object::Dictionary(d) => d, + _ => return None, + }; + n.iter().map(|(k, _)| k.clone()).find(|k| k != b"Off") +} + +/// The fields of the document's form, for the UI's form panel. +pub fn form_fields(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = lopdf_load(bytes, password)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + let mut out = Vec::new(); + for t in field_tree(&doc) { + let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b""); + let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); + let kind = match ft { + b"Tx" => "text", + b"Btn" if flags & (1 << 16) != 0 => "button", + b"Btn" if flags & (1 << 15) != 0 => "radio", + b"Btn" => "checkbox", + b"Ch" => "choice", + b"Sig" => "signature", + _ => continue, + }; + let value = match field_attr(&doc, t.id, b"V") { + Some(Object::String(s, _)) => decode_text(s), + Some(Object::Name(n)) => String::from_utf8_lossy(n).into_owned(), + _ => String::new(), + }; + let mut options = Vec::new(); + if kind == "choice" + && let Some(Object::Array(opts)) = field_attr(&doc, t.id, b"Opt") + { + for o in opts.iter().take(1000) { + let o = match o { + Object::Array(pair) => pair.get(1).cloned().unwrap_or(Object::Null), + o => o.clone(), + }; + if let Object::String(s, _) = o { + options.push(decode_text(&s)); + } + } + } + if kind == "radio" { + for w in &t.widgets { + if let Some(s) = on_state(&doc, *w) { + options.push(String::from_utf8_lossy(&s).into_owned()); + } + } + } + let first = t.widgets.first().copied(); + let page = first.and_then(|w| { + let p = doc.get_dictionary(w).ok()?.get(b"P").ok()?.as_reference().ok()?; + pages.iter().position(|x| *x == p) + }); + let page = page.or_else(|| { + first.and_then(|w| { + pages.iter().position(|p| match doc.get_dictionary(*p).ok().and_then(|d| d.get(b"Annots").ok()) { + Some(Object::Array(a)) => a.iter().any(|x| x.as_reference().ok() == Some(w)), + _ => false, + }) + }) + }); + let rect = match (page, first) { + (Some(p), Some(w)) => rect_of(doc.get_dictionary(w).ok().and_then(|d| d.get(b"Rect").ok())).map(|r| { + let f = lopdf_frame(&doc, pages[p]); + let pr = pdfium_render::prelude::PdfRect::new_from_values(r[1], r[0], r[3], r[2]); + f.user_to_view(pr) + }), + _ => None, + }; + out.push(FormField { + name: t.name, + kind: kind.into(), + value, + options, + page, + rect, + read_only: flags & 1 != 0, + multiline: kind == "text" && flags & (1 << 12) != 0, + }); + } + let _ = engine; + Ok(out) +} + +fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, None)?; + let tree = field_tree(&doc); + let mut needs_appearances = false; + for v in values { + let t = tree + .iter() + .find(|t| t.name == v.name) + .ok_or_else(|| PdfError::Invalid(format!("This PDF has no field named \"{}\".", v.name)))?; + let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b"").to_vec(); + let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); + if flags & 1 != 0 { + return Err(PdfError::Invalid(format!("The field \"{}\" is read-only.", v.name))); + } + let set = |doc: &mut Document, id: ObjectId, key: &str, val: Object| { + if let Ok(d) = doc.get_dictionary_mut(id) { + d.set(key, val); + } + }; + match (&ft[..], &v.value) { + (b"Tx", FieldInput::Text(s)) | (b"Ch", FieldInput::Choice(s)) | (b"Ch", FieldInput::Text(s)) => { + set(&mut doc, t.id, "V", text_string(s)); + for w in &t.widgets { + if let Ok(d) = doc.get_dictionary_mut(*w) { + d.remove(b"AP"); + } + } + needs_appearances = true; + } + (b"Btn", FieldInput::Check(on)) if flags & (3 << 15) == 0 => { + for w in &t.widgets { + let state = + if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() }; + set(&mut doc, *w, "AS", Object::Name(state.clone())); + set(&mut doc, t.id, "V", Object::Name(state)); + } + } + (b"Btn", FieldInput::Choice(choice)) if flags & (1 << 15) != 0 => { + let mut found = false; + for w in &t.widgets { + let on = on_state(&doc, *w); + let this = on.as_deref() == Some(choice.as_bytes()); + found |= this; + set( + &mut doc, + *w, + "AS", + Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() }), + ); + } + if !found { + return Err(PdfError::Invalid(format!("\"{choice}\" is not an option of \"{}\".", v.name))); + } + set(&mut doc, t.id, "V", Object::Name(choice.as_bytes().to_vec())); + } + _ => return Err(PdfError::Invalid(format!("That value does not fit the field \"{}\".", v.name))), + } + } + if needs_appearances { + let catalog_id = + doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?; + let form = doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"AcroForm").ok()).cloned(); + match form { + Some(Object::Reference(r)) => { + if let Ok(d) = doc.get_dictionary_mut(r) { + d.set("NeedAppearances", true); + } + } + Some(Object::Dictionary(mut d)) => { + d.set("NeedAppearances", true); + if let Ok(c) = doc.get_dictionary_mut(catalog_id) { + c.set("AcroForm", d); + } + } + _ => {} + } + } + let plain = lopdf_save(&mut doc)?; + if !needs_appearances { + return Ok(plain); + } + // Let pdfium build the missing appearances (it does so when it loads a form with NeedAppearances), so viewers + // that ignore the flag show the values too. + regenerate_appearances(engine, &plain) +} + +fn regenerate_appearances(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { + let doc = engine.open(bytes, None)?; + for page in doc.pages().iter() { + // Rendering with the form draws every widget, which makes pdfium create its appearance stream. + let cfg = pdfium_render::prelude::PdfRenderConfig::new().set_target_width(64).render_form_data(true); + let _ = page.render_with_config(&cfg); + } + crate::engine::pdfium_save(&doc) +} + +/// Flattens annotations and form fields into the page content, then drops the form and every orphaned object. +pub fn flatten(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { + let mut doc = engine.open(bytes, None)?; + let n = doc.pages().len(); + for i in 0..n { + let mut page = doc.pages_mut().get(i).map_err(PdfError::from_pdfium)?; + page.flatten().map_err(PdfError::from_pdfium)?; + } + let flat = crate::engine::pdfium_save(&doc)?; + drop(doc); + let mut doc = lopdf_load(&flat, None)?; + if let Ok(catalog_id) = doc.trailer.get(b"Root").and_then(Object::as_reference) + && let Ok(c) = doc.get_dictionary_mut(catalog_id) + { + c.remove(b"AcroForm"); + } + doc.prune_objects(); + lopdf_save(&mut doc) +} diff --git a/crates/pdf/src/engine.rs b/crates/pdf/src/engine.rs index a63468f..8a308b0 100644 --- a/crates/pdf/src/engine.rs +++ b/crates/pdf/src/engine.rs @@ -32,7 +32,9 @@ impl Engine { } pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result, PdfError> { - self.pdfium.load_pdf_from_byte_slice(bytes, password).map_err(|e| PdfError::from_pdfium_open(e, password.is_some())) + self.pdfium + .load_pdf_from_byte_slice(bytes, password) + .map_err(|e| PdfError::from_pdfium_open(e, password.is_some())) } pub(crate) fn new_document(&self) -> Result, PdfError> { diff --git a/crates/pdf/src/geometry.rs b/crates/pdf/src/geometry.rs index 11412ae..8bb9e5e 100644 --- a/crates/pdf/src/geometry.rs +++ b/crates/pdf/src/geometry.rs @@ -61,7 +61,7 @@ impl PageFrame { } pub(crate) fn normalise_rotate(r: i64) -> u16 { - (((r % 360) + 360) % 360 / 90 * 90) as u16 + (r.rem_euclid(360) / 90 * 90) as u16 } #[cfg(test)] diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 1fe854d..1d4061f 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -20,7 +20,7 @@ mod security; pub use edit::*; pub use engine::Engine; pub use error::PdfError; -pub use geometry::{ViewRect, ViewPoint}; +pub use geometry::{ViewPoint, ViewRect}; pub use pages::*; pub use reader::*; pub use redact::{RedactOptions, Redacted, Redaction, redact}; @@ -28,8 +28,7 @@ pub use security::{is_encrypted, protect, unlock}; /// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB). pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result { - let mut opts = lopdf::LoadOptions::default(); - opts.max_decompressed_size = Some(256 << 20); + let mut opts = lopdf::LoadOptions { max_decompressed_size: Some(256 << 20), ..Default::default() }; if let Some(p) = password { opts.password = Some(p.to_owned()); } diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 59fa886..3cc54bd 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -1,299 +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 { - doc.catalog() - .ok() - .and_then(|c| c.get(b"Pages").ok()) - .and_then(|p| p.as_reference().ok()) - .ok_or_else(|| PdfError::Damaged("it has no page tree".into())) -} - -/// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields -/// that only lived on them. -pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result, PdfError> { - let mut doc = lopdf_load(bytes, password)?; - reorganise_doc(&mut doc, specs)?; - doc.prune_objects(); - lopdf_save(&mut doc) -} - -pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> { - if specs.is_empty() { - return Err(PdfError::Invalid("A PDF needs at least one page.".into())); - } - let pages: Vec = doc.get_pages().values().copied().collect(); - materialise_inherited(doc, &pages); - let root = pages_root(doc)?; - let mut used = HashSet::new(); - let mut kids = Vec::new(); - for spec in specs { - match *spec { - PageSpec::Existing { index, rotate } => { - let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?; - if rotate % 90 != 0 { - return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into())); - } - // The same page twice: the second is a shallow copy (its content and resources are shared). - let id = if used.insert(src) { - src - } else { - let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); - let mut copy = copy; - copy.remove(b"Annots"); - doc.add_object(copy) - }; - let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?; - let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0); - d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64); - d.set("Parent", root); - kids.push(Object::Reference(id)); - } - PageSpec::Blank { width, height } => { - if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) { - return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into())); - } - let content = doc.add_object(Stream::new(dictionary! {}, Vec::new())); - let id = doc.add_object(dictionary! { - "Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {}, - "MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)], - }); - kids.push(Object::Reference(id)); - } - } - } - // Annotations of deleted pages, and the fields that only lived there. - let mut removed = HashSet::new(); - for p in pages.iter().filter(|p| !used.contains(*p)) { - if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) { - removed.extend(a.iter().filter_map(|o| o.as_reference().ok())); - } - } - crate::redact::prune_form_pub(doc, &removed); - // Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead - // nowhere, which every viewer tolerates); so do their annotations. - for p in pages.iter().filter(|p| !used.contains(*p)) { - doc.objects.remove(p); - } - for a in &removed { - doc.objects.remove(a); - } - let count = kids.len() as i64; - let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); - for key in INHERITABLE { - root_dict.remove(key); - } - root_dict.set("Kids", kids); - root_dict.set("Count", count); - root_dict.remove(b"Parent"); - doc.objects.insert(root, Object::Dictionary(root_dict)); - Ok(()) -} - -/// One document per range; `ranges` are 0-based inclusive page index pairs. -pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result>, PdfError> { - let mut out = Vec::new(); - for &(a, b) in ranges { - if a > b { - return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1))); - } - let specs: Vec = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect(); - out.push(reorganise(bytes, password, &specs)?); - } - Ok(out) -} - -/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages. -pub fn parse_ranges(text: &str, pages: usize) -> Result, PdfError> { - let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-.")); - let mut out = Vec::new(); - for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { - let (a, b) = match part.split_once(['-', '–']) { - Some((a, b)) => { - let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? }; - let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? }; - (a, b) - } - None => { - let n: usize = part.parse().map_err(|_| bad())?; - (n, n) - } - }; - if a == 0 || b == 0 || a > pages || b > pages { - return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them."))); - } - if a > b { - return Err(bad()); - } - out.push((a - 1, b - 1)); - } - if out.is_empty() { - return Err(bad()); - } - Ok(out) -} - -/// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look -/// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over. -pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result, PdfError> { - if inputs.len() < 2 { - return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into())); - } - let mut target = engine.new_document()?; - for (i, (bytes, password)) in inputs.iter().enumerate() { - let source = engine.open(bytes, *password).map_err(|e| match e { - PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)), - other => other, - })?; - target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?; - } - crate::engine::pdfium_save(&target) -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PageFit { - /// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one). - Image, - /// A4 portrait or landscape (whichever suits the image), with a margin. - A4, - Letter, -} - -/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly. -pub fn images_to_pdf(images: &[(Vec, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result, PdfError> { - if images.is_empty() { - return Err(PdfError::Invalid("Choose at least one image.".into())); - } - let mut doc = Document::with_version("1.7"); - let pages_id = doc.new_object_id(); - let mut kids = Vec::new(); - for (bytes, img) in images { - let (w, h) = img.dimensions(); - let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]); - let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) { - let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" }; - let mut s = Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, - "ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"}, - bytes.clone(), - ); - s.allows_compression = false; - doc.add_object(s) - } else { - let rgba = img.to_rgba8(); - let has_alpha = rgba.pixels().any(|p| p.0[3] != 255); - let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); - let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, - "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}; - if has_alpha { - let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); - let mut smask = Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, - "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, - alpha, - ); - let _ = smask.compress(); - dict.set("SMask", doc.add_object(smask)); - } - let mut s = Stream::new(dict, rgb); - let _ = s.compress(); - doc.add_object(s) - }; - let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75); - let (pw, ph) = match fit { - PageFit::Image => (iw, ih), - PageFit::A4 | PageFit::Letter => { - let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) }; - if w > h { (b, a) } else { (a, b) } - } - }; - let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) }; - let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image { 1.0 } else { f32::MAX }); - let (dw, dh) = (iw * scale, ih * scale); - let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0); - let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes(); - let content_id = doc.add_object(Stream::new(dictionary! {}, content)); - let page = doc.add_object(dictionary! { - "Type" => "Page", "Parent" => pages_id, "Contents" => content_id, - "MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)], - "Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])}, - }); - kids.push(Object::Reference(page)); - } - let count = kids.len() as i64; - doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count})); - let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); - doc.trailer.set("Root", catalog); - lopdf_save(&mut doc) -} - -/// Renders the chosen pages (0-based) at `dpi`. -pub fn pages_to_images( - engine: &Engine, - bytes: &[u8], - password: Option<&str>, - pages: &[usize], - dpi: u32, -) -> Result, PdfError> { - let doc = engine.open(bytes, password)?; - let mut out = Vec::new(); - for &i in pages { - let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?; - let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32; - drop(page); - out.push(render_doc_page(&doc, i, width, true)?); - } - Ok(out) -} +//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form, +//! bookmarks and everything else of the document stay; merge with pdfium's page import; images → PDF with lopdf +//! (a JPEG goes in as it is, without re-encoding); PDF → images with pdfium. +use crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page}; +use image::{DynamicImage, GenericImageView}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; + +/// One page of the new order. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PageSpec { + /// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90). + Existing { + index: usize, + #[serde(default)] + rotate: i32, + }, + /// A blank page of this size in points. + Blank { width: f32, height: f32 }, +} + +const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"]; + +/// Copies inherited attributes down onto each page, so pages can be moved freely. +fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) { + for &page in pages { + for key in INHERITABLE { + if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) { + continue; + } + let mut current = + doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok()); + let mut depth = 0; + let mut value = None; + while let Some(id) = current { + depth += 1; + if depth > 64 { + break; + } + let Ok(d) = doc.get_dictionary(id) else { break }; + if let Ok(v) = d.get(key) { + value = Some(v.clone()); + break; + } + current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + } + if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) { + d.set(key, v); + } + } + } +} + +fn pages_root(doc: &Document) -> Result { + doc.catalog() + .ok() + .and_then(|c| c.get(b"Pages").ok()) + .and_then(|p| p.as_reference().ok()) + .ok_or_else(|| PdfError::Damaged("it has no page tree".into())) +} + +/// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields +/// that only lived on them. +pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, password)?; + reorganise_doc(&mut doc, specs)?; + doc.prune_objects(); + lopdf_save(&mut doc) +} + +pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> { + if specs.is_empty() { + return Err(PdfError::Invalid("A PDF needs at least one page.".into())); + } + let pages: Vec = doc.get_pages().values().copied().collect(); + materialise_inherited(doc, &pages); + let root = pages_root(doc)?; + let mut used = HashSet::new(); + let mut kids = Vec::new(); + for spec in specs { + match *spec { + PageSpec::Existing { index, rotate } => { + let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?; + if rotate % 90 != 0 { + return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into())); + } + // The same page twice: the second is a shallow copy (its content and resources are shared). + let id = if used.insert(src) { + src + } else { + let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + let mut copy = copy; + copy.remove(b"Annots"); + doc.add_object(copy) + }; + let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?; + let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0); + d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64); + d.set("Parent", root); + kids.push(Object::Reference(id)); + } + PageSpec::Blank { width, height } => { + if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) { + return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into())); + } + let content = doc.add_object(Stream::new(dictionary! {}, Vec::new())); + let id = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {}, + "MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)], + }); + kids.push(Object::Reference(id)); + } + } + } + // Annotations of deleted pages, and the fields that only lived there. + let mut removed = HashSet::new(); + for p in pages.iter().filter(|p| !used.contains(*p)) { + if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) { + removed.extend(a.iter().filter_map(|o| o.as_reference().ok())); + } + } + crate::redact::prune_form_pub(doc, &removed); + // Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead + // nowhere, which every viewer tolerates); so do their annotations. + for p in pages.iter().filter(|p| !used.contains(*p)) { + doc.objects.remove(p); + } + for a in &removed { + doc.objects.remove(a); + } + let count = kids.len() as i64; + let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + for key in INHERITABLE { + root_dict.remove(key); + } + root_dict.set("Kids", kids); + root_dict.set("Count", count); + root_dict.remove(b"Parent"); + doc.objects.insert(root, Object::Dictionary(root_dict)); + Ok(()) +} + +/// One document per range; `ranges` are 0-based inclusive page index pairs. +pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result>, PdfError> { + let mut out = Vec::new(); + for &(a, b) in ranges { + if a > b { + return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1))); + } + let specs: Vec = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect(); + out.push(reorganise(bytes, password, &specs)?); + } + Ok(out) +} + +/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages. +pub fn parse_ranges(text: &str, pages: usize) -> Result, PdfError> { + let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-.")); + let mut out = Vec::new(); + for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { + let (a, b) = match part.split_once(['-', '–']) { + Some((a, b)) => { + let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? }; + let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? }; + (a, b) + } + None => { + let n: usize = part.parse().map_err(|_| bad())?; + (n, n) + } + }; + if a == 0 || b == 0 || a > pages || b > pages { + return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them."))); + } + if a > b { + return Err(bad()); + } + out.push((a - 1, b - 1)); + } + if out.is_empty() { + return Err(bad()); + } + Ok(out) +} + +/// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look +/// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over. +pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result, PdfError> { + if inputs.len() < 2 { + return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into())); + } + let mut target = engine.new_document()?; + for (i, (bytes, password)) in inputs.iter().enumerate() { + let source = engine.open(bytes, *password).map_err(|e| match e { + PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)), + other => other, + })?; + target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?; + } + crate::engine::pdfium_save(&target) +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PageFit { + /// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one). + Image, + /// A4 portrait or landscape (whichever suits the image), with a margin. + A4, + Letter, +} + +/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly. +pub fn images_to_pdf(images: &[(Vec, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result, PdfError> { + if images.is_empty() { + return Err(PdfError::Invalid("Choose at least one image.".into())); + } + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let mut kids = Vec::new(); + for (bytes, img) in images { + let (w, h) = img.dimensions(); + let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]); + let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) { + let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" }; + let mut s = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"}, + bytes.clone(), + ); + s.allows_compression = false; + doc.add_object(s) + } else { + let rgba = img.to_rgba8(); + let has_alpha = rgba.pixels().any(|p| p.0[3] != 255); + let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); + let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, + "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}; + if has_alpha { + let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); + let mut smask = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, + "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, + alpha, + ); + let _ = smask.compress(); + dict.set("SMask", doc.add_object(smask)); + } + let mut s = Stream::new(dict, rgb); + let _ = s.compress(); + doc.add_object(s) + }; + let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75); + let (pw, ph) = match fit { + PageFit::Image => (iw, ih), + PageFit::A4 | PageFit::Letter => { + let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) }; + if w > h { (b, a) } else { (a, b) } + } + }; + let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) }; + let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image { + 1.0 + } else { + f32::MAX + }); + let (dw, dh) = (iw * scale, ih * scale); + let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0); + let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes(); + let content_id = doc.add_object(Stream::new(dictionary! {}, content)); + let page = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => content_id, + "MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)], + "Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])}, + }); + kids.push(Object::Reference(page)); + } + let count = kids.len() as i64; + doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count})); + let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); + doc.trailer.set("Root", catalog); + lopdf_save(&mut doc) +} + +/// Renders the chosen pages (0-based) at `dpi`. +pub fn pages_to_images( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + pages: &[usize], + dpi: u32, +) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for &i in pages { + let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?; + let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32; + drop(page); + out.push(render_doc_page(&doc, i, width, true)?); + } + Ok(out) +} diff --git a/crates/pdf/src/reader.rs b/crates/pdf/src/reader.rs index e4699f9..ae2ab44 100644 --- a/crates/pdf/src/reader.rs +++ b/crates/pdf/src/reader.rs @@ -1,184 +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, - pub outline: Vec, - pub has_form: bool, - pub encrypted: bool, -} - -#[derive(Debug, Clone, Serialize)] -pub struct PageInfo { - /// Displayed size in points. - pub width: f32, - pub height: f32, - pub label: Option, -} - -#[derive(Debug, Clone, Serialize)] -pub struct OutlineItem { - pub title: String, - pub page: Option, - pub depth: u32, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SearchHit { - pub page: usize, - /// The hit's boxes in view space. - pub rects: Vec, -} - -pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { - let doc = engine.open(bytes, password)?; - let mut pages = Vec::new(); - for page in doc.pages().iter() { - pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); - } - let mut outline = Vec::new(); - fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { - if *budget == 0 || depth > 32 { - return; - } - *budget -= 1; - let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); - out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); - if let Some(child) = b.first_child() { - let mut next = Some(child); - while let Some(c) = next { - next = c.next_sibling(); - walk(c, depth + 1, out, budget); - } - } - } - let mut budget = 5000; - let mut next = doc.bookmarks().root(); - while let Some(b) = next { - next = b.next_sibling(); - walk(b, 0, &mut outline, &mut budget); - } - let has_form = doc.form().is_some(); - Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) -} - -/// The displayed size of every page, in points. -pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { - let doc = engine.open(bytes, password)?; - Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) -} - -pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result { - let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; - let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); - let width = width_px.clamp(1, 20_000) as i64; - let height = ((width as f32) * h / w).ceil().max(1.0) as i64; - if width * height > MAX_RENDER_PIXELS { - return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); - } - let cfg = PdfRenderConfig::new() - .set_target_size(width as i32, height as i32) - .render_form_data(forms) - .render_annotations(true) - .set_clear_color(PdfColor::WHITE); - page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) -} - -/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. -pub fn render_page( - engine: &Engine, - bytes: &[u8], - password: Option<&str>, - index: usize, - width_px: u32, -) -> Result { - let doc = engine.open(bytes, password)?; - render_doc_page(&doc, index, width_px, true) -} - -/// The text of every page, in order. -pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { - let doc = engine.open(bytes, password)?; - let mut out = Vec::new(); - for page in doc.pages().iter() { - out.push(page_text(&page)?); - } - Ok(out) -} - -/// Case-insensitive search over every page; at most `limit` hits. -pub fn search( - engine: &Engine, - bytes: &[u8], - password: Option<&str>, - query: &str, - limit: usize, -) -> Result, PdfError> { - if query.trim().is_empty() { - return Ok(Vec::new()); - } - let doc = engine.open(bytes, password)?; - let mut hits = Vec::new(); - for (i, page) in doc.pages().iter().enumerate() { - let frame = page_frame(&page); - let text = page.text().map_err(PdfError::from_pdfium)?; - let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; - while let Some(segments) = search.find_next() { - let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); - hits.push(SearchHit { page: i, rects }); - if hits.len() >= limit { - return Ok(hits); - } - } - } - Ok(hits) -} - -/// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with -/// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.) -pub(crate) fn page_text(page: &PdfPage) -> Result { - let text = page.text().map_err(PdfError::from_pdfium)?; - Ok(text.inside_rect(PdfRect::new_from_values(-1.0e6, -1.0e6, 1.0e6, 1.0e6))) -} - -pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { - // `bounding` is pdfium's effective crop box (inherited boxes included); crop/media only read the page itself. - let crop = page - .boundaries() - .bounding() - .or_else(|_| page.boundaries().crop()) - .or_else(|_| page.boundaries().media()) - .map(|b| b.bounds) - .unwrap_or(PdfRect::ZERO); - let rotate = match page.rotation() { - Ok(PdfPageRenderRotation::Degrees90) => 90, - Ok(PdfPageRenderRotation::Degrees180) => 180, - Ok(PdfPageRenderRotation::Degrees270) => 270, - _ => 0, - }; - let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; - crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } -} - -impl crate::geometry::PageFrame { - /// A user-space rectangle → view space. - pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { - let [x0, y0, x1, y1] = self.crop; - let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); - let (vx0, vy0, vx1, vy1) = match self.rotate { - 90 => (b - y0, l - x0, t - y0, rt - x0), - 180 => (x1 - rt, b - y0, x1 - l, t - y0), - 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), - _ => (l - x0, y1 - t, rt - x0, y1 - b), - }; - ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } - } -} +//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a +//! file Edge opens, Pictor opens). +use crate::{Engine, PdfError, ViewRect}; +use image::DynamicImage; +use pdfium_render::prelude::*; +use serde::Serialize; + +/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). +pub const MAX_RENDER_PIXELS: i64 = 50_000_000; + +#[derive(Debug, Clone, Serialize)] +pub struct DocInfo { + pub pages: Vec, + pub outline: Vec, + pub has_form: bool, + pub encrypted: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PageInfo { + /// Displayed size in points. + pub width: f32, + pub height: f32, + pub label: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct OutlineItem { + pub title: String, + pub page: Option, + pub depth: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SearchHit { + pub page: usize, + /// The hit's boxes in view space. + pub rects: Vec, +} + +pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { + let doc = engine.open(bytes, password)?; + let mut pages = Vec::new(); + for page in doc.pages().iter() { + pages.push(PageInfo { + width: page.width().value, + height: page.height().value, + label: page.label().map(Into::into), + }); + } + let mut outline = Vec::new(); + fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { + if *budget == 0 || depth > 32 { + return; + } + *budget -= 1; + let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); + out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); + if let Some(child) = b.first_child() { + let mut next = Some(child); + while let Some(c) = next { + next = c.next_sibling(); + walk(c, depth + 1, out, budget); + } + } + } + let mut budget = 5000; + let mut next = doc.bookmarks().root(); + while let Some(b) = next { + next = b.next_sibling(); + walk(b, 0, &mut outline, &mut budget); + } + let has_form = doc.form().is_some(); + Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) +} + +/// The displayed size of every page, in points. +pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) +} + +pub(crate) fn render_doc_page( + doc: &PdfDocument, + index: usize, + width_px: u32, + forms: bool, +) -> Result { + let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; + let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); + let width = width_px.clamp(1, 20_000) as i64; + let height = ((width as f32) * h / w).ceil().max(1.0) as i64; + if width * height > MAX_RENDER_PIXELS { + return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); + } + let cfg = PdfRenderConfig::new() + .set_target_size(width as i32, height as i32) + .render_form_data(forms) + .render_annotations(true) + .set_clear_color(PdfColor::WHITE); + page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) +} + +/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. +pub fn render_page( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + index: usize, + width_px: u32, +) -> Result { + let doc = engine.open(bytes, password)?; + render_doc_page(&doc, index, width_px, true) +} + +/// The text of every page, in order. +pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for page in doc.pages().iter() { + out.push(page_text(&page)?); + } + Ok(out) +} + +/// Case-insensitive search over every page; at most `limit` hits. +pub fn search( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + query: &str, + limit: usize, +) -> Result, PdfError> { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + let doc = engine.open(bytes, password)?; + let mut hits = Vec::new(); + for (i, page) in doc.pages().iter().enumerate() { + let frame = page_frame(&page); + let text = page.text().map_err(PdfError::from_pdfium)?; + let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; + while let Some(segments) = search.find_next() { + let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); + hits.push(SearchHit { page: i, rects }); + if hits.len() >= limit { + return Ok(hits); + } + } + } + Ok(hits) +} + +/// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with +/// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.) +pub(crate) fn page_text(page: &PdfPage) -> Result { + let text = page.text().map_err(PdfError::from_pdfium)?; + Ok(text.inside_rect(PdfRect::new_from_values(-1.0e6, -1.0e6, 1.0e6, 1.0e6))) +} + +pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { + // `bounding` is pdfium's effective crop box (inherited boxes included); crop/media only read the page itself. + let crop = page + .boundaries() + .bounding() + .or_else(|_| page.boundaries().crop()) + .or_else(|_| page.boundaries().media()) + .map(|b| b.bounds) + .unwrap_or(PdfRect::ZERO); + let rotate = match page.rotation() { + Ok(PdfPageRenderRotation::Degrees90) => 90, + Ok(PdfPageRenderRotation::Degrees180) => 180, + Ok(PdfPageRenderRotation::Degrees270) => 270, + _ => 0, + }; + let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; + crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } +} + +impl crate::geometry::PageFrame { + /// A user-space rectangle → view space. + pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { + let [x0, y0, x1, y1] = self.crop; + let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); + let (vx0, vy0, vx1, vy1) = match self.rotate { + 90 => (b - y0, l - x0, t - y0, rt - x0), + 180 => (x1 - rt, b - y0, x1 - l, t - y0), + 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), + _ => (l - x0, y1 - t, rt - x0, y1 - b), + }; + ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } + } +} diff --git a/crates/pdf/src/redact.rs b/crates/pdf/src/redact.rs index ebe4a4d..77983b8 100644 --- a/crates/pdf/src/redact.rs +++ b/crates/pdf/src/redact.rs @@ -52,7 +52,8 @@ pub fn redact( redactions: &[Redaction], opts: &RedactOptions, ) -> Result { - if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) { + 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. @@ -67,7 +68,8 @@ pub fn redact( if !seen.insert(r.page) { continue; } - let rects: Vec = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect(); + let rects: Vec = + redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect(); let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?; let (vw, vh) = (page.width().value, page.height().value); drop(page); @@ -181,7 +183,8 @@ fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSe 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 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() { @@ -272,7 +275,11 @@ fn prune_form(doc: &mut Document, removed: &HashSet) { 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()), + 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); diff --git a/crates/pdf/tests/common/mod.rs b/crates/pdf/tests/common/mod.rs index 4638108..ccd2fb2 100644 --- a/crates/pdf/tests/common/mod.rs +++ b/crates/pdf/tests/common/mod.rs @@ -38,6 +38,7 @@ 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. @@ -46,12 +47,6 @@ pub struct Options { pub inherited: bool, } -impl Default for Options { - fn default() -> Self { - Options { compress: false, rotate: 0, inherited: false } - } -} - /// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in /// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings. /// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal. @@ -84,7 +79,7 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n" 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"}); + "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}}}, @@ -160,10 +155,8 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n" "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()]}), - ); + 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}, @@ -211,7 +204,7 @@ pub fn numbered_pdf(n: usize, label: &str) -> Vec { 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()]}), + "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); diff --git a/crates/pdf/tests/edit.rs b/crates/pdf/tests/edit.rs index f263b47..a2f94f3 100644 --- a/crates/pdf/tests/edit.rs +++ b/crates/pdf/tests/edit.rs @@ -47,7 +47,9 @@ fn form_pdf() -> Vec { } doc.objects.insert( radio_id, - Object::Dictionary(dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()}), + 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"), @@ -57,17 +59,23 @@ fn form_pdf() -> Vec { 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()], - })); + 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}}}}); + "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(); @@ -89,7 +97,10 @@ fn fill() -> Edits { fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize { let (x0, y0) = ((r.x * scale) as u32, (r.y * scale) as u32); let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32); - (y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::() < 300).count() + (y0..y1.min(img.height())) + .flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))) + .filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::() < 300) + .count() } #[test] @@ -124,7 +135,13 @@ fn a_filled_form_flattens_into_page_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)); + 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] @@ -144,15 +161,36 @@ fn every_annotation() -> Vec { let r = |x, y, w, h| ViewRect { x, y, w, h }; let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None }; vec![ - Annotation { color: [1.0, 0.9, 0.0], opacity: 0.5, ..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] }) }, + 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 }), + 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 }), + a(Shape::Line { + from: ViewPoint { x: 60.0, y: 420.0 }, + to: ViewPoint { x: 300.0, y: 460.0 }, + width: 3.0, + arrow: true, + }), ] } @@ -173,7 +211,10 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() { 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"]); + 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 { @@ -197,7 +238,9 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() { #[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 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 { @@ -225,7 +268,9 @@ fn signature_png() -> Vec { 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(); + image::DynamicImage::ImageRgba8(img) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); out } @@ -236,10 +281,13 @@ fn a_signature_stamp_is_burned_into_the_page() { 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(); + 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]); @@ -259,14 +307,25 @@ fn a_protected_document_stays_protected_with_its_password() { 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; + 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 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); diff --git a/crates/pdf/tests/pages.rs b/crates/pdf/tests/pages.rs index 662e35e..f16a3db 100644 --- a/crates/pdf/tests/pages.rs +++ b/crates/pdf/tests/pages.rs @@ -25,7 +25,10 @@ fn reorder_rotate_delete_and_insert_blank() { 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"); + assert!( + !contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"), + "a deleted page survived in the file" + ); } } @@ -120,9 +123,12 @@ fn password_on_and_off() { #[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]))); + 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 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(); diff --git a/crates/pdf/tests/redaction.rs b/crates/pdf/tests/redaction.rs index 2ef49df..47d0cb9 100644 --- a/crates/pdf/tests/redaction.rs +++ b/crates/pdf/tests/redaction.rs @@ -43,7 +43,10 @@ fn assert_page_two_unchanged(input: &[u8], output: &[u8]) { assert_eq!(font(&a, pa), font(&b, pb), "page 2's fonts changed"); // The raw stream bytes too (lopdf writes untouched streams as they were). let raw = |d: &Document, p| -> Vec> { - d.get_page_contents(p).iter().map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone()).collect() + 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"); } @@ -117,7 +120,10 @@ fn the_box_is_black_and_the_rest_of_the_page_still_shows() { 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(); + 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)"); } @@ -126,8 +132,14 @@ 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(), + 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( @@ -144,10 +156,19 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() { #[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(), + pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()) + .is_err() + ); + assert!( + pictor_pdf::redact( + engine(), + &input, + None, + &[Redaction { page: 9, rects: vec![secret_box()] }], + &Default::default() + ) + .is_err(), "a page that does not exist was accepted" ); } diff --git a/crates/worker/src/client.rs b/crates/worker/src/client.rs index 7909bfb..531cec6 100644 --- a/crates/worker/src/client.rs +++ b/crates/worker/src/client.rs @@ -1,312 +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, - /// The worker's memory cap. - pub memory_mb: u64, - /// Enables the debug.* operations (tests). - pub debug: bool, -} - -impl WorkerOptions { - pub fn new(exe: impl Into) -> WorkerOptions { - WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false } - } -} - -#[derive(Debug, thiserror::Error)] -pub enum WorkerError { - /// The operation failed cleanly (bad file, wrong password, …): show `message`. - #[error("{0}")] - Op(OpError), - #[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")] - TimedOut(u64), - #[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")] - OutOfMemory, - #[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")] - Crashed(String), - #[error("Pictor's file reader could not start: {0}")] - Spawn(String), -} - -impl WorkerError { - /// A short machine-readable kind, like [`OpError::kind`]. - pub fn kind(&self) -> &str { - match self { - WorkerError::Op(e) => &e.kind, - WorkerError::TimedOut(_) => "timed_out", - WorkerError::OutOfMemory => "out_of_memory", - WorkerError::Crashed(_) => "crashed", - WorkerError::Spawn(_) => "spawn", - } - } -} - -struct Running { - child: Child, - stdin: ChildStdin, - lines: Receiver, - stderr: Arc>, - #[cfg(windows)] - _job: job::Job, -} - -pub struct Worker { - opts: WorkerOptions, - running: Option, - next_id: u64, - /// Set when the worker had to be restarted since the caller last asked (open documents are gone). - restarted: bool, -} - -impl Worker { - pub fn new(opts: WorkerOptions) -> Worker { - Worker { opts, running: None, next_id: 1, restarted: false } - } - - pub fn exe(&self) -> &Path { - &self.opts.exe - } - - /// True once after the worker was restarted (its open documents are gone). - pub fn take_restarted(&mut self) -> bool { - std::mem::take(&mut self.restarted) - } - - fn spawn(&mut self) -> Result<(), WorkerError> { - let mut cmd = Command::new(&self.opts.exe); - cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); - if let Some(d) = &self.opts.pdfium_dir { - cmd.env("PICTOR_PDFIUM_DIR", d); - } - if self.opts.debug { - cmd.env("PICTOR_WORKER_DEBUG", "1"); - } - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - cmd.creation_flags(CREATE_NO_WINDOW); - } - let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?; - #[cfg(windows)] - let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) { - Ok(j) => j, - Err(e) => { - let _ = child.kill(); - return Err(WorkerError::Spawn(format!("job object: {e}"))); - } - }; - let stdin = child.stdin.take().expect("piped"); - let stdout = child.stdout.take().expect("piped"); - let stderr_pipe = child.stderr.take().expect("piped"); - let (tx, rx) = channel(); - std::thread::spawn(move || { - let mut r = BufReader::new(stdout); - loop { - let mut line = String::new(); - match r.read_line(&mut line) { - Ok(0) | Err(_) => return, - Ok(_) => { - if tx.send(line).is_err() { - return; - } - } - } - } - }); - let stderr = Arc::new(Mutex::new(String::new())); - let sink = stderr.clone(); - std::thread::spawn(move || { - let mut r = BufReader::new(stderr_pipe); - let mut line = String::new(); - while let Ok(n) = r.read_line(&mut line) { - if n == 0 { - return; - } - let mut s = sink.lock().unwrap_or_else(|p| p.into_inner()); - if s.len() < 16 << 10 { - s.push_str(&line); - } - line.clear(); - } - }); - let mut running = Running { - child, - stdin, - lines: rx, - stderr, - #[cfg(windows)] - _job: job, - }; - let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| { - let _ = running.child.kill(); - WorkerError::Spawn("it did not answer".into()) - })?; - let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?; - if hello["protocol"].as_u64() != Some(PROTOCOL as u64) { - let _ = running.child.kill(); - return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"]))); - } - self.running = Some(running); - Ok(()) - } - - fn kill(&mut self) { - if let Some(mut r) = self.running.take() { - let _ = r.child.kill(); - let _ = r.child.wait(); - self.restarted = true; - } - } - - /// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed. - pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result { - if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) { - self.kill(); - } - if self.running.is_none() { - self.spawn()?; - } - let id = self.next_id; - self.next_id += 1; - let r = self.running.as_mut().expect("spawned"); - let line = json!({"id": id, "op": op, "args": args}).to_string(); - if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() { - return Err(self.died()); - } - let deadline = std::time::Instant::now() + timeout; - loop { - let r = self.running.as_mut().expect("spawned"); - let left = deadline.saturating_duration_since(std::time::Instant::now()); - match r.lines.recv_timeout(left) { - Ok(text) => { - let v: Value = match serde_json::from_str(&text) { - Ok(v) => v, - Err(_) => continue, - }; - if v["id"].as_u64() != Some(id) { - continue; // a late answer to a request that already timed out - } - if let Some(ok) = v.get("ok") { - return Ok(ok.clone()); - } - let err: OpError = serde_json::from_value(v["err"].clone()) - .unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer.")); - return Err(WorkerError::Op(err)); - } - Err(RecvTimeoutError::Timeout) => { - self.kill(); - return Err(WorkerError::TimedOut(timeout.as_secs().max(1))); - } - Err(RecvTimeoutError::Disconnected) => return Err(self.died()), - } - } - } - - fn died(&mut self) -> WorkerError { - let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default(); - // Give the stderr thread a moment to collect the last words. - std::thread::sleep(Duration::from_millis(50)); - let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr); - // pdfium aborts without a word when an allocation fails; the job's peak memory tells that story. - #[cfg(windows)] - let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9); - #[cfg(not(windows))] - let hit_cap = false; - self.kill(); - if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") { - WorkerError::OutOfMemory - } else { - WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string()) - } - } -} - -impl Drop for Worker { - fn drop(&mut self) { - self.kill(); - } -} - -#[cfg(windows)] -mod job { - use windows::Win32::Foundation::{CloseHandle, HANDLE}; - use windows::Win32::System::JobObjects::*; - use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; - - pub struct Job(HANDLE); - unsafe impl Send for Job {} - - impl Job { - pub fn new(memory_mb: u64) -> Result { - unsafe { - let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?; - let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); - info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20; - SetInformationJobObject( - h, - JobObjectExtendedLimitInformation, - &info as *const _ as *const _, - std::mem::size_of::() as u32, - ) - .map_err(|e| { - let _ = CloseHandle(h); - e.to_string() - })?; - Ok(Job(h)) - } - } - - pub fn assign(&self, child: &std::process::Child) -> Result<(), String> { - unsafe { - let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?; - let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string()); - let _ = CloseHandle(p); - r - } - } - } - - impl Job { - /// The most memory the worker ever committed, in bytes. - pub fn peak_bytes(&self) -> Option { - unsafe { - let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); - QueryInformationJobObject( - Some(self.0), - JobObjectExtendedLimitInformation, - &mut info as *mut _ as *mut _, - std::mem::size_of::() as u32, - None, - ) - .ok()?; - Some(info.PeakProcessMemoryUsed as u64) - } - } - } - - impl Drop for Job { - fn drop(&mut self) { - unsafe { - let _ = CloseHandle(self.0); - } - } - } -} +//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does. +//! +//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so +//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts +//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`). +use crate::{OpError, PROTOCOL}; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +#[derive(Debug, Clone)] +pub struct WorkerOptions { + pub exe: PathBuf, + /// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR). + pub pdfium_dir: Option, + /// The worker's memory cap. + pub memory_mb: u64, + /// Enables the debug.* operations (tests). + pub debug: bool, +} + +impl WorkerOptions { + pub fn new(exe: impl Into) -> WorkerOptions { + WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum WorkerError { + /// The operation failed cleanly (bad file, wrong password, …): show `message`. + #[error("{0}")] + Op(OpError), + #[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")] + TimedOut(u64), + #[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")] + OutOfMemory, + #[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")] + Crashed(String), + #[error("Pictor's file reader could not start: {0}")] + Spawn(String), +} + +impl WorkerError { + /// A short machine-readable kind, like [`OpError::kind`]. + pub fn kind(&self) -> &str { + match self { + WorkerError::Op(e) => &e.kind, + WorkerError::TimedOut(_) => "timed_out", + WorkerError::OutOfMemory => "out_of_memory", + WorkerError::Crashed(_) => "crashed", + WorkerError::Spawn(_) => "spawn", + } + } +} + +struct Running { + child: Child, + stdin: ChildStdin, + lines: Receiver, + stderr: Arc>, + #[cfg(windows)] + _job: job::Job, +} + +pub struct Worker { + opts: WorkerOptions, + running: Option, + next_id: u64, + /// Set when the worker had to be restarted since the caller last asked (open documents are gone). + restarted: bool, +} + +impl Worker { + pub fn new(opts: WorkerOptions) -> Worker { + Worker { opts, running: None, next_id: 1, restarted: false } + } + + pub fn exe(&self) -> &Path { + &self.opts.exe + } + + /// True once after the worker was restarted (its open documents are gone). + pub fn take_restarted(&mut self) -> bool { + std::mem::take(&mut self.restarted) + } + + fn spawn(&mut self) -> Result<(), WorkerError> { + let mut cmd = Command::new(&self.opts.exe); + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + if let Some(d) = &self.opts.pdfium_dir { + cmd.env("PICTOR_PDFIUM_DIR", d); + } + if self.opts.debug { + cmd.env("PICTOR_WORKER_DEBUG", "1"); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?; + #[cfg(windows)] + let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) { + Ok(j) => j, + Err(e) => { + let _ = child.kill(); + return Err(WorkerError::Spawn(format!("job object: {e}"))); + } + }; + let stdin = child.stdin.take().expect("piped"); + let stdout = child.stdout.take().expect("piped"); + let stderr_pipe = child.stderr.take().expect("piped"); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut r = BufReader::new(stdout); + loop { + let mut line = String::new(); + match r.read_line(&mut line) { + Ok(0) | Err(_) => return, + Ok(_) => { + if tx.send(line).is_err() { + return; + } + } + } + } + }); + let stderr = Arc::new(Mutex::new(String::new())); + let sink = stderr.clone(); + std::thread::spawn(move || { + let mut r = BufReader::new(stderr_pipe); + let mut line = String::new(); + while let Ok(n) = r.read_line(&mut line) { + if n == 0 { + return; + } + let mut s = sink.lock().unwrap_or_else(|p| p.into_inner()); + if s.len() < 16 << 10 { + s.push_str(&line); + } + line.clear(); + } + }); + let mut running = Running { + child, + stdin, + lines: rx, + stderr, + #[cfg(windows)] + _job: job, + }; + let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| { + let _ = running.child.kill(); + WorkerError::Spawn("it did not answer".into()) + })?; + let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?; + if hello["protocol"].as_u64() != Some(PROTOCOL as u64) { + let _ = running.child.kill(); + return Err(WorkerError::Spawn(format!( + "it speaks protocol {}, Pictor needs {PROTOCOL}", + hello["protocol"] + ))); + } + self.running = Some(running); + Ok(()) + } + + fn kill(&mut self) { + if let Some(mut r) = self.running.take() { + let _ = r.child.kill(); + let _ = r.child.wait(); + self.restarted = true; + } + } + + /// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed. + pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result { + if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) { + self.kill(); + } + if self.running.is_none() { + self.spawn()?; + } + let id = self.next_id; + self.next_id += 1; + let r = self.running.as_mut().expect("spawned"); + let line = json!({"id": id, "op": op, "args": args}).to_string(); + if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() { + return Err(self.died()); + } + let deadline = std::time::Instant::now() + timeout; + loop { + let r = self.running.as_mut().expect("spawned"); + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match r.lines.recv_timeout(left) { + Ok(text) => { + let v: Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(_) => continue, + }; + if v["id"].as_u64() != Some(id) { + continue; // a late answer to a request that already timed out + } + if let Some(ok) = v.get("ok") { + return Ok(ok.clone()); + } + let err: OpError = serde_json::from_value(v["err"].clone()) + .unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer.")); + return Err(WorkerError::Op(err)); + } + Err(RecvTimeoutError::Timeout) => { + self.kill(); + return Err(WorkerError::TimedOut(timeout.as_secs().max(1))); + } + Err(RecvTimeoutError::Disconnected) => return Err(self.died()), + } + } + } + + fn died(&mut self) -> WorkerError { + let stderr = + self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default(); + // Give the stderr thread a moment to collect the last words. + std::thread::sleep(Duration::from_millis(50)); + let stderr = + self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr); + // pdfium aborts without a word when an allocation fails; the job's peak memory tells that story. + #[cfg(windows)] + let hit_cap = self + .running + .as_ref() + .and_then(|r| r._job.peak_bytes()) + .is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9); + #[cfg(not(windows))] + let hit_cap = false; + self.kill(); + if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") { + WorkerError::OutOfMemory + } else { + WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string()) + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.kill(); + } +} + +#[cfg(windows)] +mod job { + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::System::JobObjects::*; + use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; + + pub struct Job(HANDLE); + unsafe impl Send for Job {} + + impl Job { + pub fn new(memory_mb: u64) -> Result { + unsafe { + let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?; + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + info.BasicLimitInformation.LimitFlags = + JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20; + SetInformationJobObject( + h, + JobObjectExtendedLimitInformation, + &info as *const _ as *const _, + std::mem::size_of::() as u32, + ) + .map_err(|e| { + let _ = CloseHandle(h); + e.to_string() + })?; + Ok(Job(h)) + } + } + + pub fn assign(&self, child: &std::process::Child) -> Result<(), String> { + unsafe { + let p = + OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?; + let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string()); + let _ = CloseHandle(p); + r + } + } + } + + impl Job { + /// The most memory the worker ever committed, in bytes. + pub fn peak_bytes(&self) -> Option { + unsafe { + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + QueryInformationJobObject( + Some(self.0), + JobObjectExtendedLimitInformation, + &mut info as *mut _ as *mut _, + std::mem::size_of::() as u32, + None, + ) + .ok()?; + Some(info.PeakProcessMemoryUsed as u64) + } + } + } + + impl Drop for Job { + fn drop(&mut self) { + unsafe { + let _ = CloseHandle(self.0); + } + } + } +} diff --git a/crates/worker/src/main.rs b/crates/worker/src/main.rs index 48161fa..df36abf 100644 --- a/crates/worker/src/main.rs +++ b/crates/worker/src/main.rs @@ -31,7 +31,11 @@ fn main() { 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 _ = writeln!( + out, + "{}", + json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))}) + ); let _ = out.flush(); continue; } diff --git a/crates/worker/src/ops.rs b/crates/worker/src/ops.rs index 18a35b5..cdb7093 100644 --- a/crates/worker/src/ops.rs +++ b/crates/worker/src/ops.rs @@ -238,8 +238,11 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result } let a: A = args(a)?; let engine = state.engine()?; - let files: Vec<(Vec, Option)> = - a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::>()?; + let files: Vec<(Vec, Option)> = a + .inputs + .iter() + .map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))) + .collect::>()?; 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) @@ -309,7 +312,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result 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())?; + let t = + pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?; Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h})) } "image.convert" => { @@ -347,7 +351,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result 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 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) @@ -391,7 +396,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result 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 })?; + let mut out = + write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; out["removed"] = json!(stripped.removed); Ok(out) } diff --git a/crates/worker/tests/hostile_pdf.rs b/crates/worker/tests/hostile_pdf.rs index 98e2d9a..c80c3c3 100644 --- a/crates/worker/tests/hostile_pdf.rs +++ b/crates/worker/tests/hostile_pdf.rs @@ -1,294 +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 { - let mut v = Vec::new(); - doc.save_to(&mut v).unwrap(); - v -} - -fn valid() -> Vec { - 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 { - 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) -> Vec { - 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)> { - let v = valid(); - let mut out: Vec<(&str, Vec)> = 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)> { - 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)> = 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)> = 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:?}"); -} +//! 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 { + let mut v = Vec::new(); + doc.save_to(&mut v).unwrap(); + v +} + +fn valid() -> Vec { + 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 { + 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) -> Vec { + 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)> { + let v = valid(); + let mut out: Vec<(&str, Vec)> = 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)> { + 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)> = 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)> = 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:?}"); +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index b96f932..f60457a 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -85,4 +85,149 @@ support depends on pdfium, which the brief chose). Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. +141 crates; 0 outside the allowed set. + +| Crate | Version | Licence | Allowed | +| :-- | :-- | :-- | :-- | +| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes | +| aes | 0.9.2 | MIT OR Apache-2.0 | yes | +| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes | +| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes | +| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes | +| base64 | 0.22.1 | MIT OR Apache-2.0 | yes | +| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes | +| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes | +| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes | +| block-buffer | 0.12.1 | MIT OR Apache-2.0 | yes | +| block-padding | 0.4.2 | MIT OR Apache-2.0 | yes | +| borsh | 1.8.1 | MIT OR Apache-2.0 | yes | +| borsh-derive | 1.8.1 | Apache-2.0 | yes | +| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes | +| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes | +| byteorder | 1.5.0 | Unlicense OR MIT | yes | +| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes | +| bytes | 1.12.1 | MIT | yes | +| cbc | 0.2.1 | MIT OR Apache-2.0 | yes | +| cfg_aliases | 0.2.2 | MIT | yes | +| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes | +| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes | +| chrono | 0.4.45 | MIT OR Apache-2.0 | yes | +| cipher | 0.5.2 | MIT OR Apache-2.0 | yes | +| color_quant | 1.1.0 | MIT | yes | +| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes | +| core_detect | 1.0.0 | MIT/Apache-2.0 | yes | +| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes | +| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes | +| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes | +| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes | +| digest | 0.11.3 | MIT OR Apache-2.0 | yes | +| ecb | 0.2.1 | MIT OR Apache-2.0 | yes | +| either | 1.19.0 | MIT OR Apache-2.0 | yes | +| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes | +| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes | +| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes | +| fax | 0.2.7 | MIT | yes | +| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes | +| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes | +| fnv | 1.0.7 | Apache-2.0 / MIT | yes | +| foldhash | 0.2.0 | Zlib | yes | +| g2gen | 1.2.2 | MIT/Apache-2.0 | yes | +| g2p | 1.2.2 | MIT/Apache-2.0 | yes | +| g2poly | 1.2.2 | MIT/Apache-2.0 | yes | +| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes | +| gif | 0.14.2 | MIT OR Apache-2.0 | yes | +| half | 2.7.1 | MIT OR Apache-2.0 | yes | +| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes | +| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes | +| image | 0.25.10 | MIT OR Apache-2.0 | yes | +| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes | +| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes | +| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes | +| inout | 0.2.6 | MIT OR Apache-2.0 | yes | +| itertools | 0.15.0 | MIT OR Apache-2.0 | yes | +| itoa | 1.0.19 | MIT OR Apache-2.0 | yes | +| kamadak-exif | 0.6.2 | BSD-2-Clause | yes | +| libloading | 0.9.1 | ISC | yes | +| log | 0.4.35 | MIT OR Apache-2.0 | yes | +| lopdf | 0.47.0 | MIT | yes | +| lru | 0.18.5 | MIT | yes | +| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes | +| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes | +| memchr | 2.8.3 | Unlicense OR MIT | yes | +| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes | +| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes | +| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes | +| multiversion_no_op | 1.0.0 | Apache-2.0 OR MIT | yes | +| mutate_once | 0.1.2 | BSD-2-Clause | yes | +| nom | 8.0.0 | MIT | yes | +| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes | +| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes | +| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes | +| piston-float | 1.0.1 | MIT | yes | +| png | 0.18.1 | MIT OR Apache-2.0 | yes | +| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes | +| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes | +| proptest | 1.12.0 | MIT OR Apache-2.0 | yes | +| pxfm | 0.1.30 | BSD-3-Clause OR Apache-2.0 | yes | +| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes | +| quick-error | 1.2.3 | MIT/Apache-2.0 | yes | +| quick-error | 2.0.1 | MIT/Apache-2.0 | yes | +| quote | 1.0.47 | MIT OR Apache-2.0 | yes | +| rand | 0.10.4 | MIT OR Apache-2.0 | yes | +| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes | +| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes | +| rangemap | 1.8.0 | MIT/Apache-2.0 | yes | +| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes | +| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes | +| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes | +| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes | +| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes | +| serde | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes | +| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes | +| simd-adler32 | 0.3.10 | MIT | yes | +| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes | +| stringprep | 0.1.5 | MIT/Apache-2.0 | yes | +| syn | 2.0.119 | MIT OR Apache-2.0 | yes | +| syn | 3.0.10 | MIT OR Apache-2.0 | yes | +| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes | +| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes | +| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes | +| tiff | 0.11.3 | MIT | yes | +| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes | +| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| typenum | 1.20.1 | MIT OR Apache-2.0 | yes | +| unarray | 0.1.4 | MIT OR Apache-2.0 | yes | +| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes | +| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes | +| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes | +| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes | +| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes | +| vecmath | 1.0.0 | MIT | yes | +| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes | +| weezl | 0.1.12 | MIT OR Apache-2.0 | yes | +| weezl | 0.2.1 | MIT OR Apache-2.0 | yes | +| windows | 0.62.2 | MIT OR Apache-2.0 | yes | +| windows-collections | 0.3.2 | MIT OR Apache-2.0 | yes | +| windows-core | 0.62.2 | MIT OR Apache-2.0 | yes | +| windows-future | 0.3.2 | MIT OR Apache-2.0 | yes | +| windows-implement | 0.60.2 | MIT OR Apache-2.0 | yes | +| windows-interface | 0.59.3 | MIT OR Apache-2.0 | yes | +| windows-link | 0.2.1 | MIT OR Apache-2.0 | yes | +| windows-numerics | 0.3.1 | MIT OR Apache-2.0 | yes | +| windows-result | 0.4.1 | MIT OR Apache-2.0 | yes | +| windows-strings | 0.5.1 | MIT OR Apache-2.0 | yes | +| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes | +| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes | +| winnow | 1.0.5 | MIT | yes | +| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes | +| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes | +| zlib-rs | 0.6.8 | Zlib | yes | +| zmij | 1.0.23 | MIT | yes | +| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes | +| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes | diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 0000000..91782e5 --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,106 @@ +# Formats and the worker protocol + +What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to +`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own +section here. + +## Images (crates/raster, crates/meta) + +| Format | Read | Write | Metadata strip | +| :-- | :-- | :-- | :-- | +| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical | +| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical | +| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed | +| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) | +| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused | +| BMP | yes | yes | (no metadata) | +| ICO | yes | 256/48/32/16 px | — | +| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first | +| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — | + +Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`): +128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding. + +HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video +Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing. + +## PDF (crates/pdf) + +Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the +page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space. + +| Operation | Library | Why | +| :-- | :-- | :-- | +| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens | +| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) | +| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over | +| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask | +| PDF → PNG/JPG | pdfium | rendering | +| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too | +| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` | +| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation | +| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | | +| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed | +| password off | lopdf decrypting load + plain save | | +| true redaction | pdfium render + lopdf rebuild (below) | | + +### True redaction + +Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted +black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept, +`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page +tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and +`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and +non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they +stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is +written fresh (no incremental history). The other pages' objects are written back byte for byte. + +Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only +what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form +XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests +(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw +and decompressed), and a raw byte grep. + +## The worker protocol (crates/worker), version 1 + +`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is +`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol. + +``` +→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}} +← {"id": 7, "ok": {"png": "", "width": 1200, "height": 1553}} +← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}} +``` + +Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`, +`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`, +`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user. + +| Operation | Arguments | Result | +| :-- | :-- | :-- | +| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) | +| `pdf.close` | `doc` | — | +| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` | +| `pdf.text` | `doc` | `pages`: text per page | +| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) | +| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline | +| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` | +| `pdf.extract` | `doc`, `pages`, `output` | `path` | +| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` | +| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` | +| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` | +| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` | +| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` | +| `image.thumb` | `path`, `max` | `png`, original `width`, `height` | +| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` | +| `image.heif_support` | — | `support` | +| `meta.read` | `path` | `report` (items by group), `groups` (with labels) | +| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` | +| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` | + +Saving: `mode: new` refuses to replace a file (the app picks `-edited.pdf`); `overwrite` writes +`.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).