kakemono 0.22.3

Convert PDF, Word and EPUB documents and web pages to HTML, Markdown, EPUB, LaTeX and JSON in Rust
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
//! The fonts a Word document is laid out with: those embedded in it, those
//! installed on the computer, and open fonts with the same metrics as
//! Word's usual fonts (Carlito for Calibri, Liberation for Times New Roman
//! and Arial...), which give the same line breaks.

use crate::word::fmt::model::{EmbeddedFont, FontKind};
use rustybuzz::ttf_parser;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Fonts given with [`add_font`], in the order they were given.
static ADDED: RwLock<Vec<Arc<Vec<u8>>>> = RwLock::new(Vec::new());

/// Adds a TrueType or OpenType font (or a collection) to those kakemono
/// lays out documents with and draws the text of SVG pictures with,
/// besides the fonts installed on the computer and in `KAKEMONO_FONT_DIRS`.
/// For where no font is installed: WebAssembly, small containers. It applies
/// to the documents converted after it, in the whole process, and cannot be
/// undone: the fonts are kept until the process ends. Returns the number of
/// faces in `data`.
///
/// # Errors
/// When `data` holds no font face with a family name kakemono can read.
pub fn add_font(data: Vec<u8>) -> anyhow::Result<usize> {
    let faces = (0..face_count(&data))
        .filter(|&index| ttf_parser::Face::parse(&data, index).is_ok_and(|face| !describe(&face).0.is_empty()))
        .count();
    if faces == 0 {
        anyhow::bail!("not a TrueType or OpenType font with a readable family name");
    }
    ADDED
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .push(Arc::new(data));
    Ok(faces)
}

/// The fonts given with [`add_font`].
pub(crate) fn added_fonts() -> Vec<Arc<Vec<u8>>> {
    ADDED.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}

/// The number of faces in the font file `data`: that of a collection's
/// header, bounded by what the file can hold (4 bytes of offset each), or 1.
fn face_count(data: &[u8]) -> u32 {
    let room = u32::try_from(data.len().saturating_sub(12) / 4).unwrap_or(u32::MAX);
    ttf_parser::fonts_in_collection(data).map_or(1, |count| count.min(room))
}

/// The message when no font can be loaded at all.
const NO_FONT: &str = "no font is installed: laying out pages needs at least one TrueType or OpenType font \
     (install one, name its folder in KAKEMONO_FONT_DIRS, or give it with add_font)";

/// Whether `path` names a font file by its extension.
fn is_font_file(path: &Path) -> bool {
    let ext = path
        .extension()
        .and_then(std::ffi::OsStr::to_str)
        .unwrap_or_default()
        .to_ascii_lowercase();
    matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc")
}

/// A loaded font face.
pub struct Face {
    /// The font file.
    pub data: Arc<Vec<u8>>,
    /// Index of the face in the file (collections).
    pub index: u32,
    /// Its metrics.
    pub metrics: Metrics,
    /// The family name it was found under.
    pub family: String,
}

/// The metrics of a face, in multiples of the font size.
#[derive(Debug, Clone, Copy)]
pub struct Metrics {
    /// Units per em.
    pub upem: f32,
    /// Height above the baseline Word reserves (`usWinAscent`).
    pub ascent: f32,
    /// Depth below the baseline Word reserves (`usWinDescent`).
    pub descent: f32,
    /// Extra space Word adds to a line (the external leading).
    pub leading: f32,
    /// Position of the underline below the baseline.
    pub underline_pos: f32,
    /// Thickness of the underline.
    pub underline_thickness: f32,
    /// Height of the strike-through line above the baseline.
    pub strike_pos: f32,
    /// Height of a lowercase x.
    pub x_height: f32,
    /// Height of a capital.
    pub cap_height: f32,
}

/// Identifier of a loaded face.
pub type FaceId = usize;

/// A family name with the bold and italic flags asked for.
type StyleKey = (String, bool, bool);

/// The face chosen for a style, and whether bold and italic must be faked.
type ChosenFace = (FaceId, bool, bool);

