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
//! Values of the `MATH` table (OpenType specification) for the layout of equations: the
//! constants that place the limits of n-ary operators and accents, the larger variants of
//! glyphs that displays and growing delimiters draw, the wider variants and assemblies of
//! accents, the bars over and under a base, the top accent attachments, the italic corrections
//! of glyphs, and the kerns and the space that place scripts.

use skrifa::GlyphId;
use skrifa::raw::TableProvider;
use skrifa::raw::tables::math::{MathConstant, MathKernCorner, StretchAxis};

use crate::{FontDb, FontId};

/// The constants of a font's `MATH` table that place the limits of an n-ary operator in a
/// display, and the room above them, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathLimits {
    /// The white space to leave between lines of math (`MathLeading`).
    pub math_leading: i32,
    /// The least height of an n-ary operator drawn in a display (`DisplayOperatorMinHeight`).
    pub display_operator_min_height: i32,
    /// The least distance from the top of an n-ary operator's ink up to the baseline of its
    /// upper limit (`UpperLimitBaselineRiseMin`).
    pub upper_limit_baseline_rise_min: i32,
    /// The least distance from the bottom of an n-ary operator's ink down to the baseline of
    /// its lower limit (`LowerLimitBaselineDropMin`).
    pub lower_limit_baseline_drop_min: i32,
    /// The greatest distance from the top of a base's ink down to the baseline of its
    /// superscript (`SuperscriptBaselineDropMax`).
    pub superscript_baseline_drop_max: i32,
    /// The least distance from the bottom of a base's ink down to the baseline of its
    /// subscript (`SubscriptBaselineDropMin`).
    pub subscript_baseline_drop_min: i32,
    /// The least height of delimited content that counts as a subformula
    /// (`DelimitedSubFormulaMinHeight`).
    pub delimited_sub_formula_min_height: i32,
}

/// A corner of a glyph whose kern in a font's `MATH` table moves a script beside it: a
/// superscript after the glyph kerns into its top right corner, a subscript into its bottom
/// right, and the script's first glyph into its own bottom left or top left.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MathCorner {
    /// Above and to the right.
    TopRight,
    /// Above and to the left.
    TopLeft,
    /// Below and to the right.
    BottomRight,
    /// Below and to the left.
    BottomLeft,
}

/// The constants of a font's `MATH` table that place the root sign, the bar and the degree of
/// a radical, and the room above them, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathRadical {
    /// The space between the top of the element's ink and the bar over it, in a line of text
    /// (`RadicalVerticalGap`).
    pub vertical_gap: i32,
    /// The thickness of the bar (`RadicalRuleThickness`).
    pub rule_thickness: i32,
    /// The white space above the bar (`RadicalExtraAscender`).
    pub extra_ascender: i32,
    /// The space before the degree (`RadicalKernBeforeDegree`).
    pub kern_before_degree: i32,
    /// The space after the degree, before the root sign, mostly below zero
    /// (`RadicalKernAfterDegree`).
    pub kern_after_degree: i32,
    /// The height of the degree's baseline above the bottom of the root sign, in percent of the
    /// sign's height (`RadicalDegreeBottomRaisePercent`).
    pub degree_bottom_raise_percent: i32,
    /// The height up to which a base keeps its accent without flattening it
    /// (`FlattenedAccentBaseHeight`).
    pub flattened_accent_base_height: i32,
}

/// The constants of a font's `MATH` table that place the bar over or under a base (an overbar
/// or an underbar), and the room beyond it, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathBars {
    /// The space between the top of the base's ink and an overbar (`OverbarVerticalGap`).
    pub overbar_vertical_gap: i32,
    /// The thickness of an overbar (`OverbarRuleThickness`).
    pub overbar_rule_thickness: i32,
    /// The white space above an overbar (`OverbarExtraAscender`).
    pub overbar_extra_ascender: i32,
    /// The space between the bottom of the base's ink and an underbar (`UnderbarVerticalGap`).
    pub underbar_vertical_gap: i32,
    /// The thickness of an underbar (`UnderbarRuleThickness`).
    pub underbar_rule_thickness: i32,
    /// The white space below an underbar (`UnderbarExtraDescender`).
    pub underbar_extra_descender: i32,
}

/// The constants of a font's `MATH` table that place the numerator and the denominator of a
/// skewed fraction, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathSkewedFraction {
    /// The horizontal space between the numerator and the denominator
    /// (`SkewedFractionHorizontalGap`).
    pub horizontal_gap: i32,
    /// The vertical space between the numerator's ink and the denominator's ink
    /// (`SkewedFractionVerticalGap`).
    pub vertical_gap: i32,
}

