Files
texrra-engine/crates/texrra-tex-core/src/execution/paragraph/expansion.rs
T

470 lines
16 KiB
Rust

//! pdfTeX expansion uses each live font's stretch and shrink limits. Paragraph
//! search budgets the quantization error; packing applies a font to each glyph.
use super::{FontId, SourceProvider, State, TextNode, metrics};
use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device};
use std::{collections::BTreeMap, ops::AddAssign, sync::Arc};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(super) struct Capacity {
stretch: i64,
shrink: i64,
}
impl AddAssign for Capacity {
fn add_assign(&mut self, other: Self) {
self.stretch += other.stretch;
self.shrink += other.shrink;
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct Limits {
stretch: i32,
shrink: i32,
step: i32,
}
impl Limits {
fn include(&mut self, font: super::super::font_catalog::FontExpansion) -> Result<(), String> {
for (current, next) in [
(&mut self.step, font.step),
(&mut self.stretch, font.stretch),
(&mut self.shrink, font.shrink),
] {
if next != 0 {
if *current != 0 && *current != next {
return Err(
"inconsistent font expansion steps or limits in a native paragraph".into(),
);
}
*current = next;
}
}
Ok(())
}
fn residual(self, shortfall: i64, capacity: Capacity) -> Result<i64, String> {
let (direction, limit, available) = if shortfall < 0 {
(-1, self.shrink, capacity.shrink)
} else {
(1, self.stretch, capacity.stretch)
};
if available <= 0 || shortfall == 0 {
return Ok(shortfall);
}
if available <= shortfall.abs() {
return Ok(shortfall - direction * available);
}
// A nested margin glyph can contribute before an outer character
// establishes the step. pdfTeX's initial limit and step are both -1.
let steps = if self.step == 0 { 1 } else { limit / self.step };
if steps == 0 {
return Err("paragraph margin expansion has no limit in this direction".into());
}
Ok(direction * (available / i64::from(steps)) / 2)
}
}
struct Character<'a> {
font: &'a Arc<NativeFont>,
id: FontId,
slot: u8,
width: i64,
}
fn character(node: &TextNode) -> Option<Character<'_>> {
let TextNode::Glyph { font: id, glyph, slot, .. } = node else {
return None;
};
let geometry = glyph.math_geometry.as_ref()?;
let MathItem::NativeGlyph { font, .. } = &geometry.items.first()?.item else {
return None;
};
Some(Character {
font,
id: *id,
slot: *slot,
width: glyph.width,
})
}
fn pair(nodes: &[TextNode], at: usize) -> Option<(Character<'_>, Character<'_>)> {
let left = character(nodes.get(at.checked_sub(1)?)?)?;
let right = character(nodes.get(at + 1)?)?;
(left.id == right.id && left.font.expansion == 0 && right.font.expansion == 0)
.then_some((left, right))
}
fn capacity(
state: &State,
nodes: &[TextNode],
at: usize,
limits: Option<&mut Limits>,
) -> Result<Capacity, String> {
let measure = |font: &NativeFont, slot: u8, width, right: Option<u8>| {
let Some(config) = state.fonts.expansion(font.id) else {
return Ok(Capacity::default());
};
if font.expansion != 0 {
return Ok(Capacity::default());
}
let limit_width = |amount| -> Result<i64, String> {
if amount == 0 {
return Ok(width);
}
let variant = state.fonts.expansion_limit(font.id, amount)?;
Ok(match right {
Some(right) => variant.metrics().kern(char::from(slot), char::from(right)),
None => variant.advance(slot),
})
};
let code = state.fonts.expansion_code(font.id, slot);
let scale = |value: i64| {
pdf_device::magnify(if right.is_some() { value } else { value.max(0) }, code)
};
Ok(Capacity {
stretch: scale(limit_width(config.stretch)? - width),
shrink: scale(width - limit_width(-config.shrink)?),
})
};
if let Some(glyph) = character(&nodes[at]) {
if glyph.font.expansion == 0
&& let Some(limits) = limits
&& let Some(config) = state.fonts.expansion(glyph.font.id)
{
limits.include(config)?;
}
return measure(glyph.font, glyph.slot, glyph.width, None);
}
if let TextNode::Kern {
width,
explicit: false,
} = nodes[at]
&& let Some((left, right)) = pair(nodes, at)
{
let kern = left
.font
.metrics()
.kern(char::from(left.slot), char::from(right.slot));
// A boundary kern and a TFM kern between two characters have the same
// node type. Only use the font program's actual kerning pair here.
if kern == i64::from(width) {
return measure(left.font, left.slot, kern, Some(right.slot));
}
}
Ok(Capacity::default())
}
fn sum(
state: &State,
nodes: &[TextNode],
mut limits: Option<&mut Limits>,
) -> Result<Capacity, String> {
let mut total = Capacity::default();
for i in 0..nodes.len() {
total += capacity(state, nodes, i, limits.as_deref_mut())?;
}
Ok(total)
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(super) struct Search {
limits: Limits,
prefix: Vec<Capacity>,
discretionary: BTreeMap<usize, [Capacity; 2]>,
}
impl Search {
pub(super) fn new(state: &State, nodes: &[TextNode]) -> Result<Self, String> {
let mut limits = Limits::default();
let mut total = Capacity::default();
let mut prefix = Vec::with_capacity(nodes.len() + 1);
let mut discretionary = BTreeMap::new();
prefix.push(total);
for (i, node) in nodes.iter().enumerate() {
total += capacity(state, nodes, i, Some(&mut limits))?;
prefix.push(total);
if let TextNode::Discretionary {
pre_break,
post_break,
..
} = node
{
let pre = sum(state, pre_break, Some(&mut limits))?;
let post = sum(state, post_break, Some(&mut limits))?;
if pre != Capacity::default() || post != Capacity::default() {
discretionary.insert(i, [pre, post]);
}
}
}
Ok(Self {
limits,
prefix,
discretionary,
})
}
pub(super) fn len(&self) -> usize {
self.prefix.len() + 2 * self.discretionary.len()
}
pub(super) fn residual(
&self,
shortfall: i64,
start: usize,
end: usize,
post: Option<usize>,
pre: Option<usize>,
mut total: Capacity,
) -> Result<i64, String> {
total += Capacity {
stretch: self.prefix[end].stretch - self.prefix[start].stretch,
shrink: self.prefix[end].shrink - self.prefix[start].shrink,
};
if let Some(branches) = post.and_then(|i| self.discretionary.get(&i)) {
total += branches[1];
}
if let Some(branches) = pre.and_then(|i| self.discretionary.get(&i)) {
total += branches[0];
}
self.limits.residual(shortfall, total)
}
}
fn slot_ratio(state: &State, font: &NativeFont, slot: u8, line_ratio: i32) -> i32 {
let Some(config) = state.fonts.expansion(font.id) else {
return 0;
};
if font.expansion != 0 {
return 0;
}
let max = if line_ratio < 0 {
config.shrink
} else {
config.stretch
};
let code = state.fonts.expansion_code(font.id, slot);
// Round the signed expansion product before quantizing it to the font step.
// Work on its magnitude here so both signs round away from zero at a tie.
let product = i64::from(line_ratio.abs()) * i64::from(code) * i64::from(max);
let magnitude = (product + 500_000) / 1_000_000;
let step = i64::from(config.step);
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
}
/// Variation of a candidate's protrusion at its quantized font limits.
/// pdfTeX uses the left protrusion code for this variation on both sides.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum MarginVariation {
Measured(Capacity),
Pending {
amounts: [i32; 2],
code: i32,
original: i64,
},
}
impl MarginVariation {
pub(super) fn project(state: &State, font: FontId, slot: u8) -> Result<Option<Self>, String> {
if state.fonts.expansion(font).is_none() {
return Ok(None);
}
let face = state.fonts.glyph_font(font)?;
let amounts = [slot_ratio(state, face, slot, 1000), slot_ratio(state, face, slot, -1000)];
if amounts == [0, 0] {
return Ok(None);
}
let quad = i64::from(state.fonts.font(font)?.quad());
let code = state.fonts.protrusion_code(font, slot, false);
let original = pdf_device::magnify(quad, code);
let selected = |amount| -> Result<Option<i64>, String> {
if amount == 0 {
return Ok(Some(original));
}
let Some(variant) = state.fonts.expansion_variant(font, amount) else {
return Ok(None);
};
let quad = i64::from(state.fonts.font(variant)?.quad());
Ok(Some(pdf_device::magnify(quad, code)))
};
Ok(Some(match (selected(amounts[0])?, selected(amounts[1])?) {
(Some(wide), Some(narrow)) => Self::Measured(Capacity {
stretch: original - wide,
shrink: narrow - original,
}),
_ => Self::Pending { amounts, code, original },
}))
}
pub(super) fn resolve(
&mut self,
state: &mut State,
font: FontId,
files: &mut impl SourceProvider,
) -> Result<Capacity, String> {
match *self {
Self::Measured(capacity) => Ok(capacity),
Self::Pending { amounts, code, original } => {
let defaults = state.font_defaults();
let mut selected = |amount| -> Result<i64, String> {
if amount == 0 {
return Ok(original);
}
let selected = state.fonts.ensure_expansion_variant(font, amount, defaults, files)?;
let quad = i64::from(state.fonts.font(selected)?.quad());
Ok(pdf_device::magnify(quad, code))
};
let capacity = Capacity {
stretch: original - selected(amounts[0])?,
shrink: selected(amounts[1])? - original,
};
*self = Self::Measured(capacity);
Ok(capacity)
}
}
}
}
#[derive(Default)]
struct PackingFonts(BTreeMap<(FontId, i32), FontId>);
impl PackingFonts {
fn select(
&mut self,
state: &mut State,
font: FontId,
amount: i32,
files: &mut impl SourceProvider,
) -> Result<FontId, String> {
use std::collections::btree_map::Entry;
let selected = match self.0.entry((font, amount)) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let defaults = state.font_defaults();
entry.insert(state.fonts.ensure_expansion_variant(font, amount, defaults, files)?)
}
};
Ok(*selected)
}
fn margin(
&mut self,
state: &mut State,
font: FontId,
slot: u8,
right: bool,
ratio: i32,
files: &mut impl SourceProvider,
) -> Result<Option<(i32, FontId)>, String> {
if state.fonts.expansion(font).is_none() {
return Ok(None);
}
let base = state.fonts.glyph_font(font)?.clone();
let amount = slot_ratio(state, &base, slot, ratio);
if amount == 0 {
return Ok(None);
}
let selected = self.select(state, font, amount, files)?;
let code = state.fonts.protrusion_code(font, slot, right);
let quad = i64::from(state.fonts.font(selected)?.quad());
Ok(Some((-pdf_device::magnify(quad, code) as i32, selected)))
}
}
pub(super) fn pack(
state: &mut State,
material: &mut [TextNode],
target: i64,
files: &mut impl SourceProvider,
) -> Result<(), String> {
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
let shortfall = target - natural;
let mut fonts = PackingFonts::default();
let mut capacity = Capacity::default();
if state.fonts.has_expansion() {
// Measuring the actual margin assigns its extreme variants before
// glue setting decides whether to perform any substitution.
for node in material.iter() {
let TextNode::MarginKern { width, right, font, slot } = *node else {
continue;
};
let Ok(slot) = u8::try_from(slot) else { continue };
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
if let Some((expanded, _)) = fonts.margin(state, font, slot, right, ratio, files)? {
*limit += i64::from(expanded) - i64::from(width);
}
}
}
}
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
return Ok(());
}
capacity += sum(state, material, None)?;
let available = if shortfall < 0 {
capacity.shrink
} else {
capacity.stretch
};
if available <= 0 {
return Ok(());
}
let ratio =
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
for i in 0..material.len() {
if let TextNode::MarginKern { ref mut width, right, ref mut font, slot } = material[i] {
if let Ok(slot) = u8::try_from(slot)
&& let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)?
{
*width = expanded;
*font = selected;
}
continue;
}
let Some(glyph) = character(&material[i]) else {
continue;
};
let amount = slot_ratio(state, glyph.font, glyph.slot, ratio);
if amount == 0 {
continue;
}
let selected = fonts.select(state, glyph.id, amount, files)?;
let character = char::from(glyph.slot);
let metrics = state.fonts.character(selected, glyph.slot)?
.ok_or_else(|| format!("expanded font has no TFM slot {}", glyph.slot))?;
// Reuse the original pair for synthesized kern scaling. A loaded
// TFM can affect capacity without replacing the original pair kern.
let face = state.fonts.glyph_font(selected)?;
if state.fonts.shares_font_parameters(selected)
&& !state.fonts.has_external_expansion(glyph.id)
&& let Some(TextNode::Kern { width, explicit: false }) = material.get(i + 1)
&& let Some((left, right)) = pair(material, i + 1)
{
let next = char::from(right.slot);
let original = left.font.metrics().kern(character, next);
if original == i64::from(*width)
&& let TextNode::Kern { width, .. } = &mut material[i + 1]
{
*width = i32::try_from(face.metrics().kern(character, next))
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
}
}
let TextNode::Glyph { font, glyph, .. } = &mut material[i] else {
unreachable!()
};
*font = selected;
glyph.width = metrics.width;
glyph.height = metrics.height;
glyph.depth = metrics.depth;
glyph.italic = metrics.italic;
let geometry = glyph.math_geometry.as_mut().expect("native character geometry");
geometry.metrics.width = glyph.width;
geometry.metrics.height = glyph.height;
geometry.metrics.depth = glyph.depth;
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
unreachable!()
};
*font = face.clone();
}
Ok(())
}