use super::mlist::font_parts;
use super::noad::{Atom, 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();
plain_into(&mut out, list);
out
}
pub fn plain_into(out: &mut String, list: &[Noad]) {
for item in list {
match item {
Noad::Atom(a) => {
field_into(out, &a.nucleus);
scripts_into(out, a);
}
Noad::Fraction(f) => {
plain_into(out, &f.numerator);
out.push('/');
plain_into(out, &f.denominator);
}
Noad::Radical(r) => {
if let Some(index) = &r.index {
script_into(out, true, |out| plain_into(out, index));
}
out.push('√');
field_into(out, &r.nucleus.nucleus);
}
Noad::Over(a) | Noad::Under(a) | Noad::VCenter(a) => field_into(out, &a.nucleus),
Noad::Accent(a) => {
field_into(out, &a.atom.nucleus);
if let Some(mark) = combining(a.accent) {
out.push(mark);
}
scripts_into(out, &a.atom);
}
Noad::Choice(c) => plain_into(out, &c.text),
Noad::Left(_) | Noad::Right(_) | Noad::Style(_) => {}
Noad::Glue(_) | Noad::Kern(_) | Noad::MuGlue(_) | Noad::MuKern(_) => {}
Noad::Node(_) => {}
}
}
}
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 field_into(out: &mut String, f: &Field) {
match f {
Field::Empty | Field::Box(_) => {}
Field::Char(c) => out.extend(super::font::unicode(c.fam, c.character)),
Field::Literal(c) => out.push(*c),
Field::List(l) => plain_into(out, l),
}
}
fn scripts_into(out: &mut String, a: &Atom) {
if !a.supscr.is_empty() {
script_into(out, true, |out| field_into(out, &a.supscr));
}
if !a.subscr.is_empty() {
script_into(out, false, |out| field_into(out, &a.subscr));
}
}
fn script_into(out: &mut String, superscript: bool, spell: impl FnOnce(&mut String)) {
const SUPER: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
const SUB: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
let start = out.len();
spell(out);
let end = out.len();
let digits = end > start && out.as_bytes()[start..].iter().all(u8::is_ascii_digit);
if !digits {
let mark = match superscript {
true => '^',
false => '_',
};
out.insert(start, mark);
return;
}
let table = match superscript {
true => &SUPER,
false => &SUB,
};
for at in start..end {
let digit = out.as_bytes()[at] - b'0';
out.push(table[usize::from(digit)]);
}
out.replace_range(start..end, "");
}
pub fn encode(s: &Setting) -> String {
let mut out = String::with_capacity(24 + 32 * (s.glyphs.len() + s.rules.len()));
push_numbers(&mut out, "", &[s.width, s.height, s.depth], ';');
for g in &s.glyphs {
let ch = Scaled::from(u32::from(g.ch));
push_numbers(&mut out, ";g", &[g.x, g.y, g.size, ch], ',');
}
for r in &s.rules {
push_numbers(&mut out, ";r", &[r.x, r.y, r.width, r.height], ',');
}
out
}
fn push_numbers(out: &mut String, lead: &str, numbers: &[Scaled], between: char) {
out.push_str(lead);
for (at, n) in numbers.iter().enumerate() {
if at > 0 {
out.push(between);
}
push_decimal(out, *n);
}
}
fn push_decimal(out: &mut String, n: Scaled) {
if n < 0 {
out.push('-');
}
let mut digits = [0u8; 20];
let mut at = digits.len();
let mut rest = n.unsigned_abs();
loop {
at -= 1;
digits[at] = b'0' + (rest % 10) as u8;
rest /= 10;
if rest == 0 {
break;
}
}
out.extend(digits[at..].iter().map(|&d| char::from(d)));
}
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 a_number_is_spelled_as_display_spells_it() {
let mut values = vec![
0,
1,
-1,
9,
10,
-10,
65536,
-65536,
Scaled::MAX,
Scaled::MIN,
];
let mut power: Scaled = 1;
while let Some(next) = power.checked_mul(10) {
values.extend([power - 1, power, -power, -(power - 1)]);
power = next;
}
for n in values {
let mut spelled = String::new();
push_decimal(&mut spelled, n);
assert_eq!(spelled, n.to_string());
}
}
#[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:?}"
);
}
}