f-office-docx 0.1.0

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
//! The symbol stand-in face: the face that the font choice gives a symbol font that the caller
//! has no file of. It lays out with the target's font environment symbol metrics, and draws each
//! code with the glyph of Noto Symbols CF ([`SymbolFont::DRAWING_FAMILY`]) for the character
//! that the code stands for, centered in the code's width. Its font ID lies past the faces of
//! the font database, so only the font choice answers for it, and the font choice turns its
//! glyph runs into runs of Noto Symbols CF when the layout ends
//! ([`FontChoice::draw_symbol_stand_ins`]).

use std::collections::BTreeMap;

use f_office_fonts::{
    Decoration, FaceClassification, FamilyName, FontDb, FontId, FontMetrics, LineMetrics,
    Os2Metrics, OutlineError, PathCommand, Point, ScriptMetrics, ShapeDirection, ShapeRequest,
    ShapedGlyph, SymbolFont, plain_device_width,
};
use f_office_paint::{DisplayList, GlyphRun, Item, Turn};
use f_office_units::Length;
use f_office_units::scale::THOUSANDTHS;

use super::{FontChoice, apply_line, font_units, metrics_of};
use crate::profile::fonts::{SymbolFileMetrics, SymbolFontEntry};
use crate::{ChosenFace, OutlineCommand};

/// Symbol-font metrics defined by the target's font environment.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SymbolFonts(Vec<(SymbolFont, SymbolWidths)>);

impl SymbolFonts {
    /// The numbers of the symbol fonts of the font environment's `symbol_font` tables.
    ///
    /// # Errors
    ///
    /// The key of the tables when a family is not a symbol font, or when an entry lacks a value
    /// or holds a code or size that is not one.
    pub(crate) fn of(table: &BTreeMap<String, SymbolFontEntry>) -> Result<Self, &'static str> {
        table
            .iter()
            .map(|(family, entry)| {
                let font = SymbolFont::of(family).ok_or("symbol_font")?;
                Ok((font, SymbolWidths::of(entry)?))
            })
            .collect::<Result<_, _>>()
            .map(Self)
    }

    /// The place among the fonts and the numbers of the symbol font `font`, if the font
    /// environment holds them.
    pub(crate) fn get(&self, font: SymbolFont) -> Option<(usize, &SymbolWidths)> {
        (self.0.iter().enumerate())
            .find(|(_, (of, _))| *of == font)
            .map(|(at, (_, widths))| (at, widths))
    }

    /// The place among the fonts and the numbers of the symbol font that `name` names: by its
    /// family, such as Symbol, or by the PostScript name of the target's file of it, such as
    /// `SymbolMT`, as the font database finds a face by either name. The full name of each
    /// symbol font's file is its family.
    pub(crate) fn named(&self, name: &str) -> Option<(usize, &SymbolWidths)> {
        if let Some(font) = SymbolFont::of(name) {
            return self.get(font);
        }
        let name = FamilyName::new(name);
        (self.0.iter().enumerate())
            .find(|(_, (_, widths))| name.is(&widths.postscript_name))
            .map(|(at, (_, widths))| (at, widths))
    }

    /// The symbol font at the place `at` among the fonts and its numbers.
    pub(crate) fn at(&self, at: usize) -> Option<(SymbolFont, &SymbolWidths)> {
        self.0.get(at).map(|(font, widths)| (*font, widths))
    }
}

/// Target font environment metrics of one symbol font: names,
/// metrics and classification, the widths of each mapped code and missing glyph,
/// and device heights.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SymbolWidths {
    /// The file's PostScript name.
    pub(crate) postscript_name: String,
    /// The file's version string, such as "Version 5.01".
    pub(crate) version: String,
    /// The file's metrics, in its own font units.
    pub(crate) metrics: FontMetrics,
    /// The file's classification.
    pub(crate) classification: FaceClassification,
    /// The largest size in device dots per em whose device widths `codes` hold steps of.
    measured_sizes: u16,
    /// The widths of each code, at the place of the code, none for a code that the file does
    /// not map, and the widths of the missing glyph at the place `MISSING_GLYPH`, which no code
    /// takes.
    codes: Vec<Option<CodeWidths>>,
    /// The device heights by size, in the order of the sizes: each size in pixels per em with
    /// the largest height above the baseline and the largest depth below it.
    heights: Vec<[i16; 3]>,
}

