use crate::fonts::{FontBook, FontRole};
use crate::inline::{Run, parse_inline};
use crate::parse::ResumeDoc;
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Rgb(pub f32, pub f32, pub f32);
pub const INK: Rgb = Rgb(0.102, 0.102, 0.102); pub const BODY: Rgb = Rgb(0.2, 0.2, 0.2); pub const MUTED: Rgb = Rgb(0.478, 0.478, 0.478); pub const HAIR: Rgb = Rgb(0.784, 0.784, 0.784);
pub const LETTER: (f32, f32) = (612.0, 792.0);
pub const A4: (f32, f32) = (595.2756, 841.8898);
#[derive(Clone, Copy, Debug)]
pub struct PageGeom {
pub size: (f32, f32),
pub margins: (f32, f32, f32, f32),
}
impl PageGeom {
pub fn new(size: (f32, f32)) -> PageGeom {
PageGeom {
size,
margins: (49.2, 49.2, 42.0, 38.4),
}
}
pub fn usable_width(&self) -> f32 {
self.size.0 - self.margins.0 - self.margins.1
}
}
#[derive(Clone, Debug)]
pub struct PlacedText {
pub order: u32,
pub role: FontRole,
pub size: f32,
pub color: Rgb,
pub x: f32,
pub y: f32,
pub text: String,
pub link: Option<String>,
}
#[derive(Clone, Debug)]
pub struct RuleLine {
pub x1: f32,
pub y1: f32,
pub x2: f32,
pub y2: f32,
pub width: f32,
pub color: Rgb,
}
#[derive(Clone, Debug)]
pub struct LinkRect {
pub url: String,
pub rect: [f32; 4],
}
#[derive(Default, Clone, Debug)]
pub struct PageOut {
pub texts: Vec<PlacedText>,
pub rules: Vec<RuleLine>,
pub links: Vec<LinkRect>,
}
#[derive(Debug)]
pub struct Layout {
pub pages: Vec<PageOut>,
pub geom: PageGeom,
pub scale: f32,
pub overflow: bool,
pub overflow_x: bool,
}
#[derive(Clone, Debug)]
struct Frag {
role: FontRole,
text: String,
width: f32,
link: Option<String>,
}
type WrappedLine = Vec<Frag>;
#[derive(Clone, Copy)]
struct ParaStyle {
base: FontRole,
size: f32,
leading: f32,
color: Rgb,
}
impl ParaStyle {
fn first_baseline(&self) -> f32 {
0.8 * self.size
}
}
fn wrap_runs(book: &FontBook, runs: &[Run], style: ParaStyle, width: f32) -> Vec<WrappedLine> {
let mut full = String::new();
let mut meta: Vec<(FontRole, Option<u16>)> = Vec::new();
let mut links: Vec<String> = Vec::new();
for run in runs {
let role = style.base.styled(run.bold, run.italic);
let link_idx = run.link.as_ref().map(|u| {
if let Some(i) = links.iter().position(|l| l == u) {
i as u16
} else {
links.push(u.clone());
(links.len() - 1) as u16
}
});
for c in run.text.chars() {
full.push(c);
meta.push((role, link_idx));
}
}
if full.is_empty() {
return Vec::new();
}
struct Tok {
chars: Vec<usize>, width: f32,
width_trimmed: f32,
}
let char_width = |i: usize, c: char| -> f32 {
let font = book.get(meta[i].0);
match font.glyph(c) {
Some(g) => g.advance as f32 * style.size / font.units_per_em,
None => style.size * 0.5,
}
};
let mut toks: Vec<Tok> = Vec::new();
let mut prev_byte = 0usize;
let mut char_index_of_byte: Vec<usize> = Vec::new(); {
let mut ci = 0;
let mut bytes = 0;
for c in full.chars() {
for _ in 0..c.len_utf8() {
char_index_of_byte.push(ci);
bytes += 1;
}
ci += 1;
}
char_index_of_byte.push(ci);
let _ = bytes;
}
for (brk, kind) in unicode_linebreak::linebreaks(&full) {
if brk == prev_byte {
continue;
}
let at_whitespace = full[..brk].chars().last().is_some_and(char::is_whitespace);
if !at_whitespace && kind != unicode_linebreak::BreakOpportunity::Mandatory {
continue;
}
let start = char_index_of_byte[prev_byte];
let end = char_index_of_byte[brk];
let chars: Vec<usize> = (start..end).collect();
let text: Vec<char> = full.chars().skip(start).take(end - start).collect();
let mut width = 0.0;
for (off, &i) in chars.iter().enumerate() {
width += char_width(i, text[off]);
}
let mut width_trimmed = width;
for (off, &i) in chars.iter().enumerate().rev() {
if text[off].is_whitespace() {
width_trimmed -= char_width(i, text[off]);
} else {
break;
}
}
toks.push(Tok {
chars,
width,
width_trimmed,
});
prev_byte = brk;
}
let all_chars: Vec<char> = full.chars().collect();
let mut lines: Vec<Vec<usize>> = Vec::new();
let mut cur: Vec<usize> = Vec::new();
let mut cur_w = 0.0f32;
for tok in &toks {
if !cur.is_empty() && cur_w + tok.width_trimmed > width + 0.001 {
lines.push(std::mem::take(&mut cur));
cur_w = 0.0;
}
cur.extend_from_slice(&tok.chars);
cur_w += tok.width;
}
if !cur.is_empty() {
lines.push(cur);
}
lines
.into_iter()
.map(|mut line| {
while let Some(&last) = line.last() {
if all_chars[last].is_whitespace() {
line.pop();
} else {
break;
}
}
let mut frags: Vec<Frag> = Vec::new();
for &i in &line {
let (role, link_idx) = meta[i];
let link = link_idx.map(|li| links[li as usize].clone());
let c = all_chars[i];
let w = char_width(i, c);
match frags.last_mut() {
Some(f) if f.role == role && f.link == link => {
f.text.push(c);
f.width += w;
}
_ => frags.push(Frag {
role,
text: c.to_string(),
width: w,
link,
}),
}
}
frags
})
.filter(|l| !l.is_empty())
.collect()
}
fn line_width(line: &WrappedLine) -> f32 {
line.iter().map(|f| f.width).sum()
}
enum Block {
Spacer(f32),
Header {
name: Vec<Run>,
contact: Vec<Vec<Run>>,
},
Rule,
Label(String),
EntryRow {
role: String,
company: String,
extra: String,
aside: String,
meta: String,
},
Bullet(Vec<Run>),
Skills(Vec<(Vec<Run>, Vec<Run>)>),
Note(Vec<Run>),
}
fn build_story(doc: &ResumeDoc, s: f32) -> Vec<Block> {
let mut story = Vec::new();
story.push(Block::Header {
name: parse_inline(&doc.name),
contact: doc.contact.iter().map(|c| parse_inline(c)).collect(),
});
story.push(Block::Spacer(4.0 * s));
story.push(Block::Rule);
for (i, sec) in doc.sections.iter().enumerate() {
story.push(Block::Spacer(if i == 0 { 8.0 } else { 10.0 } * s));
story.push(Block::Label(sec.label.clone()));
story.push(Block::Spacer(3.0 * s));
if sec.kind == "skills" {
story.push(Block::Skills(
sec.rows
.iter()
.map(|(a, b)| (parse_inline(a), parse_inline(b)))
.collect(),
));
} else {
for e in &sec.entries {
story.push(Block::EntryRow {
role: e.role.clone(),
company: e.company.clone(),
extra: e.extra.clone(),
aside: e.aside.clone(),
meta: e.meta.clone(),
});
story.push(Block::Spacer(3.0 * s));
for b in &e.bullets {
story.push(Block::Bullet(parse_inline(b)));
}
if !e.bullets.is_empty() {
story.push(Block::Spacer(4.0 * s));
}
}
}
for n in &sec.notes {
story.push(Block::Spacer(2.0 * s));
story.push(Block::Note(parse_inline(n)));
}
}
story
}
struct Prepared {
height: f32,
overflow_x: bool,
kind: PreparedKind,
}
fn widest(lines: &[WrappedLine]) -> f32 {
lines.iter().map(line_width).fold(0.0, f32::max)
}
const X_EPS: f32 = 0.5;
enum PreparedKind {
Spacer,
Rule,
Label(String),
Entry {
role: String,
company: String,
extra: String,
aside: String,
meta: String,
},
Bullet {
marker: char,
lines: Vec<WrappedLine>,
},
Header {
name_lines: Vec<WrappedLine>,
name_h: f32,
contact_lines: Vec<Vec<WrappedLine>>,
contact_h: f32,
},
Skills {
rows: Vec<(Vec<WrappedLine>, Vec<WrappedLine>, f32)>,
},
Note(Vec<WrappedLine>),
}
struct Styles {
name: ParaStyle,
contact: ParaStyle,
bullet: ParaStyle,
small: ParaStyle,
label: ParaStyle,
}
fn styles(s: f32) -> Styles {
Styles {
name: ParaStyle {
base: FontRole::Thin,
size: 25.5 * s,
leading: 28.0 * s,
color: INK,
},
contact: ParaStyle {
base: FontRole::Regular,
size: 7.4 * s,
leading: 10.6 * s,
color: MUTED,
},
bullet: ParaStyle {
base: FontRole::Regular,
size: 7.75 * s,
leading: 10.4 * s,
color: BODY,
},
small: ParaStyle {
base: FontRole::Regular,
size: 7.75 * s,
leading: 10.4 * s,
color: BODY,
},
label: ParaStyle {
base: FontRole::SemiBold,
size: 8.0 * s,
leading: 10.4 * s,
color: INK,
},
}
}
fn prepare(book: &FontBook, geom: &PageGeom, s: f32, block: Block) -> Prepared {
let usable = geom.usable_width();
let st = styles(s);
match block {
Block::Spacer(h) => Prepared {
height: h,
overflow_x: false,
kind: PreparedKind::Spacer,
},
Block::Rule => Prepared {
height: 3.2,
overflow_x: false,
kind: PreparedKind::Rule,
},
Block::Label(text) => Prepared {
height: 9.6 * s + 5.0,
overflow_x: book.measure(FontRole::Regular, &text, 9.6 * s) > usable + X_EPS,
kind: PreparedKind::Label(text),
},
Block::EntryRow {
role,
company,
extra,
aside,
meta,
} => {
let role_w = book.measure(FontRole::Light, &role, 13.5 * s);
let mut cluster = book.measure(FontRole::SemiBold, &company, 9.6 * s);
if !extra.is_empty() {
cluster += book.measure(FontRole::Regular, &extra, 8.0 * s) + 5.0 * s;
}
let meta_w = book.measure(FontRole::Regular, &meta, 7.4 * s);
let aside_w = book.measure(FontRole::Regular, &aside, 7.4 * s);
let overflow_x = [role_w, cluster, meta_w, aside_w]
.iter()
.any(|&w| w > usable + X_EPS);
Prepared {
height: 27.0 * s,
overflow_x,
kind: PreparedKind::Entry {
role,
company,
extra,
aside,
meta,
},
}
}
Block::Bullet(runs) => {
let width = usable - 9.0 * s;
let lines = wrap_runs(book, &runs, st.bullet, width);
Prepared {
height: lines.len() as f32 * st.bullet.leading + 1.5 * s,
overflow_x: widest(&lines) > width + X_EPS,
kind: PreparedKind::Bullet {
marker: book.bullet_char(),
lines,
},
}
}
Block::Header { name, contact } => {
let col = usable * 0.5;
let name_lines = wrap_runs(book, &name, st.name, col);
let name_h = name_lines.len().max(1) as f32 * st.name.leading;
let contact_lines: Vec<Vec<WrappedLine>> = contact
.iter()
.map(|c| wrap_runs(book, c, st.contact, col))
.collect();
let contact_h: f32 = contact_lines
.iter()
.map(|l| l.len() as f32 * st.contact.leading)
.sum();
let overflow_x = widest(&name_lines) > col + X_EPS
|| contact_lines.iter().any(|l| widest(l) > col + X_EPS);
Prepared {
height: name_h.max(contact_h),
overflow_x,
kind: PreparedKind::Header {
name_lines,
name_h,
contact_lines,
contact_h,
},
}
}
Block::Skills(rows) => {
let c1 = usable * 0.155;
let c2 = usable * 0.845;
let indent = 14.0 * s;
let label_w = (c1 - indent).max(10.0);
let mut prepared_rows = Vec::new();
let mut total = 0.0;
let mut overflow_x = false;
for (label, value) in rows {
let ll = wrap_runs(book, &label, st.label, label_w);
let vl = wrap_runs(book, &value, st.small, c2);
let h = (ll.len() as f32 * st.label.leading)
.max(vl.len() as f32 * st.small.leading)
+ 3.0;
total += h;
overflow_x |= widest(&ll) > label_w + X_EPS || widest(&vl) > c2 + X_EPS;
prepared_rows.push((ll, vl, h));
}
Prepared {
height: total,
overflow_x,
kind: PreparedKind::Skills {
rows: prepared_rows,
},
}
}
Block::Note(runs) => {
let lines = wrap_runs(book, &runs, st.small, usable);
Prepared {
height: lines.len() as f32 * st.small.leading,
overflow_x: widest(&lines) > usable + X_EPS,
kind: PreparedKind::Note(lines),
}
}
}
}
struct Ctx {
order: u32,
}
impl Ctx {
fn next(&mut self) -> u32 {
let o = self.order;
self.order += 1;
o
}
}
#[allow(clippy::too_many_arguments)]
fn place_string(
ctx: &mut Ctx,
page: &mut PageOut,
role: FontRole,
size: f32,
color: Rgb,
x: f32,
y: f32,
text: &str,
) {
if text.is_empty() {
return;
}
page.texts.push(PlacedText {
order: ctx.next(),
role,
size,
color,
x,
y,
text: text.to_string(),
link: None,
});
}
#[allow(clippy::too_many_arguments)]
fn place_para(
ctx: &mut Ctx,
page: &mut PageOut,
lines: &[WrappedLine],
style: ParaStyle,
x: f32,
y_top: f32,
width: f32,
align_right: bool,
) {
for (i, line) in lines.iter().enumerate() {
let baseline = y_top - style.first_baseline() - i as f32 * style.leading;
let lw = line_width(line);
let mut cx = if align_right { x + width - lw } else { x };
for frag in line {
let color = if frag.link.is_some() {
BODY
} else {
style.color
};
page.texts.push(PlacedText {
order: ctx.next(),
role: frag.role,
size: style.size,
color,
x: cx,
y: baseline,
text: frag.text.clone(),
link: frag.link.clone(),
});
if let Some(url) = &frag.link {
page.rules.push(RuleLine {
x1: cx,
y1: baseline - 1.0,
x2: cx + frag.width,
y2: baseline - 1.0,
width: 0.5,
color: BODY,
});
page.links.push(LinkRect {
url: url.clone(),
rect: [
cx,
baseline - 1.5,
cx + frag.width,
baseline + 0.75 * style.size,
],
});
}
cx += frag.width;
}
}
}
fn place_block(
ctx: &mut Ctx,
page: &mut PageOut,
book: &FontBook,
geom: &PageGeom,
s: f32,
prepared: &Prepared,
y_top: f32,
) {
let left = geom.margins.0;
let usable = geom.usable_width();
let st = styles(s);
match &prepared.kind {
PreparedKind::Spacer => {}
PreparedKind::Rule => {
let y = y_top - 1.6;
page.rules.push(RuleLine {
x1: left,
y1: y,
x2: left + usable,
y2: y,
width: 1.2,
color: INK,
});
}
PreparedKind::Label(text) => {
let size = 9.6 * s;
let bottom = y_top - prepared.height;
place_string(
ctx,
page,
FontRole::Regular,
size,
MUTED,
left,
bottom + 4.5,
text,
);
let w = book.measure(FontRole::Regular, text, size);
page.rules.push(RuleLine {
x1: left,
y1: bottom + 2.5,
x2: left + w + 2.0,
y2: bottom + 2.5,
width: 0.5,
color: MUTED,
});
}
PreparedKind::Entry {
role,
company,
extra,
aside,
meta,
} => {
let bottom = y_top - 27.0 * s;
let role_size = 13.5 * s;
let co_size = 9.6 * s;
let date_size = 7.4 * s;
let (y_role, y_rule, y_date) = (bottom + 13.4 * s, bottom + 8.6 * s, bottom + 2.6 * s);
let y_right = bottom + 13.2 * s;
place_string(
ctx,
page,
FontRole::Light,
role_size,
INK,
left,
y_role,
role,
);
let rw = book.measure(FontRole::Light, role, role_size);
page.rules.push(RuleLine {
x1: left,
y1: y_rule,
x2: left + rw + 4.0,
y2: y_rule,
width: 0.5,
color: HAIR,
});
if !aside.is_empty() {
place_string(
ctx,
page,
FontRole::Regular,
date_size,
MUTED,
left,
y_date,
aside,
);
}
let right_edge = left + usable;
let extra_w = if extra.is_empty() {
0.0
} else {
book.measure(FontRole::Regular, extra, 8.0 * s)
};
let co_right = if extra.is_empty() {
right_edge
} else {
right_edge - extra_w - 5.0 * s
};
let co_w = book.measure(FontRole::SemiBold, company, co_size);
place_string(
ctx,
page,
FontRole::SemiBold,
co_size,
INK,
co_right - co_w,
y_right,
company,
);
if !extra.is_empty() {
place_string(
ctx,
page,
FontRole::Regular,
8.0 * s,
MUTED,
right_edge - extra_w,
y_right,
extra,
);
}
if !meta.is_empty() {
let mw = book.measure(FontRole::Regular, meta, date_size);
place_string(
ctx,
page,
FontRole::Regular,
date_size,
MUTED,
right_edge - mw,
y_date,
meta,
);
page.rules.push(RuleLine {
x1: right_edge - mw - 2.0,
y1: bottom + 0.2,
x2: right_edge,
y2: bottom + 0.2,
width: 0.5,
color: HAIR,
});
}
}
PreparedKind::Bullet { marker, lines } => {
let first_baseline = y_top - st.bullet.first_baseline();
place_string(
ctx,
page,
FontRole::Regular,
6.2 * s,
BODY,
left,
first_baseline,
&marker.to_string(),
);
place_para(
ctx,
page,
lines,
st.bullet,
left + 9.0 * s,
y_top,
usable - 9.0 * s,
false,
);
}
PreparedKind::Header {
name_lines,
name_h,
contact_lines,
contact_h,
} => {
let h = prepared.height;
let name_top = y_top - (h - name_h);
place_para(
ctx,
page,
name_lines,
st.name,
left,
name_top,
usable * 0.5,
false,
);
let mut cy = y_top - (h - contact_h);
for cl in contact_lines {
place_para(
ctx,
page,
cl,
st.contact,
left + usable * 0.5,
cy,
usable * 0.5,
true,
);
cy -= cl.len() as f32 * st.contact.leading;
}
}
PreparedKind::Skills { rows } => {
let c1 = usable * 0.155;
let indent = 14.0 * s;
let mut y = y_top;
for (label_lines, value_lines, h) in rows {
let cell_top = y - 1.5;
place_para(
ctx,
page,
label_lines,
st.label,
left + indent,
cell_top,
(c1 - indent).max(10.0),
false,
);
place_para(
ctx,
page,
value_lines,
st.small,
left + c1,
cell_top,
usable - c1,
false,
);
y -= h;
}
}
PreparedKind::Note(lines) => {
place_para(ctx, page, lines, st.small, left, y_top, usable, false);
}
}
}
pub fn layout_doc(doc: &ResumeDoc, book: &FontBook, geom: PageGeom, scale: f32) -> Layout {
let story = build_story(doc, scale);
let prepared: Vec<Prepared> = story
.into_iter()
.map(|b| prepare(book, &geom, scale, b))
.collect();
let top_y = geom.size.1 - geom.margins.2;
let bottom = geom.margins.3;
let mut pages = vec![PageOut::default()];
let mut y = top_y;
let mut overflow = false;
let overflow_x = prepared.iter().any(|p| p.overflow_x);
let mut ctx = Ctx { order: 0 };
for p in &prepared {
let is_spacer = matches!(p.kind, PreparedKind::Spacer);
if is_spacer && (y - top_y).abs() < 0.001 {
continue;
}
if y - p.height < bottom && (y - top_y).abs() > 0.001 {
pages.push(PageOut::default());
y = top_y;
if is_spacer {
continue;
}
}
let page = pages.last_mut().unwrap();
place_block(&mut ctx, page, book, &geom, scale, p, y);
y -= p.height;
if y < bottom - 0.5 {
overflow = true;
}
}
Layout {
pages,
geom,
scale,
overflow,
overflow_x,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fonts::FontBook;
#[test]
fn never_breaks_inside_hyphenated_tokens() {
let book = FontBook::embedded().unwrap();
let style = ParaStyle {
base: FontRole::Regular,
size: 10.0,
leading: 12.0,
color: BODY,
};
let runs = parse_inline("word and then leo-sat-tracker.amazon");
let lines = wrap_runs(&book, &runs, style, 80.0);
assert!(
lines.len() >= 2,
"expected a wrap, got {} line(s)",
lines.len()
);
let last: String = lines
.last()
.unwrap()
.iter()
.map(|f| f.text.as_str())
.collect();
assert!(
last.contains("leo-sat-tracker.amazon"),
"hyphenated token was split: {last:?}"
);
}
#[test]
fn detects_horizontal_overflow() {
let book = FontBook::embedded().unwrap();
let md = format!(
"# N\n> c@d.e\n\n## X\n### R\n**C** | 2020\n- {}\n",
"a".repeat(400)
);
let doc = crate::parse::parse(&md);
let l = layout_doc(&doc, &book, PageGeom::new(LETTER), 1.0);
assert!(l.overflow_x, "400-char token should flag overflow_x");
let ok = layout_doc(
&crate::parse::parse("# N\n\n## X\n### R\n**C** | 2020\n- fine\n"),
&book,
PageGeom::new(LETTER),
1.0,
);
assert!(!ok.overflow_x);
}
}