Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
1514 lines
50 KiB
Rust
1514 lines
50 KiB
Rust
use crate::math_expr::{
|
|
MathAlignment, MathAlignmentBaseline, MathCellStyle, MathColumnAlignment,
|
|
MathDelimiterSettings, MathExpr, MathRowSpacing, MathSpacingSettings,
|
|
};
|
|
use crate::math_glyph::MathKernCorner;
|
|
use crate::math_list::{
|
|
MathBoundary, MathListContext, child_context, math_style_command, normalized_classes,
|
|
};
|
|
use crate::{MathClass, MathStyle};
|
|
|
|
/// Computes XeTeX's requested height for a delimiter from its axis extents.
|
|
pub fn delimiter_target_height(
|
|
extent_above_axis: f64,
|
|
extent_below_axis: f64,
|
|
settings: MathDelimiterSettings,
|
|
) -> f64 {
|
|
const TEX_POINTS_PER_INCH: f64 = 72.27;
|
|
|
|
let axis_distance = extent_above_axis.max(extent_below_axis);
|
|
let factor_target = axis_distance * f64::from(settings.factor) / 500.0;
|
|
let shortfall_mm = f64::from(settings.shortfall.0) / 65_536.0 * 25.4 / TEX_POINTS_PER_INCH;
|
|
let shortfall_target = axis_distance * 2.0 - shortfall_mm;
|
|
factor_target.max(shortfall_target)
|
|
}
|
|
|
|
/// Places a delimiter glyph vertically against the math axis and baseline.
|
|
pub fn delimiter_top_from_baseline(baseline: f64, axis_height: f64, delimiter_height: f64) -> f64 {
|
|
baseline - axis_height - delimiter_height / 2.0
|
|
}
|
|
|
|
/// The dimensions of a measured delimiter glyph.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathDelimiterDimensions {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
}
|
|
|
|
/// Inputs for a body enclosed by left and right delimiters.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathDelimitedLayoutInput {
|
|
pub body: MathBoxDimensions,
|
|
pub axis_height: f64,
|
|
pub left: Option<MathDelimiterDimensions>,
|
|
pub right: Option<MathDelimiterDimensions>,
|
|
}
|
|
|
|
/// Geometry for a body enclosed by left and right delimiters.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathDelimitedLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub left_x: f64,
|
|
pub left_y: Option<f64>,
|
|
pub body_x: f64,
|
|
pub body_y: f64,
|
|
pub right_x: f64,
|
|
pub right_y: Option<f64>,
|
|
}
|
|
|
|
/// A point in a math box, in the caller's chosen coordinate unit.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathLayoutPosition {
|
|
pub x: f64,
|
|
pub y: f64,
|
|
}
|
|
|
|
/// TeX state and neighboring classes needed to lay out one math-list item.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathSequenceItemPlan {
|
|
pub boundary: MathBoundary,
|
|
pub child_context: MathListContext,
|
|
pub math_style: MathStyle,
|
|
pub spacing: MathSpacingSettings,
|
|
pub is_metadata: bool,
|
|
}
|
|
|
|
/// A measured child paired with its engine-computed math-list state.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathSequenceChildLayout {
|
|
pub dimensions: MathBoxDimensions,
|
|
pub plan: MathSequenceItemPlan,
|
|
}
|
|
|
|
/// Dimensions and child placements for a horizontal math sequence.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathSequenceLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
/// Positions align with the input children; metadata items have no position.
|
|
pub child_positions: Vec<Option<MathLayoutPosition>>,
|
|
}
|
|
|
|
/// Resolve style, spacing settings, class boundaries, and child contexts for a
|
|
/// math sequence before the font backend measures its items.
|
|
pub fn plan_math_sequence(
|
|
items: &[MathExpr],
|
|
math_style: MathStyle,
|
|
spacing: MathSpacingSettings,
|
|
list_context: MathListContext,
|
|
) -> Vec<MathSequenceItemPlan> {
|
|
let classes = normalized_classes(items, math_style, list_context);
|
|
let mut current_math_style = math_style;
|
|
let mut current_spacing = spacing;
|
|
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, item)| {
|
|
let style_command = math_style_command(item);
|
|
if let Some(command) = style_command {
|
|
current_math_style = MathStyle::from_command(command);
|
|
}
|
|
if let MathExpr::MathSpacingChange(settings) = item {
|
|
current_spacing = *settings;
|
|
}
|
|
|
|
MathSequenceItemPlan {
|
|
boundary: classes[index],
|
|
child_context: child_context(&classes, index, list_context),
|
|
math_style: current_math_style,
|
|
spacing: current_spacing,
|
|
is_metadata: style_command.is_some()
|
|
|| matches!(
|
|
item,
|
|
MathExpr::MathSpacingChange(_)
|
|
| MathExpr::MathLineBreakPenaltiesChange(_)
|
|
| MathExpr::BreakPenalty(_)
|
|
),
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Arrange measured math-list children around a shared baseline.
|
|
///
|
|
/// The callback converts TeX's class-pair spacing into the caller's coordinate
|
|
/// unit using the active font metrics.
|
|
pub fn layout_math_sequence(
|
|
children: &[MathSequenceChildLayout],
|
|
baseline: f64,
|
|
mut inter_atom_spacing: impl FnMut(MathClass, MathClass, MathStyle, MathSpacingSettings) -> f64,
|
|
) -> MathSequenceLayout {
|
|
let mut top = baseline;
|
|
let mut bottom = baseline;
|
|
let mut width = 0.0;
|
|
let mut previous_class = None;
|
|
let mut child_positions = vec![None; children.len()];
|
|
|
|
for (index, child) in children.iter().enumerate() {
|
|
if child.plan.is_metadata {
|
|
continue;
|
|
}
|
|
if let (Some(previous), Some(next)) = (previous_class, child.plan.boundary.leading) {
|
|
width += inter_atom_spacing(previous, next, child.plan.math_style, child.plan.spacing);
|
|
}
|
|
|
|
let child_y = baseline - child.dimensions.baseline;
|
|
top = top.min(child_y);
|
|
bottom = bottom.max(child_y + child.dimensions.height);
|
|
child_positions[index] = Some(MathLayoutPosition {
|
|
x: width,
|
|
y: child_y,
|
|
});
|
|
width += child.dimensions.width;
|
|
previous_class = child.plan.boundary.trailing.or(previous_class);
|
|
}
|
|
|
|
let shift = -top;
|
|
for position in child_positions.iter_mut().flatten() {
|
|
position.y += shift;
|
|
}
|
|
|
|
MathSequenceLayout {
|
|
width,
|
|
height: bottom - top,
|
|
baseline: baseline + shift,
|
|
child_positions,
|
|
}
|
|
}
|
|
|
|
/// Inputs for the horizontal and vertical placement of a fenced math row.
|
|
///
|
|
/// The delimiter and spacing slices must contain one more item than `segments`.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathFencedLayoutInput<'a> {
|
|
pub segments: &'a [MathBoxDimensions],
|
|
pub delimiters: &'a [Option<MathDelimiterDimensions>],
|
|
pub spacing_before_delimiter: &'a [f64],
|
|
pub spacing_after_delimiter: &'a [f64],
|
|
pub baseline: f64,
|
|
pub axis_height: f64,
|
|
}
|
|
|
|
/// Geometry and child positions for a fenced math row.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathFencedLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub delimiter_positions: Vec<Option<MathLayoutPosition>>,
|
|
pub segment_positions: Vec<MathLayoutPosition>,
|
|
}
|
|
|
|
/// Inputs for positioning a math accent above or below its nucleus.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathAccentLayoutInput {
|
|
pub body: MathBoxDimensions,
|
|
pub accent_width: f64,
|
|
pub accent_height: f64,
|
|
pub accent_advance: Option<f64>,
|
|
pub accent_offset_x: f64,
|
|
pub body_attachment: Option<f64>,
|
|
pub accent_attachment: Option<f64>,
|
|
pub above: bool,
|
|
pub accent_delta: Option<f64>,
|
|
pub base_top_from_baseline: Option<f64>,
|
|
pub paint_baseline_from_top: Option<f64>,
|
|
pub paint_ink_bottom_from_top: Option<f64>,
|
|
pub gap: f64,
|
|
pub extra_space: f64,
|
|
}
|
|
|
|
/// Geometry for an accented math box and its two child positions.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathAccentLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub body_position: MathLayoutPosition,
|
|
pub accent_position: MathLayoutPosition,
|
|
}
|
|
|
|
/// A vertical rule position inside an array-like math alignment box.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathAlignmentRule {
|
|
pub x: f64,
|
|
pub y: f64,
|
|
pub width: f64,
|
|
pub height: f64,
|
|
}
|
|
|
|
/// Inputs for laying out the measured cells of an alignment environment.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathAlignmentLayoutInput<'a> {
|
|
pub rows: &'a [Vec<MathBoxDimensions>],
|
|
pub alignment: &'a MathAlignment,
|
|
pub cell_style: MathCellStyle,
|
|
pub row_spacing: MathRowSpacing,
|
|
pub equation_row_gap: f64,
|
|
pub strut_ascent: f64,
|
|
pub strut_descent: f64,
|
|
pub intercolumn_space: f64,
|
|
pub script_intercolumn_space: f64,
|
|
pub array_column_separation: f64,
|
|
pub array_rule_thickness: f64,
|
|
pub array_rule_gap: f64,
|
|
pub math_axis_height: f64,
|
|
pub baseline_mode: MathAlignmentBaseline,
|
|
}
|
|
|
|
/// Positions and overall dimensions for an alignment environment.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathAlignmentLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub cell_positions: Vec<Vec<MathLayoutPosition>>,
|
|
pub rules: Vec<MathAlignmentRule>,
|
|
}
|
|
|
|
/// Lays out alignment cells, rows, and optional array rules using TeX geometry.
|
|
pub fn layout_math_alignment(input: MathAlignmentLayoutInput<'_>) -> MathAlignmentLayout {
|
|
let MathAlignmentLayoutInput {
|
|
rows,
|
|
alignment,
|
|
cell_style,
|
|
row_spacing,
|
|
equation_row_gap,
|
|
strut_ascent,
|
|
strut_descent,
|
|
intercolumn_space,
|
|
script_intercolumn_space,
|
|
array_column_separation,
|
|
array_rule_thickness,
|
|
array_rule_gap,
|
|
math_axis_height,
|
|
baseline_mode,
|
|
} = input;
|
|
let column_count = rows
|
|
.iter()
|
|
.map(Vec::len)
|
|
.max()
|
|
.unwrap_or(0)
|
|
.max(match alignment {
|
|
MathAlignment::ArrayColumns { columns, .. } => columns.len(),
|
|
_ => 0,
|
|
});
|
|
assert!(column_count > 0);
|
|
|
|
let mut column_widths = vec![0.0_f64; column_count];
|
|
let mut row_metrics = Vec::with_capacity(rows.len());
|
|
for row in rows {
|
|
let ascent = row.iter().map(|cell| cell.baseline).fold(0.0, f64::max);
|
|
let descent = row
|
|
.iter()
|
|
.map(|cell| (cell.height - cell.baseline).max(0.0))
|
|
.fold(0.0, f64::max);
|
|
for (column, cell) in row.iter().enumerate() {
|
|
column_widths[column] = column_widths[column].max(cell.width);
|
|
}
|
|
row_metrics.push((ascent, descent));
|
|
}
|
|
|
|
for (ascent, descent) in &mut row_metrics {
|
|
*ascent = (*ascent).max(strut_ascent);
|
|
*descent = (*descent).max(strut_descent);
|
|
}
|
|
let row_gap = match row_spacing {
|
|
MathRowSpacing::Array => 0.0,
|
|
MathRowSpacing::Equation(_) => equation_row_gap,
|
|
MathRowSpacing::Cases => {
|
|
let stretched_ascent = strut_ascent * 1.2;
|
|
let stretched_descent = strut_descent * 1.2;
|
|
for (ascent, descent) in &mut row_metrics {
|
|
*ascent = (*ascent).max(stretched_ascent);
|
|
*descent = (*descent).max(stretched_descent);
|
|
}
|
|
0.0
|
|
}
|
|
};
|
|
|
|
let mut column_offsets = vec![0.0; column_count];
|
|
if let MathAlignment::ArrayColumns { vertical_rules, .. } = alignment {
|
|
let leading_rules = vertical_rules.first().copied().unwrap_or(0);
|
|
column_offsets[0] = array_column_separation
|
|
+ array_rule_pack_width(leading_rules, array_rule_thickness, array_rule_gap)
|
|
+ if leading_rules > 0 {
|
|
array_column_separation
|
|
} else {
|
|
0.0
|
|
};
|
|
}
|
|
for column in 1..column_count {
|
|
let gap = match alignment {
|
|
MathAlignment::AlternatingTight | MathAlignment::Multline => 0.0,
|
|
MathAlignment::Alternating if column % 2 == 0 => intercolumn_space,
|
|
MathAlignment::Alternating => 0.0,
|
|
MathAlignment::ArrayColumns { vertical_rules, .. } => {
|
|
array_column_separation * 2.0
|
|
+ array_rule_pack_width(
|
|
vertical_rules.get(column).copied().unwrap_or(0),
|
|
array_rule_thickness,
|
|
array_rule_gap,
|
|
)
|
|
}
|
|
_ if cell_style == MathCellStyle::Script => script_intercolumn_space,
|
|
_ => intercolumn_space,
|
|
};
|
|
column_offsets[column] = column_offsets[column - 1] + column_widths[column - 1] + gap;
|
|
}
|
|
let last_column_end = column_offsets[column_count - 1] + column_widths[column_count - 1];
|
|
let width = match alignment {
|
|
MathAlignment::ArrayColumns { vertical_rules, .. } => {
|
|
let trailing_rules = vertical_rules.get(column_count).copied().unwrap_or(0);
|
|
last_column_end
|
|
+ array_column_separation
|
|
+ array_rule_pack_width(trailing_rules, array_rule_thickness, array_rule_gap)
|
|
+ if trailing_rules > 0 {
|
|
array_column_separation
|
|
} else {
|
|
0.0
|
|
}
|
|
}
|
|
_ => last_column_end,
|
|
};
|
|
|
|
let mut height = 0.0;
|
|
let mut first_row_baseline = 0.0;
|
|
let mut cell_positions = Vec::with_capacity(rows.len());
|
|
for (row_index, row) in rows.iter().enumerate() {
|
|
let (ascent, descent) = row_metrics[row_index];
|
|
if row_index == 0 {
|
|
first_row_baseline = ascent;
|
|
}
|
|
let mut row_positions = Vec::with_capacity(row.len());
|
|
for (column, cell) in row.iter().enumerate() {
|
|
let column_alignment = match alignment {
|
|
MathAlignment::Multline if row_metrics.len() == 1 => MathColumnAlignment::Center,
|
|
MathAlignment::Multline if row_index == 0 => MathColumnAlignment::Left,
|
|
MathAlignment::Multline if row_index + 1 == row_metrics.len() => {
|
|
MathColumnAlignment::Right
|
|
}
|
|
MathAlignment::Multline => MathColumnAlignment::Center,
|
|
MathAlignment::Alternating | MathAlignment::AlternatingTight
|
|
if column_count == 1 =>
|
|
{
|
|
MathColumnAlignment::Center
|
|
}
|
|
MathAlignment::Alternating | MathAlignment::AlternatingTight if column % 2 == 0 => {
|
|
MathColumnAlignment::Right
|
|
}
|
|
MathAlignment::Alternating | MathAlignment::AlternatingTight => {
|
|
MathColumnAlignment::Left
|
|
}
|
|
MathAlignment::Centered => MathColumnAlignment::Center,
|
|
MathAlignment::Left => MathColumnAlignment::Left,
|
|
MathAlignment::Columns(columns) => columns
|
|
.get(column)
|
|
.copied()
|
|
.unwrap_or(MathColumnAlignment::Center),
|
|
MathAlignment::ArrayColumns { columns, .. } => columns
|
|
.get(column)
|
|
.copied()
|
|
.unwrap_or(MathColumnAlignment::Center),
|
|
};
|
|
let x = match column_alignment {
|
|
MathColumnAlignment::Left => column_offsets[column],
|
|
MathColumnAlignment::Center => {
|
|
column_offsets[column] + (column_widths[column] - cell.width) / 2.0
|
|
}
|
|
MathColumnAlignment::Right => {
|
|
column_offsets[column] + column_widths[column] - cell.width
|
|
}
|
|
};
|
|
row_positions.push(MathLayoutPosition {
|
|
x,
|
|
y: height + ascent - cell.baseline,
|
|
});
|
|
}
|
|
cell_positions.push(row_positions);
|
|
height += ascent + descent;
|
|
if row_index + 1 < row_metrics.len() {
|
|
height += row_gap;
|
|
}
|
|
}
|
|
|
|
let mut rules = Vec::new();
|
|
if let MathAlignment::ArrayColumns { vertical_rules, .. } = alignment {
|
|
for boundary in 0..=column_count {
|
|
let Some(rule_count) = vertical_rules.get(boundary).copied() else {
|
|
continue;
|
|
};
|
|
let boundary_start = if boundary == 0 {
|
|
0.0
|
|
} else {
|
|
column_offsets[boundary - 1] + column_widths[boundary - 1]
|
|
};
|
|
let mut x = boundary_start + array_column_separation;
|
|
for _ in 0..rule_count {
|
|
rules.push(MathAlignmentRule {
|
|
x: x - array_rule_thickness / 2.0,
|
|
y: 0.0,
|
|
width: array_rule_thickness,
|
|
height,
|
|
});
|
|
x += array_rule_thickness + array_rule_gap;
|
|
}
|
|
}
|
|
}
|
|
|
|
let baseline = match baseline_mode {
|
|
MathAlignmentBaseline::FirstRow => first_row_baseline,
|
|
MathAlignmentBaseline::MathAxisCentered => height / 2.0 + math_axis_height,
|
|
};
|
|
MathAlignmentLayout {
|
|
width,
|
|
height,
|
|
baseline,
|
|
cell_positions,
|
|
rules,
|
|
}
|
|
}
|
|
|
|
fn array_rule_pack_width(rule_count: usize, rule_thickness: f64, rule_gap: f64) -> f64 {
|
|
if rule_count == 0 {
|
|
0.0
|
|
} else {
|
|
rule_count as f64 * rule_thickness + (rule_count - 1) as f64 * rule_gap
|
|
}
|
|
}
|
|
|
|
/// Places a measured accent relative to its nucleus and computes the enclosing box.
|
|
pub fn layout_math_accent(input: MathAccentLayoutInput) -> MathAccentLayout {
|
|
let MathAccentLayoutInput {
|
|
body,
|
|
accent_width,
|
|
accent_height,
|
|
accent_advance,
|
|
accent_offset_x,
|
|
body_attachment,
|
|
accent_attachment,
|
|
above,
|
|
accent_delta,
|
|
base_top_from_baseline,
|
|
paint_baseline_from_top,
|
|
paint_ink_bottom_from_top,
|
|
gap,
|
|
extra_space,
|
|
} = input;
|
|
let accent_width = accent_width.max(accent_advance.unwrap_or(accent_width));
|
|
let advance_offset = accent_advance
|
|
.map(|advance| (accent_width - advance) / 2.0)
|
|
.unwrap_or(0.0);
|
|
let paint_attachment = accent_attachment
|
|
.map(|attachment| advance_offset + attachment)
|
|
.unwrap_or(accent_width / 2.0);
|
|
let accent_x = body_attachment
|
|
.map(|attachment| attachment - paint_attachment)
|
|
.unwrap_or((body.width - accent_width) / 2.0)
|
|
+ advance_offset
|
|
+ accent_offset_x;
|
|
|
|
let accent_anchor_y = if above {
|
|
body.baseline - base_top_from_baseline.unwrap_or(body.baseline) - gap
|
|
} else {
|
|
0.0
|
|
};
|
|
let accent_y = if above {
|
|
match (
|
|
accent_delta,
|
|
paint_baseline_from_top,
|
|
paint_ink_bottom_from_top,
|
|
) {
|
|
(Some(delta), Some(baseline), _) => delta - baseline,
|
|
(_, _, Some(ink_bottom)) => accent_anchor_y - ink_bottom,
|
|
_ => accent_anchor_y - accent_height,
|
|
}
|
|
} else {
|
|
body.height + gap
|
|
};
|
|
let top = if above {
|
|
0.0_f64.min(accent_y - extra_space)
|
|
} else {
|
|
0.0
|
|
};
|
|
let bottom = body.height.max(accent_y + accent_height) + if above { 0.0 } else { extra_space };
|
|
let shift = -top;
|
|
|
|
MathAccentLayout {
|
|
width: body.width,
|
|
height: bottom - top,
|
|
baseline: body.baseline + shift,
|
|
body_position: MathLayoutPosition { x: 0.0, y: shift },
|
|
accent_position: MathLayoutPosition {
|
|
x: accent_x,
|
|
y: accent_y + shift,
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Places measured segments and delimiters on one math row.
|
|
pub fn layout_fenced_box(input: MathFencedLayoutInput<'_>) -> MathFencedLayout {
|
|
let MathFencedLayoutInput {
|
|
segments,
|
|
delimiters,
|
|
spacing_before_delimiter,
|
|
spacing_after_delimiter,
|
|
baseline,
|
|
axis_height,
|
|
} = input;
|
|
assert_eq!(delimiters.len(), segments.len() + 1);
|
|
assert_eq!(spacing_before_delimiter.len(), delimiters.len());
|
|
assert_eq!(spacing_after_delimiter.len(), delimiters.len());
|
|
|
|
let mut x = 0.0;
|
|
let mut delimiter_x = vec![0.0; delimiters.len()];
|
|
let mut segment_x = vec![0.0; segments.len()];
|
|
for index in 0..segments.len() {
|
|
x += spacing_before_delimiter[index];
|
|
delimiter_x[index] = x;
|
|
x += delimiters[index]
|
|
.map(|delimiter| delimiter.width)
|
|
.unwrap_or(0.0);
|
|
x += spacing_after_delimiter[index];
|
|
segment_x[index] = x;
|
|
x += segments[index].width;
|
|
}
|
|
let last_delimiter = delimiters.len() - 1;
|
|
x += spacing_before_delimiter[last_delimiter];
|
|
delimiter_x[last_delimiter] = x;
|
|
x += delimiters[last_delimiter]
|
|
.map(|delimiter| delimiter.width)
|
|
.unwrap_or(0.0);
|
|
|
|
let mut top = 0.0_f64;
|
|
let mut bottom = baseline;
|
|
for segment in segments {
|
|
let y = baseline - segment.baseline;
|
|
top = top.min(y);
|
|
bottom = bottom.max(y + segment.height);
|
|
}
|
|
let delimiter_y = delimiters
|
|
.iter()
|
|
.map(|delimiter| {
|
|
delimiter.map(|delimiter| {
|
|
delimiter_top_from_baseline(baseline, axis_height, delimiter.height)
|
|
})
|
|
})
|
|
.collect::<Vec<_>>();
|
|
for (delimiter, y) in delimiters.iter().zip(&delimiter_y) {
|
|
if let (Some(delimiter), Some(y)) = (delimiter, y) {
|
|
top = top.min(*y);
|
|
bottom = bottom.max(*y + delimiter.height);
|
|
}
|
|
}
|
|
|
|
let shift = -top;
|
|
MathFencedLayout {
|
|
width: x,
|
|
height: bottom - top,
|
|
baseline: baseline + shift,
|
|
delimiter_positions: delimiter_x
|
|
.into_iter()
|
|
.zip(delimiter_y)
|
|
.map(|(x, y)| y.map(|y| MathLayoutPosition { x, y: y + shift }))
|
|
.collect(),
|
|
segment_positions: segment_x
|
|
.into_iter()
|
|
.zip(segments)
|
|
.map(|(x, segment)| MathLayoutPosition {
|
|
x,
|
|
y: baseline - segment.baseline + shift,
|
|
})
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
/// Places measured delimiters around a laid-out math body.
|
|
pub fn layout_delimited_box(input: MathDelimitedLayoutInput) -> MathDelimitedLayout {
|
|
let MathDelimitedLayoutInput {
|
|
body,
|
|
axis_height,
|
|
left,
|
|
right,
|
|
} = input;
|
|
let left_width = left.map(|delimiter| delimiter.width).unwrap_or(0.0);
|
|
let right_width = right.map(|delimiter| delimiter.width).unwrap_or(0.0);
|
|
let left_y = left
|
|
.map(|delimiter| delimiter_top_from_baseline(body.baseline, axis_height, delimiter.height));
|
|
let right_y = right
|
|
.map(|delimiter| delimiter_top_from_baseline(body.baseline, axis_height, delimiter.height));
|
|
let top = left_y.into_iter().chain(right_y).fold(0.0_f64, f64::min);
|
|
let bottom = left
|
|
.zip(left_y)
|
|
.map(|(delimiter, y)| y + delimiter.height)
|
|
.into_iter()
|
|
.chain(
|
|
right
|
|
.zip(right_y)
|
|
.map(|(delimiter, y)| y + delimiter.height),
|
|
)
|
|
.fold(body.height, f64::max);
|
|
let shift = -top;
|
|
|
|
MathDelimitedLayout {
|
|
width: left_width + body.width + right_width,
|
|
height: bottom - top,
|
|
baseline: body.baseline + shift,
|
|
left_x: 0.0,
|
|
left_y: left_y.map(|y| y + shift),
|
|
body_x: left_width,
|
|
body_y: shift,
|
|
right_x: left_width + body.width,
|
|
right_y: right_y.map(|y| y + shift),
|
|
}
|
|
}
|
|
|
|
/// Width, height, and baseline of a laid-out math child.
|
|
///
|
|
/// Values use one consistent coordinate unit chosen by the caller.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathBoxDimensions {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
}
|
|
|
|
/// A measured child box inside a display-math alignment.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathDisplayChildBox {
|
|
pub x: f64,
|
|
pub y: f64,
|
|
pub dimensions: MathBoxDimensions,
|
|
}
|
|
|
|
/// Vertical extent and right edge of one display-math row.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathDisplayRow {
|
|
pub baseline: f64,
|
|
pub top: f64,
|
|
pub bottom: f64,
|
|
pub right_edge: f64,
|
|
}
|
|
|
|
/// The layout of equation numbers beside or below display-math rows.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct MathDisplayTagLayout {
|
|
pub baselines: Vec<Option<f64>>,
|
|
pub row_shifts: Vec<f64>,
|
|
pub top_padding: f64,
|
|
pub height: f64,
|
|
}
|
|
|
|
/// Whether an expression's outer structure is an alignment box.
|
|
pub fn is_alignment_expression(expression: &MathExpr) -> bool {
|
|
match expression {
|
|
MathExpr::Spanned { expression, .. }
|
|
| MathExpr::Styled { expression, .. }
|
|
| MathExpr::Classified {
|
|
body: expression, ..
|
|
} => is_alignment_expression(expression),
|
|
MathExpr::Sequence(items) if items.len() == 1 => is_alignment_expression(&items[0]),
|
|
MathExpr::Alignment { .. } => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Return the row count for an outer `multline` alignment.
|
|
pub fn multline_row_count(expression: &MathExpr) -> Option<usize> {
|
|
match expression {
|
|
MathExpr::Spanned { expression, .. }
|
|
| MathExpr::Styled { expression, .. }
|
|
| MathExpr::Classified {
|
|
body: expression, ..
|
|
} => multline_row_count(expression),
|
|
MathExpr::Sequence(items) if items.len() == 1 => multline_row_count(&items[0]),
|
|
MathExpr::Alignment {
|
|
rows,
|
|
alignment: MathAlignment::Multline,
|
|
..
|
|
} => Some(rows.len()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Group measured alignment cells by baseline into display-math rows.
|
|
pub fn display_math_rows(
|
|
expression: &MathExpr,
|
|
layout: MathBoxDimensions,
|
|
children: &[MathDisplayChildBox],
|
|
) -> Vec<MathDisplayRow> {
|
|
let fallback = || {
|
|
vec![MathDisplayRow {
|
|
baseline: layout.baseline,
|
|
top: 0.0,
|
|
bottom: layout.height,
|
|
right_edge: layout.width,
|
|
}]
|
|
};
|
|
if !is_alignment_expression(expression) {
|
|
return fallback();
|
|
}
|
|
|
|
let mut rows = Vec::<MathDisplayRow>::new();
|
|
for child in children {
|
|
let baseline = child.y + child.dimensions.baseline;
|
|
let top = child.y;
|
|
let bottom = child.y + child.dimensions.height;
|
|
let right_edge = child.x + child.dimensions.width;
|
|
if let Some(row) = rows
|
|
.iter_mut()
|
|
.find(|row| (row.baseline - baseline).abs() < 0.001)
|
|
{
|
|
row.top = row.top.min(top);
|
|
row.bottom = row.bottom.max(bottom);
|
|
if child.dimensions.width > 0.0 {
|
|
row.right_edge = row.right_edge.max(right_edge);
|
|
}
|
|
} else {
|
|
rows.push(MathDisplayRow {
|
|
baseline,
|
|
top,
|
|
bottom,
|
|
right_edge: if child.dimensions.width > 0.0 {
|
|
right_edge
|
|
} else {
|
|
0.0
|
|
},
|
|
});
|
|
}
|
|
}
|
|
rows.sort_by(|left, right| left.baseline.total_cmp(&right.baseline));
|
|
if rows.is_empty() { fallback() } else { rows }
|
|
}
|
|
|
|
/// Compute the per-row horizontal expansion used by `multline`.
|
|
pub fn multline_row_x_shifts(
|
|
expression: &MathExpr,
|
|
current_width: f64,
|
|
requested_width: f64,
|
|
child_count: usize,
|
|
) -> Option<(f64, Vec<f64>)> {
|
|
let row_count = multline_row_count(expression)?;
|
|
if child_count != row_count {
|
|
return None;
|
|
}
|
|
|
|
let target_width = requested_width.max(current_width);
|
|
let extra_width = target_width - current_width;
|
|
let shifts = (0..row_count)
|
|
.map(|row_index| {
|
|
if row_count == 1 {
|
|
extra_width / 2.0
|
|
} else if row_index == 0 {
|
|
0.0
|
|
} else if row_index + 1 == row_count {
|
|
extra_width
|
|
} else {
|
|
extra_width / 2.0
|
|
}
|
|
})
|
|
.collect();
|
|
Some((target_width, shifts))
|
|
}
|
|
|
|
/// Select the math-row baselines used by a sequence of equation numbers.
|
|
pub fn equation_number_baselines(
|
|
expression: &MathExpr,
|
|
layout_baseline: f64,
|
|
number_count: usize,
|
|
rows: &[MathDisplayRow],
|
|
) -> Vec<f64> {
|
|
let row_baselines = rows.iter().map(|row| row.baseline).collect::<Vec<_>>();
|
|
if multline_row_count(expression).is_some() && number_count == 1 {
|
|
return vec![row_baselines.last().copied().unwrap_or(layout_baseline)];
|
|
}
|
|
if number_count > 1 {
|
|
return row_baselines;
|
|
}
|
|
vec![layout_baseline]
|
|
}
|
|
|
|
/// Select the display row associated with one equation number.
|
|
pub fn equation_tag_row_index(
|
|
expression: &MathExpr,
|
|
number_count: usize,
|
|
tag_baselines: &[f64],
|
|
rows: &[MathDisplayRow],
|
|
tag_index: usize,
|
|
) -> usize {
|
|
if rows.is_empty() {
|
|
return 0;
|
|
}
|
|
let has_row_tags = number_count > 1 || multline_row_count(expression).is_some();
|
|
if !is_alignment_expression(expression) || !has_row_tags {
|
|
return rows.len() - 1;
|
|
}
|
|
|
|
let Some(tag_baseline) = tag_baselines.get(tag_index) else {
|
|
return rows.len() - 1;
|
|
};
|
|
rows.iter()
|
|
.enumerate()
|
|
.min_by(|(_, left), (_, right)| {
|
|
(left.baseline - tag_baseline)
|
|
.abs()
|
|
.total_cmp(&(right.baseline - tag_baseline).abs())
|
|
})
|
|
.map_or(rows.len() - 1, |(index, _)| index)
|
|
}
|
|
|
|
/// Return the horizontal extent that must be kept clear beside an equation tag.
|
|
pub fn equation_tag_row_right_edge(
|
|
expression: &MathExpr,
|
|
layout_width: f64,
|
|
number_count: usize,
|
|
tag_baselines: &[f64],
|
|
rows: &[MathDisplayRow],
|
|
tag_index: usize,
|
|
) -> f64 {
|
|
let has_row_tags = number_count > 1 || multline_row_count(expression).is_some();
|
|
if !is_alignment_expression(expression) || !has_row_tags {
|
|
return layout_width;
|
|
}
|
|
rows.get(equation_tag_row_index(
|
|
expression,
|
|
number_count,
|
|
tag_baselines,
|
|
rows,
|
|
tag_index,
|
|
))
|
|
.map_or(layout_width, |row| row.right_edge)
|
|
}
|
|
|
|
/// Choose a centered formula origin that keeps equation numbers clear.
|
|
pub fn display_formula_x(
|
|
expression: &MathExpr,
|
|
content_width: f64,
|
|
layout_width: f64,
|
|
tag_widths: &[Option<f64>],
|
|
tag_separation: f64,
|
|
tag_baselines: &[f64],
|
|
rows: &[MathDisplayRow],
|
|
) -> f64 {
|
|
let centered = (content_width - layout_width) / 2.0;
|
|
let tag_width = tag_widths.iter().flatten().copied().fold(0.0_f64, f64::max);
|
|
if tag_width == 0.0 {
|
|
return centered;
|
|
}
|
|
|
|
if multline_row_count(expression).is_some() {
|
|
let tag_index = tag_widths.iter().position(Option::is_some).unwrap_or(0);
|
|
let row_right = equation_tag_row_right_edge(
|
|
expression,
|
|
layout_width,
|
|
tag_widths.len(),
|
|
tag_baselines,
|
|
rows,
|
|
tag_index,
|
|
);
|
|
let number_width = tag_widths
|
|
.get(tag_index)
|
|
.copied()
|
|
.flatten()
|
|
.unwrap_or(tag_width);
|
|
if number_width == 0.0 {
|
|
return centered;
|
|
}
|
|
let safe_x = content_width - number_width - tag_separation - row_right;
|
|
return if safe_x < 0.0 {
|
|
0.0
|
|
} else {
|
|
centered.min(safe_x)
|
|
};
|
|
}
|
|
|
|
let mut safe_x = None;
|
|
for (tag_index, number_width) in tag_widths.iter().enumerate() {
|
|
let Some(number_width) = number_width else {
|
|
continue;
|
|
};
|
|
if *number_width == 0.0 {
|
|
continue;
|
|
}
|
|
let row_right = equation_tag_row_right_edge(
|
|
expression,
|
|
layout_width,
|
|
tag_widths.len(),
|
|
tag_baselines,
|
|
rows,
|
|
tag_index,
|
|
);
|
|
let candidate = content_width - number_width - tag_separation - row_right;
|
|
if candidate >= 0.0 {
|
|
safe_x = Some(safe_x.map_or(candidate, |current: f64| current.min(candidate)));
|
|
}
|
|
}
|
|
safe_x.map_or(centered, |safe_x| centered.min(safe_x))
|
|
}
|
|
|
|
/// Measure the width reserved for an outer `multline` formula.
|
|
pub fn display_formula_width(
|
|
expression: &MathExpr,
|
|
content_width: f64,
|
|
tag_width: f64,
|
|
tag_separation: f64,
|
|
) -> f64 {
|
|
if multline_row_count(expression).is_some() && tag_width > 0.0 {
|
|
(content_width - tag_width - tag_separation).max(0.0)
|
|
} else {
|
|
content_width
|
|
}
|
|
}
|
|
|
|
/// Compute equation-number baselines, row shifts, and total display height.
|
|
pub fn layout_display_equation_tags(
|
|
expression: &MathExpr,
|
|
layout: MathBoxDimensions,
|
|
rows: &[MathDisplayRow],
|
|
tag_widths: &[Option<f64>],
|
|
content_width: f64,
|
|
formula_x: f64,
|
|
number_ascent: f64,
|
|
line_height: f64,
|
|
tag_separation: f64,
|
|
) -> MathDisplayTagLayout {
|
|
let row_baselines =
|
|
equation_number_baselines(expression, layout.baseline, tag_widths.len(), rows);
|
|
let fallback_row = MathDisplayRow {
|
|
baseline: layout.baseline,
|
|
top: 0.0,
|
|
bottom: layout.height,
|
|
right_edge: layout.width,
|
|
};
|
|
let mut row_shifts = vec![0.0; rows.len()];
|
|
let mut shifted_counts = vec![0usize; rows.len()];
|
|
let mut top_padding: f64 = 0.0;
|
|
let mut baselines = Vec::with_capacity(tag_widths.len());
|
|
for (index, tag_width) in tag_widths.iter().enumerate() {
|
|
let Some(tag_width) = tag_width else {
|
|
baselines.push(None);
|
|
continue;
|
|
};
|
|
if row_baselines.get(index).is_none() {
|
|
baselines.push(None);
|
|
continue;
|
|
}
|
|
let row_index =
|
|
equation_tag_row_index(expression, tag_widths.len(), &row_baselines, rows, index);
|
|
let row = rows.get(row_index).copied().unwrap_or(fallback_row);
|
|
let preceding_shift = row_shifts.iter().take(row_index).sum::<f64>();
|
|
let row_baseline = row.baseline + preceding_shift;
|
|
if *tag_width > 0.0
|
|
&& formula_x + row.right_edge + tag_width + tag_separation > content_width
|
|
{
|
|
let baseline = row.bottom
|
|
+ preceding_shift
|
|
+ tag_separation
|
|
+ number_ascent
|
|
+ line_height * shifted_counts[row_index] as f64;
|
|
baselines.push(Some(baseline));
|
|
shifted_counts[row_index] += 1;
|
|
row_shifts[row_index] += tag_separation + line_height;
|
|
} else {
|
|
top_padding = top_padding.max((number_ascent - row_baseline).max(0.0));
|
|
baselines.push(Some(row_baseline));
|
|
}
|
|
}
|
|
let height = layout.height + top_padding + row_shifts.iter().sum::<f64>();
|
|
MathDisplayTagLayout {
|
|
baselines,
|
|
row_shifts,
|
|
top_padding,
|
|
height,
|
|
}
|
|
}
|
|
|
|
/// Return one vertical offset per child and the total height added by row shifts.
|
|
pub fn display_row_child_shifts(
|
|
rows: &[MathDisplayRow],
|
|
child_baselines: &[f64],
|
|
row_shifts: &[f64],
|
|
) -> (Vec<f64>, f64) {
|
|
let total_height = row_shifts.iter().sum::<f64>();
|
|
if rows.is_empty() || total_height == 0.0 {
|
|
return (vec![0.0; child_baselines.len()], 0.0);
|
|
}
|
|
|
|
let child_shifts = child_baselines
|
|
.iter()
|
|
.map(|baseline| {
|
|
let row_index = rows
|
|
.iter()
|
|
.enumerate()
|
|
.min_by(|(_, left), (_, right)| {
|
|
(left.baseline - baseline)
|
|
.abs()
|
|
.total_cmp(&(right.baseline - baseline).abs())
|
|
})
|
|
.map_or(0, |(index, _)| index);
|
|
row_shifts.iter().take(row_index).sum::<f64>()
|
|
})
|
|
.collect();
|
|
(child_shifts, total_height)
|
|
}
|
|
|
|
/// Physical parameters used to place the numerator, denominator, and rule.
|
|
///
|
|
/// Values use the same coordinate unit as [`MathBoxDimensions`].
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathFractionLayoutInput {
|
|
pub numerator: MathBoxDimensions,
|
|
pub denominator: MathBoxDimensions,
|
|
pub numerator_shift_up: f64,
|
|
pub denominator_shift_down: f64,
|
|
pub numerator_gap_min: f64,
|
|
pub denominator_gap_min: f64,
|
|
pub rule_thickness: f64,
|
|
pub stack_gap_min: f64,
|
|
pub axis_height: f64,
|
|
pub draw_rule: bool,
|
|
}
|
|
|
|
/// Geometry for a TeX fraction box, including child positions and rule center.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathFractionLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub numerator_x: f64,
|
|
pub numerator_y: f64,
|
|
pub denominator_x: f64,
|
|
pub denominator_y: f64,
|
|
pub rule_y: Option<f64>,
|
|
}
|
|
|
|
/// Places a fraction's already-laid-out children according to TeX math rules.
|
|
pub fn layout_fraction_box(input: MathFractionLayoutInput) -> MathFractionLayout {
|
|
let MathFractionLayoutInput {
|
|
numerator,
|
|
denominator,
|
|
mut numerator_shift_up,
|
|
mut denominator_shift_down,
|
|
numerator_gap_min,
|
|
denominator_gap_min,
|
|
rule_thickness,
|
|
stack_gap_min,
|
|
axis_height,
|
|
draw_rule,
|
|
} = input;
|
|
|
|
let numerator_depth = numerator.height - numerator.baseline;
|
|
if draw_rule {
|
|
numerator_shift_up = numerator_shift_up
|
|
.max(axis_height + rule_thickness / 2.0 + numerator_gap_min + numerator_depth);
|
|
denominator_shift_down = denominator_shift_down
|
|
.max(denominator.baseline - axis_height + rule_thickness / 2.0 + denominator_gap_min);
|
|
} else {
|
|
let current_gap = (numerator_shift_up - numerator_depth)
|
|
- (denominator.baseline - denominator_shift_down);
|
|
let extra_shift = ((stack_gap_min - current_gap) / 2.0).max(0.0);
|
|
numerator_shift_up += extra_shift;
|
|
denominator_shift_down += extra_shift;
|
|
}
|
|
|
|
let numerator_y = -numerator_shift_up - numerator.baseline;
|
|
let denominator_y = denominator_shift_down - denominator.baseline;
|
|
let rule_y = -axis_height;
|
|
let mut top = 0.0_f64.min(numerator_y).min(denominator_y);
|
|
let mut bottom = 0.0_f64
|
|
.max(numerator_y + numerator.height)
|
|
.max(denominator_y + denominator.height);
|
|
if draw_rule {
|
|
top = top.min(rule_y - rule_thickness / 2.0);
|
|
bottom = bottom.max(rule_y + rule_thickness / 2.0);
|
|
}
|
|
|
|
let shift = -top;
|
|
let width = numerator.width.max(denominator.width);
|
|
MathFractionLayout {
|
|
width,
|
|
height: bottom - top,
|
|
baseline: shift,
|
|
numerator_x: (width - numerator.width) / 2.0,
|
|
numerator_y: numerator_y + shift,
|
|
denominator_x: (width - denominator.width) / 2.0,
|
|
denominator_y: denominator_y + shift,
|
|
rule_y: draw_rule.then_some(rule_y + shift),
|
|
}
|
|
}
|
|
|
|
/// The script-placement constraints needed for a non-limit script pair.
|
|
///
|
|
/// Values use the same coordinate unit as [`MathBoxDimensions`].
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathScriptLayoutMetrics {
|
|
pub subscript_top_max: f64,
|
|
pub subscript_baseline_drop_min: f64,
|
|
pub subscript_shift_down: f64,
|
|
pub superscript_bottom_min: f64,
|
|
pub superscript_baseline_drop_max: f64,
|
|
pub superscript_bottom_max_with_subscript: f64,
|
|
pub superscript_shift_up: f64,
|
|
pub superscript_shift_up_cramped: f64,
|
|
pub sub_superscript_gap_min: f64,
|
|
}
|
|
|
|
/// Inputs for placing ordinary superscripts and subscripts around a nucleus.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathScriptLayoutInput {
|
|
pub base: MathBoxDimensions,
|
|
pub subscript: Option<MathBoxDimensions>,
|
|
pub superscript: Option<MathBoxDimensions>,
|
|
pub metrics: MathScriptLayoutMetrics,
|
|
pub character_like_base: bool,
|
|
pub cramped: bool,
|
|
}
|
|
|
|
/// Which side of the nucleus contains the ordinary script.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum MathScriptSide {
|
|
Superscript,
|
|
Subscript,
|
|
}
|
|
|
|
/// Ink bounds for a math glyph relative to its baseline.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathScriptGlyphBounds {
|
|
pub top: f64,
|
|
pub bottom: f64,
|
|
}
|
|
|
|
/// Measured inputs for OpenType MATH script-kern placement.
|
|
///
|
|
/// All values use the same coordinate unit. Kern lookup closures receive
|
|
/// correction heights in that unit and return kern values in the same unit.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathScriptKernInput {
|
|
pub base: MathScriptGlyphBounds,
|
|
pub script: MathScriptGlyphBounds,
|
|
pub vertical_shift: f64,
|
|
pub side: MathScriptSide,
|
|
}
|
|
|
|
/// Vertical positions for a nucleus and its ordinary scripts.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathScriptLayout {
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub base_y: f64,
|
|
pub superscript_shift_up: Option<f64>,
|
|
pub superscript_y: Option<f64>,
|
|
pub subscript_shift_down: Option<f64>,
|
|
pub subscript_y: Option<f64>,
|
|
}
|
|
|
|
/// Selects XeTeX's larger corner-kern sum for one ordinary math script.
|
|
pub fn math_script_kern(
|
|
input: MathScriptKernInput,
|
|
base_kern_at_height: impl Fn(MathKernCorner, f64) -> Option<f64>,
|
|
script_kern_at_height: impl Fn(MathKernCorner, f64) -> Option<f64>,
|
|
) -> f64 {
|
|
let MathScriptKernInput {
|
|
base,
|
|
script,
|
|
vertical_shift,
|
|
side,
|
|
} = input;
|
|
let base_kern = |corner, height| base_kern_at_height(corner, height).unwrap_or(0.0);
|
|
let script_kern = |corner, height| script_kern_at_height(corner, height).unwrap_or(0.0);
|
|
|
|
match side {
|
|
MathScriptSide::Superscript => {
|
|
let sum_at_script_bottom =
|
|
base_kern(MathKernCorner::TopRight, vertical_shift + script.bottom)
|
|
+ script_kern(MathKernCorner::BottomLeft, script.bottom);
|
|
let sum_at_base_top = base_kern(MathKernCorner::TopRight, base.top)
|
|
+ script_kern(MathKernCorner::BottomLeft, base.top - vertical_shift);
|
|
sum_at_script_bottom.max(sum_at_base_top)
|
|
}
|
|
MathScriptSide::Subscript => {
|
|
let sum_at_script_top =
|
|
base_kern(MathKernCorner::BottomRight, -vertical_shift + script.top)
|
|
+ script_kern(MathKernCorner::TopLeft, script.top);
|
|
let sum_at_base_bottom = base_kern(MathKernCorner::BottomRight, base.bottom)
|
|
+ script_kern(MathKernCorner::TopLeft, base.bottom + vertical_shift);
|
|
sum_at_script_top.max(sum_at_base_bottom)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Applies TeX's script shift, clearance, and combined-script constraints.
|
|
pub fn layout_scripts_vertical(input: MathScriptLayoutInput) -> MathScriptLayout {
|
|
let MathScriptLayoutInput {
|
|
base,
|
|
subscript,
|
|
superscript,
|
|
metrics,
|
|
character_like_base,
|
|
cramped,
|
|
} = input;
|
|
let base_depth = base.height - base.baseline;
|
|
let mut superscript_shift_up = if character_like_base {
|
|
0.0
|
|
} else {
|
|
(base.baseline - metrics.superscript_baseline_drop_max).max(0.0)
|
|
};
|
|
let mut subscript_shift_down = if character_like_base {
|
|
0.0
|
|
} else {
|
|
(base_depth + metrics.subscript_baseline_drop_min).max(0.0)
|
|
};
|
|
|
|
if let Some(script) = superscript {
|
|
let script_depth = script.height - script.baseline;
|
|
let required_shift = if cramped {
|
|
metrics.superscript_shift_up_cramped
|
|
} else {
|
|
metrics.superscript_shift_up
|
|
};
|
|
superscript_shift_up = superscript_shift_up
|
|
.max(required_shift)
|
|
.max(script_depth + metrics.superscript_bottom_min);
|
|
}
|
|
if let Some(script) = subscript {
|
|
subscript_shift_down = subscript_shift_down.max(metrics.subscript_shift_down);
|
|
if superscript.is_none() {
|
|
subscript_shift_down =
|
|
subscript_shift_down.max(script.baseline - metrics.subscript_top_max);
|
|
}
|
|
}
|
|
if let (Some(superscript), Some(subscript)) = (superscript, subscript) {
|
|
let superscript_depth = superscript.height - superscript.baseline;
|
|
let gap = (superscript_shift_up - superscript_depth)
|
|
- (subscript.baseline - subscript_shift_down);
|
|
if gap < metrics.sub_superscript_gap_min {
|
|
subscript_shift_down += metrics.sub_superscript_gap_min - gap;
|
|
}
|
|
let superscript_bottom = superscript_shift_up - superscript_depth;
|
|
if superscript_bottom < metrics.superscript_bottom_max_with_subscript {
|
|
let adjustment = metrics.superscript_bottom_max_with_subscript - superscript_bottom;
|
|
superscript_shift_up += adjustment;
|
|
subscript_shift_down -= adjustment;
|
|
}
|
|
}
|
|
|
|
let superscript_y =
|
|
superscript.map(|script| base.baseline - superscript_shift_up - script.baseline);
|
|
let subscript_y =
|
|
subscript.map(|script| base.baseline + subscript_shift_down - script.baseline);
|
|
let top = superscript_y
|
|
.into_iter()
|
|
.chain(subscript_y)
|
|
.fold(0.0_f64, f64::min);
|
|
let bottom = superscript
|
|
.zip(superscript_y)
|
|
.map(|(script, y)| y + script.height)
|
|
.into_iter()
|
|
.chain(
|
|
subscript
|
|
.zip(subscript_y)
|
|
.map(|(script, y)| y + script.height),
|
|
)
|
|
.fold(base.height, f64::max);
|
|
let shift = -top;
|
|
|
|
MathScriptLayout {
|
|
height: bottom - top,
|
|
baseline: base.baseline + shift,
|
|
base_y: shift,
|
|
superscript_shift_up: superscript.map(|_| superscript_shift_up),
|
|
superscript_y: superscript_y.map(|y| y + shift),
|
|
subscript_shift_down: subscript.map(|_| subscript_shift_down),
|
|
subscript_y: subscript_y.map(|y| y + shift),
|
|
}
|
|
}
|
|
|
|
/// Physical constraints for display-style operator limits.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathLimitLayoutMetrics {
|
|
pub upper_gap_min: f64,
|
|
pub upper_baseline_rise_min: f64,
|
|
pub lower_gap_min: f64,
|
|
pub lower_baseline_drop_min: f64,
|
|
pub outer_padding: f64,
|
|
}
|
|
|
|
/// Inputs for placing display limits above and below an operator.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathLimitLayoutInput {
|
|
pub base: MathBoxDimensions,
|
|
pub upper: Option<MathBoxDimensions>,
|
|
pub lower: Option<MathBoxDimensions>,
|
|
pub upper_italic_correction: f64,
|
|
pub operator_skew: f64,
|
|
pub metrics: MathLimitLayoutMetrics,
|
|
}
|
|
|
|
/// Positions and bounds for a display operator with limits.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathLimitLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub base_x: f64,
|
|
pub base_y: f64,
|
|
pub upper_x: Option<f64>,
|
|
pub upper_y: Option<f64>,
|
|
pub lower_x: Option<f64>,
|
|
pub lower_y: Option<f64>,
|
|
}
|
|
|
|
/// Applies TeX's display-limit gaps, baseline constraints, and operator skew.
|
|
pub fn layout_display_limits(input: MathLimitLayoutInput) -> MathLimitLayout {
|
|
let MathLimitLayoutInput {
|
|
base,
|
|
upper,
|
|
lower,
|
|
upper_italic_correction,
|
|
operator_skew,
|
|
metrics,
|
|
} = input;
|
|
let width = base
|
|
.width
|
|
.max(
|
|
upper
|
|
.map(|script| script.width + upper_italic_correction)
|
|
.unwrap_or(0.0),
|
|
)
|
|
.max(lower.map(|script| script.width).unwrap_or(0.0));
|
|
let upper_y = upper.map(|script| {
|
|
0.0_f64
|
|
.min(-metrics.upper_gap_min - script.height)
|
|
.min(base.baseline - metrics.upper_baseline_rise_min - script.baseline)
|
|
});
|
|
let lower_y = lower.map(|script| {
|
|
(base.height + metrics.lower_gap_min)
|
|
.max(base.baseline + metrics.lower_baseline_drop_min - script.baseline)
|
|
});
|
|
let top = upper_y
|
|
.map(|y| y - metrics.outer_padding)
|
|
.into_iter()
|
|
.chain(lower_y)
|
|
.fold(0.0_f64, f64::min);
|
|
let bottom = upper
|
|
.zip(upper_y)
|
|
.map(|(script, y)| y + script.height)
|
|
.into_iter()
|
|
.chain(
|
|
lower
|
|
.zip(lower_y)
|
|
.map(|(script, y)| y + script.height + metrics.outer_padding),
|
|
)
|
|
.fold(base.height, f64::max);
|
|
let shift = -top;
|
|
|
|
MathLimitLayout {
|
|
width,
|
|
height: bottom - top,
|
|
baseline: base.baseline + shift,
|
|
base_x: (width - base.width) / 2.0,
|
|
base_y: shift,
|
|
upper_x: upper.map(|script| (width - script.width) / 2.0 + operator_skew / 2.0),
|
|
upper_y: upper_y.map(|y| y + shift),
|
|
lower_x: lower.map(|script| (width - script.width) / 2.0 - operator_skew / 2.0),
|
|
lower_y: lower_y.map(|y| y + shift),
|
|
}
|
|
}
|
|
|
|
/// Required height of a radical sign for a radicand and its overbar.
|
|
pub fn radical_sign_target_height(content_height: f64, clearance: f64, rule_thickness: f64) -> f64 {
|
|
content_height + clearance + rule_thickness
|
|
}
|
|
|
|
/// Inputs for positioning a radical sign, optional index, radicand, and rule.
|
|
///
|
|
/// Values use one consistent coordinate unit chosen by the caller.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathRadicalLayoutInput {
|
|
pub content: MathBoxDimensions,
|
|
pub index: Option<MathBoxDimensions>,
|
|
pub root_width: f64,
|
|
pub root_height: f64,
|
|
pub clearance: f64,
|
|
pub rule_thickness: f64,
|
|
pub extra_ascender: f64,
|
|
pub kern_before_degree: f64,
|
|
pub kern_after_degree: f64,
|
|
pub degree_raise_percent: f64,
|
|
pub rule_overlap: f64,
|
|
}
|
|
|
|
/// Geometry for the radical sign, optional index, radicand, and overbar.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct MathRadicalLayout {
|
|
pub width: f64,
|
|
pub height: f64,
|
|
pub baseline: f64,
|
|
pub index_x: f64,
|
|
pub index_y: Option<f64>,
|
|
pub root_x: f64,
|
|
pub root_y: f64,
|
|
pub root_position_y: f64,
|
|
pub rule_start_x: f64,
|
|
pub rule_y: f64,
|
|
pub content_x: f64,
|
|
pub content_y: f64,
|
|
}
|
|
|
|
/// Places a radical and computes the enclosing math box.
|
|
pub fn layout_radical_box(input: MathRadicalLayoutInput) -> MathRadicalLayout {
|
|
let MathRadicalLayoutInput {
|
|
content,
|
|
index,
|
|
root_width,
|
|
root_height,
|
|
clearance,
|
|
rule_thickness,
|
|
extra_ascender,
|
|
kern_before_degree,
|
|
kern_after_degree,
|
|
degree_raise_percent,
|
|
rule_overlap,
|
|
} = input;
|
|
let target_height = radical_sign_target_height(content.height, clearance, rule_thickness);
|
|
let radicand_y = extra_ascender + rule_thickness + clearance;
|
|
let baseline = radicand_y + content.baseline;
|
|
let excess_height = (root_height - target_height).max(0.0);
|
|
let root_y = extra_ascender - excess_height / 2.0;
|
|
let index_width = index.map(|index| index.width).unwrap_or(0.0);
|
|
let root_x = index
|
|
.map(|index| (index.width + kern_before_degree + kern_after_degree).max(0.0))
|
|
.unwrap_or(0.0);
|
|
let index_y = index.map(|index| baseline - root_height * degree_raise_percent - index.height);
|
|
let radical_top = -excess_height / 2.0;
|
|
let top = index_y
|
|
.map(|index_y| radical_top.min(index_y).min(root_y))
|
|
.unwrap_or_else(|| radical_top.min(root_y));
|
|
let bottom = index
|
|
.zip(index_y)
|
|
.map(|(index, index_y)| (index_y + index.height).max(radicand_y + content.height))
|
|
.unwrap_or(radicand_y + content.height)
|
|
.max(root_y + root_height);
|
|
let shift = -top;
|
|
let rule_y = root_y + rule_thickness / 2.0 + shift;
|
|
|
|
MathRadicalLayout {
|
|
width: (root_x + root_width + content.width).max(index_width),
|
|
height: bottom - top,
|
|
baseline: baseline + shift,
|
|
index_x: 0.0,
|
|
index_y: index_y.map(|index_y| index_y + shift),
|
|
root_x,
|
|
root_y,
|
|
root_position_y: root_y + shift,
|
|
rule_start_x: root_x + root_width - rule_overlap,
|
|
rule_y,
|
|
content_x: root_x + root_width,
|
|
content_y: radicand_y + shift,
|
|
}
|
|
}
|