/// The glyph of a symbol stand-in face that the file of its font draws for a character that it
/// does not map, the missing glyph, and the place of its widths among the codes: the codes of
/// a symbol font are 0x20 to 0xFF, so none is 0.
const MISSING_GLYPH: u32 = 0;

/// The widths of one code of a symbol font's file.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct CodeWidths {
    /// The advance in font units.
    advance: u16,
    /// The width in thousandths of an em that the target's PDF writer writes, where it differs
    /// from the advance rounded to thousandths.
    written: Option<u16>,
    /// The sizes, in order, at which the device width is one dot wider than the plain one.
    wider: Vec<u16>,
    /// The sizes, in order, at which the device width is one dot narrower than the plain one.
    narrower: Vec<u16>,
}

impl SymbolWidths {
    /// The numbers of one entry of the `symbol_font` tables.
    ///
    /// # Errors
    ///
    /// The key of the value that the entry lacks, or that holds a code or a size that is not
    /// one.
    fn of(entry: &SymbolFontEntry) -> Result<Self, &'static str> {
        let units_per_em = entry
            .units_per_em
            .filter(|&units| units > 0)
            .ok_or("units_per_em")?;
        let file = entry.metrics.as_ref().ok_or("metrics")?;
        // One place for each code of one byte.
        let mut codes = vec![None; usize::from(u8::MAX) + 1];
        for (key, &advance) in &entry.advance {
            let at = place(key).ok_or("advance")?;
            let slot = codes.get_mut(at).ok_or("advance")?;
            *slot = Some(CodeWidths {
                advance,
                ..CodeWidths::default()
            });
        }
        for (key, &width) in &entry.written {
            code_mut(&mut codes, key).ok_or("written")?.written = Some(width);
        }
        for (key, sizes) in &entry.wider {
            code_mut(&mut codes, key).ok_or("wider")?.wider = in_order(sizes).ok_or("wider")?;
        }
        for (key, sizes) in &entry.narrower {
            code_mut(&mut codes, key).ok_or("narrower")?.narrower =
                in_order(sizes).ok_or("narrower")?;
        }
        let sizes: Vec<u16> = (entry.heights.iter())
            .map(|&[pels, ..]| u16::try_from(pels).ok())
            .collect::<Option<_>>()
            .ok_or("heights")?;
        in_order(&sizes).ok_or("heights")?;
        Ok(Self {
            postscript_name: entry.postscript_name.clone().ok_or("postscript_name")?,
            version: entry.version.clone().ok_or("version")?,
            metrics: file_metrics(units_per_em, file),
            classification: FaceClassification {
                panose: file.panose,
                east_asian: file.east_asian,
            },
            measured_sizes: entry.measured_sizes.ok_or("measured_sizes")?,
            codes,
            heights: entry.heights.clone(),
        })
    }

    /// The units per em of the file, which measure its advances and metrics.
    pub(crate) const fn units_per_em(&self) -> u16 {
        self.metrics.units_per_em
    }

    /// The code 0x20 to 0xFF that the file maps the character `ch` to: a code written as
    /// U+F020 to U+F0FF, or as U+0020 to U+00FF, which the file takes as the same code.
    pub(crate) fn code(&self, ch: char) -> Option<u32> {
        let code = u32::from(SymbolFont::code(ch)?);
        self.widths(code).map(|_| code)
    }

    /// The advance of the code `code`, or of the missing glyph (`MISSING_GLYPH`), in font
    /// units, if the file maps the code.
    pub(crate) fn advance(&self, code: u32) -> Option<u16> {
        self.widths(code).map(|widths| widths.advance)
    }

    /// The width in thousandths of an em that the target's PDF writer writes for the code
    /// `code`: the file's bi-level advance at 1000 pixels per em, which is its advance rounded
    /// to thousandths, a half up, except where the table says otherwise.
    pub(crate) fn written(&self, code: u32) -> Option<u16> {
        let widths = self.widths(code)?;
        widths.written.or_else(|| {
            let units = i64::from(widths.advance) * THOUSANDTHS;
            let width = f_office_units::div_round(units, i64::from(self.units_per_em()));
            u16::try_from(width).ok()
        })
    }

    /// The device width of the code `code` in whole dots at `ppem` device dots per em: the
    /// plain device width of its advance, one dot wider or narrower at a size that the file's
    /// instructions move it at, up to the measured sizes.
    pub(crate) fn device_width(&self, code: u32, ppem: u16) -> Option<i32> {
        let widths = self.widths(code)?;
        let plain = plain_device_width(widths.advance, self.units_per_em(), ppem);
        let moved =
            |sizes: &[u16]| ppem <= self.measured_sizes && sizes.binary_search(&ppem).is_ok();
        Some(if moved(&widths.wider) {
            plain + 1
        } else if moved(&widths.narrower) {
            plain - 1
        } else {
            plain
        })
    }

    /// The device heights of the file at `pels` pixels per em, if its `VDMX` table lists the
    /// size.
    pub(crate) fn heights(&self, pels: u16) -> Option<(i16, i16)> {
        let pels = i16::try_from(pels).ok()?;
        let at = (self.heights)
            .binary_search_by_key(&pels, |&[size, ..]| size)
            .ok()?;
        self.heights.get(at).map(|&[_, top, bottom]| (top, bottom))
    }

    /// The widths of the code `code`, if the file maps it.
    fn widths(&self, code: u32) -> Option<&CodeWidths> {
        self.codes.get(usize::try_from(code).ok()?)?.as_ref()
    }
}