/// What text of a family in a style is set with: [`FontBook::style`].
#[derive(Debug, Clone, Copy)]
pub struct Style {
    /// The face.
    pub face: FaceId,
    /// Bold is faked.
    pub fake_bold: bool,
    /// Italic is faked.
    pub fake_italic: bool,
    /// The family is not installed (only a stand-in is).
    pub missing: bool,
    /// Built-in metrics of the family, if any.
    pub metric: Option<&'static super::metrics::MetricFace>,
}

/// A face found on the computer or in the document, before it is loaded.
#[derive(Debug, Clone)]
struct Candidate {
    source: Source,
    index: u32,
    bold: bool,
    italic: bool,
}

/// Where a font file comes from.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Source {
    /// A file on disk.
    File(PathBuf),
    /// A font embedded in the document.
    Embedded(usize),
    /// A font given with [`add_font`].
    Added(usize),
}

/// The fonts available to the layout.
pub struct FontBook {
    faces: Vec<Face>,
    by_family: HashMap<String, Vec<Candidate>>,
    loaded: HashMap<(Source, u32), FaceId>,
    embedded: Vec<Arc<Vec<u8>>>,
    /// The fonts given with [`add_font`] when the book was made.
    added: Vec<Arc<Vec<u8>>>,
    resolved: HashMap<StyleKey, Option<ChosenFace>>,
    /// [`FontBook::style`] by family as the document spells it, then by
    /// bold and italic (`2 * bold + italic`).
    styles: HashMap<String, [Option<Style>; 4]>,
    fallback_faces: Option<Vec<FaceId>>,
    kinds: HashMap<String, FontKind>,
}

/// Fonts with the same metrics as fonts Word documents often use: the
/// first one found is taken in place of the original, with the same line
/// breaks.
const ALIASES: &[(&str, &[&str])] = &[
    ("calibri", &["carlito"]),
    ("cambria", &["caladea"]),
    ("times new roman", &["liberation serif", "tinos"]),
    ("times", &["liberation serif", "tinos"]),
    ("arial", &["liberation sans", "arimo"]),
    ("helvetica", &["liberation sans", "arimo"]),
    ("arial narrow", &["liberation sans narrow"]),
    ("courier new", &["liberation mono", "cousine"]),
    ("courier", &["liberation mono", "cousine"]),
    ("georgia", &["gelasio"]),
    ("segoe ui", &["selawik"]),
    // The IPA fonts have the widths of the MS ones (names written with
    // full-width letters, "MS P明朝", are looked up as "ms p明朝").
    ("ms 明朝", &["ipamincho"]),
    ("ms mincho", &["ipamincho"]),
    ("ms p明朝", &["ipapmincho"]),
    ("ms pmincho", &["ipapmincho"]),
    ("ms ゴシック", &["ipagothic"]),
    ("ms gothic", &["ipagothic"]),
    ("ms pゴシック", &["ipapgothic"]),
    ("ms pgothic", &["ipapgothic"]),
];

/// Fonts that only look like the original (their widths differ): used to
/// draw text measured with the original's metrics (`metrics`), or when
/// nothing better is known.
const LOOKALIKES: &[(&str, &[&str])] = &[
    ("calibri light", &["carlito"]),
    // Century Gothic was drawn on the metrics of ITC Avant Garde Gothic,
    // which these two follow.
    ("century gothic", &["urw gothic", "tex gyre adventor"]),
    ("verdana", &["dejavu sans"]),
    ("tahoma", &["dejavu sans"]),
    ("segoe ui", &["open sans", "noto sans", "dejavu sans"]),
    ("trebuchet ms", &["dejavu sans"]),
    ("symbol", &["dejavu sans", "freeserif"]),
    ("wingdings", &["dejavu sans", "freeserif"]),
    ("cambria math", &["dejavu serif", "freeserif"]),
    ("times new roman", &["freeserif"]),
    ("arial", &["freesans"]),
    ("courier new", &["freemono"]),
    ("明朝", &["ipaexmincho", "noto serif cjk jp"]),
    ("ms 明朝", &["noto serif cjk jp"]),
    ("ms mincho", &["noto serif cjk jp"]),
    ("ms p明朝", &["ipaexmincho", "noto serif cjk jp"]),
    ("ms pmincho", &["ipaexmincho", "noto serif cjk jp"]),
    ("游明朝", &["ipaexmincho", "noto serif cjk jp"]),
    ("yu mincho", &["ipaexmincho", "noto serif cjk jp"]),
    ("ms ゴシック", &["noto sans cjk jp"]),
    ("ms gothic", &["noto sans cjk jp"]),
    ("ms pゴシック", &["ipaexgothic", "noto sans cjk jp"]),
    ("ms pgothic", &["ipaexgothic", "noto sans cjk jp"]),
    ("游ゴシック", &["ipaexgothic", "noto sans cjk jp"]),
    ("yu gothic", &["ipaexgothic", "noto sans cjk jp"]),
    ("メイリオ", &["ipaexgothic", "noto sans cjk jp"]),
    ("meiryo", &["ipaexgothic", "noto sans cjk jp"]),
];