/// The ink gap minimums of a font's `MATH` table for lower and upper limits, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathLimitGaps {
    /// The least distance between the base's ink bottom and the lower limit's ink top
    /// (`LowerLimitGapMin`).
    pub lower_limit_gap_min: i32,
    /// The least distance between the base's ink top and the upper limit's ink bottom
    /// (`UpperLimitGapMin`).
    pub upper_limit_gap_min: i32,
}

/// The constants of a font's `MATH` table that place a grouping character (`m:groupChr`) and its
/// base, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathStretchStack {
    /// The minimum upward shift of the base above a bottom-aligned grouping character
    /// (`StretchStackTopShiftUp`).
    pub top_shift_up: i32,
    /// The minimum downward shift of the base below a top-aligned grouping character
    /// (`StretchStackBottomShiftDown`).
    pub bottom_shift_down: i32,
    /// The minimum vertical gap above a grouping character (`StretchStackGapAboveMin`).
    pub gap_above_min: i32,
    /// The minimum vertical gap below a grouping character (`StretchStackGapBelowMin`).
    pub gap_below_min: i32,
    /// The least overlap of two parts of a glyph assembly (`MinConnectorOverlap`).
    pub min_connector_overlap: i32,
}

/// The constants of a font's `MATH` table that choose and place an accent over its base, in
/// font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathAccent {
    /// The height up to which a base keeps its accent where the accent's glyph stands
    /// (`AccentBaseHeight`).
    pub accent_base_height: i32,
    /// The height up to which a base keeps its accent without flattening it
    /// (`FlattenedAccentBaseHeight`).
    pub flattened_accent_base_height: i32,
    /// The least overlap of two parts of a glyph assembly (`MinConnectorOverlap`).
    pub min_connector_overlap: i32,
}

/// One part of a glyph assembly of a font's `MATH` table, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AssemblyPart {
    /// The part's glyph.
    pub glyph: u32,
    /// The maximum overlap length at the start of the part (`startConnectorLength`).
    pub start_connector_length: i32,
    /// The maximum overlap length at the end of the part (`endConnectorLength`).
    pub end_connector_length: i32,
    /// The length of the part along the assembly (`fullAdvance`).
    pub full_advance: i32,
    /// Whether the part can be left out or repeated.
    pub extender: bool,
}

/// How a font's `MATH` table makes a glyph wider: its horizontal size variants, each with its
/// advance measurement in font units, the glyph itself first in the fonts that list it, and the
/// parts of its glyph assembly, if it has one.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HorizontalConstruction {
    /// The variants, from the narrowest.
    pub variants: Vec<(u32, i32)>,
    /// The parts of the glyph assembly, from the left; none for a glyph without one.
    pub assembly: Vec<AssemblyPart>,
}

