texrs 0.5.0

A TeX engine: Knuth's mouth and expander, lowered for a bytecode VM
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
//! The smallest honest stomach: text and font metrics into DVI pages.
//!
//! texrs could read a document and say what its words were, and could read and
//! write the DVI format, and had nothing joining the two -- `dvi::Writer` was
//! never called outside its own tests. So a book "ran" and produced no page.
//! This is the join: measure each character in a real font, break the text into
//! lines at a measure, stack the lines down a page, and ship the result.
//!
//! What this is NOT is `tex.web`'s stomach. TeX breaks a paragraph by looking at
//! every feasible sequence of breakpoints and minimising total badness
//! (§813-§890); this takes the first break that fits, which is what every
//! word processor before TeX did and what TeX was written to improve on. There
//! is no hyphenation, no glue stretching or shrinking, no page-breaking by
//! penalties, no maths, no boxes a document can nest. A paragraph set here and
//! the same paragraph set by tex will not agree line for line.
//!
//! It is a page you can open, which is the difference between a document that
//! produces nothing and one that produces something imperfect.

use crate::dvi::Writer;
use crate::tfm::Tfm;

/// DVI's unit: 1 sp, of which there are 65536 to the printer's point.
const SP: f64 = 65536.0;

/// The page and paragraph shape, in points.
pub struct Layout {
    /// Text width, TeX's `\hsize`.
    pub measure: f64,
    /// Text height, TeX's `\vsize`.
    pub height: f64,
    /// Distance between baselines, TeX's `\baselineskip`.
    pub leading: f64,
    /// Where the text starts, from the top-left of the page.
    pub margin: f64,
    /// The font's design size, at which its metrics are stated.
    pub size: f64,
}

impl Default for Layout {
    fn default() -> Self {
        // plain.tex's own page: 6.5in by 8.9in of text, 12pt leading, 1in
        // margins. A reader comparing against a tex run should not first have
        // to account for a different page.
        Self {
            measure: 469.75,
            height: 643.20,
            leading: 12.0,
            margin: 72.0,
            size: 10.0,
        }
    }
}

/// Set `text` in `font`, and return a DVI file.
///
/// The font is named in the DVI by `font_name` so a driver can find it; the
/// metrics come from the `.tfm` the caller opened, which is the same file the
/// driver will use to place the characters.
pub fn to_dvi(text: &str, font: &Tfm, font_name: &str, layout: &Layout) -> Vec<u8> {
    // The single-font path, kept for callers that have one .tfm and want it
    // used literally. Everything else goes through the chain.
    let chain = FontChain {
        fonts: vec![Loaded {
            tfm: font.clone(),
            name: font_name.to_string(),
        }],
        map: Vec::new(),
    };
    to_dvi_chain(text, &chain, layout)
}

