f-office-docx 0.2.2

DOCX model and Word's layout rules.
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
//! The font choice: the face that the layout draws a family with for a target, from the
//! caller's font database (`FontChoice`). The caller's own face of the family counts when the
//! target's font environment permits it. Else another family draws it: the one that the
//! configuration names (`fonts.use`) or F-Office's own rule names, or else the best compatible
//! font that the Compatifont descriptions of the database and the known ones name, with the line
//! that Word gives the family where the font environment records one. A symbol font that the
//! database lacks takes a symbol stand-in face (`symbols`).

mod symbols;

use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, LazyLock};

use compatifont::{Description, Level};
use f_office_fonts::environment::{FontEnvironment, OwnFace, WordLine};
use f_office_fonts::{
    FaceInfo, FamilyName, FileNotRead, FontDb, FontId, KerningSource, Ligature, MathBars,
    MathLimits, MathRadical, Os2Metrics, OutlineError, PathCommand, ScriptLevel, ShapeFailure,
    ShapeRequest, ShapedGlyph, version_number,
};
use f_office_units::scale::THOUSANDTHS;
use sha2::{Digest, Sha256};

use crate::params::{STRIKEOUT_WITHOUT_OS2, UNDERLINE_WITHOUT_POST};
use crate::profile::Profile;
use crate::text::StandInLines;
use crate::{ChosenFace, FaceMetrics, Fonts, KerningTable, OutlineCommand, SubstituteLayout};
use f_office_warnings::Name;
use symbols::SymbolDrawing;
pub(crate) use symbols::SymbolFonts;

/// The metrics to lay out with for Word's line `line`, in the drawing font's units, which also
/// measure its glyph advances. Decorations keep the drawing font's own values. Each part is
/// rounded to the nearest font unit, a half away from zero.
fn apply_line(line: &WordLine, own: FaceMetrics) -> FaceMetrics {
    let em = i64::from(own.units_per_em.max(1));
    let units = |thousandths: i16| {
        let value = i64::from(thousandths) * em;
        i16::try_from((value + value.signum() * (THOUSANDTHS / 2)) / THOUSANDTHS).unwrap_or(0)
    };
    let ascent = u16::try_from(units(line.ascent)).unwrap_or(0);
    FaceMetrics {
        hhea_ascender: units(line.ascent),
        hhea_descender: -units(line.descent),
        hhea_line_gap: 0,
        descent: u16::try_from(units(line.descent)).unwrap_or(0),
        line_top: ascent,
        script_top: ascent,
        ..own
    }
}

/// The family whose line the target's rule for stand-ins decides ([`StandInLines`]).
pub(crate) const HELVETICA: &str = "Helvetica";

/// The families that F-Office draws another family with, before any compatible font of that
/// family, unless the configuration names one (`fonts.use`): the family, and the family that
/// draws it, which its own file or its compatible fonts then draw. This is not Office behavior:
/// these families have no compatible font, and the families that draw them share their widths.
const DRAWN_WITH: &[(&str, &str)] = &[
    (HELVETICA, "Arial"),
    ("Times", "Times New Roman"),
    ("Courier", "Courier New"),
];

/// The descriptions of fonts that Compatifont knows, such as Carlito and Liberation Sans, which
/// come after the database's own.
static KNOWN: LazyLock<Vec<Description>> =
    LazyLock::new(|| compatifont::known().unwrap_or_default());

