diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index a5333e2..a1fcb0e 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -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, }, Box(DiagnosticBox), @@ -151,6 +153,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec { 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::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::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() { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 8a98c88..f9ef5be 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -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)?; diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index 2a9b0e2..71cc75c 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -409,6 +409,8 @@ impl Executor { | Hyphenchar | Lpcode | Rpcode + | Efcode + | Pdffontexpand | Skewchar | Textfont | Scriptfont diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 51eff22..b3017d0 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -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 diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index 2cfa819..adfcdb8 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -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() { diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index 9b3b848..65e8967 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -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, @@ -146,6 +153,10 @@ pub struct FontCatalog { limits: FontLimits, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] protrusion: BTreeMap>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + expansion: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + expansion_codes: BTreeMap>, } 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 { + 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; diff --git a/crates/texrra-tex-core/src/execution/fonts.rs b/crates/texrra-tex-core/src/execution/fonts.rs index 32bfe29..fa79306 100644 --- a/crates/texrra-tex-core/src/execution/fonts.rs +++ b/crates/texrra-tex-core/src/execution/fonts.rs @@ -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, diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 9934d64..a131dae 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -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)] diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index 08f2fb9..0dd3803 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -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, 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::() > target; let mut b = super::boxes::hpack( material, 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 d5a860c..4d8178a 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -48,6 +48,7 @@ struct Entry { hash: u64, nodes: Vec, margins: Option, + expansion: Option, parameters: BTreeMap, shape: Vec, 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, diff --git a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs new file mode 100644 index 0000000..25206ba --- /dev/null +++ b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs @@ -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, + slot: u8, + width: i64, +} + +fn character(node: &TextNode) -> Option> { + 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 { + 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 { + 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, + ) -> 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(()) +} diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 18b2add..09cbdb2 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -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() diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index a52132b..3b6a4b1 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -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), diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 95d5caf..d3e7ee1 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -54,9 +54,17 @@ impl NativeFontProgram { pub struct NativeFont { pub id: FontId, pub name: String, - pub metrics: TfmMetrics, + pub metrics: Arc, pub resource: FontResource, + /// Horizontal font adjustment in thousandths. The backing TFM and + /// outline program are the original font at the original point size. + #[serde(default, skip_serializing_if = "unexpanded")] + pub expansion: i32, } +pub(crate) fn unexpanded(amount: &i32) -> bool { + *amount == 0 +} + impl NativeFont { pub fn metrics(&self) -> &TfmMetrics { &self.metrics @@ -64,6 +72,22 @@ impl NativeFont { pub fn size_sp(&self) -> i64 { self.metrics.size_sp() } + pub fn advance(&self, slot: u8) -> i64 { + let width = self.metrics.width(char::from(slot)); + if self.expansion == 0 { + return width; + } + crate::pdf_device::magnify(width, 1000 + self.expansion) + } + pub(crate) fn same_base(&self, other: &Self) -> bool { + std::ptr::eq(self, other) + || (self.id == other.id + && self.name == other.name + && (Arc::ptr_eq(&self.metrics, &other.metrics) || self.metrics == other.metrics) + && self.resource.version == other.resource.version + && (Arc::ptr_eq(&self.resource.data, &other.resource.data) + || self.resource.data == other.resource.data)) + } pub fn has_slot(&self, slot: u8) -> bool { self.metrics.has_slot(slot) } @@ -294,7 +318,7 @@ fn resolve_physical_fonts( let entry = used .entry(font.id) .or_insert_with(|| (font.clone(), BTreeSet::new())); - if entry.0.as_ref() != font.as_ref() { + if !Arc::ptr_eq(&entry.0, font) && !entry.0.same_base(font) { return Err("native font ids from different jobs cannot share output".into()); } entry.1.insert(*slot); diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index dcd26e2..106b44c 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -18,6 +18,7 @@ struct Expansion<'a, F> { files: &'a mut F, virtuals: BTreeMap, Option>)>, local_fonts: BTreeMap<(String, String, i64), Arc>, + expanded_fonts: BTreeMap<(FontId, i32), Arc>, last_id: u32, commands: usize, } @@ -46,7 +47,7 @@ fn offset(point: i64, delta: i64) -> Result { impl<'a, F: SourceProvider> Expansion<'a, F> { fn lookup(&mut self, font: &Arc) -> Result>, String> { if let Some((old, vf)) = self.virtuals.get(&font.id) { - if !Arc::ptr_eq(old, font) && old != font { + if !Arc::ptr_eq(old, font) && !old.same_base(font) { return Err("native font ids from different jobs cannot share output".into()); } return Ok(vf.clone()); @@ -104,7 +105,8 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { let font = Arc::new(NativeFont { id: FontId::for_device(self.last_id), name: local.name.clone(), - metrics, + metrics: Arc::new(metrics), + expansion: 0, resource: FontResource { version: file.version, data: Arc::new(file.data), @@ -164,7 +166,18 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { font.name )); } - let width = font.metrics.width(char::from(slot)); + let font = if glyph.font.expansion == 0 { + font + } else { + self.expanded_fonts + .entry((font.id, glyph.font.expansion)) + .or_insert_with(|| Arc::new(NativeFont { + expansion: glyph.font.expansion, + ..font.as_ref().clone() + })) + .clone() + }; + let width = font.advance(slot); let size = font.size_sp(); self.expand( Glyph { @@ -255,6 +268,7 @@ pub(super) fn expand_pages( files, virtuals: BTreeMap::new(), local_fonts: BTreeMap::new(), + expanded_fonts: BTreeMap::new(), last_id: 0x7fff_ffff, commands: 0, }; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 651bf60..e7c727f 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -441,6 +441,7 @@ fn native_pdf_font_size(size: i64) -> i64 { struct NativeTextRun { font: crate::execution::FontId, + expansion: i32, size: i64, y: i64, cursor: f64, @@ -451,7 +452,11 @@ impl NativeTextRun { fn flush(run: &mut Option, content: &mut String) { if let Some(run) = run.take() { content.push_str(&run.text); - content.push_str("] TJ ET\n"); + if run.expansion == 0 { + content.push_str("] TJ ET\n"); + } else { + content.push_str("] TJ 100 Tz ET\n"); + } } } fn push(&mut self, x: f64, slot: u8, face: &crate::native_font::NativeFont) { @@ -682,7 +687,7 @@ fn page_content( } if let Some(run) = &native_text { if run.point_size == 0.0 - || !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && *size==run.size && *y==run.y) + || !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && font.expansion==run.expansion && *size==run.size && *y==run.y) { NativeTextRun::flush(&mut native_text, &mut content); } @@ -704,14 +709,22 @@ fn page_content( let run = native_text.get_or_insert_with(|| { let point_size = native_font_units(font.size_sp(), 6_578_176, 1_000_000) as f64 / 10_000.0; + let spacing = if font.expansion == 0 { + String::new() + } else { + format!("{} Tz ", crate::pdf_device::print_decimal( + i64::from(1000 + font.expansion), 1, + )) + }; NativeTextRun { font: font.id, + expansion: font.expansion, size: *size, y: *y, cursor: pt(*x).parse().unwrap(), - point_size, + point_size: point_size * f64::from(1000 + font.expansion) / 1000.0, text: format!( - "BT /N{} {point_size:.4} Tf 1 0 0 1 {} {} Tm [", + "BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [", font.id.index(), pt(*x), pt(height - *y) @@ -1218,7 +1231,7 @@ fn native_pdf( return Err(format!("native font {} has no output encoding for slot {slot}",font.name)); } if let Some((old_font,old_paint))=fonts.insert(font.id,(font,paint)) { - if old_font != font || old_paint != paint { + if !old_font.same_base(font) || old_paint != paint { return Err("inconsistent native font snapshots or programs in PDF output".into()); } } @@ -1794,9 +1807,8 @@ fn write_pdf( } (font.clone(), paint.clone(), BTreeMap::new()) }); - assert_eq!( - entry.0.as_ref(), - font.as_ref(), + assert!( + entry.0.same_base(font), "native font ids from different jobs cannot share a PDF" ); entry.2.insert(*slot, *character); diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index c7c7ae8..7110c07 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -7,6 +7,7 @@ use crate::{ pub(super) struct NativeText { font: Option, effective_size: i64, + expansion: i32, v: i64, start_h: i64, delta_h: i64, @@ -30,6 +31,7 @@ impl NativeText { Self { font: None, effective_size: 0, + expansion: 0, v: height, start_h: 0, delta_h: 0, @@ -47,8 +49,21 @@ impl NativeText { print_decimal(number, 4) )); } + if state.expansion != font.expansion { + state.close_string(out); + state.expansion = font.expansion; + out.push_str(&format!( + "{} Tz\n", + print_decimal(i64::from(1000 + font.expansion), 1) + )); + } + let horizontal_size = if font.expansion == 0 { + state.effective_size + } else { + crate::pdf_device::magnify(state.effective_size, 1000 + font.expansion) + }; let (mut shift, shift_out) = - divide_scaled(x - state.start_h - state.delta_h, state.effective_size, 3); + divide_scaled(x - state.start_h - state.delta_h, horizontal_size, 3); let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0; let (v, v_out) = if (state.v - y).abs() >= minimum { divide_scaled(state.v - y, 6_578_176, digits + 2) @@ -77,7 +92,7 @@ impl NativeText { state.delta_h += shift_out; } out.push_str(&format!("<{slot:02X}>")); - state.delta_h += match &paint.program { + let advance = match &paint.program { crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot], crate::native_font::NativeFontProgram::Type1(_) => { divide_scaled( @@ -88,6 +103,11 @@ impl NativeText { .1 } }; + state.delta_h += if font.expansion == 0 { + advance + } else { + crate::pdf_device::magnify(advance, 1000 + font.expansion) + }; } fn close_string(&mut self, out: &mut String) { if self.opened { @@ -98,6 +118,9 @@ impl NativeText { pub(super) fn finish(text: &mut Option, out: &mut String) { if let Some(mut text) = text.take() { text.close_string(out); + if text.expansion != 0 { + out.push_str("100 Tz\n"); + } out.push_str("ET\n"); } } diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index b70ec83..26bdfe5 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -135,6 +135,7 @@ pub enum DisplayItem { struct NativeSvgGlyph<'a> { position: [i64; 2], size: i64, + expansion: i32, slot: u8, font: &'a str, glyph: &'a str, @@ -173,6 +174,7 @@ impl DisplayItem { Ok(NativeSvgGlyph { position: [*x, *y], size: *size, + expansion: font.expansion, slot: *slot, font: paint.program.name(), glyph: &paint.encoding[usize::from(*slot)], @@ -411,6 +413,7 @@ impl DisplayList { let NativeSvgGlyph { position: [x, y], size, + expansion, slot, font, glyph, @@ -423,12 +426,17 @@ impl DisplayList { let x = x as f64 / 65_536.0; let y = y as f64 / 65_536.0; let scale = size as f64 / 65_536_000.0; + let horizontal_scale = if expansion == 0 { + scale + } else { + scale * f64::from(1000 + expansion) / 1000.0 + }; let label = if type1 { crate::type1::glyph_unicode_text(glyph).unwrap_or_default() } else { String::new() }; - out.push_str(&format!("\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2])); + out.push_str(&format!("\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2])); } DisplayItem::MathGlyph { x, diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index d5f5d6d..a8d4f42 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -94,7 +94,12 @@ impl Bounds { } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum PaintKind { - Glyph { font: u32, slot: u8 }, + Glyph { + font: u32, + slot: u8, + #[serde(default, skip_serializing_if = "crate::native_font::unexpanded")] + expansion: i32, + }, Rule, PdfImage { page: usize }, } @@ -341,12 +346,13 @@ impl SourceMap { PaintKind::Glyph { font: font.id.index(), slot: *slot, + expansion: font.expansion, }, Bounds { x: *x, y: y.checked_sub(h) .ok_or("source map glyph position overflow")?, - width: scale(metrics.width(c))?, + width: scale(font.advance(*slot))?, height: h .checked_add(d) .ok_or("source map glyph height overflow")?, diff --git a/crates/texrra-tex-core/tests/execution_diagnostics.rs b/crates/texrra-tex-core/tests/execution_diagnostics.rs index f8459e5..687a2cc 100644 --- a/crates/texrra-tex-core/tests/execution_diagnostics.rs +++ b/crates/texrra-tex-core/tests/execution_diagnostics.rs @@ -417,3 +417,46 @@ fn margin_protrusion_uses_font_slots_in_break_search_and_shipout() { assert_eq!(page["glyphs"].as_u64(), Some(30)); assert!(page["max_coordinate_error_sp"].as_i64().unwrap() <= 1); } + +#[test] +fn font_expansion_codes_invalidate_cached_break_geometry() { + let source = r"\catcode123=1 \catcode125=2 +\font\roman=cmr10 \roman +\pdfoutput=1 +\pdffontexpand\roman 100 100 10 autoexpand +\hsize=30pt \parfillskip=0pt plus1fil \rightskip=0pt plus1fil +\pretolerance=100 \tolerance=200 \linepenalty=10 \baselineskip=12pt +\showboxbreadth=99 \showboxdepth=99 +\setbox0=\vbox{\pdfadjustspacing=1 \noindent AA AA\par} +\setbox1=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} +\setbox2=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} +\begingroup \efcode\roman65=0 \endgroup +\ifnum\efcode\roman65=0\else\errmessage{Expansion codes are global}\fi +\setbox3=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} +\showbox0 \showbox1 \showbox2 \showbox3 +\end +"; + let cache = std::sync::Arc::new(LineBreakCache::default()); + let executed = Executor::new(State::initex().with_etex(), Limits::default()) + .with_line_break_cache(cache.clone()) + .run( + SourceFile { + name: "font-expansion.tex".into(), + data: source.as_bytes().to_vec(), + }, + &mut Host::default(), + ) + .unwrap(); + let lists = reports(&executed); + assert_eq!(lists.len(), 4); + assert!(cache.work().reused_passes > 0); + for (report, expected_lines) in lists.iter().zip([2, 1, 1, 2]) { + assert_eq!( + report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(), + expected_lines, + "{}", + report.text + ); + assert_eq!(report.text.contains(r"\roman (-100) A"), expected_lines == 1); + } +} diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index 6f46a74..d33f693 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 32); + assert_eq!(payload["schema"], 33); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index 9ef159c..40d4716 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 32); + assert_eq!(original["schema"], 33); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index 8df9a3d..81714d9 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 32); + assert_eq!(payload["schema"], 33); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a597517..aec6870 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1126,6 +1126,32 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) +### 原生自动字宽伸缩 + +字宽伸缩参数进入真实字体目录和 schema33 格式。模式1在装盒时按字形 +的实际度量和代码选择量化比例。模式2也按断行区间和 discretionary 内容 +考虑可用伸缩量。断行缓存保存这部分度量投影。PDF 与 SVG 按比例绘制实际 +字体,来源映射保留比例和伸缩后的字形度量。本阶段支持自动伸缩,外置 +预伸缩 TFM 尚待接入。 +[pdfTeX 的伸缩参数与量化](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L17548-L17683) + +沿用冻结的 pdfTeX 四盒样例,另用同一段落对照模式1、模式2及关闭单字形 +伸缩。两组共7个盒诊断相同,10个 PDF 词框的坐标偏差为0 bp。第二组按 +同一顺序产生2、1、2行。一个定向回归验证同一会话的断行结果可复用, +并在代码改变后重新选择断点。独立最小格式重载实际代码500,输出中 +四个字形均为+50‰,来源映射的单字形宽度为516097 sp。 + +`target/p3-pdf-font-expansion-native` 的证据: + +- `witness-final/receipt.json` 为 `66485903072ed783283181d5b741cc75f893210821b3e7a414e564bfa34ce8e8`。 +- `break-final/receipt.json` 为 `8b79955a0367271116314a27b08233c57ba7b83c9c60ad50c9f5276228a351c6`。 +- `stored-expansion/receipt.json` 为 `83079cb38b9a1ced3ef8a74826abcd331ca18299d2c336678889bc8e0ad16862`。 +- `targeted-test-final.log` 为 `31b28eada6e82d08f9869fc9fdbcd9a11c87c03d73b724554e7a5f2d31988d49`。 + +最初混用同一基础字体的伸缩变体时触发 PDF 字体身份断言。已修正资源 +去重的比较规则。验证入口对预期 showbox 退出码和布局清单字段的误判 +原日志已保留。统一工作区回归、出版模板矩阵和正式性能采样留到功能集成。 + ### 原生段落边缘悬挂 `\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平