/// Set `text` through a font chain, falling back per glyph.
pub fn to_dvi_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<u8> {
    let mut w = Writer::new("texrs");
    let at = (layout.size * SP) as i32;
    for (i, f) in chain.fonts.iter().enumerate() {
        // The design size and checksum have to match the .tfm or a driver
        // refuses the file: they are how it checks it has the font the document
        // was set in.
        w.define_font(i as u32, &f.name, at, f.tfm.checksum, at);
    }

    let lines = break_lines_chain(text, chain, layout);
    let per_page = ((layout.height / layout.leading).floor() as usize).max(1);

    for (page, chunk) in lines.chunks(per_page).enumerate() {
        let counts = [page as i32 + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        w.begin_page(counts);
        let mut current = usize::MAX;
        let mut baseline = layout.margin + layout.leading;
        for line in chunk {
            // Each line starts at the left margin, on its own baseline. DVI is
            // relative, so the position is pushed and popped rather than
            // tracked: a driver reading it never has to know where the last
            // line ended.
            w.push();
            w.down((baseline * SP) as i32);
            w.right((layout.margin * SP) as i32);
            set_line(&mut w, line, chain, layout, &mut current);
            w.pop();
            baseline += layout.leading;
        }
        w.end_page();
    }
    w.finish()
}

/// Put one line's characters down, switching fonts as the chain requires.
fn set_line(w: &mut Writer, line: &str, chain: &FontChain, layout: &Layout, current: &mut usize) {
    let mut chars = line.chars().peekable();
    while let Some(ch) = chars.next() {
        // Colour arrives in the text stream as U+0001 r,g,b U+0002 ... U+0003,
        // which the runtime writes where `\textcolor` was. DVI has no colour of
        // its own; a driver is told through a `\special`, and this pair is the
        // one dvipdfmx and dvips both read.
        if ch == '\u{1}' {
            let mut spec = String::new();
            for c in chars.by_ref() {
                if c == '\u{2}' {
                    break;
                }
                spec.push(c);
            }
            let parts: Vec<&str> = spec.split(',').collect();
            if parts.len() == 3 {
                w.special(&format!(
                    "color push rgb {} {} {}",
                    parts[0], parts[1], parts[2]
                ));
            }
            continue;
        }
        if ch == '\u{3}' {
            w.special("color pop");
            continue;
        }
        if let Some((f, slot)) = chain.resolve(ch) {
            // A font switch is an op in the file, so it is emitted only when the
            // font actually changes -- one per run of characters, not one per
            // character.
            if *current != f {
                w.font(f as u32);
                *current = f;
            }
            let width = chain.fonts[f]
                .tfm
                .char(slot)
                .map(|m| m.width)
                .unwrap_or(0.0);
            w.set_char(u32::from(slot), (width * layout.size * SP) as i32);
            continue;
        }
        // No font in the chain has it. The stand-in is set in the primary font
        // rather than dropped: a glyph that vanishes takes the meaning of the
        // line with it.
        let Some(text) = FontChain::approximate(ch) else {
            continue;
        };
        if *current != 0 {
            w.font(0);
            *current = 0;
        }
        for b in text.bytes() {
            let width = chain.fonts[0].tfm.char(b).map(|m| m.width).unwrap_or(0.0);
            w.set_char(u32::from(b), (width * layout.size * SP) as i32);
        }
    }
}

/// Break `text` into lines that fit the measure.
///
/// First fit, not best fit: a word is added while it still fits and starts a new
/// line when it does not. `tex.web` §813 does far better -- it considers every
/// feasible set of breakpoints for the whole paragraph at once -- and the
/// difference is visible as a raggeder right edge here.
pub fn break_lines(text: &str, font: &Tfm, layout: &Layout) -> Vec<String> {
    let chain = FontChain {
        fonts: vec![Loaded {
            tfm: font.clone(),
            name: String::from("cmr10"),
        }],
        map: Vec::new(),
    };
    break_lines_chain(text, &chain, layout)
}

/// The same, measuring through a font chain.
pub fn break_lines_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<String> {
    use rayon::prelude::*;
    // Paragraph-parallel. A paragraph is broken independently of its
    // neighbours: the measure is the same for all of them, and no state crosses
    // the blank line between two, so this fans out with nothing to
    // synchronise. `map` keeps them in order, which matters -- a book whose
    // paragraphs arrived in completion order would be a different book.
    let paras: Vec<&str> = text.split("\n\n").collect();
    paras
        .par_iter()
        .map(|para| break_paragraph(para, chain, layout))
        .reduce(Vec::new, |mut acc, mut more| {
            acc.append(&mut more);
            acc
        })
}

/// One paragraph, first-fit.
fn break_paragraph(para: &str, chain: &FontChain, layout: &Layout) -> Vec<String> {
    let space = chain.width(' ', layout.size);
    let mut lines = Vec::new();
    let mut line = String::new();
    let mut width = 0.0f64;
    for word in para.split_whitespace() {
        let ww = chain.width_of(word, layout.size);
        let need = match line.is_empty() {
            true => ww,
            false => width + space + ww,
        };
        if !line.is_empty() && need > layout.measure {
            lines.push(std::mem::take(&mut line));
            width = ww;
            line.push_str(word);
            continue;
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
        width = need;
    }
    if !line.is_empty() {
        lines.push(line);
    }
    lines
}

/// Find a `.tfm` by name, asking the TeX installation first.
///
/// `kpsewhich` is how every TeX program answers this question, so asking it
/// gets the same answer the driver will get when it goes looking for the same
/// font. The fixed paths are the fallback for a machine without it.
pub fn find_font(name: &str) -> Option<std::path::PathBuf> {
    let file = format!("{name}.tfm");
    if let Ok(out) = std::process::Command::new("kpsewhich").arg(&file).output() {
        if out.status.success() {
            let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if !p.is_empty() && std::path::Path::new(&p).exists() {
                return Some(std::path::PathBuf::from(p));
            }
        }
    }
    for root in [
        "/usr/local/texlive",
        "/Library/TeX/texbin/../../texmf-dist",
        "/usr/share/texmf-dist",
    ] {
        let hit = std::process::Command::new("find")
            .args([root, "-name", &file, "-maxdepth", "8"])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .next()
                    .unwrap_or("")
                    .to_string()
            })
            .filter(|p| !p.is_empty());
        if let Some(p) = hit {
            return Some(std::path::PathBuf::from(p));
        }
    }
    None
}

/// A font and the name a DVI file calls it by.
pub struct Loaded {
    pub tfm: Tfm,
    pub name: String,
}

