f-office-fonts 0.3.0

Font database, metrics and outlines.
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
//! A target's font environment: what the layout knows of the fonts of the target.
//!
//! - The families that the target lacks, each with the family substitute that the target draws
//!   it with, when one is known. A document that names such a family gets the substitute, even
//!   where the caller has a face of the family.
//! - The requested names of the target's full font listing, when the target has one. A name
//!   outside the listing is absent, even where the caller has a face of it, and the listing
//!   takes precedence over the lacking families.
//! - The faces that the layout takes as the target's own, by family, style and version, each
//!   with the kerning source that the layout takes for it when that is not the source of the
//!   face's own tables.
//! - The faces that the target's font mapper gives a metafile font of a face that the target
//!   lacks, by the font's character set and pitch and family, when they are known, and the
//!   names outside the full listing that the mapper knows, which it does not answer so.
//! - The lines that Word gives some families that it draws with another family's face, as the
//!   parts of a line above and below the baseline.
//! - Other names of the target's faces, their full and PostScript names, by which a document can
//!   name a face of a family that another family's face then draws.
//!
//! A font environment is a text file of `[[face]]`, `[[lacking]]`, `[[available]]`,
//! `[[metafile_faces]]`, `[[mapper_name]]`, `[[line]]` and `[[face_name]]` sections
//! with `key = value` lines. A value is a whole number or a text in double quotes, a strict
//! subset of TOML's basic strings: a backslash stands before each backslash and each double
//! quote of the text, and the text holds no control character. The reader refuses what it does
//! not decode, a key that a section holds twice, and a face, family or name that the file
//! holds twice; the writer refuses a text with a control character.

use std::fmt::{self, Write as _};

use crate::form::{self, Section};
use crate::{FamilyName, KerningSource};

/// The font environment of a target.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FontEnvironment {
    faces: Vec<OwnFace>,
    lacking: Vec<Lacking>,
    available: Vec<FamilyName>,
    metafile_faces: Vec<MetafileFaces>,
    mapper_names: Vec<FamilyName>,
    lines: Vec<WordLine>,
    face_names: Vec<FaceName>,
}

/// The line that Word gives a family, in thousandths of an em of the face that draws it, in
/// place of that face's own line, where another family's face draws the family.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WordLine {
    /// The family.
    pub family: FamilyName,
    /// The part of the line above the baseline.
    pub ascent: i16,
    /// The part of the line below the baseline.
    pub descent: i16,
    /// Whether the line differs from the one of the family's own file, so that it also holds
    /// over that file where a document names the family itself.
    pub over_own_file: bool,
}

/// A name of a target's face other than its family's, by which a document can name the face.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FaceName {
    /// The name, such as "Arial Bold" or "`ArialMT`".
    pub name: FamilyName,
    /// The face's family, such as "Arial".
    pub family: String,
    /// The face's style for a full name (name ID 4), which gives that face whatever a run asks,
    /// or nothing for a PostScript name (name ID 6), which gives the face of the run's style.
    pub style: Option<String>,
}

/// The faces that the target's font mapper gives a metafile font of a face that the target
/// lacks, for one character set (`lfCharSet`): one face for each family (`FF_DONTCARE` to
/// `FF_DECORATIVE`, 0 to 5) and, within each, each pitch (default, fixed and variable, 0 to 2),
/// 18 in all.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetafileFaces {
    /// The character set.
    pub charset: u8,
    /// The faces, by family and then by pitch.
    pub faces: Vec<String>,
}

/// The families and the pitches of a pitch and family that [`MetafileFaces`] holds.
const METAFILE_FAMILIES: u8 = 6;
const METAFILE_PITCHES: u8 = 3;

impl MetafileFaces {
    /// The face for the pitch and family `pitch_and_family` (`lfPitchAndFamily`: the family in
    /// its high four bits, the pitch in its low two), or `None` for a family or pitch outside
    /// the table.
    #[must_use]
    pub fn face(&self, pitch_and_family: u8) -> Option<&str> {
        let (family, pitch) = (pitch_and_family >> 4, pitch_and_family & 0x03);
        if family >= METAFILE_FAMILIES || pitch >= METAFILE_PITCHES {
            return None;
        }
        self.faces
            .get(usize::from(family * METAFILE_PITCHES + pitch))
            .map(String::as_str)
    }
}

