use super::mlist::font_parts;
use super::noad::{Field, Noad, Scaled};
use crate::node::{BoxNode, Node, RuleNode};
use crate::pack::Setter;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glyph {
pub ch: char,
pub x: Scaled,
pub y: Scaled,
pub size: Scaled,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rule {
pub x: Scaled,
pub y: Scaled,
pub width: Scaled,
pub height: Scaled,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Setting {
pub width: Scaled,
pub height: Scaled,
pub depth: Scaled,
pub glyphs: Vec<Glyph>,
pub rules: Vec<Rule>,
}
pub fn flatten(b: &BoxNode, size_of_font: &dyn Fn(usize) -> Scaled) -> Setting {
let mut out = Setting {
width: b.width,
height: b.height,
depth: b.depth,
..Setting::default()
};
match b.vertical {
true => vlist(b, 0, 0, &mut out, size_of_font),
false => hlist(b, 0, 0, &mut out, size_of_font),
}
out
}
fn hlist(
b: &BoxNode,
left: Scaled,
baseline: Scaled,
out: &mut Setting,
size_of_font: &dyn Fn(usize) -> Scaled,
) {
let mut setter = Setter::new(b);
let mut x = left;
for node in &b.list {
match node {
Node::Char(c) | Node::Ligature(c) => {
out.glyphs.push(Glyph {
ch: c.character,
x,
y: baseline,
size: size_of_font(c.font),
});
x += c.width;
}
Node::Box(inner) => {
let base = baseline - inner.shift_amount;
match inner.vertical {
true => vlist(inner, x, base, out, size_of_font),
false => hlist(inner, x, base, out, size_of_font),
}
x += inner.width;
}
Node::Rule(r) => {
let (h, d) = running_vertical(r, b);
let w = match RuleNode::is_running(r.width) {
true => 0,
false => r.width,
};
if h + d > 0 && w > 0 {
out.rules.push(Rule {
x,
y: baseline - d,
width: w,
height: h + d,
});
}
x += w;
}
Node::Glue(g) => x += setter.glue(&g.spec),
Node::Kern { width, .. } | Node::Math(width) => x += width,
_ => {}
}
}
}
fn vlist(
b: &BoxNode,
left: Scaled,
baseline: Scaled,
out: &mut Setting,
size_of_font: &dyn Fn(usize) -> Scaled,
) {
let mut setter = Setter::new(b);
let mut v = baseline + b.height;
for node in &b.list {
match node {
Node::Box(inner) => {
v -= inner.height;
let x = left + inner.shift_amount;
match inner.vertical {
true => vlist(inner, x, v, out, size_of_font),
false => hlist(inner, x, v, out, size_of_font),
}
v -= inner.depth;
}
Node::Rule(r) => {
let h = match RuleNode::is_running(r.height) {
true => 0,
false => r.height,
};
let d = match RuleNode::is_running(r.depth) {
true => 0,
false => r.depth,
};
let w = match RuleNode::is_running(r.width) {
true => b.width,
false => r.width,
};
v -= h + d;
if h + d > 0 && w > 0 {
out.rules.push(Rule {
x: left,
y: v,
width: w,
height: h + d,
});
}
}
Node::Glue(g) => v -= setter.glue(&g.spec),
Node::Kern { width, .. } => v -= width,
_ => {}
}
}
}
fn running_vertical(r: &RuleNode, container: &BoxNode) -> (Scaled, Scaled) {
let h = match RuleNode::is_running(r.height) {
true => container.height,
false => r.height,
};
let d = match RuleNode::is_running(r.depth) {
true => container.depth,
false => r.depth,
};
(h, d)
}
pub fn font_size(fonts: &super::font::MathFonts, index: usize) -> Scaled {
let (fam, size) = font_parts(index);
(fonts.at(fam, size) * 65536.0).round() as Scaled
}
pub fn plain(list: &[Noad]) -> String {
let mut out = String::new();
for item in list {
match item {
Noad::Atom(a) => {
out.push_str(&plain_field(&a.nucleus));
if !a.supscr.is_empty() {
out.push_str(&script(&plain_field(&a.supscr), true));
}
if !a.subscr.is_empty() {
out.push_str(&script(&plain_field(&a.subscr), false));
}
}
Noad::Fraction(f) => {
out.push_str(&plain(&f.numerator));
out.push('/');
out.push_str(&plain(&f.denominator));
}
Noad::Radical(r) => {
if let Some(index) = &r.index {
out.push_str(&script(&plain(index), true));
}
out.push('√');
out.push_str(&plain_field(&r.nucleus.nucleus));
}
Noad::Over(a) | Noad::Under(a) | Noad::VCenter(a) => {
out.push_str(&plain_field(&a.nucleus))
}
Noad::Accent(a) => {
out.push_str(&plain_field(&a.atom.nucleus));
if let Some(mark) = combining(a.accent) {
out.push(mark);
}
if !a.atom.supscr.is_empty() {
out.push_str(&script(&plain_field(&a.atom.supscr), true));
}
if !a.atom.subscr.is_empty() {
out.push_str(&script(&plain_field(&a.atom.subscr), false));
}
}
Noad::Choice(c) => out.push_str(&plain(&c.text)),
Noad::Left(_) | Noad::Right(_) | Noad::Style(_) => {}
Noad::Glue(_) | Noad::Kern(_) | Noad::MuGlue(_) | Noad::MuKern(_) => {}
Noad::Node(_) => {}
}
}
out
}
fn combining(accent: super::noad::MathChar) -> Option<char> {
match (accent.fam, accent.character) {
(0, 0x12) => Some('\u{300}'),
(0, 0x13) => Some('\u{301}'),
(0, 0x14) => Some('\u{30C}'),
(0, 0x15) => Some('\u{306}'),
(0, 0x16) => Some('\u{304}'),
(0, 0x5E) => Some('\u{302}'),
(0, 0x5F) => Some('\u{307}'),
(0, 0x7E) => Some('\u{303}'),
(0, 0x7F) => Some('\u{308}'),
(1, 0x7E) => Some('\u{20D7}'),
(3, 0x62) => Some('\u{302}'),
(3, 0x65) => Some('\u{303}'),
_ => None,
}
}
fn plain_field(f: &Field) -> String {
match f {
Field::Empty | Field::Box(_) => String::new(),
Field::Char(c) => super::font::unicode(c.fam, c.character)
.map(String::from)
.unwrap_or_default(),
Field::Literal(c) => c.to_string(),
Field::List(l) => plain(l),
}
}
fn script(text: &str, superscript: bool) -> String {
const SUPER: &str = "⁰¹²³⁴⁵⁶⁷⁸⁹";
const SUB: &str = "₀₁₂₃₄₅₆₇₈₉";
let table: Vec<char> = match superscript {
true => SUPER.chars().collect(),
false => SUB.chars().collect(),
};
let digits: Option<String> = text
.chars()
.map(|c| c.to_digit(10).map(|d| table[d as usize]))
.collect();
match digits {
Some(s) if !s.is_empty() => s,
_ => {
let mark = match superscript {
true => '^',
false => '_',
};
format!("{mark}{text}")
}
}
}
pub fn encode(s: &Setting) -> String {
let mut out = format!("{};{};{}", s.width, s.height, s.depth);
for g in &s.glyphs {
out.push_str(&format!(";g{},{},{},{}", g.x, g.y, g.size, g.ch as u32));
}
for r in &s.rules {
out.push_str(&format!(";r{},{},{},{}", r.x, r.y, r.width, r.height));
}
out
}
pub fn decode(text: &str) -> Option<Setting> {
let mut parts = text.split(';');
let mut out = Setting {
width: parts.next()?.parse().ok()?,
height: parts.next()?.parse().ok()?,
depth: parts.next()?.parse().ok()?,
..Setting::default()
};
for part in parts {
let (kind, rest) = part.split_at(part.char_indices().nth(1)?.0);
let n: Vec<i64> = rest.split(',').filter_map(|v| v.parse().ok()).collect();
if n.len() != 4 {
return None;
}
match kind {
"g" => out.glyphs.push(Glyph {
x: n[0],
y: n[1],
size: n[2],
ch: char::from_u32(n[3] as u32)?,
}),
"r" => out.rules.push(Rule {
x: n[0],
y: n[1],
width: n[2],
height: n[3],
}),
_ => return None,
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_setting_survives_the_round_trip_through_a_marker() {
let s = Setting {
width: 123_456,
height: -7,
depth: 65536,
glyphs: vec![Glyph {
ch: '∑',
x: 10,
y: -20,
size: 655_360,
}],
rules: vec![Rule {
x: 1,
y: 2,
width: 3,
height: 4,
}],
};
assert_eq!(decode(&encode(&s)).as_ref(), Some(&s));
}
#[test]
fn an_encoded_setting_holds_no_control_character_and_no_space() {
let s = Setting {
width: -1,
height: 0,
depth: 0,
glyphs: vec![Glyph {
ch: 'x',
x: -5,
y: 0,
size: 1,
}],
rules: Vec::new(),
};
let text = encode(&s);
assert!(
!text.chars().any(|c| c.is_control() || c == ' '),
"the spec carries {text:?}"
);
}
}