Use Computer Modern math metrics for route-D formulas

This commit is contained in:
gloamxun committed 2026-10-24 01:31:51 +08:00
1 parent c9ad1e209a
commit 8f675bcabd
7 files changed
+108 -14

No files matched your search

Binary file not shown.
Binary file not shown.
+97
View File
@@ -15,6 +15,8 @@ pub enum Cmr10Metrics {
BoldItalic,
Mono,
Sans,
/// Math face: italic letters from cmmi10, big operators from cmex10.
Math,
}
static CMR10_TFM: &[u8] = include_bytes!("../assets/cmr10.tfm");
@@ -23,6 +25,8 @@ static CMTI10_TFM: &[u8] = include_bytes!("../assets/cmti10.tfm");
static CMBXTI10_TFM: &[u8] = include_bytes!("../assets/cmbxti10.tfm");
static CMTT10_TFM: &[u8] = include_bytes!("../assets/cmtt10.tfm");
static CMSS10_TFM: &[u8] = include_bytes!("../assets/cmss10.tfm");
static CMMI10_TFM: &[u8] = include_bytes!("../assets/cmmi10.tfm");
static CMEX10_TFM: &[u8] = include_bytes!("../assets/cmex10.tfm");
static CMR10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMBX10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
@@ -30,6 +34,8 @@ static CMTI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMBXTI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMTT10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSS10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMMI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMEX10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
fn parse(bytes: &[u8]) -> TfmMetrics {
TfmMetrics::parse(bytes).expect("embedded TFM must be valid")
@@ -59,6 +65,22 @@ fn parse_sans() -> TfmMetrics {
parse(CMSS10_TFM)
}
fn parse_math_italic() -> TfmMetrics {
parse(CMMI10_TFM)
}
fn parse_math_extension() -> TfmMetrics {
parse(CMEX10_TFM)
}
fn math_italic_metrics() -> &'static TfmMetrics {
CMMI10_METRICS.get_or_init(parse_math_italic)
}
fn math_extension_metrics() -> &'static TfmMetrics {
CMEX10_METRICS.get_or_init(parse_math_extension)
}
fn metrics_for(font: Cmr10Metrics) -> &'static TfmMetrics {
match font {
Cmr10Metrics::Roman => CMR10_METRICS.get_or_init(parse_roman),
@@ -67,6 +89,7 @@ fn metrics_for(font: Cmr10Metrics) -> &'static TfmMetrics {
Cmr10Metrics::BoldItalic => CMBXTI10_METRICS.get_or_init(parse_bold_italic),
Cmr10Metrics::Mono => CMTT10_METRICS.get_or_init(parse_mono),
Cmr10Metrics::Sans => CMSS10_METRICS.get_or_init(parse_sans),
Cmr10Metrics::Math => CMR10_METRICS.get_or_init(parse_roman),
}
}
@@ -103,19 +126,40 @@ impl Cmr10Metrics {
}
pub fn width(&self, character: char) -> i64 {
if self.is_math() && character.is_ascii_alphabetic() {
let width = math_italic_metrics().width(character);
if width > 0 {
return width;
}
}
let width = self.metrics().width(character);
if width > 0 { width } else { 327_680 }
}
pub fn height(&self, character: char) -> i64 {
if self.is_math() && character.is_ascii_alphabetic() {
let height = math_italic_metrics().height(character);
if height > 0 {
return height;
}
}
self.metrics().height(character)
}
pub fn depth(&self, character: char) -> i64 {
if self.is_math() && character.is_ascii_alphabetic() {
let depth = math_italic_metrics().depth(character);
if depth > 0 {
return depth;
}
}
self.metrics().depth(character)
}
pub fn italic(&self, character: char) -> i64 {
if self.is_math() && character.is_ascii_alphabetic() {
return math_italic_metrics().italic(character);
}
self.metrics().italic(character)
}
@@ -144,6 +188,40 @@ impl Cmr10Metrics {
}
}
/// Whether this face is the math face.
impl Cmr10Metrics {
pub const fn is_math(self) -> bool {
matches!(self, Self::Math)
}
}
/// Metrics for a named Computer Modern extension big operator (`\sum` and friends).
pub fn cmex_operator(name: &str) -> Option<(i64, i64, i64)> {
let slot = match name {
"sum" => 'P',
"prod" => 'Q',
"coprod" => 'R',
"int" => 'S',
"oint" => 'T',
"bigcap" => 'U',
"bigcup" => 'V',
"bigsqcup" => 'W',
"bigvee" => 'X',
"bigwedge" => 'Y',
"bigodot" => 'Z',
"bigotimes" => '[',
"bigoplus" => '\\',
"biguplus" => ']',
_ => return None,
};
let metrics = math_extension_metrics();
let width = metrics.width(slot);
if width == 0 {
return None;
}
Some((width, metrics.height(slot), metrics.depth(slot)))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -170,4 +248,23 @@ mod tests {
assert!(bold.space() > 0);
assert!(italic.height('A') > 0);
}
#[test]
fn math_face_uses_cmmi_for_letters() {
let roman = Cmr10Metrics::Roman;
let math = Cmr10Metrics::Math;
assert_ne!(math.width('f'), roman.width('f'));
assert_eq!(math.width('2'), roman.width('2'));
assert!(math.is_math());
}
#[test]
fn cmex_provides_big_operator_metrics() {
let (sum_width, _, sum_depth) = cmex_operator("sum").expect("cmex has a sum glyph");
let (int_width, _, _) = cmex_operator("int").expect("cmex has an integral glyph");
assert!(sum_width > 600_000, "sum width {sum_width}");
assert!(sum_depth > 500_000, "sum depth {sum_depth}");
assert!(int_width < sum_width);
assert!(cmex_operator("not-an-operator").is_none());
}
}
+7 -10
View File
@@ -352,15 +352,12 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
}
}
MathAtom::BigOperator { name } => {
let (width, height, depth) = match name.as_str() {
"int" => (8, 10, 4),
"prod" => (12, 8, 3),
_ => (12, 8, 3),
};
let (width, height, depth) =
crate::cmr10::cmex_operator(name).unwrap_or((12 * 65_536, 8 * 65_536, 3 * 65_536));
MathBox {
width: width * 65_536,
height: height * 65_536,
depth: depth * 65_536,
width,
height,
depth,
}
}
MathAtom::Limits { base, sub, sup } => {
@@ -1282,7 +1279,6 @@ mod tests {
let sum = layout_math(&parse_math("\\sum"), &font);
let letter = layout_math(&parse_math("s"), &font);
assert!(sum.width > letter.width);
assert!(sum.height > letter.height);
assert!(sum.depth > letter.depth);
}
#[test]
@@ -1290,7 +1286,8 @@ mod tests {
let font = Cmr10Metrics::default();
let sum = layout_math(&parse_math("\\sum_{i=1}^{n}"), &font);
let plain = layout_math(&parse_math("sum"), &font);
assert!(sum.height > plain.height);
assert!(sum.height > 0);
assert!(sum.width > 600_000);
assert!(sum.depth > plain.depth);
}
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 492 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 494 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+2 -2
View File
@@ -131,7 +131,7 @@ and justification.
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks<n>{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen<n>` or `\count<n>` changes the insertion capacity and reservation of later pages); the configured `\skip<n>` also reserves space above its class once per page in the paged builder, and a `\skip<n>` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); no CMEX size variants or TeX math spacing classes yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from the bundled `cmex10`), delimiter scaling, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an explicit approximation of TeX's `\split`/`align` behaviour); no `cmsy10` symbol alphabet, CMEX size variants or TeX math spacing classes yet |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
@@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 332 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 492 tests (332 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 334 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 494 tests (334 route-D unit, 15 engine unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 v1 unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
+1 -1
View File
@@ -925,7 +925,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
}
}
if paragraph.math {
let font = Cmr10Metrics::default();
let font = Cmr10Metrics::Math;
let atom = parse_math(&paragraph.text);
let lines = split_math_lines(&atom, &font, 480 * SCALE);
let mut unit = Unit::math_lines(index as u64, &lines, &font);