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
use std::path::Path;

use write_fonts::FontBuilder;
use write_fonts::read::tables::glyf::CurvePoint;
use write_fonts::tables::cmap::Cmap;
use write_fonts::tables::glyf::{Bbox, Contour, GlyfLocaBuilder, Glyph, SimpleGlyph};
use write_fonts::tables::gpos::{
    Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord,
};
use write_fonts::tables::gsub::{
    Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList,
};
use write_fonts::tables::head::{Flags, Head};
use write_fonts::tables::hhea::Hhea;
use write_fonts::tables::hmtx::{Hmtx, LongMetric};
use write_fonts::tables::layout::{
    CoverageTable, Feature, FeatureList, FeatureRecord, LangSys, Lookup, LookupFlag, Script,
    ScriptList, ScriptRecord,
};
use write_fonts::tables::maxp::Maxp;
use write_fonts::tables::os2::Os2;
use write_fonts::tables::post::Post;
use write_fonts::types::{FWord, GlyphId, GlyphId16, Tag};

use super::{Comparison, LayoutValues, Place, ValueKind};
use crate::FontDb;

/// One glyph after `.notdef` of a test face: its character, none for a glyph that only a
/// ligature reaches, its advance and its box, which is its one contour.
#[derive(Clone)]
struct TestGlyph {
    character: Option<char>,
    advance: u16,
    bounds: [i16; 4],
}

/// The glyphs of the test faces, by index: A, V, f, i and the ligature of f and i.
const A: usize = 0;
const V: usize = 1;
const F: usize = 2;
const I: usize = 3;
const FI: usize = 4;

/// A test face: a small TrueType face whose glyph order, kerning, ligature, line values and
/// instructions a test chooses.
#[derive(Clone)]
struct Design {
    units_per_em: u16,
    ascender: i16,
    glyphs: Vec<TestGlyph>,
    /// The kerning of the pair A V in `GPOS`.
    kerning: i16,
    /// The glyph that the ligature of f and i makes, by index.
    ligature: usize,
    /// The index in `glyphs` of glyph 1, glyph 2 and so on.
    order: Vec<usize>,
    /// The instructions of the glyph of A.
    instructions: Vec<u8>,
}

impl Default for Design {
    fn default() -> Self {
        let glyph = |character, advance, bounds| TestGlyph {
            character,
            advance,
            bounds,
        };
        Self {
            units_per_em: 1000,
            ascender: 800,
            glyphs: vec![
                glyph(Some('A'), 600, [10, 0, 590, 700]),
                glyph(Some('V'), 600, [0, 0, 600, 700]),
                glyph(Some('f'), 300, [20, 0, 320, 720]),
                glyph(Some('i'), 250, [40, 0, 210, 700]),
                glyph(None, 550, [20, 0, 510, 720]),
            ],
            kerning: -50,
            ligature: FI,
            order: vec![A, V, F, I, FI],
            instructions: Vec::new(),
        }
    }
}

/// Instructions that move the advance point of a glyph of four points one pixel to the right:
/// push the point 5 and the distance 64 (one pixel in 26.6), then shift the point by it.
const ONE_PIXEL_WIDER: [u8; 4] = [0xB1, 5, 64, 0x38];

impl Design {
    /// The glyph ID of the glyph of index `index`.
    fn id(&self, index: usize) -> GlyphId16 {
        let place = self.order.iter().position(|&i| i == index).unwrap_or(0);
        GlyphId16::new(u16::try_from(place + 1).unwrap_or(0))
    }

    fn glyph_count(&self) -> u16 {
        u16::try_from(self.order.len() + 1).unwrap_or(0)
    }

