Reject automatic expansion of bitmap fonts at PDF shipout

This commit is contained in:
gloamxun committed 2026-11-21 09:38:18 +08:00
1 parent 45b79fc5a5
commit 9527d3bbec
8 files changed
+211 -46

No files matched your search

@@ -23,6 +23,8 @@ pub struct NativeShipout {
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 = "Option::is_none")]
pub(super) pdf_font_map: Option<Arc<crate::native_font::PdfFontMapInput>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -60,6 +62,7 @@ impl NativeShipout {
magnification: self.device.magnification,
units: crate::render::DisplayUnits::TeX,
pdf: self.device.pdf.clone(),
pdf_font_map: self.pdf_font_map.clone(),
pdf_links: self.pdf_links.clone(),
pdf_text_spaces: self.pdf_text_spaces.clone(),
pdf_resources: crate::pdf_device::page_resources::PageResources {
@@ -44,12 +44,14 @@ struct ShipoutFontUse {
}
fn shipout_font_uses(
b: &NativeBox, programs: &JobVirtualFonts,
b: &NativeBox, programs: &JobVirtualFonts, fonts: &FontCatalog,
) -> 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)) {
if (!programs.is_known_physical(font.id) || fonts.automatic_origin(font.id).is_some())
&& seen.insert((font.id, slot))
{
uses.push(ShipoutFontUse { before_output, font: font.clone(), slot });
}
})?;
@@ -324,6 +326,7 @@ impl Executor {
device,
font_overrides,
virtual_glyphs: None,
pdf_font_map: self.pdf_virtual_fonts.captured_font_map(),
pdf_color_start,
pdf_color_steps: Vec::new(),
pdf_graphics_steps: Vec::new(),
@@ -364,7 +367,7 @@ impl Executor {
};
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))?
shipout_font_uses(b, &self.pdf_virtual_fonts, &self.state.fonts).map_err(|e| self.error(e, b.span))?
} else {
Vec::new()
}.into_iter().peekable();
@@ -376,7 +379,7 @@ impl Executor {
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.current = current;
self.prepare_virtual_glyph(
shipout.virtual_glyphs.as_mut().unwrap(), font_uses.next().unwrap(), files,
)?;
@@ -388,6 +391,7 @@ impl Executor {
OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. }
)
{
shipout.pdf_font_map = self.pdf_virtual_fonts.captured_font_map();
shipout.pdf_text_spaces =
Some(self.pdf_space_settings(automatic_spaces_at_start, uses_automatic_spaces));
self.current = output.span;
@@ -495,6 +499,7 @@ impl Executor {
for usage in font_uses {
self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?;
}
shipout.pdf_font_map = self.pdf_virtual_fonts.captured_font_map();
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();
@@ -556,7 +561,9 @@ impl Executor {
) -> Result<(), Error> {
self.check_cancellation()?;
let id = usage.font.id;
if self.pdf_virtual_fonts.is_known_physical(id) {
if self.pdf_virtual_fonts.is_known_physical(id)
&& self.state.fonts.automatic_origin(id).is_none()
{
return Ok(());
}
let defaults = self.font_defaults();
+88 -34
View File
@@ -130,8 +130,37 @@ impl NativeFont {
#[derive(Clone, Debug)]
struct MapEntry {
file: String,
file: Option<String>,
encoding: Option<String>,
postscript_name: bool,
unsupported_transform: Option<String>,
}
impl MapEntry {
fn is_scalable(&self) -> bool {
self.file.is_some() || self.postscript_name
}
fn type1_file(&self, name: &str) -> Result<&str, String> {
if let Some(value) = &self.unsupported_transform {
return Err(format!("native font map transform is not implemented: {value}"));
}
let file = self.file.as_deref().ok_or_else(|| {
format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support")
})?;
if !file.ends_with(".pfb") {
return Err(format!("native font program format is not implemented: {file}"));
}
Ok(file)
}
}
/// Version and lookup context of the PDF map read during shipout.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PdfFontMapInput {
pub(crate) from: std::path::PathBuf,
pub(crate) version: ResourceVersion,
}
fn map_entry(data: &[u8], name: &str) -> Result<Option<MapEntry>, String> {
let text = std::str::from_utf8(data).map_err(|_| "font map is not UTF-8/ASCII")?;
@@ -167,8 +196,13 @@ fn map_entry(data: &[u8], name: &str) -> Result<Option<MapEntry>, String> {
if !current.is_empty() {
fields.push((false, current));
}
let (mut file, mut encoding) = (None, None);
for (quote, value) in fields.into_iter().skip(1) {
let mut entry = MapEntry {
file: None,
encoding: None,
postscript_name: false,
unsupported_transform: None,
};
for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() {
if quote {
let words: Vec<_> = value.split_whitespace().collect();
// pdfTeX ignores PostScript names and ReEncodeFont words;
@@ -177,27 +211,52 @@ fn map_entry(data: &[u8], name: &str) -> Result<Option<MapEntry>, String> {
.iter()
.any(|w| matches!(*w, "SlantFont" | "ExtendFont"))
{
return Err(format!(
"native font map transform is not implemented: {value}"
));
entry.unsupported_transform.get_or_insert(value);
}
} else if value.starts_with('<') {
let path = value.trim_start_matches('<').trim_start_matches('[');
if path.ends_with(".enc") {
encoding = Some(path.to_owned());
} else if path.ends_with(".pfb") {
file = Some(path.to_owned());
} else {
return Err(format!(
"native font program format is not implemented: {path}"
));
entry.encoding = Some(path.to_owned());
} else if !path.is_empty() {
entry.file = Some(path.to_owned());
}
} else if index == 0 {
entry.postscript_name = true;
}
}
return Ok(Some(MapEntry { file: file.ok_or_else(||format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support"))?, encoding }));
return Ok(Some(entry));
}
Ok(None)
}
fn mapped_font(
map: &LoadedResource,
font: &NativeFont,
auto_expanded: bool,
) -> Result<Option<MapEntry>, String> {
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
// pdfTeX installs the dedicated spacing font on first use.
Some(MapEntry {
file: Some("pdftexspace.pfb".into()),
encoding: None,
postscript_name: false,
unsupported_transform: None,
})
} else {
map_entry(&map.data, &font.name)?.filter(MapEntry::is_scalable)
};
if auto_expanded && entry.is_none() {
return Err("font expansion: auto expansion is only possible with scalable fonts".into());
}
Ok(entry)
}
fn load_font_map(
files: &mut impl crate::execution::SourceProvider,
from: &std::path::Path,
) -> Result<LoadedResource, String> {
actual_resource(files, crate::resources::ResourceKind::Map, "pdftex.map", &from.to_string_lossy())
}
fn encoding_vector(data: &[u8]) -> Result<Vec<String>, String> {
let text = std::str::from_utf8(data).map_err(|_| "font encoding is not UTF-8/ASCII")?;
let text = text
@@ -394,29 +453,30 @@ fn resolve_physical_fonts(
) -> Result<(), String> {
use crate::{render::DisplayItem, resources::ResourceKind};
use std::collections::BTreeSet;
let mut used: BTreeMap<FontId, (Arc<NativeFont>, BTreeSet<u8>)> = BTreeMap::new();
let mut used: BTreeMap<FontId, (Arc<NativeFont>, BTreeSet<u8>, bool)> = BTreeMap::new();
for page in pages.iter() {
for item in &page.items {
if let DisplayItem::NativeGlyph { font, slot, .. } = item {
let entry = used
.entry(font.id)
.or_insert_with(|| (font.clone(), BTreeSet::new()));
.or_insert_with(|| (font.clone(), BTreeSet::new(), false));
if !Arc::ptr_eq(&entry.0, font) && !entry.0.same_base(font) {
return Err("native font ids from different jobs cannot share output".into());
}
entry.1.insert(*slot);
entry.2 |= font.expansion != 0;
}
}
}
let Some((first, _)) = used.values().next() else {
let Some((first, _, _)) = used.values().next() else {
return Ok(());
};
let map = actual_resource(
files,
ResourceKind::Map,
"pdftex.map",
&first.resource.version.path.to_string_lossy(),
)?;
let captured_map = pages.iter().find_map(|page| page.pdf_font_map.as_deref());
let from = captured_map.map_or(first.resource.version.path.as_path(), |map| map.from.as_path());
let map = load_font_map(files, from)?;
if captured_map.is_some_and(|captured| captured.version != map.version) {
return Err("PDF font map changed after shipout".into());
}
let mut resolved = BTreeMap::new();
let mut pk_resolved = BTreeMap::new();
let device = pages
@@ -424,14 +484,8 @@ fn resolve_physical_fonts(
.find_map(|p| p.pdf.as_ref())
.map(|p| p.file.clone());
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
for (id, (font, slots)) in used {
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
// The pdfTeX device adds its own map entry on first use.
Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None })
} else {
map_entry(&map.data, &font.name)?
};
let Some(entry) = entry else {
for (id, (font, slots, expanded)) in used {
let Some(entry) = mapped_font(&map, &font, expanded)? else {
let (resolution, digits) = if let Some(device) = &device {
(device.pk_resolution, device.decimal_digits)
} else {
@@ -495,13 +549,13 @@ fn resolve_physical_fonts(
);
continue;
};
let file = entry.file;
let key = (file.clone(), entry.encoding.clone());
let file = entry.type1_file(&font.name)?;
let key = (file.to_owned(), entry.encoding.clone());
if !cache.contains_key(&key) {
let resource = actual_resource(
files,
ResourceKind::Type1,
&file,
file,
&map.version.path.to_string_lossy(),
)?;
let decoded = font_cache.type1(&resource)?;
@@ -1,10 +1,10 @@
use super::{LetterspaceProgram, NativeFont, actual_resource, verify_resource};
use super::{LetterspaceProgram, NativeFont, PdfFontMapInput, actual_resource, load_font_map, mapped_font, verify_resource};
use crate::{
execution::{Cancellation, FontCatalog, FontId, FontIntegers, FontResource, SourceProvider},
math_engine_tex::{MathItem, PositionedItem},
provenance::Derivation,
render::{DisplayItem, DisplayList},
resources::ResourceKind,
resources::{LoadedResource, ResourceKind},
tfm::{FontSize, TfmMetrics},
virtual_font::{Axis, Command, LocalFont, VirtualFont},
};
@@ -49,6 +49,9 @@ enum Program {
#[derive(Clone, Default)]
pub(crate) struct JobVirtualFonts {
programs: BTreeMap<FontId, Option<Program>>,
first_physical_from: Option<std::path::PathBuf>,
font_map: Option<(Arc<PdfFontMapInput>, Arc<LoadedResource>)>,
checked_expansion_bases: BTreeSet<FontId>,
}
// Per-page packet results are relative to the enclosing glyph and shared by
@@ -109,6 +112,15 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
Ok(())
}
fn physical_font(&mut self, font: Arc<NativeFont>) -> Result<Arc<NativeFont>, String> {
let FontPrograms::Job { catalog, programs, .. } = &mut self.fonts else {
return Ok(font);
};
let face = catalog.paint_font(&font);
programs.observe_physical_font(&face, self.files)?;
Ok(face)
}
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Program>, String> {
match &mut self.fonts {
FontPrograms::Job {
@@ -218,10 +230,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
);
}
None => {
let font = match &self.fonts {
FontPrograms::Job { catalog, .. } => catalog.paint_font(&glyph.font),
FontPrograms::Standalone(_) => glyph.font,
};
let font = self.physical_font(glyph.font)?;
output.push(DisplayItem::NativeGlyph {
x: glyph.x,
y: glyph.y,
@@ -388,6 +397,28 @@ fn read_virtual(
}
impl JobVirtualFonts {
pub(crate) fn captured_font_map(&self) -> Option<Arc<PdfFontMapInput>> {
self.font_map.as_ref().map(|(input, _)| input.clone())
}
fn observe_physical_font(
&mut self, font: &NativeFont, files: &mut impl SourceProvider,
) -> Result<(), String> {
let from = self.first_physical_from.get_or_insert_with(|| font.resource.version.path.clone());
if font.expansion == 0 || self.checked_expansion_bases.contains(&font.id) {
return Ok(());
}
if self.font_map.is_none() {
let map = load_font_map(files, from)?;
let input = PdfFontMapInput { from: from.clone(), version: map.version.clone() };
self.font_map = Some((Arc::new(input), Arc::new(map)));
}
let (_, map) = self.font_map.as_ref().unwrap();
mapped_font(map, font, true)?;
self.checked_expansion_bases.insert(font.id);
Ok(())
}
pub(crate) fn is_known_physical(&self, id: FontId) -> bool {
matches!(self.programs.get(&id), Some(None))
}
@@ -530,6 +561,7 @@ impl JobVirtualFonts {
cancellation,
};
if !expansion.is_virtual(&font)? {
expansion.physical_font(font)?;
return Ok((None, 0));
}
let mut items = Vec::new();
@@ -635,6 +667,7 @@ pub(super) fn expand_pages(
width: page.width,
height: page.height,
prepared_virtual_glyphs: Some(BTreeMap::new()),
pdf_font_map: page.pdf_font_map.clone(),
magnification: page.magnification,
units: page.units,
pdf: page.pdf.clone(),
+3
View File
@@ -255,6 +255,8 @@ pub struct DisplayList {
pub magnification: i32,
pub units: DisplayUnits,
pub pdf: Option<crate::pdf_device::PdfPageData>,
#[doc(hidden)]
pub pdf_font_map: Option<std::sync::Arc<crate::native_font::PdfFontMapInput>>,
pub pdf_links: crate::pdf_device::links::PageLinks,
pub pdf_text_spaces: Option<crate::pdf_device::text_spaces::SpaceSettings>,
pub pdf_space_plan: Option<crate::pdf_device::text_spaces::SpacePlan>,
@@ -272,6 +274,7 @@ impl Default for DisplayList {
magnification: 1000,
units: DisplayUnits::PostScript,
pdf: None,
pdf_font_map: None,
pdf_links: Default::default(),
pdf_text_spaces: None,
pdf_space_plan: None,