Add bounded line expansion for Times body text

This commit is contained in:
gloamxun committed 2026-10-28 23:19:16 +08:00
1 parent 8fef7df187
commit 01b3f518cb
10 files changed
+113 -9

No files matched your search

+2
View File
@@ -7758,6 +7758,7 @@ mod tests {
left_skip: 0,
line_indents: vec![0; 10],
line_baselines: (0..10).map(|line| 8 + line * 10).collect(),
line_scales: Vec::new(),
centered: false,
right_aligned: false,
};
@@ -9468,6 +9469,7 @@ b & 2 \\
left_skip: 0,
line_indents: vec![0],
line_baselines: vec![8 * 65_536],
line_scales: Vec::new(),
centered: false,
right_aligned: false,
};
+76 -1
View File
@@ -136,6 +136,11 @@ fn default_font_size() -> i64 {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
/// Bounded line expansion in thousandths, microtype-like. A line may be
/// broken up to `line_width * (1000 + line_expansion) / 1000` and is
/// compressed back to the real measure when painted.
#[serde(default)]
pub line_expansion: i64,
/// Left skip inserted before every line (`\leftskip`).
pub left_skip: i64,
/// Right skip reserved at the end of every line (`\rightskip`).
@@ -299,16 +304,22 @@ impl ParagraphStyle {
}
}
fn line_target(&self, line: usize) -> i64 {
pub fn line_measure(&self, line: usize) -> i64 {
let (_, width) = self.line_geometry(line);
(width - self.left_skip - self.right_skip).max(1) - self.par_indent_for(line)
}
fn line_target(&self, line: usize) -> i64 {
let measure = self.line_measure(line);
(measure * (1000 + self.line_expansion) / 1000).max(measure)
}
}
impl Default for ParagraphStyle {
fn default() -> Self {
Self {
line_width: 400,
line_expansion: 0,
left_skip: 0,
right_skip: 0,
hang_indent: 0,
@@ -559,6 +570,10 @@ pub struct Paragraph {
/// Baseline of each line relative to the top of the paragraph box.
#[serde(default)]
pub line_baselines: Vec<i64>,
/// Horizontal compression per line (thousandths), used by the bounded
/// expansion model when a line was broken against an expanded measure.
#[serde(default)]
pub line_scales: Vec<i64>,
#[serde(default)]
pub centered: bool,
#[serde(default)]
@@ -597,6 +612,11 @@ impl Paragraph {
let tail_depth = line_extent(tail_lines.last().map(Vec::as_slice).unwrap_or(&[])).1;
self.height = head_height;
self.depth = head_depth;
let tail_scales = if self.line_scales.len() > lines {
self.line_scales.split_off(lines)
} else {
Vec::new()
};
Paragraph {
lines: tail_lines,
height: tail_height,
@@ -607,6 +627,7 @@ impl Paragraph {
left_skip: self.left_skip,
line_indents: tail_indents,
line_baselines: tail_baselines,
line_scales: tail_scales,
centered: self.centered,
right_aligned: self.right_aligned,
}
@@ -778,6 +799,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
left_skip: style.left_skip,
line_indents: Vec::new(),
line_baselines: Vec::new(),
line_scales: Vec::new(),
centered: style.centered,
right_aligned: style.right_aligned,
};
@@ -1436,6 +1458,27 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}
}
let depth = extents.last().map_or(0, |(_, descent)| *descent);
let line_scales: Vec<i64> = lines
.iter()
.enumerate()
.map(|(index, line)| {
let actual = style.line_measure(index).max(1);
let natural: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum();
if natural > actual {
(actual * 1000 / natural).clamp(900, 1000)
} else {
1000
}
})
.collect();
Paragraph {
// The page builder still budgets paragraphs on the line grid; the
// baseline table below carries TeX's interline glue for painting.
@@ -1452,6 +1495,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
left_skip: style.left_skip,
line_indents,
line_baselines,
line_scales,
centered: style.centered,
right_aligned: style.right_aligned,
}
@@ -2142,6 +2186,37 @@ mod tests {
.count()
}
#[test]
fn bounded_expansion_records_per_line_scales() {
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let base = ParagraphStyle {
line_width: 180,
..ParagraphStyle::default()
};
let expanded = ParagraphStyle {
line_width: 180,
line_expansion: 30,
..ParagraphStyle::default()
};
let plain = layout_paragraph(text, &base);
let stretched = layout_paragraph(text, &expanded);
assert!(stretched.lines.len() <= plain.lines.len());
assert_eq!(stretched.line_scales.len(), stretched.lines.len());
assert!(
stretched
.line_scales
.iter()
.all(|scale| (900..=1000).contains(scale)),
"{:?}",
stretched.line_scales
);
assert!(
stretched.line_scales.iter().any(|scale| *scale < 1000),
"no line was compressed: {:?}",
stretched.line_scales
);
}
#[test]
fn font_size_scales_glyphs_and_line_spacing() {
let font = crate::cmr10::Cmr10Metrics::Roman;
+4
View File
@@ -14,6 +14,7 @@ use texrra_tex_core::{
fn body_style() -> ParagraphStyle {
let font = Cmr10Metrics::default();
ParagraphStyle {
line_expansion: 0,
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
@@ -214,6 +215,7 @@ fn route_d_page_matches_pdftex_raster_geometry() {
std::fs::create_dir_all(&root).expect("create raster dir");
let style = ParagraphStyle {
line_expansion: 0,
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
@@ -395,6 +397,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
std::fs::create_dir_all(&root).expect("create raster dir");
let style = ParagraphStyle {
line_expansion: 0,
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
@@ -791,6 +794,7 @@ fn route_d_multiline_bands_track_pdftex() {
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let style = ParagraphStyle {
line_expansion: 0,
font_size: 10 * 65_536,
line_width: 150 * 65_536,
left_skip: 0,
+1 -1
View File
@@ -51,7 +51,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
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`; flat `/preview` and project previews now
prefer route-D with a v1 fallback). 1089 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 1090 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
+2 -2
View File
@@ -16,7 +16,7 @@ cargo test --workspace --offline
or run `./scripts/verify-route-d.sh`, which executes both.
The workspace currently passes **1089 tests**:
The workspace currently passes **1090 tests**:
| Suite | Tests |
| --- | --- |
@@ -29,7 +29,7 @@ The workspace currently passes **1089 tests**:
| engine/core unit | 4 + 1 |
Latest full run (web trial increment): `./scripts/verify-route-d.sh` passes
with fmt clean and **1089 tests** green.
with fmt clean and **1090 tests** green.
Latest live check (2026-10-27): the debug server served `examples/hello.tex`
from `target/debug/texrra serve`; `POST /preview` answered 200 with
+18
View File
@@ -37,3 +37,21 @@ expansion window during line breaking (microtype-like), record the chosen
expansion per line, and apply the same factor when painting PDF/SVG text. This
keeps line targets and glyph advances consistent instead of adding overflow or
collapsing interword glue.
## First result
- Added `ParagraphStyle.line_expansion` (thousandths), per-line `line_scales`
on `Paragraph`, and renderer x-advance compression.
- Times text uses a 2% expansion window. The 2.1 paragraph is now **six lines**
(was seven). Text still renders with visible word spaces.
- `3.3 Tables` remains on page 3. The reason is now localized in the page
builder: a top float that does not fit flushes the current page at
`VerticalItem::Float` instead of deferring only the float, so following text
cannot continue on page 2.
- Fidelity moved 0.8944 -> 0.8916 because line breaks and `pdftotext` word
boundaries changed; this is a geometry/flow tradeoff, not a claimed win.
## Next
Defer non-fitting top floats instead of flushing the page, then re-test 3.3.
+2 -2
View File
@@ -370,7 +370,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`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 451 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1089 tests (451 core unit, 443 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 67 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
The crate currently has 451 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1090 tests (451 core unit, 443 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 67 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
### M0 incremental demo
@@ -524,7 +524,7 @@ deliberately open rather than approximated:
## Limits and remaining gaps
The suite currently stands at 1089 passing tests, with the workspace clean.
The suite currently stands at 1090 passing tests, with the workspace clean.
Route-D serves both flat `/preview` and project preview/PDF requests by default
(automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The
objective's areas are implemented to the limits below; complex-script shaping is
+2 -2
View File
@@ -30,8 +30,8 @@ The current arXiv template comparison reports:
```text
reference_pages 3, candidate_pages 3
reference_words 1243, candidate_words 1266
word_sequence_ratio 0.8944
reference_words 1243, candidate_words 1258
word_sequence_ratio 0.8916
page 1 ink bbox: TeX [72, 79, 540, 721] route-D [71, 79, 540, 724]
page 2 ink bbox: TeX [72, 36, 540, 748] route-D [71, 41, 540, 751]
page 3 ink bbox: TeX [72, 36, 540, 748] route-D [71, 41, 540, 751]
+1 -1
View File
@@ -46,7 +46,7 @@ now means route-D.
| Area | Route-D | Evidence / impact |
| --- | --- | --- |
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1089-test suite |
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1090-test suite |
| Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures |
| Floats, captions, tables, booktabs | Supported | table/math tests, corpus |
| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests; PDF XObjects use pixel dimensions and the SVG preview embeds a PNG data URI |
+5
View File
@@ -14287,6 +14287,11 @@ fn build_document_with_labels(
};
let style = ParagraphStyle {
line_width: paragraph.width.unwrap_or(line_width),
line_expansion: if geometry.roman_family.as_deref() == Some("ptm") {
20
} else {
0
},
left_skip,
centered,
right_aligned,