    fn build(&self) -> Vec<u8> {
        let mut builder = FontBuilder::new();
        let (glyf, loca, format) = self.outlines();
        let tables = [
            builder.add_table(&self.head(format)).is_ok(),
            builder.add_table(&self.hhea()).is_ok(),
            builder.add_table(&self.maxp()).is_ok(),
            builder.add_table(&self.hmtx()).is_ok(),
            builder.add_table(&self.cmap()).is_ok(),
            builder.add_table(&glyf).is_ok(),
            builder.add_table(&loca).is_ok(),
            builder.add_table(&Os2::default()).is_ok(),
            builder.add_table(&Post::default()).is_ok(),
            builder.add_table(&self.gpos()).is_ok(),
            builder.add_table(&self.gsub()).is_ok(),
        ];
        assert!(
            tables.iter().all(|&added| added),
            "a test table does not build"
        );
        builder.build()
    }

    fn head(&self, format: write_fonts::tables::loca::LocaFormat) -> Head {
        Head {
            flags: Flags::from_bits_truncate(0x001B),
            units_per_em: self.units_per_em,
            x_min: 0,
            y_min: 0,
            x_max: 600,
            y_max: 720,
            index_to_loc_format: i16::from(format == write_fonts::tables::loca::LocaFormat::Long),
            ..Head::default()
        }
    }

    fn hhea(&self) -> Hhea {
        Hhea {
            ascender: FWord::new(self.ascender),
            descender: FWord::new(-200),
            number_of_h_metrics: self.glyph_count(),
            ..Hhea::default()
        }
    }

    fn maxp(&self) -> Maxp {
        Maxp {
            max_points: Some(4),
            max_contours: Some(1),
            max_composite_points: Some(0),
            max_composite_contours: Some(0),
            max_zones: Some(2),
            max_twilight_points: Some(0),
            max_storage: Some(0),
            max_function_defs: Some(0),
            max_instruction_defs: Some(0),
            max_stack_elements: Some(16),
            max_size_of_instructions: Some(16),
            max_component_elements: Some(0),
            max_component_depth: Some(0),
            ..Maxp::new(self.glyph_count())
        }
    }

    fn glyphs_in_order(&self) -> impl Iterator<Item = (usize, &TestGlyph)> {
        self.order
            .iter()
            .filter_map(|&index| Some((index, self.glyphs.get(index)?)))
    }

    fn hmtx(&self) -> Hmtx {
        let notdef = LongMetric {
            advance: 500,
            side_bearing: 0,
        };
        let metrics = self.glyphs_in_order().map(|(_, glyph)| LongMetric {
            advance: glyph.advance,
            side_bearing: glyph.bounds[0],
        });
        Hmtx::new(std::iter::once(notdef).chain(metrics).collect(), Vec::new())
    }

    fn cmap(&self) -> Cmap {
        let mappings = self
            .glyphs_in_order()
            .filter_map(|(index, glyph)| Some((glyph.character?, GlyphId::from(self.id(index)))));
        let cmap = Cmap::from_mappings(mappings);
        assert!(cmap.is_ok(), "the test characters map twice");
        cmap.unwrap_or_default()
    }

    fn outlines(
        &self,
    ) -> (
        write_fonts::tables::glyf::Glyf,
        write_fonts::tables::loca::Loca,
        write_fonts::tables::loca::LocaFormat,
    ) {
        let mut builder = GlyfLocaBuilder::new();
        assert!(builder.add_glyph(&Glyph::Empty).is_ok());
        for (index, glyph) in self.glyphs_in_order() {
            let [x0, y0, x1, y1] = glyph.bounds;
            let points = vec![
                CurvePoint::on_curve(x0, y0),
                CurvePoint::on_curve(x0, y1),
                CurvePoint::on_curve(x1, y1),
                CurvePoint::on_curve(x1, y0),
            ];
            let instructions = if index == A {
                self.instructions.clone()
            } else {
                Vec::new()
            };
            let simple = SimpleGlyph {
                bbox: Bbox {
                    x_min: x0,
                    y_min: y0,
                    x_max: x1,
                    y_max: y1,
                },
                contours: vec![Contour::from(points)],
                instructions,
            };
            assert!(builder.add_glyph(&simple).is_ok());
        }
        builder.build()
    }

    /// A script list of the Latin script whose default language has the one feature.
    fn scripts() -> ScriptList {
        let latin = Script::new(Some(LangSys::new(vec![0])), Vec::new());
        ScriptList::new(vec![ScriptRecord::new(Tag::new(b"latn"), latin)])
    }

