Files
visa/src/pack/pdf.rs
T
grabowski c0ef994b26
CI / secret scan (push) Successful in 9s
CI / fmt, clippy, tests (push) Successful in 55s
CI / release (push) Skipped
Pack: a PDF whose pages cannot be copied gets a note page
The second fuzz run on cnx01 found a PDF (a page's font dictionary with
a key and a broken value) on which the PDF reader, hayro-syntax 0.7.2
(Dict::entries, an unwrap), panics while the page is copied. The app
lives on (the pack renders in spawn_blocking), but the person's pack
and the card's sides failed with a 500 every time, for as long as the
file was among their documents. piece() now copies an uploaded PDF's
pages once into a throwaway document with panics caught
(pack::pdf::copies); a file that panics prints as a note page like any
unreadable file. Only a panic counts, so a PDF 2.0 file still goes to
render's retry.

tests/fuzz_cases/upload/pdf-dict-key-without-value.pdf is the finding,
replayed on every push (it panicked on stable too).
2026-11-23 10:35:33 +07:00

1106 lines
38 KiB
Rust

//! The pack as one PDF to print: a cover sheet with the contents page by
//! page and what to do before handing it in, then the forms filled in from
//! the records, then every copy in the pack's order. A PDF's pages go in as
//! they are; an image is fitted on an A4 page, turned as the camera's EXIF
//! tag says. A file that cannot be read gets a page that says so, and the
//! pack still prints.
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use krilla::color::rgb;
use krilla::configure::{ConfigurationBuilder, PdfVersion};
use krilla::destination::XyzDestination;
use krilla::error::KrillaError;
use krilla::geom::{PathBuilder, Point, Size, Transform};
use krilla::image::Image;
use krilla::metadata::Metadata;
use krilla::num::NormalizedF32;
use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::paint::{Fill, LineCap, Stroke};
use krilla::pdf::{Pdf, PdfDocument, PdfError};
use krilla::surface::Surface;
use krilla::text::TextDirection;
use krilla::{Document, SerializeSettings};
use super::{Item, PARTS};
use crate::papers::{self, Paper, Pen, Values, width};
/// A file of the pack as the store gave it.
pub struct Loaded {
/// Its name as uploaded.
pub name: String,
pub content_type: String,
/// The document's kind, which decides how large it prints.
pub kind: String,
/// The front this file is the back of (a card's two sides).
pub back_of: Option<i64>,
/// The file, or why it could not be read.
pub bytes: Result<Vec<u8>, String>,
}
/// What the cover sheet says about the application.
pub struct Cover {
/// The PDF's title.
pub title: String,
/// "MUSTERMANN, Erika"
pub person: String,
/// The passport, the employer, the office and the date.
pub lines: Vec<String>,
/// Who put it together, and when.
pub made: String,
}
/// What the person and the employer do before the pack goes in.
const BEFORE: [&str; 5] = [
"Print the pack twice: the office takes two sets.",
"The person signs TM.7, STM.2, STM.9 and STM.11, and signs every copy of the passport as a \
true copy.",
"Every page of the employer's documents carries the company's seal and the signature of the \
director named in the company certificate; the director also signs STM.1.",
"Glue the 4 x 6 cm photo to TM.7.",
"Bring the passport, the work permit, the fee of 1,900 THB, and the originals of the company \
certificate, BOJ.5, the balance sheet with PND.50, PND.1, PND.91 and SPS 1-10.",
];
/// A4 portrait, in points.
const W: f32 = 595.0;
const H: f32 = 842.0;
const MARGIN: f32 = 48.0;
const NAVY: (u8, u8, u8) = (7, 19, 35);
const INK: (u8, u8, u8) = (34, 38, 46);
const GREY: (u8, u8, u8) = (104, 112, 124);
const RED: (u8, u8, u8) = (176, 32, 32);
const AMBER: (u8, u8, u8) = (150, 98, 0);
const GOLD: (u8, u8, u8) = (245, 192, 0);
/// What one document or form puts into the PDF.
enum Piece {
Form(Paper),
/// An uploaded PDF and the size of each of its pages.
Pdf(PdfDocument, Vec<(f32, f32)>),
/// An image as it prints.
Image(Shot),
/// A card's front and back on one page.
Card(Shot, Shot),
/// A page that says what could not be added, and why.
Note(String),
}
impl Piece {
fn pages(&self) -> Result<usize> {
Ok(match self {
Piece::Form(p) => papers::page_count(*p)?,
Piece::Pdf(_, sizes) => sizes.len(),
Piece::Image(_) | Piece::Card(..) | Piece::Note(_) => 1,
})
}
}
/// What goes into the PDF for one document.
fn piece(what: &str, file: Option<Loaded>) -> Piece {
let later = "Open it from the Documents tab and print it from there.";
let Some(file) = file else {
return Piece::Note(format!("{what}: the file was not found. {later}"));
};
let name = file.name;
let bytes = match file.bytes {
Ok(b) => b,
Err(why) => {
return Piece::Note(format!("{what}: {name} could not be read ({why}). {later}"));
}
};
if file.content_type == "application/pdf" {
return match Pdf::new(bytes) {
Ok(pdf) => {
let sizes: Vec<(f32, f32)> =
pdf.pages().iter().map(|p| p.render_dimensions()).collect();
let doc = PdfDocument::new(Arc::new(pdf));
if sizes.is_empty() {
Piece::Note(format!("{what}: {name} has no pages."))
} else if !copies(&doc, &sizes) {
Piece::Note(format!(
"{what}: {name} is a PDF the app cannot copy pages from. {later}"
))
} else {
Piece::Pdf(doc, sizes)
}
}
Err(e) => Piece::Note(format!(
"{what}: {name} is a PDF the app cannot read ({e:?}). {later}"
)),
};
}
match shot(&file.content_type, &file.kind, bytes) {
Ok(s) => Piece::Image(s),
Err(e) => Piece::Note(format!(
"{what}: {name} is an image the app cannot read ({e}). {later}"
)),
}
}
/// Whether the pages of an uploaded PDF can be copied: tried once into a
/// throwaway document. The PDF reader panics on some broken files (the
/// nightly fuzzing found a font dictionary with a key and no value), which
/// would fail the whole pack, every time, for as long as the file is there;
/// such a file gets a note page instead. Only a panic counts: an error from
/// `finish` (a PDF 2.0 file in a 1.7 document) is for `render` to handle.
fn copies(pdf: &PdfDocument, sizes: &[(f32, f32)]) -> bool {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut doc = Document::new();
for (k, &(w, h)) in sizes.iter().enumerate() {
pdf_page(&mut doc, pdf, k, w, h);
}
let _ = doc.finish();
}))
.is_ok()
}
/// An image to print: the picture, how to turn it upright, its pixels'
/// size on paper and the box its kind prints in.
struct Shot {
image: Image,
orientation: u16,
/// Points per pixel at the image's own resolution: the largest it
/// prints, so a small picture is never blown up to the page.
natural: f32,
/// The longest and the shortest side it may take, in points; None for
/// a whole page.
fits: Option<(f32, f32)>,
}
fn shot(content_type: &str, kind: &str, bytes: Vec<u8>) -> Result<Shot, String> {
let orientation = if content_type == "image/jpeg" {
exif_orientation(&bytes)
} else {
1
};
let dpi = density(content_type, &bytes)
.filter(|d| *d >= 100.0)
.unwrap_or(DEFAULT_DPI);
let image = papers::picture(content_type, bytes)?;
let (w, h) = image.size();
Ok(Shot {
fits: print_box(kind, w as f32, h as f32),
image,
orientation,
natural: 72.0 / dpi,
})
}
/// The resolution assumed for a picture that does not say its own (or
/// says less than 100 dpi, as phones do): fine enough to read, so a
/// picture never prints coarser than this.
const DEFAULT_DPI: f32 = 150.0;
const MM: f32 = 72.0 / 25.4;
/// How large a copy of `kind` prints, as its longest and shortest side in
/// points: the passport's pages near their own size, a card a little
/// larger than itself, a phone's screenshot (much taller than wide, a TDAC
/// for one) as a phone shows it. None: a document of its own, which takes
/// the page.
fn print_box(kind: &str, w: f32, h: f32) -> Option<(f32, f32)> {
let (long, short) = (w.max(h), w.min(h).max(1.0));
let mm = |a: f32, b: f32| Some((a * MM, b * MM));
if kind == "tdac" || long / short >= 1.8 {
return mm(150.0, 75.0);
}
match kind {
"passport-photo-page" | "visa" | "arrival-stamp" | "extension-stamp" | "reentry-permit" => {
mm(180.0, 128.0)
}
"id-card" | "work-permit" => mm(130.0, 90.0),
"photo" => mm(60.0, 40.0),
_ => None,
}
}
/// The resolution a JPEG (JFIF) or PNG (pHYs) gives, in dots per inch.
fn density(content_type: &str, b: &[u8]) -> Option<f32> {
let be16 = |i: usize| -> Option<f32> {
Some(u16::from_be_bytes(b.get(i..i + 2)?.try_into().ok()?) as f32)
};
match content_type {
"image/jpeg" => {
// APP0 right after the start: "JFIF\0", version, units, x, y
if b.get(2..4)? != [0xFF, 0xE0] || b.get(6..11)? != b"JFIF\0" {
return None;
}
let x = be16(14)?;
match b.get(13)? {
1 => Some(x),
2 => Some(x * 2.54),
_ => None,
}
}
"image/png" => {
let i = b.windows(4).position(|w| w == b"pHYs")?;
let x = u32::from_be_bytes(b.get(i + 4..i + 8)?.try_into().ok()?) as f32;
// unit 1: per metre
(*b.get(i + 12)? == 1).then_some(x * 0.0254)
}
_ => None,
}
}
/// The pages of each item that prints: the item's index in `items`, its
/// first and last page (counted from 1).
type Spans = Vec<(usize, usize, usize)>;
/// The pack as one PDF: the cover sheet, then the items that print. `files`
/// holds the documents' files by id.
pub fn render(
cover: &Cover,
items: &[Item],
v: &Values,
mut files: HashMap<i64, Loaded>,
) -> Result<Vec<u8>> {
let pen = Pen::sarabun()?;
let mut plan: Vec<(usize, Vec<Piece>)> = Vec::new();
for (i, item) in items.iter().enumerate() {
let mut pieces: Vec<Piece> = item.paper.into_iter().map(Piece::Form).collect();
let mut ids = item.docs.iter().peekable();
while let Some(id) = ids.next() {
let file = files.remove(id);
// a card's back right after its front: both on one page
let back = ids
.peek()
.and_then(|b| files.get(b).filter(|f| f.back_of == Some(*id)).map(|_| **b));
match (file, back) {
(Some(front), Some(b)) => {
ids.next();
let back = files.remove(&b);
pieces.extend(card(&item.what, front, back));
}
(file, _) => pieces.push(piece(&item.what, file)),
}
}
if !pieces.is_empty() {
plan.push((i, pieces));
}
}
// the cover's own length decides where the rest begins
let counts: Vec<usize> = plan
.iter()
.map(|(_, pieces)| pieces.iter().map(Piece::pages).sum::<Result<usize>>())
.collect::<Result<_>>()?;
let spans_after = |cover_pages: usize| -> Spans {
let mut next = cover_pages + 1;
plan.iter()
.zip(&counts)
.map(|((i, _), n)| {
let span = (*i, next, next + n - 1);
next += n;
span
})
.collect()
};
let guess = cover_sheet(&pen, cover, items, &spans_after(1)).len();
let spans = spans_after(guess);
let sheet = cover_sheet(&pen, cover, items, &spans);
let built = match build(
&pen,
cover,
items,
v,
&plan,
&spans,
&sheet,
PdfVersion::Pdf17,
)? {
// an uploaded PDF of version 2.0 needs a pack of 2.0
Err(KrillaError::Pdf(_, PdfError::VersionMismatch(_), _)) => build(
&pen,
cover,
items,
v,
&plan,
&spans,
&sheet,
PdfVersion::Pdf20,
)?,
other => other,
};
built.map_err(|e| anyhow!("writing the pack: {e:?}"))
}
#[allow(clippy::too_many_arguments)]
fn build(
pen: &Pen<'_>,
cover: &Cover,
items: &[Item],
v: &Values,
plan: &[(usize, Vec<Piece>)],
spans: &Spans,
sheet: &[Vec<Draw>],
version: PdfVersion,
) -> Result<Result<Vec<u8>, KrillaError>> {
let configuration = ConfigurationBuilder::new()
.with_version(version)
.finish()
.map_err(|e| anyhow!("the PDF's version: {e:?}"))?;
let mut doc = Document::new_with(SerializeSettings {
configuration,
..Default::default()
});
doc.set_metadata(
Metadata::new()
.title(cover.title.clone())
.creator("Lanna Desk (lannadesk.com)".to_string()),
);
let top = |page: usize| XyzDestination::new(page, Point::from_xy(0.0, 0.0));
let mut outline = Outline::new();
outline.push_child(OutlineNode::new("Contents".to_string(), top(0)));
for draws in sheet {
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
for d in draws {
d.draw(&mut s, pen);
}
s.finish();
page.finish();
}
for ((i, pieces), (_, first, _)) in plan.iter().zip(spans) {
outline.push_child(OutlineNode::new(heading(&items[*i]), top(first - 1)));
for piece in pieces {
match piece {
Piece::Form(p) => papers::add_form(&mut doc, pen, *p, v)?,
Piece::Pdf(pdf, sizes) => {
for (k, &(w, h)) in sizes.iter().enumerate() {
pdf_page(&mut doc, pdf, k, w, h);
}
}
Piece::Image(shot) => image_page(&mut doc, shot),
Piece::Card(front, back) => card_page(&mut doc, front, back),
Piece::Note(text) => note_page(&mut doc, pen, text),
}
}
}
doc.set_outline(outline);
Ok(doc.finish())
}
fn a4(landscape: bool) -> PageSettings {
let (w, h) = if landscape { (H, W) } else { (W, H) };
PageSettings::from_wh(w, h).expect("A4 is a valid page size")
}
/// "TM.7 Application for extension of temporary stay", or what a copy is.
fn heading(item: &Item) -> String {
if item.code.is_empty() {
item.what.clone()
} else {
format!("{} {}", item.code, item.what)
}
}
/// Something drawn on the cover sheet.
enum Draw {
Text {
x: f32,
y: f32,
size: f32,
color: (u8, u8, u8),
text: String,
},
Rule {
y: f32,
},
}
impl Draw {
fn draw(&self, s: &mut Surface<'_>, pen: &Pen<'_>) {
match self {
Draw::Text {
x,
y,
size,
color,
text,
} => {
s.set_fill(Some(fill(*color)));
s.draw_text(
Point::from_xy(*x, *y),
pen.font.clone(),
*size,
text,
false,
TextDirection::Auto,
);
}
Draw::Rule { y } => {
let mut pb = PathBuilder::new();
pb.move_to(MARGIN, *y);
pb.line_to(W - MARGIN, *y);
if let Some(path) = pb.finish() {
s.set_fill(None);
s.set_stroke(Some(Stroke {
paint: color(GOLD).into(),
width: 1.6,
line_cap: LineCap::Butt,
opacity: NormalizedF32::ONE,
..Default::default()
}));
s.draw_path(&path);
s.set_stroke(None);
}
}
}
}
}
fn color((r, g, b): (u8, u8, u8)) -> rgb::Color {
rgb::Color::new(r, g, b)
}
fn fill(c: (u8, u8, u8)) -> Fill {
Fill {
paint: color(c).into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}
}
/// `text` at a size that fits `room`, at least 7.5 points, cut short with
/// an ellipsis if even that is too wide.
fn clip(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> (String, f32) {
let w = width(&pen.face, text, size);
if w <= room {
return (text.to_string(), size);
}
let smaller = (size * room / w).max(7.5);
if width(&pen.face, text, smaller) <= room {
return (text.to_string(), smaller);
}
let mut cut: String = text.to_string();
while !cut.is_empty() && width(&pen.face, &format!("{cut}…"), smaller) > room {
cut.pop();
}
(format!("{}…", cut.trim_end()), smaller)
}
/// `text` broken into lines that fit `room`.
fn wrap(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> Vec<String> {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
let tried = if line.is_empty() {
word.to_string()
} else {
format!("{line} {word}")
};
if width(&pen.face, &tried, size) > room && !line.is_empty() {
lines.push(std::mem::take(&mut line));
line = word.to_string();
} else {
line = tried;
}
}
if !line.is_empty() {
lines.push(line);
}
lines
}
/// The cover sheet, page by page: the application, the contents with their
/// pages, what is still missing, and what to do before handing it in.
fn cover_sheet(pen: &Pen<'_>, cover: &Cover, items: &[Item], spans: &Spans) -> Vec<Vec<Draw>> {
/// Moves down by `step` (to a new page at the bottom) and draws there.
fn put(pages: &mut Vec<Vec<Draw>>, y: &mut f32, step: f32, d: Draw) {
*y += step;
if *y > H - 56.0 {
pages.push(Vec::new());
*y = 72.0;
}
let d = match d {
Draw::Text {
x,
size,
color,
text,
..
} => Draw::Text {
x,
y: *y,
size,
color,
text,
},
Draw::Rule { .. } => Draw::Rule { y: *y },
};
if let Some(p) = pages.last_mut() {
p.push(d);
}
}
fn text(x: f32, size: f32, color: (u8, u8, u8), text: String) -> Draw {
Draw::Text {
x,
y: 0.0,
size,
color,
text,
}
}
let mut pages: Vec<Vec<Draw>> = vec![Vec::new()];
let mut y = 72.0;
let right = W - MARGIN;
put(
&mut pages,
&mut y,
0.0,
text(
MARGIN,
17.0,
NAVY,
"Extension of stay for work (Non-B)".into(),
),
);
put(
&mut pages,
&mut y,
24.0,
text(MARGIN, 13.0, INK, cover.person.clone()),
);
for line in &cover.lines {
put(
&mut pages,
&mut y,
16.0,
text(MARGIN, 10.0, GREY, line.clone()),
);
}
put(&mut pages, &mut y, 14.0, Draw::Rule { y: 0.0 });
put(
&mut pages,
&mut y,
26.0,
text(MARGIN, 12.0, NAVY, "Contents".into()),
);
let mut part = 0;
for (i, item) in items.iter().enumerate() {
if item.level == "info" {
continue;
}
if item.part != part {
part = item.part;
let title = format!("{part} {}", PARTS[part - 1]);
put(&mut pages, &mut y, 19.0, text(MARGIN, 10.5, NAVY, title));
}
let pages_of = spans.iter().find(|(k, ..)| *k == i);
let (place, color) = match pages_of {
Some((_, a, b)) if a == b => (format!("page {a}"), INK),
Some((_, a, b)) => (format!("pages {a}-{b}"), INK),
None if item.bring && item.level == "ok" => ("bring it".to_string(), INK),
None => (item.label.to_lowercase(), RED),
};
// the state of an item that prints but needs a look
let state = match (pages_of.is_some(), item.level) {
(true, "warn") => Some((item.label.to_string(), AMBER)),
(true, "bad") => Some((item.label.to_string(), RED)),
_ => None,
};
let x = MARGIN + 20.0;
let room = right - 128.0 - x;
let (title, size) = clip(pen, &heading(item), 9.5, room);
put(&mut pages, &mut y, 14.5, text(x, size, INK, title));
let pw = width(&pen.face, &place, 9.5);
put(&mut pages, &mut y, 0.0, text(right - pw, 9.5, color, place));
if let Some((label, c)) = state {
put(&mut pages, &mut y, 0.0, text(right - 122.0, 8.5, c, label));
}
}
put(
&mut pages,
&mut y,
30.0,
text(MARGIN, 12.0, NAVY, "Before handing it in".into()),
);
let room = W - 2.0 * MARGIN - 14.0;
for point in BEFORE {
let mut first = true;
for line in wrap(pen, point, 9.5, room) {
let step = if first { 17.0 } else { 12.5 };
if first {
put(
&mut pages,
&mut y,
step,
text(MARGIN, 9.5, GOLD_DARK, "•".into()),
);
put(&mut pages, &mut y, 0.0, text(MARGIN + 14.0, 9.5, INK, line));
} else {
put(
&mut pages,
&mut y,
step,
text(MARGIN + 14.0, 9.5, INK, line),
);
}
first = false;
}
}
// the footer sits at the bottom of the last page
if y > H - 48.0 {
pages.push(Vec::new());
}
if let Some(last) = pages.last_mut() {
last.push(Draw::Text {
x: MARGIN,
y: H - 30.0,
size: 8.0,
color: GREY,
text: cover.made.clone(),
});
}
pages
}
/// The bullets' color: the app's gold, darker for paper.
const GOLD_DARK: (u8, u8, u8) = (196, 150, 0);
/// Every page of the pack is A4 upright, so it prints in one stack.
/// `turn`: the content lies wider than tall and is turned a quarter to the
/// right to take the page.
struct Placed {
/// The content's size once upright (and turned), in its own units.
w: f32,
h: f32,
turn: bool,
}
/// Where a page of an uploaded PDF goes: on A4 upright, turned when it is
/// wider than tall, at its own size and only made smaller when it does not
/// fit (a scan of a passport stays the size of the passport).
fn pdf_page(doc: &mut Document, pdf: &PdfDocument, k: usize, w: f32, h: f32) {
let Some(size) = Size::from_wh(w, h) else {
return;
};
let turn = w > h;
let (dw, dh) = if turn { (h, w) } else { (w, h) };
let scale = (W / dw).min(H / dh).min(1.0);
let (x0, y0) = ((W - dw * scale) / 2.0, (H - dh * scale) / 2.0);
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
s.push_transform(&Transform::from_row(scale, 0.0, 0.0, scale, x0, y0));
if turn {
let [sx, ky, kx, sy, tx, ty] = upright(6, w, h);
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
}
s.draw_pdf_page(pdf, size, k);
if turn {
s.pop();
}
s.pop();
s.finish();
page.finish();
}
/// A picture's size on paper, upright: within its kind's box (turned to
/// lie as the picture lies), within the page, never larger than its own
/// resolution allows. A whole-page document that lies wider than tall, and
/// would have to shrink to fit across, is turned to take the upright page.
fn placed(shot: &Shot, room: (f32, f32)) -> (Placed, f32) {
let (pw, ph) = shot.image.size();
let (w, h) = (pw.max(1) as f32, ph.max(1) as f32);
let (uw, uh) = if shot.orientation >= 5 {
(h, w)
} else {
(w, h)
};
// turned only when lying it would have to print smaller than it is
let flat = (room.0 / uw).min(room.1 / uh);
let turn = shot.fits.is_none() && uw > uh && flat < shot.natural;
let (dw, dh) = if turn { (uh, uw) } else { (uw, uh) };
let mut scale = (room.0 / dw).min(room.1 / dh).min(shot.natural);
if let Some((long, short)) = shot.fits {
let (bw, bh) = if dw >= dh {
(long, short)
} else {
(short, long)
};
scale = scale.min(bw / dw).min(bh / dh);
}
(Placed { w: dw, h: dh, turn }, scale)
}
/// Draws the picture with its top left corner at (x, y).
fn draw_shot(s: &mut Surface<'_>, shot: &Shot, p: &Placed, scale: f32, x: f32, y: f32) {
let (pw, ph) = shot.image.size();
let (w, h) = (pw.max(1) as f32, ph.max(1) as f32);
let Some(size) = Size::from_wh(w, h) else {
return;
};
s.push_transform(&Transform::from_row(scale, 0.0, 0.0, scale, x, y));
if p.turn {
// the upright picture is (uw, uh) = (p.h, p.w): a quarter to the right
let [sx, ky, kx, sy, tx, ty] = upright(6, p.h, p.w);
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
}
let [sx, ky, kx, sy, tx, ty] = upright(shot.orientation, w, h);
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
s.draw_image(shot.image.clone(), size);
s.pop();
if p.turn {
s.pop();
}
s.pop();
}
/// A picture on an A4 page: a whole document centered on the page, a copy
/// of something smaller (a passport page, a card, a screenshot) at the top
/// at its size, so it is not blown up.
fn image_page(doc: &mut Document, shot: &Shot) {
let room = (W - 2.0 * MARGIN, H - 2.0 * MARGIN);
let (p, scale) = placed(shot, room);
let (dw, dh) = (p.w * scale, p.h * scale);
let x = (W - dw) / 2.0;
let y = if shot.fits.is_some() {
MARGIN
} else {
(H - dh) / 2.0
};
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
draw_shot(&mut s, shot, &p, scale, x, y);
s.finish();
page.finish();
}
/// A card's front above its back on one A4 page.
fn card_page(doc: &mut Document, front: &Shot, back: &Shot) {
let gap = 14.0 * MM;
let room = (W - 2.0 * MARGIN, (H - 2.0 * MARGIN - gap) / 2.0);
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
let mut y = MARGIN;
for shot in [front, back] {
let (p, scale) = placed(shot, room);
let (dw, dh) = (p.w * scale, p.h * scale);
draw_shot(&mut s, shot, &p, scale, (W - dw) / 2.0, y);
y += dh + gap;
}
s.finish();
page.finish();
}
/// A card's two sides: one page when both are pictures, else each as it
/// is.
fn card(what: &str, front: Loaded, back: Option<Loaded>) -> Vec<Piece> {
let images = |f: &Loaded| f.content_type.starts_with("image/") && f.bytes.is_ok();
match back {
Some(back) if images(&front) && images(&back) => {
let kind = front.kind.clone();
let (fname, bname) = (front.name.clone(), back.name.clone());
let fs = shot(&front.content_type, &kind, front.bytes.unwrap_or_default());
let bs = shot(&back.content_type, &kind, back.bytes.unwrap_or_default());
match (fs, bs) {
(Ok(f), Ok(b)) => vec![Piece::Card(f, b)],
(Err(e), _) => vec![Piece::Note(format!(
"{what}: {fname} is an image the app cannot read ({e})."
))],
(_, Err(e)) => vec![Piece::Note(format!(
"{what}: {bname} is an image the app cannot read ({e})."
))],
}
}
back => vec![piece(what, Some(front)), piece(what, back)],
}
}
/// A card's front and back on one A4 page, for the Documents tab.
pub fn sides(front: Loaded, back: Loaded) -> Result<Vec<u8>> {
let pieces = card("The card", front, Some(back));
let mut doc = Document::new();
let pen = Pen::sarabun()?;
for p in &pieces {
match p {
Piece::Card(f, b) => card_page(&mut doc, f, b),
Piece::Image(s) => image_page(&mut doc, s),
Piece::Pdf(pdf, sizes) => {
for (k, &(w, h)) in sizes.iter().enumerate() {
pdf_page(&mut doc, pdf, k, w, h);
}
}
Piece::Note(t) => note_page(&mut doc, &pen, t),
Piece::Form(_) => {}
}
}
doc.finish().map_err(|e| anyhow!("writing the card: {e:?}"))
}
/// The matrix `[sx, ky, kx, sy, tx, ty]` (x' = sx x + kx y + tx,
/// y' = ky x + sy y + ty) that shows an image of `w` x `h` pixels upright,
/// for its EXIF orientation (1 to 8), in a box of the turned size.
fn upright(orientation: u16, w: f32, h: f32) -> [f32; 6] {
match orientation {
2 => [-1.0, 0.0, 0.0, 1.0, w, 0.0],
3 => [-1.0, 0.0, 0.0, -1.0, w, h],
4 => [1.0, 0.0, 0.0, -1.0, 0.0, h],
5 => [0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
6 => [0.0, 1.0, -1.0, 0.0, h, 0.0],
7 => [0.0, -1.0, -1.0, 0.0, h, w],
8 => [0.0, -1.0, 1.0, 0.0, 0.0, w],
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
}
}
/// A page in place of a file that could not be added.
fn note_page(doc: &mut Document, pen: &Pen<'_>, note: &str) {
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
let mut draws = vec![Draw::Text {
x: MARGIN,
y: 96.0,
size: 15.0,
color: RED,
text: "This file could not be added".into(),
}];
let mut y = 128.0;
for line in wrap(pen, note, 11.0, W - 2.0 * MARGIN) {
draws.push(Draw::Text {
x: MARGIN,
y,
size: 11.0,
color: INK,
text: line,
});
y += 16.0;
}
for d in &draws {
d.draw(&mut s, pen);
}
s.finish();
page.finish();
}
/// The orientation (1 to 8) that the EXIF block of a JPEG gives; 1 when it
/// has none. Phones store a photo as the sensor saw it and say in this tag
/// how to turn it; browsers follow it, and so does the pack.
pub fn exif_orientation(jpeg: &[u8]) -> u16 {
fn at16(b: &[u8], i: usize, le: bool) -> Option<u16> {
let x: [u8; 2] = b.get(i..i + 2)?.try_into().ok()?;
Some(if le {
u16::from_le_bytes(x)
} else {
u16::from_be_bytes(x)
})
}
fn at32(b: &[u8], i: usize, le: bool) -> Option<u32> {
let x: [u8; 4] = b.get(i..i + 4)?.try_into().ok()?;
Some(if le {
u32::from_le_bytes(x)
} else {
u32::from_be_bytes(x)
})
}
/// The tag 0x0112 in the first image directory of a TIFF block.
fn in_tiff(t: &[u8]) -> Option<u16> {
let le = match t.get(0..2)? {
b"II" => true,
b"MM" => false,
_ => return None,
};
if at16(t, 2, le)? != 42 {
return None;
}
let dir = at32(t, 4, le)? as usize;
let n = at16(t, dir, le)? as usize;
(0..n)
.map(|k| dir + 2 + k * 12)
.find(|&e| at16(t, e, le) == Some(0x0112))
.and_then(|e| at16(t, e + 8, le))
.filter(|v| (1..=8).contains(v))
}
fn find(jpeg: &[u8]) -> Option<u16> {
if !jpeg.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut i = 2;
loop {
if *jpeg.get(i)? != 0xFF {
return None;
}
let marker = *jpeg.get(i + 1)?;
match marker {
// fill bytes
0xFF => i += 1,
// markers without a length
0x01 | 0xD0..=0xD8 => i += 2,
// the image data begins: no EXIF before it
0xD9 | 0xDA => return None,
_ => {
let len = at16(jpeg, i + 2, false)? as usize;
let body = jpeg.get(i + 4..i + 2 + len)?;
if marker == 0xE1
&& let Some(tiff) = body.strip_prefix(b"Exif\0\0")
{
return in_tiff(tiff);
}
i += 2 + len;
}
}
}
}
find(jpeg).unwrap_or(1)
}
#[cfg(test)]
mod tests {
use super::*;
/// A JPEG's head with an EXIF block that says `orientation`.
fn jpeg_with(orientation: u16, le: bool) -> Vec<u8> {
let mut tiff: Vec<u8> = Vec::new();
let p16 =
|v: u16, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
let p32 =
|v: u32, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
tiff.extend(if le { b"II" } else { b"MM" });
p16(42, &mut tiff);
p32(8, &mut tiff);
p16(2, &mut tiff);
// another tag first, then the orientation (type SHORT, count 1)
for (tag, value) in [(0x010F_u16, 0_u16), (0x0112, orientation)] {
p16(tag, &mut tiff);
p16(3, &mut tiff);
p32(1, &mut tiff);
p16(value, &mut tiff);
p16(0, &mut tiff);
}
let mut app1 = b"Exif\0\0".to_vec();
app1.extend(tiff);
let mut out = vec![0xFF, 0xD8];
// a JFIF block before it
out.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]);
out.extend([0xFF, 0xE1]);
out.extend(((app1.len() + 2) as u16).to_be_bytes());
out.extend(app1);
out.extend([0xFF, 0xDA, 0x00, 0x02]);
out
}
#[test]
fn the_exif_orientation_is_read_in_either_byte_order() {
assert_eq!(exif_orientation(&jpeg_with(6, true)), 6);
assert_eq!(exif_orientation(&jpeg_with(8, false)), 8);
assert_eq!(
exif_orientation(&jpeg_with(9, false)),
1,
"not an orientation"
);
assert_eq!(exif_orientation(&[0xFF, 0xD8, 0xFF, 0xDA]), 1);
let cut = jpeg_with(6, true);
assert_eq!(exif_orientation(&cut[..cut.len() / 2]), 1);
assert_eq!(exif_orientation(b"not a jpeg"), 1);
}
/// Where the matrix of `upright` puts a point.
fn map(m: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
let [sx, ky, kx, sy, tx, ty] = m;
(sx * x + kx * y + tx, ky * x + sy * y + ty)
}
#[test]
fn turning_maps_the_corners_onto_the_turned_box() {
let (w, h) = (40.0_f32, 30.0_f32);
for o in 1..=8u16 {
let m = upright(o, w, h);
let (bw, bh) = if o >= 5 { (h, w) } else { (w, h) };
let mut corners: Vec<(f32, f32)> = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]
.into_iter()
.map(|p| map(m, p))
.collect();
corners.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(
corners,
[(0.0, 0.0), (0.0, bh), (bw, 0.0), (bw, bh)],
"orientation {o}"
);
}
// 6, turned a quarter clockwise: the image's top left corner goes
// to the top right, its top row becomes the right edge
assert_eq!(map(upright(6, w, h), (0.0, 0.0)), (h, 0.0));
assert_eq!(map(upright(6, w, h), (w, 0.0)), (h, w));
// 8, a quarter the other way: the top row becomes the left edge
assert_eq!(map(upright(8, w, h), (0.0, 0.0)), (0.0, w));
assert_eq!(map(upright(1, w, h), (w, h)), (w, h));
}
#[test]
fn long_titles_shrink_or_are_cut_and_notes_wrap() {
let pen = Pen::sarabun().unwrap();
let (t, size) = clip(&pen, "Short", 9.5, 200.0);
assert_eq!((t.as_str(), size), ("Short", 9.5));
let long = "List of shareholders (BOJ.5), certified within six months, ".repeat(3);
let (t, size) = clip(&pen, &long, 9.5, 200.0);
assert!(t.ends_with('…') && size == 7.5, "{t} {size}");
assert!(width(&pen.face, &t, size) <= 200.0);
let lines = wrap(&pen, BEFORE[4], 9.5, 300.0);
assert!(lines.len() > 1);
assert_eq!(
lines.join(" "),
BEFORE[4].split_whitespace().collect::<Vec<_>>().join(" ")
);
assert!(lines.iter().all(|l| width(&pen.face, l, 9.5) <= 300.0));
}
/// A shot of `w` x `h` pixels of `kind` at `dpi`, without its picture.
fn sized(kind: &str, w: u32, h: u32, dpi: f32) -> (Placed, f32) {
let png = crate::seed::plain_png(w as usize, h as usize);
let s = shot("image/png", kind, png).unwrap();
let s = Shot {
natural: 72.0 / dpi,
..s
};
placed(&s, (W - 2.0 * MARGIN, H - 2.0 * MARGIN))
}
#[test]
fn copies_print_at_their_size_and_documents_take_the_page_upright() {
// a phone's screenshot (a TDAC): phone sized, never the whole page
let (p, s) = sized("tdac", 1170, 2532, DEFAULT_DPI);
assert!(!p.turn);
assert!((p.h * s - 150.0 * MM).abs() < 0.5, "{}", p.h * s / MM);
let (p, s) = sized("other", 1170, 2532, DEFAULT_DPI);
assert!(p.w * s <= 75.0 * MM + 0.5, "screenshots of any kind");
// a small picture is not blown up: 300 pixels at 150 dpi are 2 in
let (p, s) = sized("tm30-receipt", 300, 420, DEFAULT_DPI);
assert!((p.w * s - 144.0).abs() < 0.5, "{}", p.w * s);
// a large photo of a receipt fills the page, and lying it is turned
let (p, s) = sized("tm30-receipt", 4000, 3000, DEFAULT_DPI);
assert!(p.turn && p.w < p.h);
assert!((p.w * s - (W - 2.0 * MARGIN)).abs() < 0.5);
// a small one lying fits as it is and is not turned
let (p, _) = sized("tm30-receipt", 480, 320, DEFAULT_DPI);
assert!(!p.turn && p.w > p.h);
// a passport page lies as it is, near its own size
let (p, s) = sized("passport-photo-page", 4000, 2800, DEFAULT_DPI);
assert!(!p.turn && p.w > p.h);
assert!(p.w * s <= 180.0 * MM + 0.5 && p.h * s <= 128.0 * MM + 0.5);
// a scan that says 300 dpi prints at its true size: a card 85.6 mm
let (p, s) = sized("id-card", 1011, 638, 300.0);
assert!((p.w * s / MM - 85.6).abs() < 0.3, "{}", p.w * s / MM);
}
#[test]
fn the_resolution_is_read_from_jfif_and_png() {
let mut jfif = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
jfif.extend(b"JFIF\0");
jfif.extend([1, 1, 1, 0x01, 0x2C, 0x01, 0x2C, 0, 0]);
assert_eq!(density("image/jpeg", &jfif), Some(300.0));
jfif[13] = 0;
assert_eq!(density("image/jpeg", &jfif), None, "an aspect ratio only");
let mut png = b"\x89PNG....pHYs".to_vec();
png.extend(11811u32.to_be_bytes());
png.extend(11811u32.to_be_bytes());
png.push(1);
let dpi = density("image/png", &png).unwrap();
assert!((dpi - 300.0).abs() < 0.1, "{dpi}");
assert_eq!(density("image/webp", b"RIFF"), None);
}
}