/// The character that the code `code` of the symbol font `font` stands for.
pub(crate) fn character(font: SymbolFont, code: u32) -> Option<char> {
    font.character(char::from(u8::try_from(code).ok()?))
}

/// The place of the code that a key of the tables names, the hexadecimal digits of the code's
/// private use form, F020 to F0FF, or of the missing glyph that the key
/// [`SymbolFontEntry::MISSING_GLYPH`] names.
fn place(key: &str) -> Option<usize> {
    if key == SymbolFontEntry::MISSING_GLYPH {
        return usize::try_from(MISSING_GLYPH).ok();
    }
    let value = u32::try_from(crate::numbers::hex(key)?).ok()?;
    let code = SymbolFont::code(char::from_u32(value)?)?;
    // A key of the code's own form, 0020 to 00FF, is not one.
    (u32::from(code) != value).then_some(usize::from(code))
}

/// The widths of the code that the key `key` names among `codes`, if the file maps it.
fn code_mut<'a>(codes: &'a mut [Option<CodeWidths>], key: &str) -> Option<&'a mut CodeWidths> {
    codes.get_mut(place(key)?)?.as_mut()
}

/// The sizes `sizes`, when each is larger than the one before.
fn in_order(sizes: &[u16]) -> Option<Vec<u16>> {
    sizes
        .windows(2)
        .all(|pair| matches!(pair, [before, after] if before < after))
        .then(|| sizes.to_vec())
}

/// The metrics of a symbol font's file of `units_per_em` from the values of its tables.
fn file_metrics(units_per_em: u16, file: &SymbolFileMetrics) -> FontMetrics {
    let line = |[ascender, descender, line_gap]: [i16; 3]| LineMetrics {
        ascender,
        descender,
        line_gap,
    };
    let script = |[x_size, y_size, x_offset, y_offset]: [i16; 4]| ScriptMetrics {
        x_size,
        y_size,
        x_offset,
        y_offset,
    };
    let decoration = |[position, thickness]: [i16; 2]| Decoration {
        position,
        thickness,
    };
    let [win_ascent, win_descent] = file.win;
    FontMetrics {
        units_per_em,
        hhea: line(file.hhea),
        os2: Some(Os2Metrics {
            average_width: file.average_width,
            typo: line(file.typo),
            win_ascent,
            win_descent,
            use_typo_metrics: file.use_typo_metrics,
            x_height: None,
            cap_height: None,
            strikeout: decoration(file.strikeout),
            subscript: script(file.subscript),
            superscript: script(file.superscript),
            east_asian: file.east_asian,
        }),
        underline: Some(decoration(file.underline)),
    }
}

