//! Native TeX82 math-list geometry, at the standard CM 10/7/5pt sizes. //! //! Route-D stores this geometry at measurement time for PDF and SVG painting. //! The transitional AST frontend may retain its old Route-D implementation for //! unported atoms. The strict native token executor uses shared measured helpers //! with actual family parameters and propagates unsupported input; no fallback. //! Positions use scaled points, with y increasing down from the math baseline. //! Algorithms: TeX82 `make_fraction`, `make_op`, `make_scripts`, and the //! `math_spacing` table in https://mirrors.ctan.org/systems/knuth/dist/tex/tex.web. use std::sync::OnceLock; use crate::cmr10::{math_extension_slot, math_symbol_slot}; use crate::math::{MathAtom, MathBox, MathClass, big_operator_character}; use crate::tfm::TfmMetrics; const PT: i64 = 65_536; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[repr(u8)] pub enum MathStyle { Display, DisplayCramped, Text, TextCramped, Script, ScriptCramped, ScriptScript, ScriptScriptCramped, } impl MathStyle { fn from_code(code: u8) -> Self { use MathStyle::*; [ Display, DisplayCramped, Text, TextCramped, Script, ScriptCramped, ScriptScript, ScriptScriptCramped, ][usize::from(code)] } pub(crate) fn size_index(self) -> usize { match self as u8 { 0..=3 => 0, 4..=5 => 1, _ => 2, } } pub(crate) fn display(self) -> bool { (self as u8) < 2 } pub(crate) fn cramped_style(self) -> Self { Self::from_code(self as u8 | 1) } pub(crate) fn cramped(self) -> bool { self as u8 % 2 == 1 } pub(crate) fn sup(self) -> Self { Self::from_code(2 * (self as u8 / 4) + 4 + self as u8 % 2) } pub(crate) fn sub(self) -> Self { Self::from_code(2 * (self as u8 / 4) + 5) } pub(crate) fn numerator(self) -> Self { Self::from_code(self as u8 + 2 - 2 * (self as u8 / 6)) } pub(crate) fn denominator(self) -> Self { Self::from_code(2 * (self as u8 / 2) + 3 - 2 * (self as u8 / 6)) } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathFont { Roman, Italic, Symbol, Extension, } fn font(family: MathFont, style: MathStyle) -> &'static TfmMetrics { static ROMAN: OnceLock<[TfmMetrics; 3]> = OnceLock::new(); static ITALIC: OnceLock<[TfmMetrics; 3]> = OnceLock::new(); static SYMBOL: OnceLock<[TfmMetrics; 3]> = OnceLock::new(); static EXTENSION: OnceLock = OnceLock::new(); macro_rules! sizes { ($cache:ident, $ten:literal, $seven:literal, $five:literal) => { &$cache.get_or_init(|| { [ include_bytes!($ten).as_slice(), include_bytes!($seven).as_slice(), include_bytes!($five).as_slice(), ] .map(|bytes| TfmMetrics::parse(bytes).expect("embedded math TFM")) })[style.size_index()] }; } match family { MathFont::Roman => sizes!( ROMAN, "../assets/cmr10.tfm", "../assets/cmr7.tfm", "../assets/cmr5.tfm" ), MathFont::Italic => sizes!( ITALIC, "../assets/cmmi10.tfm", "../assets/cmmi7.tfm", "../assets/cmmi5.tfm" ), MathFont::Symbol => sizes!( SYMBOL, "../assets/cmsy10.tfm", "../assets/cmsy7.tfm", "../assets/cmsy5.tfm" ), // Plain TeX and standard LaTeX use cmex10 at its design size in all styles. MathFont::Extension => EXTENSION.get_or_init(|| { TfmMetrics::parse(include_bytes!("../assets/cmex10.tfm")).expect("embedded cmex10") }), } } #[derive(Clone, Copy, Debug)] pub struct MathParams { pub axis_height: i64, pub x_height: i64, pub quad: i64, pub num1: i64, pub num2: i64, pub num3: i64, pub denom1: i64, pub denom2: i64, pub sup1: i64, pub sup2: i64, pub sup3: i64, pub sub1: i64, pub sub2: i64, pub sup_drop: i64, pub sub_drop: i64, pub delim1: i64, pub delim2: i64, pub rule_thickness: i64, pub big_op_spacing: [i64; 5], } impl MathParams { pub fn for_style(style: MathStyle) -> Self { Self::from_metrics( font(MathFont::Symbol, style), font(MathFont::Extension, style), ) } pub(crate) fn from_metrics(symbol: &TfmMetrics, extension: &TfmMetrics) -> Self { Self::from_parameters(|n| symbol.param(n), |n| extension.param(n)) } pub(crate) fn from_parameters( symbol: impl Fn(usize) -> i64, extension: impl Fn(usize) -> i64, ) -> Self { Self { axis_height: symbol(21), x_height: symbol(4), quad: symbol(5), num1: symbol(7), num2: symbol(8), num3: symbol(9), denom1: symbol(10), denom2: symbol(11), sup1: symbol(12), sup2: symbol(13), sup3: symbol(14), sub1: symbol(15), sub2: symbol(16), sup_drop: symbol(17), sub_drop: symbol(18), delim1: symbol(19), delim2: symbol(20), rule_thickness: extension(7), big_op_spacing: std::array::from_fn(|i| extension(i + 8)), } } } /// A glyph's slot and design size are retained for the shared painter. Unicode /// alone cannot identify the large CMEX variant or the 7pt/5pt optical masters. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathItem { PdfImage(std::sync::Arc), NativeGlyph { font: std::sync::Arc, slot: u8, character: char, size: i64, }, Glyph { character: char, font: MathFont, slot: u8, size: i64, }, Rule { width: i64, height: i64, }, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct PositionedItem { pub x: i64, pub y: i64, pub item: MathItem, pub source: crate::provenance::PaintSource, } #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MathGeometry { pub metrics: MathBox, pub items: Vec, } impl MathGeometry { pub(crate) fn append(&mut self, child: Self, x: i64, y: i64) { self.metrics.height = self.metrics.height.max(child.metrics.height - y); self.metrics.depth = self.metrics.depth.max(child.metrics.depth + y); self.items.extend(child.items.into_iter().map(|mut item| { item.x += x; item.y += y; item })); } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MathError { UnsupportedAtom(&'static str), UnsupportedSymbol(char), UnsupportedOperator(String), } fn symbol_slot(character: char) -> Option<(MathFont, u8)> { use MathFont::*; let greek = "ΓΔΘΛΞΠΣΥΦΨΩαβγδϵζηθικλμνξπρστυϕχψωεϑϖϱςφ"; if let Some(slot) = greek.chars().position(|c| c == character) { return Some((if slot < 11 { Roman } else { Italic }, slot as u8)); } match character { 'a'..='z' | 'A'..='Z' | '<' | '>' => Some((Italic, character as u8)), '/' => Some((Italic, 61)), ',' => Some((Italic, 59)), '.' => Some((Italic, 58)), '-' | '−' => Some((Symbol, 0)), '*' => Some((Symbol, 3)), '|' => Some((Symbol, 106)), '0'..='9' | '+' | '=' | '(' | ')' | '[' | ']' | ':' | ';' | '!' | '?' => { Some((Roman, character as u8)) } _ => math_symbol_slot(character).map(|slot| (Symbol, slot)), } } fn glyph( character: char, family: MathFont, slot: u8, style: MathStyle, italic: bool, ) -> Result { let metrics = font(family, style); let slot_char = char::from(slot); if metrics.width(slot_char) == 0 { return Err(MathError::UnsupportedSymbol(character)); } Ok(MathGeometry { metrics: MathBox { width: metrics.width(slot_char) + if italic { metrics.italic(slot_char) } else { 0 }, height: metrics.height(slot_char), depth: metrics.depth(slot_char), }, items: vec![PositionedItem { source: Default::default(), x: 0, y: 0, item: MathItem::Glyph { character, font: family, slot, size: metrics.size_sp(), }, }], }) } fn symbol(character: char, style: MathStyle, italic: bool) -> Result { let (family, slot) = symbol_slot(character).ok_or(MathError::UnsupportedSymbol(character))?; glyph(character, family, slot, style, italic) } fn class(atom: &MathAtom) -> Option { use MathClass::*; Some(match atom { MathAtom::Space(_) | MathAtom::MuSpace(_) | MathAtom::Style(_) => return None, MathAtom::Classed { class, .. } => *class, MathAtom::Symbol(c) => match c { '+' | '-' | '−' | '*' | '×' | '·' | '±' | '∓' => Binary, '=' | '<' | '>' | ':' | '≤' | '≥' | '∈' | '≈' | '→' => Relation, '(' | '[' | '{' => Open, ')' | ']' | '}' | '!' | '?' => Close, ',' | ';' => Punctuation, _ => Ordinary, }, MathAtom::BigOperator { .. } | MathAtom::OperatorName { .. } => Op, MathAtom::Script { base, .. } | MathAtom::Limits { base, .. } | MathAtom::ForcedLimits { base, .. } => class(base)?, MathAtom::Styled { body, .. } => class(body)?, MathAtom::Fraction { .. } => Inner, _ => Ordinary, }) } fn class_index(class: MathClass) -> usize { use MathClass::*; match class { Ordinary => 0, Op => 1, Binary => 2, Relation => 3, Open => 4, Close => 5, Punctuation => 6, Inner => 7, } } /// TeX82's full table, including thin spaces that survive in script styles. fn spacing(left: MathClass, right: MathClass, style: MathStyle) -> i64 { let table = b"0234000122*4000133**3**344*0400400*000000234000111*1111112341011"; let level = table[class_index(left) * 8 + class_index(right)]; let mu = match level { b'2' => 3, b'1' if style.size_index() == 0 => 3, b'3' if style.size_index() == 0 => 4, b'4' if style.size_index() == 0 => 5, _ => 0, }; // TeX truncates cur_mu to sp before multiplying by the integral mu width. mu * (MathParams::for_style(style).quad / 18) } fn row(atoms: &[MathAtom], style: MathStyle) -> Result { let mut style = style; use MathClass::*; let mut classes: Vec<_> = atoms.iter().map(class).collect(); let mut previous = None; for i in 0..classes.len() { let Some(mut current) = classes[i] else { continue; }; if current == Binary && (previous.is_none() || matches!( previous, Some((_, Binary | Op | Relation | Open | Punctuation)) )) { current = Ordinary; classes[i] = Some(current); } if matches!(current, Relation | Close | Punctuation) { if let Some((index, Binary)) = previous { classes[index] = Some(Ordinary); } } previous = Some((i, current)); } if let Some((index, Binary)) = previous { classes[index] = Some(Ordinary); } let mut result = MathGeometry::default(); let mut previous = None; let mut cursor = 0; for (index, atom) in atoms.iter().enumerate() { if let MathAtom::Style(new_style) = atom { style = *new_style; continue; } if let Some(current) = classes[index] { if let Some(left) = previous { cursor += spacing(left, current, style); } previous = Some(current); } let child = layout(atom, style)?; let width = child.metrics.width; result.append(child, cursor, 0); cursor += width; // TeX's make_ord applies a same-family math kern before class glue. if let (MathAtom::Symbol(left), Some(MathAtom::Symbol(right))) = (atom, atoms.get(index + 1)) { if classes[index] == Some(Ordinary) { if let (Some((lf, ls)), Some((rf, rs))) = (symbol_slot(*left), symbol_slot(*right)) { if lf == rf { cursor += font(lf, style).kern(char::from(ls), char::from(rs)); } } } } } result.metrics.width = cursor; Ok(result) } fn roman(text: &str, style: MathStyle) -> Result { let mut result = MathGeometry::default(); let mut cursor = 0; for character in text.chars() { if character == ' ' { cursor += font(MathFont::Roman, style).space(); continue; } let slot = u8::try_from(character as u32).map_err(|_| MathError::UnsupportedSymbol(character))?; let child = glyph(character, MathFont::Roman, slot, style, false)?; let width = child.metrics.width; result.append(child, cursor, 0); cursor += width; } result.metrics.width = cursor; Ok(result) } fn operator(name: &str, style: MathStyle) -> Result { let character = big_operator_character(name).ok_or_else(|| MathError::UnsupportedOperator(name.into()))?; let mut slot = math_extension_slot(character) .ok_or_else(|| MathError::UnsupportedOperator(name.into()))?; let metrics = font(MathFont::Extension, style); if style.display() { slot = metrics.next_larger(char::from(slot)).unwrap_or(slot); } let body = glyph(character, MathFont::Extension, slot, style, true)?; let shift = (body.metrics.height - body.metrics.depth + 1) / 2 - MathParams::for_style(style).axis_height; let mut result = MathGeometry::default(); result.metrics.width = body.metrics.width; result.append(body, 0, shift); Ok(result) } fn scripts( base: &MathAtom, sub: Option<&MathAtom>, sup: Option<&MathAtom>, style: MathStyle, ) -> Result { let params = MathParams::for_style(style); let mut body = layout(base, style)?; let mut italic = 0; let nucleus = glyph_nucleus(base); let single = nucleus.is_some(); if let Some((family, slot)) = nucleus { italic = font(family, style).italic(char::from(slot)); if sub.is_some() { body.metrics.width -= italic; } } if let MathAtom::BigOperator { .. } = base { if let Some(PositionedItem { item: MathItem::Glyph { slot, .. }, .. }) = body.items.first() { italic = font(MathFont::Extension, style).italic(char::from(*slot)); if sub.is_some() { body.metrics.width -= italic; } } } let upper = sup.map(|a| layout(a, style.sup())).transpose()?; let lower = sub.map(|a| layout(a, style.sub())).transpose()?; Ok(place_scripts( body, upper, lower, italic, single, params, MathParams::for_style(style.sup()), style, PT / 2, )) } /// Shared noad geometry; callers supply actual family parameters and scriptspace. #[allow(clippy::too_many_arguments)] pub(crate) fn place_scripts( body: MathGeometry, upper: Option, lower: Option, italic: i64, single: bool, params: MathParams, drop: MathParams, style: MathStyle, script_space: i64, ) -> MathGeometry { place_scripts_with_layout( body, upper, lower, italic, single, params, drop, style, script_space, ) .0 } /// The actual make_scripts shifts, shared by geometry and native owned lists. pub(crate) struct ScriptPlacement { pub up: i64, pub down: i64, } pub(crate) fn place_scripts_with_layout( mut body: MathGeometry, upper: Option, lower: Option, italic: i64, single: bool, params: MathParams, drop: MathParams, style: MathStyle, script_space: i64, ) -> (MathGeometry, ScriptPlacement) { let has_sub = lower.is_some(); let mut up = if single { 0 } else { body.metrics.height - drop.sup_drop }; let mut down = if single { 0 } else { body.metrics.depth + drop.sub_drop }; if let Some(upper) = &upper { let min = if style.cramped() { params.sup3 } else if style.display() { params.sup1 } else { params.sup2 }; up = up .max(min) .max(upper.metrics.depth + params.x_height.abs() / 4); } if let Some(lower) = &lower { if let Some(upper) = &upper { down = down.max(params.sub2); let gap = up - upper.metrics.depth - lower.metrics.height + down; if gap < 4 * params.rule_thickness { down += 4 * params.rule_thickness - gap; let lift = (4 * params.x_height.abs() / 5 - (up - upper.metrics.depth)).max(0); up += lift; down -= lift; } } else { down = down .max(params.sub1) .max(lower.metrics.height - 4 * params.x_height.abs() / 5); } } let start = body.metrics.width; let mut end = start; if let Some(upper) = upper { let x = start + if has_sub { italic } else { 0 }; end = end.max(x + upper.metrics.width + script_space); body.append(upper, x, -up); } if let Some(lower) = lower { end = end.max(start + lower.metrics.width + script_space); body.append(lower, start, down); } body.metrics.width = end; (body, ScriptPlacement { up, down }) } fn glyph_nucleus(atom: &MathAtom) -> Option<(MathFont, u8)> { match atom { MathAtom::Symbol(character) => symbol_slot(*character), MathAtom::Row(atoms) if atoms.len() == 1 => glyph_nucleus(&atoms[0]), MathAtom::Alphabet { text, alphabet: crate::math::MathAlphabet::Italic, } if text.chars().count() == 1 => { let (_, slot) = symbol_slot(text.chars().next()?)?; Some((MathFont::Italic, slot)) } _ => None, } } fn single_symbol(atom: &MathAtom) -> Option { match atom { MathAtom::Symbol(character) => Some(*character), MathAtom::Row(atoms) if atoms.len() == 1 => single_symbol(&atoms[0]), _ => None, } } fn limits( base: &MathAtom, sub: Option<&MathAtom>, sup: Option<&MathAtom>, style: MathStyle, force: bool, ) -> Result { // Limits nodes currently encode the parser's default display limits. if !force && !style.display() { return scripts(base, sub, sup, style); } let body = layout(base, style)?; let upper = sup.map(|atom| layout(atom, style.sup())).transpose()?; let lower = sub.map(|atom| layout(atom, style.sub())).transpose()?; let width = body .metrics .width .max(upper.as_ref().map_or(0, |b| b.metrics.width)) .max(lower.as_ref().map_or(0, |b| b.metrics.width)); let italic = match body.items.first() { Some(PositionedItem { item: MathItem::Glyph { font: MathFont::Extension, slot, .. }, .. }) => font(MathFont::Extension, style).italic(char::from(*slot)), _ => 0, }; let [space1, space2, space3, space4, space5] = MathParams::for_style(style).big_op_spacing; let mut result = MathGeometry::default(); result.metrics.width = width; let b = body.metrics; result.append(body, (width - b.width) / 2, 0); if let Some(upper) = upper { let u = upper.metrics; let y = -(b.height + space1.max(space3 - u.depth) + u.depth); result.append(upper, (width - u.width) / 2 + (italic + 1) / 2, y); result.metrics.height += space5; } if let Some(lower) = lower { let l = lower.metrics; let y = b.depth + space2.max(space4 - l.height) + l.height; result.append(lower, (width - l.width) / 2 - (italic + 1) / 2, y); result.metrics.depth += space5; } Ok(result) } fn fraction( numerator: &MathAtom, denominator: &MathAtom, bar: bool, style: MathStyle, ) -> Result { let params = MathParams::for_style(style); let num = layout(numerator, style.numerator())?; let den = layout(denominator, style.denominator())?; Ok(place_fraction( num, den, bar, style, params, 78_643, Default::default(), )) } pub(crate) fn place_fraction( num: MathGeometry, den: MathGeometry, bar: bool, style: MathStyle, params: MathParams, null: i64, source: crate::provenance::PaintSource, ) -> MathGeometry { let n = num.metrics; let d = den.metrics; let width = n.width.max(d.width); let mut up = if style.display() { params.num1 } else if bar { params.num2 } else { params.num3 }; let mut down = if style.display() { params.denom1 } else { params.denom2 }; let thickness = if bar { params.rule_thickness } else { 0 }; let half = (thickness + 1) / 2; if bar { let clearance = if style.display() { 3 * thickness } else { thickness }; up = up.max(n.depth + params.axis_height + half + clearance); down = down.max(d.height - params.axis_height + half + clearance); } else { let clearance = if style.display() { 7 } else { 3 } * params.rule_thickness; let delta = ((clearance - (up - n.depth - d.height + down) + 1) / 2).max(0); up += delta; down += delta; } // TeX's two null delimiters occupy 1.2pt each, outside the fraction bar. let mut result = MathGeometry::default(); result.metrics.width = width + 2 * null; result.append(num, null + (width - n.width + 1).div_euclid(2), -up); // Preserve the fraction vlist's traversal order. Besides overlapping ink, // this determines where a PDF text object is closed for the rule and the // subsequent denominator starts a new text positioning matrix. if bar { result.items.push(PositionedItem { source, x: null, y: -params.axis_height - half, item: MathItem::Rule { width, height: thickness, }, }); } // The two TeX vlist kerns both subtract half(thickness). With an odd // thickness the actual denominator baseline is one sp above shift_down; // the declared fraction box depth still includes the full shift_down. result.append( den, null + (width - d.width + 1).div_euclid(2), down + thickness - 2 * half, ); result.metrics.depth = d.depth + down; result } pub fn layout(atom: &MathAtom, style: MathStyle) -> Result { match atom { MathAtom::Style(_) => Ok(MathGeometry::default()), MathAtom::Styled { style, body } => layout(body, *style), MathAtom::MuSpace(mu) => Ok(MathGeometry { metrics: MathBox { width: mu * (MathParams::for_style(style).quad / 18) / PT, height: 0, depth: 0, }, items: vec![], }), MathAtom::ForcedLimits { base, sub, sup } => { limits(base, sub.as_deref(), sup.as_deref(), style, true) } MathAtom::Alphabet { text, alphabet: crate::math::MathAlphabet::Roman, } => roman(text, style), MathAtom::Alphabet { text, alphabet: crate::math::MathAlphabet::Italic, } => { let mut result = MathGeometry::default(); let mut x = 0; for character in text.chars() { let (_, slot) = symbol_slot(character).ok_or(MathError::UnsupportedSymbol(character))?; let child = glyph(character, MathFont::Italic, slot, style, true)?; let width = child.metrics.width; result.append(child, x, 0); x += width; } result.metrics.width = x; Ok(result) } MathAtom::Symbol(character) => symbol(*character, style, true), MathAtom::Space(width) => Ok(MathGeometry { metrics: MathBox { width: *width, height: 0, depth: 0, }, items: vec![], }), MathAtom::Row(atoms) => row(atoms, style), MathAtom::Text(text) | MathAtom::OperatorName { name: text, .. } => roman(text, style), MathAtom::BigOperator { name } => operator(name, style), MathAtom::Classed { class: MathClass::Op, body, } if single_symbol(body).is_some() => { let body = layout(body, style)?; let shift = (body.metrics.height - body.metrics.depth + 1) / 2 - MathParams::for_style(style).axis_height; let mut result = MathGeometry::default(); result.metrics.width = body.metrics.width; result.append(body, 0, shift); Ok(result) } MathAtom::Classed { body, .. } => layout(body, style), MathAtom::Script { base, sub, sup } => scripts(base, sub.as_deref(), sup.as_deref(), style), MathAtom::Limits { base, sub, sup } => { limits(base, sub.as_deref(), sup.as_deref(), style, false) } MathAtom::Fraction { numerator, denominator, bar, } => fraction(numerator, denominator, *bar, style), MathAtom::TaggedWidth { body, tag, width } => { let body = layout(body, style)?; let tag = roman(tag, MathStyle::Text)?; let mut result = MathGeometry::default(); result.metrics.width = *width; let body_x = ((*width - body.metrics.width) / 2).max(0); let tag_x = *width - tag.metrics.width; result.append(body, body_x, 0); result.append(tag, tag_x, 0); Ok(result) } _ => Err(MathError::UnsupportedAtom( "atom not yet ported to native math geometry", )), } } #[cfg(test)] mod tests { use super::*; use crate::math::parse_math; #[test] fn matches_pdftex_box_oracle() { let probes: serde_json::Value = serde_json::from_str(include_str!("../tests/fixtures/math-tex-oracle.json")).unwrap(); let mut failures = Vec::new(); let mut max_delta = 0; for probe in probes.as_array().unwrap() { let style = match probe["style"].as_str().unwrap() { "Display" => MathStyle::Display, "Text" => MathStyle::Text, "Script" => MathStyle::Script, "ScriptScript" => MathStyle::ScriptScript, _ => unreachable!(), }; let source = probe["source"].as_str().unwrap(); let actual = layout(&parse_math(source), style).unwrap().metrics; for (field, value) in [ ("width", actual.width), ("height", actual.height), ("depth", actual.depth), ] { let expected = probe[field].as_i64().unwrap(); max_delta = max_delta.max((value - expected).abs()); if (value - expected).abs() > 8 { failures.push(format!( "{style:?} {source}: {field} {value} != {expected} (delta {})", value - expected )); } } } assert!(failures.is_empty(), "{}", failures.join("\n")); eprintln!( "{} pdfTeX probes, maximum dimension error: {max_delta}sp", probes.as_array().unwrap().len() ); } fn check_pt(actual: i64, expected: f64) { assert!( (actual as f64 / PT as f64 - expected).abs() < 0.00004, "{}pt != {expected}pt", actual as f64 / PT as f64 ); } fn glyph_position(geometry: &MathGeometry, target: char) -> (i64, i64) { geometry .items .iter() .find_map(|position| match position.item { MathItem::Glyph { character, .. } if character == target => { Some((position.x, position.y)) } _ => None, }) .unwrap() } #[test] fn script_positions_match_pdftex_showbox() { // pdfTeX: x_i^2 has a vbox shifted 2.47217pt, with upper // height 4.51111pt and total height 11.1122pt. let geometry = layout(&parse_math("x_i^2"), MathStyle::Display).unwrap(); check_pt(glyph_position(&geometry, '2').1, -4.12892); check_pt(glyph_position(&geometry, 'i').1, 2.47217); let geometry = layout(&parse_math("f_j^N"), MathStyle::Display).unwrap(); let (upper_x, _) = glyph_position(&geometry, 'N'); let (lower_x, _) = glyph_position(&geometry, 'j'); let metrics = font(MathFont::Italic, MathStyle::Display); assert_eq!(upper_x - lower_x, metrics.italic('f')); } #[test] fn fraction_positions_match_pdftex_showbox_and_rule_clearance() { let geometry = layout(&parse_math(r"\frac{x_i^2}{y_j}"), MathStyle::Display).unwrap(); check_pt(glyph_position(&geometry, 'x').1, -6.76507); check_pt(glyph_position(&geometry, 'y').1, 6.85951); let rule = geometry .items .iter() .find(|p| matches!(p.item, MathItem::Rule { .. })) .unwrap(); check_pt(rule.y, -2.69998); let MathItem::Rule { width, height } = rule.item else { unreachable!() }; check_pt(width, 10.2014); check_pt(height, 0.39998); // The numerator descender must clear the bar by three rule thicknesses. let numerator = layout(&parse_math("x_i^2"), MathStyle::Text).unwrap(); let numerator_bottom = glyph_position(&geometry, 'x').1 + numerator.metrics.depth; assert!(rule.y - numerator_bottom >= 3 * height); let denominator = layout(&parse_math("y_j"), MathStyle::TextCramped).unwrap(); let denominator_top = glyph_position(&geometry, 'y').1 - denominator.metrics.height; assert!(denominator_top - (rule.y + height) >= 3 * height); } #[test] fn display_operator_positions_and_slots_match_pdftex_showbox() { let geometry = layout(&parse_math(r"\sum_{i=1}^N"), MathStyle::Display).unwrap(); check_pt(glyph_position(&geometry, '∑').1, -9.50006); check_pt(glyph_position(&geometry, 'N').1, -12.50004); check_pt(glyph_position(&geometry, 'i').1, 11.79865); assert!(geometry.items.iter().any(|p| matches!( p.item, MathItem::Glyph { font: MathFont::Extension, slot: 88, .. } ))); let text = layout(&parse_math(r"\sum_{i=1}^N"), MathStyle::Text).unwrap(); assert!(text.items.iter().any(|p| matches!( p.item, MathItem::Glyph { font: MathFont::Extension, slot: 80, .. } ))); assert!(glyph_position(&text, 'i').0 > glyph_position(&text, '∑').0); } #[test] fn cramped_styles_and_optical_sizes_are_preserved() { for (regular, cramped) in [ (MathStyle::Display, MathStyle::DisplayCramped), (MathStyle::Text, MathStyle::TextCramped), (MathStyle::Script, MathStyle::ScriptCramped), (MathStyle::ScriptScript, MathStyle::ScriptScriptCramped), ] { let regular = layout(&parse_math("x^2"), regular).unwrap(); let cramped = layout(&parse_math("x^2"), cramped).unwrap(); assert!(glyph_position(&cramped, '2').1 > glyph_position(®ular, '2').1); assert_eq!(regular.metrics.width, cramped.metrics.width); } let text = layout(&parse_math("x"), MathStyle::Text).unwrap(); let script = layout(&parse_math("x"), MathStyle::Script).unwrap(); assert_ne!(script.metrics.width, text.metrics.width * 7 / 10); assert!(matches!( script.items[0].item, MathItem::Glyph { size: 458_752, .. } )); let nested = layout(&parse_math("x^{y^z}"), MathStyle::Text).unwrap(); assert!(nested.items.iter().any(|p| matches!( p.item, MathItem::Glyph { character: 'z', size: 327_680, .. } ))); } #[test] fn tagged_equation_translates_the_same_geometry_and_keeps_tag_at_margin() { let atom = parse_math(r"\frac{x_i}{y}"); let body = layout(&atom, MathStyle::Display).unwrap(); let measure = 468 * PT; let tagged = layout( &MathAtom::TaggedWidth { body: Box::new(atom), tag: "(1)".into(), width: measure, }, MathStyle::Display, ) .unwrap(); let offset = (measure - body.metrics.width) / 2; for (original, positioned) in body.items.iter().zip(&tagged.items) { assert_eq!(positioned.x, original.x + offset); assert_eq!(positioned.y, original.y); assert_eq!(positioned.item, original.item); } let last = tagged.items.last().unwrap(); assert_eq!( last.x + font(MathFont::Roman, MathStyle::Text).width(')'), measure ); assert_eq!(tagged.metrics.width, measure); } #[test] fn unsupported_atoms_fail_the_whole_formula() { assert!(matches!( layout(&parse_math(r"x+\sqrt{y}"), MathStyle::Display), Err(MathError::UnsupportedAtom(_)) )); assert_eq!( layout(&MathAtom::Symbol('中'), MathStyle::Text), Err(MathError::UnsupportedSymbol('中')) ); } }