Break paragraphs from character boxes, glue, and penalties

This commit is contained in:
gloamxun committed 2026-10-20 12:12:41 +08:00
1 parent 51beb682f0
commit e6da4d2fa7
2 files changed
+158 -73

No files matched your search

+156 -71
View File
@@ -61,103 +61,174 @@ impl Paragraph {
} }
} }
/// M1 word-level Knuth-Plass approximation. /// Convert text into a horizontal item stream: one box per character, one
/// glue per space, and a final penalty.
pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
let mut items = Vec::new();
for character in text.chars() {
if character.is_whitespace() {
if !matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.push(HorizontalItem::Glue {
width: style.space_width,
stretch: style.space_stretch,
shrink: style.space_shrink,
});
}
} else {
items.push(HorizontalItem::Box(HorizontalBox {
width: style.char_width,
height: style.line_height,
depth: 0,
}));
}
}
while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.pop();
}
items.push(HorizontalItem::Penalty {
width: 0,
penalty: 10_000,
flagged: false,
});
items
}
/// M1 paragraph builder over a horizontal item stream.
/// ///
/// The real TeX paragraph builder will operate on an item stream with /// Breakpoints are the ends of glue/penalty items. The cost model uses the
/// discretionary hyphens and penalties. This version keeps the same glue /// available glue stretch/shrink; overfull lines are allowed with an explicit
/// stretch/shrink cost model but only breaks at spaces; it is deliberately /// penalty so a single long word still produces output.
/// isolated so the DP can be replaced without touching the page builder. pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragraph {
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph { if items.is_empty()
let words: Vec<&str> = text.split_whitespace().collect(); || !items
if words.is_empty() { .iter()
.any(|item| matches!(item, HorizontalItem::Box(_)))
{
return Paragraph { return Paragraph {
lines: Vec::new(), lines: Vec::new(),
height: 0, height: 0,
width: 0, width: 0,
}; };
} }
let widths: Vec<i64> = words let mut breakpoints = vec![0_usize];
.iter() for (index, item) in items.iter().enumerate() {
.map(|word| word.chars().count() as i64 * style.char_width) match item {
.collect(); HorizontalItem::Glue { .. } => breakpoints.push(index + 1),
let count = words.len(); HorizontalItem::Penalty { penalty, .. } if *penalty < 10_000 => {
let mut best = vec![i64::MAX; count + 1]; breakpoints.push(index + 1)
let mut previous = vec![0_usize; count + 1]; }
_ => {}
}
}
if breakpoints.last().copied() != Some(items.len()) {
breakpoints.push(items.len());
}
breakpoints.dedup();
let count = breakpoints.len();
let mut best = vec![i64::MAX; count];
let mut previous = vec![0_usize; count];
best[0] = 0; best[0] = 0;
for end in 1..=count { for end_index in 1..count {
for start in 0..end { let end = breakpoints[end_index];
if best[start] == i64::MAX { for start_index in 0..end_index {
let start = breakpoints[start_index];
if best[start_index] == i64::MAX || start >= end {
continue; continue;
} }
let natural: i64 = widths[start..end].iter().sum::<i64>() let line = &items[start..end];
+ style.space_width * (end - start - 1) as i64; let mut natural = 0_i64;
let target = style.line_width - if start == 0 { style.par_indent } else { 0 }; let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for item in line {
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
}
HorizontalItem::Penalty { penalty, .. } => {
trailing_penalty = *penalty;
}
}
}
if !has_box {
continue;
}
let target = style.line_width
- if start_index == 0 {
style.par_indent
} else {
0
};
let is_last = end == items.len();
let (ratio, overfull) = if natural <= target { let (ratio, overfull) = if natural <= target {
let stretch = style.space_stretch * (end - start - 1) as i64; if is_last || stretch == 0 {
if stretch == 0 { (0.0, false)
// A single word has no interword glue to stretch. Treat it
// as an extremely loose line instead of a free break.
let slack = (target - natural).max(1) as f64;
(slack / style.space_stretch.max(1) as f64, false)
} else { } else {
((target - natural) as f64 / stretch as f64, false) ((target - natural) as f64 / stretch as f64, false)
} }
} else { } else if shrink == 0 {
let shrink = style.space_shrink * (end - start - 1) as i64;
if shrink == 0 {
((natural - target) as f64, true) ((natural - target) as f64, true)
} else { } else {
let ratio = (natural - target) as f64 / shrink as f64; let ratio = (natural - target) as f64 / shrink as f64;
(ratio, ratio > 1.0) (ratio, ratio > 1.0)
}
}; };
let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64; let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64;
let overfull_penalty = if overfull { 100_000 } else { 0 }; let overfull_penalty = if overfull { 100_000 } else { 0 };
let penalty = if is_last {
0
} else if trailing_penalty >= 0 {
trailing_penalty.min(10_000)
} else {
-(trailing_penalty)
};
let cost = badness let cost = badness
.saturating_mul(badness) .saturating_mul(badness)
.saturating_add(overfull_penalty); .saturating_add(overfull_penalty)
if cost < best[end] { .saturating_add(penalty);
best[end] = cost; if cost < best[end_index] {
previous[end] = start; best[end_index] = cost;
previous[end_index] = start_index;
} }
} }
} }
let mut ranges = Vec::new(); let mut ranges = Vec::new();
let mut end = count; let mut end_index = count - 1;
while end > 0 { while end_index > 0 {
let start = previous[end].min(end - 1); let start_index = previous[end_index].min(end_index - 1);
ranges.push((start, end)); ranges.push((breakpoints[start_index], breakpoints[end_index]));
end = start; end_index = start_index;
} }
ranges.reverse(); ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len()); let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0; let mut max_width = 0;
for (start, end) in ranges { for (start, end) in ranges {
let mut line = Vec::new(); let mut line: Vec<HorizontalItem> = items[start..end].to_vec();
let mut width = 0; while matches!(
for index in start..end { line.last(),
if index > start { Some(HorizontalItem::Glue { .. } | HorizontalItem::Penalty { .. })
line.push(HorizontalItem::Glue { ) {
width: style.space_width, line.pop();
stretch: style.space_stretch,
shrink: style.space_shrink,
});
width += style.space_width;
}
line.push(HorizontalItem::Box(HorizontalBox {
width: widths[index],
height: style.line_height,
depth: 0,
}));
width += widths[index];
}
if end == count {
line.push(HorizontalItem::Penalty {
width: 0,
penalty: 10_000,
flagged: false,
});
} }
let width: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
})
.sum();
max_width = max_width.max(width); max_width = max_width.max(width);
lines.push(line); lines.push(line);
} }
@@ -168,23 +239,37 @@ pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
} }
} }
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let items = text_items(text, style);
layout_items(&items, style)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
fn boxes(line: &[HorizontalItem]) -> usize {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
}
fn glues(line: &[HorizontalItem]) -> usize {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count()
}
#[test] #[test]
fn words_break_at_spaces_and_use_glue() { fn words_break_at_glue_and_lines_are_justified() {
let style = ParagraphStyle { let style = ParagraphStyle {
line_width: 100, line_width: 110,
..ParagraphStyle::default() ..ParagraphStyle::default()
}; };
let paragraph = layout_paragraph("alpha beta gamma delta", &style); let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert_eq!(paragraph.line_count(), 2); assert_eq!(paragraph.line_count(), 2);
assert!( assert!(glues(&paragraph.lines[0]) > 0);
paragraph.lines[0] assert!(boxes(&paragraph.lines[0]) >= 4);
.iter()
.any(|item| matches!(item, HorizontalItem::Glue { .. }))
);
} }
#[test] #[test]
+2 -2
View File
@@ -44,12 +44,12 @@ class execution are still ahead.
list model; list model;
- `ParagraphStyle` with `line_width`, `par_indent`, `line_height`, fixed - `ParagraphStyle` with `line_width`, `par_indent`, `line_height`, fixed
character/space metrics and glue stretch/shrink; character/space metrics and glue stretch/shrink;
- a word-level Knuth-Plass-style dynamic program that minimizes badness from - an item-stream Knuth-Plass-style dynamic program over character boxes, glue and penalty breakpoints that minimizes badness from
glue stretch/shrink, allows overfull lines with an explicit overfull penalty, glue stretch/shrink, allows overfull lines with an explicit overfull penalty,
applies `par_indent` to the first line, and emits justified glue; applies `par_indent` to the first line, and emits justified glue;
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`. - `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
M1 is deliberately word-level: it does not yet hyphenate, process M1 still does not hyphenate, process
`\discretionary`, use real TFM metrics or compare against pdfTeX. Those are the `\discretionary`, use real TFM metrics or compare against pdfTeX. Those are the
next paragraph milestones. next paragraph milestones.