From 51451813dc0993d57d665e49c38ae007bb7c3bcc Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 27 Nov 2026 16:15:18 +0800 Subject: [PATCH] Allocate and share native PDF font objects --- .../texrra-tex-core/src/execution/engine.rs | 4 + .../src/execution/engine/fonts.rs | 39 +++++++ .../src/execution/engine/page.rs | 14 ++- .../src/execution/format_image.rs | 6 +- crates/texrra-tex-core/src/execution/state.rs | 3 + crates/texrra-tex-core/src/native_font/map.rs | 11 ++ .../src/native_font/virtual_paint.rs | 16 +++ crates/texrra-tex-core/src/pdf.rs | 100 ++++++++++++++++-- .../src/pdf_device/page_resources.rs | 55 +++++++++- crates/texrra-tex-core/src/pdf_pk.rs | 7 +- docs/P2_M1_PROGRESS.md | 21 ++++ tests/native_dynamic_fonts.rs | 89 ++++++++++++++++ 12 files changed, 345 insertions(+), 20 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 115bcc9..a9c33c8 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -1011,6 +1011,10 @@ impl Executor { let number = self.pdf_page_reference(files)?; self.print_tokens(&number.to_string(), token)?; } + Pdffontobjnum => { + let number = self.pdf_font_object_query(files)?; + self.print_tokens(&number.to_string(), token)?; + } Leftmarginkern | Rightmarginkern => { let register = self.register_index(files)?; self.reads.insert(Dependency::BoxRegister(register)); diff --git a/crates/texrra-tex-core/src/execution/engine/fonts.rs b/crates/texrra-tex-core/src/execution/engine/fonts.rs index c1dd2bb..fd6bada 100644 --- a/crates/texrra-tex-core/src/execution/engine/fonts.rs +++ b/crates/texrra-tex-core/src/execution/engine/fonts.rs @@ -310,6 +310,45 @@ impl Executor { .and_then(|index| features.nth(index)).map_or(0, |tag| tag.0 as i32)) } + pub(super) fn pdf_font_object_query( + &mut self, files: &mut impl SourceProvider, + ) -> Result { + if self.state.input_profile() != InputProfile::TeX8Bit { + return self.fail("PDF font object command requires the pdfTeX profile"); + } + let id = self.font_identifier(files)?; + let font = self.state.fonts.glyph_font(id).cloned() + .map_err(|_| self.error("invalid PDF font identifier", self.current))?; + let defaults = self.font_defaults(); + Arc::make_mut(&mut self.pdf_virtual_fonts) + .check_pdf_object_font(&font, &mut self.state.fonts, defaults, files) + .map_err(|message| self.error(message, self.current))?; + self.register_pdf_font_object(&font, files) + } + + pub(super) fn register_pdf_font_object( + &mut self, font: &Arc, files: &mut impl SourceProvider, + ) -> Result { + self.reads.insert(Dependency::PdfObjects); + if let Some(number) = self.state.pdf_objects.as_deref().and_then(|objects| objects.font_number(font.id)) { + return Ok(number); + } + self.reads.insert(Dependency::FontResources); + if let Some((base, _)) = self.state.fonts.automatic_origin(font.id) { + let base = self.state.fonts.glyph_font(base).cloned() + .map_err(|message| self.error(message, self.current))?; + let number = self.register_pdf_font_object(&base, files)?; + self.state.pdf_objects.as_deref_mut().expect("registered base font") + .bind_font(font.id, number); + return Ok(number); + } + let scalable = Arc::make_mut(&mut self.pdf_virtual_fonts).scalable_pdf_object(font, files) + .map_err(|message| self.error(message, self.current))?; + self.state.pdf_objects.get_or_insert_with(Default::default) + .register_font(font.id, scalable.then_some(font.name.as_str()), self.limits.tokens) + .map_err(|message| self.error(message, self.current)) + } + pub(super) fn font_identifier( &mut self, files: &mut impl SourceProvider, diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 0edce99..0361a4e 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -835,12 +835,21 @@ impl Executor { } 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, + &mut self.state.fonts, defaults, files, usage.font.clone(), 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 { + if self.state.input_profile() == InputProfile::TeX8Bit { + for item in packet.iter() { + if let crate::math_engine_tex::MathItem::NativeGlyph { font, .. } = &item.item { + self.register_pdf_font_object(font, files)?; + } + } + } glyphs.entry(id).or_default().insert(usage.slot, packet); + } else if self.state.input_profile() == InputProfile::TeX8Bit { + self.register_pdf_font_object(&usage.font, files)?; } Ok(()) } @@ -891,6 +900,9 @@ impl Executor { let font = self.state.fonts .load_pdf_space(files, &request.name, &request.from, defaults) .map_err(|e| self.error(e, self.current))?; + if self.state.input_profile() == InputProfile::TeX8Bit { + self.register_pdf_font_object(&font, files)?; + } self.pdf_loaded_space_font = Some(font); } else { if before_output.is_none() { diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 3517ae1..0738a87 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -14,9 +14,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 87; -const COMPATIBLE_SCHEMAS: [u32; 54] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, SCHEMA, +const SCHEMA: u32 = 88; +const COMPATIBLE_SCHEMAS: [u32; 55] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 4ca0acc..28547b7 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -350,6 +350,7 @@ pub enum Primitive { Pdfuniformdeviate, Pdfnormaldeviate, Pdfpageref, + Pdffontobjnum, Partokenname, Pdfliteral, Leftmarginkern, @@ -519,6 +520,7 @@ impl Primitive { | Pdfuniformdeviate | Pdfnormaldeviate | Pdfpageref + | Pdffontobjnum | Leftmarginkern | Rightmarginkern | Pdfcolorstackinit @@ -910,6 +912,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = { ("pdfuniformdeviate", Pdfuniformdeviate), ("pdfnormaldeviate", Pdfnormaldeviate), ("pdfpageref", Pdfpageref), + ("pdffontobjnum", Pdffontobjnum), ("pdfliteral", Pdfliteral), ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index d0d7ddb..7eb429a 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -226,6 +226,17 @@ impl JobFontMap { Ok(()) } + pub(super) fn scalable_object( + &mut self, font: &NativeFont, files: &mut impl SourceProvider, + ) -> Result { + if self.bindings.is_none() { + self.initialize(true, &font.resource.version.path, files)?; + } + self.bind(font.id, &font.name); + let entry = self.bindings.as_ref().expect("initialized font map").font(font)?; + Ok(selected_outline(font, entry.as_deref(), false)?.is_some()) + } + fn bind(&mut self, id: FontId, name: &str) { let bindings = self.bindings.as_mut().unwrap(); if bindings.fonts.contains_key(&id) { diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index ffc6a5a..5541d4f 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -412,6 +412,22 @@ impl JobVirtualFonts { self.font_map.imported_type1_program(name, from, files) } + pub(crate) fn scalable_pdf_object( + &mut self, font: &NativeFont, files: &mut impl SourceProvider, + ) -> Result { + self.font_map.scalable_object(font, files) + } + + pub(crate) fn check_pdf_object_font( + &mut self, font: &Arc, catalog: &mut FontCatalog, + defaults: FontIntegers, files: &mut impl SourceProvider, + ) -> Result<(), String> { + if self.lookup(font, catalog, defaults, files)?.is_some() { + return Err("PDF font object command cannot be used with virtual font".into()); + } + Ok(()) + } + pub(crate) fn is_known_physical(&self, id: FontId) -> bool { matches!(self.programs.get(&id), Some(None)) } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 85fd860..2686389 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1542,10 +1542,19 @@ fn native_pdf( } let raw_objects = unicode.and_then(|options| options.objects); let page_tree = unicode.map_or(&[][..], |options| options.page_tree_attributes); - let font_attributes: BTreeMap<_, _> = fonts.keys().filter_map(|&font| { - let settings = unicode?.fonts.pdf_settings(font)?; - (!settings.attributes.is_empty()).then_some((font, settings.attributes.as_slice())) - }).collect(); + let mut font_attributes = BTreeMap::new(); + if let Some(options) = unicode { + for &font in fonts.keys() { + let owner = pdf_font_owner(raw_objects, font); + let attributes = [owner, font].into_iter().find_map(|id| { + let settings = options.fonts.pdf_settings(id)?; + (!settings.attributes.is_empty()).then_some(settings.attributes.as_slice()) + }); + if let Some(attributes) = attributes { + font_attributes.entry(owner).or_insert(attributes); + } + } + } let resources = if raw_objects.is_some() || !font_attributes.is_empty() || !page_tree.is_empty() @@ -1737,6 +1746,13 @@ fn native_type1_parameters( } } +fn pdf_font_owner( + objects: Option<&crate::pdf_device::page_resources::PdfObjects>, + id: crate::execution::FontId, +) -> crate::execution::FontId { + objects.and_then(|objects| objects.font_owner(objects.font_number(id)?)).unwrap_or(id) +} + fn write_native_font( objects: &mut Vec>, face: &crate::native_font::NativeFont, @@ -1746,15 +1762,18 @@ fn write_native_font( options: Option>, diagnostics: &mut Vec, reference: Option<&type1_fonts::Reference>, + target: Option, ) -> usize { let font = match &paint.program { crate::native_font::NativeFontProgram::Type1(font) => font, crate::native_font::NativeFontProgram::Pk(pk) => { - return pk_fonts::write_font(objects, face.id, pk, used, compression); + return pk_fonts::write_font(objects, face.id, pk, used, compression, target); } }; - let id = objects.len() + 1; - objects.push(Vec::new()); + let id = target.unwrap_or_else(|| { + objects.push(Vec::new()); + objects.len() + }); let m = face.metrics(); let descriptor = reference.map_or_else( || type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression), @@ -2226,6 +2245,54 @@ fn write_pdf( )); } } + let registry = unicode.and_then(|options| options.objects); + let mut device_objects = BTreeMap::new(); + if let Some(registry) = registry { + for number in registry.font_object_numbers() { + // An unused queried font leaves its reservation free. + objects.push(Vec::new()); + device_objects.insert(number, objects.len() as u32); + } + } + + let mut aliases = BTreeMap::new(); + let mut grouped_fonts = BTreeMap::new(); + for (id, (face, paint, used)) in native_used { + let owner = pdf_font_owner(registry, id); + aliases.insert(id, owner); + let entry = grouped_fonts.entry(owner).or_insert_with(|| { + let face = if owner == id { + face + } else { + let catalog = unicode.expect("font objects have a catalog").fonts; + catalog.paint_font(catalog.glyph_font(owner).expect("registered physical font")) + }; + (face, paint.clone(), BTreeMap::new()) + }); + if entry.1.encoding != paint.encoding + || entry.1.type1_program_key() != paint.type1_program_key() + { + return Err("shared PDF font has inconsistent output encoding or program".into()); + } + entry.2.extend(used); + } + let native_used = grouped_fonts; + // Font descriptors are written in reverse registration order. + if let Some(registry) = registry { + let mut latest = HashMap::new(); + for (&id, (_, paint, _)) in &native_used { + if let Some(number) = registry.font_number(id) + && let Some(program) = paint.type1_program_key() + { + let entry = latest.entry(program).or_insert((number, id)); + if number > entry.0 { + *entry = (number, id); + } + } + } + type1_descriptor_faces.extend(latest.into_iter().map(|(program, (_, id))| (program, id))); + } + // Use the form registered by shipout when one exists. A placement // retains its measured source image and can precede that registration. let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| { @@ -2268,7 +2335,7 @@ fn write_pdf( }; let (owner, owner_paint) = type1_descriptor_faces.get(&key) .map_or((face, paint), |id| { - let (face, paint, _) = &native_used[id]; + let (face, paint, _) = &native_used[&pdf_font_owner(registry, *id)]; (face, paint) }); let glyphs = used.keys().map(|slot| paint.encoding[usize::from(*slot)].as_str()); @@ -2280,6 +2347,8 @@ fn write_pdf( let mut native_font_ids = BTreeMap::new(); for (&id, (face, paint, used)) in &native_used { + let target = registry.and_then(|objects| objects.font_number(id)) + .map(|number| device_objects[&number] as usize); native_font_ids.insert( id, write_native_font( @@ -2291,9 +2360,14 @@ fn write_pdf( unicode, diagnostics, paint.type1_program_key().and_then(|key| type1_references.get(&key)), + target, ), ); } + for (font, owner) in aliases { + let id = native_font_ids[&owner]; + native_font_ids.insert(font, id); + } let mut used_faces = [false; FACE_COUNT]; let mut used_chars: [BTreeSet; FACE_COUNT] = Default::default(); for page in &paint_lists { @@ -2463,7 +2537,6 @@ fn write_pdf( } else { resources }; - let mut device_objects = BTreeMap::new(); for form in &forms { for number in [form.form.number, form.resource_number] { objects.push(Vec::new()); @@ -2578,7 +2651,14 @@ fn write_pdf( for (face, id) in &math_font_ids { fonts.push_str(&format!(" /M{} {id} 0 R", face.0)); } - for (face, id) in &native_font_ids { + let native_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item { + DisplayItem::NativeGlyph { font, .. } => Some(font.id), + _ => None, + }).chain(list.pdf_space_plan.iter().filter_map(|plan| { + plan.dedicated.as_ref().map(|font| font.font.id) + })).collect(); + for face in native_fonts { + let id = native_font_ids[&face]; fonts.push_str(&format!(" /N{} {id} 0 R", face.index())); } if !opentype.is_empty() { diff --git a/crates/texrra-tex-core/src/pdf_device/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/page_resources.rs index d99896d..33851ae 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -18,6 +18,7 @@ pub(crate) enum ObjectBody { Form, FormResources, Image(usize), + Font(FontId), PageResources, PageContents, Pages, @@ -38,7 +39,7 @@ impl ObjectBody { fn len(&self) -> usize { match self { Self::Page | Self::Link | Self::FormatLink | Self::Form - | Self::FormResources | Self::Image(_) | Self::PageResources | Self::PageContents + | Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages | Self::DiscardedAtDump => 0, Self::Direct(bytes) => bytes.len(), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), @@ -57,7 +58,7 @@ impl ObjectBody { fn parse(&self) -> Result { match self { Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources - | Self::Image(_) | Self::PageResources | Self::PageContents | Self::Pages => { + | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages => { Err("expected a generic native PDF object".into()) } Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()), @@ -96,6 +97,10 @@ pub struct PdfObjects { page_references: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] page_parent: Option, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + font_numbers: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + scalable_fonts: BTreeMap, } impl PdfObjects { @@ -142,6 +147,43 @@ impl PdfObjects { self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit) } + pub(crate) fn font_number(&self, font: FontId) -> Option { + self.font_numbers.get(&font).copied() + } + + pub(crate) fn font_owner(&self, number: u32) -> Option { + match self.entry(number)?.as_deref()? { + ObjectBody::Font(font) => Some(*font), + _ => None, + } + } + + pub(crate) fn font_object_numbers(&self) -> impl Iterator + '_ { + self.values.iter().enumerate().filter_map(|(index, entry)| { + matches!(entry.as_deref(), Some(ObjectBody::Font(_))).then_some(index as u32 + 1) + }) + } + + pub(crate) fn bind_font(&mut self, font: FontId, number: u32) { + self.font_numbers.insert(font, number); + } + + pub(crate) fn register_font( + &mut self, font: FontId, scalable_name: Option<&str>, limit: usize, + ) -> Result { + let number = if let Some(number) = scalable_name.and_then(|name| self.scalable_fonts.get(name)) { + *number + } else { + let number = self.allocate(Some(Arc::new(ObjectBody::Font(font))), limit)?; + if let Some(name) = scalable_name { + self.scalable_fonts.insert(name.to_owned(), number); + } + number + }; + self.bind_font(font, number); + Ok(number) + } + pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result { self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit) } @@ -203,7 +245,9 @@ impl PdfObjects { // A restored link whatsit gets its own annotation object when shipped. Some(ObjectBody::Link) => ObjectBody::FormatLink, Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources - | ObjectBody::PageContents | ObjectBody::Pages) => ObjectBody::DiscardedAtDump, + | ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)) => { + ObjectBody::DiscardedAtDump + } _ if self.written.contains(&number) => ObjectBody::DiscardedAtDump, _ => continue, }; @@ -214,6 +258,8 @@ impl PdfObjects { self.bytes = self.values.iter().flatten().map(|body| body.len()).sum(); self.page_references.clear(); self.page_parent = None; + self.font_numbers.clear(); + self.scalable_fonts.clear(); !self.values.is_empty() } @@ -668,7 +714,8 @@ impl ResourceOutput { link_references.entry(number).or_insert(None); continue; } - if values.contains_key(&number) || page_objects.contains(&number) || device_objects.contains(&number) { + if values.contains_key(&number) || page_objects.contains(&number) + || device_objects.contains(&number) || objects.font_owner(number).is_some() { continue; } if objects.is_discarded_at_dump(number) { diff --git a/crates/texrra-tex-core/src/pdf_pk.rs b/crates/texrra-tex-core/src/pdf_pk.rs index 20c70d1..dca4fad 100644 --- a/crates/texrra-tex-core/src/pdf_pk.rs +++ b/crates/texrra-tex-core/src/pdf_pk.rs @@ -8,9 +8,12 @@ pub(super) fn write_font( pk: &PkFontProgram, used: &BTreeMap, compression: u8, + target: Option, ) -> usize { - let font = objects.len() + 1; - objects.push(Vec::new()); + let font = target.unwrap_or_else(|| { + objects.push(Vec::new()); + objects.len() + }); let first = *used.keys().next().unwrap(); let last = *used.keys().next_back().unwrap(); let mut procs = String::new(); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 99305a9..ec724d2 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -828,6 +828,27 @@ TeX 可见的图像号由通用 PDF 对象表分配。真实页开始时分配 源码、原版和原生出页见 target/p3-pdf-shared-numbers/next-device-objects。 回执 target/p3-pdf-shared-numbers/receipt.json 的 SHA-256 为 e77e730569d6643bf5155c93cf1bb1e64070823d05094e962623fb736d88894e。 +### pdfTeX 字体对象编号与字号共享 + +`\pdffontobjnum` 根据真实字体标识和映射分配对象。首次实际绘制也走 +同一分配入口,虚拟字体使用包内实际绘制的物理字体。查询虚拟字体 +得到与原版对应的诊断。查询后未绘制的字体在交叉引用表中保留空闲 +编号。相同映射的同 TFM 可伸缩字体跨字号共享一个实际 Type 1 字典, +字典包含各字号绘制过的字形。普通 PDF 对象可以引用这个真实字典。 +页和 Form 的字体资源来自各自实际绘制。schema88 保留格式作业已 +占用的编号,重载作业按实际字体重新登记。 +[TeX Live 的字体分配和共享](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16120-L16167) + +九页 144 DPI 灰度图逐像素一致。另行核对的四种小数字号共用一个\n实际字典。编号对照覆盖首次绘制、延迟写出、 +Form 和格式重载。二十项定向回归通过。原有动态字体名称断言在 +上一发布版及当前版均因同样的六个子集前缀失败,保留原断言与 +两版日志。两页会话编辑子文件中的字号后复用已有检查点,预览 +只更新第二页,PDF、SVG 和来源映射与独立全量一致。 + +透明 PNG 和压缩对象流的分配时机仍待补齐。图像与页面 +对象编号阶段留存了对照。回执 target/p3-pdf-font-objects/receipt.json +的 SHA-256 为 6b705dff3ef2e12a119c17d9a9dc1b6965ff170f26f6f728ac5ba0015aebf98d。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/tests/native_dynamic_fonts.rs b/tests/native_dynamic_fonts.rs index 72539b0..d614869 100644 --- a/tests/native_dynamic_fonts.rs +++ b/tests/native_dynamic_fonts.rs @@ -524,3 +524,92 @@ fn only_selected_discretionary_material_requests_its_actual_font_program() { ); fs::remove_dir_all(p).unwrap(); } + +#[test] +fn shared_pdf_font_object_survives_a_checkpoint_and_size_edit() { + use lopdf::Document; + use std::sync::Arc; + use texrra_engine::native::{ + CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot, + }; + use texrra_tex_core::{execution::JobTime, resources::WorldConfig}; + + let root = directory().canonicalize().unwrap(); + let entry = root.join("entry.tex"); + let later = root.join("later.tex"); + let body = |size| -> Arc<[u8]> { + format!( + "\\font\\later=cmr10 at {size}pt\n\ + \\ifnum\\pdffontobjnum\\later=\\mainid\\else\\errmessage{{different font object}}\\fi\n" + ) + .into_bytes() + .into() + }; + let prefix = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=4 \pdfobjcompresslevel=0 \pdfcompresslevel=0 +\pdfpagewidth=100bp \pdfpageheight=100bp \pdfhorigin=5pt \pdfvorigin=5pt +\def\space{ } +\font\main=cmr10 +\edef\mainid{\pdffontobjnum\main} +\shipout\hbox{\vrule width8pt height4pt} +"; + let padding = format!("{}\n", "\\relax ".repeat(32)).repeat(48); + let suffix = r"\input later.tex +\pdfobj{<< /SharedFont \mainid\space 0 R >>} +\shipout\hbox{\pdfrefobj\pdflastobj\main Large \later Small} +\end +"; + let world = WorldConfig::new(&root); + let snapshot = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: [root.clone()].into(), + files: [ + (entry.clone(), format!("{prefix}{padding}{suffix}").into_bytes().into()), + (later.clone(), body(8)), + (root.join("pdftex.map"), Arc::from(b"cmr10 CMR10 0); + let delta = next.preview_since(Some(first.revision())).unwrap(); + assert_eq!(delta.pages.iter().map(|page| page.index).collect::>(), [1]); + let full = NativeCompiler::default().compile(revised).unwrap(); + assert_eq!(next.pdf, full.pdf); + assert_eq!(next.source_map.pages, full.source_map.pages); + assert_eq!(next.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + + let pdf = Document::load_mem(next.pdf.as_deref().unwrap()).unwrap(); + let shared = pdf.objects.values().find_map(|object| { + object.as_dict().ok()?.get(b"SharedFont").ok()?.as_reference().ok() + }).unwrap(); + let page = pdf.get_dictionary(pdf.get_pages()[&2]).unwrap(); + let resources = pdf.get_dictionary(page.get(b"Resources").unwrap().as_reference().unwrap()).unwrap(); + let fonts = resources.get(b"Font").unwrap().as_dict().unwrap(); + assert_eq!(fonts.len(), 2); + assert!(fonts.iter().all(|(_, object)| object.as_reference().unwrap() == shared)); + assert_eq!(pdf.get_dictionary(shared).unwrap().get(b"Subtype").unwrap().as_name().unwrap(), b"Type1"); + fs::remove_dir_all(root).unwrap(); +}