    fn feature(tag: [u8; 4]) -> FeatureList {
        let feature = Feature::new(None, vec![0]);
        FeatureList::new(vec![FeatureRecord::new(Tag::new(&tag), feature)])
    }

    fn gpos(&self) -> Gpos {
        let record = PairValueRecord::new(
            self.id(V),
            ValueRecord::new().with_x_advance(self.kerning),
            ValueRecord::new(),
        );
        let pairs = PairPos::format_1(
            CoverageTable::format_1(vec![self.id(A)]),
            vec![PairSet::new(vec![record])],
        );
        let lookup = PositionLookup::Pair(Lookup::new(LookupFlag::empty(), vec![pairs]));
        Gpos::new(
            Self::scripts(),
            Self::feature(*b"kern"),
            PositionLookupList::new(vec![lookup]),
        )
    }

    fn gsub(&self) -> Gsub {
        let ligature = Ligature::new(self.id(self.ligature), vec![self.id(I)]);
        let table = LigatureSubstFormat1::new(
            CoverageTable::format_1(vec![self.id(F)]),
            vec![LigatureSet::new(vec![ligature])],
        );
        let lookup = SubstitutionLookup::Ligature(Lookup::new(LookupFlag::empty(), vec![table]));
        Gsub::new(
            Self::scripts(),
            Self::feature(*b"liga"),
            SubstitutionLookupList::new(vec![lookup]),
        )
    }

    fn values(&self, sizes: &[u16]) -> LayoutValues {
        let mut db = FontDb::new();
        let id = db
            .add_font(self.build())
            .ok()
            .and_then(|ids| ids.first().copied());
        let values = id.and_then(|id| db.layout_values(id, sizes));
        assert!(values.is_some(), "the test face does not load");
        values.unwrap_or_default()
    }
}

fn compare(left: &Design, right: &Design, sizes: &[u16]) -> Comparison {
    Comparison::new(&left.values(sizes), &right.values(sizes), &ValueKind::ALL)
}

/// Each difference of a comparison as its kind and place.
fn differences(comparison: &Comparison) -> Vec<(ValueKind, Place)> {
    comparison
        .kinds()
        .iter()
        .flat_map(|kind| {
            kind.differences
                .iter()
                .map(move |difference| (kind.kind, difference.place.clone()))
        })
        .collect()
}

#[test]
fn equal_faces_have_no_difference() {
    let comparison = compare(&Design::default(), &Design::default(), &[12, 25]);
    assert!(comparison.is_match());
    let compared: Vec<(ValueKind, usize)> = comparison
        .kinds()
        .iter()
        .map(|kind| (kind.kind, kind.compared))
        .filter(|(kind, _)| *kind != ValueKind::LineValues && *kind != ValueKind::Selection)
        .collect();
    // Four characters, the source of the kerning and the one pair, one ligature, and four
    // characters at two sizes; the face has no `VDMX`, forms, math or shaped script.
    assert_eq!(
        compared,
        [
            (ValueKind::Characters, 4),
            (ValueKind::Advance, 4),
            (ValueKind::Box, 4),
            (ValueKind::Kerning, 2),
            (ValueKind::KernTable, 1),
            (ValueKind::PixelHeights, 0),
            (ValueKind::BiLevelAdvance, 8),
            (ValueKind::DeviceWidth, 8),
            (ValueKind::Ligatures, 1),
            (ValueKind::Forms, 0),
            (ValueKind::Math, 0),
            (ValueKind::Shaping, 0),
        ]
    );
}

