[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
+5 -12
View File
@@ -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
View File
@@ -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);
+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");
// 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();
+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");
// 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"
);
}