Paint paragraph glyphs in the route-D display list

This commit is contained in:
gloamxun committed 2026-10-20 13:42:58 +08:00
1 parent d07ff59d31
commit 38bacdfbd5
4 files changed
+271 -193

No files matched your search

+46 -4
View File
@@ -61,6 +61,7 @@ pub enum VerticalItem {
Mark(Mark), Mark(Mark),
Float(Float), Float(Float),
Halign(Halign), Halign(Halign),
Paragraph(Paragraph),
} }
impl Halign { impl Halign {
@@ -356,10 +357,7 @@ impl Unit {
Self { Self {
id, id,
source, source,
items: vec![VerticalItem::Box(VerticalBox { items: vec![VerticalItem::Paragraph(paragraph)],
width: paragraph.width.max(style.line_width),
height: paragraph.height,
})],
paragraph_style: Some(style), paragraph_style: Some(style),
} }
} }
@@ -611,6 +609,20 @@ impl Engine {
} }
current.items.push(item.clone()); current.items.push(item.clone());
} }
VerticalItem::Paragraph(paragraph) => {
if current.items.is_empty() && top_float_height(&current) == 0 {
used = document.top_skip.max(paragraph.height);
} else if used + paragraph.height
> document.page_goal - insertion_height - bottom_float_height(&current)
{
pages.push(std::mem::replace(&mut current, Page::empty()));
used = document.top_skip.max(paragraph.height);
insertion_height = 0;
} else {
used += paragraph.height;
}
current.items.push(item.clone());
}
VerticalItem::Glue(amount) => { VerticalItem::Glue(amount) => {
if !current.items.is_empty() { if !current.items.is_empty() {
used += amount; used += amount;
@@ -751,6 +763,7 @@ impl Engine {
VerticalItem::Mark(_) => 0, VerticalItem::Mark(_) => 0,
VerticalItem::Float(float) => float.height, VerticalItem::Float(float) => float.height,
VerticalItem::Halign(halign) => halign.height, VerticalItem::Halign(halign) => halign.height,
VerticalItem::Paragraph(paragraph) => paragraph.height,
}) })
.sum(); .sum();
if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() { if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() {
@@ -827,6 +840,20 @@ impl Engine {
} }
current.items.push(item.clone()); current.items.push(item.clone());
} }
VerticalItem::Paragraph(paragraph) => {
if current.items.is_empty() && top_float_height(&current) == 0 {
used = next.top_skip.max(paragraph.height);
} else if used + paragraph.height
> next.page_goal - insertion_height - bottom_float_height(&current)
{
pages.push(std::mem::replace(&mut current, Page::empty()));
used = next.top_skip.max(paragraph.height);
insertion_height = 0;
} else {
used += paragraph.height;
}
current.items.push(item.clone());
}
VerticalItem::Glue(amount) => { VerticalItem::Glue(amount) => {
if !current.items.is_empty() { if !current.items.is_empty() {
used += amount; used += amount;
@@ -1252,6 +1279,21 @@ mod tests {
assert_eq!(halign.cell_box(2, 0), Some((30, 110))); assert_eq!(halign.cell_box(2, 0), Some((30, 110)));
} }
#[test]
fn paragraph_display_list_paints_characters() {
let document = Document::new(400, vec![Unit::paragraph(1, "hello world")]);
let engine = Engine::layout(&document);
let list = engine.pages()[0].display_list();
let texts = list
.items
.iter()
.filter(|item| matches!(item, DisplayItem::Text { .. }))
.count();
assert!(texts >= 10, "expected painted characters, got {texts}");
let svg = list.to_svg();
assert!(svg.contains(">h</text>"));
assert!(svg.contains(">w</text>"));
}
#[test] #[test]
fn halign_display_list_paints_cells_and_rules() { fn halign_display_list_paints_cells_and_rules() {
let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10); let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10);
+7 -1
View File
@@ -6,6 +6,8 @@ pub struct HorizontalBox {
pub width: i64, pub width: i64,
pub height: i64, pub height: i64,
pub depth: 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)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -55,7 +57,7 @@ impl Default for ParagraphStyle {
} }
} }
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Paragraph { pub struct Paragraph {
pub lines: Vec<Vec<HorizontalItem>>, pub lines: Vec<Vec<HorizontalItem>>,
pub height: i64, pub height: i64,
@@ -86,6 +88,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
width: style.char_width, width: style.char_width,
height: style.line_height, height: style.line_height,
depth: 0, depth: 0,
character: Some(character),
})); }));
} }
} }
@@ -247,12 +250,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
width: *pre_break_width, width: *pre_break_width,
height: style.line_height, height: style.line_height,
depth: 0, depth: 0,
character: Some('-'),
})); }));
} else if *no_break_width > 0 { } else if *no_break_width > 0 {
line.push(HorizontalItem::Box(HorizontalBox { line.push(HorizontalItem::Box(HorizontalBox {
width: *no_break_width, width: *no_break_width,
height: style.line_height, height: style.line_height,
depth: 0, depth: 0,
character: None,
})); }));
} }
} }
@@ -317,6 +322,7 @@ pub fn text_items_with_font(
width: font.width(character), width: font.width(character),
height: style.line_height, height: style.line_height,
depth: 0, depth: 0,
character: Some(character),
})); }));
let boundary = character_index + 1; let boundary = character_index + 1;
if points.contains(&boundary) && boundary >= 2 && boundary + 2 <= word.chars().count() { if points.contains(&boundary) && boundary >= 2 && boundary + 2 <= word.chars().count() {
+216 -188
View File
@@ -1,188 +1,216 @@
//! A small display-list painter for route-D layout output. //! A small display-list painter for route-D layout output.
//! //!
//! This is deliberately independent from v1's `DocumentModel` renderer. It //! This is deliberately independent from v1's `DocumentModel` renderer. It
//! turns laid-out `\halign` tables and page rules into absolute text/rule //! turns laid-out `\halign` tables and page rules into absolute text/rule
//! primitives so the route-D core can be inspected before the PDF backend is //! primitives so the route-D core can be inspected before the PDF backend is
//! wired up. //! wired up.
use crate::{Halign, Page, VerticalItem}; use crate::{Halign, HorizontalItem, Page, VerticalItem};
/// One absolute drawing primitive in scaled points. /// One absolute drawing primitive in scaled points.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum DisplayItem { pub enum DisplayItem {
Text { Text {
x: i64, x: i64,
y: i64, y: i64,
size: i64, size: i64,
text: String, text: String,
}, },
Rule { Rule {
x: i64, x: i64,
y: i64, y: i64,
width: i64, width: i64,
height: i64, height: i64,
}, },
} }
/// A page-local list of drawing primitives. /// A page-local list of drawing primitives.
#[derive(Clone, Debug, Default, PartialEq, Eq)] #[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DisplayList { pub struct DisplayList {
pub width: i64, pub width: i64,
pub height: i64, pub height: i64,
pub items: Vec<DisplayItem>, pub items: Vec<DisplayItem>,
} }
impl DisplayList { impl DisplayList {
pub fn push(&mut self, item: DisplayItem) { pub fn push(&mut self, item: DisplayItem) {
self.items.push(item); self.items.push(item);
} }
/// Offset every primitive, used when placing a nested table on a page. /// Offset every primitive, used when placing a nested table on a page.
pub fn place(&mut self, dx: i64, dy: i64) { pub fn place(&mut self, dx: i64, dy: i64) {
for item in &mut self.items { for item in &mut self.items {
match item { match item {
DisplayItem::Text { x, y, .. } => { DisplayItem::Text { x, y, .. } => {
*x += dx; *x += dx;
*y += dy; *y += dy;
} }
DisplayItem::Rule { x, y, .. } => { DisplayItem::Rule { x, y, .. } => {
*x += dx; *x += dx;
*y += dy; *y += dy;
} }
} }
} }
} }
/// Render the list as a standalone SVG document, in PostScript points. /// Render the list as a standalone SVG document, in PostScript points.
pub fn to_svg(&self) -> String { pub fn to_svg(&self) -> String {
let width = self.width as f64 / 65_536.0; let width = self.width as f64 / 65_536.0;
let height = self.height as f64 / 65_536.0; let height = self.height as f64 / 65_536.0;
let mut out = format!( let mut out = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width:.3}pt\" height=\"{height:.3}pt\" viewBox=\"0 0 {width:.3} {height:.3}\">\n" "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width:.3}pt\" height=\"{height:.3}pt\" viewBox=\"0 0 {width:.3} {height:.3}\">\n"
); );
for item in &self.items { for item in &self.items {
match item { match item {
DisplayItem::Text { x, y, size, text } => { DisplayItem::Text { x, y, size, text } => {
let x = *x as f64 / 65_536.0; let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0; let y = *y as f64 / 65_536.0;
let size = *size as f64 / 65_536.0; let size = *size as f64 / 65_536.0;
out.push_str(&format!( out.push_str(&format!(
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"serif\">{}</text>\n", "<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"serif\">{}</text>\n",
escape(text) escape(text)
)); ));
} }
DisplayItem::Rule { DisplayItem::Rule {
x, x,
y, y,
width, width,
height, height,
} => { } => {
let x = *x as f64 / 65_536.0; let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0; let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0; let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0; let height = *height as f64 / 65_536.0;
out.push_str(&format!( out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"black\"/>\n" "<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"black\"/>\n"
)); ));
} }
} }
} }
out.push_str("</svg>\n"); out.push_str("</svg>\n");
out out
} }
} }
fn escape(text: &str) -> String { fn escape(text: &str) -> String {
text.replace('&', "&amp;") text.replace('&', "&amp;")
.replace('<', "&lt;") .replace('<', "&lt;")
.replace('>', "&gt;") .replace('>', "&gt;")
} }
impl Halign { impl Halign {
/// Convert the table into text and rule primitives, with the table origin /// Convert the table into text and rule primitives, with the table origin
/// at `(0, 0)`. /// at `(0, 0)`.
pub fn display_list(&self) -> DisplayList { pub fn display_list(&self) -> DisplayList {
let mut list = DisplayList { let mut list = DisplayList {
width: self.width, width: self.width,
height: self.height, height: self.height,
items: Vec::new(), items: Vec::new(),
}; };
let mut y = 0_i64; let mut y = 0_i64;
for (row_index, row) in self.rows.iter().enumerate() { for (row_index, row) in self.rows.iter().enumerate() {
if row.rule { if row.rule {
let height = 26_214; // 0.4pt in scaled points. let height = 26_214; // 0.4pt in scaled points.
list.push(DisplayItem::Rule { list.push(DisplayItem::Rule {
x: 0, x: 0,
y, y,
width: self.width, width: self.width,
height, height,
}); });
y += height; y += height;
continue; continue;
} }
let baseline = y + (self.line_height as f64 * 0.8) as i64; let baseline = y + (self.line_height as f64 * 0.8) as i64;
for (index, cell) in row.cells.iter().enumerate() { for (index, cell) in row.cells.iter().enumerate() {
if let Some((x, _)) = self.cell_box(row_index, index) { if let Some((x, _)) = self.cell_box(row_index, index) {
list.push(DisplayItem::Text { list.push(DisplayItem::Text {
x, x,
y: baseline, y: baseline,
size: self.line_height, size: self.line_height,
text: cell.text.clone(), text: cell.text.clone(),
}); });
} }
} }
y += self.line_height; y += self.line_height;
} }
list list
} }
} }
impl Page { impl Page {
/// Paint the page's vertical material. Paragraph text is not yet part of /// Paint the page's vertical material. Paragraph text is not yet part of
/// the route-D box model, so opaque boxes advance the cursor only. /// the route-D box model, so opaque boxes advance the cursor only.
pub fn display_list(&self) -> DisplayList { pub fn display_list(&self) -> DisplayList {
let mut list = DisplayList::default(); let mut list = DisplayList::default();
let mut y = 0_i64; let mut y = 0_i64;
for item in &self.items { for item in &self.items {
match item { match item {
VerticalItem::Box(box_) => { VerticalItem::Box(box_) => {
y += box_.height; y += box_.height;
} }
VerticalItem::Rule { width, height } => { VerticalItem::Rule { width, height } => {
list.push(DisplayItem::Rule { list.push(DisplayItem::Rule {
x: 0, x: 0,
y, y,
width: *width, width: *width,
height: *height, height: *height,
}); });
y += *height; y += *height;
} }
VerticalItem::Glue(height) => { VerticalItem::Glue(height) => {
y += (*height).max(0); y += (*height).max(0);
} }
VerticalItem::Halign(halign) => { VerticalItem::Paragraph(paragraph) => {
let mut nested = halign.display_list(); let lines = paragraph.lines.len().max(1) as i64;
nested.place(0, y); let line_height = (paragraph.height / lines).max(1);
list.items.extend(nested.items); let size = ((line_height as f64) * 0.7) as i64;
y += halign.height; for line in &paragraph.lines {
} let baseline = y + ((line_height as f64) * 0.8) as i64;
VerticalItem::Penalty(_) | VerticalItem::Mark(_) | VerticalItem::Float(_) => {} let mut x = 0_i64;
VerticalItem::Insertion(insertion) => { for item in line {
y += insertion.height; match item {
} HorizontalItem::Box(box_) => {
} if let Some(character) = box_.character {
} list.push(DisplayItem::Text {
list.width = self x,
.items y: baseline,
.iter() size,
.map(|item| match item { text: character.to_string(),
VerticalItem::Halign(halign) => halign.width, });
VerticalItem::Rule { width, .. } => *width, }
_ => 0, x += box_.width;
}) }
.max() HorizontalItem::Glue { width, .. } => x += *width,
.unwrap_or(0); HorizontalItem::Penalty { .. }
list.height = y; | HorizontalItem::Discretionary { .. } => {}
list }
} }
} y += line_height;
}
}
VerticalItem::Halign(halign) => {
let mut nested = halign.display_list();
nested.place(0, y);
list.items.extend(nested.items);
y += halign.height;
}
VerticalItem::Penalty(_) | VerticalItem::Mark(_) | VerticalItem::Float(_) => {}
VerticalItem::Insertion(insertion) => {
y += insertion.height;
}
}
}
list.width = self
.items
.iter()
.map(|item| match item {
VerticalItem::Halign(halign) => halign.width,
VerticalItem::Rule { width, .. } => *width,
_ => 0,
})
.max()
.unwrap_or(0);
list.height = y;
list
}
}
+2
View File
@@ -247,3 +247,5 @@ v1 remains the production renderer; the route-D core is additive and tested inde
`\mathstrut` is a zero-width strut with 7pt height and 2pt depth. `\mathstrut` is a zero-width strut with 7pt height and 2pt depth.
M3 painter prototype: `Page::display_list()` / `Halign::display_list()` produce absolute text and rule primitives, and `DisplayList::to_svg()` writes a standalone SVG. Paragraph text and math are not yet painted. M3 painter prototype: `Page::display_list()` / `Halign::display_list()` produce absolute text and rule primitives, and `DisplayList::to_svg()` writes a standalone SVG. Paragraph text and math are not yet painted.
Paragraph painter: `Unit::paragraph` now stores `VerticalItem::Paragraph`, and `Page::display_list()` paints each line's `HorizontalBox` characters at their line advance. Boxes created by hyphenation carry `-`; justification is approximated by item widths.