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
use super::{
    EnvironmentError, FaceName, FontEnvironment, Lacking, MetafileFaces, OwnFace, WordLine,
};
use crate::{FamilyName, KerningSource};

fn face(family: &str, style: &str, version: &str, kerning: Option<KerningSource>) -> OwnFace {
    OwnFace {
        family: family.to_owned(),
        style: style.to_owned(),
        version: version.to_owned(),
        kerning,
        units_per_em: None,
    }
}

fn lacking(family: &str, drawn_with: Option<&str>) -> Lacking {
    Lacking {
        family: FamilyName::new(family),
        drawn_with: drawn_with.map(str::to_owned),
    }
}

fn sample() -> FontEnvironment {
    FontEnvironment::new(vec![
        face("Calibri", "Bold", "Version 6.23", None),
        face("Aptos", "Regular", "Version 1.0", Some(KerningSource::Gpos)),
    ])
}

#[test]
fn writes_and_reads_an_environment() {
    let environment = sample()
        .with_lacking(vec![
            lacking("B Zar", None),
            lacking("Other", Some("Calibri")),
        ])
        .with_available(vec![FamilyName::from_static("Calibri")]);
    let text = environment.write("The fonts of a target.").unwrap();
    assert_eq!(
        text,
        "# The fonts of a target.\n\
         \n[[face]]\nfamily = \"Aptos\"\nstyle = \"Regular\"\nversion = \"Version 1.0\"\nkerning_source = \"gpos\"\n\
         \n[[face]]\nfamily = \"Calibri\"\nstyle = \"Bold\"\nversion = \"Version 6.23\"\n\
         \n[[lacking]]\nfamily = \"B Zar\"\n\
         \n[[lacking]]\nfamily = \"Other\"\ndrawn_with = \"Calibri\"\n\
         \n[[available]]\nname = \"Calibri\"\n"
    );
    let read = FontEnvironment::parse(&text).unwrap();
    assert_eq!(read, environment);
    assert_eq!(read.write("The fonts of a target.").unwrap(), text);
    assert_eq!(read.faces()[0].family, "Aptos");
    assert_eq!(read.lacking().len(), 2);
}

#[test]
fn writes_and_reads_every_text_as_it_is() {
    let version = "Version 1.000; ttfautohint (v0.93) -w \"G\"";
    let environment = FontEnvironment::new(vec![face("Calibri\\Bold", "Bold", version, None)])
        .with_lacking(vec![lacking("Arial İtalik", Some("Arial \"Narrow\""))])
        .with_available(vec![FamilyName::new("arial i\u{307}talik")]);
    let text = environment.write("").unwrap();
    for line in [
        "family = \"Calibri\\\\Bold\"",
        "version = \"Version 1.000; ttfautohint (v0.93) -w \\\"G\\\"\"",
        "family = \"Arial İtalik\"",
        "drawn_with = \"Arial \\\"Narrow\\\"\"",
        "name = \"arial i\u{307}talik\"",
    ] {
        assert!(text.contains(&format!("\n{line}\n")), "{line}\n{text}");
    }
    assert_eq!(FontEnvironment::parse(&text), Ok(environment));
}

#[test]
fn refuses_to_write_a_control_character() {
    let unwritable = sample().with_available(vec![FamilyName::from_static("line\nbreak")]);
    assert_eq!(
        unwritable.write(""),
        Err(EnvironmentError::Unwritable("line\nbreak".to_owned()))
    );
    assert!(
        EnvironmentError::Unwritable("a\nb".to_owned())
            .to_string()
            .contains("\"a\\nb\"")
    );
}

/// A full listing of Calibri, in two cases, and `MS 明朝`.
fn listed() -> FontEnvironment {
    sample().with_available(
        ["Calibri", "CALIBRI", "MS 明朝"]
            .map(FamilyName::from_static)
            .to_vec(),
    )
}

#[test]
fn a_full_listing_limits_names_and_keeps_localized_aliases() {
    let environment = listed();
    assert!(!environment.permits("Aptos"));
    assert!(environment.lacks("Aptos"));
    assert!(!environment.lacks("Calibri"));
    assert_eq!(environment.available().len(), 2);
    assert_eq!(
        FontEnvironment::parse(&environment.write("").unwrap()),
        Ok(environment)
    );
    assert!(sample().permits("Aptos"));
    assert_eq!(sample().available(), &[] as &[FamilyName]);
}

#[test]
fn a_full_listing_names_a_family_by_its_key() {
    let environment = listed();
    for name in ["CALIBRI", "calibri", "MS 明朝"] {
        assert!(environment.permits(name), "{name}");
    }
    assert!(!environment.permits("ms 明朝"));
}

#[test]
fn the_families_that_the_target_lacks_count_by_their_key() {
    let environment = sample().with_lacking(vec![lacking("B Zar", None)]);
    assert_eq!(environment.lacking(), &[lacking("B Zar", None)]);
    assert!(environment.lacks("B Zar"));
    assert!(environment.lacks("b zar"));
    assert!(!environment.lacks("Arial"));
    // A full listing takes precedence over the lacking families.
    let listed = environment.with_available(vec![FamilyName::from_static("B Zar")]);
    assert!(!listed.lacks("B Zar"));
    assert!(listed.lacks("Arial"));
}

#[test]
fn a_family_substitute_applies_only_when_the_requested_family_is_absent() {
    let text = "[[lacking]]\nfamily = \"Other\"\ndrawn_with = \"Calibri\"\n";
    let environment = FontEnvironment::parse(text).unwrap();
    assert_eq!(environment.family_substitute("Other"), Some("Calibri"));
    assert_eq!(environment.family_substitute("OTHER"), Some("Calibri"));
    assert_eq!(environment.family_substitute("Else"), None);
    let available = environment.with_available(vec![FamilyName::from_static("Other")]);
    assert_eq!(available.family_substitute("Other"), None);
    assert_eq!(available.family_substitute("Else"), None);
    for wrong in ["3", "\"\""] {
        assert_eq!(
            FontEnvironment::parse(&text.replace("\"Calibri\"", wrong)),
            Err(EnvironmentError::Entry("Other".to_owned())),
            "{wrong}"
        );
    }
}

#[test]
fn a_face_is_the_targets_own_by_its_family_style_and_version_with_case() {
    let environment = sample();
    assert!(environment.is_target_file("Calibri", "Bold", "Version 6.23"));
    assert!(!environment.is_target_file("Calibri", "Bold", "Version 6.22"));
    assert!(!environment.is_target_file("Calibri", "Italic", "Version 6.23"));
    assert!(!environment.is_target_file("calibri", "Bold", "Version 6.23"));
    assert!(!environment.is_target_file("Calibri", "bold", "Version 6.23"));
    assert!(!FontEnvironment::default().is_target_file("Calibri", "Bold", "Version 6.23"));
}

#[test]
fn writes_reads_and_finds_the_lines_of_families_and_the_other_names_of_faces() {
    let line = |family: &str, ascent, over_own_file| WordLine {
        family: FamilyName::new(family),
        ascent,
        descent: 230,
        over_own_file,
    };
    let name = |name: &str, style: Option<&str>| FaceName {
        name: FamilyName::new(name),
        family: "Arial".to_owned(),
        style: style.map(str::to_owned),
    };
    let environment = sample()
        .with_lines(vec![
            line("Symbol", 1005, false),
            line("Helvetica", 970, true),
        ])
        .with_face_names(vec![
            name("ArialMT", None),
            name("Arial Bold", Some("Bold")),
        ]);
    let text = environment.write("").unwrap();
    assert!(text.contains(
        "\n[[line]]\nfamily = \"Helvetica\"\nascent = 970\ndescent = 230\nover_own_file = 1\n"
    ));
    assert!(text.contains("\n[[face_name]]\nname = \"ArialMT\"\nfamily = \"Arial\"\n"));
    assert_eq!(FontEnvironment::parse(&text), Ok(environment.clone()));
    assert_eq!(environment.line("helvetica").map(|l| l.ascent), Some(970));
    assert_eq!(environment.line("Wingdings"), None);
    assert_eq!(
        environment
            .face_name("arial bold")
            .and_then(|n| n.style.as_deref()),
        Some("Bold")
    );
    assert_eq!(environment.face_name("Arial-BoldMT"), None);
}

#[test]
fn gives_the_recorded_kerning_source_of_an_own_face_only() {
    let environment = FontEnvironment::new(vec![
        face("Calibri", "Bold", "Version 1", Some(KerningSource::Gpos)),
        face("Calibri", "Bold", "Version 2", None),
        face(
            "Corbel",
            "Regular",
            "Version 1",
            Some(KerningSource::KernTable),
        ),
    ]);
    let source = |family, style, version| environment.recorded_kerning(family, style, version);
    assert_eq!(
        source("Calibri", "Bold", "Version 1"),
        Some(KerningSource::Gpos)
    );
    assert_eq!(source("Calibri", "Bold", "Version 2"), None);
    assert_eq!(source("Calibri", "Bold", "Version 3"), None);
    assert_eq!(source("Calibri", "Italic", "Version 1"), None);
    assert_eq!(
        source("Corbel", "Regular", "Version 1"),
        Some(KerningSource::KernTable)
    );
    let text = environment.write("").unwrap();
    assert!(text.contains("kerning_source = \"kern table\"\n"), "{text}");
    assert_eq!(FontEnvironment::parse(&text), Ok(environment));
}

