Implement native automatic font expansion for paragraphs

This commit is contained in:
gloamxun committed 2026-11-20 23:29:37 +08:00
1 parent 1dd745afcb
commit ebbc9e2c17
24 files changed
+632 -34

No files matched your search

@@ -48,6 +48,7 @@ struct Entry {
hash: u64,
nodes: Vec<BreakNode>,
margins: Option<protrusion::Search>,
expansion: Option<expansion::Search>,
parameters: BTreeMap<Parameter, ParameterValue>,
shape: Vec<ParagraphShapeLine>,
previous_lines: usize,
@@ -61,6 +62,7 @@ impl Entry {
self.nodes.len()
+ self.shape.len()
+ self.margins.as_ref().map_or(0, protrusion::Search::len)
+ self.expansion.as_ref().map_or(0, expansion::Search::len)
}
}
@@ -274,14 +276,21 @@ pub(super) fn solve(
let nodes: Vec<_> = source.iter().map(BreakNode::project).collect();
let margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
.then(|| protrusion::Search::new(state, source));
let retained = nodes.len() + shape.len() + margins.as_ref().map_or(0, protrusion::Search::len);
let expansion = (parameters[&Parameter::Pdfadjustspacing].width() > 1
&& state.fonts.has_expansion())
.then(|| expansion::Search::new(state, source))
.transpose()?;
let retained = nodes.len()
+ shape.len()
+ margins.as_ref().map_or(0, protrusion::Search::len)
+ expansion.as_ref().map_or(0, expansion::Search::len);
let mut hash = None;
if let Some(cache) = cache
&& retained <= RETAINED_NODES
&& parameters[&Parameter::Tracingparagraphs].width() <= 0
{
let mut hasher = DefaultHasher::new();
(&nodes, &margins, parameters, shape, pass, previous_lines).hash(&mut hasher);
(&nodes, &margins, &expansion, parameters, shape, pass, previous_lines).hash(&mut hasher);
let key = hasher.finish();
hash = Some(key);
let mut cache = cache
@@ -296,6 +305,7 @@ pub(super) fn solve(
&& entry.shape == shape
&& entry.nodes == nodes
&& entry.margins == margins
&& entry.expansion == expansion
}) {
let entry = cache.entries.remove(index).unwrap();
*work += entry.edges;
@@ -315,6 +325,7 @@ pub(super) fn solve(
source,
&nodes,
margins.as_ref(),
expansion.as_ref(),
parameters,
shape,
pass,
@@ -345,6 +356,7 @@ pub(super) fn solve(
hash,
nodes,
margins,
expansion,
parameters: parameters.clone(),
shape: shape.to_vec(),
previous_lines,
@@ -0,0 +1,301 @@
//! 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::{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)]
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) -> i64 {
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;
}
if available > shortfall.abs() {
direction * (available / i64::from(limit / self.step)) / 2
} else {
shortfall - direction * available
}
}
}
struct Character<'a> {
font: &'a Arc<NativeFont>,
slot: u8,
width: i64,
}
fn character(node: &TextNode) -> Option<Character<'_>> {
let TextNode::Glyph { 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,
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.font.id == right.font.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, width, kern| {
let Some(config) = state.fonts.expansion(font.id) else {
return Capacity::default();
};
if font.expansion != 0 {
return Capacity::default();
}
let code = state.fonts.expansion_code(font.id, slot);
let scale = |value| pdf_device::magnify(value, code);
let stretch = pdf_device::magnify(width, 1000 + config.stretch) - width;
let shrink = width - pdf_device::magnify(width, 1000 - config.shrink);
Capacity {
stretch: scale(if kern { stretch } else { stretch.max(0) }),
shrink: scale(if kern { shrink } else { shrink.max(0) }),
}
};
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 Ok(measure(glyph.font, glyph.slot, glyph.width, false));
}
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 Ok(measure(left.font, left.slot, kern, true));
}
}
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>,
) -> i64 {
let mut 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 glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 {
let Some(config) = state.fonts.expansion(glyph.font.id) else {
return 0;
};
if glyph.font.expansion != 0 {
return 0;
}
let max = if line_ratio < 0 {
config.shrink
} else {
config.stretch
};
let code = state.fonts.expansion_code(glyph.font.id, glyph.slot);
let magnitude = i64::from(line_ratio.abs()) * i64::from(code) * i64::from(max) / 1_000_000;
let step = i64::from(config.step);
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
}
pub(super) fn pack(state: &State, material: &mut [TextNode], target: i64) -> 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 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;
let mut fonts = BTreeMap::new();
for i in 0..material.len() {
if let TextNode::Kern {
width,
explicit: false,
} = material[i]
&& let Some((left, right)) = pair(material, i)
&& let kern = left
.font
.metrics()
.kern(char::from(left.slot), char::from(right.slot))
&& kern == i64::from(width)
{
let amount = glyph_ratio(state, &left, ratio);
if let TextNode::Kern { width, .. } = &mut material[i] {
*width = i32::try_from(pdf_device::magnify(kern, 1000 + amount))
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
}
}
}
for node in material {
let Some(glyph) = character(node) else {
continue;
};
let amount = glyph_ratio(state, &glyph, ratio);
if amount == 0 {
continue;
}
let face = fonts.entry((glyph.font.id, amount)).or_insert_with(|| {
Arc::new(NativeFont {
expansion: amount,
..glyph.font.as_ref().clone()
})
});
let TextNode::Glyph { glyph, .. } = node else {
unreachable!()
};
glyph.width = pdf_device::magnify(glyph.width, 1000 + amount);
glyph.italic = pdf_device::magnify(glyph.italic, 1000 + amount);
let geometry = glyph
.math_geometry
.as_mut()
.expect("native character geometry");
geometry.metrics.width = glyph.width;
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
unreachable!()
};
*font = face.clone();
}
Ok(())
}