#[test]
fn reads_the_values_by_character() {
    let values = Design::default().values(&[]);
    let at = |kind, place: Place| values.of(kind).and_then(|v| v.get(&place)).cloned();
    assert_eq!(
        at(ValueKind::Advance, Place::Character('V')),
        Some(vec![600])
    );
    assert_eq!(
        at(ValueKind::Box, Place::Character('i')),
        Some(vec![40, 0, 210, 700])
    );
    assert_eq!(
        at(ValueKind::Kerning, Place::Pair('A', 'V')),
        Some(vec![-50])
    );
    // The ligature starts at 0, takes 2 characters, and has its advance and box.
    assert_eq!(
        at(ValueKind::Ligatures, Place::Sequence(vec!['f', 'i'])),
        Some(vec![0, 2, 550, 20, 0, 510, 720])
    );
    assert_eq!(
        at(ValueKind::LineValues, Place::Face("hhea ascender")),
        Some(vec![800])
    );
}

#[test]
fn one_advance_one_unit_wider_is_one_difference() {
    let mut wider = Design::default();
    if let Some(glyph) = wider.glyphs.get_mut(V) {
        glyph.advance += 1;
    }
    let comparison = compare(&Design::default(), &wider, &[]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::Advance, Place::Character('V'))]
    );
    let largest = comparison.kinds().first().and_then(|kind| kind.largest());
    assert_eq!(largest.and_then(|difference| difference.gap), Some(1));
}

#[test]
fn one_kerning_pair_one_unit_less_is_one_difference() {
    let other = Design {
        kerning: -49,
        ..Design::default()
    };
    let comparison = compare(&Design::default(), &other, &[]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::Kerning, Place::Pair('A', 'V'))]
    );
}

#[test]
fn a_pair_that_one_face_does_not_list_has_the_kerning_0() {
    let other = Design {
        kerning: 0,
        ..Design::default()
    };
    let comparison = compare(&Design::default(), &other, &[]);
    assert_eq!(comparison.difference_count(), 1);
    let largest = comparison.kinds().first().and_then(|kind| kind.largest());
    assert_eq!(largest.and_then(|difference| difference.gap), Some(50));
}

#[test]
fn one_line_value_one_unit_higher_is_one_difference() {
    let other = Design {
        ascender: 801,
        ..Design::default()
    };
    let comparison = compare(&Design::default(), &other, &[]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::LineValues, Place::Face("hhea ascender"))]
    );
}

#[test]
fn one_hinted_advance_one_pixel_wider_is_one_difference() {
    let wider = Design {
        instructions: ONE_PIXEL_WIDER.to_vec(),
        ..Design::default()
    };
    let size = 12;
    let left = Design::default().values(&[size]);
    let right = wider.values(&[size]);
    let comparison = Comparison::new(&left, &right, &[ValueKind::DeviceWidth]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::DeviceWidth, Place::CharacterAt('A', size))]
    );
    // The instructions move no outline point and change no value in font units.
    let in_units: Vec<ValueKind> = ValueKind::ALL
        .into_iter()
        .filter(|kind| !kind.in_pixels())
        .collect();
    assert!(Comparison::new(&left, &right, &in_units).is_match());
}

#[test]
fn another_ligature_glyph_is_one_difference() {
    // The ligature of f and i makes the glyph of V: another advance and box.
    let other = Design {
        ligature: V,
        ..Design::default()
    };
    let comparison = compare(&Design::default(), &other, &[]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::Ligatures, Place::Sequence(vec!['f', 'i']))]
    );
}

#[test]
fn another_glyph_order_is_no_difference() {
    let renumbered = Design {
        order: vec![FI, I, F, V, A],
        ..Design::default()
    };
    assert!(compare(&Design::default(), &renumbered, &[12, 25]).is_match());
}

#[test]
fn other_units_per_em_are_one_difference_and_end_the_comparison() {
    let other = Design {
        units_per_em: 2048,
        ..Design::default()
    };
    let comparison = compare(&Design::default(), &other, &[]);
    assert_eq!(comparison.units_per_em_differ(), Some((1000, 2048)));
    assert_eq!(comparison.difference_count(), 1);
    assert_eq!(comparison.kinds(), []);
}

