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

@@ -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]> {
let mut positions = Vec::new();
self.walk(0, 0, &mut |x, y, node| {
+15 -8
View File
@@ -21,6 +21,8 @@ pub struct NativeShipout {
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 = "Option::is_none")]
pub(super) virtual_glyphs: Option<crate::native_font::VirtualGlyphs>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -53,6 +55,7 @@ impl NativeShipout {
) -> Result<crate::render::DisplayList, String> {
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,
@@ -223,6 +223,7 @@ pub struct Executor {
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>,
pdf_loaded_space_font: Option<Arc<crate::native_font::NativeFont>>,
pdf_space_probe: Option<Arc<page::PdfSpaceProbe>>,
pdf_virtual_fonts: Arc<crate::native_font::JobVirtualFonts>,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>,
@@ -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)?;
@@ -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<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 {
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,
@@ -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<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> {
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<NativeFont>) -> Arc<NativeFont> {
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<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 {
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();