Wrap p-column cells and keep wrapped rows splittable

This commit is contained in:
gloamxun committed 2026-10-24 00:57:09 +08:00
1 parent 4153657d0a
commit d1b93ac9be
4 files changed
+346 -63

No files matched your search

+314 -52
View File
@@ -55,6 +55,9 @@ pub struct HalignRow {
pub struct Halign {
pub rows: Vec<HalignRow>,
pub column_widths: Vec<i64>,
/// Per-column `p{width}` declarations; `Some` makes the column wrap.
#[serde(default)]
pub column_wrap: Vec<Option<i64>>,
pub width: i64,
pub height: i64,
pub line_height: i64,
@@ -97,12 +100,13 @@ impl Halign {
let mut chunks = Vec::new();
let mut start = 0_usize;
let mut height = 0_i64;
for (index, row) in self.rows.iter().enumerate() {
let row_height = if row.rule { 26_214 } else { self.line_height };
for index in 0..self.rows.len() {
let row_height = self.row_height(index);
if index > start && height + row_height > max_height {
chunks.push(Self {
rows: self.rows[start..index].to_vec(),
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
width: self.width,
height,
line_height: self.line_height,
@@ -115,6 +119,7 @@ impl Halign {
chunks.push(Self {
rows: self.rows[start..].to_vec(),
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
width: self.width,
height,
line_height: self.line_height,
@@ -122,11 +127,30 @@ impl Halign {
chunks
}
/// The horizontal rectangle occupied by a cell's text: `(x, width)`.
///
/// Spanned cells include the intercolumn gaps they cover. The x offset is
/// the aligned start inside that rectangle.
/// Column index of `cell_index` inside `row`.
fn cell_column(&self, row: &HalignRow, cell_index: usize) -> usize {
row.cells[..cell_index.min(row.cells.len())]
.iter()
.map(|cell| cell.span.max(1))
.sum()
}
/// The aligned rectangle of a cell: `(x, width)`.
pub fn cell_box(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> {
let (x, width) = self.cell_span(row_index, cell_index)?;
let row = self.rows.get(row_index)?;
let cell = row.cells.get(cell_index)?;
let text_width = text_width(&cell.text);
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
Some((x + offset, width))
}
/// The rectangle of the columns a cell covers, before alignment.
pub fn cell_span(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> {
let row = self.rows.get(row_index)?;
let cell = row.cells.get(cell_index)?;
let mut column = 0_usize;
@@ -152,24 +176,175 @@ impl Halign {
.sum::<i64>()
+ gaps;
let x: i64 = self.column_widths[..column].iter().sum::<i64>() + intercolumn * column as i64;
let text_width = cell
.text
.chars()
.map(|character| {
if character.is_whitespace() {
Some((x, width))
}
/// The wrapped lines of a cell; a single line unless its column declares
/// `p{width}`.
pub fn cell_lines(&self, row_index: usize, cell_index: usize) -> Vec<String> {
let row = match self.rows.get(row_index) {
Some(row) => row,
None => return Vec::new(),
};
let cell = match row.cells.get(cell_index) {
Some(cell) => cell,
None => return Vec::new(),
};
if cell.span.max(1) == 1 {
let column = self.cell_column(row, cell_index);
if let Some(Some(width)) = self.column_wrap.get(column) {
return wrap_cell_text(&cell.text, *width);
}
}
vec![cell.text.clone()]
}
/// Height of one row, counting wrapped cell lines.
pub fn row_height(&self, row_index: usize) -> i64 {
let row = match self.rows.get(row_index) {
Some(row) => row,
None => return 0,
};
if row.rule {
return 26_214;
}
let lines = (0..row.cells.len())
.map(|index| self.cell_lines(row_index, index).len())
.max()
.unwrap_or(1)
.max(1);
self.line_height * lines as i64
}
}
/// Natural width of a run of text at the illustrative 10pt metrics.
pub(crate) fn text_width(text: &str) -> i64 {
text.chars()
.map(|character| {
if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
}
})
.sum()
}
/// Greedily wrap `text` so each line fits `width`.
fn wrap_cell_text(text: &str, width: i64) -> Vec<String> {
let width = width.max(65_536);
let mut lines = Vec::new();
let mut line = String::new();
let mut line_width = 0_i64;
for word in text.split_whitespace() {
let word_width = text_width(word);
let gap = if line.is_empty() { 0 } else { 4 * 65_536 };
if !line.is_empty() && line_width + gap + word_width > width {
lines.push(std::mem::take(&mut line));
line_width = 0;
}
if !line.is_empty() && line_width + gap <= width {
line.push(' ');
line_width += gap;
}
if word_width <= width - line_width {
line.push_str(word);
line_width += word_width;
} else {
for character in word.chars() {
let character_width = if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
};
if line_width + character_width > width && !line.is_empty() {
lines.push(std::mem::take(&mut line));
line_width = 0;
}
})
.sum::<i64>();
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
Some((x + offset, width))
line.push(character);
line_width += character_width;
}
}
}
if !line.is_empty() {
lines.push(line);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
/// Parse a TeX dimension such as `25mm`, `2cm`, `72bp` or `10pt`.
fn parse_tex_dimension(spec: &str) -> Option<i64> {
let spec = spec.trim();
if spec.is_empty() {
return None;
}
let split = spec
.find(|character: char| character.is_alphabetic())
.unwrap_or(spec.len());
let (number, unit) = spec.split_at(split);
let value: f64 = number.trim().parse().ok()?;
let points_per_unit = match unit.trim() {
"pt" => 1.0,
"bp" => 72.27 / 72.0,
"mm" => 72.27 / 25.4,
"cm" => 72.27 / 2.54,
"in" => 72.27,
"em" => 10.0,
_ => return None,
};
Some((value * points_per_unit * 65_536.0).round() as i64)
}
/// Parse an alignment template into per-column alignment and wrap widths.
fn parse_column_template(template: &str) -> (Vec<CellAlignment>, Vec<Option<i64>>) {
let mut alignments = Vec::new();
let mut wraps = Vec::new();
let mut characters = template.chars().peekable();
while let Some(character) = characters.next() {
match character {
'l' | 'L' => {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
'c' | 'C' => {
alignments.push(CellAlignment::Center);
wraps.push(None);
}
'r' | 'R' => {
alignments.push(CellAlignment::Right);
wraps.push(None);
}
'p' | 'P' => {
let mut wrap = None;
if characters.peek() == Some(&'{') {
characters.next();
let mut spec = String::new();
for inner in characters.by_ref() {
if inner == '}' {
break;
}
spec.push(inner);
}
wrap = parse_tex_dimension(&spec);
}
alignments.push(CellAlignment::Left);
wraps.push(wrap);
}
'|' | '@' | ' ' => {}
_ => {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
}
}
if alignments.is_empty() {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
(alignments, wraps)
}
/// Vertical material reserved at the bottom of a page (footnotes etc.).
@@ -257,6 +432,23 @@ pub struct Unit {
impl Unit {
/// Build a simple `\halign` table with natural column widths.
pub fn halign(id: UnitId, rows: Vec<HalignRow>, column_count: usize, intercolumn: i64) -> Self {
Self::halign_with_wraps(
id,
rows,
column_count,
intercolumn,
vec![None; column_count],
)
}
/// Build a `\halign` table, honouring `p{width}` column declarations.
pub fn halign_with_wraps(
id: UnitId,
rows: Vec<HalignRow>,
column_count: usize,
intercolumn: i64,
wraps: Vec<Option<i64>>,
) -> Self {
let intercolumn = intercolumn.saturating_mul(65_536);
let mut column_widths = vec![0_i64; column_count];
for row in &rows {
@@ -264,17 +456,7 @@ impl Unit {
for cell in &row.cells {
let span = cell.span.max(1).min(column_count.saturating_sub(column));
if span == 1 {
let width: i64 = cell
.text
.chars()
.map(|character| {
if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
}
})
.sum();
let width = text_width(&cell.text);
if let Some(slot) = column_widths.get_mut(column) {
*slot = (*slot).max(width);
}
@@ -293,8 +475,7 @@ impl Unit {
.copied()
.sum::<i64>()
+ gaps;
let needed: i64 = cell.text.chars().count() as i64 * 10 * 65_536;
let extra = (needed - available).max(0);
let extra = (text_width(&cell.text) - available).max(0);
for offset in 0..span {
column_widths[column + offset] += extra / span as i64;
}
@@ -302,13 +483,24 @@ impl Unit {
column += span;
}
}
for (index, wrap) in wraps.iter().enumerate() {
if let (Some(width), Some(slot)) = (wrap, column_widths.get_mut(index)) {
*slot = (*width).max(10 * 65_536);
}
}
let gaps = intercolumn * column_count.saturating_sub(1) as i64;
let width = column_widths.iter().sum::<i64>() + gaps;
let line_height = 12 * 65_536;
let rule_height = 26_214; // 0.4pt
let height = rows
.iter()
.map(|row| if row.rule { rule_height } else { line_height })
let mut halign = Halign {
rows,
column_widths,
column_wrap: wraps,
width,
height: 0,
line_height,
};
halign.height = (0..halign.rows.len())
.map(|index| halign.row_height(index))
.sum();
Self {
id,
@@ -317,13 +509,7 @@ impl Unit {
space_before: 0,
space_stretch: 0,
space_shrink: 0,
items: vec![VerticalItem::Halign(Halign {
rows,
column_widths,
width,
height,
line_height,
})],
items: vec![VerticalItem::Halign(halign)],
}
}
@@ -345,14 +531,7 @@ impl Unit {
source: &str,
intercolumn: i64,
) -> Self {
let alignments: Vec<CellAlignment> = template
.chars()
.map(|character| match character {
'c' => CellAlignment::Center,
'r' => CellAlignment::Right,
_ => CellAlignment::Left,
})
.collect();
let (alignments, wraps) = parse_column_template(template);
let column_count = alignments.len().max(1);
let mut rows = Vec::new();
for raw_row in source.split(r"\\") {
@@ -414,7 +593,7 @@ impl Unit {
}
rows.push(HalignRow { cells, rule: false });
}
Self::halign(id, rows, column_count, intercolumn)
Self::halign_with_wraps(id, rows, column_count, intercolumn, wraps)
}
/// A running mark item, recorded on the page where it is shipped out.
@@ -6207,6 +6386,89 @@ mod tests {
assert!(widths.windows(2).all(|pair| pair[0] == pair[1]));
}
#[test]
fn paragraph_columns_wrap_cell_text() {
let unit = Unit::halign_from_source_with_template(
1,
"p{25mm}l",
"alpha beta gamma delta & short \\\\
second row & right\n",
0,
);
let VerticalItem::Halign(halign) = &unit.items[0] else {
panic!("expected halign");
};
let wrap = halign.column_wrap[0].expect("p column");
let expected = (25.0_f64 * 72.27 / 25.4 * 65_536.0).round() as i64;
assert!(
(wrap - expected).abs() <= 2,
"wrap {wrap} expected {expected}"
);
assert_eq!(halign.column_widths[0], wrap);
let lines = halign.cell_lines(0, 0);
assert!(lines.len() >= 3, "lines: {lines:?}");
assert!(lines.iter().all(|line| crate::text_width(line) <= wrap));
assert_eq!(
halign.row_height(0),
halign.line_height * lines.len() as i64
);
assert_eq!(
halign.cell_lines(1, 0),
vec!["second".to_owned(), "row".to_owned()]
);
}
#[test]
fn paragraph_columns_paint_wrapped_lines_and_split_rows() {
let unit = Unit::halign_from_source_with_template(
1,
"p{20mm}l",
"alpha beta gamma delta & x \\\\
second row text & y\n",
0,
);
let VerticalItem::Halign(halign) = &unit.items[0] else {
panic!("expected halign");
};
let lines = halign.cell_lines(0, 0);
assert!(lines.len() >= 4, "lines: {lines:?}");
let list = halign.display_list();
let texts: Vec<&str> = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert!(texts.contains(&"alpha"), "texts: {texts:?}");
assert!(texts.contains(&"beta"), "texts: {texts:?}");
let alpha_y = list
.items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "alpha" => Some(*y),
_ => None,
})
.unwrap();
let beta_y = list
.items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "beta" => Some(*y),
_ => None,
})
.unwrap();
assert!(beta_y > alpha_y, "alpha {alpha_y} beta {beta_y}");
let chunks = halign.split_for_height(halign.line_height * 2);
assert!(chunks.len() >= 2);
assert_eq!(
chunks.iter().map(|chunk| chunk.rows.len()).sum::<usize>(),
2
);
assert_eq!(chunks[0].column_widths, chunks[1].column_widths);
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
+28 -7
View File
@@ -8,7 +8,7 @@
use crate::cmr10::Cmr10Metrics;
use crate::math::{self, MathAtom};
use crate::paragraph::ParagraphFont;
use crate::{Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
/// One absolute drawing primitive in scaled points.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -284,19 +284,40 @@ impl Halign {
y += height;
continue;
}
let baseline = y + (self.line_height as f64 * 0.8) as i64;
for (index, cell) in row.cells.iter().enumerate() {
if let Some((x, _)) = self.cell_box(row_index, index) {
let row_height = self.row_height(row_index);
let lines_in_row = (0..row.cells.len())
.map(|index| self.cell_lines(row_index, index).len())
.max()
.unwrap_or(1)
.max(1);
for line_index in 0..lines_in_row {
let baseline = y
+ (self.line_height as f64 * 0.8) as i64
+ line_index as i64 * self.line_height;
for (index, cell) in row.cells.iter().enumerate() {
let lines = self.cell_lines(row_index, index);
let Some(line) = lines.get(line_index) else {
continue;
};
let Some((x, width)) = self.cell_span(row_index, index) else {
continue;
};
let text_width = crate::text_width(line);
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
x: x + offset,
y: baseline,
size: 10 * 65_536,
text: cell.text.clone(),
text: line.clone(),
});
}
}
y += self.line_height;
y += row_height;
}
list
}