latex-rust 2.1.0

Pure-Rust LaTeX math renderer. Parse to AST, TeX-faithful layout on exact rationals, emit SVG, PNG, or egui shapes. No JavaScript, no webview, no runtime.
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
//! OpenType math font metrics. Integer font units → [`Dim`](crate::Dim).

use ttf_parser::Face;

use crate::dim::Dim;
use crate::error::{Error, FontError};

/// Embedded STIX Two Math Regular 2.13 (SIL OFL 1.1).
///
/// A `static` rather than a `const`, so that the font's bytes are placed in the binary once and every use refers
/// to that one copy. A `const` is inlined at each use site, and a crate that reads these bytes as well as calling
/// [`MathFont::stix_two_math`] carries the 839 KB font twice.
pub static STIX_TWO_MATH_OTF: &[u8] =
    include_bytes!("../../fonts/stix-two-math/STIXTwoMath-Regular.otf");

/// SHA-256 (hex) of [`STIX_TWO_MATH_OTF`]. Locked by gold.
pub const STIX_TWO_MATH_SHA256: &str =
    "f2076b9f1676438439dd41e23676f5ab99056e83d6b8f8c27841591ef2ccfa72";

/// Face name as shipped.
pub const STIX_TWO_MATH_NAME: &str = "STIX Two Math";

/// Horizontal glyph metrics in font units and em.
///
/// # Examples
///
/// ```
/// use latex_rust::MathFont;
///
/// let font = MathFont::stix_two_math().unwrap();
/// let g = font.glyph('x').unwrap();
/// assert_eq!(g.ch, 'x');
/// assert!(!g.advance.is_zero());
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GlyphMetrics {
    /// Character requested.
    pub ch: char,
    /// OpenType glyph id.
    pub glyph_id: u16,
    /// Horizontal advance, font units.
    pub advance_fu: u16,
    /// Advance in em.
    pub advance: Dim,
    /// Height above baseline in em (`max(y_max, 0)`).
    pub height: Dim,
    /// Depth below baseline in em (`max(-y_min, 0)`).
    pub depth: Dim,
}

#[derive(Clone, Copy)]
struct ScriptAlternateEntry {
    glyph_id: u16,
    alternates: [Option<u16>; 2],
}

/// Loaded math face.
///
/// # Examples
///
/// ```
/// use latex_rust::MathFont;
///
/// let font = MathFont::stix_two_math().unwrap();
/// assert_eq!(font.units_per_em(), 1000);
/// ```
pub struct MathFont {
    raw: &'static [u8],
    face: Face<'static>,
    units_per_em: u16,
    ascender_fu: i16,
    descender_fu: i16,
    script_alternates: Vec<ScriptAlternateEntry>,
}

impl MathFont {
    /// Load the embedded STIX Two Math Regular face.
    ///
    /// # Errors
    ///
    /// [`crate::FontError::InvalidFace`] if the embedded bytes are not a usable OpenType face.
    ///
    /// # Examples
    ///
    /// ```
    /// use latex_rust::MathFont;
    /// assert!(MathFont::stix_two_math().is_ok());
    /// ```
    pub fn stix_two_math() -> Result<Self, Error> {
        Self::from_bytes(STIX_TWO_MATH_OTF)
    }

    /// Parse OpenType bytes. Lifetime is `'static` for the embedded font only;
    /// this constructor requires a static buffer so the face can be rebuilt.
    pub fn from_bytes(raw: &'static [u8]) -> Result<Self, Error> {
        let face = Face::parse(raw, 0).map_err(|_| FontError::InvalidFace)?;
        let units_per_em = face.units_per_em();
        if units_per_em == 0 {
            return Err(FontError::InvalidFace.into());
        }
        let ascender_fu = face.ascender();
        let descender_fu = face.descender();

        let mut script_alternates = Vec::new();
        for glyph_id in 0..face.number_of_glyphs() {
            let alternates = [
                ssty_alternate_glyph_id(&face, glyph_id, 1),
                ssty_alternate_glyph_id(&face, glyph_id, 2),
            ];

            if alternates.iter().any(Option::is_some) {
                script_alternates.push(ScriptAlternateEntry {
                    glyph_id,
                    alternates,
                });
            }
        }

        Ok(Self {
            raw,
            face,
            units_per_em,
            ascender_fu,
            descender_fu,
            script_alternates,
        })
    }