/// The font choice of one layout: the faces of a font database for a target, with the
/// target's font environment and its line of Helvetica. It answers the layout's font queries
/// ([`Fonts`]).
pub struct FontChoice<'a> {
    db: &'a FontDb,
    /// The target's font environment, whose lacking families count as missing.
    environment: Arc<FontEnvironment>,
    /// The families that the configuration adds to the fonts of Word's machine
    /// (`fonts.installed`), which count as the target's.
    added_families: Vec<FamilyName>,
    /// The families that the configuration draws families with on this computer (`fonts.use`),
    /// by the family that each draws.
    uses: Vec<(FamilyName, String)>,
    /// The Compatifont descriptions of the database, then the known ones.
    descriptions: Vec<Description>,
    /// The target's rule for the line metrics of stand-ins.
    stand_in_lines: StandInLines,
    /// Word's numbers of the symbol fonts, for their symbol stand-in faces.
    symbols: Arc<SymbolFonts>,
    /// The face of the database that draws the symbol stand-in faces, without which a symbol
    /// font that the database lacks has none.
    symbol_drawing: Option<SymbolDrawing>,
    /// The answers of [`FontChoice::choose`], by family and request. The answer depends on
    /// nothing else: `choose` reads its arguments, the three fields above, which do not change
    /// while the font choice lives, and the fixed table of stand-ins, and of the font
    /// database's own state it reads only whether a face's file loads, which the first load
    /// decides for every later one ([`FontDb::load`]). A layout makes its own font choice, so
    /// no answer outlives it. A family's key holds the name as the first request wrote it,
    /// which only the key's comparison reads: warnings and outputs take the run's own name
    /// from the layout.
    chosen: RefCell<HashMap<FamilyName, Answers>>,
    /// The answers of [`Fonts::kerning_source`], by face. The answer depends on the face's
    /// file and on the font environment, which do not change while the font choice lives.
    kerning_sources: RefCell<HashMap<FontId, KerningSource>>,
    /// What the descriptions say of each face's layout ([`FontChoice::described`]), by face. The
    /// answer depends on the face's file and on the descriptions and the font environment, which
    /// do not change while the font choice lives.
    described: RefCell<HashMap<FontId, Option<Described>>>,
    /// The font files that did not load when the font choice chose one of their faces, for
    /// the layout's warnings.
    not_read: RefCell<BTreeSet<FileNotRead>>,
}

/// What its description says of a face's layout against the target's own face of a family that
/// the face can replace.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Described {
    /// The face lays out as the target's own face, at this place of the font environment's faces.
    Exact(usize),
    /// The face has the layout of another version of the family than the target's own face.
    OtherVersion {
        family: String,
        made_for: String,
        target: String,
    },
}

/// The answers of [`FontChoice::choose`] for one family: one for each request asked so far.
type Answers = Vec<(Request, Option<ChosenFace>)>;

/// What a font query asks for a family besides its name: the style, and whether the document
/// names the family itself, so that a stand-in's line can hold over the font's own file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Request {
    bold: bool,
    italic: bool,
    named: bool,
}