/// A chain of fonts, tried in order for each character.
///
/// This is `luaotfload.add_fallback` in a TFM world, and it is the reason the
/// publication scripts required LuaTeX: a per-glyph fallback fixes missing
/// arrows, box drawing and symbols in EVERY context, verbatim code included,
/// and no other engine offered one. A `.tfm` addresses 256 slots, so a chain
/// here is not "another Unicode font" but another 256-slot font plus the map
/// saying which character lives in which of its slots.
///
/// Resolution order per character: the primary font's own map, then each
/// fallback in turn, then an ASCII stand-in for the shapes Computer Modern
/// simply does not have. What it never does is drop the character silently --
/// a glyph that vanishes takes the meaning of a line with it, and a line that
/// reads `a -- b` where the source said `a → b` is worse than one that says so.
pub struct FontChain {
    pub fonts: Vec<Loaded>,
    /// Where a character lives: which font of the chain, and which slot.
    map: Vec<(char, usize, u8)>,
}

/// Computer Modern's own positions for the characters these documents use.
///
/// `cmr10` is the text font; `cmsy10` is the symbol font and carries the
/// arrows, the set operators AND the section and paragraph marks -- those last
/// two are not in the text font, which is the mistake this table was written
/// with the first time: `§` was pointed at cmr10 slot 120 and printed an `x`.
///
/// The slots are read off what `tex` itself emits for `\S`, `\P`,
/// `\rightarrow`, `\leftarrow`, `\cup` and `\times` -- `dvitype` on its
/// output names the character each one set. A wrong slot here prints a wrong
/// glyph in silence, so guessing at them is not good enough.
const CM_SYMBOLS: &[(char, &str, u8)] = &[
    ('→', "cmsy10", 33),
    ('←', "cmsy10", 32),
    ('↔', "cmsy10", 36),
    ('−', "cmsy10", 0),
    ('×', "cmsy10", 2),
    ('÷', "cmsy10", 4),
    ('±', "cmsy10", 6),
    ('∪', "cmsy10", 91),
    ('∩', "cmsy10", 92),
    ('≤', "cmsy10", 20),
    ('≥', "cmsy10", 21),
    ('≠', "cmsy10", 54),
    ('·', "cmsy10", 1),
    ('∞', "cmsy10", 49),
    ('§', "cmsy10", 120),
    ('', "cmsy10", 123),
    ('†', "cmsy10", 121),
    ('‡', "cmsy10", 122),
];

/// Shapes Computer Modern has no glyph for, and the nearest honest stand-in.
///
/// Box drawing is the case that matters here: the documents draw trees with it,
/// and cm has no box-drawing at all. A rule could be drawn for each, but a
/// character grid built out of rules is a different picture; the ASCII shapes
/// keep the tree readable and keep the columns lined up, which is what the
/// drawing is for.
const APPROXIMATIONS: &[(char, &str)] = &[
    // Computer Modern has no copyright sign; `(c)` is what a reader of the text
    // would have written anyway.
    ('©', "(c)"),
    ('®', "(R)"),
    ('™', "(TM)"),
    ('—', "---"),
    ('–', "--"),
    ('…', "..."),
    ('─', "-"),
    ('│', "|"),
    ('├', "|-"),
    ('└', "`-"),
    ('┌', ",-"),
    ('┐', "-."),
    ('┘', "-'"),
    ('┬', "-,-"),
    ('┴', "-'-"),
    ('┼', "-+-"),
    ('•', "*"),
    ('“', "``"),
    ('”', "''"),
    ('‘', "`"),
    ('’', "'"),
];

impl FontChain {
    /// Load `primary` and each fallback by name, skipping any that is missing.
    ///
    /// A missing fallback is not an error: the chain degrades to what is
    /// installed, and the approximations catch what no loaded font carries.
    pub fn load(primary: &str, fallbacks: &[&str]) -> Result<FontChain, String> {
        let mut fonts = Vec::new();
        let path = find_font(primary).ok_or_else(|| format!("{primary}.tfm not found"))?;
        fonts.push(Loaded {
            tfm: Tfm::open(&path)?,
            name: primary.to_string(),
        });
        for f in fallbacks {
            if let Some(p) = find_font(f) {
                if let Ok(tfm) = Tfm::open(&p) {
                    fonts.push(Loaded {
                        tfm,
                        name: (*f).to_string(),
                    });
                }
            }
        }
        let mut map = Vec::new();
        for (ch, font_name, slot) in CM_SYMBOLS {
            if let Some(i) = fonts.iter().position(|f| f.name == *font_name) {
                // Only claim the slot if the font really defines it.
                if fonts[i].tfm.char(*slot).is_some() {
                    map.push((*ch, i, *slot));
                }
            }
        }
        Ok(FontChain { fonts, map })
    }

