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

+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,