/// The face of the font database that draws the codes of the symbol stand-in faces, with its
/// units per em and its glyph of the space, which draws a code that stands for no character.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct SymbolDrawing {
    font: FontId,
    units_per_em: u16,
    space: u32,
}

impl SymbolDrawing {
    /// The regular face of the family that draws the symbols of the symbol fonts
    /// ([`SymbolFont::DRAWING_FAMILY`]) in `db`, if `db` has one whose file loads.
    pub(super) fn of(db: &FontDb) -> Option<Self> {
        let family = FamilyName::from_static(SymbolFont::DRAWING_FAMILY);
        let font = db
            .query(&family, false, false)
            .filter(|&id| db.info(id).is_some_and(|info| family.is(&info.family)))?;
        db.load(font).ok()?;
        Some(Self {
            font,
            units_per_em: db.metrics(font)?.units_per_em,
            space: db.glyph_id(font, ' ').unwrap_or(0),
        })
    }
}

/// A symbol stand-in face: the symbol font, Word's numbers of it and the face that draws it.
#[derive(Clone, Copy, Debug)]
pub(super) struct SymbolFace<'a> {
    font: SymbolFont,
    pub(super) widths: &'a SymbolWidths,
    drawing: SymbolDrawing,
}

impl FontChoice<'_> {
    /// The symbol stand-in face whose font ID is `font`, if it is one: an ID past the faces of
    /// the database, at the place of its symbol font among the font environment's.
    pub(super) fn symbol_face(&self, font: FontId) -> Option<SymbolFace<'_>> {
        let drawing = self.symbol_drawing?;
        let at = font
            .index()
            .checked_sub(u32::try_from(self.db.len()).ok()?)?;
        let (symbol, widths) = self.symbols.at(usize::try_from(at).ok()?)?;
        Some(SymbolFace {
            font: symbol,
            widths,
            drawing,
        })
    }

    /// The symbol stand-in face of `family` when it names a symbol font, by its family or by the
    /// PostScript name of the target's file of it ([`SymbolFonts::named`]), whose numbers the
    /// font environment holds, and the database has the face that draws it. It lays out as the
    /// target's file of the font: with its metrics, and with Word's line for the family where
    /// the document names it and the line holds over the font's own file. The font has one
    /// regular face, so bold and italic are synthetic.
    pub(super) fn symbol_stand_in(
        &self,
        family: &str,
        (bold, italic): (bool, bool),
        named: bool,
    ) -> Option<ChosenFace> {
        self.symbol_drawing?;
        let (at, widths) = self.symbols.named(family)?;
        let first = u32::try_from(self.db.len()).ok()?;
        let font = FontId::from_index(first.checked_add(u32::try_from(at).ok()?)?);
        let own = metrics_of(&widths.metrics);
        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: bold,
            synthetic_italic: italic,
            stands_in: true,
        })
    }

    /// The glyph of the drawing face for the code `code` of the stand-in face `face`: its glyph
    /// of the character that the code stands for, else its space, and its own missing glyph
    /// for the missing glyph, which draws a box as the missing glyph of each symbol font's file
    /// does.
    fn symbol_glyph(&self, face: &SymbolFace<'_>, code: u32) -> u32 {
        if code == MISSING_GLYPH {
            return MISSING_GLYPH;
        }
        character(face.font, code)
            .and_then(|ch| self.db.glyph_id(face.drawing.font, ch))
            .filter(|&glyph| glyph != 0)
            .unwrap_or(face.drawing.space)
    }

    /// The outline of the code `code` of the stand-in face `face` in its own whole font units:
    /// the drawing face's outline of the code's glyph, each point at the nearest whole unit,
    /// scaled to the stand-in face's units per em and moved right by half the difference of the
    /// code's width and the drawn glyph's, so that it stands in the middle of the code's width,
    /// each point at the nearest whole unit again.
    ///
    /// # Errors
    ///
    /// The [`OutlineError`] of the drawing face's outline.
    pub(super) fn symbol_outline(
        &self,
        face: &SymbolFace<'_>,
        code: u32,
    ) -> Result<Vec<OutlineCommand>, OutlineError> {
        let glyph = self.symbol_glyph(face, code);
        let (own_em, drawn_em) = (
            i64::from(face.widths.units_per_em()),
            i64::from(face.drawing.units_per_em.max(1)),
        );
        let own = i64::from(face.widths.advance(code).unwrap_or(0));
        let drawn = i64::from(self.db.advance(face.drawing.font, glyph).unwrap_or(0));
        // Twice the shift, in the stand-in face's units times the drawing face's units per em.
        let shift = own * drawn_em - drawn * own_em;
        let scaled = |value: f32, shift: i64| {
            let value = i64::from(font_units(value.round()));
            let place = f_office_units::div_round(2 * value * own_em + shift, 2 * drawn_em);
            // A point beyond the range of whole units, which no font's outline holds, stays at
            // the range's end.
            i32::try_from(place).unwrap_or(if place < 0 { i32::MIN } else { i32::MAX })
        };
        let at = |p: Point| [scaled(p.x, shift), scaled(p.y, 0)];
        let outline = self.db.outline(face.drawing.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())
    }

    /// The lowest and highest heights of the outline of the code `code` of the stand-in face
    /// `face` ([`Self::symbol_outline`]), control points too, as the bounding box of a TrueType
    /// glyph counts them; none for an outline without points, such as a space's.
    ///
    /// # Errors
    ///
    /// The [`OutlineError`] of the drawing face's outline.
    pub(super) fn symbol_ink(
        &self,
        face: &SymbolFace<'_>,
        code: u32,
    ) -> Result<Option<(i32, i32)>, OutlineError> {
        let outline = self.symbol_outline(face, code)?;
        let heights = outline.iter().flat_map(|command| {
            let heights = match *command {
                OutlineCommand::MoveTo([_, y]) | OutlineCommand::LineTo([_, y]) => {
                    [Some(y), None, None]
                }
                OutlineCommand::QuadTo([_, c], [_, y]) => [Some(c), Some(y), None],
                OutlineCommand::CubicTo([_, c], [_, d], [_, y]) => [Some(c), Some(d), Some(y)],
                OutlineCommand::Close => [None, None, None],
            };
            heights.into_iter().flatten()
        });
        Ok(heights.fold(None, |range, y| {
            Some(range.map_or((y, y), |(low, high): (i32, i32)| (low.min(y), high.max(y))))
        }))
    }

    /// The glyphs of a text in the stand-in face `face`, as a shaper gives them for a face
    /// without substitutions and positions: each character's code, or the missing glyph, at its
    /// advance, in the order in which the text reads.
    pub(super) fn symbol_shape(
        face: &SymbolFace<'_>,
        request: &ShapeRequest<'_>,
    ) -> Vec<ShapedGlyph> {
        let mut glyphs: Vec<ShapedGlyph> = (request.text.char_indices())
            .map(|(cluster, ch)| {
                let glyph = face.widths.code(ch).unwrap_or(0);
                ShapedGlyph {
                    glyph,
                    advance: face.widths.advance(glyph).map_or(0, i32::from),
                    offset: (0, 0),
                    cluster,
                }
            })
            .collect();
        if request.direction == ShapeDirection::RightToLeft {
            glyphs.reverse();
        }
        glyphs
    }

    /// The width in thousandths of an em that the target's PDF writer writes for the code
    /// `glyph` of the stand-in face `face`, as the bi-level advance at `ppem` pixels per em when
    /// `ppem` is 1000; none at another size.
    pub(super) fn symbol_bi_level_advance(
        face: &SymbolFace<'_>,
        glyph: u32,
        ppem: u16,
    ) -> Option<i32> {
        (i64::from(ppem) == THOUSANDTHS)
            .then(|| face.widths.written(glyph))
            .flatten()
            .map(i32::from)
    }

    /// The family name and the version of the face that draws the stand-in face `face`, for the
    /// warning of a substituted font.
    pub(super) fn symbol_drawing_names(
        &self,
        face: &SymbolFace<'_>,
    ) -> Option<(String, Option<String>)> {
        let info = self.db.info(face.drawing.font)?;
        let version = info
            .version
            .as_deref()
            .map(|version| f_office_fonts::version_number(version).to_owned());
        Some((info.family.clone(), version))
    }

    /// The PostScript name and the version of the target's file of the font of the stand-in
    /// face `face`, when the font environment lists that file as the target's own face, so that
    /// the stand-in face steps as that file does: by its device widths where the target's own
    /// faces do, else by its advances rounded. The file of a symbol font has one face, its
    /// regular face.
    pub(super) fn symbol_target_face(&self, face: &SymbolFace<'_>) -> Option<(String, String)> {
        let widths = face.widths;
        self.environment
            .is_target_file(face.font.family(), "Regular", &widths.version)
            .then(|| (widths.postscript_name.clone(), widths.version.clone()))
    }

    /// The family whose layout the stand-in face `face` has: its symbol font.
    pub(super) fn symbol_family(face: &SymbolFace<'_>) -> String {
        face.font.family().to_owned()
    }

    /// The pages of `list` with each glyph run of a symbol stand-in face drawn with the face
    /// that draws it: each glyph is that face's glyph for its code, moved to the middle of the
    /// code's width along the run. The run's text and every other property stay.
    pub(crate) fn draw_symbol_stand_ins(&self, list: DisplayList) -> DisplayList {
        if self.symbol_drawing.is_none() {
            return list;
        }
        let pages = (list.into_pages().into_iter())
            .map(|page| page.map_items(|items| self.drawn_items(items)))
            .collect();
        DisplayList::new(pages)
    }

    /// The items `items` with the glyph runs of symbol stand-in faces drawn, in groups too.
    fn drawn_items(&self, items: Vec<Item>) -> Vec<Item> {
        items
            .into_iter()
            .map(|item| match item {
                Item::Glyphs(run) => Item::Glyphs(self.drawn_run(run)),
                Item::Group(mut group) => {
                    group.items = self.drawn_items(std::mem::take(&mut group.items));
                    Item::Group(group)
                }
                other => other,
            })
            .collect()
    }

    /// The glyph run `run` drawn with the face that draws its face, when its face is a symbol
    /// stand-in face.
    fn drawn_run(&self, mut run: GlyphRun) -> GlyphRun {
        let Some(face) = self.symbol_face(run.font) else {
            return run;
        };
        run.font = face.drawing.font;
        let size = run.size.units();
        let (own_em, drawn_em) = (
            i64::from(face.widths.units_per_em()),
            i64::from(face.drawing.units_per_em.max(1)),
        );
        let (along, down) = run.turn.map_or((i64::from(Turn::SCALE), 0), |turn| {
            (i64::from(turn.xx), i64::from(turn.yx))
        });
        let scale = i64::from(Turn::SCALE);
        for glyph in &mut run.glyphs {
            let code = glyph.id;
            glyph.id = self.symbol_glyph(&face, code);
            let own = i64::from(face.widths.advance(code).unwrap_or(0));
            let drawn = i64::from(self.db.advance(face.drawing.font, glyph.id).unwrap_or(0));
            // Half of the code's width less the drawn glyph's, each at the run's size.
            let shift = f_office_units::div_round(
                (own * drawn_em - drawn * own_em) * size,
                2 * own_em * drawn_em,
            );
            glyph.x += Length::from_units(f_office_units::div_round(shift * along, scale));
            glyph.y += Length::from_units(f_office_units::div_round(shift * down, scale));
        }
        run
    }
}

#[cfg(test)]
mod tests;