From 28dfba5a5eebb0c03dee8e404d802d42bccc45a8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 09:53:31 +0800 Subject: [PATCH] Apply job-local PDF font maps at execution and shipout --- .../texrra-tex-core/src/execution/device.rs | 4 +- .../src/execution/engine/device.rs | 25 ++ .../src/execution/engine/page.rs | 6 +- .../src/execution/format_image.rs | 11 +- crates/texrra-tex-core/src/execution/mod.rs | 7 + .../src/execution/parameters.rs | 2 + crates/texrra-tex-core/src/execution/state.rs | 19 + crates/texrra-tex-core/src/native_font.rs | 198 +++------- crates/texrra-tex-core/src/native_font/map.rs | 365 ++++++++++++++++++ .../src/native_font/virtual_paint.rs | 37 +- crates/texrra-tex-core/src/render.rs | 4 +- .../tests/execution_pk_device.rs | 46 +++ docs/P2_M1_PROGRESS.md | 31 ++ src/native_checkpoint_probe.rs | 7 + src/native_job.rs | 8 + 15 files changed, 583 insertions(+), 187 deletions(-) create mode 100644 crates/texrra-tex-core/src/native_font/map.rs diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 75247ae..e614e13 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -24,7 +24,7 @@ pub struct NativeShipout { #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) virtual_glyphs: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - pub(super) pdf_font_map: Option>, + pub(super) pdf_font_bindings: Option>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_color_start: Vec>, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -62,7 +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_font_bindings: self.pdf_font_bindings.clone(), pdf_links: self.pdf_links.clone(), pdf_text_spaces: self.pdf_text_spaces.clone(), pdf_resources: crate::pdf_device::page_resources::PageResources { diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index 3d24346..0dee00c 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -12,6 +12,7 @@ impl Executor { use Primitive::*; match primitive { Pdfglyphtounicode => self.glyph_to_unicode(files)?, + Pdfmapfile | Pdfmapline => self.pdf_font_map_command(primitive, token.span, files)?, Pdffontattr | Pdfnobuiltintounicode => { self.pdf_font_settings(primitive, files)?; } @@ -83,6 +84,30 @@ impl Executor { } Ok(()) } + fn pdf_font_map_command( + &mut self, primitive: Primitive, span: Span, files: &mut impl SourceProvider, + ) -> Result<(), Error> { + if self.read_parameter(Parameter::Pdfoutput).width() <= 0 { + return self.fail("PDF font map commands are not allowed in DVI mode"); + } + let tokens = self.scan_expanded_group(files)?; + let bytes = self.pdf_token_bytes(&tokens)?; + let suppress_duplicates = self.read_parameter(Parameter::Pdfsuppresswarningdupmap).width() > 0; + let from = self.source_name(span); + self.reads.insert(Dependency::FontResources); + let warnings = Arc::make_mut(&mut self.pdf_virtual_fonts) + .update_font_map(&bytes, primitive == Primitive::Pdfmapfile, std::path::Path::new(&from), + suppress_duplicates, files) + .map_err(|error| self.error(error, span))?; + for warning in warnings { + let text = format!("native PDF warning: {warning}"); + files.observe_diagnostic(WriteDestination::TerminalAndLog, &format!("{text}\n")) + .map_err(|e| self.error(e, span))?; + self.events.push(Event::Message { text, span }); + } + Ok(()) + } + pub(super) fn glyph_to_unicode( &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 575926a..a0dab08 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -326,7 +326,7 @@ impl Executor { device, font_overrides, virtual_glyphs: None, - pdf_font_map: self.pdf_virtual_fonts.captured_font_map(), + pdf_font_bindings: self.pdf_virtual_fonts.captured_font_bindings(), pdf_color_start, pdf_color_steps: Vec::new(), pdf_graphics_steps: Vec::new(), @@ -391,7 +391,7 @@ impl Executor { OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. } ) { - shipout.pdf_font_map = self.pdf_virtual_fonts.captured_font_map(); + shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings(); shipout.pdf_text_spaces = Some(self.pdf_space_settings(automatic_spaces_at_start, uses_automatic_spaces)); self.current = output.span; @@ -499,7 +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(); + shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings(); 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(); diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 0173a19..4042f5f 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 54; -const COMPATIBLE_SCHEMAS: [u32; 23] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, SCHEMA, +const SCHEMA: u32 = 55; +const COMPATIBLE_SCHEMAS: [u32; 24] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -127,8 +127,11 @@ impl FormatImage { if image.state.fonts.has_unrecorded_expansion_limits() { return Err("native format must be rebuilt to restore automatic expansion font identities".into()); } - if image.schema < SCHEMA { + if image.schema < 54 { image.state.restore_legacy_format_fonts()?; + } + if image.schema < 55 { + image.state.restore_legacy_font_map_commands(); image.schema = SCHEMA; } Ok(image) diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 96fbf0b..138e853 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -250,6 +250,13 @@ pub trait SourceProvider { ) -> Result, String> { Ok(None) } + /// Read an actual PDF font map. A host that can distinguish missing + /// files from other failures can return None for TeX's warning path. + fn optional_font_map( + &mut self, name: &str, from: &str, + ) -> Result, String> { + self.resource(crate::resources::ResourceKind::Map, name, from).map(Some) + } /// Read exact bytes through the normal TeX input policy. Missing inputs /// return None. Denied or unavailable host operations remain errors. fn optional_tex_input( diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index f8beb51..781f997 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -14,6 +14,7 @@ pub enum Parameter { Pdfpkresolution, Pdfimageresolution, Pdfgentounicode, + Pdfsuppresswarningdupmap, Pdfinfoomitdate, Tracingcommands, Tracingrestores, @@ -135,6 +136,7 @@ impl Parameter { Self::Pdfpkresolution, Self::Pdfimageresolution, Self::Pdfgentounicode, + Self::Pdfsuppresswarningdupmap, Self::Pdfinfoomitdate, Self::Tracingcommands, Self::Tracingrestores, diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 993f286..0e0b3b1 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -124,6 +124,8 @@ pub enum Primitive { Pdflastypos, Pdfrestore, Pdfglyphtounicode, + Pdfmapfile, + Pdfmapline, Pdffontattr, Pdfnobuiltintounicode, Currentgrouplevel, @@ -1043,6 +1045,8 @@ impl Default for State { ("pdflastypos", Pdflastypos), ("pdfrestore", Pdfrestore), ("pdfglyphtounicode", Pdfglyphtounicode), + ("pdfmapfile", Pdfmapfile), + ("pdfmapline", Pdfmapline), ("pdffontattr", Pdffontattr), ("pdfnobuiltintounicode", Pdfnobuiltintounicode), ("dump", Dump), @@ -1479,6 +1483,21 @@ impl State { Ok(()) } + pub(super) fn restore_legacy_font_map_commands(&mut self) { + for (name, meaning) in [ + ("pdfmapfile", Meaning::Primitive(Primitive::Pdfmapfile)), + ("pdfmapline", Meaning::Primitive(Primitive::Pdfmapline)), + ( + "pdfsuppresswarningdupmap", + Meaning::Parameter(Parameter::Pdfsuppresswarningdupmap), + ), + ] { + self.commands + .entry(CommandName::Control(name.into())) + .or_insert(meaning); + } + } + pub fn is_initex(&self) -> bool { self.initex } diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 1c0f331..63f8190 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -12,7 +12,10 @@ use std::{ collections::{BTreeMap, VecDeque}, sync::{Arc, Mutex}, }; +mod map; mod virtual_paint; +pub use map::PdfFontBindings; +use map::{dedicated_space_map, find_map_entry, load_map, selected_outline}; pub(crate) use virtual_paint::{JobVirtualFonts, VirtualGlyphs, VirtualPaintState}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -23,13 +26,15 @@ pub struct NativeFontPaint { pub bbox: [i32; 4], pub stem_v: i32, pub resources: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + program_index: Option, } impl NativeFontPaint { pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool { // pdfTeX requires the space name in an actual map re-encoding. matches!(self.program, NativeFontProgram::Type1(_)) - && self.resources.len() == 3 + && self.resources.len() == self.program_index.unwrap_or(1) + 2 && self.encoding[32] == "space" && font.metrics().width(' ') > 65_782 } @@ -37,7 +42,7 @@ impl NativeFontPaint { match &self.program { NativeFontProgram::Type1(_) => { // The physical font follows the map, before any encoding resource. - self.resources.get(1) + self.resources.get(self.program_index.unwrap_or(1)) } NativeFontProgram::Pk(_) => None, } @@ -128,135 +133,6 @@ impl NativeFont { } } -#[derive(Clone, Debug)] -struct MapEntry { - file: Option, - encoding: Option, - postscript_name: bool, - unsupported_transform: Option, -} - -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, String> { - let text = std::str::from_utf8(data).map_err(|_| "font map is not UTF-8/ASCII")?; - for line in text.lines() { - if line.split_whitespace().next() != Some(name) { - continue; - } - let mut fields = Vec::new(); - let mut current = String::new(); - let mut quoted = false; - for c in line.chars() { - match c { - '%' if !quoted => break, - '"' => { - if quoted { - fields.push((true, std::mem::take(&mut current))); - } else if !current.is_empty() { - fields.push((false, std::mem::take(&mut current))); - } - quoted = !quoted; - } - c if c.is_ascii_whitespace() && !quoted => { - if !current.is_empty() { - fields.push((false, std::mem::take(&mut current))); - } - } - _ => current.push(c), - } - } - if quoted { - return Err(format!("unterminated font map operation for {name}")); - } - if !current.is_empty() { - fields.push((false, current)); - } - 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; - // the actual .enc file supplies the encoding vector. - if words - .iter() - .any(|w| matches!(*w, "SlantFont" | "ExtendFont")) - { - 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") { - 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(entry)); - } - Ok(None) -} -fn mapped_font( - map: &LoadedResource, - font: &NativeFont, - auto_expanded: bool, -) -> Result, 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 { - actual_resource(files, crate::resources::ResourceKind::Map, "pdftex.map", &from.to_string_lossy()) -} - fn encoding_vector(data: &[u8]) -> Result, String> { let text = std::str::from_utf8(data).map_err(|_| "font encoding is not UTF-8/ASCII")?; let text = text @@ -418,6 +294,7 @@ impl NativeFontCache { let mut page = DisplayList { units: DisplayUnits::TeX, pdf: device, + pdf_font_bindings: Some(Arc::new(PdfFontBindings::default())), items: vec![DisplayItem::NativeGlyph { x: 0, y: 0, @@ -471,12 +348,14 @@ fn resolve_physical_fonts( let Some((first, _, _)) = used.values().next() else { return Ok(()); }; - 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 captured = pages.iter().rev().find_map(|page| page.pdf_font_bindings.as_deref()); + let default_map = if captured.is_none() { + load_map(files, "pdftex.map", &first.resource.version.path)? + } else { + None + }; + let default_version = captured.and_then(|bindings| bindings.default_map.as_ref()) + .or_else(|| default_map.as_ref().map(|map| &map.version)); let mut resolved = BTreeMap::new(); let mut pk_resolved = BTreeMap::new(); let device = pages @@ -485,7 +364,16 @@ fn resolve_physical_fonts( .map(|p| p.file.clone()); let mut cache: BTreeMap<_, (NativeFontPaint, Arc)> = BTreeMap::new(); for (id, (font, slots, expanded)) in used { - let Some(entry) = mapped_font(&map, &font, expanded)? else { + let entry = if font.pdf_space_font && font.name == "pdftexspace" { + Some(Arc::new(dedicated_space_map(&font))) + } else if let Some(bindings) = captured { + bindings.font(&font)? + } else if let Some(map) = &default_map { + find_map_entry(map, &font.name)?.map(Arc::new) + } else { + None + }; + let Some(outline) = selected_outline(&font, entry.as_deref(), expanded)? else { let (resolution, digits) = if let Some(device) = &device { (device.pk_resolution, device.decimal_digits) } else { @@ -544,29 +432,36 @@ fn resolve_physical_fonts( glyph_paths, bbox: bbox.unwrap(), stem_v: 0, - resources: vec![map.version.clone(), resource.version], + resources: entry.as_ref().and_then(|entry| entry.version.as_ref()) + .or(default_version).cloned().into_iter() + .chain(std::iter::once(resource.version)).collect(), + program_index: None, }), ); continue; }; - let file = entry.type1_file(&font.name)?; - let key = (file.to_owned(), entry.encoding.clone()); + let file = outline.type1_file(&font.name)?; + let version = outline.version.as_ref(); + let key = ( + outline.from.clone(), + version.map(|version| version.sha256.clone()), + file.to_owned(), + outline.encoding.clone(), + ); if !cache.contains_key(&key) { - let resource = actual_resource( - files, - ResourceKind::Type1, - file, - &map.version.path.to_string_lossy(), - )?; + let from = outline.from.to_string_lossy(); + let resource = actual_resource(files, ResourceKind::Type1, file, &from)?; let decoded = font_cache.type1(&resource)?; let program = &decoded.program; - let mut resources = vec![map.version.clone(), resource.version]; - let encoding = if let Some(name) = entry.encoding { + let mut resources: Vec<_> = version.cloned().into_iter().collect(); + let program_index = Some(resources.len()); + resources.push(resource.version); + let encoding = if let Some(name) = &outline.encoding { let enc = actual_resource( files, ResourceKind::Encoding, - &name, - &map.version.path.to_string_lossy(), + name, + &from, )?; let encoding = encoding_vector(&enc.data)?; resources.push(enc.version); @@ -586,6 +481,7 @@ fn resolve_physical_fonts( bbox: decoded.bbox, stem_v: decoded.stem_v, resources, + program_index, }, decoded, ), diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs new file mode 100644 index 0000000..44764df --- /dev/null +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -0,0 +1,365 @@ +//! PDF font map entries, lookup bindings, and the lifetime of the default map. +use super::{NativeFont, verify_resource}; +use crate::{ + execution::{FontId, SourceProvider}, + resources::{LoadedResource, ResourceKind, ResourceVersion}, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, + sync::Arc, +}; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(super) struct MapEntry { + pub from: PathBuf, + pub version: Option, + file: Option, + pub encoding: Option, + postscript_name: bool, + unsupported_transform: Option, +} + +impl MapEntry { + fn is_scalable(&self) -> bool { + self.file.is_some() || self.postscript_name + } + + pub(super) 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) + } +} + +fn parse_map_line( + line: &str, + from: &Path, + version: Option<&ResourceVersion>, +) -> Result, String> { + let line = line.trim(); + if line.is_empty() || line.starts_with(['%', '#', ';', '*']) { + return Ok(None); + } + let name = line.split_ascii_whitespace().next().unwrap().to_owned(); + let mut fields = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + for c in line.chars() { + match c { + '%' if !quoted => break, + '"' => { + if quoted { + fields.push((true, std::mem::take(&mut current))); + } else if !current.is_empty() { + fields.push((false, std::mem::take(&mut current))); + } + quoted = !quoted; + } + c if c.is_ascii_whitespace() && !quoted => { + if !current.is_empty() { + fields.push((false, std::mem::take(&mut current))); + } + } + _ => current.push(c), + } + } + if quoted { + return Err(format!("unterminated font map operation for {name}")); + } + if !current.is_empty() { + fields.push((false, current)); + } + let mut entry = MapEntry { + from: from.to_path_buf(), + version: version.cloned(), + 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; + // the actual .enc file supplies the encoding vector. + if words + .iter() + .any(|w| matches!(*w, "SlantFont" | "ExtendFont")) + { + 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") { + entry.encoding = Some(path.to_owned()); + } else if !path.is_empty() { + entry.file = Some(path.to_owned()); + } + } else if index == 0 && !value.as_bytes()[0].is_ascii_digit() { + entry.postscript_name = true; + } + } + Ok(Some((name, entry))) +} + +#[doc(hidden)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct PdfFontBindings { + fonts: BTreeMap>>, + pub(super) default_map: Option, +} + +impl PdfFontBindings { + pub(super) fn font(&self, font: &NativeFont) -> Result>, String> { + self.fonts + .get(&font.id) + .cloned() + .ok_or_else(|| format!("PDF font {} has no captured map binding", font.name)) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum MapMode { + Add, + Replace, + Delete, +} + +#[derive(Clone, Default)] +pub(super) struct JobFontMap { + // Ordinary unevaluated pages can retain raw lists for hosts that only + // need TeX layout. A map command or actual autoexpanded glyph activates + // the table and materializes all earlier first-use bindings in order. + first_font_source: Option, + pending_fonts: Vec<(FontId, String)>, + pending_ids: BTreeSet, + entries: Arc>>, + used_names: BTreeSet, + bindings: Option>, +} + +impl JobFontMap { + pub(super) fn bindings(&self) -> Option> { + self.bindings.clone() + } + + pub(super) fn observe( + &mut self, + font: &NativeFont, + files: &mut impl SourceProvider, + ) -> Result<(), String> { + let from = &font.resource.version.path; + self.first_font_source.get_or_insert_with(|| from.clone()); + if self.bindings.is_none() && font.expansion == 0 { + if self.pending_ids.insert(font.id) { + self.pending_fonts.push((font.id, font.name.clone())); + } + return Ok(()); + } + if self.bindings.is_none() { + self.initialize(true, from, files)?; + } + self.bind(font.id, &font.name); + let entry = self.bindings.as_ref().unwrap().font(font)?; + selected_outline(font, entry.as_deref(), font.expansion != 0)?; + Ok(()) + } + + fn bind(&mut self, id: FontId, name: &str) { + let bindings = self.bindings.as_mut().unwrap(); + if bindings.fonts.contains_key(&id) { + return; + } + let entry = self.entries.get(name).cloned(); + if entry.is_some() { + self.used_names.insert(name.into()); + } + Arc::make_mut(bindings).fonts.insert(id, entry); + } + + fn initialize( + &mut self, + default_pending: bool, + from: &Path, + files: &mut impl SourceProvider, + ) -> Result<(), String> { + let mut bindings = PdfFontBindings::default(); + if default_pending || self.first_font_source.is_some() { + let from = self.first_font_source.as_deref().unwrap_or(from); + if let Some(read) = load_map(files, "pdftex.map", from)? { + let mut ignored = Vec::new(); + self.apply_file(&read, MapMode::Add, true, &mut ignored)?; + bindings.default_map = Some(read.version); + } + } + self.bindings = Some(Arc::new(bindings)); + for (id, name) in std::mem::take(&mut self.pending_fonts) { + self.bind(id, &name); + } + self.pending_ids.clear(); + Ok(()) + } + + pub(super) fn command( + &mut self, + input: &[u8], + map_file: bool, + from: &Path, + suppress_duplicates: bool, + files: &mut impl SourceProvider, + ) -> Result, String> { + let text = + std::str::from_utf8(input).map_err(|_| "PDF font map command is not UTF-8/ASCII")?; + let text = text.trim_start_matches(' '); + let (sign, item) = match text.as_bytes().first() { + Some(b'+' | b'=' | b'-') => (text.as_bytes().first().copied(), &text[1..]), + _ => (None, text), + }; + let mode = match sign { + Some(b'=') => MapMode::Replace, + Some(b'-') => MapMode::Delete, + _ => MapMode::Add, + }; + if self.bindings.is_none() { + self.initialize(sign.is_some(), from, files)?; + } + let item = item.trim_start_matches(' '); + let mut warnings = Vec::new(); + if map_file { + if let Some(name) = item.split_ascii_whitespace().next() { + let name = if name.ends_with(".map") { + name.to_owned() + } else { + format!("{name}.map") + }; + match load_map(files, &name, from)? { + Some(read) => { + self.apply_file(&read, mode, suppress_duplicates, &mut warnings)? + } + None => warnings.push(format!("cannot open font map file {name}")), + } + } + } else { + self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings); + } + Ok(warnings) + } + + fn apply_file( + &mut self, + read: &LoadedResource, + mode: MapMode, + suppress_duplicates: bool, + warnings: &mut Vec, + ) -> Result<(), String> { + let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?; + for line in text.lines() { + self.apply_line( + line, + &read.version.path, + Some(&read.version), + mode, + suppress_duplicates, + warnings, + ); + } + Ok(()) + } + + fn apply_line( + &mut self, + line: &str, + from: &Path, + version: Option<&ResourceVersion>, + mode: MapMode, + suppress_duplicates: bool, + warnings: &mut Vec, + ) { + let (name, entry) = match parse_map_line(line, from, version) { + Ok(Some(entry)) => entry, + Ok(None) => return, + Err(error) => { + warnings.push(error); + return; + } + }; + if self.entries.contains_key(&name) { + if mode == MapMode::Add { + if !suppress_duplicates { + warnings.push(format!( + "fontmap entry for '{name}' already exists, duplicates ignored" + )); + } + return; + } + if self.used_names.contains(&name) { + warnings.push(format!( + "fontmap entry for '{name}' has been used, replace/delete not allowed" + )); + return; + } + } + if mode == MapMode::Delete { + Arc::make_mut(&mut self.entries).remove(&name); + } else { + Arc::make_mut(&mut self.entries).insert(name, Arc::new(entry)); + } + } +} + +pub(super) fn load_map( + files: &mut impl SourceProvider, + name: &str, + from: &Path, +) -> Result, String> { + files + .optional_font_map(name, &from.to_string_lossy())? + .map(|map| verify_resource(map, ResourceKind::Map, name)) + .transpose() +} + +pub(super) fn find_map_entry(map: &LoadedResource, name: &str) -> Result, String> { + let text = std::str::from_utf8(&map.data).map_err(|_| "font map is not UTF-8/ASCII")?; + let Some(line) = text + .lines() + .find(|line| line.split_ascii_whitespace().next() == Some(name)) + else { + return Ok(None); + }; + Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry)) +} + +pub(super) fn selected_outline<'a>( + font: &NativeFont, + entry: Option<&'a MapEntry>, + auto_expanded: bool, +) -> Result, String> { + let outline = entry.filter(|entry| entry.is_scalable()); + if auto_expanded && outline.is_none() && !font.pdf_space_font { + return Err("font expansion: auto expansion is only possible with scalable fonts".into()); + } + Ok(outline) +} + +pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry { + MapEntry { + from: font.resource.version.path.clone(), + version: None, + file: Some("pdftexspace.pfb".into()), + encoding: None, + postscript_name: false, + unsupported_transform: None, + } +} 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 acd3911..cb6a726 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -1,10 +1,10 @@ -use super::{LetterspaceProgram, NativeFont, PdfFontMapInput, actual_resource, load_font_map, mapped_font, verify_resource}; +use super::{LetterspaceProgram, NativeFont, PdfFontBindings, actual_resource, map::JobFontMap, verify_resource}; use crate::{ execution::{Cancellation, FontCatalog, FontId, FontIntegers, FontResource, SourceProvider}, math_engine_tex::{MathItem, PositionedItem}, provenance::Derivation, render::{DisplayItem, DisplayList}, - resources::{LoadedResource, ResourceKind}, + resources::ResourceKind, tfm::{FontSize, TfmMetrics}, virtual_font::{Axis, Command, LocalFont, VirtualFont}, }; @@ -49,9 +49,7 @@ enum Program { #[derive(Clone, Default)] pub(crate) struct JobVirtualFonts { programs: BTreeMap>, - first_physical_from: Option, - font_map: Option<(Arc, Arc)>, - checked_expansion_bases: BTreeSet, + font_map: JobFontMap, } // Per-page packet results are relative to the enclosing glyph and shared by @@ -117,7 +115,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { return Ok(font); }; let face = catalog.paint_font(&font); - programs.observe_physical_font(&face, self.files)?; + programs.font_map.observe(&face, self.files)?; Ok(face) } @@ -397,26 +395,15 @@ fn read_virtual( } impl JobVirtualFonts { - pub(crate) fn captured_font_map(&self) -> Option> { - self.font_map.as_ref().map(|(input, _)| input.clone()) + pub(crate) fn captured_font_bindings(&self) -> Option> { + self.font_map.bindings() } - 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 update_font_map( + &mut self, bytes: &[u8], map_file: bool, from: &std::path::Path, suppress_duplicates: bool, + files: &mut impl SourceProvider, + ) -> Result, String> { + self.font_map.command(bytes, map_file, from, suppress_duplicates, files) } pub(crate) fn is_known_physical(&self, id: FontId) -> bool { @@ -667,7 +654,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(), + pdf_font_bindings: page.pdf_font_bindings.clone(), magnification: page.magnification, units: page.units, pdf: page.pdf.clone(), diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 485ec71..bf7fcfd 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -256,7 +256,7 @@ pub struct DisplayList { pub units: DisplayUnits, pub pdf: Option, #[doc(hidden)] - pub pdf_font_map: Option>, + pub pdf_font_bindings: Option>, pub pdf_links: crate::pdf_device::links::PageLinks, pub pdf_text_spaces: Option, pub pdf_space_plan: Option, @@ -274,7 +274,7 @@ impl Default for DisplayList { magnification: 1000, units: DisplayUnits::PostScript, pdf: None, - pdf_font_map: None, + pdf_font_bindings: None, pdf_links: Default::default(), pdf_text_spaces: None, pdf_space_plan: None, diff --git a/crates/texrra-tex-core/tests/execution_pk_device.rs b/crates/texrra-tex-core/tests/execution_pk_device.rs index c90a262..63fd33e 100644 --- a/crates/texrra-tex-core/tests/execution_pk_device.rs +++ b/crates/texrra-tex-core/tests/execution_pk_device.rs @@ -37,6 +37,10 @@ impl Files { } c.paths .insert(ResourceKind::Map, vec![SearchPath::directory(map, false)]); + c.paths.insert( + ResourceKind::Type1, + vec![SearchPath::directory(root.join("../../assets/fonts"), false)], + ); Self { world: FileWorld::new(c).unwrap(), } @@ -49,6 +53,9 @@ impl SourceProvider for Files { fn resource(&mut self, k: ResourceKind, n: &str, f: &str) -> Result { self.world.read(k, n, Path::new(f)) } + fn optional_font_map(&mut self, n: &str, f: &str) -> Result, String> { + self.world.read_optional(ResourceKind::Map, n, Path::new(f)) + } fn pk_font(&mut self, n: &str, d: u32, f: &str) -> Result { self.world.read_pk(n, d, Path::new(f)) } @@ -312,3 +319,42 @@ fn autoexpanded_bitmap_rejects_at_shipout_before_following_commands() { if matches!(paint.program, NativeFontProgram::Pk(_)) ))); } + +#[test] +fn font_map_file_binds_new_font_ids_and_locks_used_entries() { + let map = directory(); + fs::write(map.join("pdftex.map"), "% absent row\n").unwrap(); + fs::write(map.join("outline.map"), "cmr10 CMR10 paint.as_deref(), + _ => None, + }).unwrap(); + assert_eq!(matches!(paint.program, NativeFontProgram::Type1(_)), i >= 2); + assert_eq!(paint.resources[0].path.file_name().unwrap(), + if i >= 2 { "outline.map" } else { "pdftex.map" }); + } + fs::remove_dir_all(map).unwrap(); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4c145cb..ef4b3d6 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2122,6 +2122,37 @@ pdfTeX 均输出 PDF,原生当前报告未定义的原语。下一步将动态 next-mapping-receipt.json 的 SHA-256 为 e1e905ec32d5e9899748cb57f091107d3fd56d3c59fdedaf067a4dd232f5461f。 +### 任务内 PDF 字体映射 + +\pdfmapline 和 \pdfmapfile 读取展开后的参数并立即修改任务映射表。 +支持新增、替换、删除、已使用条目锁定、重复警告开关和缺失文件诊断。 +未带模式符的首次指令可以取消尚未读取的默认表。物理字体在首次实际 +出页时绑定映射,原来无条目的字号保留其 PK 路径,后来读取的新字号 +可使用新 Type1 条目。出页记录绑定,最终 PDF 与 SVG 根据其中的真实 +映射、字体文件和编码出图。检查点记录映射命中、版本及缺失查找。 +格式升为 schema55,加载旧格式时补入新增命令。任务映射每次启动时重建。 +[pdfTeX 映射指令与默认表的执行顺序](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/mapfile.c#L748-L811) + +保留冻结的原失败用例。十个 pdfTeX 定向对照通过,七个成功作业的 +词框及 600 dpi 像素一致。混合输出前三页实际引用 Type3、Type3 和 +Type1。其余三例在出页时按参考拒绝自动伸缩位图。14 项 PK、VF 与 +格式专项及一项 PDF 间词空格出页回归通过。用原有 schema54 和新 schema55 +分别加载并执行映射, +均能出页。对照回执为 target/p3-dynamic-font-map/receipt.json, +SHA-256 6a4988e7664aede8a3d96bd6e4014385a3557cde2c36573215d15065ffab2d31。 + +三页增量工程在第二页前执行 \pdfmapfile。同一映射文件改为位图后, +第二页出页失败,保留上一版 PDF。恢复映射并修改第二页正文后复用 +1339 步,只替换第二页。PDF、SVG、来源映射与独立全量一致。 +增量回执为 target/p3-dynamic-font-map/incremental-receipt.json, +SHA-256 0c0787c6087ffe6deb2ef0e0bf058dbfb3a1625918e9cd75ecddeae78f19d061。 + +下一处差异为 Type1 绘制中的 SlantFont 和 ExtendFont。用发行版原始 +Times 映射 ptmro8r 与 ptmr8rn 及其实际 TFM、PFB、编码冻结了两例。 +pdfTeX 均成功出页,原生报告具体变换缺口。 +回执为 target/p3-dynamic-font-map/next-transform-receipt.json, +SHA-256 43653db3aa5765408347e6af2d45878a4bfe44edf2a4a7f0babf7df4dd95c23a。 + ### 原生段落边缘悬挂 `\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平 diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 01ecd85..d31e001 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -131,6 +131,13 @@ impl SourceProvider for RecordingHost<'_> { .map_err(Clone::clone) }) } + fn optional_font_map(&mut self, name: &str, from: &str) -> Result, String> { + let (name, from) = (name.to_owned(), from.to_owned()); + call!(self, optional_font_map(&name, &from); |result| { + result.as_ref().map(|resource| resource.as_ref().map(|item| item.version.clone())) + .map_err(Clone::clone) + }) + } fn optional_tex_input( &mut self, name: &str, diff --git a/src/native_job.rs b/src/native_job.rs index 34c5895..24f5d4c 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -1553,6 +1553,14 @@ impl SourceProvider for Files { } Ok(resource) } + fn optional_font_map(&mut self, name: &str, from: &str) -> Result, String> { + let kind = ResourceKind::Map; + let resource = self.world.read_optional(kind, name, Path::new(from))?; + if let Some(resource) = &resource { + self.observe_resource(kind, resource); + } + Ok(resource) + } fn optional_tex_input( &mut self, name: &str,