Files
texrra-engine/crates/texrra-tex-core/src/paragraph.rs
T

552 lines
18 KiB
Rust
Executable File

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,
/// The source character when this box came from text, for display lists.
pub character: Option<char>,
}
#[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,
},
/// A possible hyphenation point. `pre_break_width` is the hyphen width
/// added when the line breaks here; `no_break_width` is the material kept
/// when it does not break.
Discretionary {
pre_break_width: i64,
no_break_width: i64,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
/// Left skip inserted before every line (`\leftskip`).
pub left_skip: i64,
/// Right skip reserved at the end of every line (`\rightskip`).
pub right_skip: 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,
left_skip: 0,
right_skip: 0,
par_indent: 0,
line_height: 12,
char_width: 10,
space_width: 4,
space_stretch: 6,
space_shrink: 2,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ParagraphFont {
Roman,
Bold,
Italic,
}
impl Default for ParagraphFont {
fn default() -> Self {
Self::Roman
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Paragraph {
pub lines: Vec<Vec<HorizontalItem>>,
pub height: i64,
pub width: i64,
#[serde(default)]
pub font: ParagraphFont,
#[serde(default)]
pub left_skip: i64,
}
impl Paragraph {
pub fn line_count(&self) -> usize {
self.lines.len()
}
}
/// 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,
character: Some(character),
}));
}
}
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.
///
/// Breakpoints are the ends of glue/penalty items. The cost model uses the
/// available glue stretch/shrink; overfull lines are allowed with an explicit
/// penalty so a single long word still produces output.
pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragraph {
if items.is_empty()
|| !items
.iter()
.any(|item| matches!(item, HorizontalItem::Box(_)))
{
return Paragraph {
lines: Vec::new(),
height: 0,
width: 0,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
};
}
let mut breakpoints = vec![0_usize];
for (index, item) in items.iter().enumerate() {
match item {
HorizontalItem::Glue { .. } => breakpoints.push(index + 1),
HorizontalItem::Penalty { penalty, .. } if *penalty < 10_000 => {
breakpoints.push(index + 1)
}
HorizontalItem::Discretionary { .. } => breakpoints.push(index + 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;
for end_index in 1..count {
let end = breakpoints[end_index];
for start_index in 0..end_index {
let start = breakpoints[start_index];
if best[start_index] == i64::MAX || start >= end {
continue;
}
let line = &items[start..end];
let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for (offset, item) in line.iter().enumerate() {
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;
}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
} else {
natural += *no_break_width;
}
}
}
}
if !has_box {
continue;
}
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let is_last = end == items.len();
if !is_last && natural * 2 < target {
continue;
}
let (ratio, overfull) = if natural <= target {
if is_last || stretch == 0 {
(0.0, false)
} else {
((target - natural) as f64 / stretch as f64, false)
}
} else 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 penalty = if is_last {
0
} else if trailing_penalty >= 0 {
trailing_penalty.min(10_000)
} else {
-(trailing_penalty)
};
let cost = badness
.saturating_mul(badness)
.saturating_add(overfull_penalty)
.saturating_add(penalty);
if cost < best[end_index] {
best[end_index] = cost;
previous[end_index] = start_index;
}
}
}
let mut ranges = Vec::new();
let mut end_index = count - 1;
while end_index > 0 {
let start_index = previous[end_index].min(end_index - 1);
ranges.push((breakpoints[start_index], breakpoints[end_index]));
end_index = start_index;
}
ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
for (start, end) in ranges {
let mut line: Vec<HorizontalItem> = Vec::new();
for (index, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + index + 1 == end {
line.push(HorizontalItem::Box(HorizontalBox {
width: *pre_break_width,
height: style.line_height,
depth: 0,
character: Some('-'),
}));
} else if *no_break_width > 0 {
line.push(HorizontalItem::Box(HorizontalBox {
width: *no_break_width,
height: style.line_height,
depth: 0,
character: None,
}));
}
}
_ => line.push(item.clone()),
}
}
while matches!(
line.last(),
Some(HorizontalItem::Glue { .. } | HorizontalItem::Penalty { .. })
) {
line.pop();
}
let width: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum();
max_width = max_width.max(width);
lines.push(line);
}
Paragraph {
height: lines.len() as i64 * style.line_height,
width: max_width,
lines,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
}
}
/// Convert text using TFM character widths and fontdimen glue parameters.
pub fn text_items_with_font(
text: &str,
style: &ParagraphStyle,
font: &crate::cmr10::Cmr10Metrics,
) -> Vec<HorizontalItem> {
let mut items = Vec::new();
let hyphenator = hyphenate::Hyphenator::plain_tex_en_us();
let caser = hyphenate::AsciiLowerCaser::default();
let words: Vec<&str> = text.split_whitespace().collect();
for (word_index, word) in words.iter().enumerate() {
if word_index > 0 {
items.push(HorizontalItem::Glue {
width: font.space(),
stretch: font.stretch(),
shrink: font.shrink(),
});
}
let points: std::collections::HashSet<usize> = if word.is_ascii()
&& word
.chars()
.all(|character| character.is_ascii_alphabetic())
&& word.len() >= 5
{
hyphenator.calculate_indices(&caser, word).collect()
} else {
std::collections::HashSet::new()
};
for (character_index, character) in word.chars().enumerate() {
items.push(HorizontalItem::Box(HorizontalBox {
width: font.width(character),
height: style.line_height,
depth: 0,
character: Some(character),
}));
let boundary = character_index + 1;
if points.contains(&boundary) && boundary >= 2 && boundary + 2 <= word.chars().count() {
items.push(HorizontalItem::Discretionary {
pre_break_width: font.width('-'),
no_break_width: 0,
});
}
}
}
while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.pop();
}
items.push(HorizontalItem::Penalty {
width: 0,
penalty: 10_000,
flagged: false,
});
items
}
/// Paragraph builder driven by a real TFM font instead of fixed widths.
pub fn layout_paragraph_with_font(
text: &str,
style: &ParagraphStyle,
font: &crate::cmr10::Cmr10Metrics,
) -> Paragraph {
let items = text_items_with_font(text, style, font);
layout_items(&items, style)
}
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let items = text_items(text, style);
layout_items(&items, style)
}
#[cfg(test)]
mod tests {
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]
fn words_break_at_glue_and_lines_are_justified() {
let style = ParagraphStyle {
line_width: 110,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert_eq!(paragraph.line_count(), 2);
assert!(glues(&paragraph.lines[0]) > 0);
assert!(boxes(&paragraph.lines[0]) >= 4);
}
#[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 cmr10_breaks_match_pdftex_at_180pt() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 180 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega",
&style,
&font,
);
let mut words: Vec<usize> = paragraph
.lines
.iter()
.map(|line| {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count()
})
.collect();
if let Some(last) = words.last_mut() {
*last += 1;
}
assert_eq!(words, vec![7, 7, 8]);
}
#[test]
fn cmr10_breaks_match_a_pdftex_fixture() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu",
&style,
&font,
);
let counts: Vec<usize> = paragraph
.lines
.iter()
.map(|line| {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
})
.collect();
assert_eq!(counts, vec![30, 25]);
}
#[test]
fn hyphenation_inserts_discretionary_breaks() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 3_000_000,
..ParagraphStyle::default()
};
let items = text_items_with_font("hyphenation", &style, &font);
assert!(
items
.iter()
.any(|item| matches!(item, HorizontalItem::Discretionary { .. }))
);
let paragraph = layout_items(&items, &style);
assert!(paragraph.lines.len() > 1);
}
#[test]
fn cmr10_font_drives_character_widths() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"The quick brown fox jumps over the lazy dog",
&style,
&font,
);
assert!(paragraph.line_count() >= 2);
assert!(paragraph.height > 0);
}
#[test]
fn left_skip_narrows_the_measure_and_offsets_the_paragraph() {
let narrow = ParagraphStyle {
line_width: 150,
left_skip: 50,
..ParagraphStyle::default()
};
let full = ParagraphStyle {
line_width: 150,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta";
let narrow_paragraph = layout_paragraph(text, &narrow);
assert_eq!(narrow_paragraph.left_skip, 50);
assert!(narrow_paragraph.lines.len() > layout_paragraph(text, &full).lines.len());
}
#[test]
fn right_skip_narrows_the_measure() {
let narrow = ParagraphStyle {
line_width: 150,
right_skip: 50,
..ParagraphStyle::default()
};
let full = ParagraphStyle {
line_width: 150,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta";
let narrow_lines = layout_paragraph(text, &narrow).lines.len();
let full_lines = layout_paragraph(text, &full).lines.len();
assert!(narrow_lines > full_lines);
}
#[test]
fn empty_paragraph_has_no_lines() {
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
}
}