Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/math/font.rs

16.4 KiB, 7 runs

created by r1870400018:63542, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-layout `math/shared.rs` and `math/fragment`, typst-library `math/` font queries, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! A maths font: a face to shape and outline with, its MATH table and metrics in ems, and the glyph
5//! queries maths layout asks (advances, ink boxes, italics corrections, accent attachments, cut-in
6//! kerning, constructions). Ems throughout; a caller multiplies by the font size in points.
7//!
8//! Faces are found by family name in the compilation's font book -- the faces this crate embeds, New
9//! Computer Modern Math among them (Typst's default for equations), and every face the host supplies. A
10//! family the book cannot supply falls through to the next in the list and, as in Typst, to the maths
11//! fallback list.
12
13use crate::fonts::{
14 BookFace,
15 FaceVariant,
16 FontBook,
17};
18use crate::mathtable::{
19 Construction,
20 FontTables,
21 Kern,
22};
23
24use oxedyne_fe2o3_core::prelude::*;
25use oxedyne_fe2o3_font::{
26 font::Font,
27 shape::{
28 Dir,
29 Feature,
30 },
31};
32use oxedyne_fe2o3_graphics::transform::Transform;
33
34use std::collections::HashMap;
35use std::sync::{
36 Arc,
37 RwLock,
38};
39
40/// A corner of a glyph, for cut-in kerning.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum Corner {
43 TopLeft,
44 TopRight,
45 BottomRight,
46 BottomLeft,
47}
48
49impl Corner {
50 /// The diagonally opposite corner: a script's corner facing the base's.
51 pub fn inv(self) -> Self {
52 match self {
53 Corner::TopLeft => Corner::BottomRight,
54 Corner::TopRight => Corner::BottomLeft,
55 Corner::BottomRight => Corner::TopLeft,
56 Corner::BottomLeft => Corner::TopRight,
57 }
58 }
59}
60
61/// The MATH constants Typst reads, in ems (the three plain numbers excepted).
62#[derive(Clone, Copy, Debug, Default)]
63pub struct Constants {
64 pub space_width: f64,
65 pub script_percent_scale_down: i16,
66 pub script_script_percent_scale_down: i16,
67 pub display_operator_min_height: f64,
68 pub axis_height: f64,
69 pub accent_base_height: f64,
70 pub flattened_accent_base_height: f64,
71 pub subscript_shift_down: f64,
72 pub subscript_top_max: f64,
73 pub subscript_baseline_drop_min: f64,
74 pub superscript_shift_up: f64,
75 pub superscript_shift_up_cramped: f64,
76 pub superscript_bottom_min: f64,
77 pub superscript_baseline_drop_max: f64,
78 pub sub_superscript_gap_min: f64,
79 pub superscript_bottom_max_with_subscript: f64,
80 pub space_after_script: f64,
81 pub upper_limit_gap_min: f64,
82 pub upper_limit_baseline_rise_min: f64,
83 pub lower_limit_gap_min: f64,
84 pub lower_limit_baseline_drop_min: f64,
85 pub stack_top_shift_up: f64,
86 pub stack_top_display_style_shift_up: f64,
87 pub stack_bottom_shift_down: f64,
88 pub stack_bottom_display_style_shift_down: f64,
89 pub stack_gap_min: f64,
90 pub stack_display_style_gap_min: f64,
91 pub fraction_numerator_shift_up: f64,
92 pub fraction_numerator_display_style_shift_up: f64,
93 pub fraction_denominator_shift_down: f64,
94 pub fraction_denominator_display_style_shift_down: f64,
95 pub fraction_numerator_gap_min: f64,
96 pub fraction_num_display_style_gap_min: f64,
97 pub fraction_rule_thickness: f64,
98 pub fraction_denominator_gap_min: f64,
99 pub fraction_denom_display_style_gap_min: f64,
100 pub skewed_fraction_vertical_gap: f64,
101 pub skewed_fraction_horizontal_gap: f64,
102 pub overbar_vertical_gap: f64,
103 pub overbar_rule_thickness: f64,
104 pub overbar_extra_ascender: f64,
105 pub underbar_vertical_gap: f64,
106 pub underbar_rule_thickness: f64,
107 pub underbar_extra_descender: f64,
108 pub radical_vertical_gap: f64,
109 pub radical_display_style_vertical_gap: f64,
110 pub radical_rule_thickness: f64,
111 pub radical_extra_ascender: f64,
112 pub radical_kern_before_degree: f64,
113 pub radical_kern_after_degree: f64,
114 pub radical_degree_bottom_raise_percent: f64,
115}
116
117/// One shaped glyph in ems: Typst's `Glyph` without the source range.
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub struct ShapedGlyph {
120 pub id: u16,
121 pub x_advance: f64,
122 pub x_offset: f64,
123 pub y_advance: f64,
124 pub y_offset: f64,
125}
126
127/// A glyph's ink box in ems, y up.
128#[derive(Clone, Copy, Debug, PartialEq)]
129pub struct GlyphBox {
130 pub x0: f64,
131 pub y0: f64,
132 pub x1: f64,
133 pub y1: f64,
134}
135
136pub struct MathFont {
137 pub font: Arc<Font>,
138 pub tables: FontTables,
139 pub family: String,
140 pub weight: u16,
141 pub consts: Constants,
142 pub has_math: bool,
143 boxes: RwLock<HashMap<u16, Option<GlyphBox>>>,
144}
145
146impl std::fmt::Debug for MathFont {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 f.debug_struct("MathFont").field("family", &self.family).field("weight", &self.weight).finish()
149 }
150}
151
152impl MathFont {
153 /// The maths view of a book face, sharing its font so text and equations in one family are one font to
154 /// a PDF.
155 pub fn from_face(face: &BookFace) -> Outcome<Self> {
156 let tables = res!(FontTables::parse(res!(face.face()).bytes()));
157 let mut mf = Self {
158 font: face.font.clone(),
159 tables,
160 family: face.family.clone(),
161 weight: face.variant.weight,
162 consts: Constants::default(),
163 has_math: false,
164 boxes: RwLock::new(HashMap::new()),
165 };
166 mf.consts = res!(mf.constants());
167 mf.has_math = mf.tables.math.is_some();
168 Ok(mf)
169 }
170
171 pub fn upem(&self) -> f64 { self.tables.upem }
172
173 /// Design units to ems.
174 pub fn em(&self, du: f64) -> f64 { du / self.tables.upem }
175
176 fn constants(&self) -> Outcome<Constants> {
177 let space = res!(self.shape(" ", &[]));
178 let space_width = match space.first() {
179 Some(g) if g.id != 0 => g.x_advance,
180 _ => 5.0 / 18.0,
181 };
182 let m = &self.tables.metrics;
183 let math = match &self.tables.math {
184 Some(t) => t,
185 None => {
186 // Typst's fallback constants for a text face, after MathML Core.
187 let u = self.em(m.underline_thickness as f64);
188 let u = if u > 0.0 { u } else { 0.06 };
189 let xh = self.em(m.x_height as f64);
190 return Ok(Constants {
191 space_width,
192 script_percent_scale_down: 70,
193 script_script_percent_scale_down: 50,
194 axis_height: xh / 2.0,
195 accent_base_height: xh,
196 flattened_accent_base_height: self.em(m.cap_height as f64),
197 subscript_shift_down: m.subscript_y_offset.map(|v| -self.em(v as f64)).unwrap_or(-0.2),
198 subscript_top_max: 0.8 * xh,
199 superscript_shift_up: m.superscript_y_offset.map(|v| self.em(v as f64)).unwrap_or(0.5),
200 superscript_bottom_min: 0.25 * xh,
201 sub_superscript_gap_min: 4.0 * u,
202 superscript_bottom_max_with_subscript: 0.8 * xh,
203 space_after_script: 1.0 / 24.0,
204 stack_gap_min: 3.0 * u,
205 stack_display_style_gap_min: 7.0 * u,
206 fraction_numerator_gap_min: u,
207 fraction_num_display_style_gap_min: 3.0 * u,
208 fraction_rule_thickness: u,
209 fraction_denominator_gap_min: u,
210 fraction_denom_display_style_gap_min: 3.0 * u,
211 skewed_fraction_horizontal_gap: 0.5,
212 overbar_vertical_gap: 3.0 * u,
213 overbar_rule_thickness: u,
214 overbar_extra_ascender: u,
215 underbar_vertical_gap: 3.0 * u,
216 underbar_rule_thickness: u,
217 underbar_extra_descender: u,
218 radical_vertical_gap: 1.25 * u,
219 radical_display_style_vertical_gap: u + 0.25 * xh,
220 radical_rule_thickness: u,
221 radical_extra_ascender: u,
222 radical_kern_before_degree: 5.0 / 18.0,
223 radical_kern_after_degree: -10.0 / 18.0,
224 radical_degree_bottom_raise_percent: 0.6,
225 ..Constants::default()
226 });
227 }
228 };
229 let c = math.constants();
230 let e = |v: i16| self.em(v as f64);
231 Ok(Constants {
232 space_width,
233 script_percent_scale_down: c.script_percent_scale_down,
234 script_script_percent_scale_down: c.script_script_percent_scale_down,
235 display_operator_min_height: self.em(c.display_operator_min_height as f64),
236 axis_height: e(c.axis_height),
237 accent_base_height: e(c.accent_base_height),
238 flattened_accent_base_height: e(c.flattened_accent_base_height),
239 subscript_shift_down: e(c.subscript_shift_down),
240 subscript_top_max: e(c.subscript_top_max),
241 subscript_baseline_drop_min: e(c.subscript_baseline_drop_min),
242 superscript_shift_up: e(c.superscript_shift_up),
243 superscript_shift_up_cramped: e(c.superscript_shift_up_cramped),
244 superscript_bottom_min: e(c.superscript_bottom_min),
245 superscript_baseline_drop_max: e(c.superscript_baseline_drop_max),
246 sub_superscript_gap_min: e(c.sub_superscript_gap_min),
247 superscript_bottom_max_with_subscript: e(c.superscript_bottom_max_with_subscript),
248 space_after_script: e(c.space_after_script),
249 upper_limit_gap_min: e(c.upper_limit_gap_min),
250 upper_limit_baseline_rise_min: e(c.upper_limit_baseline_rise_min),
251 lower_limit_gap_min: e(c.lower_limit_gap_min),
252 lower_limit_baseline_drop_min: e(c.lower_limit_baseline_drop_min),
253 stack_top_shift_up: e(c.stack_top_shift_up),
254 stack_top_display_style_shift_up: e(c.stack_top_display_style_shift_up),
255 stack_bottom_shift_down: e(c.stack_bottom_shift_down),
256 stack_bottom_display_style_shift_down: e(c.stack_bottom_display_style_shift_down),
257 stack_gap_min: e(c.stack_gap_min),
258 stack_display_style_gap_min: e(c.stack_display_style_gap_min),
259 fraction_numerator_shift_up: e(c.fraction_num_shift_up),
260 fraction_numerator_display_style_shift_up: e(c.fraction_num_display_shift_up),
261 fraction_denominator_shift_down: e(c.fraction_den_shift_down),
262 fraction_denominator_display_style_shift_down: e(c.fraction_den_display_shift_down),
263 fraction_numerator_gap_min: e(c.fraction_num_gap_min),
264 fraction_num_display_style_gap_min: e(c.fraction_num_display_gap_min),
265 fraction_rule_thickness: e(c.fraction_rule_thickness),
266 fraction_denominator_gap_min: e(c.fraction_denom_gap_min),
267 fraction_denom_display_style_gap_min: e(c.fraction_denom_display_gap_min),
268 skewed_fraction_vertical_gap: e(c.skewed_fraction_vertical_gap),
269 skewed_fraction_horizontal_gap: e(c.skewed_fraction_horizontal_gap),
270 overbar_vertical_gap: e(c.overbar_vertical_gap),
271 overbar_rule_thickness: e(c.overbar_rule_thickness),
272 overbar_extra_ascender: e(c.overbar_extra_ascender),
273 underbar_vertical_gap: e(c.underbar_vertical_gap),
274 underbar_rule_thickness: e(c.underbar_rule_thickness),
275 underbar_extra_descender: e(c.underbar_extra_descender),
276 radical_vertical_gap: e(c.radical_vertical_gap),
277 radical_display_style_vertical_gap: e(c.radical_display_style_vertical_gap),
278 radical_rule_thickness: e(c.radical_rule_thickness),
279 radical_extra_ascender: e(c.radical_extra_ascender),
280 radical_kern_before_degree: e(c.radical_kern_before_degree),
281 radical_kern_after_degree: e(c.radical_kern_after_degree),
282 radical_degree_bottom_raise_percent: c.radical_degree_bottom_raise_percent as f64 / 100.0,
283 })
284 }
285
286 /// Shapes maths text left to right in the `math` script, in ems, with OpenType features.
287 pub fn shape(&self, text: &str, features: &[Feature]) -> Outcome<Vec<ShapedGlyph>> {
288 let size = self.upem() as f32;
289 let run = res!(self.font.shape_in(text, size, Dir::Ltr, features, *b"Zmth"));
290 Ok(self.glyphs_of(&run))
291 }
292
293 /// Shapes running text in the script its characters have, as a quoted string in maths is set.
294 pub fn shape_text(&self, text: &str, features: &[Feature]) -> Outcome<Vec<ShapedGlyph>> {
295 let size = self.upem() as f32;
296 let run = res!(self.font.shape_with(text, size, Dir::Ltr, features));
297 Ok(self.glyphs_of(&run))
298 }
299
300 fn glyphs_of(&self, run: &oxedyne_fe2o3_font::shape::Run) -> Vec<ShapedGlyph> {
301 let mut out = Vec::with_capacity(run.glyphs.len());
302 let mut pen = 0.0f64;
303 for g in &run.glyphs {
304 out.push(ShapedGlyph {
305 id: g.id as u16,
306 x_advance: self.em(g.adv as f64),
307 x_offset: self.em(g.x as f64 - pen),
308 y_advance: 0.0,
309 y_offset: self.em(g.y as f64),
310 });
311 pen += g.adv as f64;
312 }
313 out
314 }
315
316 /// Can the face draw every character of the text?
317 pub fn covers(&self, text: &str) -> bool {
318 match self.font.face(0) {
319 Ok(face) => text.chars().all(|c| face.covers(c) || c == '\u{fe00}' || c == '\u{fe01}'),
320 Err(_) => false,
321 }
322 }
323
324 pub fn advance(&self, gid: u16) -> f64 { self.em(self.tables.advance(gid) as f64) }
325
326 /// The glyph's control box in ems, as `ttf-parser` reports a glyph's bounding box; `None` for a glyph
327 /// with no outline.
328 pub fn bbox(&self, gid: u16) -> Outcome<Option<GlyphBox>> {
329 {
330 let cache = lock_read!(self.boxes);
331 if let Some(b) = cache.get(&gid) {
332 return Ok(*b);
333 }
334 }
335 let path = res!(self.font.outline(0, gid as u32, self.upem() as f32));
336 let b = path.bounds(&Transform::IDENTITY).map(|b| GlyphBox {
337 x0: self.em(b.x0 as f64),
338 y0: self.em(b.y0 as f64),
339 x1: self.em(b.x1 as f64),
340 y1: self.em(b.y1 as f64),
341 });
342 let mut cache = lock_write!(self.boxes);
343 cache.insert(gid, b);
344 Ok(b)
345 }
346
347 /// Ascent and descent of the glyph's ink box in ems, descent positive below the baseline.
348 pub fn ascent_descent(&self, gid: u16) -> Outcome<Option<(f64, f64)>> {
349 Ok(res!(self.bbox(gid)).map(|b| (b.y1, -b.y0)))
350 }
351
352 pub fn italics_correction(&self, gid: u16) -> Option<f64> {
353 self.tables.math.as_ref()?.italics_correction(gid).map(|v| self.em(v as f64))
354 }
355
356 pub fn top_accent_attachment(&self, gid: u16) -> Option<f64> {
357 self.tables.math.as_ref()?.top_accent_attachment(gid).map(|v| self.em(v as f64))
358 }
359
360 pub fn is_extended_shape(&self, gid: u16) -> bool {
361 self.tables.math.as_ref().map(|t| t.is_extended_shape(gid)).unwrap_or(false)
362 }
363
364 /// The cut-in kern at a corner and a height (ems), or `None` when the glyph has no such table.
365 pub fn kern_at_height(&self, gid: u16, corner: Corner, height: f64) -> Option<f64> {
366 let info = self.tables.math.as_ref()?.kern_info(gid)?;
367 let kern: &Kern = match corner {
368 Corner::TopLeft => info.top_left.as_ref(),
369 Corner::TopRight => info.top_right.as_ref(),
370 Corner::BottomRight => info.bottom_right.as_ref(),
371 Corner::BottomLeft => info.bottom_left.as_ref(),
372 }?;
373 Some(self.em(kern.at(height * self.upem()) as f64))
374 }
375
376 pub fn construction(&self, gid: u16, vertical: bool) -> Option<&Construction> {
377 self.tables.math.as_ref()?.construction(gid, vertical)
378 }
379
380 pub fn min_connector_overlap(&self) -> Option<f64> {
381 self.tables.math.as_ref().map(|t| self.em(t.min_connector_overlap() as f64))
382 }
383
384 pub fn has_feature(&self, tag: &[u8; 4]) -> bool { self.tables.has_feature(tag) }
385
386 pub fn cap_height(&self) -> f64 { self.em(self.tables.metrics.cap_height as f64) }
387 pub fn x_height(&self) -> f64 { self.em(self.tables.metrics.x_height as f64) }
388 pub fn ascender(&self) -> f64 { self.em(self.tables.metrics.ascender as f64) }
389 pub fn descender(&self) -> f64 { self.em(self.tables.metrics.descender as f64) }
390}
391
392/// Typst's maths fallback families, tried after the document's own when `text.fallback` is on.
393pub const FALLBACKS: &[&str] = &[
394 "new computer modern math",
395 "libertinus serif",
396 "twitter color emoji",
397 "noto color emoji",
398 "apple color emoji",
399 "segoe ui emoji",
400];
401
402/// The face of `family` nearest `variant` in the book, if the book has the family.
403pub fn select(book: &FontBook, family: &str, variant: FaceVariant) -> Outcome<Option<Arc<MathFont>>> {
404 match book.select(&family.to_lowercase(), variant) {
405 Some(id) => Ok(Some(res!(book.math_font(id)))),
406 None => Ok(None),
407 }
408}
409
410/// The face maths is set in: the first family of the list the book has, then the fallback families when
411/// `fallback` is on, as Typst's `get_font`. A list that no face answers, with the fallback off, is an error.
412pub fn resolve(book: &FontBook, families: &[String], fallback: bool, variant: FaceVariant) -> Outcome<Arc<MathFont>> {
413 for fam in families {
414 if let Some(f) = res!(select(book, fam, variant)) {
415 return Ok(f);
416 }
417 }
418 if fallback {
419 for fam in FALLBACKS {
420 if let Some(f) = res!(select(book, fam, variant)) {
421 return Ok(f);
422 }
423 }
424 }
425 Err(err!("no font could be found"; Missing))
426}
427
428/// The faces to try, in order, for a character the first face lacks.
429pub fn chain(book: &FontBook, families: &[String], fallback: bool, variant: FaceVariant) -> Outcome<Vec<Arc<MathFont>>> {
430 let mut out: Vec<Arc<MathFont>> = Vec::new();
431 let push = |f: Arc<MathFont>, out: &mut Vec<Arc<MathFont>>| {
432 if !out.iter().any(|g| Arc::ptr_eq(g, &f)) {
433 out.push(f);
434 }
435 };
436 for fam in families {
437 if let Some(f) = res!(select(book, fam, variant)) {
438 push(f, &mut out);
439 }
440 }
441 if fallback {
442 for fam in FALLBACKS {
443 if let Some(f) = res!(select(book, fam, variant)) {
444 push(f, &mut out);
445 }
446 }
447 }
448 if out.is_empty() {
449 out.push(res!(resolve(book, families, fallback, variant)));
450 }
451 Ok(out)
452}