Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+292 -125
View File
@@ -1,13 +1,28 @@
pub mod artifacts;
pub mod cmr10;
pub mod execution;
pub mod math;
pub mod math_engine_tex;
pub mod math_font;
pub mod native_font;
pub mod output;
pub mod page;
pub mod paragraph;
pub mod pdf;
pub mod pdf_device;
pub mod pdf_image;
pub mod pdf_unicode;
pub mod pk;
pub mod pk_font;
pub mod provenance;
pub mod render;
pub mod resources;
pub mod source_map;
mod subset;
pub mod tfm;
pub mod type1;
pub mod type1_outline;
mod virtual_font;
pub use cmr10::Cmr10Metrics;
use std::collections::BTreeMap;
@@ -204,6 +219,8 @@ pub enum VerticalItem {
Paragraph(Paragraph),
Math {
atom: crate::math::MathAtom,
#[serde(default)]
geometry: Option<crate::math_engine_tex::MathGeometry>,
width: i64,
height: i64,
depth: i64,
@@ -1751,8 +1768,14 @@ impl Unit {
let items = lines
.iter()
.map(|atom| {
let math_box = crate::math::layout_math(atom, font);
let prepared = crate::math::prepare_math(
atom,
crate::math_engine_tex::MathStyle::Display,
font,
);
let math_box = prepared.metrics;
VerticalItem::Math {
geometry: prepared.geometry,
atom: atom.clone(),
width: math_box.width,
height: math_box.height,
@@ -1768,10 +1791,12 @@ impl Unit {
atom: crate::math::MathAtom,
font: &crate::cmr10::Cmr10Metrics,
) -> Self {
let math_box = math::layout_math(&atom, font);
let prepared = math::prepare_math(&atom, crate::math_engine_tex::MathStyle::Display, font);
let math_box = prepared.metrics;
Self::vertical(
id,
vec![VerticalItem::Math {
geometry: prepared.geometry,
atom,
width: math_box.width,
height: math_box.height,
@@ -2144,16 +2169,22 @@ fn source_hash(source: &str) -> u64 {
hasher.finish()
}
/// Convert a document into the vertical list consumed by [`PageBuilder`].
///
/// Units made of box/glue/penalty/mark material can be expressed as
/// page-builder nodes today (a unit may contribute several nodes and be
/// split across pages); insertion classes become [`VerticalNode::Insertion`]
/// reservations and floats become top, bottom or in-text nodes. A paragraph
/// expands to one node per line with a zero-width interline glue between
/// lines, which is the legal breakpoint that lets a page break inside it.
/// `None` means the document holds material the paged builder cannot express
/// yet.
/// TeX append_to_vlist: choose baselineskip or lineskip from the pending depth.
fn interline_glue(style: Option<&ParagraphStyle>, depth: i64, height: i64) -> i64 {
let baseline = style.map_or(12 * 65_536, |s| s.baselineskip);
let limit = style.map_or(0, |s| s.lineskiplimit);
let gap = baseline - depth - height;
if gap < limit {
style.map_or(65_536, |s| s.lineskip)
} else {
gap
}
}
/// Build matching measured and painted vertical lists. Paragraph line boxes
/// carry their actual baseline/depth; the paragraph API's block spacing is
/// explicit glue. A display finalizes the preceding paragraph before adding
/// interline glue, including when discardable material lies between them.
fn document_nodes(
document: &Document,
) -> Option<(Vec<VerticalNode>, Vec<usize>, Vec<VerticalItem>)> {
@@ -2161,12 +2192,21 @@ fn document_nodes(
let mut owners = Vec::new();
let mut items = Vec::new();
let mut previous_paragraph = false;
let mut previous_depth = None;
let mut previous_style = None;
let mut previous_display = false;
for (index, unit) in document.units.iter().enumerate() {
let heading = document.headings.iter().any(|(id, _)| *id == unit.id);
if document.page_breaks.binary_search(&index).is_ok() {
nodes.push(VerticalNode::Penalty(-10_000));
owners.push(index);
items.push(VerticalItem::Penalty(-10_000));
}
if heading {
nodes.push(VerticalNode::Penalty(-300));
owners.push(index);
items.push(VerticalItem::Penalty(-300));
}
if unit.space_before > 0 {
nodes.push(VerticalNode::Glue(VerticalGlue::new(
unit.space_before,
@@ -2174,7 +2214,13 @@ fn document_nodes(
unit.space_shrink,
)));
owners.push(index);
items.push(VerticalItem::Glue(unit.space_before));
// Retain the same stretch/shrink specification in the painted
// list, so page glue setting also moves the following display.
items.push(VerticalItem::StretchGlue(VerticalGlue::new(
unit.space_before,
unit.space_stretch,
unit.space_shrink,
)));
}
for (position, item) in unit.items.iter().enumerate() {
if position == 0 && previous_paragraph && matches!(item, VerticalItem::Paragraph(_)) {
@@ -2191,65 +2237,92 @@ fn document_nodes(
)));
}
if let VerticalItem::Paragraph(paragraph) = item {
if paragraph.lines.len() > 1 {
// TeX breaks pages between lines. Expand a paragraph into
// one node per line so the page builder is free to break
// inside it; each slice renders as its own single-line
// paragraph and keeps the baselines of its own line.
let total_lines = paragraph.lines.len();
let mut line_index = 0_usize;
let mut remaining = paragraph.clone();
loop {
let tail = if remaining.lines.len() > 1 {
Some(remaining.split_at(1))
let style = unit.paragraph_style.as_ref();
let followed_by_display = unit.items[position + 1..]
.iter()
.chain(
document.units[index + 1..]
.iter()
.flat_map(|unit| &unit.items),
)
.find(|item| {
!matches!(
item,
VerticalItem::Glue(_)
| VerticalItem::StretchGlue(_)
| VerticalItem::Penalty(_)
| VerticalItem::Mark(_)
| VerticalItem::Insertion(_)
)
})
.is_some_and(|item| matches!(item, VerticalItem::Math { .. }));
let total_lines = paragraph.lines.len();
let mut remaining = paragraph.clone();
for line_index in 0..total_lines {
let tail = if remaining.lines.len() > 1 {
Some(remaining.split_at(1))
} else {
None
};
let baseline = remaining
.line_baselines
.first()
.copied()
.unwrap_or(remaining.height - remaining.depth);
if line_index == 0 && previous_display {
if let Some(depth) = previous_depth {
let gap = interline_glue(style, depth, baseline);
nodes.push(VerticalNode::Glue(VerticalGlue::new(gap, 0, 0)));
owners.push(index);
items.push(VerticalItem::Glue(gap));
}
}
// Keep actual line height/depth in both lists. The
// paragraph API's block spacing is explicit glue, never
// part of a line's height or counted as a second depth.
// At a display/heading boundary the next append_to_vlist
// replaces that trailing budget with interline glue.
let padding = if (followed_by_display || heading) && tail.is_none() {
0
} else {
(remaining.height - baseline - remaining.depth).max(0)
};
remaining.height = baseline + remaining.depth;
nodes.push(VerticalNode::Box {
height: baseline,
depth: remaining.depth,
});
owners.push(index);
items.push(VerticalItem::Paragraph(remaining.clone()));
previous_depth = Some(remaining.depth);
if tail.is_some() {
let penalty = if line_index == 0 {
document.club_penalty
} else {
None
};
let remaining_depth = if remaining.height > remaining.depth {
remaining.depth
0
} + if line_index + 2 == total_lines {
document.widow_penalty
} else {
0
};
// The line grid already budgets the descent; keep the
// grid height and report the descent separately for
// `\pagedepth`/`\maxdepth`.
nodes.push(VerticalNode::Box {
height: remaining.height,
depth: remaining_depth,
});
owners.push(index);
items.push(VerticalItem::Paragraph(remaining.clone()));
match tail {
Some(tail) => {
// TeX inserts \clubpenalty after the first line
// and \widowpenalty before the last, so a page
// break that would leave a single line behind
// pays the paragraph's penalty.
if line_index == 0 && document.club_penalty != 0 {
nodes.push(VerticalNode::Penalty(document.club_penalty));
owners.push(index);
items.push(VerticalItem::Penalty(document.club_penalty));
}
// TeX puts interline glue between lines; a
// zero-width glue node is the legal breakpoint
// the page builder needs to split here.
nodes.push(VerticalNode::Glue(VerticalGlue::new(0, 0, 0)));
owners.push(index);
items.push(VerticalItem::Glue(0));
if line_index + 1 == total_lines - 1 && document.widow_penalty != 0
{
nodes.push(VerticalNode::Penalty(document.widow_penalty));
owners.push(index);
items.push(VerticalItem::Penalty(document.widow_penalty));
}
remaining = tail;
line_index += 1;
}
None => break,
if penalty != 0 {
nodes.push(VerticalNode::Penalty(penalty));
owners.push(index);
items.push(VerticalItem::Penalty(penalty));
}
}
continue;
if padding != 0 || tail.is_some() {
nodes.push(VerticalNode::Glue(VerticalGlue::new(padding, 0, 0)));
owners.push(index);
items.push(VerticalItem::Glue(padding));
}
if let Some(tail) = tail {
remaining = tail;
}
}
previous_style = style.cloned();
previous_display = heading;
continue;
}
if let VerticalItem::Halign(halign) = item {
let capacity = (document.page_goal - document.top_skip)
@@ -2278,6 +2351,27 @@ fn document_nodes(
continue;
}
}
if let VerticalItem::Math { height, depth, .. } = item {
if let Some(previous) = previous_depth {
let gap = interline_glue(previous_style.as_ref(), previous, *height);
nodes.push(VerticalNode::Glue(VerticalGlue::new(gap, 0, 0)));
owners.push(index);
items.push(VerticalItem::Glue(gap));
}
previous_depth = Some(*depth);
previous_display = true;
} else if !matches!(
item,
VerticalItem::Glue(_)
| VerticalItem::StretchGlue(_)
| VerticalItem::Penalty(_)
| VerticalItem::Mark(_)
| VerticalItem::Insertion(_)
) {
previous_depth = None;
previous_style = None;
previous_display = false;
}
let node = match item {
VerticalItem::Box(vertical_box) => VerticalNode::Box {
height: vertical_box.height,
@@ -2335,6 +2429,11 @@ fn document_nodes(
owners.push(index);
items.push(item.clone());
}
if heading {
nodes.push(VerticalNode::Penalty(10_000));
owners.push(index);
items.push(VerticalItem::Penalty(10_000));
}
previous_paragraph = unit
.items
.last()
@@ -2343,6 +2442,14 @@ fn document_nodes(
Some((nodes, owners, items))
}
fn paged_unit_hashes(document: &Document, items: &[VerticalItem], owners: &[usize]) -> Vec<u64> {
let mut hashes = vec![DefaultHasher::new(); document.units.len()];
for (item, owner) in items.iter().zip(owners) {
item.hash(&mut hashes[*owner]);
}
hashes.into_iter().map(|hash| hash.finish()).collect()
}
fn item_height(item: &VerticalItem) -> i64 {
match item {
VerticalItem::Box(vertical_box) => vertical_box.height,
@@ -2785,6 +2892,10 @@ pub struct Layout {
/// layout came from the scrolling builder or cannot be replayed partially.
#[serde(default)]
pub paged_page_nodes: Vec<usize>,
/// Measured per-unit material, including dependencies such as a following
/// display finalizing the preceding paragraph's depth/line budget.
#[serde(default)]
pub paged_unit_hashes: Vec<u64>,
}
impl Layout {
@@ -3427,6 +3538,7 @@ impl Engine {
recomputed_pages: 0,
changed_pages: (0..pages_len).collect(),
paged_page_nodes: Vec::new(),
paged_unit_hashes: Vec::new(),
},
}
}
@@ -3496,6 +3608,16 @@ impl Engine {
/// because their placement belongs to the incremental builder for now.
pub fn layout_paged(document: &Document) -> Option<Self> {
let (nodes, owners, node_items) = document_nodes(document)?;
Self::layout_paged_from_nodes(document, &nodes, &owners, &node_items, 0)
}
fn layout_paged_from_nodes(
document: &Document,
nodes: &[VerticalNode],
owners: &[usize],
node_items: &[VerticalItem],
start_node: usize,
) -> Option<Self> {
if let Some(source) = &document.output_routine {
let program = output::OutputProgram::parse(source).ok()?;
let plain = document.insertion_classes.is_empty()
@@ -3527,7 +3649,11 @@ impl Engine {
};
let mut pages = Vec::new();
let mut held: BTreeMap<u8, Vec<VerticalItem>> = BTreeMap::new();
let mut fragments = builder.build_with_deferred_bottom_floats(&nodes);
let mut fragments = if start_node == 0 {
builder.build_with_deferred_bottom_floats(nodes)
} else {
builder.build_from(nodes, start_node)
};
let mut carried_marks: Vec<(u8, String)> = Vec::new();
let mut page_index = 0;
while page_index < fragments.len() {
@@ -3605,7 +3731,7 @@ impl Engine {
}
}
Self::set_page_glue(&mut items, fragment);
Self::set_page_glue(&mut items, fragment, document);
let mut page = Page::empty();
page.items = items;
if !carried_marks.is_empty() {
@@ -3740,6 +3866,7 @@ impl Engine {
recomputed_pages: 0,
changed_pages: (0..count).collect(),
paged_page_nodes,
paged_unit_hashes: paged_unit_hashes(document, node_items, owners),
},
})
}
@@ -3800,7 +3927,24 @@ impl Engine {
}
/// Distribute the page's glue-setting amount over its vertical glue.
fn set_page_glue(items: &mut [VerticalItem], fragment: &PageFragment) {
fn set_page_glue(items: &mut Vec<VerticalItem>, fragment: &PageFragment, document: &Document) {
if let Some((index, height)) = items.iter().enumerate().find_map(|(index, item)| {
let height = match item {
VerticalItem::Paragraph(p) => p.height - p.depth,
VerticalItem::Math { height, .. }
| VerticalItem::Rule { height, .. }
| VerticalItem::Image { height, .. } => *height,
VerticalItem::Box(b) => b.height,
VerticalItem::Halign(h) => h.height,
_ => return None,
};
Some((index, height))
}) {
let skip = (document.top_skip - height).max(0);
if skip > 0 {
items.insert(index, VerticalItem::Glue(skip));
}
}
if fragment.set == 0 {
return;
}
@@ -3882,7 +4026,7 @@ impl Engine {
other => items.push(other.clone()),
}
}
Self::set_page_glue(&mut items, &fragment);
Self::set_page_glue(&mut items, &fragment, document);
let mut page = Page::empty();
page.items = items;
page.marks = marks;
@@ -3947,6 +4091,7 @@ impl Engine {
recomputed_pages: 0,
changed_pages: (0..count).collect(),
paged_page_nodes: Vec::new(),
paged_unit_hashes: Vec::new(),
},
})
}
@@ -3978,7 +4123,7 @@ impl Engine {
page.sources.push((unit.id, source_hash(&unit.source)));
}
}
Self::set_page_glue(&mut page.items, fragment);
Self::set_page_glue(&mut page.items, fragment, document);
page.seal_in_place();
page
})
@@ -4002,11 +4147,19 @@ impl Engine {
.iter()
.any(|node| matches!(node, VerticalNode::BottomFloat { .. }))
{
// A bottom float that did not fit is carried on the fragment, and a
// suffix rebuild starting from a page boundary cannot recover that
// queue. Rebuild the whole paged document instead of misplacing it.
// Deferred bottom floats need their queue at the replay boundary.
return false;
}
let unit_hashes = paged_unit_hashes(document, &node_items, &owners);
if self.layout.paged_unit_hashes.is_empty() {
return false;
}
let unit_index = unit_hashes
.iter()
.zip(&self.layout.paged_unit_hashes)
.take(unit_index)
.position(|(new, old)| new != old)
.unwrap_or(unit_index);
let Some(mut first_node) = owners.iter().position(|owner| *owner >= unit_index) else {
return false;
};
@@ -4040,7 +4193,19 @@ impl Engine {
return false;
}
let fragments = Self::paged_builder(document).build_from(&nodes, start_node);
let rebuilt = Self::paged_pages(document, &owners, &node_items, &fragments);
let rebuilt = if nodes[start_node..]
.iter()
.any(|node| matches!(node, VerticalNode::Insertion { .. }))
{
let Some(engine) =
Self::layout_paged_from_nodes(document, &nodes, &owners, &node_items, start_node)
else {
return false;
};
engine.layout.pages
} else {
Self::paged_pages(document, &owners, &node_items, &fragments)
};
let previous = std::mem::take(&mut self.layout.pages);
let prefix = page_index.min(previous.len());
let mut pages: Vec<Page> = previous[..prefix].to_vec();
@@ -4061,6 +4226,7 @@ impl Engine {
recomputed_pages,
changed_pages,
paged_page_nodes,
paged_unit_hashes: unit_hashes,
};
true
}
@@ -4612,6 +4778,7 @@ impl Engine {
recomputed_pages: rebuilt,
changed_pages,
paged_page_nodes: Vec::new(),
paged_unit_hashes: Vec::new(),
};
}
}
@@ -4802,28 +4969,18 @@ mod tests {
#[test]
fn math_symbol_paints_with_the_cmsy_face() {
use crate::render::{DisplayItem, FontFace};
let document = Document::new(
1_000_000,
vec![Unit::math(
1,
crate::math::parse_math("\\times"),
&Cmr10Metrics::Math,
)],
);
let engine = Engine::layout(&document);
let unit = Unit::math(1, crate::math::parse_math(r"\times"), &Cmr10Metrics::Math);
let engine = Engine::layout(&Document::new(1_000_000, vec![unit]));
let list = engine.pages()[0].display_list();
let symbols: Vec<(String, FontFace)> = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Text { text, font, .. } if text == "\u{00D7}" => {
Some((text.clone(), *font))
}
_ => None,
})
.collect();
assert_eq!(symbols, vec![("\u{00D7}".to_owned(), FontFace::MathSymbol)]);
assert!(list.items.iter().any(|item| matches!(
item,
DisplayItem::MathGlyph {
character: '×',
face: crate::math_font::MathFontId(6),
slot: 3,
..
}
)));
}
#[test]
@@ -6103,6 +6260,7 @@ mod tests {
&document,
1000 * scale,
vec![VerticalItem::Math {
geometry: None,
atom: crate::math::MathAtom::Symbol('x'),
width: scale,
height: 20 * scale,
@@ -6694,6 +6852,8 @@ mod tests {
height: 792 * 65_536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
};
list.special("0.5 g 10 10 20 20 re f");
let pdf = crate::pdf::display_list_to_pdf(&list, 792 * 65_536);
@@ -6880,6 +7040,8 @@ mod tests {
height: 792 * 65_536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
};
list.link(
72 * 65_536,
@@ -6902,6 +7064,8 @@ mod tests {
height: 792 * 65_536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
};
let index = list.add_image(PdfImage {
width: 1,
@@ -7506,7 +7670,7 @@ mod tests {
let texts = list
.items
.iter()
.filter(|item| matches!(item, DisplayItem::Text { .. }))
.filter(|item| matches!(item, DisplayItem::MathGlyph { .. }))
.count();
assert!(texts >= 4, "expected sum plus both limits, got {texts}");
}
@@ -7522,7 +7686,7 @@ mod tests {
let text = list
.items
.iter()
.filter(|item| matches!(item, DisplayItem::Text { .. }))
.filter(|item| matches!(item, DisplayItem::MathGlyph { .. }))
.count();
let rules = list
.items
@@ -7578,30 +7742,23 @@ mod tests {
#[test]
fn big_operators_paint_with_the_cmex_face() {
let atom = crate::math::parse_math("\\sum_{i=1}^{n}");
let document = Document::new(
400,
vec![Unit::math(1, atom, &crate::cmr10::Cmr10Metrics::new())],
let unit = Unit::math(
1,
crate::math::parse_math(r"\sum_{i=1}^{n}"),
&Cmr10Metrics::Math,
);
let engine = Engine::layout(&document);
let engine = Engine::layout(&Document::new(1_000_000, vec![unit]));
let list = engine.pages()[0].display_list();
let item = list
.items
.iter()
.find(|item| {
matches!(
item,
DisplayItem::Text {
font: crate::render::FontFace::MathExtension,
..
}
)
})
.expect("sum should use the CMEX face");
if let DisplayItem::Text { text, .. } = item {
assert_eq!(text, "\u{2211}");
}
assert!(list.to_svg().contains('\u{2211}'));
assert!(list.items.iter().any(|item| matches!(
item,
DisplayItem::MathGlyph {
character: '∑',
face: crate::math_font::MathFontId(9),
slot: 88,
..
}
)));
assert!(list.to_svg().contains("data-font=\"CMEX10\""));
}
#[test]
@@ -8985,6 +9142,7 @@ b & 2 \\
Unit::rule(3, 100, 40),
];
let mut document = Document::new(120, units);
document.units.push(Unit::penalty(4, -10_000));
let ragged = Engine::layout_paged(&document).expect("paged");
let rule_ys = |engine: &Engine| {
engine.pages()[0]
@@ -9320,9 +9478,9 @@ b & 2 \\
#[test]
fn paged_layout_inserts_par_skip_between_paragraphs() {
let mut style = ParagraphStyle::default();
style.line_height = 30;
style.line_height = 30 * 65_536;
let mut document = Document::new(
60,
60 * 65_536,
vec![
Unit::paragraph_with_style(1, "one", style.clone()),
Unit::paragraph_with_style(2, "two", style),
@@ -9336,7 +9494,7 @@ b & 2 \\
1
);
document.par_skip = 10;
document.par_skip = 30 * 65_536;
let engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable");
assert_eq!(engine.pages().len(), 2);
assert!(matches!(
@@ -9426,6 +9584,7 @@ b & 2 \\
id: 1,
source: String::new(),
items: vec![VerticalItem::Math {
geometry: None,
atom: crate::math::MathAtom::Symbol('x'),
width: 10,
height: 70,
@@ -9452,8 +9611,8 @@ b & 2 \\
let capped = Engine::layout_paged(&document).expect("math is page-buildable");
assert_eq!(
capped.pages().len(),
1,
"allowed depth keeps the rule on the first page"
2,
"following glue consumes the retained depth; it cannot erase it"
);
}
@@ -9584,6 +9743,7 @@ b & 2 \\
id: 1,
source: String::new(),
items: vec![VerticalItem::Math {
geometry: None,
atom: crate::math::MathAtom::Symbol('x'),
width: 10,
height: 500_000,
@@ -10090,6 +10250,12 @@ b & 2 \\
engine.edit(&document, 3, "epsilon");
assert_eq!(engine.pages()[0].hash, first);
assert!(engine.recomputed_pages() < 4);
let mut edited = document.clone();
edited.units[2] = paragraph(3, "epsilon");
assert_eq!(
engine.pages(),
Engine::layout_paged(&edited).unwrap().pages()
);
}
#[test]
@@ -10163,7 +10329,7 @@ b & 2 \\
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let document = Document::new(
let mut document = Document::new(
16 * 65_536,
vec![
Unit::paragraph_with_style_and_face(
@@ -10184,6 +10350,7 @@ b & 2 \\
Unit::paragraph_with_style_and_face(3, "gamma delta", style, ParagraphFont::Roman),
],
);
document.units.swap(0, 1);
let mut engine = Engine::layout_paged(&document).expect("insertions are page-buildable");
let pages = engine.pages().len();
engine.edit(&document, 3, "epsilon zeta");