//! 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 { radicand: Box, degree: Option>, }, Text(String), Delimited { left: char, right: char, body: Box, }, Accent { accent: char, base: Box, }, Underline { base: Box, }, Binomial { numerator: Box, denominator: 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, } /// TeX math atom classes used for inter-atom spacing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MathClass { Ordinary, Binary, Relation, Open, Close, Punctuation, } pub fn math_class(character: char) -> MathClass { match character { '+' | '-' | '*' | '/' => MathClass::Binary, '=' | '<' | '>' | ':' => MathClass::Relation, '(' | '[' | '{' => MathClass::Open, ')' | ']' | '}' => MathClass::Close, ',' | ';' => MathClass::Punctuation, _ => MathClass::Ordinary, } } /// TeX's spacing table in math units (1mu = 1/18em). fn spacing_mu(left: MathClass, right: MathClass) -> i64 { use MathClass::*; match (left, right) { (Binary, Binary) | (Relation, Relation) | (Open, _) | (_, Close) | (_, Punctuation) | (Punctuation, _) => 0, (Ordinary, Binary) | (Binary, Ordinary) => 4, (Ordinary, Relation) | (Relation, Ordinary) => 5, (Binary, Relation) | (Relation, Binary) => 0, (Ordinary, Ordinary) => 0, _ => 0, } } fn scaled(value: i64, factor: f64) -> i64 { (value as f64 * factor).round() as i64 } fn atom_class(atom: &MathAtom) -> MathClass { match atom { MathAtom::Symbol(character) => math_class(*character), MathAtom::Row(atoms) => atoms.last().map(atom_class).unwrap_or(MathClass::Ordinary), _ => MathClass::Ordinary, } } fn delimiter_width(delimiter: char, font: &Cmr10Metrics) -> i64 { if delimiter == '.' { 0 } else { font.width(delimiter) } } /// 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 (index, atom) in atoms.iter().enumerate() { let boxed = layout_math(atom, font); if index > 0 { let left = atom_class(&atoms[index - 1]); let right = atom_class(atom); width += spacing_mu(left, right) * 65_536 / 18; } width += boxed.width; height = height.max(boxed.height); depth = depth.max(boxed.depth); } MathBox { width, height, depth, } } MathAtom::Sqrt { radicand, degree } => { let boxed = layout_math(radicand, font); let degree_box = degree.as_deref().map(|atom| layout_math(atom, font)); MathBox { width: boxed.width + 4 * 65_536 + degree_box.as_ref().map_or(0, |boxed| boxed.width), height: boxed.height + 2 * 65_536 + degree_box.as_ref().map_or(0, |boxed| boxed.height), depth: boxed.depth, } } MathAtom::Text(text) => MathBox { width: text .chars() .map(|character| { if character == ' ' { font.space() } else { font.width(character) } }) .sum(), height: 6 * 65_536, depth: 2 * 65_536, }, MathAtom::Delimited { left, right, body } => { let body_box = layout_math(body, font); MathBox { width: delimiter_width(*left, font) + body_box.width + delimiter_width(*right, font), height: body_box.height + 2 * 65_536, depth: body_box.depth + 2 * 65_536, } } MathAtom::Accent { base, .. } => { let base_box = layout_math(base, font); MathBox { width: base_box.width, height: base_box.height + 2 * 65_536, depth: base_box.depth, } } MathAtom::Binomial { numerator, denominator, } => { let numerator = layout_math(numerator, font); let denominator = layout_math(denominator, font); MathBox { width: numerator.width.max(denominator.width) + 4 * 65_536, height: numerator.height + denominator.height + 2 * 65_536, depth: denominator.depth, } } MathAtom::Underline { base } => { let base_box = layout_math(base, font); MathBox { width: base_box.width, height: base_box.height, depth: base_box.depth + 2 * 65_536, } } 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, false); atom } fn is_right_command(chars: &[char], index: usize) -> bool { chars.get(index) == Some(&'\\') && chars.get(index + 1) == Some(&'r') && chars.get(index + 2) == Some(&'i') && chars.get(index + 3) == Some(&'g') && chars.get(index + 4) == Some(&'h') && chars.get(index + 5) == Some(&'t') } fn parse_sequence( chars: &[char], mut index: usize, stop_at_brace: bool, stop_at_right: bool, ) -> (MathAtom, usize) { let mut atoms = Vec::new(); while index < chars.len() { if stop_at_brace && chars[index] == '}' { break; } if stop_at_right && is_right_command(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, false); 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 mut after = next; let mut degree = None; if chars.get(after) == Some(&'[') { let mut close = after + 1; while close < chars.len() && chars[close] != ']' { close += 1; } let degree_chars = &chars[after + 1..close.min(chars.len())]; let (atom, _) = parse_sequence(degree_chars, 0, false, false); degree = Some(Box::new(atom)); after = if close < chars.len() { close + 1 } else { close }; } let (radicand, after) = parse_atom(chars, after); ( MathAtom::Sqrt { radicand: Box::new(radicand), degree, }, after, ) } "hat" | "widehat" => { let (base, after) = parse_atom(chars, next); ( MathAtom::Accent { accent: '\u{0302}', base: Box::new(base), }, after, ) } "tilde" | "widetilde" => { let (base, after) = parse_atom(chars, next); ( MathAtom::Accent { accent: '\u{0303}', base: Box::new(base), }, after, ) } "binom" | "dbinom" | "tbinom" => { let (numerator, after) = parse_atom(chars, next); let (denominator, after) = parse_atom(chars, after); ( MathAtom::Binomial { numerator: Box::new(numerator), denominator: Box::new(denominator), }, after, ) } "underline" => { let (base, after) = parse_atom(chars, next); ( MathAtom::Underline { base: Box::new(base), }, after, ) } "bar" | "overline" => { let (base, after) = parse_atom(chars, next); ( MathAtom::Accent { accent: '\u{0305}', base: Box::new(base), }, after, ) } "vec" => { let (base, after) = parse_atom(chars, next); ( MathAtom::Accent { accent: '\u{20D7}', base: Box::new(base), }, after, ) } "middle" => { let delimiter = chars.get(next).copied().unwrap_or('|'); (MathAtom::Symbol(delimiter), next + 1) } "max" | "min" | "lim" | "log" | "ln" | "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "exp" | "det" | "dim" | "ker" | "hom" | "arg" | "deg" | "gcd" => { (MathAtom::Text(command.clone()), next) } "text" | "mathrm" => { let mut after = next; if chars.get(after) == Some(&'{') { after += 1; } let start = after; while after < chars.len() && chars[after] != '}' { after += 1; } let text: String = chars[start..after].iter().collect(); if after < chars.len() { after += 1; } (MathAtom::Text(text), after) } "left" => { let left = chars.get(next).copied().unwrap_or('('); let (body, after) = parse_sequence(chars, next + 1, false, true); let mut after = after; // Consume `\right` and its delimiter. if is_right_command(chars, after) { after += 6; } let right = chars.get(after).copied().unwrap_or(')'); if chars.get(after).is_some() { after += 1; } ( MathAtom::Delimited { left, right, body: Box::new(body), }, 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 sqrt_degree_is_wider_than_a_plain_root() { let font = Cmr10Metrics::default(); let plain = layout_math(&parse_math("\\sqrt{x}"), &font); let indexed = layout_math(&parse_math("\\sqrt[3]{x}"), &font); assert!(indexed.width > plain.width); assert!(indexed.height > plain.height); } #[test] fn binom_stacks_two_arguments() { let font = Cmr10Metrics::default(); let binom = layout_math(&parse_math("\\binom{n}{k}"), &font); let single = layout_math(&parse_math("n"), &font); assert!(binom.width >= single.width); assert!(binom.height > single.height); assert!(binom.depth > 0); } #[test] fn named_operators_use_upright_text_widths() { let font = Cmr10Metrics::default(); let max = layout_math(&parse_math("\\max"), &font); let single = layout_math(&parse_math("m"), &font); assert!(max.width > single.width); assert!(matches!( &parse_math("\\max"), MathAtom::Row(atoms) if matches!(&atoms[0], MathAtom::Text(text) if text == "max") )); } #[test] fn underline_adds_depth_without_changing_width() { let font = Cmr10Metrics::default(); let plain = layout_math(&parse_math("x"), &font); let underlined = layout_math(&parse_math("\\underline{x}"), &font); assert_eq!(underlined.width, plain.width); assert!(underlined.depth > plain.depth); assert_eq!(underlined.height, plain.height); } #[test] fn math_text_uses_upright_character_widths() { let font = Cmr10Metrics::default(); let atom = parse_math("\\text{PSNR}"); let MathAtom::Row(atoms) = &atom else { panic!("expected a row"); }; let MathAtom::Text(text) = &atoms[0] else { panic!("expected a text atom"); }; assert_eq!(text, "PSNR"); let text_box = layout_math(&atom, &font); let symbol = layout_math(&parse_math("P"), &font); assert!(text_box.width > symbol.width); assert!(text_box.height > 0); } #[test] fn middle_delimiter_adds_a_symbol() { let font = Cmr10Metrics::default(); let without = layout_math(&parse_math("\\left(ab\\right)"), &font); let with = layout_math(&parse_math("\\left(a\\middle|b\\right)"), &font); assert!(with.width > without.width); } #[test] fn empty_left_delimiter_has_no_width() { let font = Cmr10Metrics::default(); let dotted = layout_math(&parse_math("\\left.x\\right|"), &font); let bare = layout_math(&parse_math("x|"), &font); assert_eq!(dotted.width, bare.width); } #[test] fn accents_add_height_without_changing_width() { let font = Cmr10Metrics::default(); let plain = layout_math(&parse_math("x"), &font); let accented = layout_math(&parse_math("\\hat{x}"), &font); assert_eq!(accented.width, plain.width); assert!(accented.height > plain.height); } #[test] fn left_right_delimiters_grow_with_their_body() { let font = Cmr10Metrics::default(); let atom = parse_math("\\left(\\frac{a}{b}\\right)"); let boxed = layout_math(&atom, &font); let plain = layout_math(&parse_math("(a)"), &font); assert!(matches!(atom, MathAtom::Row(_))); assert!(boxed.height > plain.height); } #[test] fn operator_spacing_separates_binary_and_relation_atoms() { let font = Cmr10Metrics::default(); let plain = layout_math(&parse_math("xy"), &font); let binary = layout_math(&parse_math("x+y"), &font); let relation = layout_math(&parse_math("x=y"), &font); assert!(binary.width > plain.width); assert!(relation.width > binary.width); } #[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 { .. })); } }