//! 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 { 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, id: FontId, slot: u8, width: i64, } fn character(node: &TextNode) -> Option> { 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 measure( state: &State, font: &NativeFont, slot: u8, width: i64, right: Option, ) -> Result { 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 { 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)?), }) } fn capacity( state: &State, nodes: &[TextNode], at: usize, limits: Option<&mut Limits>, ) -> Result { 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(state, glyph.font, glyph.slot, glyph.width, None); } if let TextNode::Kern { width, explicit: false, } = nodes[at] && let Some((left, right)) = pair(nodes, at) { return measure(state, left.font, left.slot, i64::from(width), Some(right.slot)); } Ok(Capacity::default()) } fn sum( state: &State, nodes: &[TextNode], mut limits: Option<&mut Limits>, ) -> Result { 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, discretionary: BTreeMap, } impl Search { pub(super) fn new(state: &State, nodes: &[TextNode]) -> Result { 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, pre: Option, mut total: Capacity, ) -> Result { 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, 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, 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 { match *self { Self::Measured(capacity) => Ok(capacity), Self::Pending { amounts, code, original } => { let defaults = state.font_defaults(); let mut selected = |amount| -> Result { 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 { 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, 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; } if let TextNode::Kern { width, explicit: false } = material[i] { // The left glyph has already been visited, while the right one // still carries its original font. Check those live font choices. if let Some((left, right)) = pair(material, i) { let capacity = measure(state, left.font, left.slot, i64::from(width), Some(right.slot))?; let variation = if ratio < 0 { capacity.shrink } else { capacity.stretch }; if variation != 0 && ratio != 0 { let kern = left.font.metrics().kern(char::from(left.slot), char::from(right.slot)); let width = i32::try_from(kern) .map_err(|_| "native font kern exceeds the scaled point range")?; material[i] = TextNode::Kern { width, explicit: false }; } } 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 metrics = state.fonts.character(selected, glyph.slot)? .ok_or_else(|| format!("expanded font has no TFM slot {}", glyph.slot))?; let face = state.fonts.glyph_font(selected)?; 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(()) }