impl Fonts for FontChoice<'_> {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        self.choose(family, bold, italic, true)
    }

    fn substitute(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        self.choose(family, bold, italic, false)
    }

    fn family_substitute(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<ChosenFace> {
        let substitute = self.environment.family_substitute(family.as_str())?;
        self.choose(&FamilyName::new(substitute), bold, italic, false)
    }

    fn metafile_face(
        &self,
        family: &FamilyName,
        charset: u8,
        pitch_and_family: u8,
    ) -> Option<FamilyName> {
        self.environment
            .metafile_face(family.as_str(), charset, pitch_and_family)
            .map(FamilyName::new)
    }

    fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
        match self.symbol_face(font) {
            Some(face) => face.widths.code(ch),
            None => self.db.glyph_id(font, ch),
        }
    }

    fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
        match self.symbol_face(font) {
            Some(face) => face.widths.advance(glyph),
            None => self.db.advance(font, glyph),
        }
    }

    fn kerning(&self, font: FontId, left: u32, right: u32, table: KerningTable) -> i32 {
        match table {
            KerningTable::FaceSource => self.db.kerning(font, left, right),
            KerningTable::KernTable => {
                self.db
                    .kerning_from(font, left, right, KerningSource::KernTable)
            }
        }
    }

    fn kerning_source(&self, font: FontId) -> KerningSource {
        // The kerning source that the font environment records for a face holds over the source
        // that the face's own tables give.
        *self
            .kerning_sources
            .borrow_mut()
            .entry(font)
            .or_insert_with(|| {
                self.db
                    .info(font)
                    .and_then(|info| {
                        self.environment
                            .recorded_kerning(
                                &info.family,
                                &info.subfamily,
                                info.version.as_deref()?,
                            )
                            .or_else(|| self.exact_own_face(font)?.kerning)
                    })
                    .unwrap_or_else(|| self.db.kerning_source(font))
            })
    }

    fn ligatures(&self, font: FontId, glyphs: &[u32]) -> Vec<Ligature> {
        self.db.ligatures(font, glyphs)
    }

    fn shape(
        &self,
        font: FontId,
        request: &ShapeRequest<'_>,
    ) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
        match self.symbol_face(font) {
            Some(face) => Ok(Self::symbol_shape(&face, request)),
            None => self.db.shape(font, request),
        }
    }

    fn files_not_read(&self) -> Vec<FileNotRead> {
        self.not_read.borrow().iter().cloned().collect()
    }

    fn family_name(&self, font: FontId) -> Option<String> {
        if let Some(face) = self.symbol_face(font) {
            return self.symbol_drawing_names(&face).map(|(family, _)| family);
        }
        self.db.info(font).map(|info| info.family.clone())
    }

    fn layout_family(&self, font: FontId) -> Option<String> {
        if let Some(face) = self.symbol_face(font) {
            return Some(Self::symbol_family(&face));
        }
        let info = self.db.info(font)?;
        let target = self.exact_own_face(font).map(|own| own.family.clone());
        Some(target.unwrap_or_else(|| info.family.clone()))
    }

    fn face_version(&self, font: FontId) -> Option<String> {
        if let Some(face) = self.symbol_face(font) {
            return self.symbol_drawing_names(&face)?.1;
        }
        let version = self.db.info(font)?.version.as_deref()?;
        Some(version_number(version).to_owned())
    }

    fn substitute_layout(&self, font: FontId) -> SubstituteLayout {
        // A symbol stand-in face lays out with Word's numbers of the target's file.
        if self.symbol_face(font).is_some() {
            return SubstituteLayout::Exact;
        }
        match self.described(font) {
            Some(Described::Exact(_)) => SubstituteLayout::Exact,
            Some(Described::OtherVersion {
                family,
                made_for,
                target,
            }) => SubstituteLayout::OtherVersion {
                family: Name::new(&family),
                made_for: Name::new(&made_for),
                target: Name::new(&target),
            },
            None => SubstituteLayout::Widths,
        }
    }

    fn classification(&self, font: FontId) -> Option<f_office_fonts::FaceClassification> {
        if let Some(face) = self.symbol_face(font) {
            return Some(face.widths.classification);
        }
        self.db.info(font).map(|info| info.classification)
    }

    fn target_face(&self, font: FontId) -> Option<(String, String)> {
        // A symbol stand-in face has the layout of the target's file of its font, and is the
        // target's own face where that file is.
        if let Some(face) = self.symbol_face(font) {
            return self.symbol_target_face(&face);
        }
        let info = self.db.info(font)?;
        let (name, version) = (info.postscript_name.as_ref()?, info.version.as_ref()?);
        // The face is the target's own when the font environment lists its family, style and
        // version as the target's own, whatever the file's PostScript name, or when its
        // description gives it the layout of the target's own face.
        (self
            .environment
            .is_target_file(&info.family, &info.subfamily, version)
            || self.exact_own_face(font).is_some())
        .then(|| (name.clone(), version.clone()))
    }

    fn bi_level_advance(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        match self.symbol_face(font) {
            Some(face) => Self::symbol_bi_level_advance(&face, glyph, ppem),
            None => self.db.bi_level_advance(font, glyph, ppem),
        }
    }

    fn device_width(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        match self.symbol_face(font) {
            Some(face) => face.widths.device_width(glyph, ppem),
            None => self.db.device_width(font, glyph, ppem),
        }
    }

    fn device_heights(&self, font: FontId, pels: u16) -> Option<(i16, i16)> {
        match self.symbol_face(font) {
            Some(face) => face.widths.heights(pels),
            None => self.db.device_heights(font, pels),
        }
    }

    fn ink(&self, font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
        if let Some(face) = self.symbol_face(font) {
            return self.symbol_ink(&face, glyph);
        }
        // An outline that the font cannot give is the cause of the layout's warning.
        let outline = self.db.outline(font, glyph)?;
        // The outline's points, control points too, as the bounding box of a TrueType
        // glyph counts them.
        let heights = outline.iter().flat_map(|command| {
            let heights = match *command {
                PathCommand::MoveTo(p) | PathCommand::LineTo(p) => [Some(p.y), None, None],
                PathCommand::QuadTo(c, p) => [Some(c.y), Some(p.y), None],
                PathCommand::CubicTo(c, d, p) => [Some(c.y), Some(d.y), Some(p.y)],
                PathCommand::Close => [None, None, None],
            };
            heights.into_iter().flatten()
        });
        // An outline without points, such as a space's, has no ink.
        let range = heights.fold(None, |range: Option<(f32, f32)>, y| {
            Some(range.map_or((y, y), |(low, high)| (low.min(y), high.max(y))))
        });
        Ok(range.map(|(low, high)| (font_units(low.floor()), font_units(high.ceil()))))
    }

    fn outline(&self, font: FontId, glyph: u32) -> Result<Vec<OutlineCommand>, OutlineError> {
        if let Some(face) = self.symbol_face(font) {
            return self.symbol_outline(&face, glyph);
        }
        // A TrueType glyph's points are whole font units; a point of another outline rounds to
        // the nearest.
        let at = |p: f_office_fonts::Point| [font_units(p.x.round()), font_units(p.y.round())];
        let outline = self.db.outline(font, glyph)?;
        Ok(outline
            .into_iter()
            .map(|command| match command {
                PathCommand::MoveTo(p) => OutlineCommand::MoveTo(at(p)),
                PathCommand::LineTo(p) => OutlineCommand::LineTo(at(p)),
                PathCommand::QuadTo(c, p) => OutlineCommand::QuadTo(at(c), at(p)),
                PathCommand::CubicTo(c, d, p) => OutlineCommand::CubicTo(at(c), at(d), at(p)),
                PathCommand::Close => OutlineCommand::Close,
            })
            .collect())
    }

    fn math_limits(&self, font: FontId) -> Option<MathLimits> {
        self.db.math_limits(font)
    }

    fn math_radical(&self, font: FontId) -> Option<MathRadical> {
        self.db.math_radical(font)
    }

    fn math_bars(&self, font: FontId) -> Option<MathBars> {
        self.db.math_bars(font)
    }

    fn math_skewed_fraction(&self, font: FontId) -> Option<f_office_fonts::MathSkewedFraction> {
        self.db.math_skewed_fraction(font)
    }

    fn math_limit_gaps(&self, font: FontId) -> Option<f_office_fonts::MathLimitGaps> {
        self.db.math_limit_gaps(font)
    }

    fn display_variant(&self, font: FontId, glyph: u32) -> Option<u32> {
        self.db.display_variant(font, glyph)
    }

    fn vertical_variant(&self, font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
        self.db.vertical_variant(font, glyph, least)
    }

    fn math_accent(&self, font: FontId) -> Option<f_office_fonts::MathAccent> {
        self.db.math_accent(font)
    }

    fn math_stretch_stack(&self, font: FontId) -> Option<f_office_fonts::MathStretchStack> {
        self.db.math_stretch_stack(font)
    }

    fn top_accent_attachment(&self, font: FontId, glyph: u32) -> Option<i32> {
        self.db.top_accent_attachment(font, glyph)
    }

    fn horizontal_construction(
        &self,
        font: FontId,
        glyph: u32,
    ) -> Option<f_office_fonts::HorizontalConstruction> {
        self.db.horizontal_construction(font, glyph)
    }

    fn flattened_accent(&self, font: FontId, glyph: u32) -> Option<u32> {
        self.db.flattened_accent(font, glyph)
    }

    fn dotless_form(&self, font: FontId, glyph: u32) -> Option<u32> {
        self.db.dotless_form(font, glyph)
    }

    fn italic_correction(&self, font: FontId, glyph: u32) -> Option<i32> {
        self.db.italic_correction(font, glyph)
    }
    fn space_after_script(&self, font: FontId) -> Option<i32> {
        self.db.space_after_script(font)
    }
    fn math_kern(
        &self,
        font: FontId,
        glyph: u32,
        corner: f_office_fonts::MathCorner,
        height: i32,
    ) -> Option<i32> {
        self.db.math_kern(font, glyph, corner, height)
    }

    fn script_glyph(&self, font: FontId, glyph: u32, level: ScriptLevel) -> Option<u32> {
        self.db.script_glyph(font, glyph, level)
    }
}

