Register virtual fonts in native PDF shipout order

This commit is contained in:
gloamxun committed 2026-11-21 09:18:03 +08:00
1 parent b008c0693a
commit 614f09aa9b
11 files changed
+668 -99

No files matched your search

@@ -771,6 +771,28 @@ impl NativeBox {
} }
} }
pub(super) fn visit_shipout_font_uses(
&self,
mut emit: impl FnMut(usize, &std::sync::Arc<crate::native_font::NativeFont>, 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]> { pub(super) fn positioned_outputs(&self) -> Vec<[i64; 2]> {
let mut positions = Vec::new(); let mut positions = Vec::new();
self.walk(0, 0, &mut |x, y, node| { self.walk(0, 0, &mut |x, y, node| {
+14 -7
View File
@@ -21,6 +21,8 @@ pub struct NativeShipout {
pub device: ShipoutDevice, pub device: ShipoutDevice,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>, pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) virtual_glyphs: Option<crate::native_font::VirtualGlyphs>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>, pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -53,6 +55,7 @@ impl NativeShipout {
) -> Result<crate::render::DisplayList, String> { ) -> Result<crate::render::DisplayList, String> {
let mut page = crate::render::DisplayList { let mut page = crate::render::DisplayList {
width: self.device.page_width, width: self.device.page_width,
prepared_virtual_glyphs: self.virtual_glyphs.as_ref().map(|_| BTreeMap::new()),
height: self.device.page_height, height: self.device.page_height,
magnification: self.device.magnification, magnification: self.device.magnification,
units: crate::render::DisplayUnits::TeX, units: crate::render::DisplayUnits::TeX,
@@ -134,14 +137,18 @@ impl NativeShipout {
size, size,
character, character,
.. ..
} => DisplayItem::NativeGlyph { } => {
x, if let Some(packet) = self.virtual_glyphs.as_ref()
y, .and_then(|fonts| fonts.get(&font.id))
size, .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), font: self.font_overrides.get(&font.id).cloned().unwrap_or(font),
slot, }
character,
paint: None,
}, },
MathItem::Rule { width, height } => DisplayItem::Rule { MathItem::Rule { width, height } => DisplayItem::Rule {
x, x,
@@ -223,6 +223,7 @@ pub struct Executor {
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>, pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>,
pdf_loaded_space_font: Option<Arc<crate::native_font::NativeFont>>, pdf_loaded_space_font: Option<Arc<crate::native_font::NativeFont>>,
pdf_space_probe: Option<Arc<page::PdfSpaceProbe>>, pdf_space_probe: Option<Arc<page::PdfSpaceProbe>>,
pdf_virtual_fonts: Arc<crate::native_font::JobVirtualFonts>,
#[cfg(all(target_os = "linux", target_env = "gnu"))] #[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>, pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>, pdf_catalog_tokens: Vec<Token>,
@@ -391,6 +392,7 @@ impl Executor {
pdf_space_font: None, pdf_space_font: None,
pdf_loaded_space_font: None, pdf_loaded_space_font: None,
pdf_space_probe: None, pdf_space_probe: None,
pdf_virtual_fonts: Default::default(),
#[cfg(all(target_os = "linux", target_env = "gnu"))] #[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None, pdf_last_match: None,
pdf_catalog_tokens: Vec::new(), pdf_catalog_tokens: Vec::new(),
@@ -4019,6 +4021,9 @@ impl Executor {
.fonts .fonts
.configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files) .configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files)
.map_err(|message| self.error(message, self.current))?; .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) => { Some(Efcode) => {
let (font, slot) = self.font_character_target(files)?; let (font, slot) = self.font_character_target(files)?;
@@ -1,5 +1,8 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder}; use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*; use super::*;
use crate::native_font::{JobVirtualFonts, NativeFont, VirtualGlyphs};
use std::collections::BTreeSet;
#[derive(Clone)] #[derive(Clone)]
pub(super) struct OutputFrame { pub(super) struct OutputFrame {
@@ -34,6 +37,25 @@ pub(super) struct PdfSpaceProbe {
observed_events: usize, observed_events: usize,
} }
struct ShipoutFontUse {
before_output: usize,
font: Arc<NativeFont>,
slot: u8,
}
fn shipout_font_uses(
b: &NativeBox, programs: &JobVirtualFonts,
) -> Result<Vec<ShipoutFontUse>, 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 { impl Executor {
pub(super) fn outer_vertical(&self) -> bool { pub(super) fn outer_vertical(&self) -> bool {
self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty() self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty()
@@ -301,6 +323,7 @@ impl Executor {
box_node: b, box_node: b,
device, device,
font_overrides, font_overrides,
virtual_glyphs: None,
pdf_color_start, pdf_color_start,
pdf_color_steps: Vec::new(), pdf_color_steps: Vec::new(),
pdf_graphics_steps: Vec::new(), pdf_graphics_steps: Vec::new(),
@@ -339,6 +362,12 @@ impl Executor {
} else { } else {
Vec::new().into_iter() 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; use crate::pdf_device::text_spaces::SpaceOperation;
let automatic_spaces_at_start = self.pdf_interword_spaces; let automatic_spaces_at_start = self.pdf_interword_spaces;
let mut uses_automatic_spaces = automatic_spaces_at_start; let mut uses_automatic_spaces = automatic_spaces_at_start;
@@ -346,6 +375,12 @@ impl Executor {
let mut has_explicit_space = false; let mut has_explicit_space = false;
let mut pdf_objects = Vec::new(); let mut pdf_objects = Vec::new();
for (index, output) in outputs.into_iter().enumerate() { 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() if self.pdf_loaded_space_font.is_none()
&& (uses_automatic_spaces || has_explicit_space) && (uses_automatic_spaces || has_explicit_space)
&& matches!( && matches!(
@@ -457,6 +492,9 @@ impl Executor {
)); ));
} }
self.current = current; 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 has_space_settings = has_space_nodes || automatic_spaces_at_start;
let probed_page = (uses_automatic_spaces || has_explicit_space) let probed_page = (uses_automatic_spaces || has_explicit_space)
&& self.pdf_loaded_space_font.is_none(); && 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( fn probe_pdf_space_font(
&mut self, &mut self,
shipout: &NativeShipout, shipout: &NativeShipout,
@@ -42,6 +42,8 @@ pub struct FontInstance {
selector: CommandName, selector: CommandName,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
expansion_origin: Option<(FontId, i32)>, expansion_origin: Option<(FontId, i32)>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
automatic_expansion: bool,
} }
impl FontInstance { impl FontInstance {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
@@ -233,6 +235,7 @@ impl FontCatalog {
}, },
selector: CommandName::Control("nullfont".into()), selector: CommandName::Control("nullfont".into()),
expansion_origin: None, expansion_origin: None,
automatic_expansion: false,
}], }],
resources: Vec::new(), resources: Vec::new(),
parameter_words: 7, parameter_words: 7,
@@ -457,6 +460,7 @@ impl FontCatalog {
integers: defaults, integers: defaults,
selector, selector,
expansion_origin: None, expansion_origin: None,
automatic_expansion: false,
}); });
self.parameter_words += count; self.parameter_words += count;
Ok(id) Ok(id)
@@ -645,17 +649,7 @@ impl FontCatalog {
}) { }) {
FontId(index as u32) FontId(index as u32)
} else if automatic { } else if automatic {
self.check_font_capacity()?; return self.synthesize_expansion(font, amount);
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
} else { } else {
self.check_font_capacity()?; self.check_font_capacity()?;
let filename = format!("{name}.tfm"); let filename = format!("{name}.tfm");
@@ -670,10 +664,64 @@ impl FontCatalog {
None, 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) Ok(variant)
} }
pub(crate) fn synthesize_expansion(&mut self, base: FontId, amount: i32) -> Result<FontId, String> {
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<FontId, String> {
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<FontId> { pub(super) fn expansion_variant(&self, font: FontId, amount: i32) -> Option<FontId> {
let variants = match self.external_expansion.get(&font) { let variants = match self.external_expansion.get(&font) {
Some(expansion) => &expansion.variants, Some(expansion) => &expansion.variants,
@@ -732,27 +780,33 @@ impl FontCatalog {
} }
} }
pub(super) fn expansion_paint_fonts(&self) -> BTreeMap<FontId, Arc<NativeFont>> { pub(crate) fn paint_font(&self, font: &Arc<NativeFont>) -> Arc<NativeFont> {
// Layout retains the logical font and its metrics. A PDF shipout let Some((base, amount)) = self.automatic_origin(font.id) else {
// captures only the active links to the underlying programs. return font.clone();
let mut overrides = BTreeMap::new(); };
for (&base, variants) in &self.automatic_variants {
let base = self.glyph_font(base).expect("registered expansion base"); let base = self.glyph_font(base).expect("registered expansion base");
for (&amount, &variant) in variants { Arc::new(NativeFont {
let font = self.glyph_font(variant).expect("registered expansion variant");
overrides.insert(variant, Arc::new(NativeFont {
expansion: amount, expansion: amount,
layout_metrics: Some(font.metrics.clone()), layout_metrics: Some(font.metrics.clone()),
..base.as_ref().clone() ..base.as_ref().clone()
})); })
} }
}
overrides 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.
self.automatic_variants.values().flat_map(|variants| variants.values())
.map(|&variant| {
let font = self.glyph_font(variant).expect("registered expansion variant");
(variant, self.paint_font(font))
})
.collect()
} }
pub(super) fn reset_format_font_state(&mut self) { pub(super) fn reset_format_font_state(&mut self) {
for font in &mut self.fonts { for font in &mut self.fonts {
font.expansion_origin = None; font.expansion_origin = None;
font.automatic_expansion = false;
} }
self.expansion.clear(); self.expansion.clear();
self.automatic_variants.clear(); self.automatic_variants.clear();
+1 -1
View File
@@ -13,7 +13,7 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
mod virtual_paint; 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)] #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NativeFontPaint { pub struct NativeFontPaint {
@@ -1,13 +1,17 @@
use super::{NativeFont, actual_resource, verify_resource}; use super::{LetterspaceProgram, NativeFont, actual_resource, verify_resource};
use crate::{ use crate::{
execution::{FontId, FontResource, SourceProvider}, execution::{Cancellation, FontCatalog, FontId, FontIntegers, FontResource, SourceProvider},
math_engine_tex::{MathItem, PositionedItem},
provenance::Derivation, provenance::Derivation,
render::{DisplayItem, DisplayList}, render::{DisplayItem, DisplayList},
resources::ResourceKind, resources::ResourceKind,
tfm::{FontSize, TfmMetrics}, tfm::{FontSize, TfmMetrics},
virtual_font::{Axis, Command, LocalFont, VirtualFont}, virtual_font::{Axis, Command, LocalFont, VirtualFont},
}; };
use std::{collections::BTreeMap, sync::Arc}; use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
struct LoadedVirtual { struct LoadedVirtual {
from: String, from: String,
@@ -33,10 +37,39 @@ impl Default for VirtualPaintState {
} }
} }
#[derive(Clone)]
enum Program {
File {
vf: Arc<LoadedVirtual>,
locals: Option<Arc<BTreeMap<u32, Arc<NativeFont>>>>,
},
Letterspace(LetterspaceProgram),
}
#[derive(Clone, Default)]
pub(crate) struct JobVirtualFonts {
programs: BTreeMap<FontId, Option<Program>>,
}
// 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<FontId, BTreeMap<u8, Arc<Vec<PositionedItem>>>>;
struct Expansion<'a, F> { struct Expansion<'a, F> {
files: &'a mut F, files: &'a mut F,
state: &'a mut VirtualPaintState, fonts: FontPrograms<'a>,
commands: usize, 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 { struct Glyph {
@@ -62,73 +95,62 @@ fn offset(point: i64, delta: i64) -> Result<i64, String> {
impl<'a, F: SourceProvider> Expansion<'a, F> { impl<'a, F: SourceProvider> Expansion<'a, F> {
fn is_virtual(&mut self, font: &Arc<NativeFont>) -> Result<bool, String> { fn is_virtual(&mut self, font: &Arc<NativeFont>) -> Result<bool, String> {
Ok(font.letter_spacing.is_some() || self.lookup(font)?.is_some()) Ok(self.lookup(font)?.is_some())
}
fn with_expansion(&mut self, font: Arc<NativeFont>, ratio: i32) -> Arc<NativeFont> {
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()
} }
fn count_commands(&mut self, count: usize) -> Result<(), String> { 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; self.commands += count;
if self.commands > 5_000_000 { if self.commands > self.limit {
return Err("VF expansion command limit exceeded".into()); return Err("VF expansion command limit exceeded".into());
} }
Ok(()) Ok(())
} }
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> { fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Program>, String> {
if let Some((old, vf)) = self.state.virtuals.get(&font.id) { 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) { if !Arc::ptr_eq(old, font) && !old.same_base(font) {
return Err("native font ids from different jobs cannot share output".into()); return Err(
"native font ids from different jobs cannot share output".into()
);
} }
return Ok(vf.clone()); 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}"));
}
}
Some(Arc::new(LoadedVirtual { from, program }))
} else { } else {
None let vf = read_virtual(font, self.files)?;
state.virtuals.insert(font.id, (font.clone(), vf.clone()));
vf
}; };
self.state.virtuals.insert(font.id, (font.clone(), vf.clone())); Ok(vf.map(|vf| Program::File { vf, locals: None }))
Ok(vf) }
}
} }
fn local_font( fn local_font(
&mut self, files: &mut F,
state: &mut VirtualPaintState,
from: &str, from: &str,
local: &LocalFont, local: &LocalFont,
size: i64, size: i64,
) -> Result<Arc<NativeFont>, String> { ) -> Result<Arc<NativeFont>, String> {
let size = TfmMetrics::scale_fix_word(local.scale, size)?; let size = TfmMetrics::scale_fix_word(local.scale, size)?;
let key = (from.to_owned(), local.name.clone(), 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( check_metrics(
&font.metrics, &font.metrics,
local.checksum, local.checksum,
@@ -138,16 +160,15 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
return Ok(font.clone()); return Ok(font.clone());
} }
let name = format!("{}.tfm", local.name); 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))?; let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?;
check_metrics(&metrics, local.checksum, local.design_size, &name)?; check_metrics(&metrics, local.checksum, local.design_size, &name)?;
self.state.last_id = self state.last_id = state
.state
.last_id .last_id
.checked_add(1) .checked_add(1)
.ok_or("native device font capacity exceeded")?; .ok_or("native device font capacity exceeded")?;
let font = Arc::new(NativeFont { let font = Arc::new(NativeFont {
id: FontId::for_device(self.state.last_id), id: FontId::for_device(state.last_id),
name: local.name.clone(), name: local.name.clone(),
metrics: Arc::new(metrics), metrics: Arc::new(metrics),
expansion: 0, expansion: 0,
@@ -159,7 +180,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
data: Arc::new(file.data), data: Arc::new(file.data),
}, },
}); });
self.state.local_fonts.insert(key, font.clone()); state.local_fonts.insert(key, font.clone());
Ok(font) Ok(font)
} }
@@ -169,42 +190,49 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
output: &mut Vec<DisplayItem>, output: &mut Vec<DisplayItem>,
depth: usize, depth: usize,
) -> Result<(), String> { ) -> Result<(), String> {
if let Some(program) = &glyph.font.letter_spacing { 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 { if depth >= 16 {
return Err("VF recursion limit exceeded".into()); return Err("VF recursion limit exceeded".into());
} }
self.count_commands(3)?; self.count_commands(3)?;
let movement = TfmMetrics::scale_fix_word(program.right, glyph.size)?; let movement = TfmMetrics::scale_fix_word(program.right, glyph.size)?;
let font = self.with_expansion(program.base.clone(), glyph.font.expansion); if !program.base.has_slot(glyph.slot) {
if !font.has_slot(glyph.slot) {
return Err(format!( return Err(format!(
"VF local font {} has no TFM slot {}", "VF local font {} has no TFM slot {}",
font.name, glyph.slot program.base.name, glyph.slot
)); ));
} }
return self.expand( return self.expand(
Glyph { Glyph {
x: offset(glyph.x, movement)?, x: offset(glyph.x, movement)?,
y: glyph.y, y: glyph.y,
size: font.size_sp(), size: program.base.size_sp(),
font, font: program.base,
slot: glyph.slot, slot: glyph.slot,
}, },
output, output,
depth + 1, depth + 1,
); );
} }
let Some(vf) = self.lookup(&glyph.font)? else { None => {
let font = match &self.fonts {
FontPrograms::Job { catalog, .. } => catalog.paint_font(&glyph.font),
FontPrograms::Standalone(_) => glyph.font,
};
output.push(DisplayItem::NativeGlyph { output.push(DisplayItem::NativeGlyph {
x: glyph.x, x: glyph.x,
y: glyph.y, y: glyph.y,
size: glyph.size, size: glyph.size,
character: '\u{fffd}', character: '\u{fffd}',
font: glyph.font, font,
slot: glyph.slot, slot: glyph.slot,
paint: None, paint: None,
}); });
return Ok(()); return Ok(());
}
}; };
if depth >= 16 { if depth >= 16 {
return Err("VF recursion limit exceeded".into()); return Err("VF recursion limit exceeded".into());
@@ -227,15 +255,27 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
match *command { match *command {
Command::Character { slot, advance } => { Command::Character { slot, advance } => {
let id = local.ok_or("VF character has no selected local font")?; let id = local.ok_or("VF character has no selected local font")?;
let font = let font = if let Some(locals) = &locals {
self.local_font(&vf.from, &vf.program.local_fonts[&id], glyph.size)?; 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) { if !font.has_slot(slot) {
return Err(format!( return Err(format!(
"VF local font {} has no TFM slot {slot}", "VF local font {} has no TFM slot {slot}",
font.name font.name
)); ));
} }
let font = self.with_expansion(font, glyph.font.expansion);
let width = font.advance(slot); let width = font.advance(slot);
let size = font.size_sp(); let size = font.size_sp();
self.expand( self.expand(
@@ -303,6 +343,249 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
} }
} }
fn standalone_expansion(
state: &mut VirtualPaintState,
font: Arc<NativeFont>,
ratio: i32,
) -> Arc<NativeFont> {
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<Option<Arc<LoadedVirtual>>, 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<NativeFont>,
catalog: &mut FontCatalog,
defaults: FontIntegers,
files: &mut impl SourceProvider,
) -> Result<Option<Program>, 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<NativeFont>,
slot: u8,
limit: usize,
cancellation: Option<&Cancellation>,
) -> Result<(Option<Arc<Vec<PositionedItem>>>, 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( fn check_metrics(
metrics: &TfmMetrics, metrics: &TfmMetrics,
checksum: u32, checksum: u32,
@@ -326,11 +609,17 @@ pub(super) fn expand_pages(
) -> Result<Option<Vec<DisplayList>>, String> { ) -> Result<Option<Vec<DisplayList>>, String> {
let mut expansion = Expansion { let mut expansion = Expansion {
files, files,
state, fonts: FontPrograms::Standalone(state),
commands: 0, commands: 0,
limit: 5_000_000,
cancellation: None,
}; };
let mut uses_vf = false; let mut uses_vf = false;
for page in pages { for page in pages {
if let Some(glyphs) = &page.prepared_virtual_glyphs {
uses_vf |= !glyphs.is_empty();
continue;
}
for item in &page.items { for item in &page.items {
if let DisplayItem::NativeGlyph { font, .. } = item { if let DisplayItem::NativeGlyph { font, .. } = item {
uses_vf |= expansion.is_virtual(font)?; uses_vf |= expansion.is_virtual(font)?;
@@ -345,6 +634,7 @@ pub(super) fn expand_pages(
let mut resolved = DisplayList { let mut resolved = DisplayList {
width: page.width, width: page.width,
height: page.height, height: page.height,
prepared_virtual_glyphs: Some(BTreeMap::new()),
magnification: page.magnification, magnification: page.magnification,
units: page.units, units: page.units,
pdf: page.pdf.clone(), pdf: page.pdf.clone(),
@@ -364,8 +654,15 @@ pub(super) fn expand_pages(
slot, slot,
.. ..
} = item } = item
&& expansion.is_virtual(font)?
{ {
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( expansion.expand(
Glyph { Glyph {
x: *x, x: *x,
@@ -379,9 +676,14 @@ pub(super) fn expand_pages(
)?; )?;
true true
} else { } else {
resolved.items.push(item.clone()); false
}
} else {
false false
}; };
if !virtual_glyph {
resolved.items.push(item.clone());
}
if let Some(source) = page.sources.get(&index) { if let Some(source) = page.sources.get(&index) {
let source = if virtual_glyph { let source = if virtual_glyph {
source.clone().derived(Derivation::FontProgram) source.clone().derived(Derivation::FontProgram)
@@ -397,3 +699,39 @@ pub(super) fn expand_pages(
} }
Ok(Some(result)) Ok(Some(result))
} }
fn append_prepared_glyph(
output: &mut Vec<DisplayItem>,
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(())
}
+5
View File
@@ -243,6 +243,10 @@ pub struct DisplayList {
pub width: i64, pub width: i64,
pub height: i64, pub height: i64,
pub items: Vec<DisplayItem>, pub items: Vec<DisplayItem>,
/// 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<std::collections::BTreeMap<usize, std::sync::Arc<Vec<crate::math_engine_tex::PositionedItem>>>>,
/// Paint-order indices into `items`; absent entries have unknown origin. /// Paint-order indices into `items`; absent entries have unknown origin.
pub sources: std::collections::BTreeMap<usize, crate::provenance::PaintSource>, pub sources: std::collections::BTreeMap<usize, crate::provenance::PaintSource>,
pub images: Vec<PdfImage>, pub images: Vec<PdfImage>,
@@ -262,6 +266,7 @@ impl Default for DisplayList {
width: 0, width: 0,
height: 0, height: 0,
items: Vec::new(), items: Vec::new(),
prepared_virtual_glyphs: None,
sources: Default::default(), sources: Default::default(),
images: Vec::new(), images: Vec::new(),
magnification: 1000, magnification: 1000,
@@ -7,6 +7,7 @@ pub(super) struct VirtualFont {
pub design_size: i64, pub design_size: i64,
pub default_font: Option<u32>, pub default_font: Option<u32>,
pub local_fonts: BTreeMap<u32, LocalFont>, pub local_fonts: BTreeMap<u32, LocalFont>,
pub local_order: Vec<u32>,
pub packets: BTreeMap<u8, Packet>, pub packets: BTreeMap<u8, Packet>,
} }
@@ -121,6 +122,7 @@ impl VirtualFont {
design_size, design_size,
default_font: None, default_font: None,
local_fonts: BTreeMap::new(), local_fonts: BTreeMap::new(),
local_order: Vec::new(),
packets: BTreeMap::new(), packets: BTreeMap::new(),
}; };
let mut opcode = input.byte()?; let mut opcode = input.byte()?;
@@ -131,6 +133,7 @@ impl VirtualFont {
return Err("duplicate local font in VF".into()); return Err("duplicate local font in VF".into());
} }
vf.default_font.get_or_insert(id); vf.default_font.get_or_insert(id);
vf.local_order.push(id);
opcode = input.byte()?; opcode = input.byte()?;
} }
while opcode <= 242 { while opcode <= 242 {
@@ -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)); && *rule_y == *y + 49_152 && *width == 196_608 && *height == 49_152));
render(&root, &revision.execution, &pages); 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);
}
+34
View File
@@ -2024,6 +2024,40 @@ a990cb72f80c9d8cad28da619f683f38f3b5a337be696c39b9d01acc0223b101。
继续把实际 VF 局部字体、伸缩派生及其资源依赖接入执行与出页的同一 继续把实际 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` 接入实际字体槽和水平 `\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平