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

+205
View File
@@ -0,0 +1,205 @@
use serde::{Deserialize, Serialize};
/// A horizontal box in scaled points (1/65536 pt).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct HorizontalBox {
pub width: i64,
pub height: i64,
pub depth: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HorizontalItem {
Box(HorizontalBox),
Glue {
width: i64,
stretch: i64,
shrink: i64,
},
Penalty {
width: i64,
penalty: i64,
flagged: bool,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
pub par_indent: i64,
pub line_height: i64,
pub char_width: i64,
pub space_width: i64,
pub space_stretch: i64,
pub space_shrink: i64,
}
impl Default for ParagraphStyle {
fn default() -> Self {
Self {
line_width: 400,
par_indent: 0,
line_height: 12,
char_width: 10,
space_width: 4,
space_stretch: 6,
space_shrink: 2,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Paragraph {
pub lines: Vec<Vec<HorizontalItem>>,
pub height: i64,
pub width: i64,
}
impl Paragraph {
pub fn line_count(&self) -> usize {
self.lines.len()
}
}
/// M1 word-level Knuth-Plass approximation.
///
/// The real TeX paragraph builder will operate on an item stream with
/// discretionary hyphens and penalties. This version keeps the same glue
/// stretch/shrink cost model but only breaks at spaces; it is deliberately
/// isolated so the DP can be replaced without touching the page builder.
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let words: Vec<&str> = text.split_whitespace().collect();
if words.is_empty() {
return Paragraph {
lines: Vec::new(),
height: 0,
width: 0,
};
}
let widths: Vec<i64> = words
.iter()
.map(|word| word.chars().count() as i64 * style.char_width)
.collect();
let count = words.len();
let mut best = vec![i64::MAX; count + 1];
let mut previous = vec![0_usize; count + 1];
best[0] = 0;
for end in 1..=count {
for start in 0..end {
if best[start] == i64::MAX {
continue;
}
let natural: i64 = widths[start..end].iter().sum::<i64>()
+ style.space_width * (end - start - 1) as i64;
let target = style.line_width - if start == 0 { style.par_indent } else { 0 };
let (ratio, overfull) = if natural <= target {
let stretch = style.space_stretch * (end - start - 1) as i64;
if stretch == 0 {
// 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 {
((target - natural) as f64 / stretch as f64, false)
}
} else {
let shrink = style.space_shrink * (end - start - 1) as i64;
if shrink == 0 {
((natural - target) as f64, true)
} else {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, ratio > 1.0)
}
};
let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64;
let overfull_penalty = if overfull { 100_000 } else { 0 };
let cost = badness
.saturating_mul(badness)
.saturating_add(overfull_penalty);
if cost < best[end] {
best[end] = cost;
previous[end] = start;
}
}
}
let mut ranges = Vec::new();
let mut end = count;
while end > 0 {
let start = previous[end].min(end - 1);
ranges.push((start, end));
end = start;
}
ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
for (start, end) in ranges {
let mut line = Vec::new();
let mut width = 0;
for index in start..end {
if index > start {
line.push(HorizontalItem::Glue {
width: style.space_width,
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,
});
}
max_width = max_width.max(width);
lines.push(line);
}
Paragraph {
height: lines.len() as i64 * style.line_height,
width: max_width,
lines,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn words_break_at_spaces_and_use_glue() {
let style = ParagraphStyle {
line_width: 100,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert_eq!(paragraph.line_count(), 2);
assert!(
paragraph.lines[0]
.iter()
.any(|item| matches!(item, HorizontalItem::Glue { .. }))
);
}
#[test]
fn first_line_respects_par_indent() {
let style = ParagraphStyle {
line_width: 100,
par_indent: 20,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert!(paragraph.line_count() >= 2);
}
#[test]
fn empty_paragraph_has_no_lines() {
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
}
}