From 12d9eb6a54507b022a3176ad30ab438a3b36422a Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 07:41:45 +0800 Subject: [PATCH] Use external expanded font metrics in native paragraph layout --- .../src/execution/diagnostics.rs | 2 +- .../texrra-tex-core/src/execution/engine.rs | 9 +- .../src/execution/engine/fonts.rs | 7 +- .../src/execution/engine/paragraphs.rs | 11 +- .../src/execution/font_catalog.rs | 130 +++++++++++- .../src/execution/format_image.rs | 6 +- .../src/execution/paragraph.rs | 80 ++++---- .../src/execution/paragraph/expansion.rs | 190 +++++++++++++----- crates/texrra-tex-core/src/execution/state.rs | 7 + 9 files changed, 326 insertions(+), 116 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index 429e7cf..eef59ed 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -355,7 +355,7 @@ impl Printer<'_> { } } fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> { - let name = self.state.fonts.font(font)?.identifier_text(); + let (name, expansion) = self.state.fonts.diagnostic_font(font, expansion)?; self.command(&name); if expansion != 0 { self.literal(&format!(" ({expansion:+})")); diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 90a9ae4..1bb1ce7 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -3999,6 +3999,7 @@ impl Executor { files, )?, Some(Pdffontexpand) => { + let span = self.current; let font = self.font_identifier(files)?; self.optional_equals(files)?; let stretch = self.integer(files)?; @@ -4008,9 +4009,15 @@ impl Executor { if automatic { self.optional_space(files)?; } + let from = self.source_name(span); + let defaults = if automatic { + self.state.font_defaults() + } else { + self.font_defaults() + }; self.state .fonts - .configure_expansion(font, stretch, shrink, step, automatic) + .configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files) .map_err(|message| self.error(message, self.current))?; } Some(Efcode) => { diff --git a/crates/texrra-tex-core/src/execution/engine/fonts.rs b/crates/texrra-tex-core/src/execution/engine/fonts.rs index 5ded30c..5a8ebde 100644 --- a/crates/texrra-tex-core/src/execution/engine/fonts.rs +++ b/crates/texrra-tex-core/src/execution/engine/fonts.rs @@ -38,10 +38,9 @@ impl Executor { } pub(super) fn font_defaults(&mut self) -> FontIntegers { - FontIntegers { - hyphen: self.read_parameter(Parameter::Defaulthyphenchar).width(), - skew: self.read_parameter(Parameter::Defaultskewchar).width(), - } + self.reads.insert(Dependency::Parameter(Parameter::Defaulthyphenchar)); + self.reads.insert(Dependency::Parameter(Parameter::Defaultskewchar)); + self.state.font_defaults() } pub(super) fn font_dimension_target( diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index de676be..5929eb9 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -437,20 +437,17 @@ impl Executor { self.reads.insert(Dependency::TextFont); let start = b.vertical_start; let span = b.span; - let mut trace = super::super::paragraph_trace::Tracer::new( - &self.state, - self.limits.tokens.saturating_sub(self.diagnostic_bytes), - ); + let mut records = Vec::new(); let result = super::super::paragraph::finish( b, - &self.state, + &mut self.state, final_widow, &mut self.steps, self.limits.steps, - &mut trace, + (self.limits.tokens.saturating_sub(self.diagnostic_bytes), &mut records), self.line_break_cache.as_deref(), + files, ); - let records = trace.into_records(); if !records.is_empty() { self.reads.insert(Dependency::EscapeChar); self.reads.insert(Dependency::NewLineChar); diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index af7ac95..eb21bb3 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -40,6 +40,8 @@ pub struct FontInstance { parameters: Vec, integers: FontIntegers, selector: CommandName, + #[serde(default, skip_serializing_if = "Option::is_none")] + expansion_origin: Option<(FontId, i32)>, } impl FontInstance { pub fn name(&self) -> &str { @@ -146,6 +148,12 @@ pub(super) struct FontExpansion { pub step: i32, } +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +struct ExternalExpansion { + from: String, + variants: BTreeMap, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) struct PdfFontSettings { pub(crate) attributes: Vec, @@ -188,6 +196,8 @@ pub struct FontCatalog { #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] expansion: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + external_expansion: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] expansion_codes: BTreeMap>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(super) pdf_settings: BTreeMap, @@ -216,6 +226,7 @@ impl FontCatalog { skew: -1, }, selector: CommandName::Control("nullfont".into()), + expansion_origin: None, }], resources: Vec::new(), parameter_words: 7, @@ -223,6 +234,7 @@ impl FontCatalog { protrusion: BTreeMap::new(), auto_kern: BTreeMap::new(), expansion: BTreeMap::new(), + external_expansion: BTreeMap::new(), expansion_codes: BTreeMap::new(), pdf_settings: BTreeMap::new(), }) @@ -279,7 +291,9 @@ impl FontCatalog { // Canonical resource identity alone must not merge distinct names or // areas. Re-defining an older font does not make it the last loaded one. for (index, f) in self.fonts.iter_mut().enumerate().skip(1) { - if f.name == name && f.area == area { + // A font attached to an expansion family has an internal + // identity. A later explicit definition loads a separate font. + if f.name == name && f.area == area && f.expansion_origin.is_none() { let m = f.metrics().unwrap(); if m.requested_size(size).is_ok_and(|n| n == m.size_sp()) { f.selector = selector; @@ -430,6 +444,7 @@ impl FontCatalog { parameters, integers: defaults, selector, + expansion_origin: None, }); self.parameter_words += count; Ok(id) @@ -523,12 +538,16 @@ impl FontCatalog { pub(super) fn configure_expansion( &mut self, font: FontId, - stretch: i32, - shrink: i32, - step: i32, + from: &str, + (stretch, shrink, step): (i32, i32, i32), automatic: bool, + defaults: FontIntegers, + files: &mut impl SourceProvider, ) -> Result<(), String> { self.glyph_font(font)?; + if self.font(font)?.expansion_origin.is_some() { + return Err("cannot configure expansion on an expanded font".into()); + } let step = step.clamp(0, 100); if step == 0 { return Err("invalid font expansion step".into()); @@ -538,17 +557,110 @@ impl FontCatalog { 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()); + let external = !automatic; + if let Some(old) = self.expansion.get(&font) { + if *old != config || self.has_external_expansion(font) != external { + return Err("font has already been configured with different expansion settings".into()); + } + return Ok(()); + } + if external { + let mut variants = BTreeMap::new(); + // The extremes are read when declared; intermediate sizes only + // when packing selects them for actual text. + for amount in [stretch, -shrink].into_iter().filter(|n| *n != 0) { + let variant = self.load_external_variant(font, amount, from, defaults, files)?; + variants.insert(amount, variant); + } + self.external_expansion.insert(font, ExternalExpansion { from: from.into(), variants }); } self.expansion.insert(font, config); Ok(()) } + fn load_external_variant( + &mut self, + font: FontId, + amount: i32, + from: &str, + defaults: FontIntegers, + files: &mut impl SourceProvider, + ) -> Result { + let base = self.font(font)?; + let size = base.size_sp(); + let name = format!("{}{amount:+}", base.name); + let variant = if let Some(index) = self.fonts.iter().position(|f| { + f.name == name && f.size_sp() == size && f.expansion_origin.is_none() + }) { + FontId(index as u32) + } else { + self.check_font_capacity()?; + let filename = format!("{name}.tfm"); + let (loaded, metrics) = Self::read_tfm(files, &filename, from, FontSize::At(size)) + .map_err(|error| format!("cannot load expanded font {filename}: {error}"))?; + self.insert_font( + (&name, ""), + loaded, + metrics, + CommandName::Control(String::new()), + defaults, + None, + )? + }; + self.fonts[variant.index() as usize].expansion_origin = Some((font, amount)); + Ok(variant) + } + + pub(super) fn external_limit( + &self, + font: FontId, + amount: i32, + ) -> Result, String> { + let Some(expansion) = self.external_expansion.get(&font) else { + return Ok(None); + }; + let variant = expansion.variants.get(&amount).ok_or("missing external expansion limit")?; + Ok(Some(self.glyph_font(*variant)?.metrics())) + } + + pub(super) fn expansion_face( + &mut self, + font: &Arc, + amount: i32, + defaults: FontIntegers, + files: &mut impl SourceProvider, + ) -> Result, String> { + let Some(external) = self.external_expansion.get(&font.id) else { + return Ok(Arc::new(NativeFont { + expansion: amount, + ..font.as_ref().clone() + })); + }; + let variant = if let Some(variant) = external.variants.get(&amount) { + *variant + } else { + let from = external.from.clone(); + let variant = self.load_external_variant(font.id, amount, &from, defaults, files)?; + self.external_expansion.get_mut(&font.id).unwrap().variants.insert(amount, variant); + variant + }; + Ok(self.glyph_font(variant)?.clone()) + } + + pub(super) fn diagnostic_font(&self, font: FontId, expansion: i32) -> Result<(String, i32), String> { + let f = self.font(font)?; + if let Some((base, amount)) = f.expansion_origin { + Ok((self.font(base)?.identifier_text(), amount)) + } else { + Ok((f.identifier_text(), expansion)) + } + } + + pub(super) fn has_external_expansion(&self, font: FontId) -> bool { + self.external_expansion.contains_key(&font) + } + pub(super) fn has_expansion(&self) -> bool { !self.expansion.is_empty() } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 7e7b61a..d6c2698 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 51; -const COMPATIBLE_SCHEMAS: [u32; 20] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, SCHEMA, +const SCHEMA: u32 = 52; +const COMPATIBLE_SCHEMAS: [u32; 21] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index 298851b..2ba6be3 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -951,8 +951,9 @@ fn pack( last: bool, terminal_marker: bool, ends_in_pre_break: bool, - state: &State, + state: &mut State, span: Span, + files: &mut impl SourceProvider, ) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> { let left = p[&Parameter::Leftskip].glue(); let mut material = Vec::new(); @@ -986,7 +987,7 @@ fn pack( )); let (mut material, adjustments) = super::marks::extract(material); if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() { - expansion::pack(state, &mut material, target)?; + expansion::pack(state, &mut material, target, files)?; } let shrinking = material.iter().map(width).sum::() > target; let mut b = super::boxes::hpack( @@ -1057,12 +1058,13 @@ fn pre_display_line_size( } pub(super) fn finish( mut b: Builder, - state: &State, + state: &mut State, final_widow: Parameter, steps: &mut usize, step_limit: usize, - trace: &mut super::paragraph_trace::Tracer<'_>, + (trace_limit, records): (usize, &mut Vec), cache: Option<&LineBreakCache>, + files: &mut impl SourceProvider, ) -> Result { b.finish_text(true, state)?; if b.nodes.last().is_some_and(|n| { @@ -1113,42 +1115,43 @@ pub(super) fn finish( return Err("unsupported infinite paragraph background glue".into()); } } - let mut work = 0; + let mut trace = super::paragraph_trace::Tracer::new(state, trace_limit); let mut missing_glyphs = Vec::new(); - let mut result = None; - let mut selected_pass = 0; - for pass in 0..3 { - if pass == 0 && parameters[&Parameter::Pretolerance].width() < 0 { - continue; - } - if pass == 1 { - add_hyphens( - &mut b.nodes, + let search = (|| { + let mut work = 0; + for pass in 0..3 { + if pass == 0 && parameters[&Parameter::Pretolerance].width() < 0 { + continue; + } + if pass == 1 { + add_hyphens( + &mut b.nodes, + state, + b.initial_language, + &mut missing_glyphs, + steps, + step_limit, + )?; + } + trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?; + if let Some(path) = break_cache::solve( + &b.nodes, + ¶meters, state, - b.initial_language, - &mut missing_glyphs, - steps, - step_limit, - )?; + shape, + pass, + &mut work, + b.previous_lines, + &mut trace, + cache, + )? { + return Ok((path, pass)); + } } - trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?; - if let Some(path) = break_cache::solve( - &b.nodes, - ¶meters, - state, - shape, - pass, - &mut work, - b.previous_lines, - trace, - cache, - )? { - result = Some(path); - selected_pass = pass; - break; - } - } - let path = result.ok_or("native paragraph has no legal break sequence")?; + Err(String::from("native paragraph has no legal break sequence")) + })(); + *records = trace.into_records(); + let (path, selected_pass) = search?; let mut start = 0; let mut post = None; let mut lines = Vec::new(); @@ -1174,7 +1177,7 @@ pub(super) fn finish( true, point.zero_tail, ); - let dimensions = geometry(¶meters, shape, i + b.previous_lines); + let dimensions = geometry(¶meters, state.paragraph_shape(), i + b.previous_lines); let ends_in_pre_break = point.pre_break.is_some_and(|index| { matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty()) }); @@ -1190,6 +1193,7 @@ pub(super) fn finish( ends_in_pre_break, state, b.span, + files, )?; packed_diagnostic.push(line_box.diagnostic_eligible); packed_shrinking.push(shrinking); diff --git a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs index 25206ba..9a740da 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs @@ -1,6 +1,6 @@ //! 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 super::{FontId, SourceProvider, State, TextNode, metrics}; use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device}; use std::{collections::BTreeMap, ops::AddAssign, sync::Arc}; @@ -94,21 +94,34 @@ fn capacity( at: usize, limits: Option<&mut Limits>, ) -> Result { - let measure = |font: &NativeFont, slot, width, kern| { + let measure = |font: &NativeFont, slot: u8, width, right: Option| { let Some(config) = state.fonts.expansion(font.id) else { - return Capacity::default(); + return Ok(Capacity::default()); }; if font.expansion != 0 { - return Capacity::default(); + return Ok(Capacity::default()); } + let limit_width = |amount| -> Result { + if amount == 0 { + return Ok(width); + } + let Some(external) = state.fonts.external_limit(font.id, amount)? else { + return Ok(pdf_device::magnify(width, 1000 + amount)); + }; + let left = char::from(slot); + Ok(match right { + Some(right) => external.kern(left, char::from(right)), + None => external.width(left), + }) + }; 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) }), - } + let scale = |value: i64| { + pdf_device::magnify(if right.is_some() { value } else { value.max(0) }, code) + }; + Ok(Capacity { + stretch: scale(limit_width(config.stretch)? - width), + shrink: scale(width - limit_width(-config.shrink)?), + }) }; if let Some(glyph) = character(&nodes[at]) { if glyph.font.expansion == 0 @@ -117,7 +130,7 @@ fn capacity( { limits.include(config)?; } - return Ok(measure(glyph.font, glyph.slot, glyph.width, false)); + return measure(glyph.font, glyph.slot, glyph.width, None); } if let TextNode::Kern { width, @@ -132,7 +145,7 @@ fn capacity( // 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)); + return measure(left.font, left.slot, kern, Some(right.slot)); } } Ok(Capacity::default()) @@ -213,11 +226,11 @@ impl Search { } } -fn glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 { - let Some(config) = state.fonts.expansion(glyph.font.id) else { +fn slot_ratio(state: &State, font: &NativeFont, slot: u8, line_ratio: i32) -> i32 { + let Some(config) = state.fonts.expansion(font.id) else { return 0; }; - if glyph.font.expansion != 0 { + if font.expansion != 0 { return 0; } let max = if line_ratio < 0 { @@ -225,19 +238,81 @@ fn glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 { } else { config.stretch }; - let code = state.fonts.expansion_code(glyph.font.id, glyph.slot); + let code = state.fonts.expansion_code(font.id, 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> { +#[derive(Default)] +struct PackingFonts(BTreeMap<(FontId, i32), Arc>); + +impl PackingFonts { + fn select( + &mut self, + state: &mut State, + font: &Arc, + amount: i32, + files: &mut impl SourceProvider, + ) -> Result, String> { + use std::collections::btree_map::Entry; + let selected = match self.0.entry((font.id, amount)) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let defaults = state.font_defaults(); + entry.insert(state.fonts.expansion_face(font, amount, defaults, files)?) + } + }; + Ok(selected.clone()) + } + + fn external_margin( + &mut self, + state: &mut State, + font: FontId, + slot: u8, + right: bool, + ratio: i32, + files: &mut impl SourceProvider, + ) -> Result, String> { + if !state.fonts.has_external_expansion(font) { + return Ok(None); + } + let base = state.fonts.glyph_font(font)?.clone(); + let amount = slot_ratio(state, &base, slot, ratio); + if amount == 0 { + return Ok(None); + } + let face = self.select(state, &base, amount, files)?; + let code = state.fonts.protrusion_code(font, slot, right); + let quad = i64::from(state.fonts.font(face.id)?.quad()); + Ok(Some((-pdf_device::magnify(quad, code) as i32, face.id))) + } +} + +pub(super) fn pack( + state: &mut State, + material: &mut [TextNode], + target: i64, + files: &mut impl SourceProvider, +) -> 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 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 available = if shortfall < 0 { capacity.shrink } else { @@ -248,54 +323,63 @@ pub(super) fn pack(state: &State, material: &mut [TextNode], target: i64) -> Res } 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")?; + if let TextNode::MarginKern { ref mut width, right, ref mut font, slot } = material[i] { + if let Some((expanded, selected)) = fonts.external_margin(state, *font, slot, right, ratio, files)? { + *width = expanded; + *font = selected; } + continue; } - } - for node in material { - let Some(glyph) = character(node) else { + let Some(glyph) = character(&material[i]) else { continue; }; - let amount = glyph_ratio(state, &glyph, ratio); + let amount = slot_ratio(state, glyph.font, glyph.slot, 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 { + let face = fonts.select(state, glyph.font, amount, files)?; + let character = char::from(glyph.slot); + let external = face.expansion == 0; + if external && !face.has_slot(glyph.slot) { + return Err(format!("expanded font {} has no TFM slot {}", face.name, glyph.slot)); + } + // The external left font has already changed when pdfTeX checks + // the pair for substitution. The two font identities differ, so + // the original kern remains even though the limits affect capacity. + if !external + && let Some(TextNode::Kern { width, explicit: false }) = material.get(i + 1) + && let Some((left, right)) = pair(material, i + 1) + { + let original = left.font.metrics().kern(character, char::from(right.slot)); + if original == i64::from(*width) + && let TextNode::Kern { width, .. } = &mut material[i + 1] + { + *width = i32::try_from(pdf_device::magnify(original, 1000 + amount)) + .map_err(|_| "expanded native font kern exceeds the scaled point range")?; + } + } + let TextNode::Glyph { font, glyph, .. } = &mut material[i] 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"); + *font = face.id; + if external { + glyph.width = face.metrics().width(character); + glyph.height = face.metrics().height(character); + glyph.depth = face.metrics().depth(character); + glyph.italic = face.metrics().italic(character); + } else { + 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; + geometry.metrics.height = glyph.height; + geometry.metrics.depth = glyph.depth; let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else { unreachable!() }; - *font = face.clone(); + *font = face; } Ok(()) } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 198d48c..fc9d68c 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1685,6 +1685,13 @@ impl State { pub fn group_depth(&self) -> usize { self.groups.len() } + pub(super) fn font_defaults(&self) -> super::FontIntegers { + super::FontIntegers { + hyphen: self.parameter(Parameter::Defaulthyphenchar).width(), + skew: self.parameter(Parameter::Defaultskewchar).width(), + } + } + pub fn fingerprint(&self) -> u64 { let mut hash = FingerprintHasher::default(); self.hash(&mut hash);