/// Families tried, in order, for characters the chosen font lacks.
const FALLBACKS: &[&str] = &[
    "liberation sans",
    "dejavu sans",
    "noto sans",
    "freeserif",
    "noto sans cjk sc",
    "wenquanyi zen hei",
    "noto sans symbols",
    "noto sans symbols2",
    "dejavu serif",
];

/// The family used when nothing else is found.
const LAST_RESORT: &[&str] = &["liberation serif", "dejavu serif", "dejavu sans", "freeserif"];

impl FontBook {
    /// The fonts of the computer and those `embedded` in the document.
    pub fn new(embedded: &[EmbeddedFont], kinds: &HashMap<String, FontKind>) -> Self {
        let mut book = FontBook {
            faces: Vec::new(),
            by_family: HashMap::new(),
            loaded: HashMap::new(),
            embedded: Vec::new(),
            added: added_fonts(),
            resolved: HashMap::new(),
            styles: HashMap::new(),
            fallback_faces: None,
            kinds: kinds.clone(),
        };
        for dir in font_dirs() {
            book.scan(&dir, 0);
        }
        for at in 0..book.added.len() {
            let data = Arc::clone(&book.added[at]);
            book.add_faces(&data, &Source::Added(at));
        }
        for (at, font) in embedded.iter().enumerate() {
            book.embedded.push(Arc::new(font.data.clone()));
            book.by_family.entry(font.family.to_lowercase()).or_default().insert(
                0,
                Candidate {
                    source: Source::Embedded(at),
                    index: 0,
                    bold: font.bold,
                    italic: font.italic,
                },
            );
        }
        book
    }