#[test]
fn a_character_of_one_face_is_one_difference_and_its_pairs_are_not_compared() {
    let mut fewer = Design::default();
    if let Some(glyph) = fewer.glyphs.get_mut(V) {
        glyph.character = None;
    }
    let comparison = compare(&Design::default(), &fewer, &[12]);
    assert_eq!(
        differences(&comparison),
        [(ValueKind::Characters, Place::Character('V'))]
    );
}

#[test]
fn keeps_the_characters_of_a_range() {
    let mut values = Design::default().values(&[]);
    values.keep_characters('a'..='z');
    assert_eq!(values.characters().collect::<String>(), "fi");
    let kerning = values.of(ValueKind::Kerning);
    assert!(kerning.is_some_and(|places| !places.contains_key(&Place::Pair('A', 'V'))));
}

/// The public methods of the database that give no layout value of a face, each with the
/// reason.
const NOT_LAYOUT_VALUES: [(&str, &str); 16] = [
    ("new", "makes an empty database"),
    (
        "add_description",
        "adds a font's description, which says what it is compatible with",
    ),
    (
        "descriptions",
        "lists the descriptions, which say what the fonts are compatible with",
    ),
    ("add_font", "adds the faces of a font"),
    (
        "add_static",
        "adds the faces of a font compiled into the program",
    ),
    ("add_files", "adds the faces of font files"),
    ("load", "adds the faces of a folder"),
    ("len", "counts the faces"),
    ("is_empty", "counts the faces"),
    ("faces", "lists the faces"),
    ("data", "gives the bytes of a face's file"),
    ("origin", "says where a face came from"),
    (
        "query",
        "finds a face by its names, which an open font has of its own",
    ),
    (
        "query_with",
        "finds a face by its names, which an open font has of its own",
    ),
    (
        "query_typographic_with",
        "finds a face by its typographic family name, which an open font has of its own",
    ),
    ("layout_values", "reads the layout values"),
];

/// The names of the public methods of `impl FontDb` blocks in `source`.
fn public_methods(source: &str) -> Vec<String> {
    let mut methods = Vec::new();
    let mut inside = false;
    for line in source.lines() {
        if line.starts_with("impl FontDb {") {
            inside = true;
        } else if line.starts_with('}') {
            inside = false;
        } else if inside && let Some(rest) = line.strip_prefix("    pub fn ") {
            let name = rest.split(['(', '<']).next().unwrap_or_default();
            methods.push(name.to_owned());
        }
    }
    methods
}

/// The methods of `methods` that neither the reader of layout values (`reader`, its source)
/// calls nor the list of methods without layout values names.
fn uncovered<'a>(methods: &'a [String], reader: &str) -> Vec<&'a str> {
    methods
        .iter()
        .map(String::as_str)
        .filter(|name| {
            !NOT_LAYOUT_VALUES.iter().any(|(listed, _)| listed == name)
                && !reader.contains(&format!(".{name}("))
        })
        .collect()
}

/// The text of every Rust file under `folder`.
fn sources(folder: &Path) -> String {
    let mut text = String::new();
    let entries = std::fs::read_dir(folder).into_iter().flatten().flatten();
    for entry in entries {
        let path = entry.path();
        if path.is_dir() {
            text.push_str(&sources(&path));
        } else if path.extension().is_some_and(|e| e == "rs") {
            text.push_str(&std::fs::read_to_string(&path).unwrap_or_default());
            text.push('\n');
        }
    }
    text
}

#[test]
fn every_public_method_of_the_database_is_a_layout_value_or_named_as_none() {
    let folder = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    let methods = public_methods(&sources(&folder));
    assert!(methods.len() > 30, "found {} methods", methods.len());
    let reader = std::fs::read_to_string(folder.join("layout_values.rs")).unwrap_or_default();
    assert_eq!(uncovered(&methods, &reader), Vec::<&str>::new());
}

#[test]
fn the_guard_names_a_method_that_the_reader_does_not_call() {
    let source = "impl FontDb {\n    pub fn advance(&self) {}\n    pub fn new_value(&self) {}\n}\n";
    let methods = public_methods(source);
    assert_eq!(uncovered(&methods, "db.advance(id, glyph)"), ["new_value"]);
}