#[test]
fn a_list_that_holds_an_entry_twice_keeps_its_first() {
    let environment = FontEnvironment::new(vec![
        face("Calibri", "Bold", "Version 1", Some(KerningSource::Gpos)),
        face("Calibri", "Bold", "Version 1", None),
    ])
    .with_lacking(vec![
        lacking("Other", Some("Calibri")),
        lacking("OTHER", None),
    ]);
    assert_eq!(
        environment.faces(),
        [face(
            "Calibri",
            "Bold",
            "Version 1",
            Some(KerningSource::Gpos)
        )]
    );
    assert_eq!(environment.lacking(), [lacking("Other", Some("Calibri"))]);
}

#[test]
fn refuses_a_key_or_an_entry_that_the_text_holds_twice() {
    let face = "[[face]]\nfamily = \"Calibri\"\nstyle = \"Bold\"\nversion = \"1\"\n";
    assert!(FontEnvironment::parse(face).is_ok());
    let cases = [
        (
            format!("{face}style = \"Italic\"\n"),
            EnvironmentError::Repeated("style".to_owned()),
        ),
        (
            format!("{face}{face}"),
            EnvironmentError::Repeated("Calibri, Bold, 1".to_owned()),
        ),
        (
            "[[lacking]]\nfamily = \"B Zar\"\n[[lacking]]\nfamily = \"b zar\"\n".to_owned(),
            EnvironmentError::Repeated("b zar".to_owned()),
        ),
        (
            "[[available]]\nname = \"Arial\"\n[[available]]\nname = \"ARIAL\"\n".to_owned(),
            EnvironmentError::Repeated("ARIAL".to_owned()),
        ),
    ];
    for (text, error) in cases {
        assert_eq!(FontEnvironment::parse(&text), Err(error), "{text}");
    }
    // Two faces that differ only in the case of the family are two faces.
    let other_case = format!("{face}{}", face.replace("Calibri", "calibri"));
    assert_eq!(
        FontEnvironment::parse(&other_case).unwrap().faces().len(),
        2
    );
}

#[test]
fn refuses_wrong_environments() {
    let cases = [
        (
            "name = \"x\"\n",
            EnvironmentError::Line("name = \"x\"".to_owned()),
        ),
        (
            "[[font]]\nname = \"x\"\n",
            EnvironmentError::Line("[[font]]".to_owned()),
        ),
        (
            "[[face]]\nfamily = \"x\"\nwidth = 3\n",
            EnvironmentError::Line("width".to_owned()),
        ),
        (
            "[[face]]\nfamily = \"x\"\nstyle = \"s\"\n",
            EnvironmentError::Entry("x".to_owned()),
        ),
        (
            "[[face]]\nfamily = \"\"\nstyle = \"s\"\nversion = \"v\"\n",
            EnvironmentError::Entry(String::new()),
        ),
        (
            "[[face]]\nfamily = \"x\"\nstyle = \"s\"\nversion = 3\n",
            EnvironmentError::Entry("x".to_owned()),
        ),
        (
            "[[face]]\nfamily = \"x\"\nstyle = \"s\"\nversion = \"v\"\nkerning_source = \"no file\"\n",
            EnvironmentError::Entry("x".to_owned()),
        ),
        (
            "[[lacking]]\nfamily = \"x\"\ndocuments = 3\n",
            EnvironmentError::Line("documents".to_owned()),
        ),
        (
            "[[lacking]]\ndrawn_with = \"y\"\n",
            EnvironmentError::Entry(String::new()),
        ),
    ];
    for (text, error) in cases {
        assert_eq!(FontEnvironment::parse(text), Err(error), "{text}");
    }
    for text in [
        "[[available]]",
        "[[available]]\nname = 3",
        "[[available]]\nname = \"\"",
        "[[available]]\nfamily = \"Calibri\"",
    ] {
        assert!(FontEnvironment::parse(text).is_err(), "{text}");
    }
    for (error, text) in [
        (EnvironmentError::Entry("x".to_owned()), "\"x\""),
        (EnvironmentError::Line("y".to_owned()), "\"y\""),
        (EnvironmentError::Repeated("z".to_owned()), "\"z\" twice"),
    ] {
        assert!(error.to_string().contains(text), "{error}");
    }
}