    /// Which font and slot carries `ch`, if any font in the chain does.
    pub fn resolve(&self, ch: char) -> Option<(usize, u8)> {
        // ASCII is the primary font's own, which is the common case and worth
        // answering before any search.
        if ch.is_ascii() && self.fonts[0].tfm.char(ch as u8).is_some() {
            return Some((0, ch as u8));
        }
        self.map
            .iter()
            .find(|(c, _, _)| *c == ch)
            .map(|(_, f, s)| (*f, *s))
    }

    /// The ASCII stand-in for a character no font in the chain carries.
    pub fn approximate(ch: char) -> Option<&'static str> {
        APPROXIMATIONS
            .iter()
            .find(|(c, _)| *c == ch)
            .map(|(_, s)| *s)
    }

    /// The width of `ch` in points at `size`, however it is being rendered.
    pub fn width(&self, ch: char, size: f64) -> f64 {
        // The colour markers are instructions to the driver, not glyphs: they
        // occupy no space on the page, and measuring them would push words onto
        // the next line for text that is not there.
        if matches!(ch, '\u{1}' | '\u{2}' | '\u{3}') || ch.is_control() {
            return 0.0;
        }
        if let Some((f, slot)) = self.resolve(ch) {
            return self.fonts[f].tfm.char(slot).map(|m| m.width).unwrap_or(0.0) * size;
        }
        if let Some(text) = Self::approximate(ch) {
            return self.fonts[0].tfm.width_of(text) * size;
        }
        0.0
    }

    /// The width of a whole string, resolving each character through the chain.
    ///
    /// A colour marker's SPEC -- the `r,g,b` between U+0001 and U+0002 -- is
    /// skipped whole. Measuring the three control characters as zero is not
    /// enough: the digits and commas between them are ordinary characters that
    /// the font does have, so a coloured word measured this way came out wider
    /// than it sets and every line after it broke short.
    pub fn width_of(&self, text: &str, size: f64) -> f64 {
        let mut total = 0.0;
        let mut in_spec = false;
        for ch in text.chars() {
            match ch {
                '\u{1}' => in_spec = true,
                '\u{2}' => in_spec = false,
                _ if in_spec => {}
                c => total += self.width(c, size),
            }
        }
        total
    }
}

/// The typefaces a document asked for.
///
/// `\setmainfont{Arimo}` is a statement about the book, and setting it in
/// Computer Modern anyway is the thing this exists to stop. What texrs can
/// honour depends on the output: a DVI names `.tfm` fonts and cannot carry an
/// OpenType one at all, while a PDF can name the fourteen fonts every reader
/// has. Arimo is metric-compatible with Arial, which is metric-compatible with
/// Helvetica, so that substitution is a real one rather than a shrug.
/// Where a document keeps the font it supplied with itself.
///
/// fontspec's `\setmainfont{Arimo}[Path=..., Extension=.ttf,
/// UprightFont=Arimo-VF]` does not name an INSTALLED family: it names a file
/// that ships beside the document. Looking that name up among the installed
/// families finds nothing, and `fc-match` answers anyway, with its default --
/// so the book was set in whatever that default happened to be, which is the
/// "everything comes out in the wrong face" complaint exactly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FontFile {
    /// `Path=` -- a directory, written with a trailing separator.
    pub path: Option<String>,
    /// `UprightFont=` -- the file's name, without its extension.
    pub upright: Option<String>,
    /// `Extension=` -- `.ttf`, including the dot.
    pub extension: Option<String>,
}

impl FontFile {
    /// Read the options fontspec was given: `Key=Value` separated by commas,
    /// with `{...}` groups around values that contain commas of their own.
    pub fn parse(options: &str) -> FontFile {
        let mut out = FontFile::default();
        for (key, value) in top_level_pairs(options) {
            let value = value.trim().trim_matches(|c| c == '{' || c == '}');
            match key.trim() {
                "Path" => out.path = Some(value.to_string()),
                "UprightFont" => out.upright = Some(value.to_string()),
                "Extension" => out.extension = Some(value.to_string()),
                _ => {}
            }
        }
        out
    }