/// A face that the layout takes as the target's own: a face of this family, style and version.
/// The family and the style are compared as written, with case.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OwnFace {
    /// The family name.
    pub family: String,
    /// The style, such as "Bold Italic".
    pub style: String,
    /// The version string (name ID 5).
    pub version: String,
    /// The kerning source that the layout takes for the face in place of the one that the
    /// face's own tables give; nothing when those tables give the target's.
    pub kerning: Option<KerningSource>,
    /// The target face's `head.unitsPerEm`, recorded when stand-ins normalized to another
    /// `units_per_em` (such as 2048 for 256- or 1024-upem East Asian fonts) need the target's
    /// font-unit granularity for unit-level rounding.
    pub units_per_em: Option<u16>,
}

impl OwnFace {
    /// The family, the style and the version, by which the environment orders its faces.
    fn key(&self) -> (&str, &str, &str) {
        (&self.family, &self.style, &self.version)
    }
}

/// A font family that the target lacks, so that a document that names it gets the target's
/// substitute, even where the caller has the family.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Lacking {
    /// The family, as the font files name it.
    pub family: FamilyName,
    /// The observed family substitute, after the document's alternate, when confirmed.
    pub drawn_with: Option<String>,
}

/// An error in a font environment's text, or a text that the environment's text cannot hold.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EnvironmentError {
    /// A line that is no `[[face]]`, `[[lacking]]`, `[[available]]`, `[[metafile_faces]]`,
    /// `[[mapper_name]]`, `[[line]]` or `[[face_name]]` line and no `key = value` line of a
    /// section, or a key that its section does not know.
    Line(String),
    /// A key that a section holds twice, or a face, family or name that the file holds twice.
    Repeated(String),
    /// A section that lacks a key, or whose value has the wrong kind, such as a text that is
    /// not in the environment's form; with the section's face, family or name.
    Entry(String),
    /// A text to write holds a control character, which the environment's text cannot hold.
    Unwritable(String),
}

impl fmt::Display for EnvironmentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Line(line) => write!(f, "a font environment has the line {line:?}"),
            Self::Repeated(what) => write!(f, "a font environment holds {what:?} twice"),
            Self::Entry(what) => write!(f, "a font environment has an incomplete entry {what:?}"),
            Self::Unwritable(text) => {
                write!(f, "a font environment cannot hold the text {text:?}")
            }
        }
    }
}

impl std::error::Error for EnvironmentError {}

/// The section kinds of the environment's text.
const FACE: &str = "face";
const LACKING: &str = "lacking";
const AVAILABLE: &str = "available";
const METAFILE_FACES: &str = "metafile_faces";
const MAPPER_NAME: &str = "mapper_name";
const LINE: &str = "line";
const FACE_NAME: &str = "face_name";
/// The first character of a name that asks the font mapper for a face's vertical form.
const VERTICAL_PREFIX: char = '@';
/// The separator of the faces of a `[[metafile_faces]]` section.
const FACES_SEPARATOR: &str = ", ";

/// The `kerning_source` values of the environment's text.
const GPOS: &str = "gpos";
const KERN_TABLE: &str = "kern table";

/// A text in the environment's form.
fn quoted(text: &str) -> Result<String, EnvironmentError> {
    form::quoted(text).ok_or_else(|| EnvironmentError::Unwritable(text.to_owned()))
}

impl FontEnvironment {
    /// An environment of the target's own faces, in the order of their families, styles and
    /// versions; a face that the list holds twice keeps its first record.
    #[must_use]
    pub fn new(mut faces: Vec<OwnFace>) -> Self {
        sort_faces(&mut faces);
        faces.dedup_by(|later, first| later.key() == first.key());
        Self {
            faces,
            lacking: Vec::new(),
            available: Vec::new(),
            metafile_faces: Vec::new(),
            mapper_names: Vec::new(),
            lines: Vec::new(),
            face_names: Vec::new(),
        }
    }