/// The faces of one character set: the family's name and pitch, as "family-pitch".
fn metafile_faces(charset: u8) -> MetafileFaces {
    MetafileFaces {
        charset,
        faces: (0..6)
            .flat_map(|family| (0..3).map(move |pitch| format!("Face {family}-{pitch}")))
            .collect(),
    }
}

/// The sample with a listing of Calibri, the faces of the OEM and ANSI sets and the mapper
/// name System.
fn with_metafile_faces() -> FontEnvironment {
    sample()
        .with_available(vec![FamilyName::from_static("Calibri")])
        .with_metafile_faces(vec![metafile_faces(255), metafile_faces(0)])
        .with_mapper_names(vec![FamilyName::from_static("System")])
}

#[test]
fn writes_and_reads_the_metafile_faces() {
    let environment = with_metafile_faces();
    let text = environment.write("").unwrap();
    for line in [
        "\n[[metafile_faces]]\ncharset = 0\nfaces = \"Face 0-0, Face 0-1, Face 0-2, Face 1-0,",
        "\n[[mapper_name]]\nname = \"System\"\n",
    ] {
        assert!(text.contains(line), "{text}");
    }
    assert_eq!(FontEnvironment::parse(&text).unwrap(), environment);
}

#[test]
fn looks_up_the_metafile_faces() {
    let environment = with_metafile_faces();
    let cases = [
        // Variable pitch (2) of the roman family (1), and fixed pitch (1) of the decorative (5).
        ("Missing", 255, 0x12, Some("Face 1-2")),
        ("Missing", 0, 0x51, Some("Face 5-1")),
        // A character set, family or pitch outside the table has no face.
        ("Missing", 2, 0x00, None),
        ("Missing", 0, 0x60, None),
        ("Missing", 0, 0x03, None),
        // The table holds only for a name that the mapper does not know: not a listed family,
        // a name that the mapper knows outside the listing or a vertical form.
        ("calibri", 0, 0x00, None),
        ("SYSTEM", 0, 0x00, None),
        ("@Missing", 0, 0x00, None),
    ];
    for (family, charset, pitch_and_family, face) in cases {
        assert_eq!(
            environment.metafile_face(family, charset, pitch_and_family),
            face,
            "{family} {charset} {pitch_and_family:#04x}"
        );
    }
    // Without a full listing nothing tells that the target lacks a family.
    let unlisted = sample().with_metafile_faces(vec![metafile_faces(0)]);
    assert_eq!(unlisted.metafile_face("Missing", 0, 0x00), None);
}

#[test]
fn refuses_wrong_metafile_faces() {
    let owner = || EnvironmentError::Entry("metafile faces".to_owned());
    let mut five = metafile_faces(0);
    five.faces.truncate(5);
    let cases = [
        (
            "[[metafile_faces]]\ncharset = 0\nfaces = \"Arial\"\n".to_owned(),
            owner(),
        ),
        (
            "[[metafile_faces]]\ncharset = 300\nfaces = \"Arial\"\n".to_owned(),
            owner(),
        ),
        (
            format!(
                "[[metafile_faces]]\ncharset = 0\nfaces = \"{}\"\n",
                five.faces.join(", ")
            ),
            owner(),
        ),
        (
            "[[metafile_faces]]\ncharset = 0\nface = \"Arial\"\n".to_owned(),
            EnvironmentError::Line("face".to_owned()),
        ),
    ];
    for (text, error) in cases {
        assert_eq!(FontEnvironment::parse(&text), Err(error), "{text}");
    }
    let twice = FontEnvironment::default()
        .with_metafile_faces(vec![metafile_faces(0)])
        .write("")
        .unwrap()
        .repeat(2);
    assert_eq!(
        FontEnvironment::parse(&twice),
        Err(EnvironmentError::Repeated(
            "metafile faces of character set 0".to_owned()
        ))
    );
}

#[test]
fn writes_and_reads_own_face_units_per_em_and_refuses_zero() {
    let mut simsun = face("SimSun", "Regular", "Version 5.24", None);
    simsun.units_per_em = Some(256);
    let env = FontEnvironment::new(vec![simsun]);
    let written = env.write("").unwrap();
    assert!(written.contains("units_per_em = 256\n"), "{written}");
    assert_eq!(FontEnvironment::parse(&written), Ok(env));

    let zero = "[[face]]\nfamily = \"SimSun\"\nstyle = \"Regular\"\nversion = \"5.24\"\nunits_per_em = 0\n";
    assert_eq!(
        FontEnvironment::parse(zero),
        Err(EnvironmentError::Entry("SimSun".to_owned()))
    );
}