    /// The parsed OpenType face.
    ///
    /// An external render backend needs glyph outlines and bounding boxes,
    /// which this crate does not otherwise expose. Reaching the face here
    /// rather than re-parsing [`Self::bytes`] guarantees that the glyph ids in
    /// [`BoxContent::Glyph`](crate::BoxContent::Glyph) are resolved against the
    /// same face, parsed by the same version of `ttf-parser`, that produced
    /// them. The crate re-exports [`ttf_parser`] so that a
    /// consumer can name this type without pinning the version itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use latex_rust::{ttf_parser, MathFont};
    ///
    /// let font = MathFont::stix_two_math().expect("STIX Two Math");
    /// let metrics = font.glyph('x').expect("x");
    /// let id = ttf_parser::GlyphId(metrics.glyph_id);
    /// assert!(font.face().glyph_bounding_box(id).is_some());
    /// ```
    #[must_use]
    pub fn face(&self) -> &Face<'static> {
        &self.face
    }

    pub(crate) fn script_alternate_glyph_id(
        &self,
        glyph_id: u16,
        script_level: u8,
    ) -> Option<u16> {
        let alternate_index = match script_level {
            1 => 0,
            2 => 1,
            _ => return None,
        };

        let index = self
            .script_alternates
            .binary_search_by_key(&glyph_id, |entry| entry.glyph_id)
            .ok()?;

        self.script_alternates[index].alternates[alternate_index]
    }

    /// OpenType bytes this face was parsed from.
    #[must_use]
    pub fn bytes(&self) -> &'static [u8] {
        self.raw
    }

    /// `unitsPerEm` from the `head` table.
    #[must_use]
    pub fn units_per_em(&self) -> u16 {
        self.units_per_em
    }

    /// `hhea` ascender in font units.
    #[must_use]
    pub fn ascender_fu(&self) -> i16 {
        self.ascender_fu
    }

    /// `hhea` descender in font units (typically negative).
    #[must_use]
    pub fn descender_fu(&self) -> i16 {
        self.descender_fu
    }

    /// Ascender in em.
    #[must_use]
    pub fn ascender(&self) -> Dim {
        Dim::from_font_units(i64::from(self.ascender_fu), self.units_per_em)
    }

    /// Depth below baseline from `hhea` descender, in em (non-negative).
    #[must_use]
    pub fn descender(&self) -> Dim {
        let d = i64::from(self.descender_fu);
        Dim::from_font_units(-d, self.units_per_em)
    }

    /// Metrics for `ch`, or [`FontError::MissingGlyph`].
    pub fn glyph(&self, ch: char) -> Result<GlyphMetrics, Error> {
        let face = self.face();
        let gid = face.glyph_index(ch).ok_or(FontError::MissingGlyph { ch })?;
        let advance_fu = face
            .glyph_hor_advance(gid)
            .ok_or(FontError::MissingGlyph { ch })?;
        let mut height_fu = 0i64;
        let mut depth_fu = 0i64;
        if let Some(bbox) = face.glyph_bounding_box(gid) {
            height_fu = i64::from(bbox.y_max).max(0);
            depth_fu = i64::from(-bbox.y_min).max(0);
        }
        let upem = self.units_per_em;
        Ok(GlyphMetrics {
            ch,
            glyph_id: gid.0,
            advance_fu,
            advance: Dim::from_font_units(i64::from(advance_fu), upem),
            height: Dim::from_font_units(height_fu, upem),
            depth: Dim::from_font_units(depth_fu, upem),
        })
    }

    /// Metrics for OpenType glyph id `gid`, tagged with `ch` for the box payload.
    pub fn glyph_id(&self, ch: char, gid: u16) -> Result<GlyphMetrics, Error> {
        let face = self.face();
        let gid = ttf_parser::GlyphId(gid);
        let advance_fu = face
            .glyph_hor_advance(gid)
            .ok_or(FontError::MissingGlyph { ch })?;
        let mut height_fu = 0i64;
        let mut depth_fu = 0i64;
        if let Some(bbox) = face.glyph_bounding_box(gid) {
            height_fu = i64::from(bbox.y_max).max(0);
            depth_fu = i64::from(-bbox.y_min).max(0);
        }
        let upem = self.units_per_em;
        Ok(GlyphMetrics {
            ch,
            glyph_id: gid.0,
            advance_fu,
            advance: Dim::from_font_units(i64::from(advance_fu), upem),
            height: Dim::from_font_units(height_fu, upem),
            depth: Dim::from_font_units(depth_fu, upem),
        })
    }

    /// MATH italic correction for `glyph_id`, or zero.
    pub fn italic_correction(&self, glyph_id: u16) -> Dim {
        let face = self.face();
        let Some(math) = face.tables().math else {
            return Dim::zero();
        };
        let Some(info) = math.glyph_info else {
            return Dim::zero();
        };
        let Some(table) = info.italic_corrections else {
            return Dim::zero();
        };
        match table.get(ttf_parser::GlyphId(glyph_id)) {
            Some(v) => Dim::from_font_units(i64::from(v.value), self.units_per_em),
            None => Dim::zero(),
        }
    }

    /// MATH top-accent attachment (em from glyph left), if present.
    pub fn top_accent_attachment(&self, glyph_id: u16) -> Option<Dim> {
        let face = self.face();
        let math = face.tables().math?;
        let info = math.glyph_info?;
        let table = info.top_accent_attachments?;
        let v = table.get(ttf_parser::GlyphId(glyph_id))?;
        Some(Dim::from_font_units(i64::from(v.value), self.units_per_em))
    }

    /// Horizontal glyph-assembly parts: `(gid, start_connector, end_connector, advance, extender)`.
    /// Lengths are font units.
    pub fn horizontal_assembly_parts(&self, glyph_id: u16) -> Vec<(u16, u16, u16, u16, bool)> {
        let mut out = Vec::new();
        let face = self.face();
        let Some(math) = face.tables().math else {
            return out;
        };
        let Some(variants) = math.variants else {
            return out;
        };
        let Some(cons) = variants
            .horizontal_constructions
            .get(ttf_parser::GlyphId(glyph_id))
        else {
            return out;
        };
        let Some(assembly) = cons.assembly else {
            return out;
        };
        for i in 0..assembly.parts.len() {
            if let Some(p) = assembly.parts.get(i) {
                out.push((
                    p.glyph_id.0,
                    p.start_connector_length,
                    p.end_connector_length,
                    p.full_advance,
                    p.part_flags.extender(),
                ));
            }
        }
        out
    }

    /// Horizontal MATH variants of `glyph_id`, including the base glyph first.
    pub fn horizontal_variants(&self, glyph_id: u16) -> Vec<u16> {
        let mut out = vec![glyph_id];
        let face = self.face();
        let Some(math) = face.tables().math else {
            return out;
        };
        let Some(variants) = math.variants else {
            return out;
        };
        let Some(cons) = variants
            .horizontal_constructions
            .get(ttf_parser::GlyphId(glyph_id))
        else {
            return out;
        };
        for i in 0..cons.variants.len() {
            if let Some(v) = cons.variants.get(i) {
                out.push(v.variant_glyph.0);
            }
        }
        out
    }

    /// Vertical MATH variants of `glyph_id`, including the base glyph first.
    pub fn vertical_variants(&self, glyph_id: u16) -> Vec<u16> {
        let mut out = vec![glyph_id];
        let face = self.face();
        let Some(math) = face.tables().math else {
            return out;
        };
        let Some(variants) = math.variants else {
            return out;
        };
        let Some(cons) = variants
            .vertical_constructions
            .get(ttf_parser::GlyphId(glyph_id))
        else {
            return out;
        };
        for i in 0..cons.variants.len() {
            if let Some(v) = cons.variants.get(i) {
                out.push(v.variant_glyph.0);
            }
        }
        out
    }

    /// SHA-256 hex of the raw face bytes.
    #[must_use]
    pub fn sha256_hex(bytes: &[u8]) -> String {
        let d = crate::hash::sha256(bytes);
        let mut s = String::with_capacity(64);
        for b in d {
            s.push_str(&hex_byte(b));
        }
        s
    }
}