impl FontDb {
    /// Returns the constants of a font's `MATH` table that choose and place an accent.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_accent(&self, id: FontId) -> Option<MathAccent> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        let variants = math.math_variants().ok()?;
        Some(MathAccent {
            accent_base_height: constants.constant(MathConstant::AccentBaseHeight),
            flattened_accent_base_height: constants
                .constant(MathConstant::FlattenedAccentBaseHeight),
            min_connector_overlap: i32::from(variants.min_connector_overlap().to_u16()),
        })
    }

    /// Returns the top accent attachment of a glyph in the font's `MATH` table
    /// (`MathTopAccentAttachment`), in font units from the glyph's origin: where an accent
    /// over the glyph is centered.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
    /// table does not list. The device tables of the values are ignored.
    #[must_use]
    pub fn top_accent_attachment(&self, id: FontId, glyph: u32) -> Option<i32> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let table = math
            .math_glyph_info()
            .ok()?
            .math_top_accent_attachment()?
            .ok()?;
        let index = table.top_accent_coverage().ok()?.get(GlyphId::new(glyph))?;
        table
            .top_accent_attachment()
            .get(usize::try_from(index).ok()?)
            .map(|record| i32::from(record.value().to_i16()))
    }

    /// Returns how the font's `MATH` table makes a glyph wider: its horizontal variants and
    /// the parts of its glyph assembly.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
    /// table does not make wider.
    #[must_use]
    pub fn horizontal_construction(
        &self,
        id: FontId,
        glyph: u32,
    ) -> Option<HorizontalConstruction> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let construction = math
            .math_variants()
            .ok()?
            .glyph_construction(GlyphId::new(glyph), StretchAxis::Horizontal)?;
        let variants = construction
            .math_glyph_variant_records()
            .iter()
            .map(|record| {
                (
                    record.variant_glyph().to_u32(),
                    i32::from(record.advance_measurement().to_u16()),
                )
            })
            .collect();
        let assembly = construction
            .glyph_assembly()
            .and_then(Result::ok)
            .map_or_default(|assembly| {
                assembly
                    .part_records()
                    .iter()
                    .map(|part| AssemblyPart {
                        glyph: part.glyph_id().to_u32(),
                        start_connector_length: i32::from(part.start_connector_length().to_u16()),
                        end_connector_length: i32::from(part.end_connector_length().to_u16()),
                        full_advance: i32::from(part.full_advance().to_u16()),
                        extender: part.part_flags().bits() & 1 != 0,
                    })
                    .collect()
            });
        Some(HorizontalConstruction { variants, assembly })
    }

    /// Returns the constants of a font's `MATH` table that place the root sign, the bar and the
    /// degree of a radical, and the room above them.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_radical(&self, id: FontId) -> Option<MathRadical> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(MathRadical {
            vertical_gap: constants.constant(MathConstant::RadicalVerticalGap),
            rule_thickness: constants.constant(MathConstant::RadicalRuleThickness),
            extra_ascender: constants.constant(MathConstant::RadicalExtraAscender),
            kern_before_degree: constants.constant(MathConstant::RadicalKernBeforeDegree),
            kern_after_degree: constants.constant(MathConstant::RadicalKernAfterDegree),
            degree_bottom_raise_percent: constants
                .constant(MathConstant::RadicalDegreeBottomRaisePercent),
            flattened_accent_base_height: constants
                .constant(MathConstant::FlattenedAccentBaseHeight),
        })
    }

    /// Returns the constants of a font's `MATH` table that place an overbar and an underbar,
    /// and the room beyond them.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_bars(&self, id: FontId) -> Option<MathBars> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(MathBars {
            overbar_vertical_gap: constants.constant(MathConstant::OverbarVerticalGap),
            overbar_rule_thickness: constants.constant(MathConstant::OverbarRuleThickness),
            overbar_extra_ascender: constants.constant(MathConstant::OverbarExtraAscender),
            underbar_vertical_gap: constants.constant(MathConstant::UnderbarVerticalGap),
            underbar_rule_thickness: constants.constant(MathConstant::UnderbarRuleThickness),
            underbar_extra_descender: constants.constant(MathConstant::UnderbarExtraDescender),
        })
    }

    /// Returns the constants of a font's `MATH` table that place the numerator and the
    /// denominator of a skewed fraction.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_skewed_fraction(&self, id: FontId) -> Option<MathSkewedFraction> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(MathSkewedFraction {
            horizontal_gap: constants.constant(MathConstant::SkewedFractionHorizontalGap),
            vertical_gap: constants.constant(MathConstant::SkewedFractionVerticalGap),
        })
    }

    /// Returns the ink gap minimums of a font's `MATH` table for lower and upper limits.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_limit_gaps(&self, id: FontId) -> Option<MathLimitGaps> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(MathLimitGaps {
            lower_limit_gap_min: constants.constant(MathConstant::LowerLimitGapMin),
            upper_limit_gap_min: constants.constant(MathConstant::UpperLimitGapMin),
        })
    }

    /// Returns the constants of a font's `MATH` table that place a grouping character and its
    /// base.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_stretch_stack(&self, id: FontId) -> Option<MathStretchStack> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        let variants = math.math_variants().ok()?;
        Some(MathStretchStack {
            top_shift_up: constants.constant(MathConstant::StretchStackTopShiftUp),
            bottom_shift_down: constants.constant(MathConstant::StretchStackBottomShiftDown),
            gap_above_min: constants.constant(MathConstant::StretchStackGapAboveMin),
            gap_below_min: constants.constant(MathConstant::StretchStackGapBelowMin),
            min_connector_overlap: i32::from(variants.min_connector_overlap().to_u16()),
        })
    }

    /// Returns the constants of a font's `MATH` table that place the limits of an n-ary
    /// operator in a display, and the room above them.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device tables of the values are ignored.
    #[must_use]
    pub fn math_limits(&self, id: FontId) -> Option<MathLimits> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(MathLimits {
            math_leading: constants.constant(MathConstant::MathLeading),
            display_operator_min_height: constants.constant(MathConstant::DisplayOperatorMinHeight),
            upper_limit_baseline_rise_min: constants
                .constant(MathConstant::UpperLimitBaselineRiseMin),
            lower_limit_baseline_drop_min: constants
                .constant(MathConstant::LowerLimitBaselineDropMin),
            superscript_baseline_drop_max: constants
                .constant(MathConstant::SuperscriptBaselineDropMax),
            subscript_baseline_drop_min: constants.constant(MathConstant::SubscriptBaselineDropMin),
            delimited_sub_formula_min_height: constants
                .constant(MathConstant::DelimitedSubFormulaMinHeight),
        })
    }

    /// Returns the italic correction of a glyph in the font's `MATH` table
    /// (`MathItalicsCorrectionInfo`), in font units: how far a superscript after the glyph
    /// starts right of a subscript.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
    /// table does not list. The device tables of the values are ignored.
    #[must_use]
    pub fn italic_correction(&self, id: FontId, glyph: u32) -> Option<i32> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let info = math
            .math_glyph_info()
            .ok()?
            .math_italics_correction_info()?
            .ok()?;
        let index = info.coverage().ok()?.get(GlyphId::new(glyph))?;
        info.italics_correction()
            .get(usize::try_from(index).ok()?)
            .map(|record| i32::from(record.value().to_i16()))
    }

    /// Returns the space that the font's `MATH` table leaves after a subscript or a
    /// superscript (`SpaceAfterScript`), in font units.
    ///
    /// Returns `None` for an unknown face and a font without the table or its constants.
    /// The device table of the value is ignored.
    #[must_use]
    pub fn space_after_script(&self, id: FontId) -> Option<i32> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let constants = math.math_constants().ok()?;
        Some(constants.constant(MathConstant::SpaceAfterScript))
    }

    /// Returns the kern of a corner of a glyph at a height in the font's `MATH` table
    /// (`MathKernInfo`), in font units: how far a script at that height beside the corner moves
    /// toward the glyph, negative for a move away from it. `height` is in font units from the
    /// glyph's baseline, up positive; a height at a band's lower correction height takes that
    /// band's kern.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph whose corner
    /// the table does not list. The device tables of the values are ignored.
    #[must_use]
    pub fn math_kern(
        &self,
        id: FontId,
        glyph: u32,
        corner: MathCorner,
        height: i32,
    ) -> Option<i32> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let info = math.math_glyph_info().ok()?.math_kern_info()?.ok()?;
        let corner = match corner {
            MathCorner::TopRight => MathKernCorner::TopRight,
            MathCorner::TopLeft => MathKernCorner::TopLeft,
            MathCorner::BottomRight => MathKernCorner::BottomRight,
            MathCorner::BottomLeft => MathKernCorner::BottomLeft,
        };
        info.kern(GlyphId::new(glyph), corner)?.kerning(height)
    }

    /// Returns the glyph that a display draws for an n-ary operator: the first of the
    /// glyph's vertical variants in the font's `MATH` table whose height is at least the
    /// table's `DisplayOperatorMinHeight`.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph that has no
    /// such variant.
    #[must_use]
    pub fn display_variant(&self, id: FontId, glyph: u32) -> Option<u32> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let least = math
            .math_constants()
            .ok()?
            .constant(MathConstant::DisplayOperatorMinHeight);
        self.vertical_variant(id, glyph, least)
            .filter(|&(_, reached)| reached)
            .map(|(variant, _)| variant)
    }

    /// Returns the first of the glyph's vertical variants in the font's `MATH` table whose
    /// height (its advance measurement) is at least `least` font units, with `true`; or else
    /// the tallest variant, with `false`. The variants start with the glyph itself in the
    /// fonts that list it, such as Cambria Math.
    ///
    /// Returns `None` for an unknown face, a font without the table, and a glyph that has no
    /// vertical variants.
    #[must_use]
    pub fn vertical_variant(&self, id: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
        let math = self.face(id)?.font()?.tables().math().ok()?;
        let construction = math
            .math_variants()
            .ok()?
            .glyph_construction(GlyphId::new(glyph), StretchAxis::Vertical)?;
        let records = construction.math_glyph_variant_records();
        records
            .iter()
            .find(|record| i32::from(record.advance_measurement().to_u16()) >= least)
            .map(|record| (record.variant_glyph().to_u32(), true))
            .or_else(|| {
                records
                    .last()
                    .map(|record| (record.variant_glyph().to_u32(), false))
            })
    }
}