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

+446 -33
View File
@@ -42,6 +42,25 @@ pub enum FontFace {
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DisplayItem {
NativeGlyph {
x: i64,
y: i64,
size: i64,
character: char,
slot: u8,
font: std::sync::Arc<crate::native_font::NativeFont>,
paint: Option<std::sync::Arc<crate::native_font::NativeFontPaint>>,
},
/// A native math glyph. `face` preserves the optical master independently
/// of the painted size; `slot` preserves CMEX next-larger selection.
MathGlyph {
x: i64,
y: i64,
size: i64,
character: char,
face: crate::math_font::MathFontId,
slot: u8,
},
Text {
x: i64,
y: i64,
@@ -69,6 +88,14 @@ pub enum DisplayItem {
height: i64,
index: usize,
},
PdfImage {
x: i64,
y: i64,
width: i64,
height: i64,
image: std::sync::Arc<crate::pdf_image::PdfImageUse>,
},
PdfImageObject(crate::pdf_image::PdfImageObject),
Rect {
x: i64,
y: i64,
@@ -95,9 +122,70 @@ pub enum DisplayItem {
Background([u8; 3]),
/// Switch the fill colour for following text (RGB).
Fill([u8; 3]),
PdfColor(std::sync::Arc<crate::pdf_device::PdfColorProgram>),
PdfGraphics {
x: i64,
y: i64,
operation: crate::pdf_device::PdfGraphics,
},
Special(String),
}
#[derive(PartialEq, Eq)]
struct NativeSvgGlyph<'a> {
position: [i64; 2],
size: i64,
slot: u8,
font: &'a str,
glyph: &'a str,
path: &'a str,
type1: bool,
}
impl DisplayItem {
fn native_svg_glyph(&self) -> Option<Result<NativeSvgGlyph<'_>, String>> {
let Self::NativeGlyph {
x,
y,
size,
slot,
font,
paint,
..
} = self
else {
return None;
};
Some((|| {
let paint = paint
.as_ref()
.ok_or_else(|| format!("native font {} has not been resolved", font.name))?;
let path = paint
.glyph_paths
.get(slot)
.filter(|_| paint.encoding.len() == 256)
.ok_or_else(|| {
format!(
"native Type1 SVG outline is not resolved for {} slot {slot}",
font.name
)
})?;
Ok(NativeSvgGlyph {
position: [*x, *y],
size: *size,
slot: *slot,
font: paint.program.name(),
glyph: &paint.encoding[usize::from(*slot)],
path,
type1: matches!(
paint.program,
crate::native_font::NativeFontProgram::Type1(_)
),
})
})())
}
}
/// A raster image carried by a vertical item, with its pixel data.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RasterImage {
@@ -127,15 +215,77 @@ fn flush_link(run: &mut Option<(String, i64, i64, i64, i64)>, items: &mut Vec<Di
}
/// A page-local list of drawing primitives.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DisplayUnits {
#[default]
PostScript,
TeX,
}
impl DisplayUnits {
pub fn bp(self, value: i64) -> f64 {
value as f64 / 65536.0
* if self == Self::TeX {
800.0 / 803.0
} else {
1.0
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayList {
pub width: i64,
pub height: i64,
pub items: Vec<DisplayItem>,
/// Paint-order indices into `items`; absent entries have unknown origin.
pub sources: std::collections::BTreeMap<usize, crate::provenance::PaintSource>,
pub images: Vec<PdfImage>,
/// A common physical transform for preview/PDF, without altering fonts or
/// logical TeX geometry. 1000 is unit magnification.
pub magnification: i32,
pub units: DisplayUnits,
pub pdf: Option<crate::pdf_device::PdfPageData>,
}
impl Default for DisplayList {
fn default() -> Self {
Self {
width: 0,
height: 0,
items: Vec::new(),
sources: Default::default(),
images: Vec::new(),
magnification: 1000,
units: DisplayUnits::PostScript,
pdf: None,
}
}
}
impl DisplayList {
/// Whether this page needs the complete PDF device output for SVG preview.
pub fn has_embedded_pdf(&self) -> bool {
self.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
}
/// Compare the inputs consumed by SVG rendering. Font data for glyphs not
/// present on this page and source locations do not affect its SVG.
pub fn same_svg_paint(&self, other: &Self) -> bool {
self.width == other.width
&& self.height == other.height
&& self.units == other.units
&& self.magnification == other.magnification
&& self.images == other.images
&& self.items.len() == other.items.len()
&& self.items.iter().zip(&other.items).all(|(left, right)| {
match (left.native_svg_glyph(), right.native_svg_glyph()) {
(Some(Ok(left)), Some(Ok(right))) => left == right,
(None, None) => left == right,
_ => false,
}
})
}
pub fn push(&mut self, item: DisplayItem) {
self.items.push(item);
}
@@ -163,7 +313,9 @@ impl DisplayList {
pub fn place(&mut self, dx: i64, dy: i64) {
for item in &mut self.items {
match item {
DisplayItem::Text { x, y, .. } => {
DisplayItem::Text { x, y, .. }
| DisplayItem::MathGlyph { x, y, .. }
| DisplayItem::NativeGlyph { x, y, .. } => {
*x += dx;
*y += dy;
}
@@ -180,26 +332,119 @@ impl DisplayList {
DisplayItem::Rect { x, y, .. }
| DisplayItem::Frame { x, y, .. }
| DisplayItem::Image { x, y, .. }
| DisplayItem::PdfImage { x, y, .. }
| DisplayItem::PdfGraphics { x, y, .. }
| DisplayItem::Link { x, y, .. } => {
*x += dx;
*y += dy;
}
DisplayItem::Fill(_) | DisplayItem::Background(_) => {}
DisplayItem::Special(_) => {}
DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor(_) => {}
DisplayItem::Special(_) | DisplayItem::PdfImageObject(_) => {}
}
}
}
/// Render the list as a standalone SVG document, in PostScript points.
pub fn to_svg(&self) -> String {
self.try_to_svg()
.expect("SVG display list cannot be rendered")
}
pub fn try_to_svg(&self) -> Result<String, String> {
if !(1..=32768).contains(&self.magnification) {
return Err("invalid display-list magnification".into());
}
for item in &self.items {
if matches!(item, DisplayItem::PdfImage { .. }) {
return Err("embedded PDF page requires a PDF renderer".into());
}
if let Some(glyph) = item.native_svg_glyph() {
glyph?;
}
}
Ok(self.svg_with_resolved_fonts())
}
fn svg_with_resolved_fonts(&self) -> String {
let width = self.width as f64 / 65_536.0;
let height = self.height as f64 / 65_536.0;
let mag = f64::from(self.magnification) / 1000.0
* if self.units == DisplayUnits::TeX {
800.0 / 803.0
} else {
1.0
};
let (physical_width, physical_height) = (width * mag, height * mag);
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=\"{physical_width:.3}pt\" height=\"{physical_height:.3}pt\" viewBox=\"0 0 {physical_width:.3} {physical_height:.3}\">\n"
);
if self.magnification != 1000 || self.units == DisplayUnits::TeX {
out.push_str(&format!("<g transform=\"scale({mag:.12})\">\n"));
}
let glyphs: std::collections::BTreeSet<_> = self
.items
.iter()
.filter_map(|item| match item {
DisplayItem::MathGlyph { face, slot, .. } => Some((*face, *slot)),
_ => None,
})
.collect();
if !glyphs.is_empty() {
out.push_str("<defs>\n");
for (face, slot) in glyphs {
out.push_str(&format!(
"<path id=\"math-{}-{slot}\" d=\"{}\"/>\n",
face.0,
face.svg_path(slot)
));
}
out.push_str("</defs>\n");
}
let mut fill = [0u8, 0, 0];
let mut rule_fill = [0u8; 3];
let mut stroke = [0u8; 3];
let mut graphics = Vec::new();
let mut open_transforms = 0;
for item in &self.items {
match item {
DisplayItem::NativeGlyph { .. } => {
let NativeSvgGlyph {
position: [x, y],
size,
slot,
font,
glyph,
path,
type1,
} = item
.native_svg_glyph()
.unwrap()
.expect("resolved native SVG glyph");
let x = x as f64 / 65_536.0;
let y = y as f64 / 65_536.0;
let scale = size as f64 / 65_536_000.0;
let label = if type1 {
crate::type1::glyph_unicode_text(glyph).unwrap_or_default()
} else {
String::new()
};
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
}
DisplayItem::MathGlyph {
x,
y,
size,
character,
face,
slot,
} => {
let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0;
let scale = *size as f64 / 65_536_000.0;
out.push_str(&format!(
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
face.name(), escape(&character.to_string()), face.0,
fill[0], fill[1], fill[2], escape(&character.to_string())
));
}
DisplayItem::Background(color) => {
let width = self.width as f64 / 65_536.0;
let height = self.height as f64 / 65_536.0;
@@ -292,8 +537,14 @@ impl DisplayList {
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
let color = if rule_fill == [0; 3] {
"black".to_owned()
} else {
let [r, g, b] = rule_fill;
format!("#{r:02x}{g:02x}{b:02x}")
};
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=\"{color}\"/>\n"
));
}
// Link annotations are PDF metadata; the SVG preview omits them.
@@ -325,6 +576,47 @@ impl DisplayList {
escape(content)
));
}
DisplayItem::PdfColor(program) => {
if let Some(rgb) = program.fill {
fill = rgb;
rule_fill = rgb;
}
if let Some(rgb) = program.stroke {
stroke = rgb;
}
}
DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics;
match operation {
PdfGraphics::Save => {
graphics.push((open_transforms, fill, rule_fill, stroke));
}
PdfGraphics::Matrix(matrix) => {
let [a, b, c, d, e, f] = matrix
.about(*x as f64 / 65_536.0, *y as f64 / 65_536.0, true)
.0;
out.push_str(&format!(
"<g transform=\"matrix({a} {b} {c} {d} {e} {f})\">\n"
));
open_transforms += 1;
}
PdfGraphics::Restore { shift: [dx, dy] } => {
if let Some((depth, old_fill, old_rule, old_stroke)) = graphics.pop() {
for _ in depth..open_transforms {
out.push_str("</g>\n");
}
(open_transforms, fill, rule_fill, stroke) =
(depth, old_fill, old_rule, old_stroke);
}
if *dx != 0 || *dy != 0 {
let dx = *dx as f64 / 65_536.0;
let dy = *dy as f64 / 65_536.0;
out.push_str(&format!("<g transform=\"translate({dx} {dy})\">\n"));
open_transforms += 1;
}
}
}
}
DisplayItem::Line {
x1,
y1,
@@ -337,10 +629,13 @@ impl DisplayList {
let x2 = *x2 as f64 / 65_536.0;
let y2 = *y2 as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let [r, g, b] = stroke;
out.push_str(&format!(
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#000000\" stroke-width=\"{width:.3}\"/>\n"
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"/>\n"
));
}
DisplayItem::PdfImage { .. } => unreachable!("checked before SVG export"),
DisplayItem::PdfImageObject(_) => {}
DisplayItem::Image {
x,
y,
@@ -367,6 +662,12 @@ impl DisplayList {
}
}
}
for _ in 0..open_transforms {
out.push_str("</g>\n");
}
if self.magnification != 1000 || self.units == DisplayUnits::TeX {
out.push_str("</g>\n");
}
out.push_str("</svg>\n");
out
}
@@ -512,6 +813,8 @@ impl Halign {
height: self.height,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
};
let mut y = 0_i64;
for (row_index, row) in self.rows.iter().enumerate() {
@@ -745,19 +1048,30 @@ impl Page {
y += *height;
}
VerticalItem::Glue(height) => {
y += (*height).max(0);
y += *height;
}
VerticalItem::StretchGlue(glue) => {
y += glue.width.max(0);
y += glue.width;
}
VerticalItem::Math {
atom,
geometry,
height,
depth,
..
} => {
let font = Cmr10Metrics::new();
Self::paint_math(atom, &font, 0, y + *height, 655_360, &mut list.items);
if let Some(geometry) = geometry {
Self::paint_math_geometry(
geometry,
0,
y + *height,
655_360,
&mut list.items,
);
} else {
let font = Cmr10Metrics::new();
Self::paint_math(atom, &font, 0, y + *height, 655_360, &mut list.items);
}
y += *height + *depth;
}
VerticalItem::Paragraph(paragraph) => {
@@ -852,7 +1166,35 @@ impl Page {
let x0_math = |value: i64, positioned: &dyn Fn(i64) -> i64| {
x + positioned(value)
};
if let Some(native) = &box_.native_box {
native.paint_display(x, glyph_y, &mut list.items);
x += box_.width;
continue;
}
if box_.math.is_none()
&& let Some(g) = &box_.math_geometry
{
crate::execution::paint_native_math(
g,
x,
glyph_y,
&mut list.items,
);
x += box_.width;
continue;
}
if let Some(math) = &box_.math {
if let Some(geometry) = &box_.math_geometry {
Self::paint_math_geometry(
geometry,
x,
glyph_y,
glyph_size,
&mut list.items,
);
x += box_.width;
continue;
}
let math_font = Cmr10Metrics::default();
let mut raw = Vec::new();
Self::paint_math(math, &math_font, 0, 0, 655_360, &mut raw);
@@ -1080,6 +1422,63 @@ impl Page {
}
}
fn paint_math_geometry(
geometry: &crate::math_engine_tex::MathGeometry,
x: i64,
baseline: i64,
size: i64,
list: &mut Vec<DisplayItem>,
) {
use crate::math_engine_tex::MathItem;
let scaled = |v: i64| math::math_output_dimension(v * size / 655_360);
for position in &geometry.items {
let x = x + scaled(position.x);
let y = baseline + scaled(position.y);
list.push(match &position.item {
MathItem::NativeGlyph {
font,
slot,
size,
character,
} => DisplayItem::NativeGlyph {
x,
y,
size: scaled(*size),
font: font.clone(),
slot: *slot,
character: *character,
paint: None,
},
MathItem::Glyph {
character,
font,
slot,
size: design_size,
} => DisplayItem::MathGlyph {
x,
y,
size: scaled(*design_size),
character: *character,
slot: *slot,
face: crate::math_font::MathFontId::new(*font, *design_size),
},
MathItem::Rule { width, height } => DisplayItem::Rule {
x,
y,
width: scaled(*width),
height: scaled(*height),
},
MathItem::PdfImage(image) => DisplayItem::PdfImage {
x,
y: y - scaled(image.height),
width: scaled(image.width),
height: scaled(image.height + image.depth),
image: image.clone(),
},
});
}
}
fn paint_math(
atom: &MathAtom,
font: &Cmr10Metrics,
@@ -1089,6 +1488,20 @@ impl Page {
list: &mut Vec<DisplayItem>,
) {
match atom {
MathAtom::Style(_) | MathAtom::MuSpace(_) => {}
MathAtom::Styled { body, .. } => Self::paint_math(body, font, x, baseline, size, list),
MathAtom::ForcedLimits { base, sub, sup } => Self::paint_math(
&MathAtom::Limits {
base: base.clone(),
sub: sub.clone(),
sup: sup.clone(),
},
font,
x,
baseline,
size,
list,
),
MathAtom::Space(_) => {}
MathAtom::Symbol(character) => {
if !character.is_whitespace() {
@@ -1170,7 +1583,7 @@ impl Page {
MathAtom::Row(atoms) => {
let mut cursor = x;
for child in atoms {
let width = math::layout_math(child, font).width;
let width = math::legacy_layout_math(child, font).width;
Self::paint_math(child, font, cursor, baseline, size, list);
cursor += width;
}
@@ -1214,7 +1627,7 @@ impl Page {
}
}
MathAtom::Tagged { body, tag } => {
let body_box = math::layout_math(body, font);
let body_box = math::legacy_layout_math(body, font);
Self::paint_math(body, font, x, baseline, size, list);
let tag_width: i64 = tag
.chars()
@@ -1234,7 +1647,7 @@ impl Page {
}
}
MathAtom::TaggedWidth { body, tag, width } => {
let body_box = math::layout_math(body, font);
let body_box = math::legacy_layout_math(body, font);
let body_x = x + ((*width - body_box.width) / 2).max(0);
Self::paint_math(body, font, body_x, baseline, size, list);
let tag_width: i64 = tag
@@ -1255,7 +1668,7 @@ impl Page {
}
}
MathAtom::Script { base, sub, sup } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
let italic = math::italic_correction(base, font);
let small = (size as f64 * 0.7) as i64;
@@ -1286,8 +1699,8 @@ impl Page {
denominator,
bar,
} => {
let num = math::layout_math(numerator, font);
let den = math::layout_math(denominator, font);
let num = math::legacy_layout_math(numerator, font);
let den = math::legacy_layout_math(denominator, font);
let clearance = 2 * 65_536;
let rule_width = num.width.max(den.width) + clearance;
let bar_y = baseline - clearance;
@@ -1317,11 +1730,11 @@ impl Page {
);
}
MathAtom::Sqrt { radicand, degree } => {
let box_ = math::layout_math(radicand, font);
let box_ = math::legacy_layout_math(radicand, font);
let small = (size as f64 * 0.7) as i64;
let mut radical_x = x;
if let Some(degree) = degree {
let degree_box = math::layout_math(degree, font);
let degree_box = math::legacy_layout_math(degree, font);
Self::paint_math(degree, font, x, baseline - box_.height - small, small, list);
radical_x += degree_box.width;
}
@@ -1341,7 +1754,7 @@ impl Page {
});
}
MathAtom::Delimited { left, right, body } => {
let body_box = math::layout_math(body, font);
let body_box = math::legacy_layout_math(body, font);
let delta = body_box.height + body_box.depth;
let left_box = math::select_delimiter(*font, *left, delta);
let right_box = math::select_delimiter(*font, *right, delta);
@@ -1476,7 +1889,7 @@ impl Page {
}
}
MathAtom::Accent { accent, base } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
list.push(DisplayItem::Text {
font: FontFace::Roman,
@@ -1487,7 +1900,7 @@ impl Page {
});
}
MathAtom::Underline { base } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
list.push(DisplayItem::Rule {
x,
@@ -1501,7 +1914,7 @@ impl Page {
forward,
backward,
} => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
if *forward {
list.push(DisplayItem::Line {
@@ -1523,7 +1936,7 @@ impl Page {
}
}
MathAtom::Negated { base } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
list.push(DisplayItem::Line {
x1: x,
@@ -1534,7 +1947,7 @@ impl Page {
});
}
MathAtom::Boxed { body } => {
let body_box = math::layout_math(body, font);
let body_box = math::legacy_layout_math(body, font);
Self::paint_math(body, font, x + 65_536, baseline, size, list);
list.push(DisplayItem::Rule {
x,
@@ -1570,8 +1983,8 @@ impl Page {
}
MathAtom::Stack { top, base, above } => {
Self::paint_math(base, font, x, baseline, size, list);
let base_box = math::layout_math(base, font);
let top_box = math::layout_math(top, font);
let base_box = math::legacy_layout_math(base, font);
let top_box = math::legacy_layout_math(top, font);
Self::paint_math(
top,
font,
@@ -1586,11 +1999,11 @@ impl Page {
);
}
MathAtom::Limits { base, sub, sup } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
let small = (size as f64 * 0.7) as i64;
if let Some(sup) = sup {
let sup_box = math::script_metrics(math::layout_math(sup, font));
let sup_box = math::script_metrics(math::legacy_layout_math(sup, font));
let sup_gap = if Self::large_operator(base) {
-96_993
} else {
@@ -1606,7 +2019,7 @@ impl Page {
);
}
if let Some(sub) = sub {
let sub_box = math::script_metrics(math::layout_math(sub, font));
let sub_box = math::script_metrics(math::legacy_layout_math(sub, font));
Self::paint_math(
sub,
font,
@@ -1627,7 +2040,7 @@ impl Page {
}
}
MathAtom::Brace { base, above } => {
let base_box = math::layout_math(base, font);
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
let thickness = (size / 8).max(1);
let y = if *above {
@@ -1658,8 +2071,8 @@ impl Page {
numerator,
denominator,
} => {
let num = math::layout_math(numerator, font);
let den = math::layout_math(denominator, font);
let num = math::legacy_layout_math(numerator, font);
let den = math::legacy_layout_math(denominator, font);
let width = num.width.max(den.width);
let bracket = (size as f64 * 1.2) as i64;
Self::paint_math(