/// A whole height in font units, which fits in an `i32`.
#[expect(
    clippy::cast_possible_truncation,
    reason = "a glyph's coordinates are font units, far inside i32"
)]
fn font_units(value: f32) -> i32 {
    value as i32
}

impl<'a> FontChoice<'a> {
    /// A font choice of `db` for the target of `profile` with its font environment, with no
    /// answers kept yet.
    pub(crate) fn of(db: &'a FontDb, profile: &Profile) -> Self {
        Self::with_environment(db, profile.shared_font_environment(), profile)
    }

    /// A font choice of `db` for the target of `profile` with `environment` instead of its
    /// own, with no answers kept yet.
    #[cfg(test)]
    pub(crate) fn new(db: &'a FontDb, environment: &FontEnvironment, profile: &Profile) -> Self {
        Self::with_environment(db, Arc::new(environment.clone()), profile)
    }

    /// A font choice of `db` for the target of `profile` with `environment`.
    fn with_environment(
        db: &'a FontDb,
        environment: Arc<FontEnvironment>,
        profile: &Profile,
    ) -> Self {
        let descriptions = (db.descriptions().iter())
            .chain(KNOWN.iter())
            .cloned()
            .collect();
        Self {
            db,
            environment,
            added_families: profile.added_families().map(FamilyName::new).collect(),
            uses: (profile.used_families())
                .map(|(family, uses)| (FamilyName::new(family), uses.to_owned()))
                .collect(),
            descriptions,
            stand_in_lines: profile.stand_in_lines(),
            symbols: profile.symbol_fonts(),
            symbol_drawing: SymbolDrawing::of(db),
            chosen: RefCell::default(),
            kerning_sources: RefCell::default(),
            described: RefCell::default(),
            not_read: RefCell::default(),
        }
    }

