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

2497 lines
102 KiB
Rust
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! A small display-list painter for route-D layout output.
//!
//! This is deliberately independent from v1's `DocumentModel` renderer. It
//! 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
//! wired up.
use crate::cmr10::Cmr10Metrics;
use crate::math::{self, MathAtom, MathColumnAlign};
use crate::paragraph::ParagraphFont;
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
/// One absolute drawing primitive in scaled points.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FontFace {
Roman,
Bold,
Italic,
BoldItalic,
Mono,
Sans,
/// Computer Modern math italic (`cmmi10`).
MathItalic,
/// Computer Modern math symbols (`cmsy10`), addressed by TeX slot.
MathSymbol,
/// Computer Modern math extensions (`cmex10`), addressed by TeX slot.
MathExtension,
/// Computer Modern blackboard bold (`msbm10`).
MathBlackboard,
/// Euler Fraktur (`eufm10`).
MathFraktur,
/// Computer Modern sans-serif bold (`cmssbx10`).
SansBold,
/// Computer Modern sans-serif italic (`cmssi10`).
SansItalic,
/// Computer Modern roman small caps (`cmcsc10`).
SmallCaps,
Slanted,
BoldSlanted,
MonoItalic,
}
#[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>>,
},
OpenTypeGlyph {
x: i64,
y: i64,
size: i64,
advance: i64,
font: std::sync::Arc<crate::opentype::OpenTypeFont>,
glyph: u16,
text: String,
},
/// Word-level PDF replacement text. None closes the current word.
OpenTypeActualText(Option<String>),
/// Word-local font color and alpha. None restores the surrounding paint.
OpenTypeColor(Option<[u8; 4]>),
/// 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,
size: i64,
text: String,
font: FontFace,
},
Rule {
x: i64,
y: i64,
width: i64,
height: i64,
},
Line {
x1: i64,
y1: i64,
x2: i64,
y2: i64,
width: i64,
},
Image {
x: i64,
y: i64,
width: i64,
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),
PdfForm {
x: i64,
y: i64,
form: crate::pdf_device::forms::FormUse,
},
Rect {
x: i64,
y: i64,
width: i64,
height: i64,
color: [u8; 3],
},
Frame {
x: i64,
y: i64,
width: i64,
height: i64,
color: [u8; 3],
thickness: i64,
},
Link {
x: i64,
y: i64,
width: i64,
height: i64,
url: String,
},
/// Fill the whole page with a background colour (RGB).
Background([u8; 3]),
/// Switch the fill colour for following text (RGB).
Fill([u8; 3]),
PdfColor {
x: i64,
y: i64,
program: std::sync::Arc<crate::pdf_device::PdfColorProgram>,
mode: crate::pdf_device::PdfLiteralMode,
},
PdfGraphics {
x: i64,
y: i64,
operation: crate::pdf_device::PdfGraphics,
},
PdfTextSpace {
x: i64,
y: i64,
operation: crate::pdf_device::text_spaces::SpaceOperation,
},
Special(String),
}
#[derive(PartialEq, Eq)]
struct NativeSvgGlyph<'a> {
position: [i64; 2],
size: i64,
expansion: i32,
xdv_matrix: crate::native_font::XdvFontMatrix,
slot: u8,
font: &'a str,
glyph: &'a str,
path: &'a str,
scalable: 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(|| match &paint.program {
crate::native_font::NativeFontProgram::DeviceType1(program) => format!(
"native preview needs the actual device font {} with glyph {}",
program.name, paint.encoding.get(usize::from(*slot)).map_or(".notdef", String::as_str)
),
_ => format!("native SVG outline is not resolved for {} slot {slot}", font.name),
})?;
Ok(NativeSvgGlyph {
position: [*x, *y],
size: *size,
expansion: font.expansion,
xdv_matrix: paint.xdv_matrix,
slot: *slot,
font: paint.program.name(),
glyph: &paint.encoding[usize::from(*slot)],
path,
scalable: !matches!(
paint.program,
crate::native_font::NativeFontProgram::Pk(_)
),
})
})())
}
}
/// 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 {
pub width: u32,
pub height: u32,
pub rgb: Vec<u8>,
}
/// A raw RGB image that can be painted as a PDF XObject.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfImage {
pub width: u32,
pub height: u32,
pub rgb: Vec<u8>,
}
fn flush_link(run: &mut Option<(String, i64, i64, i64, i64)>, items: &mut Vec<DisplayItem>) {
if let Some((url, x, y, width, height)) = run.take() {
items.push(DisplayItem::Link {
x,
y,
width,
height,
url,
});
}
}
/// A page-local list of drawing primitives.
#[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>,
#[doc(hidden)]
pub forms: Vec<crate::pdf_device::forms::FormDisplay>,
/// Captured VF packets from native shipout, indexed by the raw display
/// item. None leaves lookup to a standalone renderer.
#[doc(hidden)]
pub prepared_virtual_glyphs: Option<std::collections::BTreeMap<usize, std::sync::Arc<Vec<crate::math_engine_tex::PositionedItem>>>>,
/// 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>,
#[doc(hidden)]
pub pdf_font_bindings: Option<std::sync::Arc<crate::native_font::PdfFontBindings>>,
pub pdf_links: crate::pdf_device::links::PageLinks,
pub pdf_background: Option<std::sync::Arc<crate::pdf_device::PdfColorProgram>>,
pub pdf_text_spaces: Option<crate::pdf_device::text_spaces::SpaceSettings>,
pub pdf_space_plan: Option<crate::pdf_device::text_spaces::SpacePlan>,
pub pdf_resources: crate::pdf_device::page_resources::PageResources,
}
impl Default for DisplayList {
fn default() -> Self {
Self {
width: 0,
height: 0,
items: Vec::new(),
forms: Vec::new(),
prepared_virtual_glyphs: None,
sources: Default::default(),
images: Vec::new(),
magnification: 1000,
units: DisplayUnits::PostScript,
pdf: None,
pdf_font_bindings: None,
pdf_links: Default::default(),
pdf_background: None,
pdf_text_spaces: None,
pdf_space_plan: None,
pdf_resources: Default::default(),
}
}
}
#[derive(Clone, Default)]
struct SvgTransparency {
fill: String,
stroke: String,
rule_stroke: String,
image: String,
}
impl SvgTransparency {
fn apply(&mut self, transparency: &crate::pdf_device::page_resources::Transparency) {
let attribute = |name, alpha: &str| {
if alpha == "1" {
String::new()
} else {
format!(" {name}=\"{alpha}\"")
}
};
if let Some(alpha) = &transparency.fill {
self.fill = attribute("fill-opacity", alpha);
self.image = attribute("opacity", alpha);
}
if let Some(alpha) = &transparency.stroke {
self.stroke = attribute("stroke-opacity", alpha);
self.rule_stroke = attribute("fill-opacity", alpha);
}
}
}
impl DisplayList {
/// Whether this page needs the complete PDF device output for SVG preview.
pub fn has_embedded_pdf(&self) -> bool {
self.pdf_resources.needs_pdf_for_preview
|| self
.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. } | DisplayItem::PdfForm { .. }
| DisplayItem::PdfGraphics {
operation: crate::pdf_device::PdfGraphics::Literal { .. },
..
}))
}
/// Physical size of one PDF user space unit, in big points.
pub fn pdf_user_unit(&self) -> f64 {
self.pdf_resources.viewport.as_ref().map_or(1.0, |viewport| viewport.unit())
}
fn svg_paint_items(&self) -> impl Iterator<Item = &DisplayItem> {
self.items
.iter()
.filter(|item| !matches!(item,
DisplayItem::PdfImageObject(_) | DisplayItem::OpenTypeActualText(_)))
}
/// 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 {
let mut right = other.svg_paint_items();
self.width == other.width
&& self.height == other.height
&& self.units == other.units
&& self.magnification == other.magnification
&& self.images == other.images
&& self.pdf_background == other.pdf_background
&& self.pdf_resources.opacity == other.pdf_resources.opacity
&& self.pdf_resources.viewport == other.pdf_resources.viewport
&& self.pdf_resources.needs_pdf_for_preview == other.pdf_resources.needs_pdf_for_preview
&& self.svg_paint_items().all(|left| {
let Some(right) = right.next() else {
return false;
};
match (left.native_svg_glyph(), right.native_svg_glyph()) {
(Some(Ok(left)), Some(Ok(right))) => left == right,
(None, None) => {
left == right || matches!((left, right),
(DisplayItem::PdfTextSpace { .. }, DisplayItem::PdfTextSpace { .. }))
}
_ => false,
}
})
&& right.next().is_none()
}
pub fn push(&mut self, item: DisplayItem) {
self.items.push(item);
}
pub fn special(&mut self, content: &str) {
self.items.push(DisplayItem::Special(content.to_string()));
}
pub fn link(&mut self, x: i64, y: i64, width: i64, height: i64, url: &str) {
self.items.push(DisplayItem::Link {
x,
y,
width,
height,
url: url.to_string(),
});
}
pub fn add_image(&mut self, image: PdfImage) -> usize {
self.images.push(image);
self.images.len() - 1
}
/// Offset every primitive, used when placing a nested table on a page.
pub fn place(&mut self, dx: i64, dy: i64) {
for item in &mut self.items {
match item {
DisplayItem::Text { x, y, .. }
| DisplayItem::MathGlyph { x, y, .. }
| DisplayItem::NativeGlyph { x, y, .. }
| DisplayItem::OpenTypeGlyph { x, y, .. } => {
*x += dx;
*y += dy;
}
DisplayItem::Rule { x, y, .. } => {
*x += dx;
*y += dy;
}
DisplayItem::Line { x1, y1, x2, y2, .. } => {
*x1 += dx;
*y1 += dy;
*x2 += dx;
*y2 += dy;
}
DisplayItem::Rect { x, y, .. }
| DisplayItem::Frame { x, y, .. }
| DisplayItem::Image { x, y, .. }
| DisplayItem::PdfImage { x, y, .. }
| DisplayItem::PdfForm { x, y, .. }
| DisplayItem::PdfGraphics { x, y, .. }
| DisplayItem::PdfTextSpace { x, y, .. }
| DisplayItem::Link { x, y, .. } => {
*x += dx;
*y += dy;
}
DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor { .. } => {}
DisplayItem::Special(_) | DisplayItem::PdfImageObject(_)
| DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_) => {}
}
}
}
/// 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());
}
if self.has_embedded_pdf() {
return Err("this page requires a PDF renderer".into());
}
for item in &self.items {
if let DisplayItem::PdfColor { program, .. } = item
&& program
.graphics_states
.iter()
.any(|name| !self.pdf_resources.opacity.contains_key(name))
{
return Err("unresolved PDF graphics state in SVG page".into());
}
if let Some(glyph) = item.native_svg_glyph() {
glyph?;
}
}
self.svg_with_resolved_fonts()
}
fn svg_with_resolved_fonts(&self) -> Result<String, 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 viewport = self.pdf_resources.viewport.as_ref();
let [physical_width, physical_height] = viewport
.map_or([width * mag, height * mag], |geometry| geometry.dimensions());
let mut out = format!(
"<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 let Some(viewport) = viewport {
let [a, b, c, d, e, f] = viewport.transform(height * mag).0;
out.push_str(&format!("<g transform=\"matrix({a} {b} {c} {d} {e} {f})\">\n"));
}
if self.magnification != 1000 || self.units == DisplayUnits::TeX {
out.push_str(&format!("<g transform=\"scale({mag:.12})\">\n"));
}
if let Some(color) = self.pdf_background.as_ref().and_then(|color| color.fill) {
let [r, g, b] = color;
out.push_str(&format!(
"<rect width=\"{width:.6}\" height=\"{height:.6}\" fill=\"#{r:02x}{g:02x}{b:02x}\"/>\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 opentype_paths = std::collections::BTreeMap::new();
let mut opentype_faces = std::collections::BTreeMap::new();
let mut fill = [0u8, 0, 0];
let mut rule_fill = [0u8; 3];
let mut opentype_color: Option<[u8; 4]> = None;
let mut stroke = [0u8; 3];
let mut transparency = SvgTransparency::default();
let mut graphics = Vec::new();
let mut open_transforms = 0;
for item in &self.items {
let fill_opacity = &transparency.fill;
let stroke_opacity = &transparency.stroke;
match item {
DisplayItem::NativeGlyph { .. } => {
let NativeSvgGlyph {
position: [x, y],
size,
expansion,
xdv_matrix,
slot,
font,
glyph,
path,
scalable,
} = 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 horizontal_scale = if expansion == 0 {
scale
} else {
scale * f64::from(1000 + expansion) / 1000.0
};
let label = if scalable {
crate::type1::glyph_unicode_text(glyph).unwrap_or_default()
} else {
String::new()
};
use std::fmt::Write as _;
write!(
out,
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"",
escape(font), escape(glyph), escape(&label), path,
).unwrap();
if xdv_matrix.is_identity() {
write!(out, "translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})").unwrap();
} else {
let [extend, slant] = xdv_matrix.coefficients();
write!(
out,
"matrix({:.8} 0 {:.8} -{scale:.8} {x:.5} {y:.5})",
horizontal_scale * extend,
scale * slant,
).unwrap();
}
writeln!(
out, "\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/></g>",
fill[0], fill[1], fill[2],
).unwrap();
}
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
let face = match opentype_faces.entry(font.id) {
std::collections::btree_map::Entry::Vacant(entry) => entry.insert(font.face()?),
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
};
let x = *x as f64 / 65536.;
let y = *y as f64 / 65536.;
let scale = *size as f64 / (65536. * f64::from(face.units_per_em()));
let [extend, slant] = font.paint_transform();
let embolden = font.paint_embolden();
let horizontal = scale * extend;
// Place the transformed outline in page units before
// stroking. The font matrix must not distort the stroke.
let vertical = font.is_vertical().then(|| {
font.vertical_paint_matrix(face, *glyph, *size as f64 / 65536.)
});
let transform = (embolden > 0.).then(|| {
vertical.unwrap_or([horizontal, 0., scale * slant, -scale, 0., 0.])
});
let path_size = if transform.is_some() { *size } else { 0 };
let path = opentype_paths.entry((font.id, *glyph, path_size))
.or_insert_with(|| crate::opentype::outline_matrix(face, *glyph, transform));
if !path.is_empty() {
use std::fmt::Write as _;
write!(
out,
"<g data-font=\"{}\" data-glyph=\"{glyph}\" aria-label=\"{}\"><path d=\"{path}\" transform=\"translate({x:.5} {y:.5})",
escape(&font.name), escape(text),
).unwrap();
if transform.is_none() {
if let Some([a, b, c, d, e, f]) = vertical {
write!(out, " matrix({a:.9} {b:.9} {c:.9} {d:.9} {e:.9} {f:.9})").unwrap();
} else if slant == 0. {
write!(out, " scale({horizontal:.9} -{scale:.9})").unwrap();
} else {
let shear = scale * slant;
write!(out, " matrix({horizontal:.9} 0 {shear:.9} -{scale:.9} 0 0)").unwrap();
}
}
let (fill, stroke, alpha) = match opentype_color {
Some([r, g, b, a]) => ([r, g, b], [r, g, b], Some(crate::opentype::color_alpha(a))),
None => (fill, stroke, None),
};
write!(
out, "\" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2],
).unwrap();
match alpha {
Some(alpha) if alpha < 1. => write!(out, " fill-opacity=\"{alpha}\"").unwrap(),
None => out.push_str(fill_opacity),
_ => {}
}
if embolden > 0. {
let stroke_width = embolden / self.units.bp(65536);
write!(
out,
" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{stroke_width:.9}\" stroke-miterlimit=\"10\"",
stroke[0], stroke[1], stroke[2],
).unwrap();
match alpha {
Some(alpha) if alpha < 1. => write!(out, " stroke-opacity=\"{alpha}\"").unwrap(),
None => out.push_str(stroke_opacity),
_ => {}
}
}
out.push_str("/></g>\n");
}
}
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}\"{fill_opacity}/><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;
out.push_str(&format!(
"<rect x=\"0\" y=\"0\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"#{:02x}{:02x}{:02x}\"/>\n",
color[0], color[1], color[2]
));
}
DisplayItem::Fill(color) => fill = *color,
DisplayItem::Text {
x,
y,
size,
text,
font,
} => {
let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0;
let size = *size as f64 / 65_536.0;
let family = if matches!(font, FontFace::Mono | FontFace::MonoItalic) {
"monospace"
} else if matches!(
font,
FontFace::Sans | FontFace::SansBold | FontFace::SansItalic
) {
"sans-serif"
} else {
"serif"
};
let weight = if matches!(
font,
FontFace::Bold
| FontFace::BoldItalic
| FontFace::SansBold
| FontFace::BoldSlanted
) {
" font-weight=\"bold\""
} else {
""
};
let style = if matches!(
font,
FontFace::Italic
| FontFace::BoldItalic
| FontFace::MathItalic
| FontFace::SansItalic
| FontFace::Slanted
| FontFace::BoldSlanted
| FontFace::MonoItalic
) {
" font-style=\"italic\""
} else {
""
};
let fill_attr = if fill == [0u8, 0, 0] {
String::new()
} else {
format!(" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2])
};
out.push_str(&format!(
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}{fill_opacity}>{}</text>\n",
escape(text)
));
}
DisplayItem::Rect {
x,
y,
width,
height,
color,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/>\n",
*x as f64 / 65_536.0,
*y as f64 / 65_536.0,
*width as f64 / 65_536.0,
*height as f64 / 65_536.0,
color[0],
color[1],
color[2]
));
}
DisplayItem::Rule {
x,
y,
width,
height,
} => {
let x = *x as f64 / 65_536.0;
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 stroked = self.units == DisplayUnits::TeX
&& (height <= 65_782.0 / 65_536.0 || width <= 65_782.0 / 65_536.0);
let (rgb, rule_alpha) = if stroked {
(stroke, &transparency.rule_stroke)
} else {
(rule_fill, fill_opacity)
};
let color = if rgb == [0; 3] {
"black".to_owned()
} else {
let [r, g, b] = rgb;
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=\"{color}\"{rule_alpha}/>\n"
));
}
// Link annotations are PDF metadata; the SVG preview omits them.
DisplayItem::Frame {
x,
y,
width,
height,
color,
thickness,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"{stroke_opacity}/>\n",
*x as f64 / 65_536.0,
(*y - *height) as f64 / 65_536.0,
*width as f64 / 65_536.0,
*height as f64 / 65_536.0,
color[0],
color[1],
color[2],
*thickness as f64 / 65_536.0
));
}
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. }
| DisplayItem::OpenTypeActualText(_) => {}
DisplayItem::OpenTypeColor(color) => opentype_color = *color,
DisplayItem::Special(content) => {
out.push_str(&format!(
"<!-- special: {} -->
",
escape(content)
));
}
DisplayItem::PdfColor { program, .. } => {
if let Some(rgb) = program.fill {
fill = rgb;
rule_fill = rgb;
}
if let Some(rgb) = program.stroke {
stroke = rgb;
}
for name in &program.graphics_states {
transparency.apply(&self.pdf_resources.opacity[name]);
}
}
DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics;
match operation {
PdfGraphics::TextBoundary => {}
PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) |
PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"),
PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"),
PdfGraphics::Save | PdfGraphics::Matrix(_) | PdfGraphics::SaveMatrix(_) => {
if matches!(operation, PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) {
graphics.push((
open_transforms,
fill,
rule_fill,
stroke,
transparency.clone(),
));
}
let (PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix)) = operation else {
continue;
};
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, old_alpha)) =
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);
transparency = old_alpha;
}
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,
x2,
y2,
width,
} => {
let x1 = *x1 as f64 / 65_536.0;
let y1 = *y1 as f64 / 65_536.0;
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=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"{stroke_opacity}/>\n"
));
}
DisplayItem::PdfImage { .. } => unreachable!("checked before SVG export"),
DisplayItem::PdfImageObject(_) | DisplayItem::PdfForm { .. } => {}
DisplayItem::Image {
x,
y,
width,
height,
index,
} => {
let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
if let Some(image) = self.images.get(*index)
&& image.width as u64 * image.height as u64 <= 4_000_000
{
let uri = png_data_uri(image);
let image_opacity = &transparency.image;
out.push_str(&format!(
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"{image_opacity}/>\n"
));
} else {
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"#cccccc\"/>\n"
));
}
}
}
}
for _ in 0..open_transforms {
out.push_str("</g>\n");
}
if self.magnification != 1000 || self.units == DisplayUnits::TeX {
out.push_str("</g>\n");
}
if viewport.is_some() {
out.push_str("</g>\n");
}
out.push_str("</svg>\n");
Ok(out)
}
}
fn png_data_uri(image: &PdfImage) -> String {
let png = encode_png(image.width, image.height, &image.rgb);
format!("data:image/png;base64,{}", base64(&png))
}
fn encode_png(width: u32, height: u32, rgb: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
let mut ihdr = Vec::with_capacity(13);
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
png_chunk(&mut out, b"IHDR", &ihdr);
let stride = width as usize * 3;
let mut raw = Vec::with_capacity((stride + 1) * height as usize);
for row in 0..height as usize {
raw.push(0);
let start = row * stride;
let end = start + stride;
if end <= rgb.len() {
raw.extend_from_slice(&rgb[start..end]);
} else {
raw.extend(std::iter::repeat_n(
255u8,
stride.saturating_sub(rgb.len().saturating_sub(start)),
));
}
}
let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
use std::io::Write as _;
encoder.write_all(&raw).expect("compress preview image");
let compressed = encoder.finish().expect("finish preview image");
png_chunk(&mut out, b"IDAT", &compressed);
png_chunk(&mut out, b"IEND", &[]);
out
}
fn png_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc_data = Vec::with_capacity(4 + data.len());
crc_data.extend_from_slice(kind);
crc_data.extend_from_slice(data);
out.extend_from_slice(&crc32(&crc_data).to_be_bytes());
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xffff_ffffu32;
for byte in data {
crc ^= u32::from(*byte);
for _ in 0..8 {
crc = if crc & 1 != 0 {
(crc >> 1) ^ 0xedb8_8320
} else {
crc >> 1
};
}
}
!crc
}
fn base64(data: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let a = chunk[0];
let b = chunk.get(1).copied().unwrap_or(0);
let c = chunk.get(2).copied().unwrap_or(0);
out.push(TABLE[(a >> 2) as usize] as char);
out.push(TABLE[(((a & 3) << 4) | (b >> 4)) as usize] as char);
out.push(if chunk.len() > 1 {
TABLE[(((b & 15) << 2) | (c >> 6)) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
TABLE[(c & 63) as usize] as char
} else {
'='
});
}
out
}
fn escape(text: &str) -> String {
text.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
fn paragraph_face(font: ParagraphFont) -> FontFace {
match font {
ParagraphFont::Roman => FontFace::Roman,
ParagraphFont::Bold => FontFace::Bold,
ParagraphFont::Italic => FontFace::Italic,
ParagraphFont::BoldItalic => FontFace::BoldItalic,
ParagraphFont::Mono => FontFace::Mono,
ParagraphFont::Sans => FontFace::Sans,
ParagraphFont::SansBold => FontFace::SansBold,
ParagraphFont::SansItalic => FontFace::SansItalic,
ParagraphFont::SmallCaps => FontFace::SmallCaps,
ParagraphFont::Slanted => FontFace::Slanted,
ParagraphFont::BoldSlanted => FontFace::BoldSlanted,
ParagraphFont::MonoItalic => FontFace::MonoItalic,
ParagraphFont::TimesRoman => FontFace::Roman,
ParagraphFont::TimesBold => FontFace::Bold,
ParagraphFont::TimesItalic => FontFace::Italic,
ParagraphFont::TimesBoldItalic => FontFace::BoldItalic,
}
}
fn is_math_letter(character: char) -> bool {
matches!(character, '\u{0391}'..='\u{03A9}' | '\u{03B1}'..='\u{03C9}')
}
fn character_text(character: char) -> String {
match character {
'\u{E023}' => "\\".to_owned(),
'\u{E024}' => "{".to_owned(),
'\u{E025}' => "}".to_owned(),
'\u{FB00}' => "ff".to_owned(),
'\u{FB01}' => "fi".to_owned(),
'\u{FB02}' => "fl".to_owned(),
'\u{FB03}' => "ffi".to_owned(),
'\u{FB04}' => "ffl".to_owned(),
_ => character.to_string(),
}
}
impl Halign {
/// Convert the table into text and rule primitives, with the table origin
/// at `(0, 0)`.
pub fn display_list(&self) -> DisplayList {
let mut list = DisplayList {
width: self.width,
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() {
for rule in self.rules.iter().filter(|rule| rule.row == row_index) {
let (x, width) = self.rule_rect(rule);
list.push(DisplayItem::Rule {
x,
y,
width,
height: rule.width,
});
}
if row.rule {
let height = 26_214; // 0.4pt in scaled points.
list.push(DisplayItem::Rule {
x: 0,
y,
width: self.width,
height,
});
y += height + self.row_gap(row_index);
continue;
}
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 row_span = self.cell_row_span(row_index, index);
if row_span > 1 {
if line_index != 0 {
continue;
}
let Some((x, width)) = self.cell_span(row_index, index) else {
continue;
};
let span_rows = (row_index + row_span).min(self.rows.len());
let span_height: i64 = (row_index..span_rows)
.map(|index| self.row_height(index) + self.row_gap(index))
.sum();
let center = y + span_height / 2;
for (offset_index, line) in lines.iter().enumerate() {
let baseline = center - (lines.len() as i64 - 1) * self.line_height / 2
+ self.line_height * 3 / 10
+ offset_index as i64 * self.line_height;
let line = crate::table_cell_plain_text(line);
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 + offset,
y: baseline,
size: 10 * 65_536,
text: line.clone(),
});
}
continue;
}
if self.cell_covered(row_index, index) && cell.text.trim().is_empty() {
continue;
}
let Some(line) = lines.get(line_index) else {
continue;
};
let Some((x, width)) = self.cell_span(row_index, index) else {
continue;
};
let line = crate::table_cell_plain_text(line);
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 + offset,
y: baseline,
size: 10 * 65_536,
text: line.clone(),
});
}
}
y += row_height + self.row_gap(row_index);
}
for rule in self.rules.iter().filter(|rule| rule.row == self.rows.len()) {
let (x, width) = self.rule_rect(rule);
list.push(DisplayItem::Rule {
x,
y,
width,
height: rule.width,
});
}
let rule_width = 26_214; // 0.4pt in scaled points.
for boundary in &self.vertical_rules {
let x = match *boundary {
0 => self.margin,
index if index >= self.column_widths.len() => {
(self.width - self.margin - rule_width).max(0)
}
index => {
let left = self.column_offset(index - 1) + self.column_widths[index - 1];
let right = self.column_offset(index);
((left + right) / 2 - rule_width / 2).max(0)
}
};
list.push(DisplayItem::Rule {
x,
y: 0,
width: rule_width,
height: self.height,
});
}
list
}
}
impl Page {
/// 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.
pub fn display_list(&self) -> DisplayList {
self.display_list_with_goal(0)
}
/// Paint the page, placing insertion material at `page_goal` when it is
/// positive. A zero goal keeps insertion material in normal flow.
pub fn display_list_with_goal(&self, page_goal: i64) -> DisplayList {
self.display_list_with_layout(page_goal, 0)
}
/// Paint the page with TeX's `\textfloatsep` kept between body text and a
/// float area, matching the space the page builder reserved.
pub fn display_list_with_layout(&self, page_goal: i64, text_float_sep: i64) -> DisplayList {
let mut list = DisplayList::default();
let mut y;
let top_height: i64 = self
.floats
.iter()
.filter(|float| float.placement == FloatPlacement::Top)
.map(|float| float.height + float.gap_before)
.sum();
let mut float_y = 0_i64;
for float in self
.floats
.iter()
.filter(|float| float.placement == FloatPlacement::Top)
{
float_y += float.gap_before;
Self::paint_float(float, 0, float_y, &mut list);
float_y += float.height;
}
let has_body = self.items.iter().any(|item| {
matches!(
item,
VerticalItem::Box(_)
| VerticalItem::Rule { .. }
| VerticalItem::Halign(_)
| VerticalItem::Paragraph(_)
| VerticalItem::Math { .. }
| VerticalItem::Glue(_)
)
});
y = if top_height > 0 && has_body {
top_height + text_float_sep.max(0)
} else {
top_height
};
let body_width = self
.items
.iter()
.map(|item| match item {
VerticalItem::Halign(halign) => halign.width,
VerticalItem::Rule { width, .. } => *width,
VerticalItem::Box(box_) => box_.width,
VerticalItem::Paragraph(paragraph) => paragraph.width,
VerticalItem::Math { width, .. } => *width,
_ => 0,
})
.max()
.unwrap_or(0);
let items: Vec<VerticalItem> = self
.items
.iter()
.filter(|item| !matches!(item, VerticalItem::Insertion(_)))
.cloned()
.collect();
for item in &items {
match item {
VerticalItem::Box(box_) => {
y += box_.height;
}
VerticalItem::Image {
x: image_x,
width,
height,
image,
} => {
let index = list.add_image(PdfImage {
width: image.width,
height: image.height,
rgb: image.rgb.clone(),
});
list.push(DisplayItem::Image {
x: *image_x,
y,
width: *width,
height: *height,
index,
});
y += *height;
}
VerticalItem::Rule { width, height } => {
list.push(DisplayItem::Rule {
x: 0,
y,
width: *width,
height: *height,
});
y += *height;
}
VerticalItem::Glue(height) => {
y += *height;
}
VerticalItem::StretchGlue(glue) => {
y += glue.width;
}
VerticalItem::Math {
atom,
geometry,
height,
depth,
..
} => {
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) => {
let face = paragraph_face(paragraph.font);
let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1);
let size = paragraph.font_size.max(1);
let mut current_color: Option<[u8; 3]> = None;
for (line_index, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0);
let baseline = y + paragraph
.line_baselines
.get(line_index)
.copied()
.unwrap_or(((line_height as f64) * 0.8) as i64);
let natural: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { .. }
| HorizontalItem::Discretionary { .. } => 0,
})
.sum();
let mut x = if paragraph.centered {
paragraph.left_skip + indent + ((paragraph.width - natural) / 2).max(0)
} else if paragraph.right_aligned {
paragraph.left_skip + indent + (paragraph.width - natural).max(0)
} else {
paragraph.left_skip + indent
};
let mut link_run: Option<(String, i64, i64, i64, i64)> = None;
for item in line {
match item {
HorizontalItem::Box(box_) => {
if let Some(url) = &box_.link {
let top = baseline - box_.height;
let height = box_.height + box_.depth;
match &mut link_run {
Some((open, _, open_y, width, open_height))
if open == url =>
{
let bottom = top + height;
let open_bottom = *open_y + *open_height;
*open_y = (*open_y).min(top);
*open_height = bottom.max(open_bottom) - *open_y;
*width += box_.width;
}
_ => {
flush_link(&mut link_run, &mut list.items);
link_run =
Some((url.clone(), x, top, box_.width, height));
}
}
} else {
flush_link(&mut link_run, &mut list.items);
}
let padding =
if box_.background.is_some() || box_.frame.is_some() {
3 * 65_536
} else {
0
};
if let Some(background) = box_.background {
list.items.push(DisplayItem::Rect {
x: x - padding,
y: baseline - box_.height - padding,
width: box_.width + 2 * padding,
height: box_.height + box_.depth + 2 * padding,
color: background,
});
list.items.push(DisplayItem::Fill([0, 0, 0]));
current_color = None;
}
if let Some((frame_color, thickness)) = box_.frame {
list.items.push(DisplayItem::Frame {
x: x - padding,
y: baseline - box_.height - padding,
width: box_.width + 2 * padding,
height: box_.height + box_.depth + 2 * padding,
color: frame_color,
thickness,
});
}
if box_.color != current_color {
let rgb = box_.color.unwrap_or([0, 0, 0]);
list.items.push(DisplayItem::Fill(rgb));
current_color = box_.color;
}
let glyph_size = box_.size.unwrap_or(size);
let glyph_y = baseline - box_.raise;
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);
let ratio = glyph_size as f64 / 655_360.0;
let positioned = |value: i64| (value as f64 * ratio) as i64;
for item in raw {
let item = match item {
DisplayItem::Text {
x,
y,
size,
text,
font,
} => DisplayItem::Text {
x: x0_math(x, &positioned),
y: glyph_y + positioned(y),
size: positioned(size).max(1),
text,
font,
},
DisplayItem::Rule {
x,
y,
width,
height,
} => DisplayItem::Rule {
x: x0_math(x, &positioned),
y: glyph_y + positioned(y),
width: positioned(width),
height: positioned(height).max(1),
},
DisplayItem::Line {
x1,
y1,
x2,
y2,
width,
} => DisplayItem::Line {
x1: x0_math(x1, &positioned),
y1: glyph_y + positioned(y1),
x2: x0_math(x2, &positioned),
y2: glyph_y + positioned(y2),
width: positioned(width).max(1),
},
other => other,
};
list.items.push(item);
}
}
if let Some(character) = box_.character {
list.push(DisplayItem::Text {
font: box_.font.map_or(face, paragraph_face),
x,
y: glyph_y,
size: glyph_size,
text: character_text(character),
});
}
x += box_.width;
}
HorizontalItem::Glue { width, .. } => {
if let Some((_, _, _, run_width, _)) = &mut link_run {
*run_width += *width;
}
x += *width;
}
HorizontalItem::Penalty { .. }
| HorizontalItem::Discretionary { .. } => {}
}
}
flush_link(&mut link_run, &mut list.items);
}
if current_color.is_some() {
list.items.push(DisplayItem::Fill([0, 0, 0]));
}
y += paragraph.height;
}
VerticalItem::Halign(halign) => {
let mut nested = halign.display_list();
nested.place(0, y);
list.items.extend(nested.items);
y += halign.height;
}
VerticalItem::Float(float) if float.placement == FloatPlacement::Here => {
y += float.gap_before;
Self::paint_float(float, 0, y, &mut list);
y += float.height + float.gap_after;
}
VerticalItem::Penalty(_) | VerticalItem::Mark(_) | VerticalItem::Float(_) => {}
VerticalItem::Insertion(insertion) => {
y += insertion.height;
}
}
}
let mut class_groups: Vec<(u8, Vec<VerticalItem>)> = Vec::new();
let inline_insertions = self.items.iter().filter_map(|item| match item {
VerticalItem::Insertion(insertion) => Some(insertion),
_ => None,
});
for insertion in inline_insertions.chain(self.insertions.iter()) {
if let Some((_, items)) = class_groups
.iter_mut()
.find(|(class, _)| *class == insertion.class)
{
items.extend(insertion.items.iter().cloned());
} else {
class_groups.push((insertion.class, insertion.items.clone()));
}
}
class_groups.sort_by_key(|(class, _)| *class);
let body_bottom = y;
let mut insertion_bottom = page_goal;
for (class, items) in class_groups {
let insertion_page = Page {
items,
insertions: Vec::new(),
marks: Vec::new(),
floats: Vec::new(),
sources: Vec::new(),
hash: 0,
};
let mut insertion_list = insertion_page.display_list();
let top = if page_goal > 0 {
(insertion_bottom - insertion_list.height).max(body_bottom)
} else {
y
};
insertion_list.place(0, top);
let width = insertion_list.width.max(list.width);
if class == 0 && page_goal > 0 && top > body_bottom + 26_214 {
let separator_width = (body_width * 2 / 5).max(65_536);
list.push(DisplayItem::Rule {
x: 0,
y: top - 26_214,
width: separator_width,
height: 26_214,
});
}
y = top + insertion_list.height;
list.items.extend(insertion_list.items);
list.images.extend(insertion_list.images);
list.width = list.width.max(width);
insertion_bottom = top.saturating_sub(131_072);
}
if page_goal > 0 {
let bottom_height: i64 = self
.floats
.iter()
.filter(|float| float.placement == FloatPlacement::Bottom)
.map(|float| float.height + float.gap_before)
.sum();
if bottom_height > 0 {
let bottom_area = bottom_height + text_float_sep.max(0);
let mut float_y = (page_goal - bottom_area).max(y) + text_float_sep.max(0);
for float in self
.floats
.iter()
.filter(|float| float.placement == FloatPlacement::Bottom)
{
float_y += float.gap_before;
Self::paint_float(float, 0, float_y, &mut list);
float_y += float.height;
}
y = y.max(float_y);
}
}
list.width = list.width.max(
self.items
.iter()
.map(|item| match item {
VerticalItem::Halign(halign) => halign.width,
VerticalItem::Rule { width, .. } => *width,
VerticalItem::Paragraph(paragraph) => paragraph.width,
VerticalItem::Math { width, .. } => *width,
_ => 0,
})
.max()
.unwrap_or(0),
);
list.height = y;
list
}
/// Paint a float's vertical material, or a dimension rectangle when the
/// float carries no content.
fn paint_float(float: &Float, x: i64, y: i64, list: &mut DisplayList) {
if float.content.is_empty() {
list.push(DisplayItem::Rule {
x,
y,
width: float.width,
height: float.height,
});
list.width = list.width.max(float.width);
return;
}
let page = Page {
items: float.content.clone(),
insertions: Vec::new(),
marks: Vec::new(),
floats: Vec::new(),
sources: Vec::new(),
hash: 0,
};
let mut content = page.display_list();
content.place(x, y);
list.items.extend(content.items);
list.images.extend(content.images);
list.width = list.width.max(content.width);
}
fn large_operator(atom: &MathAtom) -> bool {
match atom {
MathAtom::BigOperator { name } => matches!(
name.as_str(),
"sum" | "prod" | "coprod" | "bigcup" | "bigcap" | "bigoplus" | "bigotimes"
),
MathAtom::Symbol(character) => matches!(
character,
'∑' | '∏' | '∐' | '∫' | '∬' | '∭' | '∮' | '⋃' | '⋂' | '⨁' | '⨂'
),
MathAtom::Classed { body, .. }
| MathAtom::Script { base: body, .. }
| MathAtom::Limits { base: body, .. } => Self::large_operator(body),
_ => false,
}
}
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);
if let MathItem::OpenType(run) = &position.item {
run.paint(x, y, scaled, |item, _| list.push(item));
continue;
}
list.push(match &position.item {
MathItem::OpenType(_) => unreachable!("OpenType run handled before scalar paint"),
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::PdfForm(form) => DisplayItem::PdfForm { x, y, form: *form },
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,
x: i64,
baseline: i64,
size: i64,
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() {
let face = if character.is_ascii_alphabetic() || is_math_letter(*character) {
FontFace::MathItalic
} else if crate::cmr10::math_symbol_slot(*character).is_some() {
FontFace::MathSymbol
} else {
FontFace::Roman
};
list.push(DisplayItem::Text {
font: face,
x,
y: baseline,
size,
text: character.to_string(),
});
}
}
MathAtom::OperatorName { name, .. } => {
let roman = crate::cmr10::Cmr10Metrics::Roman;
let mut cursor = x;
for character in name.chars() {
if character == ' ' {
cursor += roman.space();
continue;
}
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: cursor,
y: baseline,
size,
text: character.to_string(),
});
cursor += roman.width(character);
}
}
MathAtom::Text(text) => {
let mut cursor = x;
for character in text.chars() {
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: cursor,
y: baseline,
size,
text: character.to_string(),
});
cursor += font.width(character);
}
}
MathAtom::Alphabet { text, alphabet } => {
let metrics = math::alphabet_metrics(*font, *alphabet);
let face = match alphabet {
math::MathAlphabet::Roman => FontFace::Roman,
math::MathAlphabet::Bold => FontFace::Bold,
math::MathAlphabet::Italic => FontFace::MathItalic,
math::MathAlphabet::Sans => FontFace::Sans,
math::MathAlphabet::Mono => FontFace::Mono,
math::MathAlphabet::Calligraphic => FontFace::MathSymbol,
math::MathAlphabet::Blackboard => FontFace::MathBlackboard,
math::MathAlphabet::Fraktur => FontFace::MathFraktur,
};
let mut cursor = x;
for character in text.chars() {
list.push(DisplayItem::Text {
font: face,
x: cursor,
y: baseline,
size,
text: character.to_string(),
});
cursor += if character == ' ' {
metrics.space()
} else {
metrics.width(character)
};
}
}
MathAtom::Row(atoms) => {
let mut cursor = x;
for child in atoms {
let width = math::legacy_layout_math(child, font).width;
Self::paint_math(child, font, cursor, baseline, size, list);
cursor += width;
}
}
MathAtom::Aligned { rows, centered } => {
let layout = math::layout_aligned(rows, *centered, font);
let x0 = x + (layout.total_width - layout.body_width) / 2;
let first_baseline = baseline - layout.height + layout.first_height;
for (index, row) in rows.iter().enumerate() {
let row_baseline = first_baseline + layout.baselines[index];
for (cell_index, cell) in row.cells.iter().enumerate() {
let cell_box = layout.boxes[index][cell_index];
let cell_x = if *centered {
x0 + (layout.body_width - cell_box.width) / 2
} else {
let start = layout.column_starts[cell_index];
let width = layout.column_widths[cell_index];
if cell_index % 2 == 0 {
x0 + start + width - cell_box.width
} else {
x0 + start
}
};
Self::paint_math(cell, font, cell_x, row_baseline, size, list);
}
if let Some(tag) = &row.tag {
let tag_width = layout.tag_widths[index];
let mut pen = x + layout.total_width - tag_width;
for character in tag.chars() {
let width = Cmr10Metrics::Roman.width(character);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: pen,
y: row_baseline,
size,
text: character.to_string(),
});
pen += width;
}
}
}
}
MathAtom::Tagged { body, tag } => {
let body_box = math::legacy_layout_math(body, font);
Self::paint_math(body, font, x, baseline, size, list);
let tag_width: i64 = tag
.chars()
.map(|character| Cmr10Metrics::Roman.width(character))
.sum();
let mut pen = x + body_box.width.max(tag_width) - tag_width;
for character in tag.chars() {
let width = Cmr10Metrics::Roman.width(character);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: pen,
y: baseline,
size,
text: character.to_string(),
});
pen += width;
}
}
MathAtom::TaggedWidth { body, tag, width } => {
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
.chars()
.map(|character| Cmr10Metrics::Roman.width(character))
.sum();
let mut pen = x + (*width).max(tag_width) - tag_width;
for character in tag.chars() {
let width = Cmr10Metrics::Roman.width(character);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: pen,
y: baseline,
size,
text: character.to_string(),
});
pen += width;
}
}
MathAtom::Script { base, sub, sup } => {
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;
let script_x = x + base_box.width + italic + 65_536 / 2;
if let Some(sup) = sup {
Self::paint_math(
sup,
font,
script_x,
baseline - base_box.height * 2 / 3,
small,
list,
);
}
if let Some(sub) = sub {
Self::paint_math(
sub,
font,
script_x,
baseline + base_box.depth + 2 * 65_536,
small,
list,
);
}
}
MathAtom::Fraction {
numerator,
denominator,
bar,
} => {
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;
if *bar {
list.push(DisplayItem::Rule {
x,
y: bar_y,
width: rule_width,
height: 26_214,
});
}
Self::paint_math(
numerator,
font,
x + (rule_width - num.width) / 2,
bar_y - clearance - num.depth,
size,
list,
);
Self::paint_math(
denominator,
font,
x + (rule_width - den.width) / 2,
bar_y + clearance + den.height,
size,
list,
);
}
MathAtom::Sqrt { radicand, degree } => {
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::legacy_layout_math(degree, font);
Self::paint_math(degree, font, x, baseline - box_.height - small, small, list);
radical_x += degree_box.width;
}
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: radical_x,
y: baseline,
size,
text: "√".to_string(),
});
Self::paint_math(radicand, font, radical_x + 4 * 65_536, baseline, size, list);
list.push(DisplayItem::Rule {
x: radical_x + 4 * 65_536,
y: baseline - box_.height - 65_536,
width: box_.width,
height: 26_214,
});
}
MathAtom::Delimited { left, right, body } => {
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);
let left_width = left_box.0;
let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter);
let scaled_size = |extent: (i64, i64, i64), delimiter: char| -> (i64, i64) {
let base = base_extent(delimiter);
let scale = if base > 0 {
(extent.1 + extent.2) as f64 / base as f64
} else {
1.0
};
let glyph_size = (size as f64 * scale) as i64;
let shift = ((glyph_size - size) as f64 * 0.35) as i64;
(glyph_size, shift)
};
if *left != '.' {
let (left_size, left_shift) = scaled_size(left_box, *left);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
y: baseline + left_shift,
size: left_size,
text: left.to_string(),
});
}
Self::paint_math(body, font, x + left_width, baseline, size, list);
if *right != '.' {
let (right_size, right_shift) = scaled_size(right_box, *right);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: x + left_width + body_box.width,
y: baseline + right_shift,
size: right_size,
text: right.to_string(),
});
}
}
MathAtom::Matrix {
rows,
align,
left,
right,
row_lead,
} => {
let layout = math::matrix_layout(rows, font, align, *left, *right, *row_lead);
let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter);
let scaled = |metrics: (char, i64, i64, i64)| -> (i64, i64) {
let base = base_extent(metrics.0);
let scale = if base > 0 {
(metrics.2 + metrics.3) as f64 / base as f64
} else {
1.0
};
let glyph_size = (size as f64 * scale) as i64;
let shift = ((glyph_size - size) as f64 * 0.35) as i64;
(glyph_size, shift)
};
let left_width = layout.left.map(|(_, width, _, _)| width).unwrap_or(0);
if let Some(metrics) = layout.left {
let (glyph_size, shift) = scaled(metrics);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
y: baseline + shift,
size: glyph_size,
text: metrics.0.to_string(),
});
}
let body_x = x + left_width + layout.border;
let first_baseline = baseline - layout.height + layout.first_height;
for (row_index, cells) in rows.iter().enumerate() {
let row_baseline = first_baseline + layout.baselines[row_index];
for (column, cell) in cells.iter().enumerate() {
let offset = match align
.get(column)
.copied()
.unwrap_or(MathColumnAlign::Center)
{
MathColumnAlign::Left => 0,
MathColumnAlign::Center => {
(layout.column_widths[column]
- layout.boxes[row_index][column].width)
/ 2
}
MathColumnAlign::Right => {
layout.column_widths[column] - layout.boxes[row_index][column].width
}
};
let cell_x = body_x + layout.column_starts[column] + offset;
Self::paint_math(cell, font, cell_x, row_baseline, size, list);
}
}
if let Some(metrics) = layout.right {
let (glyph_size, shift) = scaled(metrics);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: body_x + layout.body_width + layout.border,
y: baseline + shift,
size: glyph_size,
text: metrics.0.to_string(),
});
}
}
MathAtom::Multline { rows, tag } => {
let layout = math::multline_layout(rows, tag.as_deref(), font);
let first_baseline = baseline - layout.height + layout.first_height;
for (index, row) in rows.iter().enumerate() {
Self::paint_math(
row,
font,
x + layout.offsets[index],
first_baseline + layout.baselines[index],
size,
list,
);
}
if let Some(tag) = tag {
let row_baseline =
first_baseline + layout.baselines.last().copied().unwrap_or(0);
let mut tag_x = x + layout.body_width;
for character in tag.chars() {
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: tag_x,
y: row_baseline,
size,
text: character.to_string(),
});
tag_x += Cmr10Metrics::Roman.width(character);
}
}
}
MathAtom::Accent { accent, base } => {
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,
x: x + base_box.width / 2,
y: baseline - base_box.height - 65_536,
size,
text: accent.to_string(),
});
}
MathAtom::Underline { base } => {
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
list.push(DisplayItem::Rule {
x,
y: baseline + base_box.depth,
width: base_box.width,
height: 26_214,
});
}
MathAtom::Cancel {
base,
forward,
backward,
} => {
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
if *forward {
list.push(DisplayItem::Line {
x1: x,
y1: baseline + base_box.depth,
x2: x + base_box.width,
y2: baseline - base_box.height,
width: 26_214,
});
}
if *backward {
list.push(DisplayItem::Line {
x1: x,
y1: baseline - base_box.height,
x2: x + base_box.width,
y2: baseline + base_box.depth,
width: 26_214,
});
}
}
MathAtom::Negated { base } => {
let base_box = math::legacy_layout_math(base, font);
Self::paint_math(base, font, x, baseline, size, list);
list.push(DisplayItem::Line {
x1: x,
y1: baseline + base_box.depth,
x2: x + base_box.width,
y2: baseline - base_box.height,
width: 26_214,
});
}
MathAtom::Boxed { body } => {
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,
y: baseline - body_box.height - 65_536,
width: body_box.width + 131_072,
height: 26_214,
});
list.push(DisplayItem::Rule {
x,
y: baseline + body_box.depth + 65_536,
width: body_box.width + 131_072,
height: 26_214,
});
}
MathAtom::Phantom {
body,
horizontal,
vertical,
} => {
if *horizontal || !*vertical {
Self::paint_math(body, font, x, baseline, size, list);
}
}
MathAtom::StackLines(lines) => {
let layout = crate::math::stack_layout(lines, font);
let scale = |value: i64| value.saturating_mul(size) / 655_360;
for (index, line) in lines.iter().enumerate() {
let box_ = &layout.boxes[index];
let row_x = x + scale((layout.width - box_.width).max(0)) / 2;
let row_y = baseline + scale(layout.offsets[index]);
Self::paint_math(line, font, row_x, row_y, size, list);
}
}
MathAtom::Stack { top, base, above } => {
Self::paint_math(base, font, x, baseline, size, list);
let base_box = math::legacy_layout_math(base, font);
let top_box = math::legacy_layout_math(top, font);
Self::paint_math(
top,
font,
x + (base_box.width - top_box.width) / 2,
if *above {
baseline - base_box.height - top_box.depth
} else {
baseline + base_box.depth + top_box.height
},
size,
list,
);
}
MathAtom::Limits { base, sub, sup } => {
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::legacy_layout_math(sup, font));
let sup_gap = if Self::large_operator(base) {
-96_993
} else {
96_993
};
Self::paint_math(
sup,
font,
x + (base_box.width - sup_box.width).max(0) / 2,
baseline - base_box.height - sup_box.depth + sup_gap,
small,
list,
);
}
if let Some(sub) = sub {
let sub_box = math::script_metrics(math::legacy_layout_math(sub, font));
Self::paint_math(
sub,
font,
x + (base_box.width - sub_box.width).max(0) / 2,
baseline
+ if Self::large_operator(base) {
-4 * 65_536
} else {
math::intrinsic_depth(base, font)
}
+ 131_072
+ sub_box.height
+ 65_536
+ 46_531,
small,
list,
);
}
}
MathAtom::Brace { base, above } => {
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 {
baseline - base_box.height - size / 2
} else {
baseline + base_box.depth + size / 2
};
list.push(DisplayItem::Rule {
x,
y,
width: base_box.width,
height: thickness,
});
let tick = size / 2;
for tick_x in [x, x + base_box.width - thickness] {
list.push(DisplayItem::Rule {
x: tick_x,
y: if *above { y + thickness } else { y - tick },
width: thickness,
height: tick,
});
}
}
MathAtom::Smash { body: base, .. } | MathAtom::Classed { body: base, .. } => {
Self::paint_math(base, font, x, baseline, size, list)
}
MathAtom::Binomial {
numerator,
denominator,
} => {
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(
numerator,
font,
x + (width - num.width) / 2 + 2 * 65_536,
baseline - 8 * 65_536,
size,
list,
);
Self::paint_math(
denominator,
font,
x + (width - den.width) / 2 + 2 * 65_536,
baseline + 12 * 65_536,
size,
list,
);
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
y: baseline,
size: bracket,
text: "(".to_string(),
});
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: x + width + 4 * 65_536,
y: baseline,
size: bracket,
text: ")".to_string(),
});
}
MathAtom::BigOperator { name } => {
if let Some(character) = math::big_operator_character(name) {
list.push(DisplayItem::Text {
font: FontFace::MathExtension,
x,
y: baseline,
size,
text: character.to_string(),
});
} else {
for (index, character) in name.chars().enumerate() {
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: x + index as i64 * font.width(character),
y: baseline,
size,
text: character.to_string(),
});
}
}
}
MathAtom::SizedDelimiter {
delimiter,
size: step,
} => {
let base_extent = font.height(*delimiter) + font.depth(*delimiter);
let extent = crate::cmr10::cmex_delimiter(*delimiter, *step)
.map(|(_, height, depth)| height + depth);
let (glyph_size, shift) = match extent {
Some(extent) if base_extent > 0 && extent > base_extent => {
let scale = extent as f64 / base_extent as f64;
let glyph_size = (size as f64 * scale) as i64;
(glyph_size, ((glyph_size - size) as f64 * 0.35) as i64)
}
_ => (size, 0),
};
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
y: baseline + shift,
size: glyph_size,
text: delimiter.to_string(),
});
}
MathAtom::Middle(delimiter) => {
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
y: baseline,
size,
text: delimiter.to_string(),
});
}
MathAtom::Strut => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tall_delimiters_are_lowered_to_stay_centered() {
let atom = crate::math::parse_math(r"\left(\frac{a}{b}\right)");
let mut items = Vec::new();
Page::paint_math(
&atom,
&Cmr10Metrics::default(),
0,
100,
10 * 65_536,
&mut items,
);
let paren_y = items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "(" => Some(*y),
_ => None,
})
.expect("left delimiter");
let body_y = items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "a" => Some(*y),
_ => None,
})
.expect("body glyph");
assert!(paren_y > body_y, "tall delimiter should sit lower");
}
#[test]
fn negated_math_draws_a_diagonal_line() {
let mut items = Vec::new();
Page::paint_math(
&MathAtom::Negated {
base: Box::new(MathAtom::Symbol('=')),
},
&Cmr10Metrics::default(),
0,
0,
10 * 65_536,
&mut items,
);
assert!(
items
.iter()
.any(|item| matches!(item, DisplayItem::Line { .. }))
);
assert!(
!items
.iter()
.any(|item| matches!(item, DisplayItem::Rule { .. }))
);
}
}