    /// The file this names, looked for where it might actually be.
    ///
    /// `Path=` is written by whatever produced the document and is regularly an
    /// absolute path into a directory that no longer exists -- a build
    /// scratchpad, another machine. The fonts themselves ship beside the
    /// document, so a path that has gone stale is retried by its last
    /// component against the document's own directory.
    pub fn resolve(&self, near: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
        let upright = self.upright.as_deref()?;
        let extension = self.extension.as_deref().unwrap_or(".ttf");
        let file = format!("{upright}{extension}");
        if let Some(path) = &self.path {
            let full = std::path::Path::new(path).join(&file);
            if full.is_file() {
                return Some(full);
            }
            // The stale-path case: keep the directory the fonts are IN and look
            // for it beside the document instead.
            if let (Some(dir), Some(near)) = (last_component(path), near) {
                let beside = near.join(dir).join(&file);
                if beside.is_file() {
                    return Some(beside);
                }
            }
        }
        let beside = near?.join(&file);
        beside.is_file().then_some(beside)
    }
}

/// The last directory of a path written with a trailing separator.
fn last_component(path: &str) -> Option<&str> {
    path.trim_end_matches('/')
        .rsplit('/')
        .next()
        .filter(|c| !c.is_empty())
}

/// `Key=Value` pairs, splitting only on the commas that are not inside braces.
///
/// fontspec values nest: `UprightFeatures={RawFeature={axis={wght=400}}}` holds
/// commas in some documents, and splitting on every comma tears it apart and
/// makes the keys after it unreadable.
fn top_level_pairs(options: &str) -> Vec<(&str, &str)> {
    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    let bytes = options.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'{' | b'[' => depth += 1,
            b'}' | b']' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                if let Some(pair) = split_pair(&options[start..i]) {
                    out.push(pair);
                }
                start = i + 1;
            }
            _ => {}
        }
    }
    if let Some(pair) = split_pair(&options[start..]) {
        out.push(pair);
    }
    out
}

fn split_pair(text: &str) -> Option<(&str, &str)> {
    let at = text.find('=')?;
    Some((&text[..at], &text[at + 1..]))
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Families {
    pub main: Option<String>,
    /// The file `\setmainfont`s options named, when the document ships its
    /// own font rather than naming an installed one.
    pub main_file: FontFile,
    pub sans: Option<String>,
    pub mono: Option<String>,
}

/// What a requested family maps to among the fourteen fonts a PDF reader has.
///
/// The mapping is by what the face IS, not by its name: Arimo is Arial's
/// metrics, Liberation Sans is Arial's metrics, and Arial is Helvetica's, so
/// all three set at the same widths as Helvetica. A monospace request goes to
/// Courier whatever it was called. A name nothing is known about falls to
/// Helvetica rather than to Computer Modern, because a document that asked for
/// a font at all was asking not to be set in a book face.
pub fn base14_for(family: &str) -> &'static str {
    let f = family.to_ascii_lowercase();
    let mono = [
        "mono",
        "courier",
        "consolas",
        "menlo",
        "inconsolata",
        "sharetechmono",
        "jetbrains",
        "fira code",
        "source code",
    ];
    if mono.iter().any(|m| f.contains(m)) {
        return "Courier";
    }
    let serif = [
        "times",
        "serif",
        "georgia",
        "garamond",
        "minion",
        "palatino",
        "book",
        "charter",
        "libertine",
        "stix",
    ];
    if serif.iter().any(|m| f.contains(m)) {
        return "Times-Roman";
    }
    "Helvetica"
}