    /// The face for a family, as [`FontChoice::choose_anew`] gives it the first time that the
    /// layout asks for the family and request, and from the font choice's answers after that.
    /// A face whose file does not load counts as missing: the choice searches again without it,
    /// so that another style, the older name or a stand-in draws the family, as for a face that
    /// the database lacks (a font file not read).
    fn choose(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
        named: bool,
    ) -> Option<ChosenFace> {
        let request = Request {
            bold,
            italic,
            named,
        };
        let known = self.chosen.borrow().get(family).and_then(|answers| {
            answers
                .iter()
                .find(|(asked, _)| *asked == request)
                .map(|(_, face)| *face)
        });
        if let Some(face) = known {
            return face;
        }
        // Each pass leaves one more face out, so the passes end within the number of faces.
        let mut not_loaded = Vec::new();
        let face = loop {
            let Some(chosen) = self.choose_anew(family, bold, italic, named, &not_loaded) else {
                break None;
            };
            if self.loads(chosen.font) {
                break Some(chosen);
            }
            not_loaded.push(chosen.font);
        };
        self.chosen
            .borrow_mut()
            .entry(family.clone())
            .or_default()
            .push((request, face));
        face
    }

    /// Whether the file of a chosen face loads ([`FontDb::load`]): the database reads a font
    /// folder's file when the font choice first chooses one of its faces. A face whose file
    /// did not load counts as missing ([`FontChoice::choose`]), and the font choice keeps the
    /// file for the layout's warning (a font file not read).
    fn loads(&self, font: FontId) -> bool {
        let Err(not_read) = self.db.load(font) else {
            return true;
        };
        self.not_read.borrow_mut().insert(not_read);
        false
    }

    /// The face for a family, among the faces other than `not_loaded`, the faces whose file
    /// did not load. When the document names the family itself (`named`), Word's line metrics
    /// for it hold also over the font's own file.
    fn choose_anew(
        &self,
        name: &FamilyName,
        bold: bool,
        italic: bool,
        named: bool,
        not_loaded: &[FontId],
    ) -> Option<ChosenFace> {
        let family = name.as_str();
        let drawn_with = self.drawn_with(family);
        // A local face cannot supply a name absent from the target's full font listing.
        // The document then tries its alternate through the usual font lookup.
        if !self.environment.permits(family)
            && drawn_with.is_empty()
            && self.environment.face_name(family).is_none()
        {
            return None;
        }
        // Older builds of the Monotype fonts have PostScript names without the "MT" that
        // documents name, such as `TimesNewRomanPS-Bold` for `TimesNewRomanPS-BoldMT`, and
        // older builds of some Microsoft fonts have family names without the " MS", such as
        // "Comic Sans" for "Comic Sans MS".
        let older = family
            .strip_suffix("MT")
            .or_else(|| family.strip_suffix(" MS"))
            .filter(|name| !name.is_empty());
        let accept = |id, info: &FaceInfo| !not_loaded.contains(&id) && self.permits_face(info);
        let found = self.db.query_with(name, bold, italic, accept).or_else(|| {
            older.and_then(|older| {
                self.db
                    .query_with(&FamilyName::new(older), bold, italic, accept)
            })
        });
        if let Some(font) = found {
            return self.chosen_own(font, family, (bold, italic), named);
        }
        // A face of another family in the same typographic family, such as Arial Narrow for
        // Arial, comes after the stand-ins.
        self.draw_stand_in(family, &drawn_with, (bold, italic), not_loaded)
            .or_else(|| self.symbol_stand_in(family, (bold, italic), named))
            .or_else(|| self.draw_face_name(family, (bold, italic), not_loaded))
            .or_else(|| {
                let font = self.db.query_typographic_with(name, bold, italic, accept)?;
                self.chosen_own(font, family, (bold, italic), named)
            })
    }

