[repo] Format, clippy clean, FORMATS.md, the full crate table in DEPENDENCIES.md
This commit is contained in:
+212
-43
@@ -8,7 +8,7 @@
|
||||
//! same in every viewer; a stamp (the visual signature) goes into the page content itself.
|
||||
//! - Flatten (pdfium `FPDFPage_Flatten`), then lopdf drops the form and every orphaned object.
|
||||
use crate::geometry::{PageFrame, ViewPoint, ViewRect, normalise_rotate};
|
||||
use crate::{Engine, PdfError, PageSpec, Redaction, RedactOptions, lopdf_load, lopdf_save};
|
||||
use crate::{Engine, PageSpec, PdfError, RedactOptions, Redaction, lopdf_load, lopdf_save};
|
||||
use image::DynamicImage;
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, StringFormat, dictionary};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -38,7 +38,9 @@ pub enum Security {
|
||||
#[default]
|
||||
Keep,
|
||||
Remove,
|
||||
Set { password: String },
|
||||
Set {
|
||||
password: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -81,16 +83,42 @@ fn one() -> f32 {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Shape {
|
||||
Highlight { rects: Vec<ViewRect> },
|
||||
Underline { rects: Vec<ViewRect> },
|
||||
Strike { rects: Vec<ViewRect> },
|
||||
Highlight {
|
||||
rects: Vec<ViewRect>,
|
||||
},
|
||||
Underline {
|
||||
rects: Vec<ViewRect>,
|
||||
},
|
||||
Strike {
|
||||
rects: Vec<ViewRect>,
|
||||
},
|
||||
/// A sticky note at a point; its text is `contents`.
|
||||
Note { at: ViewPoint },
|
||||
FreeText { rect: ViewRect, text: String, size: f32 },
|
||||
Ink { strokes: Vec<Vec<ViewPoint>>, width: f32 },
|
||||
Rectangle { rect: ViewRect, width: f32 },
|
||||
Ellipse { rect: ViewRect, width: f32 },
|
||||
Line { from: ViewPoint, to: ViewPoint, width: f32, arrow: bool },
|
||||
Note {
|
||||
at: ViewPoint,
|
||||
},
|
||||
FreeText {
|
||||
rect: ViewRect,
|
||||
text: String,
|
||||
size: f32,
|
||||
},
|
||||
Ink {
|
||||
strokes: Vec<Vec<ViewPoint>>,
|
||||
width: f32,
|
||||
},
|
||||
Rectangle {
|
||||
rect: ViewRect,
|
||||
width: f32,
|
||||
},
|
||||
Ellipse {
|
||||
rect: ViewRect,
|
||||
width: f32,
|
||||
},
|
||||
Line {
|
||||
from: ViewPoint,
|
||||
to: ViewPoint,
|
||||
width: f32,
|
||||
arrow: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// An image burned into a page (the visual signature): PNG or JPEG bytes, placed upright in `rect`.
|
||||
@@ -288,13 +316,47 @@ struct Latin2Font {
|
||||
}
|
||||
|
||||
const EXTRA_GLYPHS: &[(char, &str)] = &[
|
||||
('Á', "Aacute"), ('Č', "Ccaron"), ('č', "ccaron"), ('Ď', "Dcaron"), ('ď', "dcaron"), ('Ě', "Ecaron"),
|
||||
('ě', "ecaron"), ('Ň', "Ncaron"), ('ň', "ncaron"), ('Ř', "Rcaron"), ('ř', "rcaron"), ('Ť', "Tcaron"),
|
||||
('ť', "tcaron"), ('Ů', "Uring"), ('ů', "uring"), ('Ľ', "Lcaron"), ('ľ', "lcaron"), ('Ĺ', "Lacute"),
|
||||
('ĺ', "lacute"), ('Ŕ', "Racute"), ('ŕ', "racute"), ('Ą', "Aogonek"), ('ą', "aogonek"), ('Ę', "Eogonek"),
|
||||
('ę', "eogonek"), ('Ł', "Lslash"), ('ł', "lslash"), ('Ś', "Sacute"), ('ś', "sacute"), ('Ź', "Zacute"),
|
||||
('ź', "zacute"), ('Ż', "Zdotaccent"), ('ż', "zdotaccent"), ('Ć', "Cacute"), ('ć', "cacute"), ('Ń', "Nacute"),
|
||||
('ń', "nacute"), ('Ő', "Ohungarumlaut"), ('ő', "ohungarumlaut"), ('Ű', "Uhungarumlaut"), ('ű', "uhungarumlaut"),
|
||||
('Á', "Aacute"),
|
||||
('Č', "Ccaron"),
|
||||
('č', "ccaron"),
|
||||
('Ď', "Dcaron"),
|
||||
('ď', "dcaron"),
|
||||
('Ě', "Ecaron"),
|
||||
('ě', "ecaron"),
|
||||
('Ň', "Ncaron"),
|
||||
('ň', "ncaron"),
|
||||
('Ř', "Rcaron"),
|
||||
('ř', "rcaron"),
|
||||
('Ť', "Tcaron"),
|
||||
('ť', "tcaron"),
|
||||
('Ů', "Uring"),
|
||||
('ů', "uring"),
|
||||
('Ľ', "Lcaron"),
|
||||
('ľ', "lcaron"),
|
||||
('Ĺ', "Lacute"),
|
||||
('ĺ', "lacute"),
|
||||
('Ŕ', "Racute"),
|
||||
('ŕ', "racute"),
|
||||
('Ą', "Aogonek"),
|
||||
('ą', "aogonek"),
|
||||
('Ę', "Eogonek"),
|
||||
('ę', "eogonek"),
|
||||
('Ł', "Lslash"),
|
||||
('ł', "lslash"),
|
||||
('Ś', "Sacute"),
|
||||
('ś', "sacute"),
|
||||
('Ź', "Zacute"),
|
||||
('ź', "zacute"),
|
||||
('Ż', "Zdotaccent"),
|
||||
('ż', "zdotaccent"),
|
||||
('Ć', "Cacute"),
|
||||
('ć', "cacute"),
|
||||
('Ń', "Nacute"),
|
||||
('ń', "nacute"),
|
||||
('Ő', "Ohungarumlaut"),
|
||||
('ő', "ohungarumlaut"),
|
||||
('Ű', "Uhungarumlaut"),
|
||||
('ű', "uhungarumlaut"),
|
||||
];
|
||||
|
||||
fn winansi(c: char) -> Option<u8> {
|
||||
@@ -303,10 +365,33 @@ fn winansi(c: char) -> Option<u8> {
|
||||
return Some(u as u8);
|
||||
}
|
||||
const HIGH: &[(char, u8)] = &[
|
||||
('€', 0x80), ('‚', 0x82), ('ƒ', 0x83), ('„', 0x84), ('…', 0x85), ('†', 0x86), ('‡', 0x87), ('ˆ', 0x88),
|
||||
('‰', 0x89), ('Š', 0x8A), ('‹', 0x8B), ('Œ', 0x8C), ('Ž', 0x8E), ('‘', 0x91), ('’', 0x92), ('“', 0x93),
|
||||
('”', 0x94), ('•', 0x95), ('–', 0x96), ('—', 0x97), ('˜', 0x98), ('™', 0x99), ('š', 0x9A), ('›', 0x9B),
|
||||
('œ', 0x9C), ('ž', 0x9E), ('Ÿ', 0x9F),
|
||||
('€', 0x80),
|
||||
('‚', 0x82),
|
||||
('ƒ', 0x83),
|
||||
('„', 0x84),
|
||||
('…', 0x85),
|
||||
('†', 0x86),
|
||||
('‡', 0x87),
|
||||
('ˆ', 0x88),
|
||||
('‰', 0x89),
|
||||
('Š', 0x8A),
|
||||
('‹', 0x8B),
|
||||
('Œ', 0x8C),
|
||||
('Ž', 0x8E),
|
||||
('‘', 0x91),
|
||||
('’', 0x92),
|
||||
('“', 0x93),
|
||||
('”', 0x94),
|
||||
('•', 0x95),
|
||||
('–', 0x96),
|
||||
('—', 0x97),
|
||||
('˜', 0x98),
|
||||
('™', 0x99),
|
||||
('š', 0x9A),
|
||||
('›', 0x9B),
|
||||
('œ', 0x9C),
|
||||
('ž', 0x9E),
|
||||
('Ÿ', 0x9F),
|
||||
];
|
||||
HIGH.iter().find(|(h, _)| *h == c).map(|(_, b)| *b)
|
||||
}
|
||||
@@ -328,7 +413,9 @@ impl Latin2Font {
|
||||
}
|
||||
fn encode(&self, text: &str) -> Vec<u8> {
|
||||
text.chars()
|
||||
.map(|c| winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?'))
|
||||
.map(|c| {
|
||||
winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?')
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn dict(&self) -> Dictionary {
|
||||
@@ -431,7 +518,14 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
match &a.shape {
|
||||
Shape::Highlight { .. } => ops.push_str(&format!(
|
||||
"{} {} m {} {} l {} {} l {} {} l h f\n",
|
||||
fmt(tl.0), fmt(tl.1), fmt(tr.0), fmt(tr.1), fmt(br.0), fmt(br.1), fmt(bl.0), fmt(bl.1)
|
||||
fmt(tl.0),
|
||||
fmt(tl.1),
|
||||
fmt(tr.0),
|
||||
fmt(tr.1),
|
||||
fmt(br.0),
|
||||
fmt(br.1),
|
||||
fmt(bl.0),
|
||||
fmt(bl.1)
|
||||
)),
|
||||
_ => {
|
||||
let t = if matches!(a.shape, Shape::Underline { .. }) { 0.93 } else { 0.55 };
|
||||
@@ -440,7 +534,11 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
let p1 = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h * t });
|
||||
ops.push_str(&format!(
|
||||
"{} w {} {} m {} {} l S\n",
|
||||
fmt(lw), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1)
|
||||
fmt(lw),
|
||||
fmt(p0.0),
|
||||
fmt(p0.1),
|
||||
fmt(p1.0),
|
||||
fmt(p1.1)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -461,8 +559,14 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
let [x, y] = [rect[0], rect[1]];
|
||||
let content = format!(
|
||||
"/GS0 gs {rgb} rg 0.25 0.2 0.1 RG 1 w {x0} {y0} 18 18 re B\n0.25 0.2 0.1 RG 1 w {lx} {l1} m {rx} {l1} l {lx} {l2} m {rx} {l2} l {lx} {l3} m {rx2} {l3} l S\n",
|
||||
x0 = fmt(x + 1.0), y0 = fmt(y + 1.0), lx = fmt(x + 4.0), rx = fmt(x + 16.0), rx2 = fmt(x + 12.0),
|
||||
l1 = fmt(y + 14.0), l2 = fmt(y + 10.0), l3 = fmt(y + 6.0)
|
||||
x0 = fmt(x + 1.0),
|
||||
y0 = fmt(y + 1.0),
|
||||
lx = fmt(x + 4.0),
|
||||
rx = fmt(x + 16.0),
|
||||
rx2 = fmt(x + 12.0),
|
||||
l1 = fmt(y + 14.0),
|
||||
l2 = fmt(y + 10.0),
|
||||
l3 = fmt(y + 6.0)
|
||||
);
|
||||
("Text", rect, content, dictionary! {"Name" => "Comment", "Open" => false})
|
||||
}
|
||||
@@ -473,7 +577,14 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
let m = upright_matrix(&frame, *vr);
|
||||
let mut ops = format!(
|
||||
"/GS0 gs q {} {} {} {} {} {} cm BT /Helv {} Tf {rgb} rg {} TL\n",
|
||||
fmt(m[0]), fmt(m[1]), fmt(m[2]), fmt(m[3]), fmt(m[4]), fmt(m[5]), fmt(size), fmt(size * 1.2)
|
||||
fmt(m[0]),
|
||||
fmt(m[1]),
|
||||
fmt(m[2]),
|
||||
fmt(m[3]),
|
||||
fmt(m[4]),
|
||||
fmt(m[5]),
|
||||
fmt(size),
|
||||
fmt(size * 1.2)
|
||||
);
|
||||
ops.push_str(&format!("2 {} Td\n", fmt(vr.h - size)));
|
||||
for (i, line) in wrap(text, size, vr.w - 4.0).iter().enumerate() {
|
||||
@@ -539,21 +650,54 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
let k = 0.552_284_8;
|
||||
format!(
|
||||
"{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c S\n",
|
||||
fmt(cx + rx), fmt(cy),
|
||||
fmt(cx + rx), fmt(cy + k * ry), fmt(cx + k * rx), fmt(cy + ry), fmt(cx), fmt(cy + ry),
|
||||
fmt(cx - k * rx), fmt(cy + ry), fmt(cx - rx), fmt(cy + k * ry), fmt(cx - rx), fmt(cy),
|
||||
fmt(cx - rx), fmt(cy - k * ry), fmt(cx - k * rx), fmt(cy - ry), fmt(cx), fmt(cy - ry),
|
||||
fmt(cx + k * rx), fmt(cy - ry), fmt(cx + rx), fmt(cy - k * ry), fmt(cx + rx), fmt(cy)
|
||||
fmt(cx + rx),
|
||||
fmt(cy),
|
||||
fmt(cx + rx),
|
||||
fmt(cy + k * ry),
|
||||
fmt(cx + k * rx),
|
||||
fmt(cy + ry),
|
||||
fmt(cx),
|
||||
fmt(cy + ry),
|
||||
fmt(cx - k * rx),
|
||||
fmt(cy + ry),
|
||||
fmt(cx - rx),
|
||||
fmt(cy + k * ry),
|
||||
fmt(cx - rx),
|
||||
fmt(cy),
|
||||
fmt(cx - rx),
|
||||
fmt(cy - k * ry),
|
||||
fmt(cx - k * rx),
|
||||
fmt(cy - ry),
|
||||
fmt(cx),
|
||||
fmt(cy - ry),
|
||||
fmt(cx + k * rx),
|
||||
fmt(cy - ry),
|
||||
fmt(cx + rx),
|
||||
fmt(cy - k * ry),
|
||||
fmt(cx + rx),
|
||||
fmt(cy)
|
||||
)
|
||||
};
|
||||
let sub = if matches!(a.shape, Shape::Rectangle { .. }) { "Square" } else { "Circle" };
|
||||
(sub, u, format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)), dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}})
|
||||
(
|
||||
sub,
|
||||
u,
|
||||
format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)),
|
||||
dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}},
|
||||
)
|
||||
}
|
||||
Shape::Line { from, to, width, arrow } => {
|
||||
let w = width.clamp(0.25, 72.0);
|
||||
let p0 = frame.to_user(*from);
|
||||
let p1 = frame.to_user(*to);
|
||||
let mut ops = format!("/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n", fmt(w), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1));
|
||||
let mut ops = format!(
|
||||
"/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n",
|
||||
fmt(w),
|
||||
fmt(p0.0),
|
||||
fmt(p0.1),
|
||||
fmt(p1.0),
|
||||
fmt(p1.1)
|
||||
);
|
||||
let head = (w * 4.0).max(8.0);
|
||||
if *arrow {
|
||||
let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1);
|
||||
@@ -563,12 +707,18 @@ fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<
|
||||
let (px, py) = (-uy * head * 0.5, ux * head * 0.5);
|
||||
ops.push_str(&format!(
|
||||
"{} {} m {} {} l {} {} l h f\n",
|
||||
fmt(p1.0), fmt(p1.1), fmt(bx + px), fmt(by + py), fmt(bx - px), fmt(by - py)
|
||||
fmt(p1.0),
|
||||
fmt(p1.1),
|
||||
fmt(bx + px),
|
||||
fmt(by + py),
|
||||
fmt(bx - px),
|
||||
fmt(by - py)
|
||||
));
|
||||
}
|
||||
let pad = head + w;
|
||||
let rect = [p0.0.min(p1.0) - pad, p0.1.min(p1.1) - pad, p0.0.max(p1.0) + pad, p0.1.max(p1.1) + pad];
|
||||
let mut extra = dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}};
|
||||
let mut extra =
|
||||
dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}};
|
||||
if *arrow {
|
||||
extra.set("LE", vec![Object::Name(b"None".to_vec()), Object::Name(b"OpenArrow".to_vec())]);
|
||||
}
|
||||
@@ -644,7 +794,12 @@ fn add_stamp(doc: &mut Document, page: ObjectId, s: &Stamp, n: usize) -> Result<
|
||||
let name = format!("PictorStamp{n}");
|
||||
let ops = format!(
|
||||
"q {} {} {} {} {} {} cm /{name} Do Q\n",
|
||||
fmt(m[0] * dw), fmt(m[1] * dw), fmt(m[2] * dh), fmt(m[3] * dh), fmt(m[4]), fmt(m[5])
|
||||
fmt(m[0] * dw),
|
||||
fmt(m[1] * dw),
|
||||
fmt(m[2] * dh),
|
||||
fmt(m[3] * dh),
|
||||
fmt(m[4]),
|
||||
fmt(m[5])
|
||||
);
|
||||
// Resources: a page-local copy (it may have been shared or inherited), with the image added.
|
||||
let resources = match inherited(doc, page, b"Resources") {
|
||||
@@ -722,7 +877,14 @@ fn field_tree(doc: &Document) -> Vec<Terminal> {
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
fn walk(doc: &Document, id: ObjectId, prefix: &str, out: &mut Vec<Terminal>, seen: &mut std::collections::HashSet<ObjectId>, depth: u32) {
|
||||
fn walk(
|
||||
doc: &Document,
|
||||
id: ObjectId,
|
||||
prefix: &str,
|
||||
out: &mut Vec<Terminal>,
|
||||
seen: &mut std::collections::HashSet<ObjectId>,
|
||||
depth: u32,
|
||||
) {
|
||||
if depth > 32 || !seen.insert(id) || out.len() > 10_000 {
|
||||
return;
|
||||
}
|
||||
@@ -757,7 +919,7 @@ fn field_tree(doc: &Document) -> Vec<Terminal> {
|
||||
|
||||
pub(crate) fn decode_text(b: &[u8]) -> String {
|
||||
if b.starts_with(&[0xFE, 0xFF]) {
|
||||
let u: Vec<u16> = b[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
|
||||
let u: Vec<u16> = b[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
|
||||
String::from_utf16_lossy(&u)
|
||||
} else {
|
||||
b.iter().map(|&c| c as char).collect()
|
||||
@@ -893,7 +1055,8 @@ fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result<Vec
|
||||
}
|
||||
(b"Btn", FieldInput::Check(on)) if flags & (3 << 15) == 0 => {
|
||||
for w in &t.widgets {
|
||||
let state = if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() };
|
||||
let state =
|
||||
if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() };
|
||||
set(&mut doc, *w, "AS", Object::Name(state.clone()));
|
||||
set(&mut doc, t.id, "V", Object::Name(state));
|
||||
}
|
||||
@@ -904,7 +1067,12 @@ fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result<Vec
|
||||
let on = on_state(&doc, *w);
|
||||
let this = on.as_deref() == Some(choice.as_bytes());
|
||||
found |= this;
|
||||
set(&mut doc, *w, "AS", Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() }));
|
||||
set(
|
||||
&mut doc,
|
||||
*w,
|
||||
"AS",
|
||||
Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() }),
|
||||
);
|
||||
}
|
||||
if !found {
|
||||
return Err(PdfError::Invalid(format!("\"{choice}\" is not an option of \"{}\".", v.name)));
|
||||
@@ -915,7 +1083,8 @@ fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result<Vec
|
||||
}
|
||||
}
|
||||
if needs_appearances {
|
||||
let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?;
|
||||
let catalog_id =
|
||||
doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?;
|
||||
let form = doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"AcroForm").ok()).cloned();
|
||||
match form {
|
||||
Some(Object::Reference(r)) => {
|
||||
|
||||
@@ -32,7 +32,9 @@ impl Engine {
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
@@ -61,7 +61,7 @@ impl PageFrame {
|
||||
}
|
||||
|
||||
pub(crate) fn normalise_rotate(r: i64) -> u16 {
|
||||
(((r % 360) + 360) % 360 / 90 * 90) as u16
|
||||
(r.rem_euclid(360) / 90 * 90) as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -20,7 +20,7 @@ mod security;
|
||||
pub use edit::*;
|
||||
pub use engine::Engine;
|
||||
pub use error::PdfError;
|
||||
pub use geometry::{ViewRect, ViewPoint};
|
||||
pub use geometry::{ViewPoint, ViewRect};
|
||||
pub use pages::*;
|
||||
pub use reader::*;
|
||||
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
||||
@@ -28,8 +28,7 @@ pub use security::{is_encrypted, protect, unlock};
|
||||
|
||||
/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
|
||||
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
||||
let mut opts = lopdf::LoadOptions::default();
|
||||
opts.max_decompressed_size = Some(256 << 20);
|
||||
let mut opts = lopdf::LoadOptions { max_decompressed_size: Some(256 << 20), ..Default::default() };
|
||||
if let Some(p) = password {
|
||||
opts.password = Some(p.to_owned());
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) {
|
||||
if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut current =
|
||||
doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut depth = 0;
|
||||
let mut value = None;
|
||||
while let Some(id) = current {
|
||||
@@ -236,7 +237,7 @@ pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt
|
||||
let has_alpha = rgba.pixels().any(|p| p.0[3] != 255);
|
||||
let rgb: Vec<u8> = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect();
|
||||
let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64,
|
||||
"Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8};
|
||||
"Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8};
|
||||
if has_alpha {
|
||||
let alpha: Vec<u8> = rgba.pixels().map(|p| p.0[3]).collect();
|
||||
let mut smask = Stream::new(
|
||||
@@ -260,7 +261,11 @@ pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt
|
||||
}
|
||||
};
|
||||
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 scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image {
|
||||
1.0
|
||||
} else {
|
||||
f32::MAX
|
||||
});
|
||||
let (dw, dh) = (iw * scale, ih * scale);
|
||||
let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0);
|
||||
let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes();
|
||||
|
||||
@@ -42,7 +42,11 @@ pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Doc
|
||||
let doc = engine.open(bytes, password)?;
|
||||
let mut pages = Vec::new();
|
||||
for page in doc.pages().iter() {
|
||||
pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) });
|
||||
pages.push(PageInfo {
|
||||
width: page.width().value,
|
||||
height: page.height().value,
|
||||
label: page.label().map(Into::into),
|
||||
});
|
||||
}
|
||||
let mut outline = Vec::new();
|
||||
fn walk(b: PdfBookmark, depth: u32, out: &mut Vec<OutlineItem>, budget: &mut u32) {
|
||||
@@ -76,7 +80,12 @@ pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Resu
|
||||
Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result<DynamicImage, PdfError> {
|
||||
pub(crate) fn render_doc_page(
|
||||
doc: &PdfDocument,
|
||||
index: usize,
|
||||
width_px: u32,
|
||||
forms: bool,
|
||||
) -> Result<DynamicImage, PdfError> {
|
||||
let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?;
|
||||
let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0));
|
||||
let width = width_px.clamp(1, 20_000) as i64;
|
||||
|
||||
@@ -52,7 +52,8 @@ pub fn redact(
|
||||
redactions: &[Redaction],
|
||||
opts: &RedactOptions,
|
||||
) -> Result<Redacted, PdfError> {
|
||||
if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) {
|
||||
if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty))
|
||||
{
|
||||
return Err(PdfError::Invalid("Draw at least one box to redact.".into()));
|
||||
}
|
||||
// 1. Render every redacted page with pdfium (annotations and form fields included) and burn the boxes in.
|
||||
@@ -67,7 +68,8 @@ pub fn redact(
|
||||
if !seen.insert(r.page) {
|
||||
continue;
|
||||
}
|
||||
let rects: Vec<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 (vw, vh) = (page.width().value, page.height().value);
|
||||
drop(page);
|
||||
@@ -181,7 +183,8 @@ fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSe
|
||||
for &page in pages {
|
||||
// The nearest ancestor's /Resources, and every Pages node on the way up.
|
||||
let mut inherited = None;
|
||||
let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut current =
|
||||
doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut depth = 0;
|
||||
while let Some(id) = current {
|
||||
if depth > 64 || !nodes.insert(id) && inherited.is_some() {
|
||||
@@ -272,7 +275,11 @@ fn prune_form(doc: &mut Document, removed: &HashSet<ObjectId>) {
|
||||
if changed {
|
||||
let target = match acroform {
|
||||
Some(id) => doc.get_dictionary_mut(id).ok(),
|
||||
None => doc.get_dictionary_mut(catalog_id).ok().and_then(|c| c.get_mut(b"AcroForm").ok()).and_then(|o| o.as_dict_mut().ok()),
|
||||
None => doc
|
||||
.get_dictionary_mut(catalog_id)
|
||||
.ok()
|
||||
.and_then(|c| c.get_mut(b"AcroForm").ok())
|
||||
.and_then(|o| o.as_dict_mut().ok()),
|
||||
};
|
||||
if let Some(f) = target {
|
||||
f.set("Fields", kept);
|
||||
|
||||
@@ -38,6 +38,7 @@ fn s(text: &str) -> Object {
|
||||
Object::String(text.as_bytes().to_vec(), StringFormat::Literal)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Options {
|
||||
pub compress: bool,
|
||||
/// /Rotate on page 1.
|
||||
@@ -46,12 +47,6 @@ pub struct Options {
|
||||
pub inherited: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Options { compress: false, rotate: 0, inherited: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in
|
||||
/// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings.
|
||||
/// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal.
|
||||
@@ -84,7 +79,7 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n"
|
||||
let c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec()));
|
||||
|
||||
let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica",
|
||||
"Encoding" => "WinAnsiEncoding"});
|
||||
"Encoding" => "WinAnsiEncoding"});
|
||||
let field_ap = doc.add_object(Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()],
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}},
|
||||
@@ -160,10 +155,8 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n"
|
||||
"Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id,
|
||||
"ActualText" => s("STRUCT-SECRET"), "K" => 0,
|
||||
});
|
||||
doc.objects.insert(
|
||||
struct_root_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}),
|
||||
);
|
||||
doc.objects
|
||||
.insert(struct_root_id, Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}));
|
||||
let attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec()));
|
||||
let filespec = doc.add_object(dictionary! {
|
||||
"Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach},
|
||||
@@ -211,7 +204,7 @@ pub fn numbered_pdf(n: usize, label: &str) -> Vec<u8> {
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", catalog);
|
||||
|
||||
+86
-27
@@ -47,7 +47,9 @@ fn form_pdf() -> Vec<u8> {
|
||||
}
|
||||
doc.objects.insert(
|
||||
radio_id,
|
||||
Object::Dictionary(dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()}),
|
||||
Object::Dictionary(
|
||||
dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()},
|
||||
),
|
||||
);
|
||||
let city = doc.add_object(dictionary! {
|
||||
"Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"),
|
||||
@@ -57,17 +59,23 @@ fn form_pdf() -> Vec<u8> {
|
||||
let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 12 Tf 72 780 Td (Form) Tj ET".to_vec()));
|
||||
let mut annots = vec![name.into(), agree.into(), city.into()];
|
||||
annots.extend(kids);
|
||||
doc.objects.insert(page_id, Object::Dictionary(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}},
|
||||
}));
|
||||
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
|
||||
}));
|
||||
doc.objects.insert(
|
||||
page_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}},
|
||||
}),
|
||||
);
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
|
||||
}),
|
||||
);
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id,
|
||||
"AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()],
|
||||
"DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}});
|
||||
"AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()],
|
||||
"DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}});
|
||||
doc.trailer.set("Root", catalog);
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).unwrap();
|
||||
@@ -89,7 +97,10 @@ fn fill() -> Edits {
|
||||
fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize {
|
||||
let (x0, y0) = ((r.x * scale) as u32, (r.y * scale) as u32);
|
||||
let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32);
|
||||
(y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::<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]
|
||||
@@ -124,7 +135,13 @@ fn a_filled_form_flattens_into_page_text() {
|
||||
let doc = Document::load_mem(&out).unwrap();
|
||||
assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening");
|
||||
let p = page_ids(&doc)[0];
|
||||
assert!(doc.get_dictionary(p).unwrap().get(b"Annots").map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false)).unwrap_or(true));
|
||||
assert!(
|
||||
doc.get_dictionary(p)
|
||||
.unwrap()
|
||||
.get(b"Annots")
|
||||
.map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false))
|
||||
.unwrap_or(true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -144,15 +161,36 @@ fn every_annotation() -> Vec<Annotation> {
|
||||
let r = |x, y, w, h| ViewRect { x, y, w, h };
|
||||
let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None };
|
||||
vec![
|
||||
Annotation { color: [1.0, 0.9, 0.0], opacity: 0.5, ..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] }) },
|
||||
Annotation {
|
||||
color: [1.0, 0.9, 0.0],
|
||||
opacity: 0.5,
|
||||
..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] })
|
||||
},
|
||||
a(Shape::Underline { rects: vec![r(60.0, 150.0, 200.0, 20.0)] }),
|
||||
a(Shape::Strike { rects: vec![r(60.0, 190.0, 200.0, 20.0)] }),
|
||||
Annotation { contents: Some("Zkontrolovat čísla".into()), ..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } }) },
|
||||
a(Shape::FreeText { rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0 }),
|
||||
a(Shape::Ink { strokes: vec![vec![ViewPoint { x: 60.0, y: 330.0 }, ViewPoint { x: 160.0, y: 380.0 }, ViewPoint { x: 260.0, y: 330.0 }]], width: 3.0 }),
|
||||
Annotation {
|
||||
contents: Some("Zkontrolovat čísla".into()),
|
||||
..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } })
|
||||
},
|
||||
a(Shape::FreeText {
|
||||
rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0
|
||||
}),
|
||||
a(Shape::Ink {
|
||||
strokes: vec![vec![
|
||||
ViewPoint { x: 60.0, y: 330.0 },
|
||||
ViewPoint { x: 160.0, y: 380.0 },
|
||||
ViewPoint { x: 260.0, y: 330.0 },
|
||||
]],
|
||||
width: 3.0,
|
||||
}),
|
||||
a(Shape::Rectangle { rect: r(300.0, 330.0, 100.0, 50.0), width: 2.0 }),
|
||||
a(Shape::Ellipse { rect: r(420.0, 330.0, 100.0, 50.0), width: 2.0 }),
|
||||
a(Shape::Line { from: ViewPoint { x: 60.0, y: 420.0 }, to: ViewPoint { x: 300.0, y: 460.0 }, width: 3.0, arrow: true }),
|
||||
a(Shape::Line {
|
||||
from: ViewPoint { x: 60.0, y: 420.0 },
|
||||
to: ViewPoint { x: 300.0, y: 460.0 },
|
||||
width: 3.0,
|
||||
arrow: true,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -173,7 +211,10 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() {
|
||||
String::from_utf8(d.get(b"Subtype").unwrap().as_name().unwrap().to_vec()).unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(subtypes, ["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]);
|
||||
assert_eq!(
|
||||
subtypes,
|
||||
["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]
|
||||
);
|
||||
let after = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8();
|
||||
for a in every_annotation() {
|
||||
let r = match &a.shape {
|
||||
@@ -197,7 +238,9 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() {
|
||||
|
||||
#[test]
|
||||
fn a_free_text_on_a_rotated_page_lands_where_it_was_drawn() {
|
||||
let input = pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }]).unwrap();
|
||||
let input =
|
||||
pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }])
|
||||
.unwrap();
|
||||
let rect = ViewRect { x: 100.0, y: 300.0, w: 300.0, h: 40.0 };
|
||||
let edits = Edits {
|
||||
annotations: vec![Annotation {
|
||||
@@ -225,7 +268,9 @@ fn signature_png() -> Vec<u8> {
|
||||
if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) }
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
image::DynamicImage::ImageRgba8(img)
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -236,10 +281,13 @@ fn a_signature_stamp_is_burned_into_the_page() {
|
||||
let edits = Edits { stamps: vec![Stamp { page: 1, rect, image: signature_png() }], ..Default::default() };
|
||||
let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes;
|
||||
let img = pictor_pdf::render_page(engine(), &out, None, 1, 595).unwrap().to_rgb8();
|
||||
let red = (700..780).flat_map(|y| (300..500).map(move |x| (x, y))).filter(|&(x, y)| {
|
||||
let p = img.get_pixel(x, y).0;
|
||||
p[0] > 150 && p[1] < 80
|
||||
}).count();
|
||||
let red = (700..780)
|
||||
.flat_map(|y| (300..500).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| {
|
||||
let p = img.get_pixel(x, y).0;
|
||||
p[0] > 150 && p[1] < 80
|
||||
})
|
||||
.count();
|
||||
assert!(red > 100, "the signature is not visible ({red} red pixels)");
|
||||
// Transparent parts stay transparent: the page is white just above the signature's line.
|
||||
assert_eq!(img.get_pixel(305, 702).0, [255, 255, 255]);
|
||||
@@ -259,14 +307,25 @@ fn a_protected_document_stays_protected_with_its_password() {
|
||||
let out = pictor_pdf::apply(engine(), &locked, Some("pw"), &edits).unwrap().bytes;
|
||||
assert!(pictor_pdf::is_encrypted(&out));
|
||||
assert_eq!(pictor_pdf::extract_text(engine(), &out, Some("pw")).unwrap()[0].trim(), "Secret page 1");
|
||||
let removed = pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() }).unwrap().bytes;
|
||||
let removed =
|
||||
pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() })
|
||||
.unwrap()
|
||||
.bytes;
|
||||
assert!(!pictor_pdf::is_encrypted(&removed));
|
||||
assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_serialise_for_the_worker() {
|
||||
let edits = Edits { annotations: every_annotation(), stamps: vec![Stamp { page: 0, rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 }, image: vec![0, 1, 2, 250, 255] }], ..Default::default() };
|
||||
let edits = Edits {
|
||||
annotations: every_annotation(),
|
||||
stamps: vec![Stamp {
|
||||
page: 0,
|
||||
rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 },
|
||||
image: vec![0, 1, 2, 250, 255],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_string(&edits).unwrap();
|
||||
let back: Edits = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.annotations.len(), 9);
|
||||
|
||||
@@ -25,7 +25,10 @@ fn reorder_rotate_delete_and_insert_blank() {
|
||||
assert_eq!(sizes[2], (842.0, 595.0), "page 1 was not turned");
|
||||
// Deleted pages are gone from the file, not just from the page list.
|
||||
for blob in scan_objects(&out) {
|
||||
assert!(!contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"), "a deleted page survived in the file");
|
||||
assert!(
|
||||
!contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"),
|
||||
"a deleted page survived in the file"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,9 +123,12 @@ fn password_on_and_off() {
|
||||
#[test]
|
||||
fn images_to_pdf_and_back() {
|
||||
let mut jpeg = Vec::new();
|
||||
let photo = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(400, 300, |x, y| image::Rgb([x as u8, y as u8, 128])));
|
||||
let photo =
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(400, 300, |x, y| image::Rgb([x as u8, y as u8, 128])));
|
||||
photo.write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
|
||||
let logo = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 200, |x, _| image::Rgba([255, 0, 0, if x < 50 { 255 } else { 0 }])));
|
||||
let logo = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 200, |x, _| {
|
||||
image::Rgba([255, 0, 0, if x < 50 { 255 } else { 0 }])
|
||||
}));
|
||||
let mut png = Vec::new();
|
||||
logo.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let pdf = pictor_pdf::images_to_pdf(&[(jpeg.clone(), photo.clone()), (png, logo)], PageFit::A4, 36.0).unwrap();
|
||||
|
||||
@@ -43,7 +43,10 @@ fn assert_page_two_unchanged(input: &[u8], output: &[u8]) {
|
||||
assert_eq!(font(&a, pa), font(&b, pb), "page 2's fonts changed");
|
||||
// The raw stream bytes too (lopdf writes untouched streams as they were).
|
||||
let raw = |d: &Document, p| -> Vec<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");
|
||||
}
|
||||
@@ -117,7 +120,10 @@ fn the_box_is_black_and_the_rest_of_the_page_still_shows() {
|
||||
let p = img.get_pixel(300, 100);
|
||||
assert!(p.0.iter().all(|&c| c < 16), "box not black: {p:?}");
|
||||
// "PUBLIC-LINE" at PDF (72, 300) → view y ≈ 492: some dark pixels remain in that band.
|
||||
let dark = (480..500).flat_map(|y| (72..160).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100).count();
|
||||
let dark = (480..500)
|
||||
.flat_map(|y| (72..160).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100)
|
||||
.count();
|
||||
assert!(dark > 20, "the text outside the box disappeared ({dark} dark pixels)");
|
||||
}
|
||||
|
||||
@@ -126,8 +132,14 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() {
|
||||
let input = secret_pdf(&Options::default());
|
||||
let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap();
|
||||
assert!(
|
||||
pictor_pdf::redact(engine(), &locked, None, &[Redaction { page: 0, rects: vec![secret_box()] }], &Default::default())
|
||||
.is_err(),
|
||||
pictor_pdf::redact(
|
||||
engine(),
|
||||
&locked,
|
||||
None,
|
||||
&[Redaction { page: 0, rects: vec![secret_box()] }],
|
||||
&Default::default()
|
||||
)
|
||||
.is_err(),
|
||||
"redacted without the password"
|
||||
);
|
||||
let out = pictor_pdf::redact(
|
||||
@@ -144,10 +156,19 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() {
|
||||
#[test]
|
||||
fn no_redaction_box_is_refused() {
|
||||
let input = secret_pdf(&Options::default());
|
||||
assert!(pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()).is_err());
|
||||
assert!(
|
||||
pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 9, rects: vec![secret_box()] }], &Default::default())
|
||||
.is_err(),
|
||||
pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default())
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
pictor_pdf::redact(
|
||||
engine(),
|
||||
&input,
|
||||
None,
|
||||
&[Redaction { page: 9, rects: vec![secret_box()] }],
|
||||
&Default::default()
|
||||
)
|
||||
.is_err(),
|
||||
"a page that does not exist was accepted"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -161,7 +161,10 @@ impl Worker {
|
||||
let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?;
|
||||
if hello["protocol"].as_u64() != Some(PROTOCOL as u64) {
|
||||
let _ = running.child.kill();
|
||||
return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"])));
|
||||
return Err(WorkerError::Spawn(format!(
|
||||
"it speaks protocol {}, Pictor needs {PROTOCOL}",
|
||||
hello["protocol"]
|
||||
)));
|
||||
}
|
||||
self.running = Some(running);
|
||||
Ok(())
|
||||
@@ -220,13 +223,19 @@ impl Worker {
|
||||
}
|
||||
|
||||
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();
|
||||
let stderr =
|
||||
self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default();
|
||||
// Give the stderr thread a moment to collect the last words.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
|
||||
let stderr =
|
||||
self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
|
||||
// pdfium aborts without a word when an allocation fails; the job's peak memory tells that story.
|
||||
#[cfg(windows)]
|
||||
let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9);
|
||||
let hit_cap = self
|
||||
.running
|
||||
.as_ref()
|
||||
.and_then(|r| r._job.peak_bytes())
|
||||
.is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9);
|
||||
#[cfg(not(windows))]
|
||||
let hit_cap = false;
|
||||
self.kill();
|
||||
@@ -258,7 +267,8 @@ mod job {
|
||||
unsafe {
|
||||
let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?;
|
||||
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
info.BasicLimitInformation.LimitFlags =
|
||||
JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20;
|
||||
SetInformationJobObject(
|
||||
h,
|
||||
@@ -276,7 +286,8 @@ mod job {
|
||||
|
||||
pub fn assign(&self, child: &std::process::Child) -> Result<(), String> {
|
||||
unsafe {
|
||||
let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
|
||||
let p =
|
||||
OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
|
||||
let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string());
|
||||
let _ = CloseHandle(p);
|
||||
r
|
||||
|
||||
@@ -31,7 +31,11 @@ fn main() {
|
||||
let req: Value = match serde_json::from_str(line.trim_end()) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let _ = writeln!(out, "{}", json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))}));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))})
|
||||
);
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -238,8 +238,11 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
||||
}
|
||||
let a: A = args(a)?;
|
||||
let engine = state.engine()?;
|
||||
let files: Vec<(Vec<u8>, Option<String>)> =
|
||||
a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::<Result<_, _>>()?;
|
||||
let files: Vec<(Vec<u8>, Option<String>)> = a
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| read_file(&i.path).map(|b| (b, i.password.clone())))
|
||||
.collect::<Result<_, _>>()?;
|
||||
let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect();
|
||||
let bytes = pictor_pdf::merge(engine, &refs)?;
|
||||
write_out(&a.output, &bytes, SaveMode::New)
|
||||
@@ -309,7 +312,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
||||
let bytes = read_file(&a.path)?;
|
||||
let img = pictor_raster::decode(&bytes, &Limits::default())?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let t = pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
|
||||
let t =
|
||||
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
|
||||
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
|
||||
}
|
||||
"image.convert" => {
|
||||
@@ -347,7 +351,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
||||
if let Some(f) = a.resize {
|
||||
img = pictor_raster::resize(&img, f, &limits)?;
|
||||
}
|
||||
let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
|
||||
let format =
|
||||
Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
|
||||
let (bytes, format) = if let Some(target) = a.target_bytes {
|
||||
let c = pictor_raster::compress_to(&img, format, target, &limits)?;
|
||||
(c.bytes, c.format)
|
||||
@@ -391,7 +396,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
||||
let a: A = args(a)?;
|
||||
let bytes = read_file(&a.input)?;
|
||||
let stripped = pictor_meta::strip(&bytes)?;
|
||||
let mut out = write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
|
||||
let mut out =
|
||||
write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
|
||||
out["removed"] = json!(stripped.removed);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -27,9 +27,12 @@ fn base_doc(content: &[u8]) -> Document {
|
||||
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
|
||||
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
|
||||
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
|
||||
doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}));
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
|
||||
doc.objects.insert(
|
||||
pages,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
|
||||
doc.trailer.set("Root", cat);
|
||||
doc
|
||||
@@ -54,10 +57,12 @@ fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
|
||||
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
|
||||
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
|
||||
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
|
||||
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
|
||||
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
|
||||
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
|
||||
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc});
|
||||
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
|
||||
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
|
||||
let font = doc.add_object(
|
||||
dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
|
||||
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc},
|
||||
);
|
||||
let page = *doc.get_pages().values().next().unwrap();
|
||||
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
|
||||
save(doc)
|
||||
@@ -112,7 +117,13 @@ fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
|
||||
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
|
||||
out.push(("parent loop", save(doc)));
|
||||
}
|
||||
out.push(("object that is a reference to itself", replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R").into_iter().chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied()).collect()));
|
||||
out.push((
|
||||
"object that is a reference to itself",
|
||||
replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R")
|
||||
.into_iter()
|
||||
.chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied())
|
||||
.collect(),
|
||||
));
|
||||
out.push(("deeply nested arrays", {
|
||||
let mut deep = vec![b'['; 200_000];
|
||||
deep.extend(vec![b']'; 200_000]);
|
||||
@@ -142,11 +153,23 @@ fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
|
||||
out.push(("content stream that inflates to 1 GiB", save(doc)));
|
||||
}
|
||||
// Malformed fonts.
|
||||
out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect())));
|
||||
out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat())));
|
||||
out.push(("truncated Type 1 font", font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec())));
|
||||
out.push((
|
||||
"TrueType font of garbage",
|
||||
font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()),
|
||||
));
|
||||
out.push((
|
||||
"TrueType claiming 65535 tables",
|
||||
font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()),
|
||||
));
|
||||
out.push((
|
||||
"truncated Type 1 font",
|
||||
font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec()),
|
||||
));
|
||||
// Encryption with a handler that does not exist.
|
||||
out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>")));
|
||||
out.push((
|
||||
"unknown security handler",
|
||||
replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"),
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -210,7 +233,8 @@ fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
|
||||
let mut tally = Tally::default();
|
||||
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
|
||||
all.extend(fetched());
|
||||
let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
|
||||
let annotation =
|
||||
json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
|
||||
for (i, (name, bytes)) in all.iter().enumerate() {
|
||||
let path = dir.path().join(format!("f{i}.pdf"));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
@@ -221,7 +245,11 @@ fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
|
||||
let doc = match &opened {
|
||||
Ok(v) => {
|
||||
tally.ok += 1;
|
||||
println!("{name:40} {:10} {took:>8.2?} ok, {} pages", "open", v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0));
|
||||
println!(
|
||||
"{name:40} {:10} {took:>8.2?} ok, {} pages",
|
||||
"open",
|
||||
v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0)
|
||||
);
|
||||
v["doc"].as_u64()
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -246,7 +274,13 @@ fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
|
||||
continue;
|
||||
}
|
||||
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
|
||||
run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}));
|
||||
run(
|
||||
&mut w,
|
||||
&mut tally,
|
||||
name,
|
||||
"pdf.save",
|
||||
json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}),
|
||||
);
|
||||
}
|
||||
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
|
||||
w.take_restarted();
|
||||
@@ -274,7 +308,10 @@ fn the_client_survives_crash_hang_and_memory_blowup() {
|
||||
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:?}");
|
||||
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());
|
||||
@@ -283,7 +320,11 @@ fn the_client_survives_crash_hang_and_memory_blowup() {
|
||||
#[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}))] {
|
||||
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:?}"),
|
||||
|
||||
@@ -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.
|
||||
|
||||
<!-- deps:begin -->
|
||||
141 crates; 0 outside the allowed set.
|
||||
|
||||
| Crate | Version | Licence | Allowed |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes |
|
||||
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
||||
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
||||
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
||||
| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes |
|
||||
| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes |
|
||||
| block-buffer | 0.12.1 | MIT OR Apache-2.0 | yes |
|
||||
| block-padding | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
||||
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
||||
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
||||
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
||||
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
||||
| bytes | 1.12.1 | MIT | yes |
|
||||
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| cfg_aliases | 0.2.2 | MIT | yes |
|
||||
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
||||
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
||||
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
||||
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
||||
| color_quant | 1.1.0 | MIT | yes |
|
||||
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
||||
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
||||
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
||||
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
||||
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
||||
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
||||
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
||||
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
||||
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
||||
| fax | 0.2.7 | MIT | yes |
|
||||
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
||||
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||
| foldhash | 0.2.0 | Zlib | yes |
|
||||
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||
| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes |
|
||||
| gif | 0.14.2 | MIT OR Apache-2.0 | yes |
|
||||
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
||||
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
||||
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
||||
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
||||
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
||||
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||
| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes |
|
||||
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
||||
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
||||
| libloading | 0.9.1 | ISC | yes |
|
||||
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
||||
| lopdf | 0.47.0 | MIT | yes |
|
||||
| lru | 0.18.5 | MIT | yes |
|
||||
| maybe-owned | 0.3.4 | MIT OR Apache-2.0 | yes |
|
||||
| md-5 | 0.11.0 | MIT OR Apache-2.0 | yes |
|
||||
| memchr | 2.8.3 | Unlicense OR MIT | yes |
|
||||
| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||
| miniz_oxide | 0.9.1 | MIT OR Zlib OR Apache-2.0 | yes |
|
||||
| moxcms | 0.8.1 | BSD-3-Clause OR Apache-2.0 | yes |
|
||||
| multiversion_no_op | 1.0.0 | Apache-2.0 OR MIT | yes |
|
||||
| mutate_once | 0.1.2 | BSD-2-Clause | yes |
|
||||
| nom | 8.0.0 | MIT | yes |
|
||||
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
||||
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
||||
| piston-float | 1.0.1 | MIT | yes |
|
||||
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
||||
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
||||
| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes |
|
||||
| proptest | 1.12.0 | MIT OR Apache-2.0 | yes |
|
||||
| pxfm | 0.1.30 | BSD-3-Clause OR Apache-2.0 | yes |
|
||||
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
||||
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
||||
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
||||
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
||||
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
||||
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
||||
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
||||
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
||||
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
||||
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
||||
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
||||
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
||||
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
||||
| serde | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
||||
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
||||
| simd-adler32 | 0.3.10 | MIT | yes |
|
||||
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
||||
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
||||
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||
| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes |
|
||||
| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||
| tiff | 0.11.3 | MIT | yes |
|
||||
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
||||
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
||||
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
||||
| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| unicode-properties | 0.1.5 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes |
|
||||
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
||||
| vecmath | 1.0.0 | MIT | yes |
|
||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
||||
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-collections | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-core | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-future | 0.3.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-implement | 0.60.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-interface | 0.59.3 | MIT OR Apache-2.0 | yes |
|
||||
| windows-link | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-numerics | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-result | 0.4.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-strings | 0.5.1 | MIT OR Apache-2.0 | yes |
|
||||
| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes |
|
||||
| windows-threading | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||
| winnow | 1.0.5 | MIT | yes |
|
||||
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||
| zlib-rs | 0.6.8 | Zlib | yes |
|
||||
| zmij | 1.0.23 | MIT | yes |
|
||||
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||
<!-- deps:end -->
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Formats and the worker protocol
|
||||
|
||||
What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to
|
||||
`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own
|
||||
section here.
|
||||
|
||||
## Images (crates/raster, crates/meta)
|
||||
|
||||
| Format | Read | Write | Metadata strip |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical |
|
||||
| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical |
|
||||
| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed |
|
||||
| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) |
|
||||
| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused |
|
||||
| BMP | yes | yes | (no metadata) |
|
||||
| ICO | yes | 256/48/32/16 px | — |
|
||||
| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first |
|
||||
| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — |
|
||||
|
||||
Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`):
|
||||
128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding.
|
||||
|
||||
HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video
|
||||
Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing.
|
||||
|
||||
## PDF (crates/pdf)
|
||||
|
||||
Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the
|
||||
page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space.
|
||||
|
||||
| Operation | Library | Why |
|
||||
| :-- | :-- | :-- |
|
||||
| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens |
|
||||
| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) |
|
||||
| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over |
|
||||
| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask |
|
||||
| PDF → PNG/JPG | pdfium | rendering |
|
||||
| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too |
|
||||
| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` |
|
||||
| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation |
|
||||
| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | |
|
||||
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
||||
| password off | lopdf decrypting load + plain save | |
|
||||
| true redaction | pdfium render + lopdf rebuild (below) | |
|
||||
|
||||
### True redaction
|
||||
|
||||
Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted
|
||||
black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept,
|
||||
`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page
|
||||
tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and
|
||||
`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and
|
||||
non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they
|
||||
stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is
|
||||
written fresh (no incremental history). The other pages' objects are written back byte for byte.
|
||||
|
||||
Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only
|
||||
what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form
|
||||
XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests
|
||||
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
||||
and decompressed), and a raw byte grep.
|
||||
|
||||
## The worker protocol (crates/worker), version 1
|
||||
|
||||
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
||||
`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol.
|
||||
|
||||
```
|
||||
→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}}
|
||||
← {"id": 7, "ok": {"png": "<base64>", "width": 1200, "height": 1553}}
|
||||
← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}}
|
||||
```
|
||||
|
||||
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
||||
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
||||
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
||||
|
||||
| Operation | Arguments | Result |
|
||||
| :-- | :-- | :-- |
|
||||
| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) |
|
||||
| `pdf.close` | `doc` | — |
|
||||
| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` |
|
||||
| `pdf.text` | `doc` | `pages`: text per page |
|
||||
| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) |
|
||||
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
||||
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
||||
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
||||
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
||||
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
||||
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
||||
| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` |
|
||||
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
||||
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
||||
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
||||
| `image.heif_support` | — | `support` |
|
||||
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
||||
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
||||
| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` |
|
||||
|
||||
Saving: `mode: new` refuses to replace a file (the app picks `<name>-edited.pdf`); `overwrite` writes
|
||||
`<file>.bak` first, then replaces the file in one rename (`crates/save`).
|
||||
|
||||
Caps: files over 1 GB are refused; the client runs the worker in a Job Object (2 GB by default, killed with the
|
||||
app) and gives each request a time cap; a worker that hangs or dies is replaced on the next request (open documents
|
||||
must then be opened again).
|
||||
Reference in New Issue
Block a user