resumark 0.1.1

ATS-safe resume typesetting from Markdown — extraction order as a verified contract
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! Layout: turns a parsed resume into positioned text runs and rules.
//!
//! # The extraction-order contract
//!
//! Every placed text run carries an explicit `order` index, assigned in the
//! document's *declared reading order* — independent of the sequence in which
//! positions happen to be computed. The PDF backend emits runs in `order`, so
//! the content stream (what raw extractors and most ATS parsers read) matches
//! the declared order exactly. Where two runs share a visual line, baselines
//! and x-positions are arranged so that position-based extractors (pdftotext's
//! default reading-order mode) recover a faithful structure — see
//! `verify::check_reading` for exactly what that mode promises. `verify`
//! asserts both.
//!
//! The visual design and all dimensions are a faithful port of the reference
//! renderer (`render_resume.py`).

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); // #1a1a1a
pub const BODY: Rgb = Rgb(0.2, 0.2, 0.2); // #333333
pub const MUTED: Rgb = Rgb(0.478, 0.478, 0.478); // #7a7a7a
pub const HAIR: Rgb = Rgb(0.784, 0.784, 0.784); // #c8c8c8

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),
    /// Left, right, top, bottom margins in points.
    pub margins: (f32, f32, f32, f32),
}

impl PageGeom {
    pub fn new(size: (f32, f32)) -> PageGeom {
        // 0.6" / 0.6" / 0.5" / 0.45", plus the 6pt the reference renderer
        // inherits from ReportLab's default Frame padding.
        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
    }
}

/// One positioned text run. `y` is the baseline in PDF coordinates.
#[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,
    /// [x1, y1, x2, y2]
    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,
    /// True when content ran below the bottom margin on some page.
    pub overflow: bool,
    /// True when some run is wider than its column (an unbreakable token
    /// that will render past the column edge).
    pub overflow_x: bool,
}

// ---------------------------------------------------------------------------
// Paragraph wrapping
// ---------------------------------------------------------------------------

#[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 {
    /// Distance from the top of the line box down to the first baseline.
    fn first_baseline(&self) -> f32 {
        0.8 * self.size
    }
}

/// Wrap styled runs to a width. Break opportunities come from UAX #14.
fn wrap_runs(book: &FontBook, runs: &[Run], style: ParaStyle, width: f32) -> Vec<WrappedLine> {
    // Flatten to per-char metadata over the concatenated text.
    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();
    }

    // Tokens: substrings between consecutive break opportunities. A token
    // keeps its trailing whitespace; the width check ignores that whitespace.
    struct Tok {
        chars: Vec<usize>, // indices into meta
        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(); // byte -> char idx map
    {
        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;
        }
        // Break only at whitespace (plus the mandatory end-of-text break).
        // UAX #14 also allows breaks after hyphens and inside URLs, but
        // splitting a compound or a URL across lines both diverges from the
        // reference renderer and scrambles what extractors read back.
        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;
    }

    // Greedy fill.
    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);
    }

    // Trim trailing whitespace, then group chars into frags by (role, link).
    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()
}

// ---------------------------------------------------------------------------
// Blocks (the "story", mirroring the reference renderer's flowables)
// ---------------------------------------------------------------------------

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
}

// ---------------------------------------------------------------------------
// Prepared blocks: wrapped once per scale, then placed during pagination
// ---------------------------------------------------------------------------

struct Prepared {
    height: f32,
    /// Some run in this block is wider than its column (an unbreakable
    /// token); it will render past the column edge.
    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,
        },
        // 1.2pt line plus 1pt of space either side, like the reference's
        // HRFlowable.
        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),
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Placement
// ---------------------------------------------------------------------------

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,
    });
}

/// Place wrapped paragraph lines. Returns nothing; consumes height externally.
#[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) => {
            // Muted section label with a short rule beneath it.
            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,
        } => {
            // Role left; company (and optional extra) right; aside under the
            // role; dates/location under the company. Baselines are
            // deliberate: the role sits a hair above the company so it always
            // extracts first. Declared order follows how the eye reads the
            // block: a single-line left column reads row-wise (role, company,
            // extra, meta); a two-line left column (aside present) reads
            // column-wise (role, aside, company, extra, meta) — which is also
            // what position-based extractors recover.
            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,
                );
            }

            // Compute right-aligned positions first, then emit in declared
            // order (company before extra) regardless.
            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 } => {
            // Marker in the left margin zone, text indented 9pt·s.
            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,
        } => {
            // Name left, contact right, bottom-aligned. Name emits first so
            // it leads the text layer.
            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);
        }
    }
}

/// Lay the document out at a fixed scale.
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);
        // Drop spacers that land at the top of a page.
        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");
        // Width fits the leading words but not the hyphenated token, which
        // must move to the next line whole — never split at its hyphens.
        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);
    }
}