use super::ast::*;
use super::symbols::FontStyleKind;
mod atop_geometry;
mod big_op_geometry;
mod binomial_geometry;
mod cases_columns;
mod decoration_geometry;
mod delimiter_advance;
mod delimiter_outline;
mod fraction_geometry;
mod glyph_advances;
mod hancom_decoration;
mod hancom_sum;
mod implicit_legacy;
mod integral_placement;
mod ladder_geometry;
mod left_script_geometry;
mod legacy;
mod legacy_original_geometry;
mod limit_geometry;
mod literal_text;
mod long_div_geometry;
mod matrix_geometry;
mod matrix_row_frame;
mod paren_geometry;
mod plain_matrix_geometry;
mod script_geometry;
mod source_font_advance;
mod source_font_symbol;
mod source_font_text;
mod source_glyph_runs;
mod source_greek_symbol;
mod source_italic_advance;
mod source_roman_advance;
pub(super) use source_roman_advance::measured as measured_roman_advance;
mod source_variable_style;
mod symbol_advances;
mod symbol_spacing;
mod variable_style;
pub(crate) use variable_style::is_styled_variable;
pub use super::box_types::{FontGlyphPaint, LayoutBox, LayoutKind};
pub(super) fn supports_implicit_legacy(node: &EqNode) -> bool {
implicit_legacy::supports(node)
}
#[derive(Clone, Copy)]
pub struct EqLayout {
pub font_size: f64,
dpi: f64,
hancom_cjk_advance: bool,
hancom_latin: bool,
latin_italic: bool,
hancom_math_face: bool,
hancom_eqn: bool,
legacy_equation: bool,
legacy_math_face: bool,
legacy_declared_width: Option<f64>,
math_digit_advance: Option<u16>,
variable_italic: bool,
variable_bold: bool,
source_variable_glyphs: bool,
standalone_eqalign: bool,
legacy_hft_metrics: bool,
implicit_legacy_font: bool,
}
pub(crate) const SCRIPT_SCALE: f64 = 0.7; pub(crate) const RADICAL_DEGREE_SCALE: f64 = 0.5;
const FRAC_LINE_PAD: f64 = 0.2; const FRAC_LINE_THICK: f64 = 0.04; const SQRT_PAD: f64 = 0.1; const PAREN_PAD: f64 = 0.08; pub(crate) const BIG_OP_SCALE: f64 = 1.5; pub(crate) const INTEGRAL_SCALE: f64 = 2.5;
#[derive(Clone, Copy, Debug)]
pub(crate) struct IntegralGeom {
pub width: f64,
pub top_y: f64,
pub bottom_y: f64,
pub top_hook_x: f64,
pub bottom_hook_x: f64,
}
pub(crate) fn integral_geom(fs: f64) -> IntegralGeom {
let baseline = fs * INTEGRAL_SCALE * 0.7;
let source_font_size = fs * 2.0;
IntegralGeom {
width: source_font_size * 630.0 / 1024.0,
top_y: baseline + fs * AXIS_HEIGHT - source_font_size * 820.0 / 1024.0,
bottom_y: baseline + fs * AXIS_HEIGHT + source_font_size * 202.0 / 1024.0,
top_hook_x: source_font_size * 579.0 / 1024.0,
bottom_hook_x: source_font_size * 50.0 / 1024.0,
}
}
pub(crate) const BIG_OP_TRAIL_PAD: f64 = 0.45;
const MATRIX_COL_GAP: f64 = 0.8; const MATRIX_ROW_GAP: f64 = 0.3; pub(crate) const AXIS_HEIGHT: f64 = 0.25;
const TEXT_BASELINE: f64 = 0.8;
pub(super) fn legacy_logical_frame(value: &LayoutBox, fs: f64) -> Option<(f64, f64)> {
fraction_geometry::legacy_operand_frame(value, fs)
}
impl EqLayout {
pub fn new(font_size: f64) -> Self {
Self {
font_size,
dpi: super::super::DEFAULT_DPI,
hancom_cjk_advance: false,
hancom_latin: false,
latin_italic: true,
hancom_math_face: false,
hancom_eqn: false,
legacy_equation: false,
legacy_math_face: false,
legacy_declared_width: None,
math_digit_advance: None,
variable_italic: true,
variable_bold: false,
source_variable_glyphs: true,
standalone_eqalign: false,
legacy_hft_metrics: false,
implicit_legacy_font: false,
}
}
pub(crate) fn for_equation(equation: &crate::model::control::Equation, dpi: f64) -> Self {
Self {
font_size: super::super::hwpunit_to_px(equation.font_size.max(1) as i32, dpi),
dpi,
hancom_cjk_advance: equation.font_name.eq_ignore_ascii_case("HYhwpEQ"),
hancom_latin: equation.font_name.eq_ignore_ascii_case("HYhwpEQ")
|| equation.font_name.eq_ignore_ascii_case("HancomEQN"),
latin_italic: true,
hancom_math_face: equation.font_name.eq_ignore_ascii_case("HYhwpEQ"),
hancom_eqn: equation.font_name.eq_ignore_ascii_case("HancomEQN"),
legacy_equation: legacy::matches_version(equation),
legacy_math_face: equation.uses_legacy_display()
|| equation.uses_implicit_legacy_font(),
legacy_declared_width: (equation.uses_legacy_display()
&& equation.attr & crate::model::control::EQUATION_LINE_MODE_BIT == 0
&& equation.eqedit & crate::model::control::EQUATION_LINE_MODE_BIT == 0
&& equation.common.width > 0
&& equation.common.width <= i32::MAX as u32
&& equation.common.width_criterion == crate::model::shape::SizeCriterion::Absolute)
.then(|| super::super::hwpunit_to_px(equation.common.width as i32, dpi)),
math_digit_advance: (equation.font_name.eq_ignore_ascii_case("HYhwpEQ")
|| equation.font_name.eq_ignore_ascii_case("HancomEQN"))
.then_some(512),
variable_italic: true,
variable_bold: false,
source_variable_glyphs: true,
standalone_eqalign: false,
legacy_hft_metrics: super::uses_legacy_hft_metrics(equation),
implicit_legacy_font: equation.uses_implicit_legacy_font(),
}
}
pub(super) fn legacy_flow_layout(
equation: &crate::model::control::Equation,
dpi: f64,
) -> Option<LayoutBox> {
if equation.common.size_protect || !legacy::matches_version(equation) {
return None;
}
let ast = super::parser::EqParser::for_document(super::document_script::tokenize(
&equation.script,
))
.parse();
if !legacy::supports(&ast)
|| (super::uses_legacy_hft_metrics(equation) && !legacy::compound_frame(&ast))
{
return None;
}
let intrinsic = Self::for_equation(equation, dpi).layout(&ast);
let intrinsic_width = super::super::px_to_hwpunit(intrinsic.width, dpi).max(1) as u32;
let intrinsic_height = super::super::px_to_hwpunit(intrinsic.height, dpi).max(1) as u32;
(equation.common.width < intrinsic_width || equation.common.height < intrinsic_height)
.then_some(intrinsic)
}
pub fn layout(&self, node: &EqNode) -> LayoutBox {
let implicit = self.implicit_legacy_font && implicit_legacy::supports(node);
let root = Self {
implicit_legacy_font: implicit,
legacy_math_face: self.legacy_math_face && (!self.implicit_legacy_font || implicit),
legacy_equation: self.legacy_equation
&& legacy::supports(node)
&& (!self.legacy_hft_metrics || legacy::compound_frame(node)),
standalone_eqalign: matrix_geometry::is_standalone_eqalign(node),
..*self
};
let result = root.layout_node(node, self.font_size);
if implicit {
return legacy::root(
implicit_legacy::line_frame(result, self.font_size),
self.font_size,
self.dpi,
);
}
if let Some(width) = self.legacy_declared_width {
let mut projected = root.matrix_row_box(result.clone(), self.font_size);
if super::legacy_coordinate_plane::project(node, &mut projected, width) {
return projected;
}
}
if self.legacy_hft_metrics && result.width > 0.0 {
let (height, baseline) = legacy_logical_frame(&result, self.font_size)
.unwrap_or((result.height, result.baseline));
let mut body = result;
let inset = if standalone_cjk_fraction_owns_inset(node) {
0.0
} else {
self.original_group_unit().unwrap_or(self.font_size * 0.22)
};
body.x = inset;
body.y = baseline - body.baseline;
return LayoutBox {
font_size: self.font_size,
x: 0.0,
y: 0.0,
width: body.width + inset,
height,
baseline,
kind: LayoutKind::Row(vec![body]),
};
}
if root.legacy_equation && result.height > 0.0 {
legacy::root(result, self.font_size, self.dpi)
} else if (self.hancom_math_face || self.hancom_eqn) && result.height > 0.0 {
root.matrix_row_box(result, self.font_size)
} else {
result
}
}
fn text_width(&self, text: &str, fs: f64, italic: bool) -> f64 {
if !self.legacy_hft_metrics {
return estimate_text_width(text, fs, italic);
}
text.chars()
.map(|ch| match ch {
'0'..='9' => fs * 0.5,
'=' | '+' | '-' | '%' => fs,
'×' => fs * 0.68,
_ => estimate_text_width(&ch.to_string(), fs, italic),
})
.sum()
}
fn layout_fraction_operand(&self, node: &EqNode, fs: f64) -> (LayoutBox, f64) {
let mut body = self.layout_node(node, fs);
if !self.legacy_hft_metrics || !operand_starts_cjk(node) {
return (body, 0.0);
}
let inset = fs * 0.22;
body.x = inset;
(
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: body.width + inset,
height: body.height,
baseline: body.baseline,
kind: LayoutKind::Row(vec![body]),
},
inset,
)
}
fn layout_node(&self, node: &EqNode, fs: f64) -> LayoutBox {
if self.legacy_equation {
match node {
EqNode::Text(text)
| EqNode::Number(text)
| EqNode::Symbol(text)
| EqNode::MathSymbol(text) => return legacy::text(text, fs),
EqNode::Fraction { numer, denom } => {
return legacy::fraction(
self.layout_node(numer, fs),
self.layout_node(denom, fs),
fs,
);
}
EqNode::Paren { left, right, body } => {
return legacy::parentheses(left, right, self.layout_node(body, fs), fs);
}
_ => {}
}
}
match node {
EqNode::Row(children) => self.layout_row(children, fs),
EqNode::Group(body) => {
let value = self.layout_node(body, fs);
self.original_group_frame(value, matches!(body.as_ref(), EqNode::Empty))
}
EqNode::Text(s) => self.layout_text(s, fs),
EqNode::Number(s) => self.layout_number(s, fs),
EqNode::Symbol(s) => self.layout_symbol(s, fs),
EqNode::MathSymbol(s) => self.layout_math_symbol(s, fs),
EqNode::Function(s) => self.layout_function(s, fs),
EqNode::Quoted(s) => self.layout_literal_text(s, fs),
EqNode::Fraction { numer, denom } => self.layout_fraction(numer, denom, fs),
EqNode::Atop { top, bottom } => self.layout_atop(top, bottom, fs),
EqNode::Binomial { top, bottom } => self.layout_binomial(top, bottom, fs),
EqNode::Sqrt { index, body } => self.layout_sqrt(index, body, fs),
EqNode::Superscript { base, sup } => self.layout_superscript(base, sup, fs),
EqNode::Subscript { base, sub } => self.layout_subscript(base, sub, fs),
EqNode::SubSup { base, sub, sup } => self.layout_subsup(base, sub, sup, fs),
EqNode::LeftScripts { base, sub, sup } => {
self.layout_left_scripts(base, sub.as_deref(), sup.as_deref(), fs)
}
EqNode::BigOp { symbol, sub, sup } => self.layout_big_op(symbol, sub, sup, fs),
EqNode::Limit { is_upper, sub } => self.layout_limit(*is_upper, sub, fs),
EqNode::Matrix { rows, style } => self.layout_matrix(rows, *style, fs),
EqNode::Cases { rows } => self.layout_cases(rows, fs),
EqNode::EqAlign {
rows,
alignment_marks,
} => self.layout_eqalign(rows, alignment_marks, fs),
EqNode::Rel { arrow, over, under } => self.layout_rel(arrow, over, under, fs),
EqNode::LongDiv {
divisor,
quotient,
body,
} => self.layout_long_div(divisor, quotient, body, fs),
EqNode::Pile { rows, align } => self.layout_pile(rows, *align, fs),
EqNode::Paren { left, right, body } => self.layout_paren(left, right, body, fs),
EqNode::Decoration { kind, body } => self.layout_decoration(*kind, body, fs),
EqNode::FontStyle { style, body } => self.layout_font_style(*style, body, fs),
EqNode::Color { r, g, b, body } => {
let child = self.layout_node(body, fs);
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: child.width,
height: child.height,
baseline: child.baseline,
kind: LayoutKind::Color {
rgb: [*r, *g, *b],
body: Box::new(child),
},
}
}
EqNode::Space(kind) => self.layout_space(*kind, fs),
EqNode::Newline => LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
baseline: 0.0,
kind: LayoutKind::Newline,
},
EqNode::Empty => LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
baseline: 0.0,
kind: LayoutKind::Empty,
},
}
}
fn layout_row(&self, children: &[EqNode], fs: f64) -> LayoutBox {
if self.implicit_legacy_font && children.iter().any(|node| matches!(node, EqNode::Row(_))) {
return self.layout_row(&implicit_legacy::flatten_terms(children), fs);
}
if children.iter().any(|node| matches!(node, EqNode::Newline)) {
return self.layout_newline_rows(children, fs);
}
if children.is_empty() {
return LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: 0.0,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Row(Vec::new()),
};
}
let (source_nodes, mut boxes): (Vec<&EqNode>, Vec<LayoutBox>) = children
.iter()
.zip(self.row_children(children, fs))
.filter(|(_, b)| b.width > 0.0 || matches!(b.kind, LayoutKind::Newline))
.unzip();
if boxes.is_empty() {
return LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: 0.0,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Row(Vec::new()),
};
}
let max_ascent = boxes.iter().map(|b| b.baseline).fold(0.0f64, f64::max);
let max_descent = boxes
.iter()
.map(|b| b.height - b.baseline)
.fold(0.0f64, f64::max);
let total_height = max_ascent + max_descent;
let mut x = if self.legacy_hft_metrics && !self.legacy_equation {
source_nodes
.first()
.map_or(0.0, |node| self.original_opening_inset(node))
} else {
0.0
};
for index in 0..boxes.len() {
if self.legacy_hft_metrics && !self.legacy_equation && index > 0 {
x += self
.original_group_boundary_gap(source_nodes[index - 1], source_nodes[index])
.unwrap_or_else(|| {
legacy_operator_gap(source_nodes[index - 1], source_nodes[index], fs)
});
}
let b = &mut boxes[index];
b.x = x;
b.y = max_ascent - b.baseline;
x += b.width;
}
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: x,
height: total_height,
baseline: max_ascent,
kind: LayoutKind::Row(boxes),
}
}
fn layout_text(&self, text: &str, fs: f64) -> LayoutBox {
if self.implicit_legacy_font && super::text_has_cjk(text) {
return implicit_legacy::cjk_text(text, fs);
}
if self.legacy_hft_metrics {
if let Some(layout) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::LegacyLiteral, fs, 0.0)
{
return layout;
}
}
if let Some(layout) = self.layout_hancom_glyphs(
text,
super::hancom_glyphs::Role::Variable {
italic: self.latin_italic,
},
fs,
0.0,
) {
return layout;
}
if self.hancom_math_face && text == "%" {
if let Some(result) = source_font_symbol::layout(text, fs, self.dpi) {
return result;
}
}
if self.hancom_math_face {
if let Some(result) = source_greek_symbol::literal(text, fs, self.dpi) {
return result;
}
if let Some(result) = source_font_text::layout(
text,
fs,
self.dpi,
self.variable_italic,
self.variable_bold,
self.source_variable_glyphs,
) {
return result;
}
}
let has_cjk = text.chars().any(|c| {
matches!(c,
'\u{3000}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{AC00}'..='\u{D7AF}'
)
});
let display_text =
variable_style::display_text(text, self.variable_italic, self.variable_bold);
let w = if has_cjk && self.hancom_cjk_advance {
let advance = (fs * 48.0 / self.dpi).round().max(1.0) * self.dpi / 48.0;
text.chars()
.map(|ch| {
if super::text_has_cjk(&ch.to_string()) {
advance
} else {
estimate_text_width(&ch.to_string(), fs, false)
}
})
.sum()
} else if !has_cjk {
glyph_advances::text_width(&display_text, fs)
.unwrap_or_else(|| estimate_text_width(text, fs, self.variable_italic))
} else {
self.text_width(text, fs, !has_cjk)
};
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Text(display_text),
}
}
fn layout_number(&self, text: &str, fs: f64) -> LayoutBox {
if let Some(layout) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::Number, fs, 0.0)
{
return layout;
}
let w = if self.legacy_hft_metrics {
self.text_width(text, fs, false)
} else {
text.chars()
.map(|ch| {
if ch.is_ascii_digit() {
if let Some(advance) = self.math_digit_advance {
source_font_text::logical_advance(advance, fs, self.dpi)
} else {
fs * 0.5
}
} else {
estimate_text_width(&ch.to_string(), fs, false)
}
})
.sum()
};
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Number(text.to_string()),
}
}
fn layout_symbol(&self, text: &str, fs: f64) -> LayoutBox {
if let Some(layout) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::Operator, fs, 0.0)
{
return layout;
}
if self.hancom_math_face && !self.legacy_hft_metrics {
if !self.variable_bold {
if let Some(result) =
source_font_symbol::layout_operator_outline(text, fs, self.dpi)
{
return result;
}
}
if let Some(result) = source_font_symbol::layout(text, fs, self.dpi) {
return result;
}
}
let display = if self.legacy_hft_metrics {
text
} else {
match text {
"-" => "−",
"'" => "′",
_ => text,
}
};
let source_operator = (self.hancom_math_face && !self.legacy_hft_metrics)
.then(|| source_font_symbol::operator_metrics(display, fs, self.dpi))
.flatten();
let w = if self.legacy_hft_metrics {
self.text_width(text, fs, false)
} else if self.hancom_math_face && matches!(text, "(" | ")") {
source_font_advance::paren(fs, self.dpi)
} else {
source_operator
.map(|(width, _)| width)
.unwrap_or_else(|| estimate_text_width(display, fs, false))
};
let pad = if self.legacy_hft_metrics && matches!(text, "+" | "-" | "=") {
0.0
} else if source_operator.is_some() {
0.0
} else if super::symbols::is_binary_symbol(text) || matches!(text, "=" | "<" | ">") {
fs * 0.15
} else if matches!(text, "(" | ")" | "[" | "]" | "'" | "′" | "″" | "‴" | "/") {
0.0
} else {
fs * 0.05
};
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w + pad * 2.0,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Symbol(display.to_string()),
}
}
fn layout_math_symbol(&self, text: &str, fs: f64) -> LayoutBox {
if let Some(layout) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::SmallOperator, fs, 0.0)
{
return layout;
}
if let Some(layout) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::Operator, fs, 0.0)
{
return layout;
}
if self.hancom_eqn {
if let Some(value) =
self.layout_hancom_glyphs(text, super::hancom_glyphs::Role::Greek, fs, 0.0)
{
return value;
}
}
if self.hancom_math_face && !self.legacy_math_face && !self.legacy_hft_metrics {
if let Some(result) = source_font_symbol::layout_command(text, fs, self.dpi) {
return result;
}
}
if self.hancom_math_face {
if let Some(result) = source_greek_symbol::command(text, fs, self.dpi) {
return result;
}
}
let kind = || {
if !text.is_empty() && text.chars().all(variable_style::is_greek_variable) {
LayoutKind::Text(variable_style::display_text(
text,
self.variable_italic,
self.variable_bold,
))
} else {
LayoutKind::MathSymbol(text.to_string())
}
};
if self.hancom_math_face {
if let Some(width) = source_roman_advance::measured(text, fs, self.dpi) {
return LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width,
height: fs,
baseline: fs * 0.8,
kind: kind(),
};
}
if source_font_symbol::operator_metrics(text, fs, self.dpi).is_some() {
return self.layout_symbol(text, fs);
}
if let Some(result) = source_font_symbol::layout(text, fs, self.dpi) {
return result;
}
}
if is_integral_symbol(text) {
let op_fs = fs * INTEGRAL_SCALE;
let geom = integral_geom(fs);
return LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: geom.width
+ if self.hancom_math_face {
0.0
} else {
fs * BIG_OP_TRAIL_PAD
},
height: op_fs,
baseline: op_fs * 0.7, kind: kind(),
};
}
let w = glyph_advances::text_width(text, fs)
.unwrap_or_else(|| estimate_text_width(text, fs, false));
let symbol = LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w,
height: fs,
baseline: fs * 0.8,
kind: kind(),
};
if super::symbols::is_relation_symbol(text) {
let padding = fs * 0.15;
let space = |x| LayoutBox {
font_size: fs,
x,
y: 0.0,
width: padding,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Space(padding),
};
let mut glyph = symbol;
glyph.x = padding;
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w + padding * 2.0,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Row(vec![space(0.0), glyph, space(padding + w)]),
}
} else {
symbol
}
}
fn layout_rel(
&self,
arrow: &str,
over: &EqNode,
under: &Option<Box<EqNode>>,
fs: f64,
) -> LayoutBox {
let small_fs = fs * 0.7;
let gap = fs * 0.1;
let mut arrow_box = self.layout_node(&EqNode::MathSymbol(arrow.to_string()), fs);
let mut over_box = self.layout_node(over, small_fs);
let mut under_box = under.as_ref().map(|u| self.layout_node(u, small_fs));
let max_w = arrow_box
.width
.max(over_box.width)
.max(under_box.as_ref().map(|u| u.width).unwrap_or(0.0));
arrow_box.width = max_w;
let mut y = 0.0;
over_box.x = (max_w - over_box.width) / 2.0;
over_box.y = y;
y += over_box.height + gap;
arrow_box.x = 0.0;
arrow_box.y = y;
let arrow_center_y = y + arrow_box.height / 2.0;
y += arrow_box.height + gap;
if let Some(ref mut ub) = under_box {
ub.x = (max_w - ub.width) / 2.0;
ub.y = y;
y += ub.height;
} else {
y -= gap; }
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: max_w,
height: y,
baseline: arrow_center_y,
kind: LayoutKind::Rel {
arrow: Box::new(arrow_box),
over: Box::new(over_box),
under: under_box.map(Box::new),
},
}
}
fn layout_space(&self, kind: SpaceKind, fs: f64) -> LayoutBox {
let w = match kind {
SpaceKind::Normal
if self.hancom_math_face || self.hancom_eqn || self.implicit_legacy_font =>
{
fs * 0.5
}
SpaceKind::Normal => fs * 0.33,
SpaceKind::Thin if self.hancom_math_face || self.implicit_legacy_font => {
let size = super::font_frame_metrics::base_unit_at_dpi(fs, self.dpi);
super::super::hwpunit_to_px((size / 8) as i32, self.dpi)
}
SpaceKind::Thin => fs * 0.17,
SpaceKind::Tab => fs * 1.0,
};
LayoutBox {
font_size: fs,
x: 0.0,
y: 0.0,
width: w,
height: fs,
baseline: fs * 0.8,
kind: LayoutKind::Space(w),
}
}
}
pub(crate) fn is_integral_symbol(symbol: &str) -> bool {
matches!(symbol, "∫" | "∬" | "∭" | "∮" | "∯" | "∰")
}
fn operand_starts_cjk(node: &EqNode) -> bool {
match node {
EqNode::Text(text) => text
.chars()
.next()
.is_some_and(|ch| super::text_has_cjk(&ch.to_string())),
EqNode::Row(children) => children.first().is_some_and(operand_starts_cjk),
EqNode::FontStyle { body, .. } | EqNode::Color { body, .. } => operand_starts_cjk(body),
_ => false,
}
}
fn standalone_cjk_fraction_owns_inset(node: &EqNode) -> bool {
match node {
EqNode::Fraction { numer, .. } => operand_starts_cjk(numer),
EqNode::Row(children) if children.len() == 1 => {
standalone_cjk_fraction_owns_inset(&children[0])
}
EqNode::FontStyle { body, .. } | EqNode::Color { body, .. } => {
standalone_cjk_fraction_owns_inset(body)
}
_ => false,
}
}
fn legacy_operator(node: &EqNode) -> Option<&str> {
match node {
EqNode::Symbol(symbol) | EqNode::MathSymbol(symbol)
if matches!(symbol.as_str(), "=" | "+" | "-" | "×") =>
{
Some(symbol)
}
EqNode::FontStyle { body, .. } | EqNode::Color { body, .. } => legacy_operator(body),
_ => None,
}
}
fn legacy_operator_gap(previous: &EqNode, current: &EqNode, fs: f64) -> f64 {
let before = if legacy_operator(previous).is_none() {
match legacy_operator(current) {
Some("=") => 0.14,
Some("-") => 0.11,
Some("+") => 0.10,
_ => 0.0,
}
} else {
0.0
};
let after = match legacy_operator(previous) {
Some("=") => 0.17,
Some("-") => 0.11,
Some("+") => 0.10,
_ => 0.0,
};
fs * (before + after)
}
fn legacy_delimiter_width(delimiter: &str, fs: f64) -> Option<f64> {
match delimiter {
"(" | ")" => Some(fs * 0.375),
"[" | "]" => Some(fs * 0.387),
_ => None,
}
}
pub(crate) fn estimate_text_width(text: &str, font_size: f64, italic: bool) -> f64 {
if !italic {
if let Some(width) = glyph_advances::text_width(text, font_size) {
return width;
}
}
let mut w = 0.0;
for ch in text.chars() {
let ratio = if matches!(ch, '(' | ')') {
0.389
} else if ch == '−' {
0.778
} else if ch.is_ascii() {
if ch.is_ascii_uppercase() {
0.65
} else if ch.is_ascii_lowercase() {
0.55
} else if ch.is_ascii_digit() {
0.55
} else {
0.5
}
} else {
estimate_unicode_char_width(ch)
};
w += font_size * ratio;
}
if italic {
w *= 1.05;
}
w
}
fn estimate_unicode_char_width(ch: char) -> f64 {
match ch {
'′' | '″' | '‴' | '\'' | '`' => 0.3,
'α'..='ω' | 'ϑ' | 'ϖ' => 0.55,
'Α'..='Ω' | 'ϒ' => 0.65,
'±' | '∓' | '×' | '÷' | '·' | '∘' | '†' | '‡' | '•' => 0.6,
'≠' | '≤' | '≥' | '≈' | '≡' | '≅' | '∼' | '≃' | '≍' | '≐' | '∝' | '≺' | '≻' => {
0.7
}
'∈' | '∉' | '∋' | '⊂' | '⊃' | '⊆' | '⊇' | '∀' | '∃' | '¬' | '∧' | '∨' => {
0.65
}
'⊏' | '⊐' | '⊑' | '⊒' | '⊻' | '⊢' | '⊣' | '⊨' => 0.65,
'∫' | '∬' | '∭' | '∮' | '∯' | '∰' => 0.5,
'∑' | '∏' | '∐' => 0.8,
'∪' | '∩' | '⊔' | '⊓' | '⊎' | '⋀' | '⋁' => 0.7,
'⊕' | '⊗' | '⊙' | '⊖' | '⊘' => 0.7,
'←' | '→' | '↑' | '↓' | '↔' | '↕' => 0.8,
'⇐' | '⇒' | '⇑' | '⇓' | '⇔' | '⇕' => 0.8,
'↖' | '↗' | '↙' | '↘' | '↦' | '↩' | '↪' => 0.8,
'⋯' | '…' | '⋮' | '⋱' => 0.8,
'∂' | '∅' | '∇' | '∞' | '∠' | '∡' | '∢' | '⊾' => 0.6,
'⊥' | '⊤' => 0.8,
'°' | '‰' | '‱' | '♯' => 0.5,
'ℵ' | 'ℏ' | 'ı' | 'ȷ' | 'ℓ' | '℘' | 'ℑ' | 'ℜ' | 'ℒ' | 'Å' | '℧' => 0.6,
'℃' | '℉' => 0.9,
'△' | '▽' | '○' | '◇' | '⋄' => 0.7,
'\u{3000}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{AC00}'..='\u{D7AF}' => 1.0,
_ => 0.6,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::renderer::equation::parser::EqParser;
use crate::renderer::equation::tokenizer::tokenize;
fn parse_and_layout(script: &str, font_size: f64) -> LayoutBox {
let tokens = tokenize(script);
let ast = EqParser::new(tokens).parse();
EqLayout::new(font_size).layout(&ast)
}
#[test]
fn test_simple_text() {
let lb = parse_and_layout("abc", 20.0);
assert!(lb.width > 0.0);
assert!(lb.height > 0.0);
}
#[test]
fn test_fraction_layout() {
let lb = parse_and_layout("a over b", 20.0);
assert!(lb.width > 0.0);
assert!(lb.height > 20.0); }
#[test]
fn test_big_op_trailing_pad() {
fn find_big_op(b: &LayoutBox) -> Option<&LayoutBox> {
if matches!(b.kind, LayoutKind::BigOp { .. }) {
return Some(b);
}
if let LayoutKind::Row(children) = &b.kind {
for c in children {
if let Some(f) = find_big_op(c) {
return Some(f);
}
}
}
None
}
let fs = 20.0;
let lb = parse_and_layout("sum_{n=1}^{N} b", fs);
let big = find_big_op(&lb).expect("BigOp 노드가 있어야 함");
let inner = match &big.kind {
LayoutKind::BigOp { sub, sup, .. } => {
let s = sub.as_ref().map(|b| b.x + b.width).unwrap_or(0.0);
let p = sup.as_ref().map(|b| b.x + b.width).unwrap_or(0.0);
s.max(p)
}
_ => unreachable!(),
};
assert!(
big.width - inner >= fs * BIG_OP_TRAIL_PAD * 0.9,
"BigOp trailing 간격 부재: width={} inner={}",
big.width,
inner
);
}
#[test]
fn test_superscript_layout() {
let lb = parse_and_layout("x^2", 20.0);
assert!(lb.width > 0.0);
assert!(lb.height > 0.0);
}
#[test]
fn test_superscript_tall_base_no_overshoot() {
fn find_sup(lb: &LayoutBox) -> Option<(&LayoutBox, &LayoutBox)> {
match &lb.kind {
LayoutKind::Superscript { base, sup } => Some((base, sup)),
LayoutKind::Row(ch) => ch.iter().rev().find_map(find_sup),
_ => None,
}
}
for script in ["LEFT ( {1} over {6} RIGHT )^4", "x^4"] {
let layout = parse_and_layout(script, 12.0);
let (base, sup) = find_sup(&layout).expect("본체와 위첨자 소유");
let base_baseline = base.y + base.baseline;
let sup_baseline = sup.y + sup.baseline;
assert!(
sup_baseline < base_baseline,
"위첨자 기준선은 본체보다 높아야 함: {script}"
);
assert!(
sup.x >= base.x + base.width,
"위첨자는 본체 뒤에 배치되어야 함"
);
let relative_error = (layout.baseline - base_baseline).abs() / layout.height;
assert!(
relative_error < 1e-9,
"합성 기준선은 본체 기준선을 한 번만 소비해야 함"
);
assert!(
base.y >= 0.0 && sup.y >= 0.0,
"자식 상단은 합성 프레임 안에 있어야 함"
);
assert!(base.y + base.height <= layout.height, "본체 점유 영역 보존");
assert!(sup.y + sup.height <= layout.height, "위첨자 점유 영역 보존");
}
}
#[test]
fn test_superscript_fraction_baseline() {
let lb = parse_and_layout("25^{{1} over {3}}", 14.0);
let (base_box, sup_box) = match &lb.kind {
LayoutKind::Superscript { base, sup } => (base, sup),
LayoutKind::Row(children) => {
let last = children.last().unwrap();
match &last.kind {
LayoutKind::Superscript { base, sup } => (base, sup),
_ => panic!("Expected Superscript in Row"),
}
}
_ => panic!("Expected Superscript or Row, got {:?}", lb.kind),
};
assert!(
sup_box.y <= base_box.y,
"sup.y ({}) should be <= base.y ({})",
sup_box.y,
base_box.y
);
let sup_baseline_abs = sup_box.y + sup_box.baseline;
let base_baseline_abs = base_box.y + base_box.baseline;
assert!(
sup_baseline_abs < base_baseline_abs,
"sup baseline ({}) should be above base baseline ({})",
sup_baseline_abs,
base_baseline_abs
);
}
#[test]
fn test_eq01_script() {
let lb = parse_and_layout(
"평점=입찰가격평가~배점한도 TIMES LEFT ( {최저입찰가격} over {해당입찰가격} RIGHT )",
20.0,
);
assert!(lb.width > 100.0);
assert!(lb.height > 0.0);
}
#[test]
fn test_cases_korean_no_overlap() {
let lb = parse_and_layout(
"a _{n+1} = {cases{``a _{n} -3&&LEFT ( LEFT |` a _{n} `RIGHT | 이~홀수인~경우 RIGHT )#``{1} over {2} a _{n}&&LEFT ( a _{n} =0~또는~ LEFT |` a _{n} `RIGHT | 이~짝수인~경우 RIGHT )}}",
14.67,
);
assert!(lb.width > 0.0, "CASES width should be positive");
assert!(lb.height > 0.0, "CASES height should be positive");
let top_children = match &lb.kind {
LayoutKind::Row(children) => children,
other => panic!("Top-level should be Row, got {:?}", other),
};
let cases_paren = top_children
.iter()
.find(|c| matches!(&c.kind, LayoutKind::Paren { .. }))
.expect("Should contain a Paren (CASES) element");
let cases_body = match &cases_paren.kind {
LayoutKind::Paren { body, .. } => body,
_ => unreachable!(),
};
let rows = match &cases_body.kind {
LayoutKind::Row(rows) => rows,
other => panic!("CASES body should be Row, got {:?}", other),
};
assert!(rows.len() >= 2, "CASES should have at least 2 rows");
let row1 = &rows[0];
let row2 = &rows[1];
let row1_bottom = row1.y + row1.height;
let row2_top = row2.y;
assert!(
row2_top >= row1_bottom,
"CASES rows should not overlap: row1 bottom={:.1}, row2 top={:.1}",
row1_bottom,
row2_top
);
}
#[test]
fn test_korean_text_width_not_italic() {
let korean = parse_and_layout("홀수인~경우", 20.0);
let latin = parse_and_layout("abcdef", 20.0);
assert!(
korean.width > latin.width,
"Korean text width ({:.1}) should be larger than Latin ({:.1})",
korean.width,
latin.width
);
}
}