    /// The same environment with the families that the target lacks, in the order of their
    /// names as [`FamilyName`] compares them; a family that the list holds twice keeps its
    /// first entry.
    #[must_use]
    pub fn with_lacking(mut self, mut lacking: Vec<Lacking>) -> Self {
        sort_lacking(&mut lacking);
        lacking.dedup_by(|later, first| later.family == first.family);
        self.lacking = lacking;
        self
    }

    /// The same environment with the requested names of the target's full font listing, in
    /// the order of their names as [`FamilyName`] compares them.
    #[must_use]
    pub fn with_available(mut self, mut names: Vec<FamilyName>) -> Self {
        sort_names(&mut names);
        names.dedup();
        self.available = names;
        self
    }

    /// The environment with the faces that the target's font mapper gives a metafile font of
    /// a missing face, in the order of their character sets; a character set that the list
    /// holds twice keeps its first entry.
    #[must_use]
    pub fn with_metafile_faces(mut self, mut entries: Vec<MetafileFaces>) -> Self {
        entries.sort_by_key(|entry| entry.charset);
        entries.dedup_by_key(|entry| entry.charset);
        self.metafile_faces = entries;
        self
    }

    /// The environment with the names outside the full listing that the target's font mapper
    /// knows, such as its raster faces and its font substitutes, in the order of their names as
    /// [`FamilyName`] compares them.
    #[must_use]
    pub fn with_mapper_names(mut self, mut names: Vec<FamilyName>) -> Self {
        sort_names(&mut names);
        names.dedup();
        self.mapper_names = names;
        self
    }

    /// The environment with the lines that Word gives families drawn with another family's
    /// face, in the order of their families as [`FamilyName`] compares names; a family that the
    /// list holds twice keeps its first line.
    #[must_use]
    pub fn with_lines(mut self, mut lines: Vec<WordLine>) -> Self {
        lines.sort_by(|a, b| a.family.cmp_name(b.family.as_str()));
        lines.dedup_by(|later, first| later.family == first.family);
        self.lines = lines;
        self
    }

    /// The environment with other names of the target's faces, in the order of the names as
    /// [`FamilyName`] compares them; a name that the list holds twice keeps its first entry.
    #[must_use]
    pub fn with_face_names(mut self, mut names: Vec<FaceName>) -> Self {
        names.sort_by(|a, b| a.name.cmp_name(b.name.as_str()));
        names.dedup_by(|later, first| later.name == first.name);
        self.face_names = names;
        self
    }

    /// The face that the target's font mapper gives a metafile font of the family `family`,
    /// with the character set `charset` and the pitch and family `pitch_and_family`, when the
    /// target lacks the family and the environment knows the face. Only a full listing tells
    /// that the target lacks a family, and the mapper does not answer so for a name that it
    /// knows outside the listing or for the vertical form of a face (a name that starts with
    /// `@`).
    #[must_use]
    pub fn metafile_face(&self, family: &str, charset: u8, pitch_and_family: u8) -> Option<&str> {
        if self.available.is_empty()
            || self.permits(family)
            || family.starts_with(VERTICAL_PREFIX)
            || self
                .mapper_names
                .binary_search_by(|probe| probe.cmp_name(family))
                .is_ok()
        {
            return None;
        }
        let at = self
            .metafile_faces
            .binary_search_by_key(&charset, |entry| entry.charset)
            .ok()?;
        self.metafile_faces.get(at)?.face(pitch_and_family)
    }

    /// The target's own faces.
    #[must_use]
    pub fn faces(&self) -> &[OwnFace] {
        &self.faces
    }

    /// The families that the target lacks.
    #[must_use]
    pub fn lacking(&self) -> &[Lacking] {
        &self.lacking
    }

    /// The requested names from a full target listing, or an empty slice without one.
    #[must_use]
    pub fn available(&self) -> &[FamilyName] {
        &self.available
    }

    /// The faces that the target's font mapper gives a metafile font of a missing face, in the
    /// order of their character sets.
    #[must_use]
    pub fn metafile_faces(&self) -> &[MetafileFaces] {
        &self.metafile_faces
    }

    /// The names outside the full listing that the target's font mapper knows.
    #[must_use]
    pub fn mapper_names(&self) -> &[FamilyName] {
        &self.mapper_names
    }