    /// Adds the font files under `dir`.
    fn scan(&mut self, dir: &Path, depth: usize) {
        const MAX_DEPTH: usize = 6;
        let Ok(entries) = std::fs::read_dir(dir) else { return };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if depth < MAX_DEPTH {
                    self.scan(&path, depth + 1);
                }
                continue;
            }
            if !is_font_file(&path) {
                continue;
            }
            let Ok(data) = std::fs::read(&path) else { continue };
            self.add_faces(&data, &Source::File(path));
        }
    }

    /// Adds the faces of the font file `data`, read from `source`.
    fn add_faces(&mut self, data: &[u8], source: &Source) {
        for index in 0..face_count(data) {
            let Ok(face) = ttf_parser::Face::parse(data, index) else {
                continue;
            };
            let (families, bold, italic) = describe(&face);
            for family in families {
                self.by_family.entry(family).or_default().push(Candidate {
                    source: source.clone(),
                    index,
                    bold,
                    italic,
                });
            }
        }
    }

    /// The face of `family` in a style, the faked styles and whether the
    /// family is missing, and its built-in metrics, cached: resolving them
    /// for each run of text was a sixth of the layout's time.
    pub fn style(&mut self, family: &str, bold: bool, italic: bool) -> Style {
        let at = usize::from(bold) * 2 + usize::from(italic);
        if let Some(style) = self.styles.get(family).and_then(|styles| styles[at]) {
            return style;
        }
        let (face, fake_bold, fake_italic) = self.face(family, bold, italic);
        let style = Style {
            face,
            fake_bold,
            fake_italic,
            missing: !self.has_family(family),
            metric: super::metrics::lookup(family, bold, italic),
        };
        self.styles.entry(family.to_string()).or_default()[at] = Some(style);
        style
    }

    /// The face for `family` in the given style: the family itself, a font
    /// with the same metrics, or a fallback; and whether bold and italic
    /// must be faked.
    pub fn face(&mut self, family: &str, bold: bool, italic: bool) -> (FaceId, bool, bool) {
        let key = (family.to_lowercase(), bold, italic);
        if let Some(found) = self.resolved.get(&key) {
            return found.unwrap_or_else(|| self.last_resort(bold, italic));
        }
        let mut names = vec![key.0.clone()];
        let plain = table_name(&key.0);
        for table in [ALIASES, LOOKALIKES] {
            for (_, aliases) in table.iter().filter(|(name, _)| *name == plain) {
                names.extend(aliases.iter().map(|alias| (*alias).to_string()));
            }
        }
        let mut found = None;
        for name in &names {
            if let Some(face) = self.load_family(name, bold, italic) {
                found = Some(face);
                break;
            }
        }
        if found.is_none() {
            // A stand-in of the same kind.
            let lower = key.0.as_str();
            let kind = self.kinds.get(lower).copied().unwrap_or_else(|| guess_kind(lower));
            let stand_ins: &[&str] = match kind {
                FontKind::Serif => &["liberation serif", "dejavu serif", "freeserif"],
                FontKind::Mono => &["liberation mono", "dejavu sans mono", "freemono"],
                FontKind::Sans | FontKind::Symbol => &["liberation sans", "dejavu sans", "freesans"],
            };
            for name in stand_ins {
                if let Some(face) = self.load_family(name, bold, italic) {
                    found = Some(face);
                    break;
                }
            }
        }
        self.resolved.insert(key, found);
        found.unwrap_or_else(|| self.last_resort(bold, italic))
    }

    /// Whether `family` (or a font with its metrics) is available.
    pub fn has_family(&self, family: &str) -> bool {
        let name = family.to_lowercase();
        let plain = table_name(&name);
        self.by_family.contains_key(&name)
            || ALIASES
                .iter()
                .find(|(alias, _)| *alias == plain)
                .is_some_and(|(_, aliases)| aliases.iter().any(|alias| self.by_family.contains_key(*alias)))
    }

    /// For an East Asian family `family` that is not installed, the
    /// Western family of its kind (Times New Roman for a Mincho, Arial for
    /// a Gothic) that sets its Latin letters and digits: the stand-ins of
    /// the East Asian text (the IPA P fonts) have wider digits than the MS
    /// P fonts' half an em. `None` for another family.
    pub fn latin_stand_in(&self, family: &str) -> Option<&'static str> {
        let lower = family.to_lowercase();
        let plain = table_name(&lower);
        let east_asian = !plain.is_ascii()
            || LOOKALIKES
                .iter()
                .any(|(name, aliases)| *name == plain && aliases.iter().any(|alias| alias.contains("cjk")));
        if !east_asian || self.by_family.contains_key(&lower) {
            return None;
        }
        Some(match guess_kind(&plain) {
            FontKind::Serif => "Times New Roman",
            FontKind::Mono => "Courier New",
            FontKind::Sans | FontKind::Symbol => "Arial",
        })
    }

    /// Checks that a face can be loaded at all (an installed font, one
    /// embedded in the document or one given with [`add_font`]): the
    /// layouts call it before laying out, so that none reaches the panic of
    /// [`FontBook::last_resort`].
    ///
    /// # Errors
    /// When no face can be loaded.
    pub fn require_font(&mut self) -> anyhow::Result<()> {
        match self.try_last_resort(false, false) {
            Some(_) => Ok(()),
            None => anyhow::bail!(NO_FONT),
        }
    }

    /// The face used when a family is not found.
    fn last_resort(&mut self, bold: bool, italic: bool) -> (FaceId, bool, bool) {
        // `require_font` has checked that there is one.
        self.try_last_resort(bold, italic).expect(NO_FONT)
    }

    /// The face used when a family is not found: a usual font, else the
    /// first family (by name) whose face loads; `None` when none does.
    fn try_last_resort(&mut self, bold: bool, italic: bool) -> Option<(FaceId, bool, bool)> {
        for name in LAST_RESORT {
            if let Some(face) = self.load_family(name, bold, italic) {
                return Some(face);
            }
        }
        // Any font at all, chosen the same way at every run.
        let mut names: Vec<String> = self.by_family.keys().cloned().collect();
        names.sort_unstable();
        names.into_iter().find_map(|name| self.load_family(&name, bold, italic))
    }

    /// Loads the best face of family `name` for the style.
    fn load_family(&mut self, name: &str, bold: bool, italic: bool) -> Option<(FaceId, bool, bool)> {
        let candidates = self.by_family.get(name)?.clone();
        let score = |cand: &Candidate| u8::from(cand.bold != bold) * 2 + u8::from(cand.italic != italic);
        let best = candidates.iter().min_by_key(|cand| score(cand))?;
        let id = self.load(best.source.clone(), best.index, name)?;
        Some((id, bold && !best.bold, italic && !best.italic))
    }

    /// Loads a face once.
    fn load(&mut self, source: Source, index: u32, family: &str) -> Option<FaceId> {
        if let Some(&id) = self.loaded.get(&(source.clone(), index)) {
            return Some(id);
        }
        let data = match &source {
            Source::File(path) => Arc::new(std::fs::read(path).ok()?),
            Source::Embedded(at) => self.embedded.get(*at)?.clone(),
            Source::Added(at) => self.added.get(*at)?.clone(),
        };
        let face = ttf_parser::Face::parse(&data, index).ok()?;
        let metrics = metrics(&face);
        self.faces.push(Face {
            data: data.clone(),
            index,
            metrics,
            family: family.to_string(),
        });
        let id = self.faces.len() - 1;
        self.loaded.insert((source, index), id);
        Some(id)
    }

    /// The loaded face `id`.
    pub fn get(&self, id: FaceId) -> &Face {
        &self.faces[id]
    }

    /// All loaded faces.
    pub fn faces(&self) -> &[Face] {
        &self.faces
    }

    /// The fallback faces, loaded once (regular style).
    pub fn fallbacks(&mut self) -> Vec<FaceId> {
        if let Some(faces) = &self.fallback_faces {
            return faces.clone();
        }
        let mut faces = Vec::new();
        for name in FALLBACKS {
            if let Some((id, _, _)) = self.load_family(name, false, false) {
                faces.push(id);
            }
        }
        self.fallback_faces = Some(faces.clone());
        faces
    }

    /// Whether face `id` has a glyph for `ch`.
    pub fn covers(&self, id: FaceId, ch: char) -> bool {
        let face = &self.faces[id];
        ttf_parser::Face::parse(&face.data, face.index)
            .ok()
            .and_then(|parsed| parsed.glyph_index(ch))
            .is_some()
    }
}

