use super::ast::MatrixStyle;
use super::layout::*;
use super::symbols::{DecoKind, FontStyleKind};
pub const DEFAULT_EQUATION_FONT_FAMILY_ATTR: &str =
"font-family=\"'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif\"";
const EQ_FONT_FAMILY: &str = " font-family=\"'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif\"";
pub fn render_equation_svg(layout: &LayoutBox, color: &str, base_font_size: f64) -> String {
let mut svg = String::new();
render_box(
&mut svg,
layout,
0.0,
0.0,
color,
base_font_size,
true,
false,
);
svg
}
fn render_box(
svg: &mut String,
lb: &LayoutBox,
parent_x: f64,
parent_y: f64,
color: &str,
fs: f64,
italic: bool,
bold: bool,
) {
let fs = if lb.font_size > 0.0 { lb.font_size } else { fs };
let x = parent_x + lb.x;
let y = parent_y + lb.y;
match &lb.kind {
LayoutKind::HancomGlyphs(run) => {
for ((glyph, offset), shear) in run.glyphs.chars().zip(&run.positions).zip(&run.shears)
{
svg.push_str(&format!(
"<text x=\"0\" y=\"0\" transform=\"matrix(1 0 {} 1 {:.2} {:.2})\" font-size=\"{:.2}\" fill=\"{}\" font-family=\"{}\">{}</text>\n",
-shear, x + offset, y + lb.baseline + run.baseline_shift, fs, color,
run.font_family, escape_xml(&glyph.to_string()),
));
}
}
LayoutKind::Row(children) => {
for child in children {
render_box(svg, child, x, y, color, fs, italic, bold);
}
}
LayoutKind::Text(text) => {
let text_x = x;
let text_y = y + lb.baseline;
let esc = escape_xml(text);
let fi = fs;
let has_cjk = super::text_has_cjk(text);
let styled = is_styled_variable(text);
let italic_attr = if !has_cjk && italic && !styled {
" font-style=\"italic\""
} else {
""
};
let weight_attr = if bold && !styled {
" font-weight=\"bold\""
} else {
""
};
if has_cjk && (lb.width - estimate_text_width(text, fi, false)).abs() > 0.01 {
for (ch, offset) in super::positioned_cjk_text(text, fi, lb.width) {
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{} font-family=\"'Haansoft Batang', '한컴바탕', 'Batang', '바탕', serif\">{}</text>\n",
text_x + offset, text_y, fi, color, weight_attr, escape_xml(&ch.to_string()),
));
}
return;
}
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}{}{}>{}</text>\n",
text_x,
text_y,
fi,
color,
italic_attr,
weight_attr,
if has_cjk {
" font-family=\"'Haansoft Batang', '한컴바탕', 'Batang', '바탕', serif\""
} else {
EQ_FONT_FAMILY
},
esc,
));
}
LayoutKind::Number(text) => {
let text_x = x;
let text_y = y + lb.baseline;
let esc = escape_xml(text);
let fi = fs;
let style_attr = if bold { " font-weight=\"bold\"" } else { "" };
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}{}>{}</text>\n",
text_x, text_y, fi, color, style_attr, EQ_FONT_FAMILY, esc,
));
}
LayoutKind::Symbol(text) => {
let text_x = x + lb.width / 2.0;
let text_y = y + lb.baseline;
let esc = escape_xml(text);
let fi = fs;
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\"{}>{}</text>\n",
text_x, text_y, fi, color, EQ_FONT_FAMILY, esc,
));
}
LayoutKind::FontGlyph {
text,
font_family,
outline,
paint,
} => {
if let Some(commands) = outline {
let scale_x = paint.map_or(1.0, |p| p.scale_x);
let stroke = paint.map_or_else(String::new, |p| format!(
" stroke=\"{color}\" stroke-width=\"{:.6}\" stroke-linejoin=\"miter\" stroke-miterlimit=\"10\"",
p.stroke_width,
));
svg.push_str(&format!(
"<path d=\"{}\" transform=\"translate({x:.4},{y:.4}) scale({scale_x:.8},1)\" fill=\"{color}\"{stroke}/>\n",
super::multiplication_outline::path_data(commands),
));
return;
}
let scale_x = paint.map_or(1.0, |p| p.scale_x);
if scale_x != 1.0 {
svg.push_str(&format!(
"<text x=\"0\" y=\"0\" transform=\"translate({:.4},{:.4}) scale({scale_x:.8},1)\" font-size=\"{fs:.4}\" fill=\"{color}\" font-family=\"{}\">{}</text>\n",
x, y + lb.baseline, escape_xml(font_family), escape_xml(text),
));
} else {
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" font-family=\"{}\">{}</text>\n",
x, y + lb.baseline, fs, color, escape_xml(font_family), escape_xml(text),
));
}
}
LayoutKind::MathSymbol(text) => {
if super::layout::is_integral_symbol(text) {
svg.push_str(&integral_path(x, y, fs, color));
} else {
let text_x = x;
let text_y = y + lb.baseline;
let esc = escape_xml(text);
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
text_x, text_y, fs, color, EQ_FONT_FAMILY, esc,
));
}
}
LayoutKind::Function(name) => {
let text_x = x;
let text_y = y + lb.baseline;
let esc = escape_xml(name);
let fi = fs;
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
text_x, text_y, fi, color, EQ_FONT_FAMILY, esc,
));
}
LayoutKind::Fraction {
numer,
denom,
axis_height,
rule_thickness,
rule_start,
rule_end,
} => {
render_box(svg, numer, x, y, color, fs, italic, bold);
let line_y = y + lb.baseline - axis_height;
let line_thick = rule_thickness;
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
x + rule_start, line_y,
x + rule_end, line_y,
color, line_thick,
));
render_box(svg, denom, x, y, color, fs, italic, bold);
}
LayoutKind::Atop { top, bottom } => {
render_box(svg, top, x, y, color, fs, italic, bold);
render_box(svg, bottom, x, y, color, fs, italic, bold);
}
LayoutKind::Sqrt { index, body } => {
let geometry = super::radical_outline::geometry(lb, body, fs);
svg.push_str(&format!(
"<path d=\"{}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n",
super::multiplication_outline::path_data(&geometry.outline),
));
svg.push_str(&format!(
"<line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"{color}\" stroke-width=\"{:.4}\"/>\n",
x + geometry.bar_start.0, y + geometry.bar_start.1,
x + geometry.bar_end.0, y + geometry.bar_end.1,
geometry.rule_thickness,
));
if let Some(idx) = index {
render_box(
svg,
idx,
x,
y,
color,
fs * super::layout::RADICAL_DEGREE_SCALE,
false,
false,
);
}
render_box(svg, body, x, y, color, fs, italic, bold);
}
LayoutKind::Superscript { base, sup } => {
render_box(svg, base, x, y, color, fs, italic, bold);
render_box(
svg,
sup,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
italic,
bold,
);
}
LayoutKind::Subscript { base, sub } => {
render_box(svg, base, x, y, color, fs, italic, bold);
render_box(
svg,
sub,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
italic,
bold,
);
}
LayoutKind::SubSup { base, sub, sup } => {
render_box(svg, base, x, y, color, fs, italic, bold);
render_box(
svg,
sub,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
italic,
bold,
);
render_box(
svg,
sup,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
italic,
bold,
);
}
LayoutKind::BigOp {
symbol,
sub,
sup,
op_font_size,
op_x,
op_y,
op_baseline,
..
} => {
let is_integral = super::layout::is_integral_symbol(symbol);
let op_fs = *op_font_size;
let esc = escape_xml(symbol);
if is_integral {
svg.push_str(&integral_path(x + op_x, y + op_y, fs, color));
} else {
let op_x = x + op_x;
let op_y = y + op_baseline;
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
op_x, op_y, op_fs, color, EQ_FONT_FAMILY, esc,
));
}
if let Some(sup_box) = sup {
render_box(
svg,
sup_box,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
false,
false,
);
}
if let Some(sub_box) = sub {
render_box(
svg,
sub_box,
x,
y,
color,
fs * super::layout::SCRIPT_SCALE,
false,
false,
);
}
}
LayoutKind::Limit {
is_upper,
name,
name_font_size,
sub_font_size,
sub,
} => {
if let Some(name) = name {
render_box(svg, name, x, y, color, name.height, false, false);
} else {
let name = if *is_upper { "Lim" } else { "lim" };
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
x,
y + lb.baseline,
name_font_size,
color,
EQ_FONT_FAMILY,
name,
));
}
if let Some(sub_box) = sub {
render_box(svg, sub_box, x, y, color, *sub_font_size, false, false);
}
}
LayoutKind::Matrix { cells, style } => {
let bracket_chars = match style {
MatrixStyle::Paren => ("(", ")"),
MatrixStyle::Bracket => ("[", "]"),
MatrixStyle::Vert => ("|", "|"),
MatrixStyle::Plain | MatrixStyle::Ladder | MatrixStyle::ShortLadder => ("", ""),
};
if !bracket_chars.0.is_empty() {
draw_stretch_bracket(svg, bracket_chars.0, x, y, fs * 0.3, lb.height, color, fs);
draw_stretch_bracket(
svg,
bracket_chars.1,
x + lb.width - fs * 0.3,
y,
fs * 0.3,
lb.height,
color,
fs,
);
}
for row in cells {
for cell in row {
render_box(svg, cell, x, y, color, fs, italic, bold);
}
}
}
LayoutKind::Rel { arrow, over, under } => {
render_box(svg, over, x, y, color, fs, italic, bold);
render_box(svg, arrow, x, y, color, fs, italic, bold);
if let Some(u) = under {
render_box(svg, u, x, y, color, fs, italic, bold);
}
}
LayoutKind::EqAlign { rows } => {
for (left, right) in rows {
render_box(svg, left, x, y, color, fs, italic, bold);
render_box(svg, right, x, y, color, fs, italic, bold);
}
}
LayoutKind::Paren {
left,
right,
left_width,
right_width,
delimiter_height,
glyph_delimiters,
left_outline,
right_outline,
body,
} => {
let use_glyph = *glyph_delimiters;
if !left.is_empty() {
if let Some(commands) = left_outline {
let path = super::multiplication_outline::path_data(commands);
svg.push_str(&format!("<path d=\"{path}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n"));
} else if use_glyph && (left == "(" || left == ")") {
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
x, y + lb.baseline, fs, color, EQ_FONT_FAMILY, escape_xml(left),
));
} else {
draw_stretch_bracket(
svg,
left,
x,
y,
*left_width,
*delimiter_height,
color,
fs,
);
}
}
render_box(svg, body, x, y, color, fs, italic, bold);
if !right.is_empty() {
let right_x = x + lb.width - right_width;
if let Some(commands) = right_outline {
let path = super::multiplication_outline::path_data(commands);
svg.push_str(&format!("<path d=\"{path}\" transform=\"translate({right_x:.4},{y:.4})\" fill=\"{color}\"/>\n"));
} else if use_glyph && (right == "(" || right == ")") {
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
right_x, y + lb.baseline, fs, color, EQ_FONT_FAMILY, escape_xml(right),
));
} else {
draw_stretch_bracket(
svg,
right,
right_x,
y,
*right_width,
*delimiter_height,
color,
fs,
);
}
}
}
LayoutKind::Decoration {
kind,
body,
negation,
outline,
} => {
render_box(svg, body, x, y, color, fs, italic, bold);
if let Some(commands) = outline {
svg.push_str(&format!(
"<path d=\"{}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n",
super::multiplication_outline::path_data(commands),
));
} else if *kind == DecoKind::StrikeThrough {
let g = negation
.clone()
.unwrap_or_else(|| super::negation_geometry::geometry(body));
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
x + g.start.0, y + g.start.1, x + g.end.0, y + g.end.1, color, g.thickness,
));
} else if *kind == DecoKind::Box {
svg.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
x, y, lb.width, lb.height, color, fs * 0.03,
));
} else {
let deco_y = y + fs * 0.05;
let mid_x = x + body.x + body.width / 2.0;
draw_decoration(svg, *kind, mid_x, deco_y, body.width, color, fs);
}
}
LayoutKind::Color { rgb, body } => {
let body_color = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]);
render_box(svg, body, x, y, &body_color, fs, italic, bold);
}
LayoutKind::FontStyle { style, body } => {
let (new_italic, new_bold) = match style {
FontStyleKind::Roman | FontStyleKind::SansSerif | FontStyleKind::Monospace => {
(false, false)
}
FontStyleKind::Italic => (true, bold),
FontStyleKind::Bold => (italic, true),
FontStyleKind::Blackboard => (false, true),
FontStyleKind::Calligraphy | FontStyleKind::Fraktur => (false, false),
};
render_box(svg, body, x, y, color, fs, new_italic, new_bold);
}
LayoutKind::Space(_) | LayoutKind::Newline | LayoutKind::Empty => {}
}
}
pub(crate) fn integral_path_data(x: f64, y: f64, fs: f64) -> String {
use super::integral_outline::{commands, Command};
use std::fmt::Write;
let mut path = String::new();
for command in commands(x, y, fs) {
match command {
Command::Move((x, y)) => {
let _ = write!(path, "M{x:.4},{y:.4}");
}
Command::Line((x, y)) => {
let _ = write!(path, "L{x:.4},{y:.4}");
}
Command::Cubic([(a, b), (c, d), (e, f)]) => {
let _ = write!(path, "C{a:.4},{b:.4} {c:.4},{d:.4} {e:.4},{f:.4}");
}
Command::Close => path.push('Z'),
}
}
path
}
fn integral_path(x: f64, y: f64, fs: f64, color: &str) -> String {
format!(
"<path d=\"{}\" fill=\"{}\"/>\n",
integral_path_data(x, y, fs),
color
)
}
fn font_size_from_box(lb: &LayoutBox, base_fs: f64) -> f64 {
if lb.height > 0.0 {
lb.height
} else {
base_fs
}
}
fn draw_stretch_bracket(
svg: &mut String,
bracket: &str,
x: f64,
y: f64,
w: f64,
h: f64,
color: &str,
fs: f64,
) {
if matches!(bracket, "{" | "}") {
let commands = super::brace_stretch::commands(x, y, w, h, fs, bracket == "}");
svg.push_str(&format!(
"<path d=\"{}\" fill=\"{}\"/>\n",
super::multiplication_outline::path_data(&commands),
color
));
return;
}
let mid_x = x + w / 2.0;
let stroke_w = if matches!(bracket, "(" | ")") {
(fs * 0.042).max(0.48)
} else {
fs * 0.04
};
match bracket {
"(" => {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} C{:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\" stroke-linecap=\"round\"/>\n",
x + w * 0.9, y,
x + w * 0.05, y + h * 0.18,
x + w * 0.05, y + h * 0.82,
x + w * 0.9, y + h,
color, stroke_w,
));
}
")" => {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} C{:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\" stroke-linecap=\"round\"/>\n",
x + w * 0.1, y,
x + w * 0.95, y + h * 0.18,
x + w * 0.95, y + h * 0.82,
x + w * 0.1, y + h,
color, stroke_w,
));
}
"[" => {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x + w * 0.2, y,
mid_x - w * 0.2, y,
mid_x - w * 0.2, y + h,
mid_x + w * 0.2, y + h,
color, stroke_w,
));
}
"]" => {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - w * 0.2, y,
mid_x + w * 0.2, y,
mid_x + w * 0.2, y + h,
mid_x - w * 0.2, y + h,
color, stroke_w,
));
}
"|" => {
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x, y, mid_x, y + h, color, stroke_w,
));
}
_ => {
let esc = escape_xml(bracket);
svg.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\"{}>{}</text>\n",
mid_x, y + h * 0.7, h, color, EQ_FONT_FAMILY, esc,
));
}
}
}
fn draw_decoration(
svg: &mut String,
kind: DecoKind,
mid_x: f64,
y: f64,
width: f64,
color: &str,
fs: f64,
) {
let stroke_w = fs * 0.03;
let half_w = width / 2.0;
match kind {
DecoKind::Hat => {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w * 0.6, y + fs * 0.15,
mid_x, y,
mid_x + half_w * 0.6, y + fs * 0.15,
color, stroke_w,
));
}
DecoKind::Bar | DecoKind::Overline => {
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w, y + fs * 0.05,
mid_x + half_w, y + fs * 0.05,
color, stroke_w,
));
}
DecoKind::Vec | DecoKind::Dyad => {
let arrow_y = y + fs * 0.05;
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w, arrow_y,
mid_x + half_w, arrow_y,
color, stroke_w,
));
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x + half_w - fs * 0.1, arrow_y - fs * 0.06,
mid_x + half_w, arrow_y,
mid_x + half_w - fs * 0.1, arrow_y + fs * 0.06,
color, stroke_w,
));
if kind == DecoKind::Dyad {
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w + fs * 0.1, arrow_y - fs * 0.06,
mid_x - half_w, arrow_y,
mid_x - half_w + fs * 0.1, arrow_y + fs * 0.06,
color, stroke_w,
));
}
}
DecoKind::Tilde => {
let ty = y + fs * 0.08;
svg.push_str(&format!(
"<path d=\"M{:.2},{:.2} Q{:.2},{:.2} {:.2},{:.2} Q{:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w * 0.6, ty,
mid_x - half_w * 0.2, ty - fs * 0.08,
mid_x, ty,
mid_x + half_w * 0.2, ty + fs * 0.08,
mid_x + half_w * 0.6, ty,
color, stroke_w,
));
}
DecoKind::Dot => {
svg.push_str(&format!(
"<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
mid_x,
y + fs * 0.06,
fs * 0.03,
color,
));
}
DecoKind::DDot => {
let gap = fs * 0.1;
svg.push_str(&format!(
"<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
mid_x - gap,
y + fs * 0.06,
fs * 0.03,
color,
));
svg.push_str(&format!(
"<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
mid_x + gap,
y + fs * 0.06,
fs * 0.03,
color,
));
}
DecoKind::Underline | DecoKind::Under => {
let uy = y + fs * 1.1;
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w, uy, mid_x + half_w, uy, color, stroke_w,
));
}
_ => {
svg.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
mid_x - half_w * 0.5, y + fs * 0.1,
mid_x + half_w * 0.5, y + fs * 0.1,
color, stroke_w,
));
}
}
}
fn escape_xml(text: &str) -> String {
let mut result = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'&' => result.push_str("&"),
'<' => result.push_str("<"),
'>' => result.push_str(">"),
'"' => result.push_str("""),
'\'' => result.push_str("'"),
'\u{09}' | '\u{0A}' | '\u{0D}' => result.push(ch),
'\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
result.push(ch)
}
_ => {} }
}
result
}
pub fn eq_color_to_svg(color: u32) -> String {
let r = color & 0xFF;
let g = (color >> 8) & 0xFF;
let b = (color >> 16) & 0xFF;
format!("#{:02x}{:02x}{:02x}", r, g, b)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::renderer::equation::layout::EqLayout;
use crate::renderer::equation::parser::EqParser;
use crate::renderer::equation::tokenizer::tokenize;
fn render_eq(script: &str) -> String {
let tokens = tokenize(script);
let ast = EqParser::new(tokens).parse();
let layout = EqLayout::new(20.0).layout(&ast);
render_equation_svg(&layout, "#000000", 20.0)
}
fn rendered_text(svg: &str) -> String {
let wrapped = format!("<svg>{svg}</svg>");
let document = roxmltree::Document::parse(&wrapped).expect("유효한 수식 SVG");
document
.descendants()
.filter(|node| node.has_tag_name("text"))
.filter_map(|node| node.text())
.collect()
}
#[test]
fn escape_xml_drops_xml_invalid_control_chars() {
assert_eq!(escape_xml("a\u{03}b"), "ab");
for c in ['\u{00}', '\u{08}', '\u{0B}', '\u{0C}', '\u{0E}', '\u{1F}'] {
assert_eq!(
escape_xml(&format!("x{c}y")),
"xy",
"control {:#04x}",
c as u32
);
}
assert_eq!(escape_xml("a\u{FFFE}\u{FFFF}b"), "ab");
assert_eq!(escape_xml("a\tb\nc\rd"), "a\tb\nc\rd");
assert_eq!(escape_xml("<a & b>\"'"), "<a & b>"'");
}
#[test]
fn test_simple_text_svg() {
let svg = render_eq("abc");
assert!(svg.contains("<text"));
assert_eq!(
rendered_text(&svg),
"𝑎𝑏𝑐",
"변수 내용·순서·이탤릭 글리프 보존"
);
}
#[test]
fn test_fraction_svg() {
let svg = render_eq("a over b");
assert!(svg.contains("<text")); assert!(svg.contains("<line")); }
#[test]
fn test_atop_svg_has_no_fraction_line() {
let svg = render_eq("a atop b");
assert!(svg.contains("<text"));
assert!(!svg.contains("<line"));
let y_values: Vec<&str> = svg
.lines()
.filter_map(|line| line.split(" y=\"").nth(1))
.filter_map(|rest| rest.split('"').next())
.collect();
assert_eq!(
y_values.len(),
2,
"ATOP은 위/아래 텍스트 2개를 렌더링해야 함: {}",
svg
);
assert_ne!(
y_values[0], y_values[1],
"ATOP은 두 항을 세로로 배치해야 함: {}",
svg
);
}
#[test]
fn test_paren_svg() {
let svg = render_eq("LEFT ( a RIGHT )");
assert!(svg.contains("<text")); assert!(!svg.contains("<path")); }
#[test]
fn test_paren_stretch_svg() {
let svg = render_eq("LEFT ( a over b RIGHT )");
assert!(svg.contains("<path")); assert!(svg.contains(" C")); assert!(svg.contains("stroke-linecap=\"round\""));
assert!(svg.contains("<line")); }
#[test]
fn test_issue_1139_integral_left_right_parens_are_curved() {
let svg = render_eq(" int _{0} ^{pi } {} x`cos LEFT ( {pi } over {2} -x RIGHT ) dx");
assert!(
!svg.contains(">∫<"),
"적분 기호는 path 로 렌더되어야 함(text ∫ 아님): {}",
svg
);
assert!(
svg.contains("<path"),
"적분 기호가 path 로 렌더되어야 함: {}",
svg
);
assert!(svg.contains(">cos<"), "cos 함수가 렌더링되어야 함: {}", svg);
assert!(
rendered_text(&svg).contains('𝜋'),
"pi 명령의 이탤릭 수학 글리프가 보존되어야 함: {}",
svg
);
assert!(
svg.contains(" C"),
"큰 둥근 괄호는 cubic path여야 함: {}",
svg
);
assert!(
!svg.contains(">LEFT<"),
"LEFT 명령이 문자로 새면 안 됨: {}",
svg
);
assert!(
!svg.contains(">RIGHT<"),
"RIGHT 명령이 문자로 새면 안 됨: {}",
svg
);
}
#[test]
fn test_eq01_svg() {
let svg = render_eq(
"평점=입찰가격평가~배점한도 TIMES LEFT ( {최저입찰가격} over {해당입찰가격} RIGHT )",
);
assert!(svg.contains("평점"));
assert!(svg.contains("×")); assert!(svg.contains("<line")); assert!(svg.contains("<path")); }
#[test]
fn test_default_text_is_italic() {
let svg = render_eq("K");
assert!(rendered_text(&svg) == "𝐾", "기본 변수는 italic: {}", svg);
}
#[test]
fn test_rm_disables_italic() {
let svg = render_eq("rm K");
assert!(
!svg.contains("font-style=\"italic\""),
"rm 적용 시 italic 없음: {}",
svg
);
assert!(svg.contains(">K<"));
}
#[test]
fn test_rm_prefix_form_disables_italic() {
let svg = render_eq("rmK");
assert!(
!svg.contains("font-style=\"italic\""),
"rmK 적용 시 italic 없음: {}",
svg
);
assert!(svg.contains(">K<"));
assert!(!svg.contains(">rmK<"));
}
#[test]
fn test_rm_compound_chemical_symbol() {
let svg = render_eq("rmCa");
assert!(!svg.contains("font-style=\"italic\""));
assert!(svg.contains(">Ca<"));
}
#[test]
fn test_it_keeps_italic() {
let svg = render_eq("it K");
assert_eq!(rendered_text(&svg), "𝐾");
}
#[test]
fn test_cjk_never_italic() {
let svg = render_eq("평점");
assert!(
!svg.contains("font-style=\"italic\""),
"CJK는 italic 미적용: {}",
svg
);
assert!(svg.contains("평점"));
}
}