fn ssty_alternate_glyph_id(
    face: &Face<'_>,
    glyph_id: u16,
    script_level: u8,
) -> Option<u16> {
    let alternate_index = match script_level {
        1 => 0,
        2 => 1,
        _ => return None,
    };

    let gsub = face.tables().gsub?;
    let feature = gsub.features.find(ttf_parser::Tag::from_bytes(b"ssty"))?;

    for lookup_index in feature.lookup_indices {
        let Some(lookup) = gsub.lookups.get(lookup_index) else {
            continue;
        };

        for subtable in lookup
            .subtables
            .into_iter::<ttf_parser::gsub::SubstitutionSubtable<'_>>()
        {
            let ttf_parser::gsub::SubstitutionSubtable::Alternate(alternate) =
                subtable
            else {
                continue;
            };

            let Some(coverage_index) =
                alternate.coverage.get(ttf_parser::GlyphId(glyph_id))
            else {
                continue;
            };

            let Some(set) =
                alternate.alternate_sets.get(coverage_index)
            else {
                continue;
            };

            if let Some(selected) =
                set.alternates.get(alternate_index)
            {
                return Some(selected.0);
            }
        }
    }

    None
}

fn hex_byte(b: u8) -> String {
    const H: &[u8; 16] = b"0123456789abcdef";
    let hi = H[(b >> 4) as usize];
    let lo = H[(b & 0xf) as usize];
    let mut out = String::with_capacity(2);
    out.push(hi as char);
    out.push(lo as char);
    out
}