/// A family name `name` (lowercase) as the tables of fonts name it: its
/// full-width letters, digits and spaces (MS P明朝) made plain.
pub(crate) fn table_name(name: &str) -> String {
    const FULL_WIDTH_OFFSET: u32 = 0xFEE0;
    name.chars()
        .map(|ch| match ch {
            '\u{3000}' => ' ',
            '\u{FF01}'..='\u{FF5E}' => char::from_u32(u32::from(ch) - FULL_WIDTH_OFFSET).unwrap_or(ch),
            _ => ch,
        })
        .collect::<String>()
        .to_lowercase()
}

/// The kind of a font from its name, when the document does not say.
fn guess_kind(name: &str) -> FontKind {
    const SERIF_WORDS: &[&str] = &[
        "times",
        "roman",
        "serif",
        "garamond",
        "georgia",
        "book",
        "mincho",
        "明朝",
        "明體",
        "宋体",
        "mingliu",
        "simsun",
        "batang",
        "myeongjo",
        "cambria",
        "palatino",
        "baskerville",
        "minion",
        "caslon",
        "bodoni",
        "century",
    ];
    const MONO_WORDS: &[&str] = &["mono", "courier", "consolas", "code", "typewriter"];
    // "-Roman" after a family names its upright style, not a serif
    // (Helvetica-Roman, MetaNormalLF-Roman).
    let name = name.strip_suffix("-roman").unwrap_or(name);
    // A gothic is a sans serif (Century Gothic, MS Gothic, ゴシック).
    if name.contains("sans") || name.contains("gothic") || name.contains("ゴシック") {
        FontKind::Sans
    } else if MONO_WORDS.iter().any(|word| name.contains(word)) {
        FontKind::Mono
    } else if SERIF_WORDS.iter().any(|word| name.contains(word)) {
        FontKind::Serif
    } else {
        FontKind::Sans
    }
}