    /// The lines that Word gives families drawn with another family's face.
    #[must_use]
    pub fn lines(&self) -> &[WordLine] {
        &self.lines
    }

    /// The line that Word gives the family `family`, as [`FamilyName`] compares names.
    #[must_use]
    pub fn line(&self, family: &str) -> Option<&WordLine> {
        self.lines
            .binary_search_by(|probe| probe.family.cmp_name(family))
            .ok()
            .and_then(|at| self.lines.get(at))
    }

    /// The other names of the target's faces.
    #[must_use]
    pub fn face_names(&self) -> &[FaceName] {
        &self.face_names
    }

    /// The face that `name` names by its full or PostScript name, as [`FamilyName`] compares
    /// names.
    #[must_use]
    pub fn face_name(&self, name: &str) -> Option<&FaceName> {
        self.face_names
            .binary_search_by(|probe| probe.name.cmp_name(name))
            .ok()
            .and_then(|at| self.face_names.get(at))
    }

    /// Whether a requested name is in the target's full font listing, when it has one, as
    /// [`FamilyName`] compares names.
    #[must_use]
    pub fn permits(&self, name: &str) -> bool {
        self.available.is_empty()
            || self
                .available
                .binary_search_by(|probe| probe.cmp_name(name))
                .is_ok()
    }

    /// Whether the target lacks the font family `family`, as [`FamilyName`] compares names:
    /// a name outside the full listing, or without one, a lacking family.
    #[must_use]
    pub fn lacks(&self, family: &str) -> bool {
        if self.available.is_empty() {
            self.lacking.iter().any(|l| l.family.is(family))
        } else {
            !self.permits(family)
        }
    }

    /// The observed family substitute for a name that the target lacks.
    #[must_use]
    pub fn family_substitute(&self, family: &str) -> Option<&str> {
        self.lacks(family).then(|| {
            self.lacking
                .iter()
                .find(|entry| entry.family.is(family))?
                .drawn_with
                .as_deref()
        })?
    }

    /// Whether the layout takes a face of this family, style and version as the target's own.
    /// The family and the style are compared as written, with case, and not by the family name
    /// key ([`FamilyName`]), so a face whose family differs from the own face's only in case is
    /// not the target's own.
    #[must_use]
    pub fn is_target_file(&self, family: &str, style: &str, version: &str) -> bool {
        self.face(family, style, version).is_some()
    }

    /// The kerning source that the layout takes for the target's own face of this family,
    /// style and version ([`FontEnvironment::is_target_file`]) in place of the face's own;
    /// nothing for any other face, and for an own face whose tables give the target's.
    #[must_use]
    pub fn recorded_kerning(
        &self,
        family: &str,
        style: &str,
        version: &str,
    ) -> Option<KerningSource> {
        self.face(family, style, version)?.kerning
    }

    /// The own face of this family, style and version.
    fn face(&self, family: &str, style: &str, version: &str) -> Option<&OwnFace> {
        let key = (family, style, version);
        self.faces
            .binary_search_by(|face| face.key().cmp(&key))
            .ok()
            .and_then(|at| self.faces.get(at))
    }

