Phase 5: the Immigration Bureau's forms, filled in from the records
CI / secret scan (push) Successful in 5s
CI / fmt, clippy, tests (push) Successful in 39s

A Forms tab on each person fills in TM.7, STM.2, STM.9, STM.11 and STM.1
for an extension of stay, TM.47 for a 90-day report and TM.8 for a re-entry
permit. The Bureau's blank pages (forms/, with their sources and checksums)
go unchanged into a new PDF, and the values are written on the dotted lines
in Sarabun; boxes are ticked and the title circled where a form asks.
scripts/gen_layout.py measures the blanks into src/papers/layout.rs.

The tab says what would stay blank and links to where it is added. What only
the application says (the date, the office, the reason, the days, a trip) is
carried in the links and never stored. The extension's five forms also come
in one PDF. Opening or downloading a form is audited as entity "form" with
the forms' codes, never their values.

Migration 0005 adds what STM.1 and STM.11 ask of the company (capital,
revenue, equity, staff, a coordinator), a work permit's salary and contract
dates, and where an arrival came from. The Nix package now takes forms/.
This commit is contained in:
grabowski committed 2026-11-18 12:30:03 +07:00
1 parent 2a6e972b68
commit a2cedcdd7e
40 files changed
+3404 -35

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
//! The Immigration Bureau's forms, filled in from the records. Each page of
//! the blank form (forms/, as the Bureau publishes it) is laid unchanged into
//! a new PDF, and the values are written on its dotted lines in Sarabun, the
//! font of the forms themselves; a box is ticked or the person's title is
//! circled where the form asks for that.
pub mod layout;
pub mod values;
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use krilla::Document;
use krilla::color::rgb;
use krilla::geom::{PathBuilder, Point, Size};
use krilla::metadata::Metadata;
use krilla::num::NormalizedF32;
use krilla::page::PageSettings;
use krilla::paint::{Fill, LineCap, Stroke};
use krilla::pdf::{Pdf, PdfDocument};
use krilla::surface::Surface;
use krilla::text::{Font, TextDirection};
use serde::Serialize;
/// The values by key (`layout.rs` names the keys), as they go on the form.
pub type Values = HashMap<&'static str, String>;
/// A blank: the value of `key` is written from `x` on the baseline `y`
/// (points from the page's top left), within `w`.
#[derive(Debug)]
pub struct Blank {
pub page: usize,
pub x: f32,
pub y: f32,
pub w: f32,
pub key: &'static str,
}
/// A box that is ticked, or a printed word that is circled (`ring`), when
/// the value of `key` is `is`.
#[derive(Debug)]
pub struct Mark {
pub page: usize,
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub key: &'static str,
pub is: &'static str,
pub ring: bool,
}
#[derive(Debug)]
pub struct Layout {
pub blanks: &'static [Blank],
pub marks: &'static [Mark],
}
const fn b(page: usize, x: f32, y: f32, w: f32, key: &'static str) -> Blank {
Blank { page, x, y, w, key }
}
#[allow(clippy::too_many_arguments)]
const fn m(
page: usize,
x: f32,
y: f32,
w: f32,
h: f32,
key: &'static str,
is: &'static str,
ring: bool,
) -> Mark {
Mark {
page,
x,
y,
w,
h,
key,
is,
ring,
}
}
/// A form of the Immigration Bureau.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
pub enum Paper {
Tm7,
Stm2,
Stm9,
Stm11,
Stm1,
Tm47,
Tm8,
}
/// Every form, in the order the Forms tab lists them.
pub const ALL: [Paper; 7] = [
Paper::Tm7,
Paper::Stm2,
Paper::Stm9,
Paper::Stm11,
Paper::Stm1,
Paper::Tm47,
Paper::Tm8,
];
/// The forms of an extension of stay, in the order the officer reads them.
pub const EXTENSION: [Paper; 5] = [
Paper::Tm7,
Paper::Stm2,
Paper::Stm9,
Paper::Stm11,
Paper::Stm1,
];
/// Where the blank forms come from: Immigration Division 1's downloads, the
/// versions of 2025 for the STM forms (forms/README.md).
const SOURCE: &str = "https://bangkok.immigration.go.th/en/downloads_en/";
impl Paper {
pub fn slug(self) -> &'static str {
match self {
Paper::Tm7 => "tm7",
Paper::Stm2 => "stm2",
Paper::Stm9 => "stm9",
Paper::Stm11 => "stm11",
Paper::Stm1 => "stm1",
Paper::Tm47 => "tm47",
Paper::Tm8 => "tm8",
}
}
pub fn from_slug(s: &str) -> Option<Paper> {
ALL.into_iter().find(|p| p.slug() == s)
}
pub fn code(self) -> &'static str {
match self {
Paper::Tm7 => "TM.7",
Paper::Stm2 => "STM.2",
Paper::Stm9 => "STM.9",
Paper::Stm11 => "STM.11",
Paper::Stm1 => "STM.1",
Paper::Tm47 => "TM.47",
Paper::Tm8 => "TM.8",
}
}
pub fn title(self) -> &'static str {
match self {
Paper::Tm7 => "Application for extension of temporary stay",
Paper::Stm2 => "Acknowledgment of the conditions of a temporary stay",
Paper::Stm9 => "Acknowledgment of the penalties for overstay",
Paper::Stm11 => "Consent to the checking of the application",
Paper::Stm1 => "Certificate of employment, from the employer",
Paper::Tm47 => "Notification of staying longer than 90 days",
Paper::Tm8 => "Application for a re-entry permit",
}
}
pub fn when(self) -> &'static str {
match self {
Paper::Tm7 | Paper::Stm2 | Paper::Stm9 | Paper::Stm11 => {
"With every extension of stay; signed by the person."
}
Paper::Stm1 => {
"With an extension for work; signed by the director, with the company's seal."
}
Paper::Tm47 => "For a 90-day report in person or by someone the person authorizes.",
Paper::Tm8 => "Before a trip abroad, so that the extension of stay is kept.",
}
}
pub fn source(self) -> &'static str {
SOURCE
}
fn blank(self) -> &'static [u8] {
match self {
Paper::Tm7 => include_bytes!("../../forms/tm7.pdf"),
Paper::Stm2 => include_bytes!("../../forms/stm2.pdf"),
Paper::Stm9 => include_bytes!("../../forms/stm9.pdf"),
Paper::Stm11 => include_bytes!("../../forms/stm11.pdf"),
Paper::Stm1 => include_bytes!("../../forms/stm1.pdf"),
Paper::Tm47 => include_bytes!("../../forms/tm47.pdf"),
Paper::Tm8 => include_bytes!("../../forms/tm8.pdf"),
}
}
pub fn layout(self) -> &'static Layout {
match self {
Paper::Tm7 => &layout::TM7,
Paper::Stm2 => &layout::STM2,
Paper::Stm9 => &layout::STM9,
Paper::Stm11 => &layout::STM11,
Paper::Stm1 => &layout::STM1,
Paper::Tm47 => &layout::TM47,
Paper::Tm8 => &layout::TM8,
}
}
/// The keys the form uses, each once, in the order of its blanks.
pub fn keys(self) -> Vec<&'static str> {
let l = self.layout();
let mut out: Vec<&'static str> = Vec::new();
let keys = l
.blanks
.iter()
.map(|b| b.key.trim_end_matches('+'))
.chain(l.marks.iter().map(|m| m.key));
for k in keys {
if !out.contains(&k) {
out.push(k);
}
}
out
}
}
/// Sarabun (SIL Open Font License, forms/fonts/OFL.txt): Thai and Latin.
static FONT: &[u8] = include_bytes!("../../forms/fonts/Sarabun-Regular.ttf");
/// The size of the values, and the least they shrink to in a short blank.
const SIZE: f32 = 10.5;
const MIN_SIZE: f32 = 6.0;
/// Values sit this far above the dotted line, as handwriting would.
const LIFT: f32 = 1.6;
/// The width of `text` at `size` points, as shaped.
fn width(face: &rustybuzz::Face<'_>, text: &str, size: f32) -> f32 {
let mut buf = rustybuzz::UnicodeBuffer::new();
buf.push_str(text);
buf.guess_segment_properties();
let shaped = rustybuzz::shape(face, &[], buf);
let units: i32 = shaped.glyph_positions().iter().map(|p| p.x_advance).sum();
units as f32 * size / f32::from(face.units_per_em() as u16)
}
/// The size at which `text` fits into `room`, never under MIN_SIZE.
fn fitting(face: &rustybuzz::Face<'_>, text: &str, room: f32) -> f32 {
let w = width(face, text, SIZE);
if w <= room {
SIZE
} else {
(SIZE * room / w).max(MIN_SIZE)
}
}
/// Splits `text` into a first line that fits `room` at full size and the
/// rest.
fn first_line<'a>(face: &rustybuzz::Face<'_>, text: &'a str, room: f32) -> (&'a str, &'a str) {
let mut end = 0;
for (i, c) in text.char_indices() {
if c == ' ' {
if width(face, &text[..i], SIZE) > room {
break;
}
end = i;
}
}
if end == 0 || width(face, text, SIZE) <= room {
return (text, "");
}
(&text[..end], text[end..].trim_start())
}
struct Pen<'a> {
font: Font,
face: rustybuzz::Face<'a>,
}
impl Pen<'_> {
fn write(&self, s: &mut Surface<'_>, blank: &Blank, text: &str) {
if text.is_empty() {
return;
}
let room = blank.w - 4.0;
let size = fitting(&self.face, text, room);
let w = width(&self.face, text, size);
// a short blank (a day, an age) gets its value in the middle
let x = if blank.w < 70.0 {
blank.x + ((blank.w - w) / 2.0).max(0.0)
} else {
blank.x + 3.0
};
s.draw_text(
Point::from_xy(x, blank.y - LIFT),
self.font.clone(),
size,
text,
false,
TextDirection::Auto,
);
}
}
fn ink() -> rgb::Color {
rgb::Color::new(0, 0, 0)
}
fn stroke(width: f32) -> Stroke {
Stroke {
paint: ink().into(),
width,
line_cap: LineCap::Round,
opacity: NormalizedF32::ONE,
..Default::default()
}
}
/// An X in a box.
fn tick(s: &mut Surface<'_>, mk: &Mark) {
let inset = mk.w.min(mk.h) * 0.22;
let (x0, y0) = (mk.x + inset, mk.y + inset);
let (x1, y1) = (mk.x + mk.w - inset, mk.y + mk.h - inset);
// a square X in a tall box
let side = (x1 - x0).min(y1 - y0);
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
let h = side / 2.0;
let mut pb = PathBuilder::new();
pb.move_to(cx - h, cy - h);
pb.line_to(cx + h, cy + h);
pb.move_to(cx + h, cy - h);
pb.line_to(cx - h, cy + h);
if let Some(path) = pb.finish() {
s.set_fill(None);
s.set_stroke(Some(stroke(1.3)));
s.draw_path(&path);
s.set_stroke(None);
}
}
/// An ellipse around a printed word.
fn ring(s: &mut Surface<'_>, mk: &Mark) {
let (rx, ry) = (mk.w / 2.0 + 2.5, mk.h / 2.0 - 1.0);
let (cx, cy) = (mk.x + mk.w / 2.0, mk.y + mk.h / 2.0 + 0.5);
// four cubic arcs
const K: f32 = 0.552_284_8;
let mut pb = PathBuilder::new();
pb.move_to(cx + rx, cy);
pb.cubic_to(cx + rx, cy + K * ry, cx + K * rx, cy + ry, cx, cy + ry);
pb.cubic_to(cx - K * rx, cy + ry, cx - rx, cy + K * ry, cx - rx, cy);
pb.cubic_to(cx - rx, cy - K * ry, cx - K * rx, cy - ry, cx, cy - ry);
pb.cubic_to(cx + K * rx, cy - ry, cx + rx, cy - K * ry, cx + rx, cy);
pb.close();
if let Some(path) = pb.finish() {
s.set_fill(None);
s.set_stroke(Some(stroke(0.8)));
s.draw_path(&path);
s.set_stroke(None);
}
}
/// The title to circle on a line that offers `offered`: the person's own,
/// or Miss for Ms and Ms for Miss where the line has only the other.
fn title_on_line<'a>(title: &str, offered: &[&'a Mark]) -> Option<&'a Mark> {
let alt = match title {
"Ms" => "Miss",
"Miss" => "Ms",
_ => "",
};
offered
.iter()
.find(|mk| mk.is == title)
.or_else(|| offered.iter().find(|mk| mk.is == alt))
.copied()
}
fn fill_page(s: &mut Surface<'_>, pen: &Pen<'_>, layout: &Layout, page: usize, v: &Values) {
s.set_fill(Some(Fill {
paint: ink().into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}));
// what is left of a flowing value for its next line
let mut rest = String::new();
let blanks: Vec<&Blank> = layout.blanks.iter().filter(|b| b.page == page).collect();
for (i, blank) in blanks.iter().enumerate() {
let continued = blank.key.ends_with('+');
let text = if continued {
std::mem::take(&mut rest)
} else {
v.get(blank.key).cloned().unwrap_or_default()
};
let flows_on = blanks
.get(i + 1)
.is_some_and(|next| next.key.ends_with('+'));
if flows_on {
let (line, more) = first_line(&pen.face, &text, blank.w - 6.0);
pen.write(s, blank, line);
rest = more.to_string();
} else {
pen.write(s, blank, &text);
}
}
let marks: Vec<&Mark> = layout.marks.iter().filter(|mk| mk.page == page).collect();
for mk in marks.iter().filter(|mk| !mk.ring) {
if v.get(mk.key).is_some_and(|x| x == mk.is) {
tick(s, mk);
}
}
// titles: one ring on each line that offers them
let title = v.get("title").map(String::as_str).unwrap_or("");
let mut lines: Vec<f32> = marks.iter().filter(|mk| mk.ring).map(|mk| mk.y).collect();
lines.dedup_by(|a, b| (*a - *b).abs() < 1.0);
for y in lines {
let offered: Vec<&Mark> = marks
.iter()
.filter(|mk| mk.ring && (mk.y - y).abs() < 1.0)
.copied()
.collect();
if let Some(mk) = title_on_line(title, &offered) {
ring(s, mk);
}
}
}
/// The forms filled in with `v`, one after the other in one PDF.
pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> {
let font = Font::new(FONT.into(), 0).context("the font Sarabun")?;
let face = rustybuzz::Face::from_slice(FONT, 0).context("the font Sarabun")?;
let pen = Pen { font, face };
let mut doc = Document::new();
doc.set_metadata(
Metadata::new()
.title(title.to_string())
.creator("visa.buildfor.life".to_string()),
);
for &paper in papers {
let pdf = Pdf::new(Arc::new(paper.blank()))
.map_err(|e| anyhow!("the blank form {}: {e:?}", paper.code()))?;
let pages: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
let blank = PdfDocument::new(Arc::new(pdf));
for (i, (w, h)) in pages.into_iter().enumerate() {
let settings = PageSettings::from_wh(w, h).context("a page size")?;
let mut page = doc.start_page_with(settings);
let mut s = page.surface();
s.draw_pdf_page(&blank, Size::from_wh(w, h).context("a page size")?, i);
fill_page(&mut s, &pen, paper.layout(), i + 1, v);
s.finish();
page.finish();
}
}
doc.finish().map_err(|e| anyhow!("writing the PDF: {e:?}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn face() -> rustybuzz::Face<'static> {
rustybuzz::Face::from_slice(FONT, 0).unwrap()
}
#[test]
fn every_form_has_its_blanks_and_keys() {
for p in ALL {
assert_eq!(Paper::from_slug(p.slug()), Some(p));
assert!(!p.layout().blanks.is_empty(), "{}", p.code());
assert!(p.blank().starts_with(b"%PDF-"), "{}", p.code());
for b in p.layout().blanks {
assert!(b.w > 10.0 && b.x > 30.0 && b.x + b.w < 570.0, "{b:?}");
assert!(b.y > 50.0 && b.y < 830.0, "{b:?}");
}
}
assert!(Paper::Tm7.keys().contains(&"reason"));
assert!(!Paper::Tm7.keys().contains(&"reason+"));
}
#[test]
fn a_long_value_shrinks_and_a_reason_flows() {
let f = face();
assert_eq!(fitting(&f, "18", 30.0), SIZE);
let long = "DEMO ENGINEERING COMPANY LIMITED, FIFTH FLOOR, DEMO TOWER";
let size = fitting(&f, long, 120.0);
assert!((MIN_SIZE..SIZE).contains(&size), "{size}");
let (line, rest) = first_line(&f, long, 150.0);
assert!(width(&f, line, SIZE) <= 150.0, "{line}");
assert_eq!(format!("{line} {rest}"), long);
assert_eq!(first_line(&f, "SHORT", 150.0), ("SHORT", ""));
}
#[test]
fn thai_is_shaped_with_its_marks() {
let f = face();
// the tone mark and the vowel above take no room of their own
assert!(width(&f, "นี้", SIZE) < width(&f, "นนน", SIZE));
}
#[test]
fn the_title_or_its_neighbour_is_circled() {
let mr = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Mr", true);
let miss = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Miss", true);
let ms = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Ms", true);
assert_eq!(
title_on_line("Ms", &[&mr, &miss]).map(|x| x.is),
Some("Miss")
);
assert_eq!(title_on_line("Miss", &[&mr, &ms]).map(|x| x.is), Some("Ms"));
assert_eq!(title_on_line("Ms", &[&mr, &ms]).map(|x| x.is), Some("Ms"));
assert!(title_on_line("", &[&mr, &miss]).is_none());
}
#[test]
fn a_filled_form_is_a_pdf_with_the_form_s_pages() {
let mut v = Values::new();
v.insert("family_name", "MUSTERMANN".into());
v.insert("title", "Ms".into());
v.insert("entries", "multiple".into());
v.insert(
"reason",
"TO CONTINUE WORKING FOR DEMO ENGINEERING CO., LTD. AS ELECTRICAL ENGINEER, AS IN THE WORK PERMIT AND THE EMPLOYER'S CERTIFICATE".into(),
);
let pdf = render(&[Paper::Tm7, Paper::Tm8], &v, "TM.7 and TM.8").unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let parsed = Pdf::new(pdf).unwrap();
assert_eq!(parsed.pages().len(), 4);
}
}