/// Set a document straight to PDF, honouring the font it asked for.
///
/// The DVI path names `.tfm` fonts and so can only ever set in Computer Modern;
/// a PDF can name the fourteen faces every reader has, which is how
/// `\setmainfont{Arimo}` becomes Helvetica's metrics rather than a book face.
/// Colour travels the same markers the DVI path reads and comes out as PDF's
/// own `rg` operator.
/// `page` is what `\pagecolor` asked for, painted under everything else.
/// `near` is the directory the document was read from, which is where a font
/// it ships with itself is looked for.
pub fn to_pdf(
    text: &str,
    families: &Families,
    layout: &Layout,
    page_colour: Option<crate::colour::Rgb>,
    near: Option<&std::path::Path>,
) -> Vec<u8> {
    use crate::pdf::{document, Font, Page};

    // The font the document asked for, EMBEDDED if it can be found: that is
    // the difference between a page set in Arimo's metrics and one set in
    // Arimo. Failing that, one of the fourteen, which gets the widths right
    // and the shapes wrong -- better than refusing to typeset.
    let requested = families.main.as_deref();
    // A font the document SHIPS is tried first: it is the one the document
    // actually meant, and its family name is regularly not installed at all.
    let embedded = families
        .main_file
        .resolve(near)
        .and_then(|file| embed_file(&file))
        .or_else(|| requested.and_then(embed_family));
    let main = embedded.clone().unwrap_or_else(|| {
        Font::Base14(requested.map(base14_for).unwrap_or("Helvetica").to_string())
    });

    // Measure in the face that will be printed. An embedded font carries its
    // own widths; without one, cmr10's are the closest thing installed, and a
    // line may then run a little long or short of the measure.
    let embedded_widths = match &main {
        Font::TrueType { widths, .. } => Some(widths.clone()),
        _ => None,
    };
    let metrics = find_font("cmr10").and_then(|p| Tfm::open(&p).ok());
    let width_of = |word: &str| -> f64 {
        if let Some(w) = &embedded_widths {
            // PDF widths are 1/1000 em, and codes below 32 are not in the table.
            return word
                .chars()
                .map(|c| {
                    let code = c as usize;
                    let at = code.saturating_sub(32);
                    let mille = w.get(at).copied().unwrap_or(500);
                    mille as f64 / 1000.0 * layout.size
                })
                .sum();
        }
        match &metrics {
            Some(f) => f.width_of(word) * layout.size,
            None => word.chars().count() as f64 * layout.size * 0.5,
        }
    };

    let lines = break_lines_measured(text, layout, &width_of);
    let per_page = ((layout.height / layout.leading).floor() as usize).max(1);

    let mut pages = Vec::new();
    for chunk in paginate(&lines, per_page) {
        let mut page = Page::letter();
        // The page is painted first, and only first: a fill drawn after the
        // text covers it, and a document that sets a dark page sets light
        // text to go on it -- so getting the order wrong loses the words.
        if let Some((r, g, b)) = page_colour {
            page.content.push_str(&format!(
                "{r} {g} {b} rg\n0 0 {} {} re\nf\n0 0 0 rg\n",
                page.width, page.height
            ));
        }
        let mut y = layout.height + layout.margin - layout.leading;
        for line in chunk {
            // A line is a sequence of RUNS, each with its own colour: the
            // markers turn colour on and off part way along it. Collapsing the
            // line to one colour state was the first attempt and drew none at
            // all, because the closing marker put the state back before
            // anything was emitted.
            let mut x = layout.margin;
            for (plain, colour) in colour_runs(line) {
                if plain.is_empty() {
                    continue;
                }
                if let Some((r, g, b)) = &colour {
                    page.content.push_str(&format!("{r} {g} {b} rg\n"));
                }
                page.text_in(main.clone(), layout.size, x, y, &plain);
                if colour.is_some() {
                    page.content.push_str("0 g\n");
                }
                x += width_of(&plain);
            }
            y -= layout.leading;
        }
        pages.push(page);
    }
    document(&pages)
}

/// Break lines with a caller-supplied measurer.
fn break_lines_measured(
    text: &str,
    layout: &Layout,
    width_of: &dyn Fn(&str) -> f64,
) -> Vec<String> {
    let space = width_of(" ");
    let mut lines = Vec::new();
    for para in text.split("\n\n") {
        // A forced break is its own line, so the paginator can see one. It has
        // to come out here because `split_whitespace` below counts a form feed
        // as whitespace and would silently drop it.
        for (part_number, part) in para.split(PAGE_BREAK).enumerate() {
            if part_number > 0 {
                lines.push(PAGE_BREAK.to_string());
            }
            let mut line = String::new();
            let mut width = 0.0f64;
            for word in part.split_whitespace() {
                let ww = width_of(word);
                let need = match line.is_empty() {
                    true => ww,
                    false => width + space + ww,
                };
                if !line.is_empty() && need > layout.measure {
                    lines.push(std::mem::take(&mut line));
                    width = ww;
                    line.push_str(word);
                    continue;
                }
                if !line.is_empty() {
                    line.push(' ');
                }
                line.push_str(word);
                width = need;
            }
            if !line.is_empty() {
                lines.push(line);
            }
        }
    }
    lines
}

/// Split a line into runs of text that share a colour.
///
/// Split broken lines into pages, at a forced break or when the page is full.
///
/// `chunks(per_page)` alone cannot do this: it fills every page to the brim,
/// so a `\newpage` has nowhere to say anything and a chapter starts wherever
/// the previous one happened to end.
fn paginate(lines: &[String], per_page: usize) -> Vec<Vec<&str>> {
    let mut pages: Vec<Vec<&str>> = Vec::new();
    let mut page: Vec<&str> = Vec::new();
    for line in lines {
        if line.chars().all(|c| c == PAGE_BREAK) && !line.is_empty() {
            // Consecutive breaks do not make blank pages: \clearpage after
            // \newpage is one break, which is what both mean together.
            if !page.is_empty() {
                pages.push(std::mem::take(&mut page));
            }
            continue;
        }
        if page.len() >= per_page {
            pages.push(std::mem::take(&mut page));
        }
        page.push(line);
    }
    if !page.is_empty() {
        pages.push(page);
    }
    pages
}