    /// Reads a font environment.
    ///
    /// # Errors
    ///
    /// Returns an error when a line or an entry is not as the format says, and when the text
    /// holds a key of a section, or a face, family or name, twice.
    pub fn parse(text: &str) -> Result<Self, EnvironmentError> {
        let sections = form::sections(
            text,
            &[
                FACE,
                LACKING,
                AVAILABLE,
                METAFILE_FACES,
                MAPPER_NAME,
                LINE,
                FACE_NAME,
            ],
        )
        .map_err(EnvironmentError::Line)?;
        if let Some(key) = sections
            .iter()
            .find_map(|(_, section)| form::repeated_key(section))
        {
            return Err(EnvironmentError::Repeated(key.to_owned()));
        }
        let of = |kind: &'static str| sections.iter().filter(move |(k, _)| *k == kind);
        let mut faces: Vec<OwnFace> = of(FACE).map(own_face).collect::<Result<_, _>>()?;
        sort_faces(&mut faces);
        if let Some(face) = repeated(&faces, |a, b| a.key() == b.key()) {
            return Err(EnvironmentError::Repeated(format!(
                "{}, {}, {}",
                face.family, face.style, face.version
            )));
        }
        let mut lacking: Vec<Lacking> =
            of(LACKING).map(lacking_family).collect::<Result<_, _>>()?;
        sort_lacking(&mut lacking);
        if let Some(entry) = repeated(&lacking, |a, b| a.family == b.family) {
            return Err(EnvironmentError::Repeated(entry.family.as_str().to_owned()));
        }
        let mut available: Vec<FamilyName> = of(AVAILABLE)
            .map(|section| name_of(section, "available name"))
            .collect::<Result<_, _>>()?;
        sort_names(&mut available);
        if let Some(name) = repeated(&available, PartialEq::eq) {
            return Err(EnvironmentError::Repeated(name.as_str().to_owned()));
        }
        let mut metafile_faces: Vec<MetafileFaces> = of(METAFILE_FACES)
            .map(metafile_faces)
            .collect::<Result<_, _>>()?;
        metafile_faces.sort_by_key(|entry| entry.charset);
        if let Some(entry) = repeated(&metafile_faces, |a, b| a.charset == b.charset) {
            return Err(EnvironmentError::Repeated(format!(
                "metafile faces of character set {}",
                entry.charset
            )));
        }
        let mut mapper_names: Vec<FamilyName> = of(MAPPER_NAME)
            .map(|section| name_of(section, "mapper name"))
            .collect::<Result<_, _>>()?;
        sort_names(&mut mapper_names);
        if let Some(name) = repeated(&mapper_names, PartialEq::eq) {
            return Err(EnvironmentError::Repeated(name.as_str().to_owned()));
        }
        let mut lines: Vec<WordLine> = of(LINE).map(word_line).collect::<Result<_, _>>()?;
        lines.sort_by(|a, b| a.family.cmp_name(b.family.as_str()));
        if let Some(line) = repeated(&lines, |a, b| a.family == b.family) {
            return Err(EnvironmentError::Repeated(line.family.as_str().to_owned()));
        }
        let mut face_names: Vec<FaceName> =
            of(FACE_NAME).map(face_name).collect::<Result<_, _>>()?;
        face_names.sort_by(|a, b| a.name.cmp_name(b.name.as_str()));
        if let Some(name) = repeated(&face_names, |a, b| a.name == b.name) {
            return Err(EnvironmentError::Repeated(name.name.as_str().to_owned()));
        }
        Ok(Self {
            faces,
            lacking,
            available,
            metafile_faces,
            mapper_names,
            lines,
            face_names,
        })
    }

    /// Writes the environment in the form that [`FontEnvironment::parse`] reads, after
    /// `header`, whose lines become comments.
    ///
    /// # Errors
    ///
    /// Returns [`EnvironmentError::Unwritable`] when a text holds a control character, which
    /// the environment's text cannot hold.
    pub fn write(&self, header: &str) -> Result<String, EnvironmentError> {
        let mut out = String::new();
        for line in header.lines() {
            let _ = writeln!(out, "# {line}");
        }
        write_faces(&mut out, &self.faces)?;
        for lacking in &self.lacking {
            let _ = write!(
                out,
                "\n[[{LACKING}]]\nfamily = {}\n",
                quoted(lacking.family.as_str())?
            );
            if let Some(drawn_with) = &lacking.drawn_with {
                let _ = writeln!(out, "drawn_with = {}", quoted(drawn_with)?);
            }
        }
        write_names(&mut out, AVAILABLE, &self.available)?;
        for entry in &self.metafile_faces {
            let _ = write!(
                out,
                "\n[[{METAFILE_FACES}]]\ncharset = {}\nfaces = {}\n",
                entry.charset,
                quoted(&entry.faces.join(FACES_SEPARATOR))?
            );
        }
        write_names(&mut out, MAPPER_NAME, &self.mapper_names)?;
        write_lines(&mut out, &self.lines)?;
        write_face_names(&mut out, &self.face_names)?;
        Ok(out)
    }
}

