Set vertical glue for ragged and flushed pages

This commit is contained in:
gloamxun committed 2026-10-23 04:13:12 +08:00
1 parent 448152cea4
commit 00c23a3511
6 files changed
+143 -14

No files matched your search

+1 -1
View File
@@ -596,7 +596,7 @@ Letter) set the MediaBox and the preview page box; the route-D endpoints read
leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension
assignments from the submitted source. Page marks collected by `\mark` are exposed through
`Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom floats sit at the page bottom with `Document::float_sep` between them and a `Document::bottom_fraction_percent` cap, while in-text floats flow inline with their `Document::in_text_sep` gaps counted as body height. The v1 `/preview` and project APIs are unchanged and remain the default.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom floats sit at the page bottom with `Document::float_sep` between them and a `Document::bottom_fraction_percent` cap, while in-text floats flow inline with their `Document::in_text_sep` gaps counted as body height. Vertical glue is set after the break: `Document::ragged_bottom` defaults to TeX's `\raggedbottom`, and setting it false applies `\flushbottom`, stretching `StretchGlue` so the page body reaches the goal. The v1 `/preview` and project APIs are unchanged and remain the default.
Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
document and returns the same page list plus `changedPages` and
+90 -1
View File
@@ -11,7 +11,8 @@ pub mod tfm;
pub use cmr10::Cmr10Metrics;
use std::collections::BTreeMap;
use page::{InsertionLimit, PageBuilder, PageFragment, VerticalGlue, VerticalNode};
pub use page::VerticalGlue;
use page::{InsertionLimit, PageBuilder, PageFragment, VerticalNode};
pub use paragraph::{
HorizontalBox, HorizontalItem, Paragraph, ParagraphFont, ParagraphStyle, layout_items,
layout_paragraph, layout_paragraph_with_font, text_items, text_items_with_font,
@@ -67,6 +68,8 @@ pub enum VerticalItem {
height: i64,
},
Glue(i64),
/// Glue with TeX stretch and shrink, used for vertical glue setting.
StretchGlue(VerticalGlue),
Penalty(i64),
Insertion(Insertion),
Mark(Mark),
@@ -220,6 +223,7 @@ impl Float {
VerticalItem::Box(box_) => box_.height,
VerticalItem::Rule { height, .. } => *height,
VerticalItem::Glue(height) => *height,
VerticalItem::StretchGlue(glue) => glue.width.max(0),
VerticalItem::Halign(halign) => halign.height,
VerticalItem::Paragraph(paragraph) => paragraph.height,
VerticalItem::Math { height, depth, .. } => height + depth,
@@ -589,6 +593,10 @@ pub struct Document {
/// `\bottomfraction`, in percent).
#[serde(default = "default_bottom_fraction")]
pub bottom_fraction_percent: u8,
/// TeX `\raggedbottom` (default) versus `\flushbottom`: when false the
/// paged builder stretches each page's glue so it reaches the page goal.
#[serde(default = "default_ragged_bottom")]
pub ragged_bottom: bool,
/// Maximum percentage of a text page that top floats may occupy (TeX's
/// `\topfraction`, in percent).
#[serde(default = "default_top_fraction")]
@@ -664,6 +672,10 @@ fn default_bottom_fraction() -> u8 {
30
}
fn default_ragged_bottom() -> bool {
true
}
fn default_top_fraction() -> u8 {
70
}
@@ -692,6 +704,7 @@ impl Document {
text_fraction_percent: default_text_fraction(),
float_page_fraction_percent: 50,
bottom_fraction_percent: default_bottom_fraction(),
ragged_bottom: default_ragged_bottom(),
top_fraction_percent: default_top_fraction(),
top_number: default_top_number(),
bottom_number: default_bottom_number(),
@@ -839,6 +852,7 @@ fn document_nodes(
depth: 0,
},
VerticalItem::Glue(height) => VerticalNode::Glue(VerticalGlue::new(*height, 0, 0)),
VerticalItem::StretchGlue(glue) => VerticalNode::Glue(*glue),
VerticalItem::Penalty(value) => VerticalNode::Penalty(*value),
VerticalItem::Mark(mark) => VerticalNode::Mark(mark.clone()),
VerticalItem::Insertion(insertion) => VerticalNode::Insertion {
@@ -878,6 +892,7 @@ fn item_height(item: &VerticalItem) -> i64 {
VerticalItem::Box(vertical_box) => vertical_box.height,
VerticalItem::Rule { height, .. } => *height,
VerticalItem::Glue(amount) => (*amount).max(0),
VerticalItem::StretchGlue(glue) => glue.width.max(0),
VerticalItem::Insertion(insertion) => insertion.height,
VerticalItem::Float(float) => float.height,
VerticalItem::Halign(halign) => halign.height,
@@ -1437,6 +1452,12 @@ impl Engine {
current.items.push(item.clone());
}
}
VerticalItem::StretchGlue(glue) => {
if !current.items.is_empty() {
used += glue.width.max(0);
current.items.push(item.clone());
}
}
VerticalItem::Penalty(penalty) => {
if *penalty <= -10_000 && !current.items.is_empty() {
pages.push(std::mem::replace(&mut current, Page::empty()));
@@ -1752,6 +1773,7 @@ impl Engine {
}
}
Self::set_page_glue(&mut items, fragment);
let mut page = Page::empty();
page.items = items;
page.marks = marks;
@@ -1870,6 +1892,37 @@ impl Engine {
text_float_sep: document.text_float_sep.max(0),
float_sep: document.float_sep.max(0),
bottom_fraction_percent: document.bottom_fraction_percent,
ragged_bottom: document.ragged_bottom,
}
}
/// Distribute the page's glue-setting amount over its vertical glue.
fn set_page_glue(items: &mut [VerticalItem], fragment: &PageFragment) {
if fragment.set == 0 {
return;
}
let mut remaining = fragment.set;
let mut total = if remaining > 0 {
fragment.stretch
} else {
fragment.shrink
};
for item in items.iter_mut() {
let VerticalItem::StretchGlue(glue) = item else {
continue;
};
let share = if remaining > 0 {
glue.stretch.max(0)
} else {
glue.shrink.max(0)
};
if share <= 0 || total <= 0 {
continue;
}
let delta = remaining * share / total;
glue.width += delta;
remaining -= delta;
total -= share;
}
}
@@ -1901,6 +1954,7 @@ impl Engine {
page.sources.push((unit.id, source_hash(&unit.source)));
}
}
Self::set_page_glue(&mut page.items, fragment);
page.seal_in_place();
page
})
@@ -2046,6 +2100,7 @@ impl Engine {
VerticalItem::Box(vertical_box) => vertical_box.height,
VerticalItem::Rule { height, .. } => *height,
VerticalItem::Glue(height) => *height,
VerticalItem::StretchGlue(glue) => glue.width.max(0),
VerticalItem::Penalty(_) => 0,
VerticalItem::Insertion(insertion) => insertion.height,
VerticalItem::Mark(_) => 0,
@@ -2236,6 +2291,12 @@ impl Engine {
current.items.push(item.clone());
}
}
VerticalItem::StretchGlue(glue) => {
if !current.items.is_empty() {
used += glue.width.max(0);
current.items.push(item.clone());
}
}
VerticalItem::Penalty(penalty) => {
if *penalty <= -10_000 && !current.items.is_empty() {
pages.push(std::mem::replace(&mut current, Page::empty()));
@@ -5053,6 +5114,34 @@ mod tests {
}
#[test]
fn paged_glue_setting_fills_or_ragged_bottoms() {
let units = vec![
Unit::rule(1, 100, 40),
Unit::vertical(
2,
vec![VerticalItem::StretchGlue(VerticalGlue::new(0, 10, 0))],
),
Unit::rule(3, 100, 40),
];
let mut document = Document::new(120, units);
let ragged = Engine::layout_paged(&document).expect("paged");
let rule_ys = |engine: &Engine| {
engine.pages()[0]
.display_list()
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Rule { y, .. } => Some(*y),
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(rule_ys(&ragged), vec![0, 40]);
document.ragged_bottom = false;
let flush = Engine::layout_paged(&document).expect("paged");
assert_eq!(rule_ys(&flush), vec![0, 80]);
}
fn paged_layout_breaks_simple_vertical_lists() {
let document = Document::new(
100,
+36 -1
View File
@@ -12,7 +12,7 @@ use std::collections::BTreeMap;
use crate::Mark;
/// Vertical glue with the stretch and shrink TeX uses to set a page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct VerticalGlue {
pub width: i64,
pub stretch: i64,
@@ -95,6 +95,9 @@ pub struct PageFragment {
pub stretch: i64,
/// Total shrink of the vertical glue on the page.
pub shrink: i64,
/// Signed glue-setting amount applied to the page: positive stretch to
/// fill the goal, negative shrink to fit it (zero when ragged).
pub set: i64,
/// Accepted insertion space per class, including material held over from
/// the previous page.
pub insertions: Vec<InsertionSpace>,
@@ -129,6 +132,8 @@ pub struct PageBuilder {
pub float_sep: i64,
/// TeX bottomfraction: percent of the page bottom floats may occupy.
pub bottom_fraction_percent: u8,
/// TeX `\raggedbottom` (default) versus `\flushbottom`.
pub ragged_bottom: bool,
}
impl PageBuilder {
@@ -141,6 +146,7 @@ impl PageBuilder {
text_float_sep: 0,
float_sep: 0,
bottom_fraction_percent: 100,
ragged_bottom: true,
}
}
@@ -506,6 +512,19 @@ impl PageBuilder {
bottom: i64,
insertions: Vec<InsertionSpace>,
) -> PageFragment {
let reserved: i64 = insertions.iter().map(|space| space.height).sum();
let target = (self.page_goal - bottom - reserved).max(0);
let set = if self.ragged_bottom {
0
} else if height < target {
// TeX stretches glue past its nominal amount (the glue set ratio
// is unbounded upward); only shrink is clamped.
target - height
} else if height > target {
-(height - target).min(shrink)
} else {
0
};
PageFragment {
start,
end,
@@ -517,6 +536,7 @@ impl PageBuilder {
depth,
stretch,
shrink,
set,
insertions,
}
}
@@ -595,6 +615,21 @@ mod tests {
}
#[test]
#[test]
fn flush_bottom_stretches_glue_to_the_goal() {
let nodes = vec![box_(40, 0), glue(0, 10, 0), box_(40, 0)];
let mut builder = PageBuilder::new(120);
assert_eq!(
builder.build(&nodes)[0].set,
0,
"ragged pages do not set glue"
);
builder.ragged_bottom = false;
let pages = builder.build(&nodes);
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].set, 40);
}
fn fragments_report_glue_stretch_and_shrink() {
let builder = PageBuilder::new(100);
let nodes = vec![box_(40, 0), glue(0, 20, 5), box_(40, 0)];
+3
View File
@@ -388,6 +388,9 @@ impl Page {
VerticalItem::Glue(height) => {
y += (*height).max(0);
}
VerticalItem::StretchGlue(glue) => {
y += glue.width.max(0);
}
VerticalItem::Math {
atom,
height,
+5 -6
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`). 379 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 380 workspace tests are green and no oracle
fixture is ignored.
Known gaps, in dependency order:
@@ -264,7 +264,7 @@ badness from the page goal and accumulated glue, adding the break penalty, and
applying `\topskip` to the first box and `\maxdepth` to the page depth. Seven
unit tests cover overfull avoidance, exact glue filling, forced penalties,
penalty-driven earlier breaks, `\topskip`, `\maxdepth`, marks, insertion
limits and top-float placement.
limits, float placement and vertical glue setting.
`Engine::layout_paged` now feeds it every document whose units are single
vertical items (`Document::max_depth` supplies `\maxdepth`) and materialises the
chosen fragments as hashed pages; ties go to the breakpoint closest to the page
@@ -279,12 +279,11 @@ the source. Insertion classes are placed by the
paged builder with their limits and held-over material, top floats are placed
at the head of a fragment with `\textfloatsep` reserved above the body, and
bottom floats sit at the page bottom with `\floatsep` between them and a
`\bottomfraction` cap; in-text floats flow inline with their `\intextsep` gaps counted as body height. Paged layouts also record the
`\bottomfraction` cap; in-text floats flow inline with their `\intextsep` gaps counted as body height. Vertical glue is set when pages are materialised: `PageBuilder::ragged_bottom` defaults to `\raggedbottom`, while `\flushbottom` stretches `VerticalItem::StretchGlue` proportionally so the page body reaches the goal (`PageFragment::set` records the signed setting amount). Paged layouts also record the
node index starting each page, so `Engine::edit` reuses the sealed prefix and
rebuilds only the pages from the edited unit onward; insertions and interpreted
`\output` keep the full-rebuild fallback. Next: paper margins, then
extend the `\output` interpreter past the
shipout/ifdim/ifnum/ifodd/ifcase subset.
`\output` keep the full-rebuild fallback. Next: extend the `\output`
interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset.
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
page counts identical and first/last baselines within 1pt of pdfLaTeX.
+8 -5
View File
@@ -116,7 +116,7 @@ and justification.
| --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
| 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` and vertical-glue fixtures; generic fil glue and `\prevgraf` next |
| 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, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) 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 or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
| 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` vertical glue setting applied when pages are materialised), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep` and a `\bottomfraction` cap) 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 or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
| 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; no booktabs/longtable parity yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
@@ -342,7 +342,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 255 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 379 tests (255 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 256 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 380 tests (256 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo
@@ -379,9 +379,12 @@ deliberately open rather than approximated:
- **M2**: the scrolling builder still drives `Document`; `page::PageBuilder`
implements TeX's candidate-breakpoint cost (badness + penalty, glue
stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it
for simple documents; paged edits replay from the edited page, but bottom
and its remaining float path still needs a paged equivalent before it can become the default;
paper margins remain open, and
for simple documents; `PageBuilder::ragged_bottom` selects `\raggedbottom`
(the default) or `\flushbottom`, which stretches `VerticalItem::StretchGlue`
in proportion to its stretch so the page body reaches the goal (only shrink
is clamped, as in TeX); paged edits replay from the edited page, insertions
and an interpreted `\output` keep the full-rebuild fallback; paper margins
remain open, and
the `\output` interpreter only covers the shipout/ifdim/ifnum/ifodd/ifcase subset (explicit
`\hoffset`/`\voffset` offsets are applied by the PDF writer).
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented.