Add the M1 box/glue/penalty paragraph builder

This commit is contained in:
gloamxun committed 2026-10-20 12:11:09 +08:00
1 parent 99dbb5ebb0
commit 51beb682f0
5 files changed
+282 -30

No files matched your search

+41 -16
View File
@@ -1,3 +1,7 @@
pub mod paragraph;
pub use paragraph::{HorizontalBox, HorizontalItem, Paragraph, ParagraphStyle, layout_paragraph};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
@@ -24,17 +28,25 @@ pub struct Unit {
}
impl Unit {
/// M0 placeholder for the real TeX paragraph builder: one line per 40
/// characters, 12pt baseline distance, 10pt text.
/// M1 paragraph builder: box/glue/penalty item stream with a
/// Knuth-Plass-style word-level line breaker.
pub fn paragraph(id: UnitId, source: impl Into<String>) -> Self {
Self::paragraph_with_style(id, source, ParagraphStyle::default())
}
pub fn paragraph_with_style(
id: UnitId,
source: impl Into<String>,
style: ParagraphStyle,
) -> Self {
let source = source.into();
let lines = source.chars().count().div_ceil(40).max(1) as i64;
let paragraph = layout_paragraph(&source, &style);
Self {
id,
source,
items: vec![VerticalItem::Box(VerticalBox {
width: 10 * 40,
height: lines * 12,
width: paragraph.width.max(style.line_width),
height: paragraph.height,
})],
}
}
@@ -195,17 +207,30 @@ impl Engine {
next.units[unit_index].source = source.into();
next.units[unit_index] = Unit::paragraph(unit_id, next.units[unit_index].source.clone());
let checkpoint = self
.layout
.checkpoints
.get(unit_index)
.cloned()
.unwrap_or(Checkpoint {
unit_index,
page_index: 0,
used: 0,
page_items: Vec::new(),
});
let mut checkpoint =
self.layout
.checkpoints
.get(unit_index)
.cloned()
.unwrap_or(Checkpoint {
unit_index,
page_index: 0,
used: 0,
page_items: Vec::new(),
});
let edited_height: i64 = next.units[unit_index]
.items
.iter()
.map(|item| match item {
VerticalItem::Box(vertical_box) => vertical_box.height,
VerticalItem::Glue(height) | VerticalItem::Penalty(height) => *height,
})
.sum();
if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() {
checkpoint.page_index += 1;
checkpoint.used = 0;
checkpoint.page_items.clear();
}
let old_pages = self.layout.pages.clone();
let mut pages = old_pages[..checkpoint.page_index].to_vec();
let mut current = Page {