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

@@ -7,6 +7,8 @@ pub enum DiagnosticNode {
Character {
font: FontId,
slot: u8,
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
expansion: i32,
ligature: Option<String>,
},
Box(DiagnosticBox),
@@ -151,6 +153,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
TextNode::Language(l) => DiagnosticNode::Language(*l),
TextNode::Glyph {
font,
glyph,
slot,
original,
ligature,
@@ -160,6 +163,13 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
} => DiagnosticNode::Character {
font: *font,
slot: *slot,
expansion: glyph.math_geometry.as_ref()
.and_then(|geometry| geometry.items.first())
.and_then(|paint| match &paint.item {
crate::math_engine_tex::MathItem::NativeGlyph { font, .. } => Some(font.expansion),
_ => None,
})
.unwrap_or(0),
ligature: ligature.then(|| {
format!(
"{}{original}{}",
@@ -182,6 +192,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
DiagnosticNode::Character {
font: font.id,
slot: *slot,
expansion: font.expansion,
ligature: None,
}
} else {
@@ -338,9 +349,12 @@ impl Printer<'_> {
self.flex(g.shrink.amount, g.shrink.order);
}
}
fn character(&mut self, font: FontId, slot: u8) -> Result<(), String> {
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
let name = self.state.fonts.font(font)?.identifier_text();
self.command(&name);
if expansion != 0 {
self.literal(&format!(" ({expansion:+})"));
}
self.literal(" ");
self.ascii(slot);
Ok(())
@@ -443,9 +457,10 @@ impl Printer<'_> {
DiagnosticNode::Character {
font,
slot,
expansion,
ligature,
} => {
self.character(*font, *slot)?;
self.character(*font, *slot, *expansion)?;
if let Some(s) = ligature {
self.literal(" (ligature ");
for c in s.chars() {
@@ -2022,6 +2022,11 @@ impl Executor {
}
Ok(value.width())
}
Meaning::Primitive(Primitive::Efcode) => {
let (font, slot) = self.font_character_target(files)?;
self.reads.insert(Dependency::FontResources);
Ok(self.state.fonts.expansion_code(font, slot))
}
Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => {
let (font, slot) = self.font_character_target(files)?;
Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode))
@@ -3861,6 +3866,27 @@ impl Executor {
matches!(primitive, Some(Edef | Xdef)),
files,
)?,
Some(Pdffontexpand) => {
let font = self.font_identifier(files)?;
self.optional_equals(files)?;
let stretch = self.integer(files)?;
let shrink = self.integer(files)?;
let step = self.integer(files)?;
let automatic = self.keyword("autoexpand", files)?;
if automatic {
self.optional_space(files)?;
}
self.state
.fonts
.configure_expansion(font, stretch, shrink, step, automatic)
.map_err(|message| self.error(message, self.current))?;
}
Some(Efcode) => {
let (font, slot) = self.font_character_target(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
self.state.fonts.set_expansion_code(font, slot, code);
}
Some(Lpcode | Rpcode) => {
let (font, slot) = self.font_character_target(files)?;
self.optional_equals(files)?;
@@ -409,6 +409,8 @@ impl Executor {
| Hyphenchar
| Lpcode
| Rpcode
| Efcode
| Pdffontexpand
| Skewchar
| Textfont
| Scriptfont
@@ -783,7 +783,8 @@ impl Executor {
| Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode
| Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Textfont | Scriptfont
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand
| Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
@@ -225,6 +225,7 @@ impl Executor {
| Primitive::Hyphenchar
| Primitive::Lpcode
| Primitive::Rpcode
| Primitive::Efcode
| Primitive::Skewchar
)
)
@@ -276,7 +277,7 @@ impl Executor {
}
Ok(n as i32)
}
fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
pub(super) fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if let Some(t) = self.expanded(files)?
&& !t.token.kind.is_space()
{
@@ -51,7 +51,7 @@ impl FontInstance {
self.metrics().map_or(0, TfmMetrics::size_sp)
}
pub fn metrics(&self) -> Option<&TfmMetrics> {
self.glyph_font.as_ref().map(|f| &f.metrics)
self.glyph_font.as_ref().map(|f| f.metrics())
}
pub fn parameters(&self) -> &[i32] {
&self.parameters
@@ -138,6 +138,13 @@ impl Default for FontLimits {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) struct FontExpansion {
pub stretch: i32,
pub shrink: i32,
pub step: i32,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog {
fonts: Vec<FontInstance>,
@@ -146,6 +153,10 @@ pub struct FontCatalog {
limits: FontLimits,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion: BTreeMap<FontId, FontExpansion>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion_codes: BTreeMap<FontId, BTreeMap<u8, u16>>,
}
impl Default for FontCatalog {
fn default() -> Self {
@@ -176,6 +187,8 @@ impl FontCatalog {
parameter_words: 7,
limits,
protrusion: BTreeMap::new(),
expansion: BTreeMap::new(),
expansion_codes: BTreeMap::new(),
})
}
pub fn fonts(&self) -> &[FontInstance] {
@@ -271,8 +284,9 @@ impl FontCatalog {
let glyph_font = Arc::new(crate::native_font::NativeFont {
id,
name: name.into(),
metrics,
metrics: Arc::new(metrics),
resource: self.resources[resource].clone(),
expansion: 0,
});
self.fonts.push(FontInstance {
name: name.into(),
@@ -331,6 +345,62 @@ impl FontCatalog {
self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code;
}
}
pub(super) fn configure_expansion(
&mut self,
font: FontId,
stretch: i32,
shrink: i32,
step: i32,
automatic: bool,
) -> Result<(), String> {
self.glyph_font(font)?;
let step = step.clamp(0, 100);
if step == 0 {
return Err("invalid font expansion step".into());
}
let stretch = stretch.clamp(0, 1000) / step * step;
let shrink = shrink.clamp(0, 500) / step * step;
if stretch == 0 && shrink == 0 {
return Err("invalid font expansion limits".into());
}
if !automatic {
return Err("native font expansion requires autoexpand; external expanded metrics are unsupported".into());
}
let config = FontExpansion { stretch, shrink, step };
if self.expansion.get(&font).is_some_and(|old| *old != config) {
return Err("font has already been configured with different expansion settings".into());
}
self.expansion.insert(font, config);
Ok(())
}
pub(super) fn has_expansion(&self) -> bool {
!self.expansion.is_empty()
}
pub(super) fn expansion(&self, font: FontId) -> Option<FontExpansion> {
self.expansion.get(&font).copied()
}
pub(super) fn expansion_code(&self, font: FontId, slot: u8) -> i32 {
self.expansion_codes
.get(&font)
.and_then(|codes| codes.get(&slot))
.map_or(1000, |code| i32::from(*code))
}
pub(super) fn set_expansion_code(&mut self, font: FontId, slot: u8, code: i32) {
let code = code.clamp(0, 1000);
if code < 1000 {
self.expansion_codes.entry(font).or_default().insert(slot, code as u16);
} else if let Some(codes) = self.expansion_codes.get_mut(&font) {
codes.remove(&slot);
if codes.is_empty() {
self.expansion_codes.remove(&font);
}
}
}
pub fn set_integers(&mut self, id: FontId, integers: FontIntegers) -> Result<(), String> {
self.font(id)?;
self.fonts[id.0 as usize].integers = integers;
@@ -49,7 +49,7 @@ pub(super) fn text_glyph_from_font(
) -> HorizontalBox {
let f = face.metrics();
let c = char::from(slot);
let (width, height, depth, italic) = (f.width(c), f.height(c), f.depth(c), f.italic(c));
let (width, height, depth, italic) = (face.advance(slot), f.height(c), f.depth(c), f.italic(c));
HorizontalBox {
width,
height,
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 32;
const COMPATIBLE_SCHEMAS: [u32; 4] = [27, 28, 31, SCHEMA];
const SCHEMA: u32 = 33;
const COMPATIBLE_SCHEMAS: [u32; 5] = [27, 28, 31, 32, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -4,6 +4,7 @@ use crate::{HorizontalBox, Paragraph, ParagraphFont};
use std::collections::BTreeMap;
mod break_cache;
mod expansion;
mod protrusion;
use break_cache::BreakNode;
pub use break_cache::{LineBreakCache, LineBreakWork};
@@ -557,6 +558,7 @@ fn break_lines(
nodes: &[TextNode],
projected: &[BreakNode],
margins: Option<&protrusion::Search>,
expansion: Option<&expansion::Search>,
p: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine],
pass: u8,
@@ -743,7 +745,10 @@ fn break_lines(
|| p[&Parameter::Parfillskip].glue().canonical_zero;
margins.width(a.start, b.end, a.post_break, b.pre_break, right_visible)
});
let delta = target - natural + hanging;
let shortfall = target - natural + hanging;
let delta = expansion.map_or(shortfall, |expansion| {
expansion.residual(shortfall, a.start, b.end, a.post_break, b.pre_break)
});
let infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = if delta >= 0 {
if infinite {
@@ -964,7 +969,10 @@ fn pack(
p[&Parameter::Rightskip].glue(),
Parameter::Rightskip,
));
let (material, adjustments) = super::marks::extract(material);
let (mut material, adjustments) = super::marks::extract(material);
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
expansion::pack(state, &mut material, target)?;
}
let shrinking = material.iter().map(width).sum::<i64>() > target;
let mut b = super::boxes::hpack(
material,
@@ -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(())
}
@@ -112,6 +112,7 @@ pub enum Parameter {
Lineskip,
Tabskip,
Pdfprotrudechars,
Pdfadjustspacing,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -227,6 +228,7 @@ impl Parameter {
Self::Lineskip,
Self::Tabskip,
Self::Pdfprotrudechars,
Self::Pdfadjustspacing,
];
pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase()
@@ -317,6 +317,8 @@ pub enum Primitive {
Pdflastmatch,
Lpcode,
Rpcode,
Efcode,
Pdffontexpand,
}
impl Primitive {
@@ -739,6 +741,8 @@ impl Default for State {
("hyphenchar", Hyphenchar),
("lpcode", Lpcode),
("rpcode", Rpcode),
("efcode", Efcode),
("pdffontexpand", Pdffontexpand),
("fontname", Fontname),
("fontdimen", Fontdimen),
("skewchar", Skewchar),