/// A forced page break, carried through the text the way colour is.
///
/// `\newpage` and `\clearpage` were defined by the prelude to expand to
/// nothing, so a book's title page, copyright page and first chapter ran
/// together into one stream of prose and the page count came out at half what
/// the document asks for. A form feed is what the character means, it survives
/// the run because it is not a word, and it is split out of the text BEFORE
/// words are, since Rust counts it as whitespace and would otherwise drop it.
pub const PAGE_BREAK: char = '\u{c}';

/// A stretch of a line and the colour it is drawn in, if it is not the default.
///
/// The three strings are the r, g and b the document asked for, kept verbatim
/// as written rather than parsed, because they are handed straight back to
/// PDF's `rg` operator.
type ColourRun = (String, Option<(String, String, String)>);

/// The markers the runtime writes turn colour on and off part way along a line,
/// so a line is not one string in one colour: `let x` may be black and `= 1`
/// blue. Each run is emitted with its own colour and its own position, which is
/// why the caller advances x by the width of what it just drew.
fn colour_runs(line: &str) -> Vec<ColourRun> {
    let mut runs = Vec::new();
    let mut current: Option<(String, String, String)> = None;
    let mut text = String::new();
    let mut chars = line.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '\u{1}' => {
                if !text.is_empty() {
                    runs.push((std::mem::take(&mut text), current.clone()));
                }
                let mut spec = String::new();
                for c in chars.by_ref() {
                    if c == '\u{2}' {
                        break;
                    }
                    spec.push(c);
                }
                let p: Vec<&str> = spec.split(',').collect();
                current = match p.len() == 3 {
                    true => Some((p[0].to_string(), p[1].to_string(), p[2].to_string())),
                    false => None,
                };
            }
            '\u{3}' => {
                if !text.is_empty() {
                    runs.push((std::mem::take(&mut text), current.clone()));
                }
                current = None;
            }
            c => text.push(c),
        }
    }
    if !text.is_empty() {
        runs.push((text, current));
    }
    runs
}

/// Find the file for a font family the document named.
///
/// `\setmainfont{Arimo}` names a FAMILY, not a path, and resolving one is what
/// fontconfig exists for. `fc-match` is asked first because it answers the way
/// every other program on the machine would; the directory walk is the fallback
/// for a machine without it. A family nothing matches returns `None` and the
/// caller falls back to naming one of the fourteen, which gets the widths right
/// and the shapes wrong -- better than refusing to typeset.
pub fn find_family(family: &str) -> Option<std::path::PathBuf> {
    if let Ok(out) = std::process::Command::new("fc-match")
        .args(["-f", "%{file}", family])
        .output()
    {
        if out.status.success() {
            let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
            let path = std::path::Path::new(&p);
            // fc-match ALWAYS answers, with a default when it has no match, so
            // the answer is only useful if it looks like the family asked for.
            if path.exists() && file_matches(path, family) {
                return Some(path.to_path_buf());
            }
        }
    }
    let wanted = normalise(family);
    for dir in [
        "/System/Library/Fonts",
        "/System/Library/Fonts/Supplemental",
        "/Library/Fonts",
        "/usr/share/fonts",
        "/usr/local/share/fonts",
    ] {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            if ext != "ttf" && ext != "otf" {
                continue;
            }
            if normalise(&path.file_stem()?.to_string_lossy()).starts_with(&wanted) {
                return Some(path);
            }
        }
    }
    None
}

/// A font file's stem, compared the way a family name should be: case and
/// spacing are not part of the identity.
fn file_matches(path: &std::path::Path, family: &str) -> bool {
    path.file_stem()
        .map(|s| normalise(&s.to_string_lossy()).starts_with(&normalise(family)))
        .unwrap_or(false)
}

fn normalise(name: &str) -> String {
    name.chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .collect::<String>()
        .to_ascii_lowercase()
}

/// Load a family as an embeddable PDF font: its outlines, and its own widths.
///
/// This is the difference between a page set in Arimo's METRICS and one set in
/// Arimo. The widths come from the font's `hmtx` through its `cmap`, so a line
/// is measured in the face it will be printed in rather than in Computer
/// Modern's.
pub fn embed_family(family: &str) -> Option<crate::pdf::Font> {
    embed_file(&find_family(family)?)
}

