Phase 6: the Non-B extension pack, checked and printed as one PDF
The pack for an extension of stay based on work, item by item in the
officer's order, each with its state at the date of the application:
generated, has blanks, uploaded, missing, out of date, no date, or not
needed for this person.
- src/pack/mod.rs: the rules as a pure function of the records and the
documents, a unit test per rule. Copies belong to their record (the
current passport, the last arrival and its TDAC, the re-entry permit it
came back on, every extension since the passport was issued, the last
90-day report, the current address, the work permit); the company
certificate and BOJ.5 count six months from their certification, the
balance sheet 17 months from its year's end, PND.1, SPS 1-10 and PP.30
the last three months, PND.91 the latest year; two photos of the office.
Sources in docs/PLAN.md (thailand.go.th 006_008, Immigration Division 1).
- A Pack tab: the six parts, each item's files and form, and what fixes it
(the upload with the kind and record chosen, through the new ?kind= on
the Documents tab and on a company's page; a document's date; a record).
The application's fields are the Forms tab's, and both tabs carry them.
- /people/{id}/pack.pdf (src/pack/pdf.rs): a cover sheet with the contents
page by page and what to sign and bring, the five forms, then every copy:
uploaded PDFs as they are (a PDF 2.0 upload makes the pack 2.0), images
fitted on A4 and turned as their EXIF orientation says, a page in place of
a file that cannot be read; bookmarks per item. krilla gains its
raster-images feature. The audit logs the forms' codes and a view or
download of each document that went in.
- A company's page shows its part of every employee's pack.
- The extension deadline links to the pack; at 390 px the six tabs fit, as
"Visa and stay" reads "Stay" on phones.
- Demo data shows every state.
- The Forms tab showed "Back about" and "Purpose" empty: the template read
app.back and app.purpose, which serialize as "return" and "for".
docs/PLAN.md: phase 6 done, open question 2 settled (the office is the
application's), phase 7 planned from Alex's answers: the client link, the
MRZ from a phone photo, later the signed agreement; reminders move to 8.
Checks: cargo fmt, clippy -D warnings, 97 unit and 47 integration tests;
layout_check 0 problems (pack, company, forms, dashboard, person; light,
dark, desk, phone); the tabs measured at 390 and 360 px; the pack PDF
rendered and looked at, an EXIF-turned JPEG upright.
This commit is contained in:
1 parent
990d5c88a4
commit
fc8c1b6a44
26 files changed
+3367
-59
No files matched your search
+796
@@ -0,0 +1,796 @@
|
||||
//! 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::{Data, 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 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 and its EXIF orientation.
|
||||
Image(Image, u16),
|
||||
/// 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::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();
|
||||
if sizes.is_empty() {
|
||||
Piece::Note(format!("{what}: {name} has no pages."))
|
||||
} else {
|
||||
Piece::Pdf(PdfDocument::new(Arc::new(pdf)), sizes)
|
||||
}
|
||||
}
|
||||
Err(e) => Piece::Note(format!(
|
||||
"{what}: {name} is a PDF the app cannot read ({e:?}). {later}"
|
||||
)),
|
||||
};
|
||||
}
|
||||
let orientation = if file.content_type == "image/jpeg" {
|
||||
exif_orientation(&bytes)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let data: Data = bytes.into();
|
||||
let image = match file.content_type.as_str() {
|
||||
"image/jpeg" => Image::from_jpeg(data, true),
|
||||
"image/png" => Image::from_png(data, true),
|
||||
"image/webp" => Image::from_webp(data, true),
|
||||
other => Err(format!("{other} is not an image type the app takes")),
|
||||
};
|
||||
match image {
|
||||
Ok(i) => Piece::Image(i, orientation),
|
||||
Err(e) => Piece::Note(format!(
|
||||
"{what}: {name} is an image the app cannot read ({e}). {later}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
for id in &item.docs {
|
||||
pieces.push(piece(&item.what, files.remove(id)));
|
||||
}
|
||||
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("visa.buildfor.life".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() {
|
||||
let (Some(settings), Some(size)) =
|
||||
(PageSettings::from_wh(w, h), Size::from_wh(w, h))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let mut page = doc.start_page_with(settings);
|
||||
let mut s = page.surface();
|
||||
s.draw_pdf_page(pdf, size, k);
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
}
|
||||
Piece::Image(image, orientation) => image_page(&mut doc, image, *orientation),
|
||||
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);
|
||||
|
||||
/// An image on an A4 page of its own orientation, as large as the margins
|
||||
/// allow, turned upright as its EXIF orientation says.
|
||||
fn image_page(doc: &mut Document, image: &Image, orientation: u16) {
|
||||
let (pw, ph) = image.size();
|
||||
let (w, h) = (pw.max(1) as f32, ph.max(1) as f32);
|
||||
let (dw, dh) = if orientation >= 5 { (h, w) } else { (w, h) };
|
||||
let landscape = dw > dh;
|
||||
let (page_w, page_h) = if landscape { (H, W) } else { (W, H) };
|
||||
let scale = ((page_w - 2.0 * MARGIN) / dw).min((page_h - 2.0 * MARGIN) / dh);
|
||||
let (x0, y0) = ((page_w - dw * scale) / 2.0, (page_h - dh * scale) / 2.0);
|
||||
let Some(size) = Size::from_wh(w, h) else {
|
||||
return;
|
||||
};
|
||||
let [sx, ky, kx, sy, tx, ty] = upright(orientation, w, h);
|
||||
let mut page = doc.start_page_with(a4(landscape));
|
||||
let mut s = page.surface();
|
||||
s.push_transform(&Transform::from_row(scale, 0.0, 0.0, scale, x0, y0));
|
||||
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
|
||||
s.draw_image(image.clone(), size);
|
||||
s.pop();
|
||||
s.pop();
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user