Separate format font metrics from live expansion links

This commit is contained in:
gloamxun committed 2026-11-21 08:43:02 +08:00
1 parent 9b80a782cf
commit b008c0693a
11 files changed
+389 -84

No files matched your search

@@ -4,6 +4,7 @@ use crate::{HorizontalBox, HorizontalItem, Paragraph, ParagraphFont};
mod tail;
pub(super) use tail::TailNodeRef;
mod leaders;
mod legacy_fonts;
pub use leaders::{LeaderGlue, LeaderMode, LeaderPattern};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -0,0 +1,64 @@
//! Format schema 53 stored device faces in boxes. Rebind them to the original
//! logical font slots before a restored job changes any active expansion links.
use super::*;
use crate::{math_engine_tex::MathItem, native_font::NativeFont};
use std::{collections::BTreeMap, sync::Arc};
type Replacements = BTreeMap<(FontId, i32), Arc<NativeFont>>;
impl NativeBox {
pub(in crate::execution) fn rebind_legacy_expansion_fonts(&mut self, fonts: &Replacements) {
match &mut self.content {
BoxContent::Horizontal(nodes) => rebind_horizontal(nodes, fonts),
BoxContent::Vertical(nodes) => rebind_vertical(nodes, fonts),
}
}
}
fn rebind_horizontal(nodes: &mut [TextNode], fonts: &Replacements) {
for node in nodes {
match node {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
if let Some(b) = &mut glyph.native_box {
b.rebind_legacy_expansion_fonts(fonts);
}
if let Some(geometry) = &mut glyph.math_geometry {
for item in &mut geometry.items {
if let MathItem::NativeGlyph { font, .. } = &mut item.item
&& let Some(logical) = fonts.get(&(font.id, font.expansion))
{
*font = logical.clone();
}
}
}
}
TextNode::Discretionary { pre_break, post_break, .. } => {
rebind_horizontal(pre_break, fonts);
rebind_horizontal(post_break, fonts);
}
TextNode::Adjustment(value) => rebind_vertical(&mut value.nodes, fonts),
TextNode::Insertion(value) => rebind_vertical(&mut value.nodes, fonts),
TextNode::Leaders(leader) => rebind_leader(leader, fonts),
_ => {}
}
}
}
fn rebind_vertical(nodes: &mut [NativeVerticalNode], fonts: &Replacements) {
for node in nodes {
match node {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
b.rebind_legacy_expansion_fonts(fonts);
}
NativeVerticalNode::Insertion(value) => rebind_vertical(&mut value.nodes, fonts),
NativeVerticalNode::Leaders(leader) => rebind_leader(leader, fonts),
_ => {}
}
}
}
fn rebind_leader(leader: &mut LeaderGlue, fonts: &Replacements) {
if let LeaderPattern::Box(b) = &mut leader.pattern {
b.rebind_legacy_expansion_fonts(fonts);
}
}
@@ -1,7 +1,7 @@
//! Per-shipout device state. Original TeX boxes remain unscaled semantic lists.
use super::*;
use crate::pdf_device::{PdfColorProgram, PdfGraphics};
use std::sync::Arc;
use std::{collections::BTreeMap, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShipoutDevice {
@@ -19,6 +19,8 @@ pub struct ShipoutDevice {
pub struct NativeShipout {
pub box_node: NativeBox,
pub device: ShipoutDevice,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -136,7 +138,7 @@ impl NativeShipout {
x,
y,
size,
font,
font: self.font_overrides.get(&font.id).cloned().unwrap_or(font),
slot,
character,
paint: None,
@@ -291,9 +291,16 @@ impl Executor {
} else {
Vec::new()
};
let font_overrides = if device.pdf.is_some() {
self.reads.insert(Dependency::FontResources);
self.state.fonts.expansion_paint_fonts()
} else {
Default::default()
};
let mut shipout = NativeShipout {
box_node: b,
device,
font_overrides,
pdf_color_start,
pdf_color_steps: Vec::new(),
pdf_graphics_steps: Vec::new(),
@@ -188,6 +188,10 @@ pub struct FontCatalog {
fonts: Vec<FontInstance>,
resources: Vec<FontResource>,
parameter_words: usize,
// Metric synthesis shares parameter storage independently of active
// expansion links, including after a format has been reloaded.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
parameter_owners: BTreeMap<FontId, FontId>,
limits: FontLimits,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
@@ -232,6 +236,7 @@ impl FontCatalog {
}],
resources: Vec::new(),
parameter_words: 7,
parameter_owners: BTreeMap::new(),
limits,
protrusion: BTreeMap::new(),
auto_kern: BTreeMap::new(),
@@ -496,16 +501,14 @@ impl FontCatalog {
}
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;
}
let parameters = parameters.clone();
for (&variant, &share) in &self.parameter_owners {
if share == owner {
let current = &mut self.fonts[variant.0 as usize].parameters;
if current.len() == parameters.len() {
*current = parameters.clone();
} else if index < current.len() {
Arc::make_mut(current)[index] = value;
}
}
}
@@ -513,24 +516,24 @@ impl FontCatalog {
}
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,
}
self.parameter_owners.get(&id).copied().unwrap_or(id)
}
fn expansion_code_owner(&self, id: FontId) -> FontId {
self.fonts.get(id.index() as usize)
.and_then(|font| font.expansion_origin.map(|(base, _)| base))
.unwrap_or(id)
}
pub(super) fn protrusion_code(&self, font: FontId, slot: u8, right: bool) -> i32 {
let font = self.expansion_code_owner(font);
self.protrusion.get(&font).and_then(|font| font.get(&slot))
.map_or(0, |codes| i32::from(codes[usize::from(right)]))
}
pub(super) fn set_protrusion_code(
&mut self, font: FontId, slot: u8, right: bool, code: i32,
) {
let font = self.expansion_code_owner(font);
let code = code.clamp(-1000, 1000) as i16;
if code != 0 || self.protrusion.get(&font).is_some_and(|font| font.contains_key(&slot)) {
self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code;
@@ -541,6 +544,7 @@ impl FontCatalog {
}
pub(super) fn auto_kern_code(&self, font: FontId, slot: u8, after: bool) -> i32 {
let font = self.expansion_code_owner(font);
self.auto_kern
.get(&font)
.and_then(|codes| codes.get(&slot))
@@ -548,6 +552,7 @@ impl FontCatalog {
}
pub(super) fn set_auto_kern_code(&mut self, font: FontId, slot: u8, after: bool, code: i32) {
let font = self.expansion_code_owner(font);
let side = usize::from(after);
let code = code.clamp(-1000, 1000) as i16;
if code != 0 {
@@ -566,7 +571,7 @@ impl FontCatalog {
}
pub(super) fn auto_kern_for(state: &State, font: FontId) -> Option<AutoKern<'_>> {
let codes = state.fonts.auto_kern.get(&font)?;
let codes = state.fonts.auto_kern.get(&state.fonts.expansion_code_owner(font))?;
let prepend = state.parameter(Parameter::Pdfprependkern).width() > 0;
let append = state.parameter(Parameter::Pdfappendkern).width() > 0;
(prepend || append).then(|| AutoKern {
@@ -642,16 +647,14 @@ impl FontCatalog {
} 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()
});
let glyph_font = Self::synthesized_font(self.glyph_font(font)?, variant, &name, amount)?;
let owner = self.parameter_owner(font);
self.fonts.push(FontInstance {
name,
glyph_font: Some(glyph_font),
expansion_origin: Some((font, amount)),
..base.clone()
});
self.parameter_owners.insert(variant, owner);
variant
} else {
self.check_font_capacity()?;
@@ -690,44 +693,101 @@ impl FontCatalog {
})
}
pub(super) fn expansion_face(
fn synthesized_font(
base: &NativeFont, id: FontId, name: &str, amount: i32,
) -> Result<Arc<NativeFont>, String> {
let mut metrics = base.metrics().clone();
metrics.expand_horizontal(amount)?;
Ok(Arc::new(NativeFont {
id,
name: name.into(),
metrics: Arc::new(metrics),
resource: base.resource.clone(),
expansion: 0,
layout_metrics: None,
letter_spacing: None,
pdf_space_font: false,
}))
}
pub(super) fn ensure_expansion_variant(
&mut self,
font: FontId,
amount: i32,
defaults: FontIntegers,
files: &mut impl SourceProvider,
) -> Result<(FontId, Arc<NativeFont>), 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()));
) -> Result<FontId, String> {
if let Some(variant) = self.expansion_variant(font, amount) {
return Ok(variant);
}
let variant = if let Some(variant) = self.expansion_variant(font, amount) {
variant
if let Some(external) = self.external_expansion.get(&font) {
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);
Ok(variant)
} else {
let variant = self.load_expansion_variant(font, amount, true, "", defaults, files)?;
self.automatic_variants.entry(font).or_default().insert(amount, variant);
variant
};
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))
Ok(variant)
}
}
pub(super) fn expansion_paint_fonts(&self) -> BTreeMap<FontId, Arc<NativeFont>> {
// Layout retains the logical font and its metrics. A PDF shipout
// captures only the active links to the underlying programs.
let mut overrides = BTreeMap::new();
for (&base, variants) in &self.automatic_variants {
let base = self.glyph_font(base).expect("registered expansion base");
for (&amount, &variant) in variants {
let font = self.glyph_font(variant).expect("registered expansion variant");
overrides.insert(variant, Arc::new(NativeFont {
expansion: amount,
layout_metrics: Some(font.metrics.clone()),
..base.as_ref().clone()
}));
}
}
overrides
}
pub(super) fn reset_format_font_state(&mut self) {
for font in &mut self.fonts {
font.expansion_origin = None;
}
self.expansion.clear();
self.automatic_variants.clear();
self.external_expansion.clear();
self.expansion_codes.clear();
self.protrusion.clear();
self.auto_kern.clear();
self.pdf_settings.clear();
}
/// Convert old device-shaped font entries into logical metrics before
/// removing the job's expansion links.
pub(super) fn restore_legacy_synthesized_fonts(
&mut self,
) -> Result<BTreeMap<(FontId, i32), Arc<NativeFont>>, String> {
let mut replaced = BTreeMap::new();
for (index, font) in self.fonts.iter_mut().enumerate() {
let Some((base, amount)) = font.expansion_origin else { continue };
let id = FontId(index as u32);
if self.automatic_variants.get(&base).and_then(|variants| variants.get(&amount)) != Some(&id) {
continue;
}
let old = font.glyph_font.as_ref().ok_or("missing automatic expansion font")?;
if old.expansion != 0 {
let logical = Self::synthesized_font(old, id, &font.name, amount)?;
self.parameter_owners.insert(id, base);
font.glyph_font = Some(logical);
}
replaced.insert((base, amount), font.glyph_font.as_ref().unwrap().clone());
}
Ok(replaced)
}
pub(super) fn shares_font_parameters(&self, id: FontId) -> bool {
self.parameter_owners.contains_key(&id)
}
pub(super) fn diagnostic_font(&self, font: FontId, expansion: i32) -> Result<(String, i32), String> {
@@ -735,7 +795,7 @@ impl FontCatalog {
if let Some((base, amount)) = f.expansion_origin {
Ok((self.font(base)?.identifier_text(), amount))
} else {
Ok((f.identifier_text(), expansion))
Ok((f.identifier_text(), if self.shares_font_parameters(font) { 0 } else { expansion }))
}
}
@@ -752,6 +812,7 @@ impl FontCatalog {
}
pub(super) fn expansion_code(&self, font: FontId, slot: u8) -> i32 {
let font = self.expansion_code_owner(font);
self.expansion_codes
.get(&font)
.and_then(|codes| codes.get(&slot))
@@ -759,6 +820,7 @@ impl FontCatalog {
}
pub(super) fn set_expansion_code(&mut self, font: FontId, slot: u8, code: i32) {
let font = self.expansion_code_owner(font);
let code = code.clamp(0, 1000);
if code < 1000 {
self.expansion_codes.entry(font).or_default().insert(slot, code as u16);
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
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 SCHEMA: u32 = 54;
const COMPATIBLE_SCHEMAS: [u32; 23] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -115,7 +115,7 @@ impl FormatImage {
if !COMPATIBLE_SCHEMAS.contains(&identity.schema) || identity.engine != ENGINE {
return Err("incompatible native format image".into());
}
let image: Self =
let mut image: Self =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if image.schema != identity.schema
|| image.engine != ENGINE
@@ -127,6 +127,10 @@ impl FormatImage {
if image.state.fonts.has_unrecorded_expansion_limits() {
return Err("native format must be rebuilt to restore automatic expansion font identities".into());
}
if image.schema < SCHEMA {
image.state.restore_legacy_format_fonts()?;
image.schema = SCHEMA;
}
Ok(image)
}
@@ -114,7 +114,7 @@ fn capacity(
}
let variant = state.fonts.expansion_limit(font.id, amount)?;
Ok(match right {
Some(right) => variant.horizontal(variant.metrics().kern(char::from(slot), char::from(right))),
Some(right) => variant.metrics().kern(char::from(slot), char::from(right)),
None => variant.advance(slot),
})
};
@@ -307,7 +307,7 @@ impl MarginVariation {
if amount == 0 {
return Ok(original);
}
let (selected, _) = state.fonts.expansion_face(font, amount, defaults, files)?;
let selected = state.fonts.ensure_expansion_variant(font, amount, defaults, files)?;
let quad = i64::from(state.fonts.font(selected)?.quad());
Ok(pdf_device::magnify(quad, code))
};
@@ -323,7 +323,7 @@ impl MarginVariation {
}
#[derive(Default)]
struct PackingFonts(BTreeMap<(FontId, i32), (FontId, Arc<NativeFont>)>);
struct PackingFonts(BTreeMap<(FontId, i32), FontId>);
impl PackingFonts {
fn select(
@@ -332,16 +332,16 @@ impl PackingFonts {
font: FontId,
amount: i32,
files: &mut impl SourceProvider,
) -> Result<(FontId, Arc<NativeFont>), String> {
) -> Result<FontId, String> {
use std::collections::btree_map::Entry;
let selected = match self.0.entry((font, 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)?)
entry.insert(state.fonts.ensure_expansion_variant(font, amount, defaults, files)?)
}
};
Ok(selected.clone())
Ok(*selected)
}
fn margin(
@@ -361,7 +361,7 @@ impl PackingFonts {
if amount == 0 {
return Ok(None);
}
let (selected, _) = self.select(state, font, 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(selected)?.quad());
Ok(Some((-pdf_device::magnify(quad, code) as i32, selected)))
@@ -421,21 +421,24 @@ pub(super) fn pack(
if amount == 0 {
continue;
}
let (selected, paint) = fonts.select(state, glyph.id, amount, files)?;
let selected = fonts.select(state, glyph.id, amount, files)?;
let character = char::from(glyph.slot);
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 face = state.fonts.glyph_font(selected)?;
if state.fonts.shares_font_parameters(selected)
&& !state.fonts.has_external_expansion(glyph.id)
&& 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));
let next = char::from(right.slot);
let original = left.font.metrics().kern(character, next);
if original == i64::from(*width)
&& let TextNode::Kern { width, .. } = &mut material[i + 1]
{
*width = i32::try_from(pdf_device::magnify(original, 1000 + amount))
*width = i32::try_from(face.metrics().kern(character, next))
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
}
}
@@ -454,7 +457,7 @@ pub(super) fn pack(
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
unreachable!()
};
*font = paint;
*font = face.clone();
}
Ok(())
}
+12 -1
View File
@@ -1465,9 +1465,20 @@ impl State {
}
self.pdf_info.clear();
self.pdf_pages_attributes.clear();
self.fonts.pdf_settings.clear();
self.fonts.reset_format_font_state();
self
}
pub(super) fn restore_legacy_format_fonts(&mut self) -> Result<(), String> {
let replacements = self.fonts.restore_legacy_synthesized_fonts()?;
if !replacements.is_empty() {
for b in self.boxes.values_mut() {
b.rebind_legacy_expansion_fonts(&replacements);
}
}
self.fonts.reset_format_font_state();
Ok(())
}
pub fn is_initex(&self) -> bool {
self.initex
}