Lay out insertion classes through the page builder

This commit is contained in:
gloamxun committed 2026-10-23 02:53:04 +08:00
1 parent 6305f059ac
commit 6cf8221ba7
6 files changed
+452 -61

No files matched your search

+202 -17
View File
@@ -8,7 +8,9 @@ mod subset;
pub mod tfm;
pub use cmr10::Cmr10Metrics;
use page::{PageBuilder, VerticalGlue, VerticalNode};
use std::collections::BTreeMap;
use page::{InsertionLimit, PageBuilder, VerticalGlue, VerticalNode};
pub use paragraph::{
HorizontalBox, HorizontalItem, Paragraph, ParagraphFont, ParagraphStyle, layout_items,
layout_paragraph, layout_paragraph_with_font, text_items, text_items_with_font,
@@ -768,8 +770,9 @@ fn source_hash(source: &str) -> u64 {
///
/// Units made of box/glue/penalty/mark material can be expressed as
/// page-builder nodes today (a unit may contribute several nodes and be
/// split across pages); floats and insertions return `None`, leaving the
/// scrolling builder in charge.
/// split across pages); insertion classes become [`VerticalNode::Insertion`]
/// reservations. Floats return `None`, leaving the scrolling builder in
/// charge.
fn document_nodes(
document: &Document,
) -> Option<(Vec<VerticalNode>, Vec<usize>, Vec<VerticalItem>)> {
@@ -802,7 +805,11 @@ fn document_nodes(
VerticalItem::Glue(height) => VerticalNode::Glue(VerticalGlue::new(*height, 0, 0)),
VerticalItem::Penalty(value) => VerticalNode::Penalty(*value),
VerticalItem::Mark(mark) => VerticalNode::Mark(mark.clone()),
VerticalItem::Insertion(_) | VerticalItem::Float(_) => return None,
VerticalItem::Insertion(insertion) => VerticalNode::Insertion {
class: insertion.class,
height: document.insertion_reserve(insertion.class, insertion.height),
},
VerticalItem::Float(_) => return None,
};
nodes.push(node);
owners.push(index);
@@ -826,6 +833,60 @@ fn item_height(item: &VerticalItem) -> i64 {
}
}
/// Take the longest prefix of `items` whose reserved height fits `capacity`.
///
/// Returns `(accepted, remainder, reserved_height)`. A single item larger than
/// the capacity is still accepted alone: TeX only splits insertion material at
/// item boundaries.
fn take_insertion_prefix(
document: &Document,
class: u8,
items: Vec<VerticalItem>,
capacity: i64,
) -> (Vec<VerticalItem>, Vec<VerticalItem>, i64) {
let mut accepted = Vec::new();
let mut reserved = 0_i64;
let mut rest = items.into_iter();
let mut remainder = Vec::new();
while let Some(item) = rest.next() {
let reserve = document.insertion_reserve(class, item_height(&item));
if reserved + reserve <= capacity {
accepted.push(item);
reserved += reserve;
continue;
}
if accepted.is_empty() {
reserved += reserve;
accepted.push(item);
} else {
remainder.push(item);
}
remainder.extend(rest);
break;
}
(accepted, remainder, reserved)
}
fn attach_insertion(
insertions: &mut BTreeMap<u8, Insertion>,
used: &mut BTreeMap<u8, i64>,
class: u8,
accepted: Vec<VerticalItem>,
reserved: i64,
) {
if accepted.is_empty() && reserved == 0 {
return;
}
*used.entry(class).or_insert(0) += reserved;
let entry = insertions.entry(class).or_insert_with(|| Insertion {
class,
height: 0,
items: Vec::new(),
});
entry.height += reserved;
entry.items.extend(accepted);
}
fn top_float_height(page: &Page) -> i64 {
page.floats
.iter()
@@ -1562,41 +1623,105 @@ impl Engine {
/// scrolling builder.
///
/// This is the staged P2 integration: it accepts documents whose units are
/// single vertical items (boxes, rules, paragraphs, math, haligns, glue,
/// penalties and marks). Floats and insertions still make it return `None`,
/// because their page interaction belongs to the incremental builder for
/// now.
/// vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties
/// and marks). Insertion classes are laid out here too, including material
/// held over past the class limit. Floats still make it return `None`,
/// because their placement belongs to the incremental builder for now.
pub fn layout_paged(document: &Document) -> Option<Self> {
let (nodes, owners, node_items) = document_nodes(document)?;
let builder = PageBuilder {
page_goal: document.page_goal,
top_skip: document.top_skip,
max_depth: document.max_depth,
insertion_limits: document
.insertion_classes
.iter()
.map(|class| InsertionLimit {
class: class.number,
height: document.insertion_class_limit(class.number),
})
.collect(),
};
let mut pages = Vec::new();
let mut held: BTreeMap<u8, Vec<VerticalItem>> = BTreeMap::new();
for fragment in builder.build(&nodes) {
let mut items = Vec::new();
let mut marks = Vec::new();
let mut sources = Vec::new();
for index in fragment.start..fragment.end {
let item = node_items[index].clone();
if let VerticalItem::Mark(mark) = &item {
marks.push(mark.clone());
} else {
items.push(item);
let mut insertions: BTreeMap<u8, Insertion> = BTreeMap::new();
let mut used: BTreeMap<u8, i64> = BTreeMap::new();
// Material held over from the previous page fills its class first.
let held_classes: Vec<u8> = held.keys().copied().collect();
for class in held_classes {
let material = held.remove(&class).unwrap_or_default();
let limit = document.insertion_class_limit(class);
let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0);
let (accepted, remainder, reserved) =
take_insertion_prefix(document, class, material, capacity);
attach_insertion(&mut insertions, &mut used, class, accepted, reserved);
if !remainder.is_empty() {
held.insert(class, remainder);
}
}
for index in fragment.start..fragment.end {
let item = &node_items[index];
let unit = &document.units[owners[index]];
if sources.last().map(|(id, _)| *id) != Some(unit.id) {
sources.push((unit.id, source_hash(&unit.source)));
}
match item {
VerticalItem::Mark(mark) => marks.push(mark.clone()),
VerticalItem::Insertion(insertion) => {
let class = insertion.class;
let limit = document.insertion_class_limit(class);
let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0);
let (accepted, remainder, reserved) = take_insertion_prefix(
document,
class,
insertion.items.clone(),
capacity,
);
attach_insertion(&mut insertions, &mut used, class, accepted, reserved);
if !remainder.is_empty() {
held.entry(class).or_default().extend(remainder);
}
}
other => items.push(other.clone()),
}
}
let mut page = Page::empty();
page.items = items;
page.marks = marks;
page.insertions = insertions.into_values().collect();
page.sources = sources;
page.seal_in_place();
pages.push(page);
}
// Insertion material that did not fit its class limit on the page where
// it was raised is carried to dedicated pages, as TeX holds it over.
while !held.is_empty() {
let classes: Vec<u8> = held.keys().copied().collect();
let mut insertions: BTreeMap<u8, Insertion> = BTreeMap::new();
let mut used: BTreeMap<u8, i64> = BTreeMap::new();
for class in classes {
let material = held.remove(&class).unwrap_or_default();
let limit = document.insertion_class_limit(class);
let (accepted, remainder, reserved) =
take_insertion_prefix(document, class, material, limit);
attach_insertion(&mut insertions, &mut used, class, accepted, reserved);
if !remainder.is_empty() {
held.insert(class, remainder);
}
}
let mut page = Page::empty();
page.insertions = insertions.into_values().collect();
page.seal_in_place();
pages.push(page);
}
let count = pages.len();
Some(Self {
layout: Layout {
@@ -4847,11 +4972,71 @@ mod tests {
}
#[test]
fn paged_layout_refuses_floats_and_insertions() {
fn paged_layout_refuses_floats_but_places_insertions() {
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Top, 100, 20)]);
assert!(Engine::layout_paged(&floated).is_none());
let insertion = Document::new(100, vec![Unit::insertion(1, 0, 10, Vec::new())]);
assert!(Engine::layout_paged(&insertion).is_none());
let insertion = Document::new(
100,
vec![
Unit::rule(1, 80, 20),
Unit::insertion(
2,
0,
40,
vec![VerticalItem::Rule {
width: 80,
height: 40,
}],
),
],
);
let layout = Engine::layout_paged(&insertion).expect("insertions are page-buildable");
assert_eq!(layout.pages().len(), 1);
assert_eq!(layout.pages()[0].insertions.len(), 1);
assert_eq!(layout.pages()[0].insertions[0].height, 40);
assert_eq!(layout.pages()[0].insertions[0].items.len(), 1);
}
#[test]
fn paged_layout_holds_over_insertion_material() {
let mut document = Document::new(
100,
vec![
Unit::rule(1, 80, 20),
Unit::insertion(
2,
0,
80,
vec![
VerticalItem::Rule {
width: 80,
height: 40,
},
VerticalItem::Rule {
width: 80,
height: 40,
},
],
),
Unit::rule(3, 80, 10),
],
);
document.insertion_classes = vec![InsertionClass {
number: 0,
fraction_percent: 50,
max_height: None,
skip: None,
multiplier: 1000,
}];
let layout = Engine::layout_paged(&document).expect("insertions are page-buildable");
assert_eq!(layout.pages().len(), 2);
assert_eq!(layout.pages()[0].insertions[0].items.len(), 1);
assert_eq!(layout.pages()[1].insertions[0].items.len(), 1);
// Body text keeps filling the page after a split insertion; the held
// over material gets a page of its own.
assert_eq!(layout.pages()[0].items.len(), 2);
assert!(layout.pages()[1].items.is_empty());
}
#[test]