[repo] Format, clippy clean, FORMATS.md, the full crate table in DEPENDENCIES.md

This commit is contained in:
2026-11-16 13:58:06 +01:00
parent 196802863a
commit a06e3f9b73
17 changed files with 2708 additions and 2125 deletions
+1141 -972
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -32,7 +32,9 @@ impl Engine {
} }
pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result<PdfDocument<'a>, PdfError> { pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result<PdfDocument<'a>, PdfError> {
self.pdfium.load_pdf_from_byte_slice(bytes, password).map_err(|e| PdfError::from_pdfium_open(e, password.is_some())) self.pdfium
.load_pdf_from_byte_slice(bytes, password)
.map_err(|e| PdfError::from_pdfium_open(e, password.is_some()))
} }
pub(crate) fn new_document(&self) -> Result<PdfDocument<'_>, PdfError> { pub(crate) fn new_document(&self) -> Result<PdfDocument<'_>, PdfError> {
+1 -1
View File
@@ -61,7 +61,7 @@ impl PageFrame {
} }
pub(crate) fn normalise_rotate(r: i64) -> u16 { 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)] #[cfg(test)]
+2 -3
View File
@@ -20,7 +20,7 @@ mod security;
pub use edit::*; pub use edit::*;
pub use engine::Engine; pub use engine::Engine;
pub use error::PdfError; pub use error::PdfError;
pub use geometry::{ViewRect, ViewPoint}; pub use geometry::{ViewPoint, ViewRect};
pub use pages::*; pub use pages::*;
pub use reader::*; pub use reader::*;
pub use redact::{RedactOptions, Redacted, Redaction, redact}; 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). /// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> { pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
let mut opts = lopdf::LoadOptions::default(); let mut opts = lopdf::LoadOptions { max_decompressed_size: Some(256 << 20), ..Default::default() };
opts.max_decompressed_size = Some(256 << 20);
if let Some(p) = password { if let Some(p) = password {
opts.password = Some(p.to_owned()); opts.password = Some(p.to_owned());
} }
+304 -299
View File
@@ -1,299 +1,304 @@
//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form, //! 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 //! 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. //! (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 crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page};
use image::{DynamicImage, GenericImageView}; use image::{DynamicImage, GenericImageView};
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashSet; use std::collections::HashSet;
/// One page of the new order. /// One page of the new order.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")] #[serde(tag = "kind", rename_all = "snake_case")]
pub enum PageSpec { pub enum PageSpec {
/// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90). /// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90).
Existing { Existing {
index: usize, index: usize,
#[serde(default)] #[serde(default)]
rotate: i32, rotate: i32,
}, },
/// A blank page of this size in points. /// A blank page of this size in points.
Blank { width: f32, height: f32 }, Blank { width: f32, height: f32 },
} }
const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"]; 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. /// Copies inherited attributes down onto each page, so pages can be moved freely.
fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) { fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) {
for &page in pages { for &page in pages {
for key in INHERITABLE { for key in INHERITABLE {
if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) { if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) {
continue; 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 current =
let mut depth = 0; doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
let mut value = None; let mut depth = 0;
while let Some(id) = current { let mut value = None;
depth += 1; while let Some(id) = current {
if depth > 64 { depth += 1;
break; if depth > 64 {
} break;
let Ok(d) = doc.get_dictionary(id) else { break }; }
if let Ok(v) = d.get(key) { let Ok(d) = doc.get_dictionary(id) else { break };
value = Some(v.clone()); if let Ok(v) = d.get(key) {
break; value = Some(v.clone());
} break;
current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); }
} 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); if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) {
} d.set(key, v);
} }
} }
} }
}
fn pages_root(doc: &Document) -> Result<ObjectId, PdfError> {
doc.catalog() fn pages_root(doc: &Document) -> Result<ObjectId, PdfError> {
.ok() doc.catalog()
.and_then(|c| c.get(b"Pages").ok()) .ok()
.and_then(|p| p.as_reference().ok()) .and_then(|c| c.get(b"Pages").ok())
.ok_or_else(|| PdfError::Damaged("it has no page tree".into())) .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. /// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields
pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result<Vec<u8>, PdfError> { /// that only lived on them.
let mut doc = lopdf_load(bytes, password)?; pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result<Vec<u8>, PdfError> {
reorganise_doc(&mut doc, specs)?; let mut doc = lopdf_load(bytes, password)?;
doc.prune_objects(); reorganise_doc(&mut doc, specs)?;
lopdf_save(&mut doc) doc.prune_objects();
} lopdf_save(&mut doc)
}
pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> {
if specs.is_empty() { pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> {
return Err(PdfError::Invalid("A PDF needs at least one page.".into())); if specs.is_empty() {
} return Err(PdfError::Invalid("A PDF needs at least one page.".into()));
let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect(); }
materialise_inherited(doc, &pages); let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect();
let root = pages_root(doc)?; materialise_inherited(doc, &pages);
let mut used = HashSet::new(); let root = pages_root(doc)?;
let mut kids = Vec::new(); let mut used = HashSet::new();
for spec in specs { let mut kids = Vec::new();
match *spec { for spec in specs {
PageSpec::Existing { index, rotate } => { match *spec {
let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?; PageSpec::Existing { index, rotate } => {
if rotate % 90 != 0 { let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?;
return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into())); 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) { // The same page twice: the second is a shallow copy (its content and resources are shared).
src let id = if used.insert(src) {
} else { src
let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); } else {
let mut copy = copy; let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
copy.remove(b"Annots"); let mut copy = copy;
doc.add_object(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); let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?;
d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64); let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0);
d.set("Parent", root); d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64);
kids.push(Object::Reference(id)); 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) { PageSpec::Blank { width, height } => {
return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into())); 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! { let content = doc.add_object(Stream::new(dictionary! {}, Vec::new()));
"Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {}, let id = doc.add_object(dictionary! {
"MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)], "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)); });
} kids.push(Object::Reference(id));
} }
} }
// Annotations of deleted pages, and the fields that only lived there. }
let mut removed = HashSet::new(); // Annotations of deleted pages, and the fields that only lived there.
for p in pages.iter().filter(|p| !used.contains(*p)) { let mut removed = HashSet::new();
if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) { for p in pages.iter().filter(|p| !used.contains(*p)) {
removed.extend(a.iter().filter_map(|o| o.as_reference().ok())); 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 crate::redact::prune_form_pub(doc, &removed);
// nowhere, which every viewer tolerates); so do their annotations. // Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead
for p in pages.iter().filter(|p| !used.contains(*p)) { // nowhere, which every viewer tolerates); so do their annotations.
doc.objects.remove(p); for p in pages.iter().filter(|p| !used.contains(*p)) {
} doc.objects.remove(p);
for a in &removed { }
doc.objects.remove(a); 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(); let count = kids.len() as i64;
for key in INHERITABLE { let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
root_dict.remove(key); for key in INHERITABLE {
} root_dict.remove(key);
root_dict.set("Kids", kids); }
root_dict.set("Count", count); root_dict.set("Kids", kids);
root_dict.remove(b"Parent"); root_dict.set("Count", count);
doc.objects.insert(root, Object::Dictionary(root_dict)); root_dict.remove(b"Parent");
Ok(()) doc.objects.insert(root, Object::Dictionary(root_dict));
} Ok(())
}
/// One document per range; `ranges` are 0-based inclusive page index pairs.
pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result<Vec<Vec<u8>>, PdfError> { /// One document per range; `ranges` are 0-based inclusive page index pairs.
let mut out = Vec::new(); pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result<Vec<Vec<u8>>, PdfError> {
for &(a, b) in ranges { let mut out = Vec::new();
if a > b { for &(a, b) in ranges {
return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1))); if a > b {
} return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1)));
let specs: Vec<PageSpec> = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect(); }
out.push(reorganise(bytes, password, &specs)?); let specs: Vec<PageSpec> = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect();
} out.push(reorganise(bytes, password, &specs)?);
Ok(out) }
} Ok(out)
}
/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages.
pub fn parse_ranges(text: &str, pages: usize) -> Result<Vec<(usize, usize)>, PdfError> { /// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages.
let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-.")); pub fn parse_ranges(text: &str, pages: usize) -> Result<Vec<(usize, usize)>, PdfError> {
let mut out = Vec::new(); let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-."));
for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { let mut out = Vec::new();
let (a, b) = match part.split_once(['-', '–']) { for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) {
Some((a, b)) => { let (a, b) = match part.split_once(['-', '–']) {
let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? }; Some((a, b)) => {
let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? }; let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? };
(a, b) 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())?; None => {
(n, n) 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 == 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()); if a > b {
} return Err(bad());
out.push((a - 1, b - 1)); }
} out.push((a - 1, b - 1));
if out.is_empty() { }
return Err(bad()); if out.is_empty() {
} return Err(bad());
Ok(out) }
} 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. /// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look
pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result<Vec<u8>, PdfError> { /// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over.
if inputs.len() < 2 { pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result<Vec<u8>, PdfError> {
return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into())); 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 mut target = engine.new_document()?;
let source = engine.open(bytes, *password).map_err(|e| match e { for (i, (bytes, password)) in inputs.iter().enumerate() {
PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)), let source = engine.open(bytes, *password).map_err(|e| match e {
other => other, 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)?; })?;
} target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?;
crate::engine::pdfium_save(&target) }
} crate::engine::pdfium_save(&target)
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum PageFit { #[serde(rename_all = "snake_case")]
/// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one). pub enum PageFit {
Image, /// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one).
/// A4 portrait or landscape (whichever suits the image), with a margin. Image,
A4, /// A4 portrait or landscape (whichever suits the image), with a margin.
Letter, A4,
} Letter,
}
/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly.
pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result<Vec<u8>, PdfError> { /// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly.
if images.is_empty() { pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result<Vec<u8>, PdfError> {
return Err(PdfError::Invalid("Choose at least one image.".into())); 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 doc = Document::with_version("1.7");
let mut kids = Vec::new(); let pages_id = doc.new_object_id();
for (bytes, img) in images { let mut kids = Vec::new();
let (w, h) = img.dimensions(); for (bytes, img) in images {
let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]); let (w, h) = img.dimensions();
let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) { let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]);
let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" }; let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) {
let mut s = Stream::new( let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" };
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, let mut s = Stream::new(
"ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"}, dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
bytes.clone(), "ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
); bytes.clone(),
s.allows_compression = false; );
doc.add_object(s) s.allows_compression = false;
} else { doc.add_object(s)
let rgba = img.to_rgba8(); } else {
let has_alpha = rgba.pixels().any(|p| p.0[3] != 255); let rgba = img.to_rgba8();
let rgb: Vec<u8> = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); let has_alpha = rgba.pixels().any(|p| p.0[3] != 255);
let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, let rgb: Vec<u8> = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect();
"Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}; let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64,
if has_alpha { "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8};
let alpha: Vec<u8> = rgba.pixels().map(|p| p.0[3]).collect(); if has_alpha {
let mut smask = Stream::new( let alpha: Vec<u8> = rgba.pixels().map(|p| p.0[3]).collect();
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, let mut smask = Stream::new(
"ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
alpha, "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8},
); alpha,
let _ = smask.compress(); );
dict.set("SMask", doc.add_object(smask)); let _ = smask.compress();
} dict.set("SMask", doc.add_object(smask));
let mut s = Stream::new(dict, rgb); }
let _ = s.compress(); let mut s = Stream::new(dict, rgb);
doc.add_object(s) 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 { let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75);
PageFit::Image => (iw, ih), let (pw, ph) = match fit {
PageFit::A4 | PageFit::Letter => { PageFit::Image => (iw, ih),
let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) }; PageFit::A4 | PageFit::Letter => {
if w > h { (b, a) } else { (a, b) } 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 margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) };
let (dw, dh) = (iw * scale, ih * scale); let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image {
let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0); 1.0
let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes(); } else {
let content_id = doc.add_object(Stream::new(dictionary! {}, content)); f32::MAX
let page = doc.add_object(dictionary! { });
"Type" => "Page", "Parent" => pages_id, "Contents" => content_id, let (dw, dh) = (iw * scale, ih * scale);
"MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)], let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0);
"Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])}, 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));
kids.push(Object::Reference(page)); let page = doc.add_object(dictionary! {
} "Type" => "Page", "Parent" => pages_id, "Contents" => content_id,
let count = kids.len() as i64; "MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)],
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count})); "Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])},
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); });
doc.trailer.set("Root", catalog); kids.push(Object::Reference(page));
lopdf_save(&mut doc) }
} let count = kids.len() as i64;
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}));
/// Renders the chosen pages (0-based) at `dpi`. let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
pub fn pages_to_images( doc.trailer.set("Root", catalog);
engine: &Engine, lopdf_save(&mut doc)
bytes: &[u8], }
password: Option<&str>,
pages: &[usize], /// Renders the chosen pages (0-based) at `dpi`.
dpi: u32, pub fn pages_to_images(
) -> Result<Vec<DynamicImage>, PdfError> { engine: &Engine,
let doc = engine.open(bytes, password)?; bytes: &[u8],
let mut out = Vec::new(); password: Option<&str>,
for &i in pages { pages: &[usize],
let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?; dpi: u32,
let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32; ) -> Result<Vec<DynamicImage>, PdfError> {
drop(page); let doc = engine.open(bytes, password)?;
out.push(render_doc_page(&doc, i, width, true)?); let mut out = Vec::new();
} for &i in pages {
Ok(out) 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)
}
+193 -184
View File
@@ -1,184 +1,193 @@
//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a //! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a
//! file Edge opens, Pictor opens). //! file Edge opens, Pictor opens).
use crate::{Engine, PdfError, ViewRect}; use crate::{Engine, PdfError, ViewRect};
use image::DynamicImage; use image::DynamicImage;
use pdfium_render::prelude::*; use pdfium_render::prelude::*;
use serde::Serialize; use serde::Serialize;
/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). /// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA).
pub const MAX_RENDER_PIXELS: i64 = 50_000_000; pub const MAX_RENDER_PIXELS: i64 = 50_000_000;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct DocInfo { pub struct DocInfo {
pub pages: Vec<PageInfo>, pub pages: Vec<PageInfo>,
pub outline: Vec<OutlineItem>, pub outline: Vec<OutlineItem>,
pub has_form: bool, pub has_form: bool,
pub encrypted: bool, pub encrypted: bool,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct PageInfo { pub struct PageInfo {
/// Displayed size in points. /// Displayed size in points.
pub width: f32, pub width: f32,
pub height: f32, pub height: f32,
pub label: Option<String>, pub label: Option<String>,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct OutlineItem { pub struct OutlineItem {
pub title: String, pub title: String,
pub page: Option<usize>, pub page: Option<usize>,
pub depth: u32, pub depth: u32,
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct SearchHit { pub struct SearchHit {
pub page: usize, pub page: usize,
/// The hit's boxes in view space. /// The hit's boxes in view space.
pub rects: Vec<ViewRect>, pub rects: Vec<ViewRect>,
} }
pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> { pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> {
let doc = engine.open(bytes, password)?; let doc = engine.open(bytes, password)?;
let mut pages = Vec::new(); let mut pages = Vec::new();
for page in doc.pages().iter() { for page in doc.pages().iter() {
pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); pages.push(PageInfo {
} width: page.width().value,
let mut outline = Vec::new(); height: page.height().value,
fn walk(b: PdfBookmark, depth: u32, out: &mut Vec<OutlineItem>, budget: &mut u32) { label: page.label().map(Into::into),
if *budget == 0 || depth > 32 { });
return; }
} let mut outline = Vec::new();
*budget -= 1; fn walk(b: PdfBookmark, depth: u32, out: &mut Vec<OutlineItem>, budget: &mut u32) {
let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); if *budget == 0 || depth > 32 {
out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); return;
if let Some(child) = b.first_child() { }
let mut next = Some(child); *budget -= 1;
while let Some(c) = next { let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize);
next = c.next_sibling(); out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth });
walk(c, depth + 1, out, budget); if let Some(child) = b.first_child() {
} let mut next = Some(child);
} while let Some(c) = next {
} next = c.next_sibling();
let mut budget = 5000; walk(c, depth + 1, out, budget);
let mut next = doc.bookmarks().root(); }
while let Some(b) = next { }
next = b.next_sibling(); }
walk(b, 0, &mut outline, &mut budget); let mut budget = 5000;
} let mut next = doc.bookmarks().root();
let has_form = doc.form().is_some(); while let Some(b) = next {
Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) next = b.next_sibling();
} walk(b, 0, &mut outline, &mut budget);
}
/// The displayed size of every page, in points. let has_form = doc.form().is_some();
pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<(f32, f32)>, PdfError> { Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() })
let doc = engine.open(bytes, password)?; }
Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect())
} /// The displayed size of every page, in points.
pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<(f32, f32)>, PdfError> {
pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result<DynamicImage, PdfError> { let doc = engine.open(bytes, password)?;
let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect())
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; pub(crate) fn render_doc_page(
if width * height > MAX_RENDER_PIXELS { doc: &PdfDocument,
return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); index: usize,
} width_px: u32,
let cfg = PdfRenderConfig::new() forms: bool,
.set_target_size(width as i32, height as i32) ) -> Result<DynamicImage, PdfError> {
.render_form_data(forms) let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?;
.render_annotations(true) let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0));
.set_clear_color(PdfColor::WHITE); let width = width_px.clamp(1, 20_000) as i64;
page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) 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)));
/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. }
pub fn render_page( let cfg = PdfRenderConfig::new()
engine: &Engine, .set_target_size(width as i32, height as i32)
bytes: &[u8], .render_form_data(forms)
password: Option<&str>, .render_annotations(true)
index: usize, .set_clear_color(PdfColor::WHITE);
width_px: u32, page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium)
) -> Result<DynamicImage, PdfError> { }
let doc = engine.open(bytes, password)?;
render_doc_page(&doc, index, width_px, true) /// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn.
} pub fn render_page(
engine: &Engine,
/// The text of every page, in order. bytes: &[u8],
pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<String>, PdfError> { password: Option<&str>,
let doc = engine.open(bytes, password)?; index: usize,
let mut out = Vec::new(); width_px: u32,
for page in doc.pages().iter() { ) -> Result<DynamicImage, PdfError> {
out.push(page_text(&page)?); let doc = engine.open(bytes, password)?;
} render_doc_page(&doc, index, width_px, true)
Ok(out) }
}
/// The text of every page, in order.
/// Case-insensitive search over every page; at most `limit` hits. pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<String>, PdfError> {
pub fn search( let doc = engine.open(bytes, password)?;
engine: &Engine, let mut out = Vec::new();
bytes: &[u8], for page in doc.pages().iter() {
password: Option<&str>, out.push(page_text(&page)?);
query: &str, }
limit: usize, Ok(out)
) -> Result<Vec<SearchHit>, PdfError> { }
if query.trim().is_empty() {
return Ok(Vec::new()); /// Case-insensitive search over every page; at most `limit` hits.
} pub fn search(
let doc = engine.open(bytes, password)?; engine: &Engine,
let mut hits = Vec::new(); bytes: &[u8],
for (i, page) in doc.pages().iter().enumerate() { password: Option<&str>,
let frame = page_frame(&page); query: &str,
let text = page.text().map_err(PdfError::from_pdfium)?; limit: usize,
let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; ) -> Result<Vec<SearchHit>, PdfError> {
while let Some(segments) = search.find_next() { if query.trim().is_empty() {
let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); return Ok(Vec::new());
hits.push(SearchHit { page: i, rects }); }
if hits.len() >= limit { let doc = engine.open(bytes, password)?;
return Ok(hits); 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)?;
Ok(hits) 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();
/// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with hits.push(SearchHit { page: i, rects });
/// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.) if hits.len() >= limit {
pub(crate) fn page_text(page: &PdfPage) -> Result<String, PdfError> { return Ok(hits);
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))) }
} }
Ok(hits)
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 /// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with
.boundaries() /// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.)
.bounding() pub(crate) fn page_text(page: &PdfPage) -> Result<String, PdfError> {
.or_else(|_| page.boundaries().crop()) let text = page.text().map_err(PdfError::from_pdfium)?;
.or_else(|_| page.boundaries().media()) Ok(text.inside_rect(PdfRect::new_from_values(-1.0e6, -1.0e6, 1.0e6, 1.0e6)))
.map(|b| b.bounds) }
.unwrap_or(PdfRect::ZERO);
let rotate = match page.rotation() { pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame {
Ok(PdfPageRenderRotation::Degrees90) => 90, // `bounding` is pdfium's effective crop box (inherited boxes included); crop/media only read the page itself.
Ok(PdfPageRenderRotation::Degrees180) => 180, let crop = page
Ok(PdfPageRenderRotation::Degrees270) => 270, .boundaries()
_ => 0, .bounding()
}; .or_else(|_| page.boundaries().crop())
let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; .or_else(|_| page.boundaries().media())
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 } .map(|b| b.bounds)
} .unwrap_or(PdfRect::ZERO);
let rotate = match page.rotation() {
impl crate::geometry::PageFrame { Ok(PdfPageRenderRotation::Degrees90) => 90,
/// A user-space rectangle → view space. Ok(PdfPageRenderRotation::Degrees180) => 180,
pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { Ok(PdfPageRenderRotation::Degrees270) => 270,
let [x0, y0, x1, y1] = self.crop; _ => 0,
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 { let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value];
90 => (b - y0, l - x0, t - y0, rt - x0), 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 }
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), impl crate::geometry::PageFrame {
}; /// A user-space rectangle → view space.
ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } 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() }
}
}
+11 -4
View File
@@ -52,7 +52,8 @@ pub fn redact(
redactions: &[Redaction], redactions: &[Redaction],
opts: &RedactOptions, opts: &RedactOptions,
) -> Result<Redacted, PdfError> { ) -> Result<Redacted, PdfError> {
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())); 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. // 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) { if !seen.insert(r.page) {
continue; continue;
} }
let rects: Vec<ViewRect> = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect(); let rects: Vec<ViewRect> =
redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect();
let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?; let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?;
let (vw, vh) = (page.width().value, page.height().value); let (vw, vh) = (page.width().value, page.height().value);
drop(page); drop(page);
@@ -181,7 +183,8 @@ fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSe
for &page in pages { for &page in pages {
// The nearest ancestor's /Resources, and every Pages node on the way up. // The nearest ancestor's /Resources, and every Pages node on the way up.
let mut inherited = None; 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; let mut depth = 0;
while let Some(id) = current { while let Some(id) = current {
if depth > 64 || !nodes.insert(id) && inherited.is_some() { if depth > 64 || !nodes.insert(id) && inherited.is_some() {
@@ -272,7 +275,11 @@ fn prune_form(doc: &mut Document, removed: &HashSet<ObjectId>) {
if changed { if changed {
let target = match acroform { let target = match acroform {
Some(id) => doc.get_dictionary_mut(id).ok(), 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 { if let Some(f) = target {
f.set("Fields", kept); f.set("Fields", kept);
+5 -12
View File
@@ -38,6 +38,7 @@ fn s(text: &str) -> Object {
Object::String(text.as_bytes().to_vec(), StringFormat::Literal) Object::String(text.as_bytes().to_vec(), StringFormat::Literal)
} }
#[derive(Default)]
pub struct Options { pub struct Options {
pub compress: bool, pub compress: bool,
/// /Rotate on page 1. /// /Rotate on page 1.
@@ -46,12 +47,6 @@ pub struct Options {
pub inherited: bool, 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 /// 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. /// 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. /// 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 c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec()));
let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica",
"Encoding" => "WinAnsiEncoding"}); "Encoding" => "WinAnsiEncoding"});
let field_ap = doc.add_object(Stream::new( let field_ap = doc.add_object(Stream::new(
dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()], dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()],
"Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, "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, "Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id,
"ActualText" => s("STRUCT-SECRET"), "K" => 0, "ActualText" => s("STRUCT-SECRET"), "K" => 0,
}); });
doc.objects.insert( doc.objects
struct_root_id, .insert(struct_root_id, Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}));
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 attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec()));
let filespec = doc.add_object(dictionary! { let filespec = doc.add_object(dictionary! {
"Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach}, "Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach},
@@ -211,7 +204,7 @@ pub fn numbered_pdf(n: usize, label: &str) -> Vec<u8> {
doc.objects.insert( doc.objects.insert(
pages_id, pages_id,
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64, 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}); let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
doc.trailer.set("Root", catalog); doc.trailer.set("Root", catalog);
+86 -27
View File
@@ -47,7 +47,9 @@ fn form_pdf() -> Vec<u8> {
} }
doc.objects.insert( doc.objects.insert(
radio_id, 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! { let city = doc.add_object(dictionary! {
"Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"), "Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"),
@@ -57,17 +59,23 @@ fn form_pdf() -> Vec<u8> {
let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 12 Tf 72 780 Td (Form) Tj ET".to_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()]; let mut annots = vec![name.into(), agree.into(), city.into()];
annots.extend(kids); annots.extend(kids);
doc.objects.insert(page_id, Object::Dictionary(dictionary! { doc.objects.insert(
"Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots, page_id,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}}, Object::Dictionary(dictionary! {
})); "Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots,
doc.objects.insert(pages_id, Object::Dictionary(dictionary! { "Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}},
"Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1, }),
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], );
})); 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, let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id,
"AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()], "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}}}}); "DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}});
doc.trailer.set("Root", catalog); doc.trailer.set("Root", catalog);
let mut out = Vec::new(); let mut out = Vec::new();
doc.save_to(&mut out).unwrap(); doc.save_to(&mut out).unwrap();
@@ -89,7 +97,10 @@ fn fill() -> Edits {
fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize { 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 (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); let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32);
(y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::<u32>() < 300).count() (y0..y1.min(img.height()))
.flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y)))
.filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::<u32>() < 300)
.count()
} }
#[test] #[test]
@@ -124,7 +135,13 @@ fn a_filled_form_flattens_into_page_text() {
let doc = Document::load_mem(&out).unwrap(); let doc = Document::load_mem(&out).unwrap();
assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening"); assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening");
let p = page_ids(&doc)[0]; 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] #[test]
@@ -144,15 +161,36 @@ fn every_annotation() -> Vec<Annotation> {
let r = |x, y, w, h| ViewRect { x, y, w, h }; 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 }; let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None };
vec![ 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::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)] }), 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 } }) }, Annotation {
a(Shape::FreeText { rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0 }), contents: Some("Zkontrolovat čísla".into()),
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::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::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::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() String::from_utf8(d.get(b"Subtype").unwrap().as_name().unwrap().to_vec()).unwrap()
}) })
.collect(); .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(); let after = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8();
for a in every_annotation() { for a in every_annotation() {
let r = match &a.shape { let r = match &a.shape {
@@ -197,7 +238,9 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() {
#[test] #[test]
fn a_free_text_on_a_rotated_page_lands_where_it_was_drawn() { 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 rect = ViewRect { x: 100.0, y: 300.0, w: 300.0, h: 40.0 };
let edits = Edits { let edits = Edits {
annotations: vec![Annotation { annotations: vec![Annotation {
@@ -225,7 +268,9 @@ fn signature_png() -> Vec<u8> {
if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) } if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) }
}); });
let mut out = Vec::new(); 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 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 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 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 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 red = (700..780)
let p = img.get_pixel(x, y).0; .flat_map(|y| (300..500).map(move |x| (x, y)))
p[0] > 150 && p[1] < 80 .filter(|&(x, y)| {
}).count(); 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)"); 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. // 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]); 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; let out = pictor_pdf::apply(engine(), &locked, Some("pw"), &edits).unwrap().bytes;
assert!(pictor_pdf::is_encrypted(&out)); assert!(pictor_pdf::is_encrypted(&out));
assert_eq!(pictor_pdf::extract_text(engine(), &out, Some("pw")).unwrap()[0].trim(), "Secret page 1"); 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::is_encrypted(&removed));
assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err()); assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err());
} }
#[test] #[test]
fn edits_serialise_for_the_worker() { 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 json = serde_json::to_string(&edits).unwrap();
let back: Edits = serde_json::from_str(&json).unwrap(); let back: Edits = serde_json::from_str(&json).unwrap();
assert_eq!(back.annotations.len(), 9); assert_eq!(back.annotations.len(), 9);
+9 -3
View File
@@ -25,7 +25,10 @@ fn reorder_rotate_delete_and_insert_blank() {
assert_eq!(sizes[2], (842.0, 595.0), "page 1 was not turned"); 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. // Deleted pages are gone from the file, not just from the page list.
for blob in scan_objects(&out) { 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] #[test]
fn images_to_pdf_and_back() { fn images_to_pdf_and_back() {
let mut jpeg = Vec::new(); 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(); 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(); let mut png = Vec::new();
logo.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); 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(); let pdf = pictor_pdf::images_to_pdf(&[(jpeg.clone(), photo.clone()), (png, logo)], PageFit::A4, 36.0).unwrap();
+28 -7
View File
@@ -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"); 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). // The raw stream bytes too (lopdf writes untouched streams as they were).
let raw = |d: &Document, p| -> Vec<Vec<u8>> { let raw = |d: &Document, p| -> Vec<Vec<u8>> {
d.get_page_contents(p).iter().map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone()).collect() 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"); 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); let p = img.get_pixel(300, 100);
assert!(p.0.iter().all(|&c| c < 16), "box not black: {p:?}"); 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. // "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)"); 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 input = secret_pdf(&Options::default());
let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap(); let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap();
assert!( assert!(
pictor_pdf::redact(engine(), &locked, None, &[Redaction { page: 0, rects: vec![secret_box()] }], &Default::default()) pictor_pdf::redact(
.is_err(), engine(),
&locked,
None,
&[Redaction { page: 0, rects: vec![secret_box()] }],
&Default::default()
)
.is_err(),
"redacted without the password" "redacted without the password"
); );
let out = pictor_pdf::redact( let out = pictor_pdf::redact(
@@ -144,10 +156,19 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() {
#[test] #[test]
fn no_redaction_box_is_refused() { fn no_redaction_box_is_refused() {
let input = secret_pdf(&Options::default()); let input = secret_pdf(&Options::default());
assert!(pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()).is_err());
assert!( assert!(
pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 9, rects: vec![secret_box()] }], &Default::default()) pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default())
.is_err(), .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" "a page that does not exist was accepted"
); );
} }
+323 -312
View File
@@ -1,312 +1,323 @@
//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does. //! 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 //! 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 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`). //! a fresh one (open PDFs must then be opened again: the error kind says `restarted`).
use crate::{OpError, PROTOCOL}; use crate::{OpError, PROTOCOL};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write}; use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio}; use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct WorkerOptions { pub struct WorkerOptions {
pub exe: PathBuf, pub exe: PathBuf,
/// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR). /// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR).
pub pdfium_dir: Option<PathBuf>, pub pdfium_dir: Option<PathBuf>,
/// The worker's memory cap. /// The worker's memory cap.
pub memory_mb: u64, pub memory_mb: u64,
/// Enables the debug.* operations (tests). /// Enables the debug.* operations (tests).
pub debug: bool, pub debug: bool,
} }
impl WorkerOptions { impl WorkerOptions {
pub fn new(exe: impl Into<PathBuf>) -> WorkerOptions { pub fn new(exe: impl Into<PathBuf>) -> WorkerOptions {
WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false } WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false }
} }
} }
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum WorkerError { pub enum WorkerError {
/// The operation failed cleanly (bad file, wrong password, …): show `message`. /// The operation failed cleanly (bad file, wrong password, …): show `message`.
#[error("{0}")] #[error("{0}")]
Op(OpError), Op(OpError),
#[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")] #[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")]
TimedOut(u64), TimedOut(u64),
#[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")] #[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")]
OutOfMemory, OutOfMemory,
#[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")] #[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")]
Crashed(String), Crashed(String),
#[error("Pictor's file reader could not start: {0}")] #[error("Pictor's file reader could not start: {0}")]
Spawn(String), Spawn(String),
} }
impl WorkerError { impl WorkerError {
/// A short machine-readable kind, like [`OpError::kind`]. /// A short machine-readable kind, like [`OpError::kind`].
pub fn kind(&self) -> &str { pub fn kind(&self) -> &str {
match self { match self {
WorkerError::Op(e) => &e.kind, WorkerError::Op(e) => &e.kind,
WorkerError::TimedOut(_) => "timed_out", WorkerError::TimedOut(_) => "timed_out",
WorkerError::OutOfMemory => "out_of_memory", WorkerError::OutOfMemory => "out_of_memory",
WorkerError::Crashed(_) => "crashed", WorkerError::Crashed(_) => "crashed",
WorkerError::Spawn(_) => "spawn", WorkerError::Spawn(_) => "spawn",
} }
} }
} }
struct Running { struct Running {
child: Child, child: Child,
stdin: ChildStdin, stdin: ChildStdin,
lines: Receiver<String>, lines: Receiver<String>,
stderr: Arc<Mutex<String>>, stderr: Arc<Mutex<String>>,
#[cfg(windows)] #[cfg(windows)]
_job: job::Job, _job: job::Job,
} }
pub struct Worker { pub struct Worker {
opts: WorkerOptions, opts: WorkerOptions,
running: Option<Running>, running: Option<Running>,
next_id: u64, next_id: u64,
/// Set when the worker had to be restarted since the caller last asked (open documents are gone). /// Set when the worker had to be restarted since the caller last asked (open documents are gone).
restarted: bool, restarted: bool,
} }
impl Worker { impl Worker {
pub fn new(opts: WorkerOptions) -> Worker { pub fn new(opts: WorkerOptions) -> Worker {
Worker { opts, running: None, next_id: 1, restarted: false } Worker { opts, running: None, next_id: 1, restarted: false }
} }
pub fn exe(&self) -> &Path { pub fn exe(&self) -> &Path {
&self.opts.exe &self.opts.exe
} }
/// True once after the worker was restarted (its open documents are gone). /// True once after the worker was restarted (its open documents are gone).
pub fn take_restarted(&mut self) -> bool { pub fn take_restarted(&mut self) -> bool {
std::mem::take(&mut self.restarted) std::mem::take(&mut self.restarted)
} }
fn spawn(&mut self) -> Result<(), WorkerError> { fn spawn(&mut self) -> Result<(), WorkerError> {
let mut cmd = Command::new(&self.opts.exe); let mut cmd = Command::new(&self.opts.exe);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(d) = &self.opts.pdfium_dir { if let Some(d) = &self.opts.pdfium_dir {
cmd.env("PICTOR_PDFIUM_DIR", d); cmd.env("PICTOR_PDFIUM_DIR", d);
} }
if self.opts.debug { if self.opts.debug {
cmd.env("PICTOR_WORKER_DEBUG", "1"); cmd.env("PICTOR_WORKER_DEBUG", "1");
} }
#[cfg(windows)] #[cfg(windows)]
{ {
use std::os::windows::process::CommandExt; use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000; const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW); cmd.creation_flags(CREATE_NO_WINDOW);
} }
let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?; let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?;
#[cfg(windows)] #[cfg(windows)]
let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) { let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) {
Ok(j) => j, Ok(j) => j,
Err(e) => { Err(e) => {
let _ = child.kill(); let _ = child.kill();
return Err(WorkerError::Spawn(format!("job object: {e}"))); return Err(WorkerError::Spawn(format!("job object: {e}")));
} }
}; };
let stdin = child.stdin.take().expect("piped"); let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped"); let stdout = child.stdout.take().expect("piped");
let stderr_pipe = child.stderr.take().expect("piped"); let stderr_pipe = child.stderr.take().expect("piped");
let (tx, rx) = channel(); let (tx, rx) = channel();
std::thread::spawn(move || { std::thread::spawn(move || {
let mut r = BufReader::new(stdout); let mut r = BufReader::new(stdout);
loop { loop {
let mut line = String::new(); let mut line = String::new();
match r.read_line(&mut line) { match r.read_line(&mut line) {
Ok(0) | Err(_) => return, Ok(0) | Err(_) => return,
Ok(_) => { Ok(_) => {
if tx.send(line).is_err() { if tx.send(line).is_err() {
return; return;
} }
} }
} }
} }
}); });
let stderr = Arc::new(Mutex::new(String::new())); let stderr = Arc::new(Mutex::new(String::new()));
let sink = stderr.clone(); let sink = stderr.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let mut r = BufReader::new(stderr_pipe); let mut r = BufReader::new(stderr_pipe);
let mut line = String::new(); let mut line = String::new();
while let Ok(n) = r.read_line(&mut line) { while let Ok(n) = r.read_line(&mut line) {
if n == 0 { if n == 0 {
return; return;
} }
let mut s = sink.lock().unwrap_or_else(|p| p.into_inner()); let mut s = sink.lock().unwrap_or_else(|p| p.into_inner());
if s.len() < 16 << 10 { if s.len() < 16 << 10 {
s.push_str(&line); s.push_str(&line);
} }
line.clear(); line.clear();
} }
}); });
let mut running = Running { let mut running = Running {
child, child,
stdin, stdin,
lines: rx, lines: rx,
stderr, stderr,
#[cfg(windows)] #[cfg(windows)]
_job: job, _job: job,
}; };
let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| { let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| {
let _ = running.child.kill(); let _ = running.child.kill();
WorkerError::Spawn("it did not answer".into()) WorkerError::Spawn("it did not answer".into())
})?; })?;
let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?; 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) { if hello["protocol"].as_u64() != Some(PROTOCOL as u64) {
let _ = running.child.kill(); let _ = running.child.kill();
return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"]))); return Err(WorkerError::Spawn(format!(
} "it speaks protocol {}, Pictor needs {PROTOCOL}",
self.running = Some(running); hello["protocol"]
Ok(()) )));
} }
self.running = Some(running);
fn kill(&mut self) { Ok(())
if let Some(mut r) = self.running.take() { }
let _ = r.child.kill();
let _ = r.child.wait(); fn kill(&mut self) {
self.restarted = true; if let Some(mut r) = self.running.take() {
} let _ = r.child.kill();
} let _ = r.child.wait();
self.restarted = true;
/// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed. }
pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result<Value, WorkerError> { }
if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) {
self.kill(); /// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed.
} pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result<Value, WorkerError> {
if self.running.is_none() { if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) {
self.spawn()?; self.kill();
} }
let id = self.next_id; if self.running.is_none() {
self.next_id += 1; self.spawn()?;
let r = self.running.as_mut().expect("spawned"); }
let line = json!({"id": id, "op": op, "args": args}).to_string(); let id = self.next_id;
if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() { self.next_id += 1;
return Err(self.died()); let r = self.running.as_mut().expect("spawned");
} let line = json!({"id": id, "op": op, "args": args}).to_string();
let deadline = std::time::Instant::now() + timeout; if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() {
loop { return Err(self.died());
let r = self.running.as_mut().expect("spawned"); }
let left = deadline.saturating_duration_since(std::time::Instant::now()); let deadline = std::time::Instant::now() + timeout;
match r.lines.recv_timeout(left) { loop {
Ok(text) => { let r = self.running.as_mut().expect("spawned");
let v: Value = match serde_json::from_str(&text) { let left = deadline.saturating_duration_since(std::time::Instant::now());
Ok(v) => v, match r.lines.recv_timeout(left) {
Err(_) => continue, Ok(text) => {
}; let v: Value = match serde_json::from_str(&text) {
if v["id"].as_u64() != Some(id) { Ok(v) => v,
continue; // a late answer to a request that already timed out Err(_) => continue,
} };
if let Some(ok) = v.get("ok") { if v["id"].as_u64() != Some(id) {
return Ok(ok.clone()); continue; // a late answer to a request that already timed out
} }
let err: OpError = serde_json::from_value(v["err"].clone()) if let Some(ok) = v.get("ok") {
.unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer.")); return Ok(ok.clone());
return Err(WorkerError::Op(err)); }
} let err: OpError = serde_json::from_value(v["err"].clone())
Err(RecvTimeoutError::Timeout) => { .unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer."));
self.kill(); return Err(WorkerError::Op(err));
return Err(WorkerError::TimedOut(timeout.as_secs().max(1))); }
} Err(RecvTimeoutError::Timeout) => {
Err(RecvTimeoutError::Disconnected) => return Err(self.died()), 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)); 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(stderr); let stderr =
// pdfium aborts without a word when an allocation fails; the job's peak memory tells that story. self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default();
#[cfg(windows)] // Give the stderr thread a moment to collect the last words.
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); std::thread::sleep(Duration::from_millis(50));
#[cfg(not(windows))] let stderr =
let hit_cap = false; self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
self.kill(); // pdfium aborts without a word when an allocation fails; the job's peak memory tells that story.
if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") { #[cfg(windows)]
WorkerError::OutOfMemory let hit_cap = self
} else { .running
WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string()) .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;
impl Drop for Worker { self.kill();
fn drop(&mut self) { if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") {
self.kill(); WorkerError::OutOfMemory
} } else {
} WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string())
}
#[cfg(windows)] }
mod job { }
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::*; impl Drop for Worker {
use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; fn drop(&mut self) {
self.kill();
pub struct Job(HANDLE); }
unsafe impl Send for Job {} }
impl Job { #[cfg(windows)]
pub fn new(memory_mb: u64) -> Result<Job, String> { mod job {
unsafe { use windows::Win32::Foundation::{CloseHandle, HANDLE};
let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?; use windows::Win32::System::JobObjects::*;
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20; pub struct Job(HANDLE);
SetInformationJobObject( unsafe impl Send for Job {}
h,
JobObjectExtendedLimitInformation, impl Job {
&info as *const _ as *const _, pub fn new(memory_mb: u64) -> Result<Job, String> {
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, unsafe {
) let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?;
.map_err(|e| { let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
let _ = CloseHandle(h); info.BasicLimitInformation.LimitFlags =
e.to_string() JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
})?; info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20;
Ok(Job(h)) SetInformationJobObject(
} h,
} JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
pub fn assign(&self, child: &std::process::Child) -> Result<(), String> { std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
unsafe { )
let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?; .map_err(|e| {
let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string()); let _ = CloseHandle(h);
let _ = CloseHandle(p); e.to_string()
r })?;
} Ok(Job(h))
} }
} }
impl Job { pub fn assign(&self, child: &std::process::Child) -> Result<(), String> {
/// The most memory the worker ever committed, in bytes. unsafe {
pub fn peak_bytes(&self) -> Option<u64> { let p =
unsafe { OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string());
QueryInformationJobObject( let _ = CloseHandle(p);
Some(self.0), r
JobObjectExtendedLimitInformation, }
&mut info as *mut _ as *mut _, }
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, }
None,
) impl Job {
.ok()?; /// The most memory the worker ever committed, in bytes.
Some(info.PeakProcessMemoryUsed as u64) pub fn peak_bytes(&self) -> Option<u64> {
} unsafe {
} let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
} QueryInformationJobObject(
Some(self.0),
impl Drop for Job { JobObjectExtendedLimitInformation,
fn drop(&mut self) { &mut info as *mut _ as *mut _,
unsafe { std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
let _ = CloseHandle(self.0); None,
} )
} .ok()?;
} Some(info.PeakProcessMemoryUsed as u64)
} }
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.0);
}
}
}
}
+5 -1
View File
@@ -31,7 +31,11 @@ fn main() {
let req: Value = match serde_json::from_str(line.trim_end()) { let req: Value = match serde_json::from_str(line.trim_end()) {
Ok(v) => v, Ok(v) => v,
Err(e) => { 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(); let _ = out.flush();
continue; continue;
} }
+11 -5
View File
@@ -238,8 +238,11 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
} }
let a: A = args(a)?; let a: A = args(a)?;
let engine = state.engine()?; let engine = state.engine()?;
let files: Vec<(Vec<u8>, Option<String>)> = let files: Vec<(Vec<u8>, Option<String>)> = a
a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::<Result<_, _>>()?; .inputs
.iter()
.map(|i| read_file(&i.path).map(|b| (b, i.password.clone())))
.collect::<Result<_, _>>()?;
let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect(); let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect();
let bytes = pictor_pdf::merge(engine, &refs)?; let bytes = pictor_pdf::merge(engine, &refs)?;
write_out(&a.output, &bytes, SaveMode::New) write_out(&a.output, &bytes, SaveMode::New)
@@ -309,7 +312,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
let bytes = read_file(&a.path)?; let bytes = read_file(&a.path)?;
let img = pictor_raster::decode(&bytes, &Limits::default())?; let img = pictor_raster::decode(&bytes, &Limits::default())?;
let (w, h) = (img.width(), img.height()); 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})) Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
} }
"image.convert" => { "image.convert" => {
@@ -347,7 +351,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
if let Some(f) = a.resize { if let Some(f) = a.resize {
img = pictor_raster::resize(&img, f, &limits)?; 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 (bytes, format) = if let Some(target) = a.target_bytes {
let c = pictor_raster::compress_to(&img, format, target, &limits)?; let c = pictor_raster::compress_to(&img, format, target, &limits)?;
(c.bytes, c.format) (c.bytes, c.format)
@@ -391,7 +396,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
let a: A = args(a)?; let a: A = args(a)?;
let bytes = read_file(&a.input)?; let bytes = read_file(&a.input)?;
let stripped = pictor_meta::strip(&bytes)?; 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); out["removed"] = json!(stripped.removed);
Ok(out) Ok(out)
} }
+335 -294
View File
@@ -1,294 +1,335 @@
//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text, //! 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; //! 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 //! 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. //! 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). //! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
use flate2::{Compression, write::ZlibEncoder}; use flate2::{Compression, write::ZlibEncoder};
use lopdf::{Document, Object, Stream, dictionary}; use lopdf::{Document, Object, Stream, dictionary};
use pictor_worker::client::{Worker, WorkerError, WorkerOptions}; use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
use serde_json::json; use serde_json::json;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(15); const CAP: Duration = Duration::from_secs(15);
fn worker() -> Worker { fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-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.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024; o.memory_mb = 1024;
o.debug = true; o.debug = true;
Worker::new(o) Worker::new(o)
} }
fn base_doc(content: &[u8]) -> Document { fn base_doc(content: &[u8]) -> Document {
let mut doc = Document::with_version("1.7"); let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id(); let pages = doc.new_object_id();
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec())); let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c, let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}}); "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1, doc.objects.insert(
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]})); pages,
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages}); Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
doc.trailer.set("Root", cat); "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
doc );
} let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", cat);
fn save(mut doc: Document) -> Vec<u8> { doc
let mut v = Vec::new(); }
doc.save_to(&mut v).unwrap();
v fn save(mut doc: Document) -> Vec<u8> {
} let mut v = Vec::new();
doc.save_to(&mut v).unwrap();
fn valid() -> Vec<u8> { v
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET")) }
}
fn valid() -> Vec<u8> {
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> { save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern"); }
[&hay[..i], to, &hay[i + from.len()..]].concat()
} fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> { [&hay[..i], to, &hay[i + from.len()..]].concat()
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, fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800, let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff}); let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" }, let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc}); "FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
let page = *doc.get_pages().values().next().unwrap(); "Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}}); let font = doc.add_object(
save(doc) dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
} "BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc},
);
fn fixtures() -> Vec<(&'static str, Vec<u8>)> { let page = *doc.get_pages().values().next().unwrap();
let v = valid(); doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
let mut out: Vec<(&str, Vec<u8>)> = vec![ save(doc)
("empty file", Vec::new()), }
("header only", b"%PDF-1.7\n".to_vec()),
("truncated at 10%", v[..v.len() / 10].to_vec()), fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
("truncated at 50%", v[..v.len() / 2].to_vec()), let v = valid();
("truncated before the trailer", v[..v.len() - 40].to_vec()), let mut out: Vec<(&str, Vec<u8>)> = vec![
("random bytes after a header", { ("empty file", Vec::new()),
let mut x = b"%PDF-1.7\n".to_vec(); ("header only", b"%PDF-1.7\n".to_vec()),
let mut s = 0x2545_4446u32; ("truncated at 10%", v[..v.len() / 10].to_vec()),
for _ in 0..20_000 { ("truncated at 50%", v[..v.len() / 2].to_vec()),
s ^= s << 13; ("truncated before the trailer", v[..v.len() - 40].to_vec()),
s ^= s >> 17; ("random bytes after a header", {
s ^= s << 5; let mut x = b"%PDF-1.7\n".to_vec();
x.push(s as u8); let mut s = 0x2545_4446u32;
} for _ in 0..20_000 {
x s ^= s << 13;
}), s ^= s >> 17;
]; s ^= s << 5;
// Broken xref: startxref points nowhere, then the table itself is garbage. x.push(s as u8);
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())); x
// 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(); // Broken xref: startxref points nowhere, then the table itself is garbage.
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0); let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
let mut garbled = v.clone(); out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7; // lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
let end = (data + 40).min(garbled.len()); let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
for b in garbled[data..end].iter_mut() { let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
*b = b.wrapping_mul(31).wrapping_add(7); let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
} let mut garbled = v.clone();
out.push(("garbled xref table", garbled)); let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat())); let end = (data + 40).min(garbled.len());
// Recursive references. for b in garbled[data..end].iter_mut() {
{ *b = b.wrapping_mul(31).wrapping_add(7);
let mut doc = base_doc(b""); }
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap(); out.push(("garbled xref table", garbled));
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]); out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
out.push(("page tree that contains itself", save(doc))); // Recursive references.
} {
{ let mut doc = base_doc(b"");
let mut doc = base_doc(b""); let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
let page = *doc.get_pages().values().next().unwrap(); doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap(); out.push(("page tree that contains itself", save(doc)));
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page)); }
out.push(("parent loop", save(doc))); {
} let mut doc = base_doc(b"");
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())); let page = *doc.get_pages().values().next().unwrap();
out.push(("deeply nested arrays", { let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
let mut deep = vec![b'['; 200_000]; doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
deep.extend(vec![b']'; 200_000]); out.push(("parent loop", save(doc)));
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat()) }
})); out.push((
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647"))); "object that is a reference to itself",
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]"))); replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R")
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB. .into_iter()
{ .chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied())
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET"); .collect(),
let bytes = save(doc); ));
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap(); out.push(("deeply nested arrays", {
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap(); let mut deep = vec![b'['; 200_000];
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat())); deep.extend(vec![b']'; 200_000]);
} replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
{ }));
let mut z = ZlibEncoder::new(Vec::new(), Compression::best()); out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
let zeros = vec![b' '; 1 << 20]; out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
for _ in 0..1024 { // A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
z.write_all(&zeros).unwrap(); {
} let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
let bomb = z.finish().unwrap(); let bytes = save(doc);
let mut doc = base_doc(b""); let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
let page = *doc.get_pages().values().next().unwrap(); let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false)); out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
doc.get_dictionary_mut(page).unwrap().set("Contents", c); }
out.push(("content stream that inflates to 1 GiB", save(doc))); {
} let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
// Malformed fonts. let zeros = vec![b' '; 1 << 20];
out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()))); for _ in 0..1024 {
out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()))); z.write_all(&zeros).unwrap();
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. let bomb = z.finish().unwrap();
out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"))); let mut doc = base_doc(b"");
out 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);
fn fetched() -> Vec<(String, Vec<u8>)> { out.push(("content stream that inflates to 1 GiB", save(doc)));
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched"); }
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() }; // Malformed fonts.
let mut v: Vec<(String, Vec<u8>)> = rd out.push((
.filter_map(|e| e.ok()) "TrueType font of garbage",
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf"))) font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()),
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap())) ));
.collect(); out.push((
v.sort(); "TrueType claiming 65535 tables",
v font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()),
} ));
out.push((
#[derive(Default, Debug)] "truncated Type 1 font",
struct Tally { font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec()),
ok: usize, ));
typed_error: usize, // Encryption with a handler that does not exist.
timed_out: usize, out.push((
out_of_memory: usize, "unknown security handler",
crashed: usize, replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"),
} ));
out
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); fn fetched() -> Vec<(String, Vec<u8>)> {
let took = start.elapsed(); let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap"); let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
let outcome = match &r { let mut v: Vec<(String, Vec<u8>)> = rd
Ok(_) => { .filter_map(|e| e.ok())
tally.ok += 1; .filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
"ok".to_string() .map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
} .collect();
Err(WorkerError::Op(e)) => { v.sort();
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}"); v
tally.typed_error += 1; }
format!("{} ({})", e.kind, e.message)
} #[derive(Default, Debug)]
Err(WorkerError::TimedOut(_)) => { struct Tally {
tally.timed_out += 1; ok: usize,
"timed out".into() typed_error: usize,
} timed_out: usize,
Err(WorkerError::OutOfMemory) => { out_of_memory: usize,
tally.out_of_memory += 1; crashed: usize,
"out of memory".into() }
}
Err(WorkerError::Crashed(m)) => { fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
tally.crashed += 1; let start = Instant::now();
format!("crashed: {m}") let r = w.call(op, args, CAP);
} let took = start.elapsed();
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"), assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
}; let outcome = match &r {
println!("{name:40} {op:10} {took:>8.2?} {outcome}"); Ok(_) => {
} tally.ok += 1;
"ok".to_string()
#[test] }
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() { Err(WorkerError::Op(e)) => {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
let mut w = worker(); tally.typed_error += 1;
let mut tally = Tally::default(); format!("{} ({})", e.kind, e.message)
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect(); }
all.extend(fetched()); Err(WorkerError::TimedOut(_)) => {
let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]}); tally.timed_out += 1;
for (i, (name, bytes)) in all.iter().enumerate() { "timed out".into()
let path = dir.path().join(format!("f{i}.pdf")); }
std::fs::write(&path, bytes).unwrap(); Err(WorkerError::OutOfMemory) => {
let p = path.to_string_lossy().to_string(); tally.out_of_memory += 1;
let start = Instant::now(); "out of memory".into()
let opened = w.call("pdf.open", json!({"path": p}), CAP); }
let took = start.elapsed(); Err(WorkerError::Crashed(m)) => {
let doc = match &opened { tally.crashed += 1;
Ok(v) => { format!("crashed: {m}")
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)); Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
v["doc"].as_u64() };
} println!("{name:40} {op:10} {took:>8.2?} {outcome}");
Err(e) => { }
match e {
WorkerError::Op(_) => tally.typed_error += 1, #[test]
WorkerError::TimedOut(_) => tally.timed_out += 1, fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
WorkerError::OutOfMemory => tally.out_of_memory += 1, let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
WorkerError::Crashed(_) => tally.crashed += 1, let mut w = worker();
WorkerError::Spawn(e) => panic!("{e}"), let mut tally = Tally::default();
} let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind()); all.extend(fetched());
None 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() {
if let Some(doc) = doc { let path = dir.path().join(format!("f{i}.pdf"));
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800})); std::fs::write(&path, bytes).unwrap();
if w.take_restarted() { let p = path.to_string_lossy().to_string();
continue; let start = Instant::now();
} let opened = w.call("pdf.open", json!({"path": p}), CAP);
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc})); let took = start.elapsed();
if w.take_restarted() { let doc = match &opened {
continue; Ok(v) => {
} tally.ok += 1;
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string(); println!(
run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"})); "{name:40} {:10} {took:>8.2?} ok, {} pages",
} "open",
run(&mut w, &mut tally, name, "meta.read", json!({"path": p})); v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0)
w.take_restarted(); );
// The tray carries on: a normal request right after works. v["doc"].as_u64()
let good = dir.path().join("good.pdf"); }
std::fs::write(&good, valid()).unwrap(); Err(e) => {
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one"); match e {
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap(); WorkerError::Op(_) => tally.typed_error += 1,
} WorkerError::TimedOut(_) => tally.timed_out += 1,
println!("{} fixtures: {tally:?}", all.len()); WorkerError::OutOfMemory => tally.out_of_memory += 1,
assert!(all.len() >= 21); WorkerError::Crashed(_) => tally.crashed += 1,
assert_eq!(tally.timed_out, 0, "a fixture hung"); WorkerError::Spawn(e) => panic!("{e}"),
assert_eq!(tally.crashed, 0, "a worker died without a known cause"); }
} println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
None
#[test] }
fn the_client_survives_crash_hang_and_memory_blowup() { };
let mut w = worker(); if let Some(doc) = doc {
let crash = w.call("debug.crash", json!({}), CAP); run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}"); if w.take_restarted() {
assert!(w.take_restarted()); continue;
let start = Instant::now(); }
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2)); run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}"); if w.take_restarted() {
assert!(start.elapsed() < Duration::from_secs(10)); continue;
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. let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
assert!(matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))), "the 1 GB memory cap did not hold: {oom:?}"); run(
// And it works again. &mut w,
let ok = w.call("image.heif_support", json!({}), CAP).unwrap(); &mut tally,
assert!(ok["support"].is_string()); name,
} "pdf.save",
json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}),
#[test] );
fn unknown_operations_and_bad_arguments_are_typed_errors() { }
let mut w = worker(); run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
for (op, args) in [("nope", json!({})), ("pdf.open", json!({"wrong": 1})), ("pdf.render", json!({"doc": 77, "page": 0, "width": 10}))] { w.take_restarted();
match w.call(op, args, CAP) { // The tray carries on: a normal request right after works.
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"), let good = dir.path().join("good.pdf");
other => panic!("{op}: {other:?}"), 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();
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:?}"); 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:?}");
}
+145
View File
@@ -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. Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
<!-- deps:begin --> <!-- deps:begin -->
141 crates; 0 outside the allowed set.
| Crate | Version | Licence | Allowed |
| :-- | :-- | :-- | :-- |
| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes |
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
| block-buffer | 0.12.1 | MIT OR Apache-2.0 | yes |
| block-padding | 0.4.2 | MIT OR Apache-2.0 | yes |
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
| bytes | 1.12.1 | MIT | yes |
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
| cfg_aliases | 0.2.2 | MIT | yes |
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
| color_quant | 1.1.0 | MIT | yes |
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
| fax | 0.2.7 | MIT | yes |
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
| foldhash | 0.2.0 | Zlib | yes |
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes |
| gif | 0.14.2 | MIT OR Apache-2.0 | yes |
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
| libloading | 0.9.1 | ISC | yes |
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
| lopdf | 0.47.0 | MIT | yes |
| lru | 0.18.5 | MIT | yes |
| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes |
| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes |
| memchr | 2.8.3 | Unlicense OR MIT | yes |
| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes |
| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes |
| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes |
| multiversion_no_op | 1.0.0 | Apache-2.0 OR MIT | yes |
| mutate_once | 0.1.2 | BSD-2-Clause | yes |
| nom | 8.0.0 | MIT | yes |
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
| piston-float | 1.0.1 | MIT | yes |
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes |
| proptest | 1.12.0 | MIT OR Apache-2.0 | yes |
| pxfm | 0.1.30 | BSD-3-Clause OR Apache-2.0 | yes |
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
| serde | 1.0.229 | MIT OR Apache-2.0 | yes |
| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes |
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
| simd-adler32 | 0.3.10 | MIT | yes |
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes |
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
| tiff | 0.11.3 | MIT | yes |
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
| vecmath | 1.0.0 | MIT | yes |
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
| windows-collections | 0.3.2 | MIT OR Apache-2.0 | yes |
| windows-core | 0.62.2 | MIT OR Apache-2.0 | yes |
| windows-future | 0.3.2 | MIT OR Apache-2.0 | yes |
| windows-implement | 0.60.2 | MIT OR Apache-2.0 | yes |
| windows-interface | 0.59.3 | MIT OR Apache-2.0 | yes |
| windows-link | 0.2.1 | MIT OR Apache-2.0 | yes |
| windows-numerics | 0.3.1 | MIT OR Apache-2.0 | yes |
| windows-result | 0.4.1 | MIT OR Apache-2.0 | yes |
| windows-strings | 0.5.1 | MIT OR Apache-2.0 | yes |
| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes |
| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes |
| winnow | 1.0.5 | MIT | yes |
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
| zlib-rs | 0.6.8 | Zlib | yes |
| zmij | 1.0.23 | MIT | yes |
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
<!-- deps:end --> <!-- deps:end -->
+106
View File
@@ -0,0 +1,106 @@
# Formats and the worker protocol
What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to
`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own
section here.
## Images (crates/raster, crates/meta)
| Format | Read | Write | Metadata strip |
| :-- | :-- | :-- | :-- |
| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical |
| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical |
| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed |
| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) |
| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused |
| BMP | yes | yes | (no metadata) |
| ICO | yes | 256/48/32/16 px | — |
| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first |
| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — |
Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`):
128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding.
HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video
Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing.
## PDF (crates/pdf)
Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the
page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space.
| Operation | Library | Why |
| :-- | :-- | :-- |
| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens |
| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) |
| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over |
| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask |
| PDF → PNG/JPG | pdfium | rendering |
| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too |
| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` |
| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation |
| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | |
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
| password off | lopdf decrypting load + plain save | |
| true redaction | pdfium render + lopdf rebuild (below) | |
### True redaction
Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted
black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept,
`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page
tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and
`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and
non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they
stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is
written fresh (no incremental history). The other pages' objects are written back byte for byte.
Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only
what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form
XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
and decompressed), and a raw byte grep.
## The worker protocol (crates/worker), version 1
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol.
```
→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}}
← {"id": 7, "ok": {"png": "<base64>", "width": 1200, "height": 1553}}
← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}}
```
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
| Operation | Arguments | Result |
| :-- | :-- | :-- |
| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) |
| `pdf.close` | `doc` | — |
| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` |
| `pdf.text` | `doc` | `pages`: text per page |
| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) |
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` |
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
| `image.heif_support` | — | `support` |
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` |
Saving: `mode: new` refuses to replace a file (the app picks `<name>-edited.pdf`); `overwrite` writes
`<file>.bak` first, then replaces the file in one rename (`crates/save`).
Caps: files over 1 GB are refused; the client runs the worker in a Job Object (2 GB by default, killed with the
app) and gives each request a time cap; a worker that hangs or dies is replaced on the next request (open documents
must then be opened again).