Measure external font expansion at paragraph break margins

This commit is contained in:
gloamxun committed 2026-11-21 08:08:11 +08:00
1 parent 91b3e6a8fe
commit 1e4c113b27
6 files changed
+242 -91

No files matched your search

@@ -5,7 +5,7 @@ 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)]
struct Capacity {
pub(super) struct Capacity {
stretch: i64,
shrink: i64,
}
@@ -43,20 +43,25 @@ impl Limits {
Ok(())
}
fn residual(self, shortfall: i64, capacity: Capacity) -> i64 {
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 shortfall;
return Ok(shortfall);
}
if available > shortfall.abs() {
direction * (available / i64::from(limit / self.step)) / 2
} else {
shortfall - direction * available
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)
}
}
@@ -211,8 +216,9 @@ impl Search {
end: usize,
post: Option<usize>,
pre: Option<usize>,
) -> i64 {
let mut total = Capacity {
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,
};
@@ -244,6 +250,80 @@ fn slot_ratio(state: &State, font: &NativeFont, slot: u8, line_ratio: i32) -> i3
(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.has_external_expansion(font) {
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.external_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 base = state.fonts.glyph_font(font)?.clone();
let defaults = state.font_defaults();
let mut selected = |amount| -> Result<i64, String> {
if amount == 0 {
return Ok(original);
}
let face = state.fonts.expansion_face(&base, amount, defaults, files)?;
let quad = i64::from(state.fonts.font(face.id)?.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), Arc<NativeFont>>);
@@ -298,21 +378,26 @@ pub(super) fn pack(
) -> Result<(), String> {
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
let shortfall = target - natural;
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
return Ok(());
}
let mut fonts = PackingFonts::default();
let mut capacity = sum(state, material, None)?;
for node in material.iter() {
let TextNode::MarginKern { width, right, font, slot } = *node else {
continue;
};
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
if let Some((expanded, _)) = fonts.external_margin(state, font, slot, right, ratio, files)? {
*limit += i64::from(expanded) - i64::from(width);
let mut capacity = Capacity::default();
if state.fonts.has_external_expansions() {
// 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;
};
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
if let Some((expanded, _)) = fonts.external_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 {