Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.2.0528.5 KB2026-10-160.1.1542.8 KB2026-10-150.1.0541.1 KB2026-10-15
Version
0.1.1
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
542.8 KB
Downloads
9
Checksum
2e36f65a5798a2a0281457d1ed7f5a4e1a74967fea2880b4961ede38808a3682
Dependencies
None

font.rs

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
//! The metrics and glyphs of one font
//!
//! Reads an OpenType file and keeps only what typesetting needs.
//! All metrics are converted to em, so font units are not visible from outside.
//!
//! Chemical formulas need the advances and the outlines, plus the cap height and the x-height.
//! The cap height sets the height at which bonds are drawn, and the x-height sets the positions
//! of subscripts and superscripts.
//! Nothing here is typeset the way math is, so the MATH table is not read.

use crate::cff::{self, Cff};
use crate::error::Error;
use crate::glyf::{self, Glyf};
use crate::opentype::{self, require};
use crate::outline::{self, Outline};
use std::collections::HashMap;


/// Which form the glyphs are stored in
#[derive(Debug, Clone)]
enum Kind {
    Cff(Cff),
    Glyf(Glyf),
}


/// A loaded font
#[derive(Debug, Clone)]
pub struct Font {
    data: Vec<u8>,
    family: String,
    units_per_em: f64,
    kind: Kind,
    map: HashMap<char, u16>,
    /// The advance of each glyph (em)
    advance: Vec<f64>,
    /// The vertical space each glyph actually covers (em), as (height, depth)
    extent: Vec<(f64, f64)>,
    /// The left and right side bearings of each glyph (em).
    /// The space between the ink and the advance
    bearing: Vec<(f64, f64)>,
    cap_height: f64,
    x_height: f64,
    digit_height: f64,
}


/// The cap height used when it cannot be measured (em)
const DEFAULT_CAP_HEIGHT: f64 = 0.7;

/// The x-height used when it cannot be measured (em)
const DEFAULT_X_HEIGHT: f64 = 0.45;

/// The digit height used when it cannot be measured (em)
const DEFAULT_DIGIT_HEIGHT: f64 = 0.66;


/// Loads a font file
pub fn load(data: Vec<u8>) -> Result<Font, Error> {
    let (head_at, _) = require(&data, "head")?;
    let shape = opentype::head(&data, head_at)?;
    let units_per_em = shape.units_per_em;
    let (maxp_at, _) = require(&data, "maxp")?;
    let count = opentype::glyph_count(&data, maxp_at)?;
    let (hmtx_at, _) = require(&data, "hmtx")?;
    let (hhea_at, _) = require(&data, "hhea")?;
    let (cmap_at, _) = require(&data, "cmap")?;
    let (name_at, _) = require(&data, "name")?;

    let kind = match opentype::find(&data, "CFF ")? {
        Some((cff_at, _)) => Kind::Cff(cff::parse(&data, cff_at, units_per_em)?),
        None => {
            let (glyf_at, _) = require(&data, "glyf")?;
            let (loca_at, _) = require(&data, "loca")?;

            Kind::Glyf(glyf::new(glyf_at, loca_at, shape.long_loca, count))
        }
    };

    let advance = opentype::advances(&data, hmtx_at, hhea_at, count)?
        .into_iter()
        .map(|width| width / units_per_em)
        .collect();
    let mut font = Font {
        family: opentype::family_name(&data, name_at)?,
        map: opentype::character_map(&data, cmap_at)?,
        units_per_em,
        kind,
        advance,
        extent: Vec::new(),
        bearing: Vec::new(),
        cap_height: DEFAULT_CAP_HEIGHT,
        x_height: DEFAULT_X_HEIGHT,
        digit_height: DEFAULT_DIGIT_HEIGHT,
        data,
    };

    let (extent, bearing) = measure_all(&font, count)?;
    font.extent = extent;
    font.bearing = bearing;
    font.cap_height = height_of(&font, 'H', DEFAULT_CAP_HEIGHT);
    font.x_height = height_of(&font, 'x', DEFAULT_X_HEIGHT);
    font.digit_height = height_of(&font, '0', DEFAULT_DIGIT_HEIGHT);

    Ok(font)
}


/// The name of the typeface
pub fn family(font: &Font) -> &str {
    &font.family
}


/// The fallback for characters that the typeface does not have
pub const FALLBACK: &str = "serif";


/// The number of font coordinate units per em
pub fn units_per_em(font: &Font) -> f64 {
    font.units_per_em
}


/// The cap height (em). The height at which bonds are drawn is based on it
pub fn cap_height(font: &Font) -> f64 {
    font.cap_height
}


/// The x-height (em)
pub fn x_height(font: &Font) -> f64 {
    font.x_height
}


/// The height of digits (em)
///
/// Digits sit on the baseline, but + and − are drawn centered on the math axis.
/// When they are put side by side in a charge, this height is used to align their heights
pub fn digit_height(font: &Font) -> f64 {
    font.digit_height
}


/// The glyph ID for a character
pub fn glyph_of(font: &Font, character: char) -> Option<u16> {
    font.map.get(&character).copied()
}