    /// The face `font` that the database found for the requested `family`, or `None` when its
    /// family is one that the target lacks, which is missing, and no stand-in draws it.
    fn chosen_own(
        &self,
        font: FontId,
        family: &str,
        (bold, italic): (bool, bool),
        named: bool,
    ) -> Option<ChosenFace> {
        let info = self.db.info(font)?;
        if self.environment.lacks(&info.family)
            && !self.added(&info.family)
            && !self.reference_stand_in(info)
        {
            return None;
        }
        let synthetic_bold = bold && info.light();
        let synthetic_italic = italic && !info.italic;
        let own = self.metrics(font)?;
        // Word's line for the family holds over its own file only where the document names the
        // family itself.
        let line = (self.line(family)).filter(|line| named && line.over_own_file);
        Some(ChosenFace {
            font,
            metrics: line.map_or(own, |line| apply_line(line, own)),
            synthetic_bold,
            synthetic_italic,
            stands_in: false,
        })
    }

    /// The target's own face that `font` lays out as, when its description gives it the layout
    /// of that face ([`FontChoice::described`]).
    fn exact_own_face(&self, font: FontId) -> Option<&OwnFace> {
        match self.described(font)? {
            Described::Exact(at) => self.environment.faces().get(at),
            Described::OtherVersion { .. } => None,
        }
    }

    /// What the descriptions say of the layout of `font`, kept for each face. A face lays out as
    /// the target's own face of a family when its file is one of its description's, by its
    /// SHA-256, and the description has an entry from a check against that family whose items
    /// reach the layout level: as the own face of the entry's version, or else as a face of
    /// another version than the own face's. A description belongs to a face of its family and
    /// version, and an entry that names scripts holds for every script of the face: the
    /// layout asks for the face, not for a script.
    fn described(&self, font: FontId) -> Option<Described> {
        if let Some(known) = self.described.borrow().get(&font) {
            return known.clone();
        }
        let answer = self.describe(font);
        self.described.borrow_mut().insert(font, answer.clone());
        answer
    }

    /// What the descriptions say of the layout of `font` ([`FontChoice::described`]).
    fn describe(&self, font: FontId) -> Option<Described> {
        let info = self.db.info(font)?;
        let version = version_number(info.version.as_deref()?);
        let description = self.descriptions.iter().find(|description| {
            FamilyName::new(description.family_name.as_str()).is(&info.family)
                && description.version == version
        })?;
        let file = description.font(&info.subfamily)?;
        let (bytes, _) = self.db.data(font)?;
        if sha256(bytes) != file.sha256.as_str() {
            return None;
        }
        let mut other = None;
        for entry in &description.compatible_with {
            if entry.basis != compatifont::Basis::Check || entry.level() != Some(Level::Layout) {
                continue;
            }
            let style = (entry.subfamilies.get(&info.subfamily)).unwrap_or(&info.subfamily);
            let mut own = (self.environment.faces().iter().enumerate())
                .filter(|(_, own)| own.family == entry.family_name && own.style == *style);
            let made_for = entry.version.as_deref();
            if let Some((at, _)) = own
                .clone()
                .find(|(_, own)| Some(version_number(&own.version)) == made_for)
            {
                return Some(Described::Exact(at));
            }
            if let (None, Some((_, own)), Some(made_for)) = (&other, own.next(), made_for) {
                other = Some(Described::OtherVersion {
                    family: entry.family_name.clone(),
                    made_for: made_for.to_owned(),
                    target: version_number(&own.version).to_owned(),
                });
            }
        }
        other
    }

    /// The families that draw `family` in its place, best first: the family that the
    /// configuration names for it (`fonts.use`), or else F-Office's own rule
    /// ([`DRAWN_WITH`]), and the families that draw that one in turn, then the compatible fonts
    /// of the last family, as Compatifont ranks them for the target's version of it.
    fn drawn_with(&self, family: &str) -> Vec<String> {
        let mut drawn_with: Vec<String> = Vec::new();
        let mut last = family.to_owned();
        // A configuration that names families in a ring stops at the first family that comes
        // again.
        while let Some(next) = self.next_family(&last) {
            let again = |name: &String| FamilyName::new(name.as_str()).is(next);
            if FamilyName::new(family).is(next) || drawn_with.iter().any(again) {
                break;
            }
            drawn_with.push(next.to_owned());
            last = next.to_owned();
        }
        let version = self.target_version(&last);
        for candidate in compatifont::choose(&self.descriptions, &last, version) {
            let name = &candidate.description.family_name;
            if !(drawn_with.iter()).any(|other| FamilyName::new(other.as_str()).is(name)) {
                drawn_with.push(name.clone());
            }
        }
        drawn_with
    }

