diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index a687b92..e69bcc3 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -37,7 +37,7 @@ pub struct FontInstance { area: String, resource: Option, glyph_font: Option>, - parameters: Vec, + parameters: Arc>, integers: FontIntegers, selector: CommandName, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -198,6 +198,8 @@ pub struct FontCatalog { #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] external_expansion: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + automatic_variants: 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, @@ -220,7 +222,7 @@ impl FontCatalog { area: String::new(), resource: None, glyph_font: None, - parameters: vec![0; 7], + parameters: Arc::new(vec![0; 7]), integers: FontIntegers { hyphen: 45, skew: -1, @@ -235,6 +237,7 @@ impl FontCatalog { auto_kern: BTreeMap::new(), expansion: BTreeMap::new(), external_expansion: BTreeMap::new(), + automatic_variants: BTreeMap::new(), expansion_codes: BTreeMap::new(), pdf_settings: BTreeMap::new(), }) @@ -245,6 +248,9 @@ impl FontCatalog { pub fn fonts(&self) -> &[FontInstance] { &self.fonts } + pub(super) fn parameter_words(&self) -> usize { + self.parameter_words + } pub fn resources(&self) -> &[FontResource] { &self.resources } @@ -433,6 +439,7 @@ impl FontCatalog { metrics: Arc::new(metrics), resource: self.resources[resource].clone(), expansion: 0, + layout_metrics: None, letter_spacing, pdf_space_font: false, }); @@ -441,7 +448,7 @@ impl FontCatalog { area: area.into(), resource: Some(resource), glyph_font: Some(glyph_font), - parameters, + parameters: Arc::new(parameters), integers: defaults, selector, expansion_origin: None, @@ -467,7 +474,7 @@ impl FontCatalog { if added > self.limits.parameter_words - self.parameter_words { return Err("native font parameter capacity exceeded".into()); } - self.fonts[id.0 as usize].parameters.resize(number, 0); + Arc::make_mut(&mut self.fonts[id.0 as usize].parameters).resize(number, 0); self.parameter_words += added; } Ok(number - 1) @@ -479,9 +486,44 @@ impl FontCatalog { } pub fn set_fontdimen(&mut self, id: FontId, number: i32, value: i32) -> Result<(), String> { let index = self.parameter_index(id, number)?; - self.fonts[id.0 as usize].parameters[index] = value; + // A synthesized font shares the sized parameters with its base. + // Replace the shared snapshot on assignment so older job states and + // checkpoints keep their original values. + let owner = self.parameter_owner(id); + if index >= self.fonts[owner.0 as usize].parameters.len() { + Arc::make_mut(&mut self.fonts[id.0 as usize].parameters)[index] = value; + return Ok(()); + } + let parameters = &mut self.fonts[owner.0 as usize].parameters; + Arc::make_mut(parameters)[index] = value; + if let Some(variants) = self.automatic_variants.get(&owner) { + let parameters = parameters.clone(); + for &variant in variants.values() { + if self.parameter_owner(variant) == owner { + let current = &mut self.fonts[variant.0 as usize].parameters; + if current.len() == parameters.len() { + *current = parameters.clone(); + } else { + Arc::make_mut(current)[index] = value; + } + } + } + } Ok(()) } + + fn parameter_owner(&self, id: FontId) -> FontId { + let font = &self.fonts[id.0 as usize]; + match font.expansion_origin { + Some((base, _)) + if font.glyph_font.as_ref().is_some_and(|glyph| glyph.expansion != 0) => + { + base + } + _ => id, + } + } + pub(super) fn protrusion_code(&self, font: FontId, slot: u8, right: bool) -> i32 { self.protrusion.get(&font).and_then(|font| font.get(&slot)) .map_or(0, |codes| i32::from(codes[usize::from(right)])) @@ -565,24 +607,27 @@ impl FontCatalog { } 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); - } + let mut variants = BTreeMap::new(); + // The two extremes have font numbers as soon as declared. Other + // quantized ratios are assigned when used by paragraph processing. + for amount in [stretch, -shrink].into_iter().filter(|n| *n != 0) { + let variant = self.load_expansion_variant(font, amount, automatic, from, defaults, files)?; + variants.insert(amount, variant); + } + if automatic { + self.automatic_variants.insert(font, variants); + } else { self.external_expansion.insert(font, ExternalExpansion { from: from.into(), variants }); } self.expansion.insert(font, config); Ok(()) } - fn load_external_variant( + fn load_expansion_variant( &mut self, font: FontId, amount: i32, + automatic: bool, from: &str, defaults: FontIntegers, files: &mut impl SourceProvider, @@ -594,6 +639,20 @@ impl FontCatalog { f.name == name && f.size_sp() == size && f.expansion_origin.is_none() }) { FontId(index as u32) + } else if automatic { + self.check_font_capacity()?; + let variant = FontId(self.fonts.len() as u32); + let glyph_font = Arc::new(NativeFont { + expansion: amount, + ..self.glyph_font(font)?.as_ref().clone() + }); + self.fonts.push(FontInstance { + name, + glyph_font: Some(glyph_font), + expansion_origin: Some((font, amount)), + ..base.clone() + }); + variant } else { self.check_font_capacity()?; let filename = format!("{name}.tfm"); @@ -612,44 +671,63 @@ 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 expansion_variant(&self, font: FontId, amount: i32) -> Option { + let variants = match self.external_expansion.get(&font) { + Some(expansion) => &expansion.variants, + None => self.automatic_variants.get(&font)?, + }; + variants.get(&amount).copied() } - 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_limit(&self, font: FontId, amount: i32) -> Result<&NativeFont, String> { + let variant = self.expansion_variant(font, amount).ok_or("missing font expansion limit")?; + Ok(self.glyph_font(variant)?) + } + + pub(super) fn has_unrecorded_expansion_limits(&self) -> bool { + self.expansion.keys().any(|font| { + !self.external_expansion.contains_key(font) && !self.automatic_variants.contains_key(font) + }) } pub(super) fn expansion_face( &mut self, - font: &Arc, + font: FontId, 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 + ) -> Result<(FontId, Arc), String> { + if let Some(external) = self.external_expansion.get(&font) { + let variant = if let Some(variant) = external.variants.get(&amount) { + *variant + } else { + let from = external.from.clone(); + let variant = self.load_expansion_variant(font, amount, false, &from, defaults, files)?; + self.external_expansion.get_mut(&font).unwrap().variants.insert(amount, variant); + variant + }; + return Ok((variant, self.glyph_font(variant)?.clone())); + } + let variant = if let Some(variant) = self.expansion_variant(font, 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); + let variant = self.load_expansion_variant(font, amount, true, "", defaults, files)?; + self.automatic_variants.entry(font).or_default().insert(amount, variant); variant }; - Ok(self.glyph_font(variant)?.clone()) + let metrics = self.glyph_font(variant)?; + // Logical font IDs belong to character lists. The PDF and SVG + // device still use the base font program and one horizontal scale. + let paint = if metrics.expansion != 0 { + metrics.clone() + } else { + Arc::new(NativeFont { + expansion: amount, + layout_metrics: Some(metrics.metrics.clone()), + ..self.glyph_font(font)?.as_ref().clone() + }) + }; + Ok((variant, paint)) } pub(super) fn diagnostic_font(&self, font: FontId, expansion: i32) -> Result<(String, i32), String> { @@ -661,10 +739,6 @@ 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) } @@ -702,9 +776,10 @@ impl FontCatalog { Ok(()) } pub fn character(&self, id: FontId, slot: u8) -> Result, String> { - let Some(m) = self.font(id)?.metrics() else { + let Some(font) = &self.font(id)?.glyph_font else { return Ok(None); }; + let m = font.metrics(); if !m.has_slot(slot) { return Ok(None); } @@ -713,10 +788,10 @@ impl FontCatalog { font: id, slot, size: m.size_sp(), - width: m.width(c), + width: font.advance(slot), height: m.height(c), depth: m.depth(c), - italic: m.italic(c), + italic: font.horizontal(m.italic(c)), })) } } diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index d6c2698..10118f9 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 = 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 SCHEMA: u32 = 53; +const COMPATIBLE_SCHEMAS: [u32; 22] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -124,6 +124,9 @@ impl FormatImage { { return Err("incompatible native format image".into()); } + if image.state.fonts.has_unrecorded_expansion_limits() { + return Err("native format must be rebuilt to restore automatic expansion font identities".into()); + } Ok(image) } 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 559705c..12fdd7d 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -281,7 +281,7 @@ pub(super) fn solve( && state.fonts.has_expansion()) .then(|| expansion::Search::new(state, source)) .transpose()?; - let expand_margins = expansion.is_some() && state.fonts.has_external_expansions(); + let expand_margins = expansion.is_some(); let mut margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1) .then(|| protrusion::Search::new(state, source, expand_margins)) .transpose()?; diff --git a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs index c0d4801..5769ad7 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/expansion.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/expansion.rs @@ -67,12 +67,13 @@ impl Limits { struct Character<'a> { font: &'a Arc, + id: FontId, slot: u8, width: i64, } fn character(node: &TextNode) -> Option> { - let TextNode::Glyph { glyph, slot, .. } = node else { + let TextNode::Glyph { font: id, glyph, slot, .. } = node else { return None; }; let geometry = glyph.math_geometry.as_ref()?; @@ -81,6 +82,7 @@ fn character(node: &TextNode) -> Option> { }; Some(Character { font, + id: *id, slot: *slot, width: glyph.width, }) @@ -89,7 +91,7 @@ fn character(node: &TextNode) -> Option> { 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) + (left.id == right.id && left.font.expansion == 0 && right.font.expansion == 0) .then_some((left, right)) } @@ -110,13 +112,10 @@ fn capacity( 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); + let variant = state.fonts.expansion_limit(font.id, amount)?; Ok(match right { - Some(right) => external.kern(left, char::from(right)), - None => external.width(left), + Some(right) => variant.horizontal(variant.metrics().kern(char::from(slot), char::from(right))), + None => variant.advance(slot), }) }; let code = state.fonts.expansion_code(font.id, slot); @@ -264,7 +263,7 @@ pub(super) enum MarginVariation { impl MarginVariation { pub(super) fn project(state: &State, font: FontId, slot: u8) -> Result, String> { - if !state.fonts.has_external_expansion(font) { + if state.fonts.expansion(font).is_none() { return Ok(None); } let face = state.fonts.glyph_font(font)?; @@ -279,7 +278,7 @@ impl MarginVariation { if amount == 0 { return Ok(Some(original)); } - let Some(variant) = state.fonts.external_variant(font, amount) else { + let Some(variant) = state.fonts.expansion_variant(font, amount) else { return Ok(None); }; let quad = i64::from(state.fonts.font(variant)?.quad()); @@ -303,14 +302,13 @@ impl MarginVariation { 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()); + let (selected, _) = state.fonts.expansion_face(font, amount, defaults, files)?; + let quad = i64::from(state.fonts.font(selected)?.quad()); Ok(pdf_device::magnify(quad, code)) }; let capacity = Capacity { @@ -325,18 +323,18 @@ impl MarginVariation { } #[derive(Default)] -struct PackingFonts(BTreeMap<(FontId, i32), Arc>); +struct PackingFonts(BTreeMap<(FontId, i32), (FontId, Arc)>); impl PackingFonts { fn select( &mut self, state: &mut State, - font: &Arc, + font: FontId, amount: i32, files: &mut impl SourceProvider, - ) -> Result, String> { + ) -> Result<(FontId, Arc), String> { use std::collections::btree_map::Entry; - let selected = match self.0.entry((font.id, amount)) { + let selected = match self.0.entry((font, amount)) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { let defaults = state.font_defaults(); @@ -346,7 +344,7 @@ impl PackingFonts { Ok(selected.clone()) } - fn external_margin( + fn margin( &mut self, state: &mut State, font: FontId, @@ -355,7 +353,7 @@ impl PackingFonts { ratio: i32, files: &mut impl SourceProvider, ) -> Result, String> { - if !state.fonts.has_external_expansion(font) { + if state.fonts.expansion(font).is_none() { return Ok(None); } let base = state.fonts.glyph_font(font)?.clone(); @@ -363,10 +361,10 @@ impl PackingFonts { if amount == 0 { return Ok(None); } - let face = self.select(state, &base, amount, files)?; + let (selected, _) = self.select(state, font, 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))) + let quad = i64::from(state.fonts.font(selected)?.quad()); + Ok(Some((-pdf_device::magnify(quad, code) as i32, selected))) } } @@ -380,7 +378,7 @@ pub(super) fn pack( let shortfall = target - natural; let mut fonts = PackingFonts::default(); let mut capacity = Capacity::default(); - if state.fonts.has_external_expansions() { + if state.fonts.has_expansion() { // Measuring the actual margin assigns its extreme variants before // glue setting decides whether to perform any substitution. for node in material.iter() { @@ -388,7 +386,7 @@ pub(super) fn pack( 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)? { + if let Some((expanded, _)) = fonts.margin(state, font, slot, right, ratio, files)? { *limit += i64::from(expanded) - i64::from(width); } } @@ -410,7 +408,7 @@ pub(super) fn pack( pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32; for i in 0..material.len() { 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)? { + if let Some((expanded, selected)) = fonts.margin(state, *font, slot, right, ratio, files)? { *width = expanded; *font = selected; } @@ -423,16 +421,13 @@ pub(super) fn pack( if amount == 0 { continue; } - let face = fonts.select(state, glyph.font, amount, files)?; + let (selected, paint) = fonts.select(state, glyph.id, 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 metrics = state.fonts.character(selected, glyph.slot)? + .ok_or_else(|| format!("expanded font has no TFM slot {}", glyph.slot))?; + // Reuse the original pair for synthesized kern scaling. A loaded + // TFM can affect capacity without replacing the original pair kern. + if state.fonts.glyph_font(selected)?.expansion != 0 && let Some(TextNode::Kern { width, explicit: false }) = material.get(i + 1) && let Some((left, right)) = pair(material, i + 1) { @@ -447,16 +442,11 @@ pub(super) fn pack( let TextNode::Glyph { font, glyph, .. } = &mut material[i] else { unreachable!() }; - *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); - } + *font = selected; + glyph.width = metrics.width; + glyph.height = metrics.height; + glyph.depth = metrics.depth; + glyph.italic = metrics.italic; let geometry = glyph.math_geometry.as_mut().expect("native character geometry"); geometry.metrics.width = glyph.width; geometry.metrics.height = glyph.height; @@ -464,7 +454,7 @@ pub(super) fn pack( let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else { unreachable!() }; - *font = face; + *font = paint; } Ok(()) } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index fc9d68c..d66767d 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1152,12 +1152,7 @@ impl State { + self.mathfonts.len(); c.usage.state.save_entries = self.groups.iter().map(|g| g.saved.len()).sum(); c.usage.state.font_instances = self.fonts.fonts().len() - 1; - c.usage.state.font_parameter_cells = self - .fonts - .fonts() - .iter() - .map(|f| f.parameters().len()) - .sum(); + c.usage.state.font_parameter_cells = self.fonts.parameter_words(); c.usage.state.tfm_resources = self.fonts.resources().len(); c.usage.state.tfm_resource_bytes = self.fonts.resources().iter().map(|r| r.version.bytes).sum(); diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index ad5c2d7..c60d87a 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -68,6 +68,10 @@ pub struct NativeFont { /// outline program are the original font at the original point size. #[serde(default, skip_serializing_if = "unexpanded")] pub expansion: i32, + /// Metrics from a TFM loaded before it joined an automatic expansion + /// family. The device embeds the base program but moves by these widths. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) layout_metrics: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub letter_spacing: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -91,12 +95,23 @@ impl NativeFont { pub fn size_sp(&self) -> i64 { self.metrics.size_sp() } + pub(crate) fn layout_metrics(&self) -> &TfmMetrics { + self.layout_metrics.as_deref().unwrap_or(&self.metrics) + } pub fn advance(&self, slot: u8) -> i64 { - let width = self.metrics.width(char::from(slot)); + let width = self.layout_metrics().width(char::from(slot)); + if self.layout_metrics.is_some() { + width + } else { + self.horizontal(width) + } + } + pub(crate) fn horizontal(&self, value: i64) -> i64 { if self.expansion == 0 { - return width; + value + } else { + crate::pdf_device::magnify(value, 1000 + self.expansion) } - crate::pdf_device::magnify(width, 1000 + self.expansion) } pub(crate) fn same_base(&self, other: &Self) -> bool { std::ptr::eq(self, other) 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 e50ea20..1328d94 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -151,6 +151,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { name: local.name.clone(), metrics: Arc::new(metrics), expansion: 0, + layout_metrics: None, letter_spacing: None, pdf_space_font: false, resource: FontResource { diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index 6a1ed08..583c04d 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -127,7 +127,14 @@ impl NativeText { let advance = match &paint.program { crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot], crate::native_font::NativeFontProgram::Type1(_) => { - divide_scaled(font.metrics().width(char::from(slot)), size, 4).1 + let width = if font.layout_metrics.is_some() { + let width = font.advance(slot); + let factor = i64::from(1000 + font.expansion); + width.signum() * ((1000 * width.abs() + factor / 2) / factor) + } else { + font.metrics().width(char::from(slot)) + }; + divide_scaled(width, size, 4).1 } }; if font.expansion == 0 { diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index 397da58..ac6620c 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -371,7 +371,7 @@ impl SourceMap { font, .. } => { - let metrics = font.metrics(); + let metrics = font.layout_metrics(); let scale = |n: i64| -> Result { if metrics.size_sp() == 0 { return Err("source map glyph has zero design size".into()); diff --git a/crates/texrra-tex-core/tests/execution_diagnostics.rs b/crates/texrra-tex-core/tests/execution_diagnostics.rs index 687a2cc..9ba9fc2 100644 --- a/crates/texrra-tex-core/tests/execution_diagnostics.rs +++ b/crates/texrra-tex-core/tests/execution_diagnostics.rs @@ -460,3 +460,59 @@ fn font_expansion_codes_invalidate_cached_break_geometry() { assert_eq!(report.text.contains(r"\roman (-100) A"), expected_lines == 1); } } + +#[test] +fn autoexpand_assigns_font_numbers_and_shares_parameters() { + let declaration = r"\catcode123=1 \catcode125=2 +\font\roman=cmr10 \roman +\pdfoutput=1 +\fontdimen8\roman=2pt +\pdffontexpand\roman 50 50 25 autoexpand +\pdffontexpand\roman 50 50 25 autoexpand +\fontdimen8\roman=3pt +"; + let body = r"\pdfadjustspacing=1 \parfillskip=0pt \hsize=30.75pt +\showboxbreadth=99 \showboxdepth=99 +\setbox0=\vbox{\noindent AAAA\par} +\showbox0 +\end +"; + let fonts = |input: &str| { + execute(input, &mut Host::default()) + .unwrap() + .state + .fonts() + .clone() + }; + let declared = fonts(&format!("{declaration}\\end")); + assert_eq!( + declared + .fonts() + .iter() + .map(FontInstance::name) + .collect::>(), + ["nullfont", "cmr10", "cmr10+50", "cmr10-50"] + ); + assert_eq!(declared.resources().len(), 1); + + let mut packed = fonts(&format!("{declaration}{body}")); + assert_eq!(packed.fonts().len(), 5); + assert_eq!(packed.fonts()[4].name(), "cmr10+25"); + assert!(packed.fonts()[1..].iter().all(|font| font.parameters()[7] == 3 * 65536)); + + let mut previous = packed.clone(); + let base = packed + .load( + &mut Host::default(), + "cmr10", + "diagnostics.tex", + texrra_tex_core::tfm::FontSize::Design, + CommandName::Control("roman".into()), + FontIntegers { hyphen: 45, skew: -1 }, + ) + .unwrap(); + assert!(packed.set_fontdimen(base, 9, 0).unwrap_err().contains("only the last loaded font")); + packed.set_fontdimen(base, 8, 4 * 65536).unwrap(); + assert!(packed.fonts()[1..].iter().all(|font| font.parameters()[7] == 4 * 65536)); + assert_eq!(previous.fontdimen(base, 8).unwrap(), 3 * 65536); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 1e41fa0..34b88e5 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1948,6 +1948,45 @@ TFM 并改动第二页文本,复用 1217 步,只更换第二页。PDF、SVG 有无声明的原样对照在 next-auto-font-table,回执 SHA-256 为 6ecef22622cab83b83a11f6e2dbc33e82ba02ea38b8a70c4f791f7a0f9e18d1f。 +### 自动字宽伸缩的字体表和设备度量 + +原生字体表会在声明 autoexpand 时建立正负边界档位,首次用到 +量化档位时再建立对应字体编号。装盒节点记录选中的字体编号,绘制共享 +基准字体程序及其实际资源。自动生成的档位共享活的字体参数,检查点保留 +修改前的参数值。相同设置可重复声明,预先加载的同名同尺寸 TFM +继续提供独立参数和实际布局度量。PDF 的文本游标使用这个 TFM 的实际 +字宽,并复用基准程序和水平伸缩比。 +[pdfTeX 的字体编号和度量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16110-L16236) +[pdfTeX 的文本游标字宽](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L14705-L14730) + +冻结的有无声明用例与 pdfTeX 1.40.29 的退出状态、TFM 读取顺序一致。 +声明后无法把基准字体从 7 个参数扩展到 8 个。声明前已分配的第 8 个 +参数仍然可写。单侧自动生成和预加载边界档位两例的出页字形、词框坐标 +以及 600 dpi 彩色栅格一致。外置边缘绘制和无限胶水时缺档诊断两项定向 +复验通过。字体目录和盒诊断共 18 项通过,包含新增的字体编号、延后分配、 +共享参数和快照隔离回归。用例和回执在 target/p3-auto-font-table。 +四项参考对照的初始通过回执 SHA-256 为 +76e2533693f025ca28cd17773e1957131513cd60f5d3b7cf59de04ec301f30ee。 + +三页工程连续编辑的实测中,非法扩展基准字体的 `\fontdimen` 被拒绝, +上一版 PDF 仍可用。修正编辑并把第二页从 +25‰ 切换为 −25‰ 后, +恢复 1209 个执行步骤,只替换第二页。PDF、SVG 页及来源映射与独立 +全量编译一致,incremental-final/run.log 的 SHA-256 为 +9cd1778f4be6e5866fdcb04e51a9dfd10b39d58e91031a45e6caf3cdaea04d34。 +本阶段按功能范围验证,实时延迟预算留待性能验收。 + +原生格式 schema53 记录字体表及活动伸缩关联。旧格式若含此前未记录 +真实档位的 autoexpand 设置,加载时会明确要求用原样源重新生成格式。 +下一入口在 format/receipt.json,SHA-256 为 +d518a35d1972179cd8460d544fcff4a1fe25e3f2a2563fe1dfc5bb7b1de8b81d。 +pdfTeX 的 INITEX dump 保留生成字体及共享参数位置,reload 后清掉活动 +伸缩关联。实际用例重载后仍拒绝为基准字体新增第 9 个参数,并可直接 +选取 `cmr10+50` 读取更新过的第 8 个参数,全程没有重读 TFM。原生当前 +重载会继续自动伸缩,按名字选取已生成档位则尝试打开不存在的 TFM。 +下一步区分格式重载与实时检查点的字体状态,核对保留的字体编号、度量和 +参数所有权,再测试重载后重新声明的行为。 +[pdfTeX 的字体表 dump 与 undump](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L30631-L30700) + ### 原生段落边缘悬挂 `\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平