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
+708 -139

No files matched your search

@@ -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<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> {
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<i64, String> {
impl<'a, F: SourceProvider> Expansion<'a, F> {
fn is_virtual(&mut self, font: &Arc<NativeFont>) -> Result<bool, String> {
Ok(font.letter_spacing.is_some() || 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()
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<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, 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<NativeFont>) -> Result<Option<Program>, 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<Arc<NativeFont>, 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<DisplayItem>,
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<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(
metrics: &TfmMetrics,
checksum: u32,
@@ -326,11 +609,17 @@ pub(super) fn expand_pages(
) -> Result<Option<Vec<DisplayList>>, 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<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(())
}