    /// The family that draws `family` by the configuration (`fonts.use`) or else by
    /// F-Office's own rule ([`DRAWN_WITH`]).
    fn next_family(&self, family: &str) -> Option<&str> {
        (self.uses.iter())
            .find(|(of, _)| of.is(family))
            .map(|(_, uses)| uses.as_str())
            .or_else(|| {
                (DRAWN_WITH.iter())
                    .find(|(of, _)| FamilyName::from_static(of).is(family))
                    .map(|(_, uses)| *uses)
            })
    }

    /// The version of the target's own face of `family`, as Compatifont writes versions: of its
    /// regular face, else of its first face.
    fn target_version(&self, family: &str) -> Option<&str> {
        let faces = || (self.environment.faces().iter()).filter(|face| face.family == family);
        faces()
            .find(|face| face.style == "Regular")
            .or_else(|| faces().next())
            .map(|face| version_number(&face.version))
    }

    /// The line that Word gives `family` where the target's rule for stand-ins gives it one.
    fn line(&self, family: &str) -> Option<&WordLine> {
        (self.environment.line(family)).filter(|_| self.stand_in_lines.of_family(family))
    }

    fn permits_face(&self, info: &FaceInfo) -> bool {
        info.postscript_name
            .as_deref()
            .is_none_or(|name| self.environment.permits(name))
            || self.added(&info.family)
            || self.reference_stand_in(info)
    }

    /// Whether the configuration adds the family `family` to the fonts of Word's machine.
    fn added(&self, family: &str) -> bool {
        self.added_families.iter().any(|added| added.is(family))
    }

    // A face of a family that a stand-in draws, such as Helvetica, which Word draws with
    // Arial, is permitted when the font environment lists it as the target's own.
    fn reference_stand_in(&self, info: &FaceInfo) -> bool {
        !self.environment.available().is_empty()
            && info.version.as_deref().is_some_and(|version| {
                self.environment
                    .is_target_file(&info.family, &info.subfamily, version)
            })
            && !self.drawn_with(&info.family).is_empty()
    }

    /// The face that draws `family` in its place, of the first of the families `drawn_with`
    /// that the database has, among the faces other than `not_loaded`.
    fn draw_stand_in(
        &self,
        family: &str,
        drawn_with: &[String],
        (bold, italic): (bool, bool),
        not_loaded: &[FontId],
    ) -> Option<ChosenFace> {
        let accept = |id, _: &FaceInfo| !not_loaded.contains(&id);
        let font = drawn_with.iter().find_map(|other| {
            let other = FamilyName::new(other.as_str());
            self.db
                .query_with(&other, bold, italic, accept)
                .or_else(|| self.db.query_with(&other, false, false, accept))
        })?;
        let own = self.metrics(font)?;
        // Word draws the missing font itself, whose bold and italic faces are not known here.
        Some(ChosenFace {
            font,
            metrics: self.line(family).map_or(own, |line| apply_line(line, own)),
            synthetic_bold: false,
            synthetic_italic: false,
            stands_in: true,
        })
    }

    /// The stand-in of the target's face that `name` names by its full or PostScript name, as
    /// the font environment records it. The run's bold and italic beyond the face's own are
    /// synthetic, as for the target's face found by that name.
    fn draw_face_name(
        &self,
        name: &str,
        (bold, italic): (bool, bool),
        not_loaded: &[FontId],
    ) -> Option<ChosenFace> {
        let face = self.environment.face_name(name)?;
        let style = face.style.as_deref().map_or((bold, italic), |style| {
            (style.contains("Bold"), style.contains("Italic"))
        });
        let drawn_with = self.drawn_with(&face.family);
        let chosen = self.draw_stand_in(&face.family, &drawn_with, style, not_loaded)?;
        let info = self.db.info(chosen.font)?;
        Some(ChosenFace {
            synthetic_bold: bold && info.light(),
            synthetic_italic: italic && !info.italic,
            ..chosen
        })
    }

    /// The face metrics of `font` from its tables ([`metrics_of`]).
    fn metrics(&self, font: FontId) -> Option<FaceMetrics> {
        self.db.metrics(font).map(metrics_of)
    }
}