/// Writes one section for each of `faces`.
fn write_faces(out: &mut String, faces: &[OwnFace]) -> Result<(), EnvironmentError> {
    for face in faces {
        let _ = write!(
            out,
            "\n[[{FACE}]]\nfamily = {}\nstyle = {}\nversion = {}\n",
            quoted(&face.family)?,
            quoted(&face.style)?,
            quoted(&face.version)?
        );
        if let Some(source) = face.kerning {
            let source = match source {
                KerningSource::Gpos => GPOS,
                KerningSource::KernTable => KERN_TABLE,
            };
            let _ = writeln!(out, "kerning_source = {}", quoted(source)?);
        }
        if let Some(units_per_em) = face.units_per_em {
            let _ = writeln!(out, "units_per_em = {units_per_em}");
        }
    }
    Ok(())
}

/// Writes one section of Word's line for each of `lines`.
fn write_lines(out: &mut String, lines: &[WordLine]) -> Result<(), EnvironmentError> {
    for line in lines {
        let _ = write!(
            out,
            "\n[[{LINE}]]\nfamily = {}\nascent = {}\ndescent = {}\nover_own_file = {}\n",
            quoted(line.family.as_str())?,
            line.ascent,
            line.descent,
            u8::from(line.over_own_file)
        );
    }
    Ok(())
}

/// Writes one section of a face's name for each of `names`.
fn write_face_names(out: &mut String, names: &[FaceName]) -> Result<(), EnvironmentError> {
    for name in names {
        let _ = write!(
            out,
            "\n[[{FACE_NAME}]]\nname = {}\nfamily = {}\n",
            quoted(name.name.as_str())?,
            quoted(&name.family)?
        );
        if let Some(style) = &name.style {
            let _ = writeln!(out, "style = {}", quoted(style)?);
        }
    }
    Ok(())
}

/// Writes one section `section` with the key `name` for each of `names`.
fn write_names(
    out: &mut String,
    section: &str,
    names: &[FamilyName],
) -> Result<(), EnvironmentError> {
    for name in names {
        let _ = write!(out, "\n[[{section}]]\nname = {}\n", quoted(name.as_str())?);
    }
    Ok(())
}

/// Sorts faces by their family, style and version.
fn sort_faces(faces: &mut [OwnFace]) {
    faces.sort_by(|a, b| a.key().cmp(&b.key()));
}

/// Sorts lacking families by their names, as [`FamilyName`] compares them.
fn sort_lacking(lacking: &mut [Lacking]) {
    lacking.sort_by(|a, b| a.family.cmp_name(b.family.as_str()));
}

/// Sorts names as [`FamilyName`] compares them.
fn sort_names(names: &mut [FamilyName]) {
    names.sort_by(|a, b| a.cmp_name(b.as_str()));
}

/// The first item of the sorted `items` that is the `same` as the one before it.
fn repeated<T>(items: &[T], same: impl Fn(&T, &T) -> bool) -> Option<&T> {
    items.windows(2).find_map(|pair| match pair {
        [earlier, item] if same(earlier, item) => Some(item),
        _ => None,
    })
}

/// Refuses a key of `section` that is not among `known`.
fn known_keys(section: &Section<'_>, known: &[&str]) -> Result<(), EnvironmentError> {
    match section
        .1
        .iter()
        .find(|(key, _)| !known.contains(&key.as_str()))
    {
        Some((key, _)) => Err(EnvironmentError::Line(key.clone())),
        None => Ok(()),
    }
}

/// The text of `key` in `section`, with `owner`, the section's face, family or name, in its
/// error.
fn text_of(
    section: &Section<'_>,
    key: &str,
    owner: &str,
) -> Result<Option<String>, EnvironmentError> {
    form::text_of(&section.1, key, || entry(owner))
}

/// The error of an incomplete section, with `owner`, the section's face, family or name.
fn entry(owner: &str) -> EnvironmentError {
    EnvironmentError::Entry(owner.to_owned())
}

