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,
@@ -274,7 +274,7 @@ fn format_retains_synthesized_slots_and_parameters_but_resets_active_paint() {
\end
",
),
&mut Host,
&mut font_world::FontFiles,
)
.unwrap();
let mut messages = Vec::new();
@@ -280,3 +280,35 @@ fn absent_density_or_provider_is_a_real_failure_and_never_changes_font_identity(
.contains(&Dependency::PdfDeviceConfiguration { pk_resolution: 300 })
);
}
#[test]
fn autoexpanded_bitmap_rejects_at_shipout_before_following_commands() {
let declaration = r"\pdfpkresolution=600
\font\bitmap=cmr10 \pdffontexpand\bitmap 75 75 25 autoexpand
\pdfadjustspacing=1 \parfillskip=0pt
\setbox0=\vbox{\hsize=32.25pt \bitmap \noindent AAAA\par}";
let mut files = Files::new(600);
let error = native(
&format!(r"{declaration}\shipout\box0\errmessage{{after shipout}}\end"),
&mut files,
)
.unwrap_err();
assert!(error.message.contains("auto expansion is only possible with scalable fonts"));
assert!(files.world.trace().reads.iter().any(|read| read.path.ends_with("pdftex.map")));
assert!(!files.world.trace().lookups.iter().any(|read| read.kind == ResourceKind::Pk));
let mut files = Files::new(600);
let execution = native(
&format!(r"{declaration}\shipout\hbox{{\bitmap AAAA}}\message{{ORDINARY}}\end"),
&mut files,
)
.unwrap();
assert_eq!(messages(&execution), ["ORDINARY"]);
let mut pages = execution.shipout_display_lists().unwrap();
resolve_native_fonts(&mut pages, &mut files).unwrap();
assert!(pages[0].items.iter().any(|item| matches!(
item,
texrra_tex_core::render::DisplayItem::NativeGlyph { paint: Some(paint), .. }
if matches!(paint.program, NativeFontProgram::Pk(_))
)));
}
+33
View File
@@ -2089,6 +2089,39 @@ next-bitmap-receipt.json 的 SHA-256 为
6d9ede00c8be61b517c201fd0081a1a0de477a25b6b8da2fb68f2eb29cbec045。
[pdfTeX 初始化实际 PDF 字体](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L14905-L14920)
### PK 位图自动伸缩的出页判定
原生出页在处理首个真正使用的自动伸缩物理字体时,按实际 PDF
字体映射判断可伸缩性。直接字形和 VF 字符程序映射到的物理字形
经过同一判定。缺少映射与显式 PK 条目都进入位图路径。自动伸缩
的位图在出页时失败,普通位图继续按实际 PK 程序绘制。仅装盒
和丢弃的材料无需读取 PDF 映射。出页记录已检查的映射版本,
最终 PDF 和 SVG 使用通过版本核对的映射。
[pdfTeX 判断字体是否可伸缩](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/mapfile.c#L594-L623)
[pdfTeX 的出页检查](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L14905-L14920)
七个 pdfTeX 对照通过。冻结的真实 600 dpi PK、显式 PK 映射和
递归到 PK 的 VF 字符程序,在自动伸缩出页时均按参考失败。
VF 的前置延迟写出已经执行,后置写出尚未执行。两份正常 PK 输出
的词框、144 dpi 彩色栅格与参考一致,可伸缩 Type1 对照在 600 dpi
也一致。13 项位图、虚拟字体和格式定向回归通过。
target/p3-bitmap-autoexpand/receipt.json 的 SHA-256 为
bc9f4e2304f034813cafca50e2643fd927e745c8f091b85e83b2a5c02dc40206。
三页增量工程中,将映射改成位图后,原生在第二页出页期间拒绝,
且保留此前发布的 PDF。恢复真实映射并编辑第二页后复用 1339 步,
只替换第二页,PDF、SVG 和来源映射与独立全量编译一致。
incremental/final.log 的 SHA-256 为
d3f86cfed83f1f4604ba22eb3d994583876b90a4e5a925b7e8e247df557a3ab9。
下一处缺口是任务内动态映射。冻结的两份输入以实际 PK 条目为起点,
分别用 `\pdfmapline` 和 `\pdfmapfile` 改为同一真实 Type1 文件,
pdfTeX 均输出 PDF,原生当前报告未定义的原语。下一步将动态映射和
实际 .map 资源版本接入任务和出页快照,覆盖增删替换、已使用的
字体身份以及检查点失效。
next-mapping-receipt.json 的 SHA-256 为
e1e905ec32d5e9899748cb57f091107d3fd56d3c59fdedaf067a4dd232f5461f。
### 原生段落边缘悬挂
`\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平