/// The advance of a glyph (em)
pub fn advance(font: &Font, glyph: u16) -> f64 {
    font.advance.get(glyph as usize).copied().unwrap_or(0.0)
}


/// The height and depth that a glyph covers (em). Depth is positive downward
pub fn extent(font: &Font, glyph: u16) -> (f64, f64) {
    font.extent.get(glyph as usize).copied().unwrap_or((0.0, 0.0))
}


/// The left and right side bearings of a glyph (em). The space up to the left edge of the ink,
/// and the space from the right edge of the ink to the end of the advance
pub fn bearing(font: &Font, glyph: u16) -> (f64, f64) {
    font.bearing.get(glyph as usize).copied().unwrap_or((0.0, 0.0))
}


/// The approximate advance, height, and depth (em) for placing a character the font does not have
pub fn fallback_metric(character: char) -> (f64, f64, f64) {
    if character as u32 >= 0x2e80 {
        (1.0, 0.88, 0.12)
    } else {
        (0.5, 0.7, 0.0)
    }
}


/// The outline of a glyph. Coordinates stay in font units, and y points up
pub fn outline_of(font: &Font, glyph: u16) -> Outline {
    let found = match &font.kind {
        Kind::Cff(cff) => cff::outline(&font.data, cff, glyph),
        Kind::Glyf(glyf) => glyf::outline(&font.data, glyf, glyph),
    };

    found.unwrap_or_default()
}


/// The font used in tests and samples. It is compiled in only for tests
#[cfg(test)]
pub fn sample() -> Font {
    let path = "font/latinmodern-math.otf";
    let data = std::fs::read(path).expect("試験用のフォントを読めません");

    load(data).expect("フォントを読み込めません")
}


/// The ink height of one character (em). The default value if the font does not have it
fn height_of(font: &Font, character: char, default: f64) -> f64 {
    match font.map.get(&character) {
        Some(glyph) => match font.extent.get(*glyph as usize) {
            Some((height, _)) if *height > 0.0 => *height,
            _ => default,
        },
        None => default,
    }
}


/// Measures the vertical and horizontal extent of every glyph. Runs only once, at load time
type Measured = (Vec<(f64, f64)>, Vec<(f64, f64)>);


fn measure_all(font: &Font, count: usize) -> Result<Measured, Error> {
    let mut extent = Vec::with_capacity(count);
    let mut bearing = Vec::with_capacity(count);

    for glyph in 0..count {
        let drawn = match &font.kind {
            Kind::Cff(cff) => cff::outline(&font.data, cff, glyph as u16)?,
            Kind::Glyf(glyf) => glyf::outline(&font.data, glyf, glyph as u16)?,
        };
        let (left, bottom, right, top) = outline::bounds(&drawn);
        let units = font.units_per_em;
        extent.push((top / units, -bottom / units));

        let advance = font.advance.get(glyph).copied().unwrap_or(0.0);
        bearing.push((left / units, (advance - right / units).max(0.0)));
    }

    Ok((extent, bearing))
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_name_and_the_unit() {
        let font = sample();
        assert_eq!(family(&font), "Latin Modern Math");
        assert_eq!(units_per_em(&font), 1000.0);
    }

    #[test]
    fn measures_letters() {
        let font = sample();
        let carbon = glyph_of(&font, 'C').unwrap();
        let hydrogen = glyph_of(&font, 'H').unwrap();
        assert!(advance(&font, carbon) > 0.3 && advance(&font, carbon) < 1.0);
        assert!(extent(&font, hydrogen).1.abs() < 1e-9, "H に深さが出ています");
        // C is a round letter, so it sticks out slightly at both the top and the bottom
        assert!(extent(&font, carbon).1 > 0.0 && extent(&font, carbon).1 < 0.05);
        assert!(extent(&font, carbon).0 > extent(&font, hydrogen).0);
        assert!(extent(&font, hydrogen).0 > 0.5);
    }

    #[test]
    fn the_heights_come_from_the_font() {
        let font = sample();
        assert!(cap_height(&font) > 0.5 && cap_height(&font) < 0.9);
        assert!(x_height(&font) > 0.3 && x_height(&font) < 0.6);
        assert!(x_height(&font) < cap_height(&font));
    }

    #[test]
    fn outlines_come_out_in_font_units() {
        let font = sample();
        let oxygen = glyph_of(&font, 'O').unwrap();
        let drawn = outline_of(&font, oxygen);
        assert!(!drawn.segment.is_empty());
        let (_, _, _, top) = outline::bounds(&drawn);
        assert!((top / units_per_em(&font) - extent(&font, oxygen).0).abs() < 1e-9);
    }

    #[test]
    fn a_font_without_math_still_loads() {
        let path = "/System/Library/Fonts/Supplemental/Times New Roman.ttf";
        let Ok(data) = std::fs::read(path) else {
            return;
        };
        let font = load(data).unwrap();
        assert!(cap_height(&font) > 0.5);
        assert!(glyph_of(&font, 'C').is_some());
    }
}