/// The family of a `[[face]]` or `[[lacking]]` section, which names the section in its errors;
/// an empty text when the section has none in the form.
fn family_of(section: &Section<'_>) -> String {
    text_of(section, "family", "")
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// The own face of one `[[face]]` section.
fn own_face(section: &Section<'_>) -> Result<OwnFace, EnvironmentError> {
    known_keys(
        section,
        &[
            "family",
            "style",
            "version",
            "kerning_source",
            "units_per_em",
        ],
    )?;
    let family = family_of(section);
    let text = |key: &str| text_of(section, key, &family);
    let kerning = match text("kerning_source")?.as_deref() {
        Some(GPOS) => Some(KerningSource::Gpos),
        Some(KERN_TABLE) => Some(KerningSource::KernTable),
        None => None,
        Some(_) => return Err(entry(&family)),
    };
    let units_per_em = match form::value_of(&section.1, "units_per_em") {
        None => None,
        Some(raw) => match raw.parse::<u16>() {
            Ok(value) if value > 0 => Some(value),
            _ => return Err(entry(&family)),
        },
    };
    match (text("family")?, text("style")?, text("version")?) {
        (Some(family), Some(style), Some(version)) if !family.is_empty() => Ok(OwnFace {
            family,
            style,
            version,
            kerning,
            units_per_em,
        }),
        _ => Err(entry(&family)),
    }
}

/// The family that the target lacks of one `[[lacking]]` section.
fn lacking_family(section: &Section<'_>) -> Result<Lacking, EnvironmentError> {
    known_keys(section, &["family", "drawn_with"])?;
    let family = family_of(section);
    let drawn_with = text_of(section, "drawn_with", &family)?;
    if family.is_empty() || drawn_with.as_deref() == Some("") {
        return Err(entry(&family));
    }
    Ok(Lacking {
        family: FamilyName::new(family.clone()),
        drawn_with,
    })
}

/// The name of one `[[available]]` or `[[mapper_name]]` section, which a refusal calls `owner`.
fn name_of(section: &Section<'_>, owner: &str) -> Result<FamilyName, EnvironmentError> {
    known_keys(section, &["name"])?;
    text_of(section, "name", owner)?
        .filter(|name| !name.is_empty())
        .map(FamilyName::new)
        .ok_or_else(|| entry(owner))
}

/// The line of one `[[line]]` section: a family, the two parts of its line in thousandths of an
/// em, and whether it holds over the family's own file, 1 or 0.
fn word_line(section: &Section<'_>) -> Result<WordLine, EnvironmentError> {
    known_keys(section, &["family", "ascent", "descent", "over_own_file"])?;
    let family = family_of(section);
    let number = |key: &str| form::value_of(&section.1, key).and_then(|v| v.parse::<i16>().ok());
    match (number("ascent"), number("descent"), number("over_own_file")) {
        (Some(ascent), Some(descent), Some(over @ (0 | 1))) if !family.is_empty() => Ok(WordLine {
            family: FamilyName::new(family),
            ascent,
            descent,
            over_own_file: over == 1,
        }),
        _ => Err(entry(&family)),
    }
}

/// The other name of a face of one `[[face_name]]` section.
fn face_name(section: &Section<'_>) -> Result<FaceName, EnvironmentError> {
    known_keys(section, &["name", "family", "style"])?;
    let name = text_of(section, "name", "face name")?.unwrap_or_default();
    let text = |key: &str| text_of(section, key, &name);
    match (text("family")?, text("style")?) {
        (Some(family), style) if !name.is_empty() && !family.is_empty() => Ok(FaceName {
            name: FamilyName::new(name),
            family,
            style,
        }),
        _ => Err(entry(&name)),
    }
}

/// The faces of one `[[metafile_faces]]` section: a character set and its 18 faces.
fn metafile_faces(section: &Section<'_>) -> Result<MetafileFaces, EnvironmentError> {
    const OWNER: &str = "metafile faces";
    known_keys(section, &["charset", "faces"])?;
    let charset = form::value_of(&section.1, "charset")
        .and_then(|value| value.parse::<u8>().ok())
        .ok_or_else(|| entry(OWNER))?;
    let faces: Vec<String> = text_of(section, "faces", OWNER)?
        .ok_or_else(|| entry(OWNER))?
        .split(FACES_SEPARATOR)
        .map(str::to_owned)
        .collect();
    let count = usize::from(METAFILE_FAMILIES * METAFILE_PITCHES);
    if faces.len() != count || faces.iter().any(String::is_empty) {
        return Err(entry(OWNER));
    }
    Ok(MetafileFaces { charset, faces })
}

#[cfg(test)]
mod tests;