diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index c1bda42..0365e79 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -771,6 +771,28 @@ impl NativeBox { } } + pub(super) fn visit_shipout_font_uses( + &self, + mut emit: impl FnMut(usize, &std::sync::Arc, u8), + ) -> Result<(), String> { + use crate::math_engine_tex::MathItem; + let mut output_count = 0; + self.walk(0, 0, &mut |_, _, node| match node { + BoxPaint::Output(_) => output_count += 1, + BoxPaint::Box(b) => { + if let Some(geometry) = &b.math_geometry { + for item in &geometry.items { + if let MathItem::NativeGlyph { font, slot, .. } = &item.item { + emit(output_count, font, *slot); + } + } + } + } + _ => {} + })?; + Ok(()) + } + pub(super) fn positioned_outputs(&self) -> Vec<[i64; 2]> { let mut positions = Vec::new(); self.walk(0, 0, &mut |x, y, node| { diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 7025374..fef3061 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -21,6 +21,8 @@ pub struct NativeShipout { pub device: ShipoutDevice, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(super) font_overrides: BTreeMap>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) virtual_glyphs: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_color_start: Vec>, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -53,6 +55,7 @@ impl NativeShipout { ) -> Result { let mut page = crate::render::DisplayList { width: self.device.page_width, + prepared_virtual_glyphs: self.virtual_glyphs.as_ref().map(|_| BTreeMap::new()), height: self.device.page_height, magnification: self.device.magnification, units: crate::render::DisplayUnits::TeX, @@ -134,14 +137,18 @@ impl NativeShipout { size, character, .. - } => DisplayItem::NativeGlyph { - x, - y, - size, - font: self.font_overrides.get(&font.id).cloned().unwrap_or(font), - slot, - character, - paint: None, + } => { + if let Some(packet) = self.virtual_glyphs.as_ref() + .and_then(|fonts| fonts.get(&font.id)) + .and_then(|glyphs| glyphs.get(&slot)) + { + page.prepared_virtual_glyphs.as_mut().unwrap() + .insert(page.items.len(), packet.clone()); + } + DisplayItem::NativeGlyph { + x, y, size, slot, character, paint: None, + font: self.font_overrides.get(&font.id).cloned().unwrap_or(font), + } }, MathItem::Rule { width, height } => DisplayItem::Rule { x, diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 1bb1ce7..a575b83 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -223,6 +223,7 @@ pub struct Executor { pdf_space_font: Option, pdf_loaded_space_font: Option>, pdf_space_probe: Option>, + pdf_virtual_fonts: Arc, #[cfg(all(target_os = "linux", target_env = "gnu"))] pdf_last_match: Option>, pdf_catalog_tokens: Vec, @@ -391,6 +392,7 @@ impl Executor { pdf_space_font: None, pdf_loaded_space_font: None, pdf_space_probe: None, + pdf_virtual_fonts: Default::default(), #[cfg(all(target_os = "linux", target_env = "gnu"))] pdf_last_match: None, pdf_catalog_tokens: Vec::new(), @@ -4019,6 +4021,9 @@ impl Executor { .fonts .configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files) .map_err(|message| self.error(message, self.current))?; + self.pdf_virtual_fonts + .propagate_expansion(font, &mut self.state.fonts, defaults, files) + .map_err(|message| self.error(message, self.current))?; } Some(Efcode) => { let (font, slot) = self.font_character_target(files)?; diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index dec4d4f..d34d970 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -1,5 +1,8 @@ use super::super::boxes::{self, PackSpec, VerticalBuilder}; use super::*; +use crate::native_font::{JobVirtualFonts, NativeFont, VirtualGlyphs}; +use std::collections::BTreeSet; + #[derive(Clone)] pub(super) struct OutputFrame { @@ -34,6 +37,25 @@ pub(super) struct PdfSpaceProbe { observed_events: usize, } +struct ShipoutFontUse { + before_output: usize, + font: Arc, + slot: u8, +} + +fn shipout_font_uses( + b: &NativeBox, programs: &JobVirtualFonts, +) -> Result, String> { + let mut uses = Vec::new(); + let mut seen = BTreeSet::new(); + b.visit_shipout_font_uses(|before_output, font, slot| { + if !programs.is_known_physical(font.id) && seen.insert((font.id, slot)) { + uses.push(ShipoutFontUse { before_output, font: font.clone(), slot }); + } + })?; + Ok(uses) +} + impl Executor { pub(super) fn outer_vertical(&self) -> bool { self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty() @@ -301,6 +323,7 @@ impl Executor { box_node: b, device, font_overrides, + virtual_glyphs: None, pdf_color_start, pdf_color_steps: Vec::new(), pdf_graphics_steps: Vec::new(), @@ -339,6 +362,12 @@ impl Executor { } else { Vec::new().into_iter() }; + let mut font_uses = if device.pdf.is_some() { + shipout.virtual_glyphs = Some(VirtualGlyphs::new()); + shipout_font_uses(b, &self.pdf_virtual_fonts).map_err(|e| self.error(e, b.span))? + } else { + Vec::new() + }.into_iter().peekable(); use crate::pdf_device::text_spaces::SpaceOperation; let automatic_spaces_at_start = self.pdf_interword_spaces; let mut uses_automatic_spaces = automatic_spaces_at_start; @@ -346,6 +375,12 @@ impl Executor { let mut has_explicit_space = false; let mut pdf_objects = Vec::new(); for (index, output) in outputs.into_iter().enumerate() { + while font_uses.peek().is_some_and(|usage| usage.before_output == index) { + self.current = output.span; + self.prepare_virtual_glyph( + shipout.virtual_glyphs.as_mut().unwrap(), font_uses.next().unwrap(), files, + )?; + } if self.pdf_loaded_space_font.is_none() && (uses_automatic_spaces || has_explicit_space) && matches!( @@ -457,6 +492,9 @@ impl Executor { )); } self.current = current; + for usage in font_uses { + self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?; + } let has_space_settings = has_space_nodes || automatic_spaces_at_start; let probed_page = (uses_automatic_spaces || has_explicit_space) && self.pdf_loaded_space_font.is_none(); @@ -512,6 +550,27 @@ impl Executor { } } + fn prepare_virtual_glyph( + &mut self, glyphs: &mut VirtualGlyphs, usage: ShipoutFontUse, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + self.check_cancellation()?; + let id = usage.font.id; + if self.pdf_virtual_fonts.is_known_physical(id) { + return Ok(()); + } + let defaults = self.font_defaults(); + let (packet, work) = Arc::make_mut(&mut self.pdf_virtual_fonts).glyph( + &mut self.state.fonts, defaults, files, usage.font, usage.slot, + self.limits.steps.saturating_sub(self.steps), self.cancellation.as_ref(), + ).map_err(|e| self.error(e, self.current))?; + self.steps += work; + if let Some(packet) = packet { + glyphs.entry(id).or_default().insert(usage.slot, packet); + } + Ok(()) + } + fn probe_pdf_space_font( &mut self, shipout: &NativeShipout, diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index b710b75..3719a09 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -42,6 +42,8 @@ pub struct FontInstance { selector: CommandName, #[serde(default, skip_serializing_if = "Option::is_none")] expansion_origin: Option<(FontId, i32)>, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + automatic_expansion: bool, } impl FontInstance { pub fn name(&self) -> &str { @@ -233,6 +235,7 @@ impl FontCatalog { }, selector: CommandName::Control("nullfont".into()), expansion_origin: None, + automatic_expansion: false, }], resources: Vec::new(), parameter_words: 7, @@ -457,6 +460,7 @@ impl FontCatalog { integers: defaults, selector, expansion_origin: None, + automatic_expansion: false, }); self.parameter_words += count; Ok(id) @@ -645,17 +649,7 @@ impl FontCatalog { }) { FontId(index as u32) } else if automatic { - self.check_font_capacity()?; - let variant = FontId(self.fonts.len() as u32); - 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), - ..base.clone() - }); - self.parameter_owners.insert(variant, owner); - variant + return self.synthesize_expansion(font, amount); } else { self.check_font_capacity()?; let filename = format!("{name}.tfm"); @@ -670,10 +664,64 @@ impl FontCatalog { None, )? }; - self.fonts[variant.index() as usize].expansion_origin = Some((font, amount)); + let instance = &mut self.fonts[variant.index() as usize]; + instance.expansion_origin = Some((font, amount)); + instance.automatic_expansion = automatic; Ok(variant) } + pub(crate) fn synthesize_expansion(&mut self, base: FontId, amount: i32) -> Result { + self.check_font_capacity()?; + let font = self.font(base)?; + let name = format!("{}{amount:+}", font.name); + let id = FontId(self.fonts.len() as u32); + let glyph_font = Self::synthesized_font(self.glyph_font(base)?, id, &name, amount)?; + let owner = self.parameter_owner(base); + self.fonts.push(FontInstance { + name, + glyph_font: Some(glyph_font), + expansion_origin: Some((base, amount)), + automatic_expansion: true, + ..font.clone() + }); + self.parameter_owners.insert(id, owner); + Ok(id) + } + + pub(crate) fn load_virtual_local( + &mut self, name: &str, from: &str, size: i64, + defaults: FontIntegers, files: &mut impl SourceProvider, + ) -> Result { + if let Some(index) = self.fonts.iter().skip(1).position(|font| { + font.name == name && font.size_sp() == size && font.glyph_font.as_ref().is_some_and(|f| f.letter_spacing.is_none()) + }) { + return Ok(FontId((index + 1) as u32)); + } + self.check_font_capacity()?; + let (loaded, metrics) = Self::read_tfm(files, &format!("{name}.tfm"), from, FontSize::At(size))?; + self.insert_font( + (name, ""), loaded, metrics, CommandName::Control(String::new()), defaults, None, + ) + } + + pub(crate) fn automatic_origin(&self, id: FontId) -> Option<(FontId, i32)> { + let instance = self.fonts.get(id.index() as usize)?; + if instance.automatic_expansion { instance.expansion_origin } else { None } + } + + pub(crate) fn inherit_virtual_expansion( + &mut self, parent: FontId, local: FontId, from: &str, defaults: FontIntegers, + files: &mut impl SourceProvider, + ) -> Result<(), String> { + if let Some(config) = self.expansion(parent) { + self.configure_expansion( + local, from, (config.stretch, config.shrink, config.step), + !self.has_external_expansion(parent), defaults, files, + )?; + } + Ok(()) + } + pub(super) fn expansion_variant(&self, font: FontId, amount: i32) -> Option { let variants = match self.external_expansion.get(&font) { Some(expansion) => &expansion.variants, @@ -732,27 +780,33 @@ impl FontCatalog { } } + pub(crate) fn paint_font(&self, font: &Arc) -> Arc { + let Some((base, amount)) = self.automatic_origin(font.id) else { + return font.clone(); + }; + let base = self.glyph_font(base).expect("registered expansion base"); + Arc::new(NativeFont { + expansion: amount, + layout_metrics: Some(font.metrics.clone()), + ..base.as_ref().clone() + }) + } + pub(super) fn expansion_paint_fonts(&self) -> BTreeMap> { // 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 { + self.automatic_variants.values().flat_map(|variants| variants.values()) + .map(|&variant| { 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 + (variant, self.paint_font(font)) + }) + .collect() } pub(super) fn reset_format_font_state(&mut self) { for font in &mut self.fonts { font.expansion_origin = None; + font.automatic_expansion = false; } self.expansion.clear(); self.automatic_variants.clear(); diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index c60d87a..1e94812 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -13,7 +13,7 @@ use std::{ sync::{Arc, Mutex}, }; mod virtual_paint; -pub(crate) use virtual_paint::VirtualPaintState; +pub(crate) use virtual_paint::{JobVirtualFonts, VirtualGlyphs, VirtualPaintState}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NativeFontPaint { 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 1328d94..111a98b 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -1,13 +1,17 @@ -use super::{NativeFont, actual_resource, verify_resource}; +use super::{LetterspaceProgram, NativeFont, actual_resource, verify_resource}; use crate::{ - execution::{FontId, FontResource, SourceProvider}, + execution::{Cancellation, FontCatalog, FontId, FontIntegers, FontResource, SourceProvider}, + math_engine_tex::{MathItem, PositionedItem}, provenance::Derivation, render::{DisplayItem, DisplayList}, resources::ResourceKind, tfm::{FontSize, TfmMetrics}, virtual_font::{Axis, Command, LocalFont, VirtualFont}, }; -use std::{collections::BTreeMap, sync::Arc}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; struct LoadedVirtual { from: String, @@ -33,10 +37,39 @@ impl Default for VirtualPaintState { } } +#[derive(Clone)] +enum Program { + File { + vf: Arc, + locals: Option>>>, + }, + Letterspace(LetterspaceProgram), +} + +#[derive(Clone, Default)] +pub(crate) struct JobVirtualFonts { + programs: BTreeMap>, +} + +// Per-page packet results are relative to the enclosing glyph and shared by +// every occurrence of that glyph. The original boxes still own the raw lists. +pub(crate) type VirtualGlyphs = BTreeMap>>>; + struct Expansion<'a, F> { files: &'a mut F, - state: &'a mut VirtualPaintState, + fonts: FontPrograms<'a>, commands: usize, + limit: usize, + cancellation: Option<&'a Cancellation>, +} + +enum FontPrograms<'a> { + Standalone(&'a mut VirtualPaintState), + Job { + programs: &'a mut JobVirtualFonts, + catalog: &'a mut FontCatalog, + defaults: FontIntegers, + }, } struct Glyph { @@ -62,73 +95,62 @@ fn offset(point: i64, delta: i64) -> Result { impl<'a, F: SourceProvider> Expansion<'a, F> { fn is_virtual(&mut self, font: &Arc) -> Result { - Ok(font.letter_spacing.is_some() || self.lookup(font)?.is_some()) - } - - fn with_expansion(&mut self, font: Arc, ratio: i32) -> Arc { - if ratio == 0 { - return font; - } - self.state.expanded_fonts - .entry((font.id, ratio)) - .or_insert_with(|| { - Arc::new(NativeFont { - expansion: ratio, - ..font.as_ref().clone() - }) - }) - .clone() + Ok(self.lookup(font)?.is_some()) } fn count_commands(&mut self, count: usize) -> Result<(), String> { + if self.cancellation.is_some_and(Cancellation::is_cancelled) { + return Err("native compilation cancelled".into()); + } self.commands += count; - if self.commands > 5_000_000 { + if self.commands > self.limit { return Err("VF expansion command limit exceeded".into()); } Ok(()) } - fn lookup(&mut self, font: &Arc) -> Result>, String> { - if let Some((old, vf)) = self.state.virtuals.get(&font.id) { - 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()); - } - let name = format!("{}.vf", font.name); - let from = font.resource.version.path.to_string_lossy(); - let vf = self.files.virtual_font(&name, &from)?; - let vf = if let Some(loaded) = vf { - let loaded = verify_resource(loaded, ResourceKind::Vf, &name)?; - let from = loaded.version.path.to_string_lossy().into_owned(); - let program = - VirtualFont::parse(&loaded.data).map_err(|error| format!("{from}: {error}"))?; - check_metrics(&font.metrics, program.checksum, program.design_size, &name)?; - for (&slot, packet) in &program.packets { - if font.has_slot(slot) - && TfmMetrics::scale_fix_word(packet.width, font.size_sp())? - != font.metrics.width(char::from(slot)) - { - return Err(format!("{name} width differs from TFM at slot {slot}")); + fn lookup(&mut self, font: &Arc) -> Result, String> { + match &mut self.fonts { + FontPrograms::Job { + programs, + catalog, + defaults, + } => programs.lookup(font, catalog, *defaults, self.files), + FontPrograms::Standalone(state) => { + if let Some(program) = &font.letter_spacing { + let base = standalone_expansion(state, program.base.clone(), font.expansion); + return Ok(Some(Program::Letterspace(LetterspaceProgram { + base, + right: program.right, + }))); } + let vf = if let Some((old, vf)) = state.virtuals.get(&font.id) { + if !Arc::ptr_eq(old, font) && !old.same_base(font) { + return Err( + "native font ids from different jobs cannot share output".into() + ); + } + vf.clone() + } else { + let vf = read_virtual(font, self.files)?; + state.virtuals.insert(font.id, (font.clone(), vf.clone())); + vf + }; + Ok(vf.map(|vf| Program::File { vf, locals: None })) } - Some(Arc::new(LoadedVirtual { from, program })) - } else { - None - }; - self.state.virtuals.insert(font.id, (font.clone(), vf.clone())); - Ok(vf) + } } fn local_font( - &mut self, + files: &mut F, + state: &mut VirtualPaintState, from: &str, local: &LocalFont, size: i64, ) -> Result, String> { let size = TfmMetrics::scale_fix_word(local.scale, size)?; let key = (from.to_owned(), local.name.clone(), size); - if let Some(font) = self.state.local_fonts.get(&key) { + if let Some(font) = state.local_fonts.get(&key) { check_metrics( &font.metrics, local.checksum, @@ -138,16 +160,15 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { return Ok(font.clone()); } let name = format!("{}.tfm", local.name); - let file = actual_resource(self.files, ResourceKind::Tfm, &name, from)?; + let file = actual_resource(files, ResourceKind::Tfm, &name, from)?; let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?; check_metrics(&metrics, local.checksum, local.design_size, &name)?; - self.state.last_id = self - .state + state.last_id = state .last_id .checked_add(1) .ok_or("native device font capacity exceeded")?; let font = Arc::new(NativeFont { - id: FontId::for_device(self.state.last_id), + id: FontId::for_device(state.last_id), name: local.name.clone(), metrics: Arc::new(metrics), expansion: 0, @@ -159,7 +180,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { data: Arc::new(file.data), }, }); - self.state.local_fonts.insert(key, font.clone()); + state.local_fonts.insert(key, font.clone()); Ok(font) } @@ -169,42 +190,49 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { output: &mut Vec, depth: usize, ) -> Result<(), String> { - if let Some(program) = &glyph.font.letter_spacing { - if depth >= 16 { - return Err("VF recursion limit exceeded".into()); + let program = self.lookup(&glyph.font)?; + let (vf, locals) = match program { + Some(Program::File { vf, locals }) => (vf, locals), + Some(Program::Letterspace(program)) => { + if depth >= 16 { + return Err("VF recursion limit exceeded".into()); + } + self.count_commands(3)?; + let movement = TfmMetrics::scale_fix_word(program.right, glyph.size)?; + if !program.base.has_slot(glyph.slot) { + return Err(format!( + "VF local font {} has no TFM slot {}", + program.base.name, glyph.slot + )); + } + return self.expand( + Glyph { + x: offset(glyph.x, movement)?, + y: glyph.y, + size: program.base.size_sp(), + font: program.base, + slot: glyph.slot, + }, + output, + depth + 1, + ); } - self.count_commands(3)?; - let movement = TfmMetrics::scale_fix_word(program.right, glyph.size)?; - let font = self.with_expansion(program.base.clone(), glyph.font.expansion); - if !font.has_slot(glyph.slot) { - return Err(format!( - "VF local font {} has no TFM slot {}", - font.name, glyph.slot - )); - } - return self.expand( - Glyph { - x: offset(glyph.x, movement)?, + None => { + let font = match &self.fonts { + FontPrograms::Job { catalog, .. } => catalog.paint_font(&glyph.font), + FontPrograms::Standalone(_) => glyph.font, + }; + output.push(DisplayItem::NativeGlyph { + x: glyph.x, y: glyph.y, - size: font.size_sp(), + size: glyph.size, + character: '\u{fffd}', font, slot: glyph.slot, - }, - output, - depth + 1, - ); - } - let Some(vf) = self.lookup(&glyph.font)? else { - output.push(DisplayItem::NativeGlyph { - x: glyph.x, - y: glyph.y, - size: glyph.size, - character: '\u{fffd}', - font: glyph.font, - slot: glyph.slot, - paint: None, - }); - return Ok(()); + paint: None, + }); + return Ok(()); + } }; if depth >= 16 { return Err("VF recursion limit exceeded".into()); @@ -227,15 +255,27 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { match *command { Command::Character { slot, advance } => { let id = local.ok_or("VF character has no selected local font")?; - let font = - self.local_font(&vf.from, &vf.program.local_fonts[&id], glyph.size)?; + let font = if let Some(locals) = &locals { + locals[&id].clone() + } else { + let FontPrograms::Standalone(state) = &mut self.fonts else { + unreachable!() + }; + let font = Self::local_font( + self.files, + state, + &vf.from, + &vf.program.local_fonts[&id], + glyph.size, + )?; + standalone_expansion(state, font, glyph.font.expansion) + }; if !font.has_slot(slot) { return Err(format!( "VF local font {} has no TFM slot {slot}", font.name )); } - let font = self.with_expansion(font, glyph.font.expansion); let width = font.advance(slot); let size = font.size_sp(); self.expand( @@ -303,6 +343,249 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { } } +fn standalone_expansion( + state: &mut VirtualPaintState, + font: Arc, + ratio: i32, +) -> Arc { + if ratio == 0 { + return font; + } + state + .expanded_fonts + .entry((font.id, ratio)) + .or_insert_with(|| { + Arc::new(NativeFont { + expansion: ratio, + ..font.as_ref().clone() + }) + }) + .clone() +} + +fn read_virtual( + font: &NativeFont, + files: &mut impl SourceProvider, +) -> Result>, String> { + let name = format!("{}.vf", font.name); + let from = font.resource.version.path.to_string_lossy(); + let Some(loaded) = files.virtual_font(&name, &from)? else { + return Ok(None); + }; + let loaded = verify_resource(loaded, ResourceKind::Vf, &name)?; + let from = loaded.version.path.to_string_lossy().into_owned(); + let program = VirtualFont::parse(&loaded.data).map_err(|error| format!("{from}: {error}"))?; + check_metrics(&font.metrics, program.checksum, program.design_size, &name)?; + for (&slot, packet) in &program.packets { + if font.has_slot(slot) + && TfmMetrics::scale_fix_word(packet.width, font.size_sp())? + != font.metrics.width(char::from(slot)) + { + return Err(format!("{name} width differs from TFM at slot {slot}")); + } + } + Ok(Some(Arc::new(LoadedVirtual { from, program }))) +} + +impl JobVirtualFonts { + pub(crate) fn is_known_physical(&self, id: FontId) -> bool { + matches!(self.programs.get(&id), Some(None)) + } + + fn lookup( + &mut self, + font: &Arc, + catalog: &mut FontCatalog, + defaults: FontIntegers, + files: &mut impl SourceProvider, + ) -> Result, String> { + if let Some(program) = self.programs.get(&font.id) { + return Ok(program.clone()); + } + let program = if let Some((base, ratio)) = catalog.automatic_origin(font.id) { + let base = catalog.glyph_font(base)?.clone(); + match self.lookup(&base, catalog, defaults, files)? { + Some(Program::File { + vf, + locals: Some(locals), + }) => { + let mut derived = BTreeMap::new(); + for id in &vf.program.local_order { + let local = catalog.synthesize_expansion(locals[id].id, ratio)?; + derived.insert(*id, catalog.glyph_font(local)?.clone()); + } + Some(Program::File { + vf, + locals: Some(Arc::new(derived)), + }) + } + Some(Program::Letterspace(program)) => { + let local = catalog.synthesize_expansion(program.base.id, ratio)?; + Some(Program::Letterspace(LetterspaceProgram { + base: catalog.glyph_font(local)?.clone(), + right: program.right, + })) + } + Some(Program::File { locals: None, .. }) => unreachable!(), + None => None, + } + } else if let Some(program) = &font.letter_spacing { + Some(Program::Letterspace(program.clone())) + } else if let Some(vf) = read_virtual(font, files)? { + let mut locals = BTreeMap::new(); + for id in &vf.program.local_order { + let local = &vf.program.local_fonts[id]; + let size = TfmMetrics::scale_fix_word(local.scale, font.size_sp())?; + let local_id = + catalog.load_virtual_local(&local.name, &vf.from, size, defaults, files)?; + let local_font = catalog.glyph_font(local_id)?.clone(); + check_metrics( + local_font.metrics(), + local.checksum, + local.design_size, + &local.name, + )?; + catalog.inherit_virtual_expansion(font.id, local_id, &vf.from, defaults, files)?; + locals.insert(*id, local_font); + } + Some(Program::File { + vf, + locals: Some(Arc::new(locals)), + }) + } else { + None + }; + self.programs.insert(font.id, program.clone()); + Ok(program) + } + + pub(crate) fn propagate_expansion( + &self, + font: FontId, + catalog: &mut FontCatalog, + defaults: FontIntegers, + files: &mut impl SourceProvider, + ) -> Result<(), String> { + // An already-read VF keeps its bindings. New expansion limits + // propagate through the actual local definitions in file order. + let mut pending: Vec<(FontId, Option<(FontId, String)>)> = vec![(font, None)]; + let mut seen = BTreeSet::new(); + while let Some((font, from_parent)) = pending.pop() { + if let Some((parent, from)) = from_parent { + catalog.inherit_virtual_expansion(parent, font, &from, defaults, files)?; + } + if !seen.insert(font) { + continue; + } + match self.programs.get(&font) { + Some(Some(Program::File { + vf, + locals: Some(locals), + })) => { + pending.extend( + vf.program + .local_order + .iter() + .rev() + .map(|id| (locals[id].id, Some((font, vf.from.clone())))), + ); + } + Some(Some(Program::File { locals: None, .. })) => unreachable!(), + _ => { + if let Some(program) = &catalog.glyph_font(font)?.letter_spacing { + let base = &program.base; + pending.push(( + base.id, + Some(( + font, + base.resource.version.path.to_string_lossy().into_owned(), + )), + )); + } + } + } + } + Ok(()) + } + + pub(crate) fn glyph( + &mut self, + catalog: &mut FontCatalog, + defaults: FontIntegers, + files: &mut impl SourceProvider, + font: Arc, + slot: u8, + limit: usize, + cancellation: Option<&Cancellation>, + ) -> Result<(Option>>, usize), String> { + let mut expansion = Expansion { + files, + fonts: FontPrograms::Job { + programs: self, + catalog, + defaults, + }, + commands: 0, + limit: limit.min(5_000_000), + cancellation, + }; + if !expansion.is_virtual(&font)? { + return Ok((None, 0)); + } + let mut items = Vec::new(); + expansion.expand( + Glyph { + x: 0, + y: 0, + size: font.size_sp(), + font, + slot, + }, + &mut items, + 0, + )?; + let items = items + .into_iter() + .map(|item| { + let (x, y, item) = match item { + DisplayItem::NativeGlyph { + x, + y, + font, + slot, + character, + size, + .. + } => ( + x, + y, + MathItem::NativeGlyph { + font, + slot, + character, + size, + }, + ), + DisplayItem::Rule { + x, + y, + width, + height, + } => (x, y, MathItem::Rule { width, height }), + _ => unreachable!("VF packet yields glyphs and rules"), + }; + PositionedItem { + x, + y, + item, + source: Default::default(), + } + }) + .collect(); + Ok((Some(Arc::new(items)), expansion.commands)) + } +} + fn check_metrics( metrics: &TfmMetrics, checksum: u32, @@ -326,11 +609,17 @@ pub(super) fn expand_pages( ) -> Result>, String> { let mut expansion = Expansion { files, - state, + fonts: FontPrograms::Standalone(state), commands: 0, + limit: 5_000_000, + cancellation: None, }; let mut uses_vf = false; for page in pages { + if let Some(glyphs) = &page.prepared_virtual_glyphs { + uses_vf |= !glyphs.is_empty(); + continue; + } for item in &page.items { if let DisplayItem::NativeGlyph { font, .. } = item { uses_vf |= expansion.is_virtual(font)?; @@ -345,6 +634,7 @@ pub(super) fn expand_pages( let mut resolved = DisplayList { width: page.width, height: page.height, + prepared_virtual_glyphs: Some(BTreeMap::new()), magnification: page.magnification, units: page.units, pdf: page.pdf.clone(), @@ -364,24 +654,36 @@ pub(super) fn expand_pages( slot, .. } = item - && expansion.is_virtual(font)? { - expansion.expand( - Glyph { - x: *x, - y: *y, - size: *size, - font: font.clone(), - slot: *slot, - }, - &mut resolved.items, - 0, - )?; - true + if let Some(glyphs) = &page.prepared_virtual_glyphs { + if let Some(glyph) = glyphs.get(&index) { + append_prepared_glyph(&mut resolved.items, *x, *y, glyph)?; + true + } else { + false + } + } else if expansion.is_virtual(font)? { + expansion.expand( + Glyph { + x: *x, + y: *y, + size: *size, + font: font.clone(), + slot: *slot, + }, + &mut resolved.items, + 0, + )?; + true + } else { + false + } } else { - resolved.items.push(item.clone()); false }; + if !virtual_glyph { + resolved.items.push(item.clone()); + } if let Some(source) = page.sources.get(&index) { let source = if virtual_glyph { source.clone().derived(Derivation::FontProgram) @@ -397,3 +699,39 @@ pub(super) fn expand_pages( } Ok(Some(result)) } + +fn append_prepared_glyph( + output: &mut Vec, + x: i64, + y: i64, + parts: &[PositionedItem], +) -> Result<(), String> { + for part in parts { + let x = offset(x, part.x)?; + let y = offset(y, part.y)?; + output.push(match &part.item { + MathItem::NativeGlyph { + font, + slot, + character, + size, + } => DisplayItem::NativeGlyph { + x, + y, + size: *size, + font: font.clone(), + slot: *slot, + character: *character, + paint: None, + }, + MathItem::Rule { width, height } => DisplayItem::Rule { + x, + y, + width: *width, + height: *height, + }, + _ => return Err("invalid retained VF packet geometry".into()), + }); + } + Ok(()) +} diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 0b0111d..613e05f 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -243,6 +243,10 @@ pub struct DisplayList { pub width: i64, pub height: i64, pub items: Vec, + /// Captured VF packets from native shipout, indexed by the raw display + /// item. None leaves lookup to a standalone renderer. + #[doc(hidden)] + pub prepared_virtual_glyphs: Option>>>, /// Paint-order indices into `items`; absent entries have unknown origin. pub sources: std::collections::BTreeMap, pub images: Vec, @@ -262,6 +266,7 @@ impl Default for DisplayList { width: 0, height: 0, items: Vec::new(), + prepared_virtual_glyphs: None, sources: Default::default(), images: Vec::new(), magnification: 1000, diff --git a/crates/texrra-tex-core/src/virtual_font.rs b/crates/texrra-tex-core/src/virtual_font.rs index eda67bf..997820d 100644 --- a/crates/texrra-tex-core/src/virtual_font.rs +++ b/crates/texrra-tex-core/src/virtual_font.rs @@ -7,6 +7,7 @@ pub(super) struct VirtualFont { pub design_size: i64, pub default_font: Option, pub local_fonts: BTreeMap, + pub local_order: Vec, pub packets: BTreeMap, } @@ -121,6 +122,7 @@ impl VirtualFont { design_size, default_font: None, local_fonts: BTreeMap::new(), + local_order: Vec::new(), packets: BTreeMap::new(), }; let mut opcode = input.byte()?; @@ -131,6 +133,7 @@ impl VirtualFont { return Err("duplicate local font in VF".into()); } vf.default_font.get_or_insert(id); + vf.local_order.push(id); opcode = input.byte()?; } while opcode <= 242 { diff --git a/crates/texrra-tex-core/tests/virtual_fonts.rs b/crates/texrra-tex-core/tests/virtual_fonts.rs index 0f13001..38a811c 100644 --- a/crates/texrra-tex-core/tests/virtual_fonts.rs +++ b/crates/texrra-tex-core/tests/virtual_fonts.rs @@ -306,3 +306,45 @@ fn nested_vf_preserves_pen_position_rules_and_one_to_many_origin() { && *rule_y == *y + 49_152 && *width == 196_608 && *height == 49_152)); render(&root, &revision.execution, &pages); } + +#[test] +fn autoexpanded_virtual_shipout_allocates_job_fonts_before_following_commands() { + const SOURCE: &str = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfpkresolution=600 +\font\virtual=ptmr7t +\pdffontexpand\virtual 75 75 25 autoexpand +\pdfadjustspacing=1 \parfillskip=0pt \hsize=31pt +\setbox0=\vbox{\virtual \noindent AAAA\par} +\font\sentinel=cmr10 +\fontdimen8\sentinel=1pt +\shipout\copy0 +\end +"; + let (root, mut host) = fixture("job-font-ids"); + let revision = execute(&root, SOURCE.as_bytes(), &mut host); + let fonts = revision.execution.state.fonts(); + let names: Vec<_> = fonts.fonts().iter().map(FontInstance::name).collect(); + assert_eq!( + names, + ["nullfont", "ptmr7t", "ptmr7t+75", "ptmr7t-75", "cmr10", "ptmr8r", + "ptmr8r+75", "ptmr8r-75", "ptmr8r+75"], + ); + + let source = SOURCE.replace(r"\end", r"\fontdimen9\sentinel=2pt \end"); + let run = |bytes: &str, host: &mut Host| { + Executor::new(State::initex().with_etex(), Limits::default()) + .with_native_pages() + .run( + SourceFile { name: root.join("probe.tex").to_string_lossy().into_owned(), + data: bytes.as_bytes().to_vec() }, + host, + ) + }; + assert!( + run(&source, &mut host) + .unwrap_err() + .message.contains("only the last loaded font can extend fontdimen") + ); + let control = source.replace(r"\shipout\copy0", ""); + assert_eq!(run(&control, &mut host).unwrap().state.fonts().fonts().len(), 5); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3ceafe3..d02bf16 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2024,6 +2024,40 @@ a990cb72f80c9d8cad28da619f683f38f3b5a337be696c39b9d01acc0223b101。 继续把实际 VF 局部字体、伸缩派生及其资源依赖接入执行与出页的同一 字体编号空间,保持已经验证的格式和检查点生命周期。 +### PDF 出页登记实际虚拟字体 + +原生 PDF 出页按盒子的绘制顺序发现虚拟字体。首次读取 VF 时按文件 +声明顺序登记实际大小的局部字体,已加载的同名同尺寸 TFM 可复用。 +自动伸缩实际生成派生局部字体编号,参数所有权和逻辑度量保存在任务 +字体表中。延迟写出观察它前面的字形已经触发的字体分配。原始出页盒 +仍保有逻辑字形,绘制复用出页时执行的 VF 字符程序和来源,同一页 +同一槽的重复绘制共享结果。检查点保留解析后的程序及其真实资源依赖。 +[pdfTeX 的局部字体读取](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16725-L16790) +[pdfTeX 的自动伸缩虚拟字体](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16957-L16986) + +TeX Live 原样 ptmr7t VF 对照覆盖出页后参数扩展被拒、无出页仍可 +扩展、延迟写出的先后、首次出页前后声明自动伸缩、以及 INITEX 导出 +字体表。参考和原生的 TFM/VF 读取顺序及九个字体编号顺序一致。 +两份 PDF 的词框及 600 dpi 彩色栅格相同。11 项虚拟字体、格式和 +领导胶水定向回归通过。回执在 target/p3-job-vf,SHA-256 为 +a77bd3d6d7727acd3d9d83e2cb14a6a47a774d386ccaf3be4b0cff9d28eb1a61。 + +三页工程先改第三页正文,恢复 1963 步,仅替换第三页。随后改动实际 +VF 的一个字符程序,恢复点退到该资源第一次出页使用之前,复用 +1333 步,仅替换第二、三页。两次增量结果与独立全量的 PDF、SVG +和来源映射一致。改动 VF 后的 PDF 也与独立 pdfTeX 的词框及三页 +144 dpi 灰度栅格一致。移除局部 TFM 后,上一版 PDF 保持可用。 +incremental/final.log 的 SHA-256 为 +ef65a1a00b7eae2cda41cc93778a076224931d898e3cdf716cc2b97c94662070。 + +下一处差异在复用已有局部字体时出现。预先给 ptmr8r 设置 ±50‰, +随后使用设置为 ±75‰ 的 ptmr7t VF。pdfTeX 在读取 VF 时按父字体 +继承实际新边界并完成输出。原生当前将此路径按显式重复声明处理, +报告配置冲突。冻结对照 next-conflict-receipt.json 的 SHA-256 为 +ec13538d65721f2cf1de9294c42881fb55bfca37cf65764903d053cd2e8ee2b3。 +下一步区分显式声明与 VF 继承,核对继承前已分配的档位、实际新边界、 +物理输出以及另一页的增量复用。 + ### 原生段落边缘悬挂 `\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平