//! M4 math list model: symbols, scripts and fractions expressed as boxes. //! //! This is deliberately independent of v1's math renderer. It provides the //! geometry the route-D page builder needs; token-to-atom conversion and the //! final painter arrive in later M4 slices. use crate::cmr10::Cmr10Metrics; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum MathAtom { Symbol(char), Row(Vec), Sqrt(Box), Script { base: Box, sub: Option>, sup: Option>, }, Fraction { numerator: Box, denominator: Box, }, } impl MathAtom { pub fn symbol(character: char) -> Self { Self::Symbol(character) } pub fn script(base: MathAtom, sub: Option, sup: Option) -> Self { Self::Script { base: Box::new(base), sub: sub.map(Box::new), sup: sup.map(Box::new), } } pub fn fraction(numerator: MathAtom, denominator: MathAtom) -> Self { Self::Fraction { numerator: Box::new(numerator), denominator: Box::new(denominator), } } } /// Geometry of a math atom in scaled points, measured from its baseline. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MathBox { pub width: i64, pub height: i64, pub depth: i64, } fn scaled(value: i64, factor: f64) -> i64 { (value as f64 * factor).round() as i64 } /// Lay out a math atom at the current style size. pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { match atom { MathAtom::Symbol(character) => MathBox { width: font.width(*character), height: 7 * 65_536, depth: 2 * 65_536, }, MathAtom::Row(atoms) => { let mut width = 0; let mut height = 0; let mut depth = 0; for atom in atoms { let boxed = layout_math(atom, font); width += boxed.width; height = height.max(boxed.height); depth = depth.max(boxed.depth); } MathBox { width, height, depth, } } MathAtom::Sqrt(atom) => { let boxed = layout_math(atom, font); MathBox { width: boxed.width + 4 * 65_536, height: boxed.height + 2 * 65_536, depth: boxed.depth, } } MathAtom::Script { base, sub, sup } => { let base_box = layout_math(base, font); let sub_box = sub.as_deref().map(|atom| layout_math(atom, font)); let sup_box = sup.as_deref().map(|atom| layout_math(atom, font)); let script_width = sub_box .as_ref() .map(|boxed| boxed.width) .unwrap_or(0) .max(sup_box.as_ref().map(|boxed| boxed.width).unwrap_or(0)); let sup_height = sup_box.as_ref().map_or(0, |boxed| boxed.height); let sub_depth = sub_box.as_ref().map_or(0, |boxed| boxed.depth); MathBox { width: base_box.width + scaled(script_width, 0.7), height: base_box .height .max(scaled(base_box.height, 0.6) + scaled(sup_height, 0.7)), depth: base_box .depth .max(scaled(base_box.depth, 0.5) + scaled(sub_depth, 0.7)), } } MathAtom::Fraction { numerator, denominator, } => { let numerator_box = layout_math(numerator, font); let denominator_box = layout_math(denominator, font); let width = numerator_box .width .max(denominator_box.width) .saturating_add(2 * 65_536); MathBox { width, height: scaled(numerator_box.height + numerator_box.depth, 0.7) + 2 * 65_536, depth: scaled(denominator_box.height + denominator_box.depth, 0.7) + 2 * 65_536, } } } } /// Parse a small TeX math subset into a [`MathAtom`] row. /// /// Supported: plain symbols, `{}` groups, `_`/`^` scripts, `\frac{a}{b}` and /// `\sqrt{x}`. Whitespace is ignored. Unknown control words become `?` so a /// later M4 parser can replace them. pub fn parse_math(input: &str) -> MathAtom { let chars: Vec = input.chars().filter(|ch| !ch.is_whitespace()).collect(); let (atom, _) = parse_sequence(&chars, 0, false); atom } fn parse_sequence(chars: &[char], mut index: usize, stop_at_brace: bool) -> (MathAtom, usize) { let mut atoms = Vec::new(); while index < chars.len() { if stop_at_brace && chars[index] == '}' { break; } let (mut atom, mut next) = parse_atom(chars, index); let mut sub = None; let mut sup = None; loop { if next < chars.len() && chars[next] == '_' && sub.is_none() { let (script, after) = parse_script(chars, next + 1); sub = Some(Box::new(script)); next = after; } else if next < chars.len() && chars[next] == '^' && sup.is_none() { let (script, after) = parse_script(chars, next + 1); sup = Some(Box::new(script)); next = after; } else { break; } } if sub.is_some() || sup.is_some() { atom = MathAtom::Script { base: Box::new(atom), sub, sup, }; } atoms.push(atom); index = next; } (MathAtom::Row(atoms), index) } fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) { let Some(&character) = chars.get(index) else { return (MathAtom::Row(Vec::new()), index); }; if character == '{' { let (atom, next) = parse_sequence(chars, index + 1, true); let next = if chars.get(next) == Some(&'}') { next + 1 } else { next }; return (atom, next); } if character == '\\' { let mut next = index + 1; let mut command = String::new(); while let Some(&ch) = chars.get(next) { if ch.is_ascii_alphabetic() { command.push(ch); next += 1; } else { break; } } return match command.as_str() { "frac" => { let (numerator, after) = parse_atom(chars, next); let (denominator, after) = parse_atom(chars, after); (MathAtom::fraction(numerator, denominator), after) } "sqrt" => { let (radicand, after) = parse_atom(chars, next); (MathAtom::Sqrt(Box::new(radicand)), after) } _ => (MathAtom::Symbol('?'), next), }; } (MathAtom::Symbol(character), index + 1) } fn parse_script(chars: &[char], index: usize) -> (MathAtom, usize) { if chars.get(index) == Some(&'{') { parse_atom(chars, index) } else if chars.get(index) == Some(&'\\') { parse_atom(chars, index) } else if let Some(&character) = chars.get(index) { (MathAtom::Symbol(character), index + 1) } else { (MathAtom::Row(Vec::new()), index) } } #[cfg(test)] mod tests { use super::*; #[test] fn math_symbol_uses_font_width() { let font = Cmr10Metrics::default(); let boxed = layout_math(&MathAtom::symbol('x'), &font); assert_eq!(boxed.width, font.width('x')); assert!(boxed.height > 0); assert!(boxed.depth > 0); } #[test] fn script_stacks_above_and_below_the_base() { let font = Cmr10Metrics::default(); let plain = layout_math(&MathAtom::symbol('x'), &font); let scripted = layout_math( &MathAtom::script( MathAtom::symbol('x'), Some(MathAtom::symbol('i')), Some(MathAtom::symbol('2')), ), &font, ); assert!(scripted.width > plain.width); assert!(scripted.height > plain.height); assert!(scripted.depth >= plain.depth); } #[test] fn fraction_is_wider_than_its_parts() { let font = Cmr10Metrics::default(); let numerator = layout_math(&MathAtom::symbol('a'), &font); let fraction = layout_math( &MathAtom::fraction(MathAtom::symbol('a'), MathAtom::symbol('b')), &font, ); assert!(fraction.width > numerator.width); assert!(fraction.height > numerator.height); assert!(fraction.depth > 0); } #[test] fn parse_script_attaches_to_the_previous_atom() { let atom = parse_math("x^2"); let MathAtom::Row(atoms) = atom else { panic!("expected a row"); }; assert!(matches!(&atoms[0], MathAtom::Script { sup: Some(_), .. })); } #[test] fn parse_fraction_and_sqrt() { let atom = parse_math("\\frac{a}{b} + \\sqrt{x}"); let MathAtom::Row(atoms) = atom else { panic!("expected a row"); }; assert!(matches!(&atoms[0], MathAtom::Fraction { .. })); assert!(matches!(&atoms[2], MathAtom::Sqrt(_))); } }