/// The face metrics of a face with the metrics `m` of its tables. A face without a `post` table
/// takes the underline of `UNDERLINE_WITHOUT_POST`, and one without an `OS/2` table the
/// strikeout of `STRIKEOUT_WITHOUT_OS2`.
fn metrics_of(m: &f_office_fonts::FontMetrics) -> FaceMetrics {
    let hhea_descent = u16::try_from(i32::from(m.hhea.descender).abs()).unwrap_or(0);
    let hhea_ascent = u16::try_from(m.hhea.ascender.max(0)).unwrap_or(0);
    let hhea_line =
        i32::from(m.hhea.ascender) - i32::from(m.hhea.descender) + i32::from(m.hhea.line_gap);
    // Without an OS/2 table, the line is the hhea line, and its top lies above the hhea
    // descent.
    let hhea_top = u16::try_from((hhea_line - i32::from(hhea_descent)).max(0)).unwrap_or(0);
    let (line_top, script_top) = m
        .os2
        .as_ref()
        .map_or((hhea_top, hhea_ascent), |os2| script_tops(os2, hhea_line));
    let em = i16::try_from(m.units_per_em).unwrap_or(i16::MAX);
    // A part of the em, which is no larger than the em.
    let part = |parts: i16| em / parts;
    let (underline_position, underline_thickness) = UNDERLINE_WITHOUT_POST;
    let (strikeout_position, strikeout_thickness) = STRIKEOUT_WITHOUT_OS2;
    FaceMetrics {
        units_per_em: m.units_per_em,
        hhea_ascender: m.hhea.ascender,
        hhea_descender: m.hhea.descender,
        hhea_line_gap: m.hhea.line_gap,
        descent: m.os2.as_ref().map_or(hhea_descent, line_descent),
        underline_position: m
            .underline
            .as_ref()
            .map_or(-part(underline_position), |u| u.position),
        underline_thickness: m
            .underline
            .as_ref()
            .map_or(part(underline_thickness), |u| u.thickness),
        strikeout_position: m
            .os2
            .as_ref()
            .map_or(part(strikeout_position), |os2| os2.strikeout.position),
        strikeout_thickness: m
            .os2
            .as_ref()
            .map_or(part(strikeout_thickness), |os2| os2.strikeout.thickness),
        superscript_offset: m.os2.as_ref().map_or(0, |os2| os2.superscript.y_offset),
        subscript_offset: m.os2.as_ref().map_or(0, |os2| os2.subscript.y_offset),
        superscript_size: m.os2.as_ref().map_or(0, |os2| os2.superscript.y_size),
        subscript_size: m.os2.as_ref().map_or(0, |os2| os2.subscript.y_size),
        line_top,
        script_top,
        east_asian: m.os2.as_ref().is_some_and(|os2| os2.east_asian),
        average_width: m.os2.as_ref().map_or(0, |os2| os2.average_width),
    }
}

/// The top of a font's line and its top without a line gap, above the baseline, for placing
/// superscripts: with `USE_TYPO_METRICS`, both are the typo ascender plus the typo line gap;
/// else the line's top is the larger of the `hhea` line (`hhea_line`) and the win line, less
/// `usWinDescent`, and the top without a gap is `usWinAscent`.
fn script_tops(os2: &Os2Metrics, hhea_line: i32) -> (u16, u16) {
    let clamp = |value: i32| u16::try_from(value.max(0)).unwrap_or(u16::MAX);
    if os2.use_typo_metrics {
        let top = clamp(i32::from(os2.typo.ascender) + i32::from(os2.typo.line_gap));
        return (top, top);
    }
    let (ascent, descent) = (i32::from(os2.win_ascent), i32::from(os2.win_descent));
    (
        clamp(hhea_line.max(ascent + descent) - descent),
        clamp(ascent),
    )
}

/// The depth that a line keeps below the baseline for a font: `usWinDescent`, or the typo
/// descender when the font sets `USE_TYPO_METRICS`.
fn line_descent(os2: &Os2Metrics) -> u16 {
    let typo = os2.typo.descender.unsigned_abs();
    if os2.use_typo_metrics {
        typo
    } else {
        os2.win_descent
    }
}

/// The SHA-256 of `bytes`, in lowercase hexadecimal, as Compatifont writes it.
fn sha256(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let digest = Sha256::digest(bytes);
    digest
        .iter()
        .fold(String::with_capacity(digest.len() * 2), |mut hex, byte| {
            let _ = write!(hex, "{byte:02x}");
            hex
        })
}

#[cfg(test)]
mod tests;