/// The family names (lowercase), boldness and italic of a face.
fn describe(face: &ttf_parser::Face<'_>) -> (Vec<String>, bool, bool) {
    let mut families = Vec::new();
    for name in face.names() {
        let id = name.name_id;
        if id != ttf_parser::name_id::FAMILY && id != ttf_parser::name_id::TYPOGRAPHIC_FAMILY {
            continue;
        }
        if let Some(text) = name.to_string() {
            let text = text.to_lowercase();
            if !families.contains(&text) {
                families.push(text);
            }
        }
    }
    let bold = face.is_bold() || face.weight().to_number() >= 600;
    (families, bold, face.is_italic() || face.is_oblique())
}

/// The metrics of a face, as Word uses them.
fn metrics(face: &ttf_parser::Face<'_>) -> Metrics {
    let upem = f32::from(face.units_per_em());
    let tables = face.tables();
    let (win_ascent, win_descent) = tables
        .os2
        .map(|os2| {
            (
                f32::from(os2.windows_ascender()),
                f32::from(os2.windows_descender()).abs(),
            )
        })
        .filter(|(ascent, descent)| ascent + descent > 0.0)
        .unwrap_or_else(|| (f32::from(face.ascender()), f32::from(face.descender()).abs()));
    let hhea_height = f32::from(face.ascender()) - f32::from(face.descender());
    let leading = (f32::from(face.line_gap()) - ((win_ascent + win_descent) - hhea_height)).max(0.0);
    let underline = face.underline_metrics();
    let strike = face.strikeout_metrics();
    Metrics {
        upem,
        ascent: win_ascent / upem,
        descent: win_descent / upem,
        leading: leading / upem,
        underline_pos: underline.map_or(0.1, |line| -f32::from(line.position) / upem),
        underline_thickness: underline.map_or(0.05, |line| f32::from(line.thickness).max(1.0) / upem),
        strike_pos: strike.map_or(0.25, |line| f32::from(line.position) / upem),
        x_height: face.x_height().map_or(0.45, |height| f32::from(height) / upem),
        cap_height: face.capital_height().map_or(0.65, |height| f32::from(height) / upem),
    }
}

/// The directories with installed fonts, and those named in
/// `KAKEMONO_FONT_DIRS` (separated like `PATH`).
fn font_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(extra) = std::env::var_os("KAKEMONO_FONT_DIRS") {
        dirs.extend(std::env::split_paths(&extra));
    }
    let home = std::env::var_os("HOME").map(PathBuf::from);
    if cfg!(target_os = "windows") {
        let windir = std::env::var_os("WINDIR").map_or_else(|| PathBuf::from("C:\\Windows"), PathBuf::from);
        dirs.push(windir.join("Fonts"));
        if let Some(local) = std::env::var_os("LOCALAPPDATA") {
            dirs.push(PathBuf::from(local).join("Microsoft\\Windows\\Fonts"));
        }
    } else if cfg!(target_os = "macos") {
        dirs.push("/System/Library/Fonts".into());
        dirs.push("/Library/Fonts".into());
        if let Some(home) = &home {
            dirs.push(home.join("Library/Fonts"));
        }
    } else {
        dirs.push("/usr/share/fonts".into());
        dirs.push("/usr/local/share/fonts".into());
        if let Some(home) = &home {
            dirs.push(home.join(".local/share/fonts"));
            dirs.push(home.join(".fonts"));
        }
    }
    dirs
}

#[cfg(test)]
mod tests {
    use super::{FontKind, guess_kind};

    #[test]
    fn a_roman_style_is_not_a_serif() {
        assert_eq!(guess_kind("times new roman"), FontKind::Serif);
        assert_eq!(guess_kind("metanormallf-roman"), FontKind::Sans);
        assert_eq!(guess_kind("century gothic"), FontKind::Sans);
        assert_eq!(guess_kind("ms p明朝"), FontKind::Serif);
    }
}