From 1e4c113b27459b4a1d5d5f13b0be4d0c3789f0b4 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 08:08:11 +0800 Subject: [PATCH] Measure external font expansion at paragraph break margins --- .../src/execution/font_catalog.rs | 8 ++ .../src/execution/paragraph.rs | 36 +++-- .../src/execution/paragraph/break_cache.rs | 18 ++- .../src/execution/paragraph/expansion.rs | 125 +++++++++++++++--- .../src/execution/paragraph/protrusion.rs | 105 ++++++++++----- .../src/execution/paragraph_trace.rs | 41 +++--- 6 files changed, 242 insertions(+), 91 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index eb21bb3..a687b92 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -612,6 +612,10 @@ impl FontCatalog { Ok(variant) } + pub(super) fn external_variant(&self, font: FontId, amount: i32) -> Option { + self.external_expansion.get(&font)?.variants.get(&amount).copied() + } + pub(super) fn external_limit( &self, font: FontId, @@ -657,6 +661,10 @@ impl FontCatalog { } } + pub(super) fn has_external_expansions(&self) -> bool { + !self.external_expansion.is_empty() + } + pub(super) fn has_external_expansion(&self, font: FontId) -> bool { self.external_expansion.contains_key(&font) } diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index 2ba6be3..8f5f4cc 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -572,14 +572,16 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) fn break_lines( nodes: &[TextNode], projected: &[BreakNode], - margins: Option<&protrusion::Search>, + mut margins: Option<&mut protrusion::Search>, expansion: Option<&expansion::Search>, + state: &mut State, + files: &mut impl SourceProvider, p: &BTreeMap, shape: &[ParagraphShapeLine], pass: u8, work: &mut usize, previous_lines: usize, - trace: &mut super::paragraph_trace::Tracer<'_>, + trace: &mut super::paragraph_trace::Tracer, ) -> Result>, String> { let get = |q| p[&q].width() as i64; let left = p[&Parameter::Leftskip].glue(); @@ -753,17 +755,26 @@ fn break_lines( if target < 0 && shape.is_empty() { return Err("negative native paragraph measure".into()); } - let hanging = margins.map_or(0, |margins| { + let mut shortfall = target - natural; + let mut margin_variation = expansion::Capacity::default(); + if let Some(margins) = margins.as_deref_mut() { // The active paragraph still ends in parfillskip. A nonzero // fill stops the right search at the terminal breakpoint. let right_visible = !final_break || p[&Parameter::Parfillskip].glue().canonical_zero; - margins.width(a.start, b.end, a.post_break, b.pre_break, right_visible) - }); - 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 edges = margins.edges(a.start, b.end, a.post_break, b.pre_break, right_visible); + shortfall += i64::from(edges[0].width) + i64::from(edges[1].width); + if shortfall != 0 && expansion.is_some() { + margin_variation = margins.variation(edges, state, files)?; + } + } + let delta = if let Some(expansion) = expansion { + expansion.residual( + shortfall, a.start, b.end, a.post_break, b.pre_break, margin_variation, + )? + } else { + shortfall + }; let infinite = stretch[1..].iter().any(|n| *n != 0); let bad = if delta >= 0 { if infinite { @@ -816,7 +827,7 @@ fn break_lines( get(Parameter::Doublehyphendemerits) }); } - trace.material(nodes, b.end)?; + trace.material(state, nodes, b.end)?; trace.push(ParagraphTrace::Feasible { position: b.end, kind: if final_break { @@ -1091,7 +1102,7 @@ pub(super) fn finish( .iter() .map(|p| (*p, state.parameter(*p))) .collect(); - let shape = state.paragraph_shape(); + let shape = state.paragraph_shape().to_vec(); for n in &b.nodes { if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) @@ -1138,7 +1149,8 @@ pub(super) fn finish( &b.nodes, ¶meters, state, - shape, + files, + &shape, pass, &mut work, b.previous_lines, diff --git a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs index 63378af..559705c 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -267,21 +267,24 @@ pub(super) fn candidate_widths( pub(super) fn solve( source: &[TextNode], parameters: &BTreeMap, - state: &State, + state: &mut State, + files: &mut impl SourceProvider, shape: &[ParagraphShapeLine], pass: u8, work: &mut usize, previous_lines: usize, - trace: &mut super::super::paragraph_trace::Tracer<'_>, + trace: &mut super::super::paragraph_trace::Tracer, cache: Option<&LineBreakCache>, ) -> Result { let nodes: Vec<_> = source.iter().map(BreakNode::project).collect(); - let margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1) - .then(|| protrusion::Search::new(state, source)); let expansion = (parameters[&Parameter::Pdfadjustspacing].width() > 1 && state.fonts.has_expansion()) .then(|| expansion::Search::new(state, source)) .transpose()?; + let expand_margins = expansion.is_some() && state.fonts.has_external_expansions(); + let mut margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1) + .then(|| protrusion::Search::new(state, source, expand_margins)) + .transpose()?; let retained = nodes.len() + shape.len() + margins.as_ref().map_or(0, protrusion::Search::len) @@ -289,6 +292,9 @@ pub(super) fn solve( let mut hash = None; if let Some(cache) = cache && retained <= RETAINED_NODES + // A pass that can assign a font has job effects. Only reuse search + // once all projected variations come from the live font table. + && !margins.as_ref().is_some_and(protrusion::Search::needs_fonts) && parameters[&Parameter::Tracingparagraphs].width() <= 0 { let mut hasher = DefaultHasher::new(); @@ -326,8 +332,10 @@ pub(super) fn solve( let result = break_lines( source, &nodes, - margins.as_ref(), + margins.as_mut(), expansion.as_ref(), + state, + files, parameters, shape, pass, diff --git a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs index 9a740da..c0d4801 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs @@ -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 { 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, pre: Option, - ) -> i64 { - let mut total = Capacity { + mut total: Capacity, + ) -> Result { + 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, 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, 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 { + 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 { + 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>); @@ -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 { diff --git a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs index 0e4228a..26d0dcd 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/protrusion.rs @@ -158,39 +158,60 @@ pub(super) fn margin_kern( }) } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct EdgeMeasure { + pub(super) width: i32, + expanding: Option<(FontId, u8)>, +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] struct Projected { - left: Option<(usize, i32)>, - right: Option<(usize, i32)>, - pre: Option, - post: Option, + left: Option<(usize, EdgeMeasure)>, + right: Option<(usize, EdgeMeasure)>, + pre: Option, + post: Option, } #[derive(Debug, PartialEq, Eq, Hash)] -pub(super) struct Search(Vec); +pub(super) struct Search { + widths: Vec, + variations: BTreeMap<(FontId, u8), expansion::MarginVariation>, +} impl Search { - pub(super) fn new(state: &State, nodes: &[TextNode]) -> Self { + pub(super) fn new(state: &State, nodes: &[TextNode], expand: bool) -> Result { let mut widths = vec![Projected::default(); nodes.len() + 1]; + let mut variations = BTreeMap::new(); + let mut project = |edge: Edge, right| -> Result { + use std::collections::btree_map::Entry; + let width = edge.width(state, right); + let mut expanding = None; + if expand && let Edge::Glyph(font, slot) = edge { + let key = (font, slot); + match variations.entry(key) { + Entry::Occupied(_) => expanding = Some(key), + Entry::Vacant(entry) => { + if let Some(variation) = expansion::MarginVariation::project(state, font, slot)? { + entry.insert(variation); + expanding = Some(key); + } + } + } + } + Ok(EdgeMeasure { width, expanding }) + }; for (i, node) in nodes.iter().enumerate() { let edge = Edge::node(node, true); widths[i + 1].right = if matches!(edge, Edge::Skip) { widths[i].right } else { - Some((i, edge.width(state, true))) + Some((i, project(edge, true)?)) }; - if let TextNode::Discretionary { - pre_break, - post_break, - .. - } = node - { - widths[i].pre = pre_break - .last() - .map(|node| Edge::character(node).width(state, true)); - widths[i].post = post_break - .first() - .map(|node| Edge::character(node).width(state, false)); + if let TextNode::Discretionary { pre_break, post_break, .. } = node { + widths[i].pre = pre_break.last() + .map(|node| project(Edge::character(node), true)).transpose()?; + widths[i].post = post_break.first() + .map(|node| project(Edge::character(node), false)).transpose()?; } } for (i, node) in nodes.iter().enumerate().rev() { @@ -198,36 +219,54 @@ impl Search { widths[i].left = if matches!(edge, Edge::Skip) { widths[i + 1].left } else { - Some((i, edge.width(state, false))) + Some((i, project(edge, false)?)) }; } - Self(widths) + Ok(Self { widths, variations }) } pub(super) fn len(&self) -> usize { - self.0.len() + self.widths.len() + self.variations.len() } - pub(super) fn width( + pub(super) fn needs_fonts(&self) -> bool { + self.variations.values().any(|v| matches!(v, expansion::MarginVariation::Pending { .. })) + } + + pub(super) fn edges( &self, start: usize, end: usize, post: Option, pre: Option, right_visible: bool, - ) -> i64 { - let left = post.and_then(|i| self.0[i].post).or_else(|| { - self.0[start] - .left + ) -> [EdgeMeasure; 2] { + let left = post.and_then(|i| self.widths[i].post).or_else(|| { + self.widths[start].left .filter(|(i, _)| *i < end) - .map(|(_, width)| width) + .map(|(_, edge)| edge) }); - let right = pre.and_then(|i| self.0[i].pre).or_else(|| { - self.0[end] - .right + let right = pre.and_then(|i| self.widths[i].pre).or_else(|| { + self.widths[end].right .filter(|(i, _)| right_visible && *i >= start) - .map(|(_, width)| width) + .map(|(_, edge)| edge) }); - i64::from(left.unwrap_or(0)) + i64::from(right.unwrap_or(0)) + [left.unwrap_or_default(), right.unwrap_or_default()] + } + + pub(super) fn variation( + &mut self, + edges: [EdgeMeasure; 2], + state: &mut State, + files: &mut impl SourceProvider, + ) -> Result { + let mut total = expansion::Capacity::default(); + for edge in edges { + if let Some(key) = edge.expanding { + total += self.variations.get_mut(&key).expect("projected margin glyph") + .resolve(state, key.0, files)?; + } + } + Ok(total) } } diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index 7593d8c..15b8c7f 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -110,8 +110,9 @@ pub struct ParagraphTraceReport { pub span: Span, } -pub(super) struct Tracer<'a> { - state: &'a State, +pub(super) struct Tracer { + escapechar: i32, + trailing_fill: bool, enabled: bool, records: Vec, printed: Option, @@ -120,10 +121,11 @@ pub(super) struct Tracer<'a> { bytes: usize, limit: usize, } -impl<'a> Tracer<'a> { - pub fn new(state: &'a State, limit: usize) -> Self { +impl Tracer { + pub fn new(state: &State, limit: usize) -> Self { Self { - state, + escapechar: state.escapechar, + trailing_fill: !state.parameter(Parameter::Parfillskip).glue().canonical_zero, enabled: state.parameter(Parameter::Tracingparagraphs).width() > 0, records: Vec::new(), printed: None, @@ -140,7 +142,7 @@ impl<'a> Tracer<'a> { if self.enabled { self.bytes = self.bytes.saturating_add( record - .text(self.state.escapechar) + .text(self.escapechar) .map_or(0, |s| s.len() + 1), ); if self.bytes > self.limit { @@ -159,11 +161,11 @@ impl<'a> Tracer<'a> { announced: pass != 1 || first_was_run, }) } - fn character(&mut self, font: FontId, text: &str, out: &mut String) -> Result<(), String> { + fn character(&mut self, state: &State, font: FontId, text: &str, out: &mut String) -> Result<(), String> { if font != self.font { out.push_str(&escape( - self.state.escapechar, - &self.state.fonts.font(font)?.identifier_text(), + self.escapechar, + &state.fonts.font(font)?.identifier_text(), )); out.push(' '); self.font = font; @@ -171,7 +173,7 @@ impl<'a> Tracer<'a> { out.push_str(text); Ok(()) } - fn short(&mut self, nodes: &[TextNode], out: &mut String) -> Result<(), String> { + fn short(&mut self, state: &State, nodes: &[TextNode], out: &mut String) -> Result<(), String> { let mut i = 0; while let Some(n) = nodes.get(i) { match n { @@ -183,7 +185,7 @@ impl<'a> Tracer<'a> { .. } => { let character = (*slot as char).to_string(); - self.character(*font, if *ligature { original } else { &character }, out)?; + self.character(state, *font, if *ligature { original } else { &character }, out)?; } TextNode::MathChar(b) => { if let Some(g) = &b.math_geometry @@ -191,7 +193,7 @@ impl<'a> Tracer<'a> { && let crate::math_engine_tex::MathItem::NativeGlyph { font, slot, .. } = &g.items[0].item { - self.character(font.id, &(*slot as char).to_string(), out)?; + self.character(state, font.id, &(*slot as char).to_string(), out)?; } else { return Err( "native math character short diagnostic structure is unavailable" @@ -226,8 +228,8 @@ impl<'a> Tracer<'a> { replacement_count, .. } => { - self.short(pre_break, out)?; - self.short(post_break, out)?; + self.short(state, pre_break, out)?; + self.short(state, post_break, out)?; i += usize::from(*replacement_count); } TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) @@ -240,19 +242,16 @@ impl<'a> Tracer<'a> { } Ok(()) } - pub fn material(&mut self, nodes: &[TextNode], end: usize) -> Result<(), String> { + pub fn material(&mut self, state: &State, nodes: &[TextNode], end: usize) -> Result<(), String> { if !self.enabled || self.printed == Some(end) { return Ok(()); } let mut text = String::new(); // short_display includes the breakpoint itself (not its following link). let stop = (end + 1).min(nodes.len()); - self.short(&nodes[self.next_material.min(stop)..stop], &mut text)?; - if end == nodes.len() { - let g = self.state.parameter(Parameter::Parfillskip).glue(); - if !g.canonical_zero { - text.push(' '); - } + self.short(state, &nodes[self.next_material.min(stop)..stop], &mut text)?; + if end == nodes.len() && self.trailing_fill { + text.push(' '); } self.push(ParagraphTrace::Material { text })?; self.printed = Some(end);