/// Embed the font FILE a document supplied itself.
///
/// fontspec `Path=` names a directory of `.ttf` files that ship WITH the
/// document, which is how a book uses a face nobody has installed. Looking
/// such a name up among the installed families finds nothing, and fc-match
/// answers with a default -- so the book was set in whatever that default was.
pub fn embed_file(path: &std::path::Path) -> Option<crate::pdf::Font> {
    let bytes = std::fs::read(path).ok()?;
    let sfnt = crate::sfnt::Sfnt::parse(bytes.clone()).ok()?;
    // A CFF-flavoured OpenType carries PostScript outlines, which a
    // /FontFile2 must not: that entry means a TrueType font program.
    if sfnt.is_cff() {
        return None;
    }
    let head = sfnt.head().ok()?;
    let hhea = sfnt.hhea().ok()?;
    let cmap = sfnt.cmap().ok()?;
    let advances = sfnt.advance_widths().ok()?;
    let upem = f64::from(head.units_per_em.max(1));
    let scale = |v: f64| (v * 1000.0 / upem).round() as i64;

    // PDF wants a width for every code in the range, in 1/1000 em, so a code
    // the font has no glyph for still needs an entry.
    let mut widths = Vec::with_capacity(224);
    for code in 32u32..=255 {
        let gid = cmap.get(&code).copied().unwrap_or(0) as usize;
        let adv = advances
            .get(gid)
            .or_else(|| advances.last())
            .copied()
            .unwrap_or(0);
        widths.push(scale(f64::from(adv)));
    }
    Some(crate::pdf::Font::TrueType {
        name: path.file_stem()?.to_string_lossy().replace(' ', ""),
        bytes,
        widths,
        bbox: [
            scale(f64::from(head.x_min)),
            scale(f64::from(head.y_min)),
            scale(f64::from(head.x_max)),
            scale(f64::from(head.y_max)),
        ],
        ascent: scale(f64::from(hhea.ascender)),
        descent: scale(f64::from(hhea.descender)),
    })
}

#[cfg(test)]
mod font_file_tests {
    use super::FontFile;

    /// The options a real book writes, verbatim.
    const REAL: &str = "\n    Path=/private/tmp/build/scifi2/docs/.fonts/,\n    Extension=.ttf,\n    RawFeature={fallback=symfb},\n    UprightFont=Arimo-VF,\n    UprightFeatures={RawFeature={axis={wght=400}}},\n    BoldFont=Arimo-VF,\n    BoldFeatures={RawFeature={axis={wght=700}}},\n";

    #[test]
    fn the_options_a_document_ships_its_font_with() {
        let spec = FontFile::parse(REAL);
        assert_eq!(spec.upright.as_deref(), Some("Arimo-VF"));
        assert_eq!(spec.extension.as_deref(), Some(".ttf"));
        assert_eq!(
            spec.path.as_deref(),
            Some("/private/tmp/build/scifi2/docs/.fonts/")
        );
    }

    #[test]
    fn a_value_holding_commas_does_not_tear_the_keys_after_it() {
        // `UprightFeatures={RawFeature={axis={wght=400}}}` sits BEFORE the keys
        // that matter in some documents. Splitting on every comma leaves
        // `wght=400}}}` as a key and loses everything past it.
        let spec = FontFile::parse("Extension=.ttf,Numbers={Proportional,Lining},UprightFont=X-VF");
        assert_eq!(spec.upright.as_deref(), Some("X-VF"));
        assert_eq!(spec.extension.as_deref(), Some(".ttf"));
    }

    #[test]
    fn a_stale_path_is_retried_beside_the_document() {
        // `Path=` is written when the document is BUILT and regularly points
        // into a scratch directory that is gone by the time it is read. The
        // fonts ship with the document, so the last component is tried there.
        let dir = std::env::temp_dir().join(format!("texrs_ff_{}", std::process::id()));
        let fonts = dir.join(".fonts");
        std::fs::create_dir_all(&fonts).expect("mkdir");
        let file = fonts.join("Arimo-VF.ttf");
        std::fs::write(&file, b"not really a font").expect("write");

        let spec =
            FontFile::parse("Path=/gone/for/good/.fonts/,Extension=.ttf,UprightFont=Arimo-VF");
        assert_eq!(spec.resolve(Some(&dir)), Some(file.clone()));
        // With nowhere to look, it resolves to nothing rather than to a guess.
        assert_eq!(spec.resolve(None), None);

        // A path that IS there wins outright.
        let direct = format!(
            "Path={}/,Extension=.ttf,UprightFont=Arimo-VF",
            fonts.display()
        );
        assert_eq!(FontFile::parse(&direct).resolve(None), Some(file));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn options_that_name_no_file_resolve_to_nothing() {
        // `\setmainfont{Georgia}` with no options at all must fall through to
        // the installed families rather than resolving to some file nearby.
        assert_eq!(
            FontFile::parse("").resolve(Some(std::path::Path::new("/tmp"))),
            None
        );
    }
}