Skip to main content

f_office_fonts/
math.rs

1//! Values of the `MATH` table (OpenType specification) for the layout of equations: the
2//! constants that place the limits of n-ary operators and accents, the larger variants of
3//! glyphs that displays and growing delimiters draw, the wider variants and assemblies of
4//! accents, the bars over and under a base, the top accent attachments, the italic corrections
5//! of glyphs, and the kerns and the space that place scripts.
6
7use skrifa::GlyphId;
8use skrifa::raw::TableProvider;
9use skrifa::raw::tables::math::{MathConstant, MathKernCorner, StretchAxis};
10
11use crate::{FontDb, FontId};
12
13/// The constants of a font's `MATH` table that place the limits of an n-ary operator in a
14/// display, and the room above them, in font units.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct MathLimits {
17    /// The white space to leave between lines of math (`MathLeading`).
18    pub math_leading: i32,
19    /// The least height of an n-ary operator drawn in a display (`DisplayOperatorMinHeight`).
20    pub display_operator_min_height: i32,
21    /// The least distance from the top of an n-ary operator's ink up to the baseline of its
22    /// upper limit (`UpperLimitBaselineRiseMin`).
23    pub upper_limit_baseline_rise_min: i32,
24    /// The least distance from the bottom of an n-ary operator's ink down to the baseline of
25    /// its lower limit (`LowerLimitBaselineDropMin`).
26    pub lower_limit_baseline_drop_min: i32,
27    /// The greatest distance from the top of a base's ink down to the baseline of its
28    /// superscript (`SuperscriptBaselineDropMax`).
29    pub superscript_baseline_drop_max: i32,
30    /// The least distance from the bottom of a base's ink down to the baseline of its
31    /// subscript (`SubscriptBaselineDropMin`).
32    pub subscript_baseline_drop_min: i32,
33    /// The least height of delimited content that counts as a subformula
34    /// (`DelimitedSubFormulaMinHeight`).
35    pub delimited_sub_formula_min_height: i32,
36}
37
38/// A corner of a glyph whose kern in a font's `MATH` table moves a script beside it: a
39/// superscript after the glyph kerns into its top right corner, a subscript into its bottom
40/// right, and the script's first glyph into its own bottom left or top left.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum MathCorner {
43    /// Above and to the right.
44    TopRight,
45    /// Above and to the left.
46    TopLeft,
47    /// Below and to the right.
48    BottomRight,
49    /// Below and to the left.
50    BottomLeft,
51}
52
53/// The constants of a font's `MATH` table that place the root sign, the bar and the degree of
54/// a radical, and the room above them, in font units.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct MathRadical {
57    /// The space between the top of the element's ink and the bar over it, in a line of text
58    /// (`RadicalVerticalGap`).
59    pub vertical_gap: i32,
60    /// The thickness of the bar (`RadicalRuleThickness`).
61    pub rule_thickness: i32,
62    /// The white space above the bar (`RadicalExtraAscender`).
63    pub extra_ascender: i32,
64    /// The space before the degree (`RadicalKernBeforeDegree`).
65    pub kern_before_degree: i32,
66    /// The space after the degree, before the root sign, mostly below zero
67    /// (`RadicalKernAfterDegree`).
68    pub kern_after_degree: i32,
69    /// The height of the degree's baseline above the bottom of the root sign, in percent of the
70    /// sign's height (`RadicalDegreeBottomRaisePercent`).
71    pub degree_bottom_raise_percent: i32,
72    /// The height up to which a base keeps its accent without flattening it
73    /// (`FlattenedAccentBaseHeight`).
74    pub flattened_accent_base_height: i32,
75}
76
77/// The constants of a font's `MATH` table that place the bar over or under a base (an overbar
78/// or an underbar), and the room beyond it, in font units.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct MathBars {
81    /// The space between the top of the base's ink and an overbar (`OverbarVerticalGap`).
82    pub overbar_vertical_gap: i32,
83    /// The thickness of an overbar (`OverbarRuleThickness`).
84    pub overbar_rule_thickness: i32,
85    /// The white space above an overbar (`OverbarExtraAscender`).
86    pub overbar_extra_ascender: i32,
87    /// The space between the bottom of the base's ink and an underbar (`UnderbarVerticalGap`).
88    pub underbar_vertical_gap: i32,
89    /// The thickness of an underbar (`UnderbarRuleThickness`).
90    pub underbar_rule_thickness: i32,
91    /// The white space below an underbar (`UnderbarExtraDescender`).
92    pub underbar_extra_descender: i32,
93}
94
95/// The constants of a font's `MATH` table that place the numerator and the denominator of a
96/// skewed fraction, in font units.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub struct MathSkewedFraction {
99    /// The horizontal space between the numerator and the denominator
100    /// (`SkewedFractionHorizontalGap`).
101    pub horizontal_gap: i32,
102    /// The vertical space between the numerator's ink and the denominator's ink
103    /// (`SkewedFractionVerticalGap`).
104    pub vertical_gap: i32,
105}
106
107/// The ink gap minimums of a font's `MATH` table for lower and upper limits, in font units.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct MathLimitGaps {
110    /// The least distance between the base's ink bottom and the lower limit's ink top
111    /// (`LowerLimitGapMin`).
112    pub lower_limit_gap_min: i32,
113    /// The least distance between the base's ink top and the upper limit's ink bottom
114    /// (`UpperLimitGapMin`).
115    pub upper_limit_gap_min: i32,
116}
117
118/// The constants of a font's `MATH` table that place a grouping character (`m:groupChr`) and its
119/// base, in font units.
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct MathStretchStack {
122    /// The minimum upward shift of the base above a bottom-aligned grouping character
123    /// (`StretchStackTopShiftUp`).
124    pub top_shift_up: i32,
125    /// The minimum downward shift of the base below a top-aligned grouping character
126    /// (`StretchStackBottomShiftDown`).
127    pub bottom_shift_down: i32,
128    /// The minimum vertical gap above a grouping character (`StretchStackGapAboveMin`).
129    pub gap_above_min: i32,
130    /// The minimum vertical gap below a grouping character (`StretchStackGapBelowMin`).
131    pub gap_below_min: i32,
132    /// The least overlap of two parts of a glyph assembly (`MinConnectorOverlap`).
133    pub min_connector_overlap: i32,
134}
135
136/// The constants of a font's `MATH` table that choose and place an accent over its base, in
137/// font units.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct MathAccent {
140    /// The height up to which a base keeps its accent where the accent's glyph stands
141    /// (`AccentBaseHeight`).
142    pub accent_base_height: i32,
143    /// The height up to which a base keeps its accent without flattening it
144    /// (`FlattenedAccentBaseHeight`).
145    pub flattened_accent_base_height: i32,
146    /// The least overlap of two parts of a glyph assembly (`MinConnectorOverlap`).
147    pub min_connector_overlap: i32,
148}
149
150/// One part of a glyph assembly of a font's `MATH` table, in font units.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub struct AssemblyPart {
153    /// The part's glyph.
154    pub glyph: u32,
155    /// The maximum overlap length at the start of the part (`startConnectorLength`).
156    pub start_connector_length: i32,
157    /// The maximum overlap length at the end of the part (`endConnectorLength`).
158    pub end_connector_length: i32,
159    /// The length of the part along the assembly (`fullAdvance`).
160    pub full_advance: i32,
161    /// Whether the part can be left out or repeated.
162    pub extender: bool,
163}
164
165/// How a font's `MATH` table makes a glyph wider: its horizontal size variants, each with its
166/// advance measurement in font units, the glyph itself first in the fonts that list it, and the
167/// parts of its glyph assembly, if it has one.
168#[derive(Clone, Debug, Default, PartialEq, Eq)]
169pub struct HorizontalConstruction {
170    /// The variants, from the narrowest.
171    pub variants: Vec<(u32, i32)>,
172    /// The parts of the glyph assembly, from the left; none for a glyph without one.
173    pub assembly: Vec<AssemblyPart>,
174}
175
176impl FontDb {
177    /// Returns the constants of a font's `MATH` table that choose and place an accent.
178    ///
179    /// Returns `None` for an unknown face and a font without the table or its constants.
180    /// The device tables of the values are ignored.
181    #[must_use]
182    pub fn math_accent(&self, id: FontId) -> Option<MathAccent> {
183        let math = self.face(id)?.font()?.tables().math().ok()?;
184        let constants = math.math_constants().ok()?;
185        let variants = math.math_variants().ok()?;
186        Some(MathAccent {
187            accent_base_height: constants.constant(MathConstant::AccentBaseHeight),
188            flattened_accent_base_height: constants
189                .constant(MathConstant::FlattenedAccentBaseHeight),
190            min_connector_overlap: i32::from(variants.min_connector_overlap().to_u16()),
191        })
192    }
193
194    /// Returns the top accent attachment of a glyph in the font's `MATH` table
195    /// (`MathTopAccentAttachment`), in font units from the glyph's origin: where an accent
196    /// over the glyph is centered.
197    ///
198    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
199    /// table does not list. The device tables of the values are ignored.
200    #[must_use]
201    pub fn top_accent_attachment(&self, id: FontId, glyph: u32) -> Option<i32> {
202        let math = self.face(id)?.font()?.tables().math().ok()?;
203        let table = math
204            .math_glyph_info()
205            .ok()?
206            .math_top_accent_attachment()?
207            .ok()?;
208        let index = table.top_accent_coverage().ok()?.get(GlyphId::new(glyph))?;
209        table
210            .top_accent_attachment()
211            .get(usize::try_from(index).ok()?)
212            .map(|record| i32::from(record.value().to_i16()))
213    }
214
215    /// Returns how the font's `MATH` table makes a glyph wider: its horizontal variants and
216    /// the parts of its glyph assembly.
217    ///
218    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
219    /// table does not make wider.
220    #[must_use]
221    pub fn horizontal_construction(
222        &self,
223        id: FontId,
224        glyph: u32,
225    ) -> Option<HorizontalConstruction> {
226        let math = self.face(id)?.font()?.tables().math().ok()?;
227        let construction = math
228            .math_variants()
229            .ok()?
230            .glyph_construction(GlyphId::new(glyph), StretchAxis::Horizontal)?;
231        let variants = construction
232            .math_glyph_variant_records()
233            .iter()
234            .map(|record| {
235                (
236                    record.variant_glyph().to_u32(),
237                    i32::from(record.advance_measurement().to_u16()),
238                )
239            })
240            .collect();
241        let assembly = construction
242            .glyph_assembly()
243            .and_then(Result::ok)
244            .map_or_default(|assembly| {
245                assembly
246                    .part_records()
247                    .iter()
248                    .map(|part| AssemblyPart {
249                        glyph: part.glyph_id().to_u32(),
250                        start_connector_length: i32::from(part.start_connector_length().to_u16()),
251                        end_connector_length: i32::from(part.end_connector_length().to_u16()),
252                        full_advance: i32::from(part.full_advance().to_u16()),
253                        extender: part.part_flags().bits() & 1 != 0,
254                    })
255                    .collect()
256            });
257        Some(HorizontalConstruction { variants, assembly })
258    }
259
260    /// Returns the constants of a font's `MATH` table that place the root sign, the bar and the
261    /// degree of a radical, and the room above them.
262    ///
263    /// Returns `None` for an unknown face and a font without the table or its constants.
264    /// The device tables of the values are ignored.
265    #[must_use]
266    pub fn math_radical(&self, id: FontId) -> Option<MathRadical> {
267        let math = self.face(id)?.font()?.tables().math().ok()?;
268        let constants = math.math_constants().ok()?;
269        Some(MathRadical {
270            vertical_gap: constants.constant(MathConstant::RadicalVerticalGap),
271            rule_thickness: constants.constant(MathConstant::RadicalRuleThickness),
272            extra_ascender: constants.constant(MathConstant::RadicalExtraAscender),
273            kern_before_degree: constants.constant(MathConstant::RadicalKernBeforeDegree),
274            kern_after_degree: constants.constant(MathConstant::RadicalKernAfterDegree),
275            degree_bottom_raise_percent: constants
276                .constant(MathConstant::RadicalDegreeBottomRaisePercent),
277            flattened_accent_base_height: constants
278                .constant(MathConstant::FlattenedAccentBaseHeight),
279        })
280    }
281
282    /// Returns the constants of a font's `MATH` table that place an overbar and an underbar,
283    /// and the room beyond them.
284    ///
285    /// Returns `None` for an unknown face and a font without the table or its constants.
286    /// The device tables of the values are ignored.
287    #[must_use]
288    pub fn math_bars(&self, id: FontId) -> Option<MathBars> {
289        let math = self.face(id)?.font()?.tables().math().ok()?;
290        let constants = math.math_constants().ok()?;
291        Some(MathBars {
292            overbar_vertical_gap: constants.constant(MathConstant::OverbarVerticalGap),
293            overbar_rule_thickness: constants.constant(MathConstant::OverbarRuleThickness),
294            overbar_extra_ascender: constants.constant(MathConstant::OverbarExtraAscender),
295            underbar_vertical_gap: constants.constant(MathConstant::UnderbarVerticalGap),
296            underbar_rule_thickness: constants.constant(MathConstant::UnderbarRuleThickness),
297            underbar_extra_descender: constants.constant(MathConstant::UnderbarExtraDescender),
298        })
299    }
300
301    /// Returns the constants of a font's `MATH` table that place the numerator and the
302    /// denominator of a skewed fraction.
303    ///
304    /// Returns `None` for an unknown face and a font without the table or its constants.
305    /// The device tables of the values are ignored.
306    #[must_use]
307    pub fn math_skewed_fraction(&self, id: FontId) -> Option<MathSkewedFraction> {
308        let math = self.face(id)?.font()?.tables().math().ok()?;
309        let constants = math.math_constants().ok()?;
310        Some(MathSkewedFraction {
311            horizontal_gap: constants.constant(MathConstant::SkewedFractionHorizontalGap),
312            vertical_gap: constants.constant(MathConstant::SkewedFractionVerticalGap),
313        })
314    }
315
316    /// Returns the ink gap minimums of a font's `MATH` table for lower and upper limits.
317    ///
318    /// Returns `None` for an unknown face and a font without the table or its constants.
319    /// The device tables of the values are ignored.
320    #[must_use]
321    pub fn math_limit_gaps(&self, id: FontId) -> Option<MathLimitGaps> {
322        let math = self.face(id)?.font()?.tables().math().ok()?;
323        let constants = math.math_constants().ok()?;
324        Some(MathLimitGaps {
325            lower_limit_gap_min: constants.constant(MathConstant::LowerLimitGapMin),
326            upper_limit_gap_min: constants.constant(MathConstant::UpperLimitGapMin),
327        })
328    }
329
330    /// Returns the constants of a font's `MATH` table that place a grouping character and its
331    /// base.
332    ///
333    /// Returns `None` for an unknown face and a font without the table or its constants.
334    /// The device tables of the values are ignored.
335    #[must_use]
336    pub fn math_stretch_stack(&self, id: FontId) -> Option<MathStretchStack> {
337        let math = self.face(id)?.font()?.tables().math().ok()?;
338        let constants = math.math_constants().ok()?;
339        let variants = math.math_variants().ok()?;
340        Some(MathStretchStack {
341            top_shift_up: constants.constant(MathConstant::StretchStackTopShiftUp),
342            bottom_shift_down: constants.constant(MathConstant::StretchStackBottomShiftDown),
343            gap_above_min: constants.constant(MathConstant::StretchStackGapAboveMin),
344            gap_below_min: constants.constant(MathConstant::StretchStackGapBelowMin),
345            min_connector_overlap: i32::from(variants.min_connector_overlap().to_u16()),
346        })
347    }
348
349    /// Returns the constants of a font's `MATH` table that place the limits of an n-ary
350    /// operator in a display, and the room above them.
351    ///
352    /// Returns `None` for an unknown face and a font without the table or its constants.
353    /// The device tables of the values are ignored.
354    #[must_use]
355    pub fn math_limits(&self, id: FontId) -> Option<MathLimits> {
356        let math = self.face(id)?.font()?.tables().math().ok()?;
357        let constants = math.math_constants().ok()?;
358        Some(MathLimits {
359            math_leading: constants.constant(MathConstant::MathLeading),
360            display_operator_min_height: constants.constant(MathConstant::DisplayOperatorMinHeight),
361            upper_limit_baseline_rise_min: constants
362                .constant(MathConstant::UpperLimitBaselineRiseMin),
363            lower_limit_baseline_drop_min: constants
364                .constant(MathConstant::LowerLimitBaselineDropMin),
365            superscript_baseline_drop_max: constants
366                .constant(MathConstant::SuperscriptBaselineDropMax),
367            subscript_baseline_drop_min: constants.constant(MathConstant::SubscriptBaselineDropMin),
368            delimited_sub_formula_min_height: constants
369                .constant(MathConstant::DelimitedSubFormulaMinHeight),
370        })
371    }
372
373    /// Returns the italic correction of a glyph in the font's `MATH` table
374    /// (`MathItalicsCorrectionInfo`), in font units: how far a superscript after the glyph
375    /// starts right of a subscript.
376    ///
377    /// Returns `None` for an unknown face, a font without the table, and a glyph that the
378    /// table does not list. The device tables of the values are ignored.
379    #[must_use]
380    pub fn italic_correction(&self, id: FontId, glyph: u32) -> Option<i32> {
381        let math = self.face(id)?.font()?.tables().math().ok()?;
382        let info = math
383            .math_glyph_info()
384            .ok()?
385            .math_italics_correction_info()?
386            .ok()?;
387        let index = info.coverage().ok()?.get(GlyphId::new(glyph))?;
388        info.italics_correction()
389            .get(usize::try_from(index).ok()?)
390            .map(|record| i32::from(record.value().to_i16()))
391    }
392
393    /// Returns the space that the font's `MATH` table leaves after a subscript or a
394    /// superscript (`SpaceAfterScript`), in font units.
395    ///
396    /// Returns `None` for an unknown face and a font without the table or its constants.
397    /// The device table of the value is ignored.
398    #[must_use]
399    pub fn space_after_script(&self, id: FontId) -> Option<i32> {
400        let math = self.face(id)?.font()?.tables().math().ok()?;
401        let constants = math.math_constants().ok()?;
402        Some(constants.constant(MathConstant::SpaceAfterScript))
403    }
404
405    /// Returns the kern of a corner of a glyph at a height in the font's `MATH` table
406    /// (`MathKernInfo`), in font units: how far a script at that height beside the corner moves
407    /// toward the glyph, negative for a move away from it. `height` is in font units from the
408    /// glyph's baseline, up positive; a height at a band's lower correction height takes that
409    /// band's kern.
410    ///
411    /// Returns `None` for an unknown face, a font without the table, and a glyph whose corner
412    /// the table does not list. The device tables of the values are ignored.
413    #[must_use]
414    pub fn math_kern(
415        &self,
416        id: FontId,
417        glyph: u32,
418        corner: MathCorner,
419        height: i32,
420    ) -> Option<i32> {
421        let math = self.face(id)?.font()?.tables().math().ok()?;
422        let info = math.math_glyph_info().ok()?.math_kern_info()?.ok()?;
423        let corner = match corner {
424            MathCorner::TopRight => MathKernCorner::TopRight,
425            MathCorner::TopLeft => MathKernCorner::TopLeft,
426            MathCorner::BottomRight => MathKernCorner::BottomRight,
427            MathCorner::BottomLeft => MathKernCorner::BottomLeft,
428        };
429        info.kern(GlyphId::new(glyph), corner)?.kerning(height)
430    }
431
432    /// Returns the glyph that a display draws for an n-ary operator: the first of the
433    /// glyph's vertical variants in the font's `MATH` table whose height is at least the
434    /// table's `DisplayOperatorMinHeight`.
435    ///
436    /// Returns `None` for an unknown face, a font without the table, and a glyph that has no
437    /// such variant.
438    #[must_use]
439    pub fn display_variant(&self, id: FontId, glyph: u32) -> Option<u32> {
440        let math = self.face(id)?.font()?.tables().math().ok()?;
441        let least = math
442            .math_constants()
443            .ok()?
444            .constant(MathConstant::DisplayOperatorMinHeight);
445        self.vertical_variant(id, glyph, least)
446            .filter(|&(_, reached)| reached)
447            .map(|(variant, _)| variant)
448    }
449
450    /// Returns the first of the glyph's vertical variants in the font's `MATH` table whose
451    /// height (its advance measurement) is at least `least` font units, with `true`; or else
452    /// the tallest variant, with `false`. The variants start with the glyph itself in the
453    /// fonts that list it, such as Cambria Math.
454    ///
455    /// Returns `None` for an unknown face, a font without the table, and a glyph that has no
456    /// vertical variants.
457    #[must_use]
458    pub fn vertical_variant(&self, id: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
459        let math = self.face(id)?.font()?.tables().math().ok()?;
460        let construction = math
461            .math_variants()
462            .ok()?
463            .glyph_construction(GlyphId::new(glyph), StretchAxis::Vertical)?;
464        let records = construction.math_glyph_variant_records();
465        records
466            .iter()
467            .find(|record| i32::from(record.advance_measurement().to_u16()) >= least)
468            .map(|record| (record.variant_glyph().to_u32(), true))
469            .or_else(|| {
470                records
471                    .last()
472                    .map(|record| (record.variant_glyph().to_u32(), false))
473            })
474    }
475}