diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index ed23ca1..c867a61 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -14,6 +14,7 @@ use std::{ }; mod cff; mod map; +mod sfd; mod truetype; mod virtual_paint; pub use cff::OpenTypeCffProgram; @@ -41,7 +42,7 @@ pub struct NativeFontPaint { } struct MappedOutline { - data: Vec, + data: Arc<[u8]>, encoding: Option>, resources: Vec, program_index: usize, @@ -434,6 +435,8 @@ fn resolve_physical_fonts( .or_else(|| default_map.as_ref().map(|map| &map.version)); let mut resolved = BTreeMap::new(); let mut direct_resolved = BTreeMap::new(); + let mut subfonts = sfd::Files::default(); + let mut outlines = map::OutlineFiles::default(); let device = pages.iter().find_map(|page| page.pdf.as_ref()); let xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv); let device = device.map(|pdf| pdf.file.clone()); @@ -444,7 +447,7 @@ fn resolve_physical_fonts( } 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) + find_map_entry(map, &font.name, files, &mut subfonts)?.map(Arc::new) } else { None }; @@ -519,12 +522,12 @@ fn resolve_physical_fonts( continue; }; if let Some(file) = outline.true_type_file() { - let paint = truetype::resolve(files, outline, file, &font, slots)?; + let paint = truetype::resolve(files, &mut outlines, outline, file, &font, slots)?; direct_resolved.insert(id, Arc::new(paint)); continue; } if let Some(file) = outline.open_type_file() { - let paint = cff::resolve(files, outline, file, &font, slots)?; + let paint = cff::resolve(files, &mut outlines, outline, file, &font, slots)?; direct_resolved.insert(id, Arc::new(paint)); continue; } diff --git a/crates/texrra-tex-core/src/native_font/cff.rs b/crates/texrra-tex-core/src/native_font/cff.rs index a5049f3..515debe 100644 --- a/crates/texrra-tex-core/src/native_font/cff.rs +++ b/crates/texrra-tex-core/src/native_font/cff.rs @@ -1,5 +1,8 @@ //! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face. -use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry}; +use super::{ + MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, + map::{MapEntry, OutlineFiles}, +}; use crate::{execution::SourceProvider, resources::ResourceKind}; use read_fonts::ps::cff::CffFontRef; use rustybuzz::ttf_parser::{Face, GlyphId, Tag}; @@ -20,6 +23,7 @@ impl OpenTypeCffProgram { pub(super) fn resolve( files: &mut impl SourceProvider, + outlines: &mut OutlineFiles, outline: &MapEntry, file: &str, font: &NativeFont, @@ -33,7 +37,7 @@ pub(super) fn resolve( encoding, resources, program_index, - } = outline.read_outline(files, ResourceKind::OpenType, file)?; + } = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?; let face = Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?; let table = face @@ -89,7 +93,7 @@ pub(super) fn resolve( .map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em())); let program = OpenTypeCffProgram { name: outline.postscript_name().unwrap_or(&font.name).to_owned(), - data: data.into(), + data, }; Ok(NativeFontPaint { program: NativeFontProgram::OpenTypeCff(program), diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index ee9912c..166dfcc 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -1,5 +1,5 @@ //! PDF font map entries, lookup bindings, and the lifetime of the default map. -use super::{MappedOutline, MappedType1, NativeFont, actual_resource, encoding_vector, verify_resource}; +use super::{MappedOutline, MappedType1, NativeFont, actual_resource, encoding_vector, sfd, verify_resource}; use crate::{ execution::{FontId, SourceProvider}, resources::{LoadedResource, ResourceKind, ResourceVersion}, @@ -19,6 +19,10 @@ pub(super) struct MapEntry { #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub(super) subset: bool, pub encoding: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) subfont: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cmap: Option<[u16; 2]>, postscript_name: bool, #[serde(default, skip_serializing_if = "Option::is_none")] ps_name: Option, @@ -29,6 +33,30 @@ pub(super) struct MapEntry { } type PostscriptKey = (String, i32, i32); +type OutlineKey = (ResourceKind, PathBuf, String); + +/// Share the inspected bytes of a physical outline within an output pass. +#[derive(Default)] +pub(super) struct OutlineFiles(BTreeMap)>); + +impl OutlineFiles { + fn read( + &mut self, + files: &mut impl SourceProvider, + kind: ResourceKind, + file: &str, + from: &Path, + ) -> Result<(ResourceVersion, Arc<[u8]>), String> { + let key = (kind, from.to_owned(), file.to_owned()); + if let Some(found) = self.0.get(&key) { + return Ok(found.clone()); + } + let loaded = actual_resource(files, kind, file, &from.to_string_lossy())?; + let value = (loaded.version, Arc::from(loaded.data)); + self.0.insert(key, value.clone()); + Ok(value) + } +} impl MapEntry { fn postscript_key(&self) -> Option { @@ -60,14 +88,18 @@ impl MapEntry { pub(super) fn read_outline( &self, files: &mut impl SourceProvider, + outlines: &mut OutlineFiles, kind: ResourceKind, file: &str, ) -> Result { let from = self.from.to_string_lossy(); - let program = actual_resource(files, kind, file, &from)?; + let (program, data) = outlines.read(files, kind, file, &self.from)?; let mut resources: Vec<_> = self.version.iter().cloned().collect(); + if let Some(subfont) = &self.subfont { + resources.push(subfont.version.as_ref().clone()); + } let program_index = resources.len(); - resources.push(program.version); + resources.push(program); let encoding = if let Some(name) = &self.encoding { let file = actual_resource(files, ResourceKind::Encoding, name, &from)?; let names = encoding_vector(&file.data)?; @@ -76,7 +108,20 @@ impl MapEntry { } else { None }; - Ok(MappedOutline { data: program.data, encoding, resources, program_index }) + Ok(MappedOutline { data, encoding, resources, program_index }) + } + + fn for_subfont(mut self, definition: &sfd::Definition, codes: &sfd::Codes) -> Self { + self.ps_name = None; + self.postscript_name = false; + self.descriptor_flags = None; + self.encoding = None; + self.subfont = Some(sfd::Subfont { + version: definition.version.clone(), + codes: codes.clone(), + cmap: self.cmap.unwrap_or([3, 1]), + }); + self } pub(super) fn postscript_name(&self) -> Option<&str> { @@ -140,12 +185,15 @@ fn parse_map_line( file: None, subset: false, encoding: None, + subfont: None, + cmap: None, postscript_name: false, ps_name: None, descriptor_flags: None, transform: Type1Transform::default(), }; - for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() { + let mut fields = fields.into_iter().skip(1).enumerate(); + while let Some((index, (quote, value))) = fields.next() { if quote { let mut previous = ""; for word in value.split_ascii_whitespace() { @@ -166,6 +214,22 @@ fn parse_map_line( } previous = word; } + } else if let Some(spec) = value.strip_prefix("PidEid=") { + let (platform, encoding) = spec.split_once(',') + .ok_or_else(|| format!("invalid PidEid for {name}"))?; + let continuation; + let encoding = if encoding.is_empty() { + continuation = fields.next().and_then(|(_, (quote, value))| (!quote).then_some(value)) + .ok_or_else(|| format!("invalid PidEid for {name}"))?; + &continuation + } else { + encoding + }; + let parse = |value| sfd::integer(value).and_then(|value| u16::try_from(value).ok()); + entry.cmap = Some([ + parse(platform).ok_or_else(|| format!("invalid PidEid for {name}"))?, + parse(encoding).ok_or_else(|| format!("invalid PidEid for {name}"))?, + ]); } else if value.starts_with('<') { let path = value.trim_start_matches('<').trim_start_matches('['); if path.ends_with(".enc") { @@ -202,6 +266,11 @@ fn parse_map_line( "SlantFont/ExtendFont require an embedded Type1 program for {name}" )); } + if entry.cmap.is_some() + && (entry.true_type_file().is_none() || !entry.subset || entry.encoding.is_some()) + { + return Err(format!("PidEid requires a subsetted non-reencoded TrueType font: {name}")); + } Ok(Some((name, entry))) } @@ -237,6 +306,7 @@ pub(super) struct JobFontMap { pending_fonts: Vec<(FontId, String)>, pending_ids: BTreeSet, entries: Arc>>, + subfonts: sfd::Files, used_names: BTreeSet, // PDF inclusion addresses the PostScript name independently of the TFM. postscript_entries: Arc)>>, @@ -310,7 +380,7 @@ impl JobFontMap { 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)?; + self.apply_file(&read, MapMode::Add, true, &mut ignored, files)?; bindings.default_map = Some(read.version); } } @@ -384,13 +454,13 @@ impl JobFontMap { }; match load_map(files, &name, from)? { Some(read) => { - self.apply_file(&read, mode, suppress_duplicates, &mut warnings)? + self.apply_file(&read, mode, suppress_duplicates, &mut warnings, files)? } None => warnings.push(format!("cannot open font map file {name}")), } } } else { - self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings); + self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings, files)?; } Ok(warnings) } @@ -401,6 +471,7 @@ impl JobFontMap { mode: MapMode, suppress_duplicates: bool, warnings: &mut Vec, + files: &mut impl SourceProvider, ) -> Result<(), String> { let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?; for line in text.lines() { @@ -411,7 +482,8 @@ impl JobFontMap { mode, suppress_duplicates, warnings, - ); + files, + )?; } Ok(()) } @@ -424,15 +496,39 @@ impl JobFontMap { mode: MapMode, suppress_duplicates: bool, warnings: &mut Vec, - ) { + files: &mut impl SourceProvider, + ) -> Result<(), String> { let (name, entry) = match parse_map_line(line, from, version) { Ok(Some(entry)) => entry, - Ok(None) => return, + Ok(None) => return Ok(()), Err(error) => { warnings.push(error); - return; + return Ok(()); } }; + if let Some((prefix, file)) = sfd::template(&name) { + let definition = format!("{file}.sfd"); + if let Some(definition) = self.subfonts.get(files, &definition, &entry.from)? { + for (suffix, codes) in &definition.subfonts { + let subfont = entry.clone().for_subfont(&definition, codes); + self.apply_entry(format!("{prefix}{suffix}"), subfont, mode, suppress_duplicates, warnings); + } + return Ok(()); + } + warnings.push(format!("cannot open SFD file {definition} for reading")); + } + self.apply_entry(name, entry, mode, suppress_duplicates, warnings); + Ok(()) + } + + fn apply_entry( + &mut self, + name: String, + entry: MapEntry, + mode: MapMode, + suppress_duplicates: bool, + warnings: &mut Vec, + ) { if self.entries.contains_key(&name) { if mode == MapMode::Add { if !suppress_duplicates { @@ -503,15 +599,28 @@ pub(super) fn load_map( .transpose() } -pub(super) fn find_map_entry(map: &LoadedResource, name: &str) -> Result, String> { +pub(super) fn find_map_entry( + map: &LoadedResource, + name: &str, + files: &mut impl SourceProvider, + definitions: &mut sfd::Files, +) -> 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)) + for line in text.lines() { + let Some(candidate) = line.split_ascii_whitespace().next() else { continue }; + if candidate == name { + return Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry)); + } + if let Some((prefix, file)) = sfd::template(candidate) + && let Some(suffix) = name.strip_prefix(prefix) + && let Some((_, entry)) = parse_map_line(line, &map.version.path, Some(&map.version))? + && let Some(definition) = definitions.get(files, &format!("{file}.sfd"), &entry.from)? + && let Some((_, codes)) = definition.subfonts.iter().find(|(infix, _)| infix == suffix) + { + return Ok(Some(entry.for_subfont(&definition, codes))); + } + } + Ok(None) } pub(super) fn selected_outline<'a>( @@ -532,6 +641,8 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry { version: None, file: Some("pdftexspace.pfb".into()), encoding: None, + subfont: None, + cmap: None, postscript_name: false, ps_name: None, descriptor_flags: None, diff --git a/crates/texrra-tex-core/src/native_font/sfd.rs b/crates/texrra-tex-core/src/native_font/sfd.rs new file mode 100644 index 0000000..6e3184e --- /dev/null +++ b/crates/texrra-tex-core/src/native_font/sfd.rs @@ -0,0 +1,158 @@ +//! Subfont definition files bind 8-bit TeX slots to a TrueType cmap. +use crate::{ + execution::SourceProvider, + resources::{ResourceKind, ResourceVersion}, +}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + sync::Arc, +}; + +pub(super) type Codes = Arc<[Option]>; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(super) struct Subfont { + pub(super) version: Arc, + pub(super) codes: Codes, + pub(super) cmap: [u16; 2], +} + +pub(super) struct Definition { + pub(super) version: Arc, + pub(super) subfonts: Vec<(String, Codes)>, +} + +#[derive(Clone, Default)] +pub(super) struct Files(BTreeMap<(PathBuf, String), Arc>); + +impl Files { + pub(super) fn get( + &mut self, + files: &mut impl SourceProvider, + name: &str, + from: &Path, + ) -> Result>, String> { + let key = (from.to_owned(), name.to_owned()); + if let Some(result) = self.0.get(&key) { + return Ok(Some(result.clone())); + } + let result = files + .optional_font_file(ResourceKind::Sfd, name, &from.to_string_lossy())? + .map(|resource| { + let resource = super::verify_resource(resource, ResourceKind::Sfd, name)?; + let subfonts = parse(&resource.data).map_err(|error| { + format!( + "invalid SFD file {}: {error}", + resource.version.path.display() + ) + })?; + Ok::<_, String>(Arc::new(Definition { + version: Arc::new(resource.version), + subfonts, + })) + }) + .transpose()?; + if let Some(definition) = &result { + self.0.insert(key, definition.clone()); + } + Ok(result) + } +} + +/// The pdfTeX map spelling is prefix@definition@, with an implicit .sfd. +pub(super) fn template(name: &str) -> Option<(&str, &str)> { + let (prefix, file) = name.strip_suffix('@')?.split_once('@')?; + (!prefix.is_empty() && !file.is_empty() && !file.contains('@')).then_some((prefix, file)) +} + +fn parse(data: &[u8]) -> Result, String> { + let text = std::str::from_utf8(data).map_err(|_| "expected UTF-8/ASCII")?; + let mut lines = text + .lines() + .enumerate() + .map(|(index, line)| (index + 1, line.trim())) + .filter(|(_, line)| !line.is_empty() && !line.starts_with('#')); + let mut result = Vec::new(); + while let Some((line, start)) = lines.next() { + let mut row = start.to_owned(); + while row.ends_with('\\') { + row.pop(); + let (_, continuation) = lines + .next() + .ok_or_else(|| format!("line {line}: unterminated continuation"))?; + row.push(' '); + row.push_str(continuation); + } + let (name, input) = row.split_once(char::is_whitespace).unwrap_or((&row, "")); + let codes = parse_codes(input).map_err(|error| format!("line {line}: {error}"))?; + result.push((name.to_owned(), codes)); + } + // pdfTeX registers subfonts in reverse file order. + result.reverse(); + Ok(result) +} + +fn parse_codes(mut input: &str) -> Result { + let mut codes = [None; 256]; + let mut offset = 0; + while !input.trim().is_empty() { + let start = number(&mut input)?; + if let Some(rest) = input.strip_prefix(':') { + offset = usize::try_from(start) + .ok() + .filter(|&slot| slot < codes.len()) + .ok_or("invalid subfont slot offset")?; + input = rest; + continue; + } + let end = if let Some(rest) = input.strip_prefix('_') { + input = rest; + number(&mut input)? + } else { + start + }; + if start < -1 || end < start || end > i64::from(u16::MAX) { + return Err("invalid subfont character range".into()); + } + let count = (end - start + 1) as usize; + let range = codes + .get_mut(offset..offset + count) + .ok_or("subfont slots exceed 255")?; + for (code, value) in range.iter_mut().zip(start..=end) { + *code = u16::try_from(value).ok(); + } + offset += count; + } + Ok(codes.into()) +} + +pub(super) fn integer(token: &str) -> Option { + let (negative, digits) = if let Some(rest) = token.strip_prefix('-') { + (true, rest) + } else { + (false, token.strip_prefix('+').unwrap_or(token)) + }; + let (radix, digits) = if let Some(hex) = digits + .strip_prefix("0x") + .or_else(|| digits.strip_prefix("0X")) + { + (16, hex) + } else if digits.starts_with('0') { + (8, digits) + } else { + (10, digits) + }; + let value = i64::from_str_radix(digits, radix).ok()?; + Some(if negative { -value } else { value }) +} + +fn number(input: &mut &str) -> Result { + let text = input.trim_start(); + let end = text + .find(|character: char| character.is_whitespace() || matches!(character, ':' | '_')) + .unwrap_or(text.len()); + let (token, rest) = text.split_at(end); + *input = rest.trim_start(); + integer(token).ok_or_else(|| format!("invalid subfont number {token:?}")) +} diff --git a/crates/texrra-tex-core/src/native_font/truetype.rs b/crates/texrra-tex-core/src/native_font/truetype.rs index 1acc5fd..5458a57 100644 --- a/crates/texrra-tex-core/src/native_font/truetype.rs +++ b/crates/texrra-tex-core/src/native_font/truetype.rs @@ -1,5 +1,8 @@ //! The PDF map binds TeX slots to a real TrueType face, independent of the TFM. -use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry}; +use super::{ + MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, + map::{MapEntry, OutlineFiles}, +}; use crate::{execution::SourceProvider, resources::ResourceKind}; use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id}; use std::{ @@ -14,6 +17,10 @@ pub struct TrueTypeProgram { data: Arc<[u8]>, glyphs: Vec, pub(crate) reencoded: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) subfont_codes: Option]>>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) missing_subfont_cmap: Option<[u16; 2]>, } impl TrueTypeProgram { @@ -53,6 +60,16 @@ impl TrueTypeProgram { .map_err(|error| error.to_string())? .number_of_glyphs(); tables.insert(tag(b"cmap"), slot_cmap(&mapping, glyph_count)); + if self.subfont_codes.is_some() + && let Some(post) = tables.get_mut(&tag(b"post")) + { + // A numeric subfont leaves extraction to the PDF encoding. + if post.len() < 32 { + return Err("invalid TrueType post table".into()); + } + post.truncate(32); + post[..4].copy_from_slice(&0x0003_0000u32.to_be_bytes()); + } if let Some(os2) = original.raw_face().table(tag(b"OS/2")) { tables.insert(tag(b"OS/2"), symbol_os2(os2)?); } @@ -65,6 +82,7 @@ impl TrueTypeProgram { pub(super) fn resolve( files: &mut impl SourceProvider, + outlines: &mut OutlineFiles, outline: &MapEntry, file: &str, font: &NativeFont, @@ -75,13 +93,20 @@ pub(super) fn resolve( encoding, resources, program_index, - } = outline.read_outline(files, ResourceKind::TrueType, file)?; + } = outline.read_outline(files, outlines, ResourceKind::TrueType, file)?; let face = Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?; if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 { return Err(format!("invalid TrueType outline tables in {file}")); } - if outline.subset && encoding.is_none() { + let subfont = outline.subfont.as_ref().filter(|_| outline.subset); + let subfont_cmap = + subfont.and_then(|subfont| { + face.tables().cmap?.subtables.into_iter().find(|table| { + [platform_number(table.platform_id), table.encoding_id] == subfont.cmap + }) + }); + if outline.subset && encoding.is_none() && subfont.is_none() { return Err(format!( "subset TrueType font {} needs a reencoding", font.name @@ -89,7 +114,16 @@ pub(super) fn resolve( } let reencoded = encoding.is_some(); - let glyphs = if outline.subset { + let glyphs = if let Some(subfont) = subfont { + subfont + .codes + .iter() + .map(|&code| { + code.and_then(|code| subfont_cmap?.glyph_index(u32::from(code))) + .map_or(0, |glyph| glyph.0) + }) + .collect() + } else if outline.subset { let encoding = encoding.as_ref().unwrap(); encoding .iter() @@ -108,9 +142,19 @@ pub(super) fn resolve( if let Some(name) = face.glyph_name(GlyphId(glyph)) { return name.to_owned(); } - let character = win_ansi(slot as u8); - if glyph != 0 && face.glyph_index(character) == Some(GlyphId(glyph)) { - format!("uni{:04X}", u32::from(character)) + let unicode = if let Some(subfont) = subfont { + subfont.codes[slot] + .filter(|_| subfont_cmap.is_some_and(|table| table.is_unicode())) + .map(u32::from) + } else { + let character = win_ansi(slot as u8); + (face.glyph_index(character) == Some(GlyphId(glyph))) + .then_some(u32::from(character)) + }; + if let Some(code) = + unicode.filter(|&code| glyph != 0 && char::from_u32(code).is_some()) + { + format!("uni{code:04X}") } else { ".notdef".to_owned() } @@ -139,11 +183,16 @@ pub(super) fn resolve( let bbox = face.global_bounding_box(); let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] .map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em())); + let missing_subfont_cmap = subfont + .filter(|_| subfont_cmap.is_none()) + .map(|subfont| subfont.cmap); let program = TrueTypeProgram { name, - data: data.into(), + data, glyphs, reencoded, + subfont_codes: subfont.map(|subfont| subfont.codes.clone()), + missing_subfont_cmap, }; Ok(NativeFontPaint { program: NativeFontProgram::TrueType(program), @@ -159,6 +208,16 @@ pub(super) fn resolve( }) } +fn platform_number(platform: PlatformId) -> u16 { + match platform { + PlatformId::Unicode => 0, + PlatformId::Macintosh => 1, + PlatformId::Iso => 2, + PlatformId::Windows => 3, + PlatformId::Custom => 4, + } +} + fn builtin_glyph(face: &Face<'_>, slot: u8) -> GlyphId { let code = u32::from(slot); if let Some(cmap) = face.tables().cmap { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 6d9165d..1cf84df 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1851,6 +1851,14 @@ fn write_native_font( ("Type1", descriptor, name, format!("[{widths}]"), encoding, true) } NativeFontProgram::TrueType(program) => { + if let Some(codes) = &program.subfont_codes { + for &slot in used.keys().filter(|&&slot| codes[usize::from(slot)].is_none()) { + diagnostics.push(format!("character {slot} in subfont {} is not mapped to any charcode", face.name)); + } + } + if let Some([platform, encoding]) = program.missing_subfont_cmap { + diagnostics.push(format!("cannot find cmap subtable for (pid,eid) = ({platform}, {encoding})")); + } let width_object = objects.len() + 1; objects.push(format!("[{widths}]").into_bytes()); let (descriptor, name) = truetype_fonts::write( diff --git a/crates/texrra-tex-core/src/pdf/truetype_fonts.rs b/crates/texrra-tex-core/src/pdf/truetype_fonts.rs index debb0b4..ae213ee 100644 --- a/crates/texrra-tex-core/src/pdf/truetype_fonts.rs +++ b/crates/texrra-tex-core/src/pdf/truetype_fonts.rs @@ -17,17 +17,25 @@ pub(super) fn write( ) -> Result<(usize, String), String> { let mut slots: BTreeSet<_> = used.collect(); let name = if paint.subset { - let names = slots - .iter() - .map(|&slot| &paint.encoding[usize::from(slot)]) - .filter(|name| *name != ".notdef") - .cloned() - .collect(); + let names = if let Some(codes) = &program.subfont_codes { + slots + .iter() + .filter_map(|&slot| codes[usize::from(slot)]) + .map(|code| format!("/c{code:04X}")) + .collect() + } else { + slots + .iter() + .map(|&slot| &paint.encoding[usize::from(slot)]) + .filter(|name| *name != ".notdef") + .cloned() + .collect() + }; let tag = (0..100) .map(|salt| subset_tag(&program.name, &names, salt)) .find(|tag| subset_tags.insert(tag.clone())) .ok_or("TrueType subset name collision limit exceeded")?; - if paint.encoding[97] == "a" { + if program.subfont_codes.is_none() && paint.encoding[97] == "a" { // Match pdfTeX's additional glyph for older PDF readers. slots.insert(b'a'); } diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index 4ec61d8..e1a8cd2 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -34,6 +34,7 @@ pub enum ResourceKind { Config, FontMapping, PdfImage, + Sfd, } impl ResourceKind { fn directory(self) -> &'static str { @@ -49,6 +50,7 @@ impl ResourceKind { Self::Map => "fonts/map", Self::Format | Self::Config => "web2c", Self::FontMapping => "fonts/misc", + Self::Sfd => "fonts/sfd", } } fn environment(self) -> &'static str { @@ -65,6 +67,7 @@ impl ResourceKind { Self::Format => "TEXFORMATS", Self::Config => "TEXMFCNF", Self::FontMapping => "MISCFONTS", + Self::Sfd => "SFDFONTS", } } fn extensions(self) -> &'static [&'static str] { @@ -81,9 +84,10 @@ impl ResourceKind { Self::Format => &["fmt"], Self::Config => &["cnf"], Self::FontMapping => &["tec"], + Self::Sfd => &["sfd"], } } - const ALL: [Self; 12] = [ + const ALL: [Self; 13] = [ Self::Tex, Self::Tfm, Self::Vf, @@ -96,6 +100,7 @@ impl ResourceKind { Self::Format, Self::Config, Self::FontMapping, + Self::Sfd, ]; } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 630d503..de99b49 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,34 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### pdfTeX 的 TrueType SFD 子字体 + +字体映射读取实际 SFD,按定义展开子字体条目。偏移、字符范围及 +续行进入各自的 TeX 槽位表。映射命令沿用普通条目的增加、替换、 +删除及使用后锁定语义。SFD 通过 SFDFONTS 及项目资源命名空间 +解析,文件版本随字体绑定记录。相同映射来源使用的实际字体字节 +在一次输出解析中共享。 +[原版 SFD 读取及子字体注册](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/subfont.c#L93-L215) + +子集以实际 cmap 的 PidEid 定位字形,按子字体字符码生成子集名, +并为 TeX 槽位写出嵌入字体的 cmap。整嵌保留原始 cmap。九组 +原版成功输出覆盖两个子字体、显式 PidEid、映射命令、缺失槽位、 +缺失 cmap 及系统 Microsoft YaHei TTC 第一张字体的整嵌和子集。 +每组 144 DPI 灰度、词框、文字、字符宽度及字体描述符一致。 +PDF 对象编号与部分子集的二进制表仍有差异。缺失 SFD 和完整 +删除命令均报告无法取得 cjk00 的位图后退出。 +[原版子集字符码与命名](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writettf.c#L263-L286) + +四项定向回归通过。双子字体对照的实际字体查找和读取从两次减 +为一次。三页编辑会话中,SFD 修改重新执行。正文修改及恢复 SFD +各复用 103 步。三次只更新第 2 页,PDF、测量页面、完整 SVG、 +来源映射及 aux 与独立全量一致。缺失文件时保留旧预览和 aux。 + +证据在 target/p3-truetype-sfd。receipt.json 的 SHA-256 为 +bb2b459cd20d38cc1ed35058a52b4b6d81ef92688ed16abd3bb3c653a8acfdb3。 +下一入口是传统 Type 1 的 PFA 字体程序。next-pfa 保存真实 CMR10 +的 PFA 表示、原版子集 PDF 及当前候选的格式不支持诊断。 + ### pdfTeX 映射的 OpenType CFF 字体 传统字体映射读取实际 OpenType、TFM 和可选编码文件。TeX 槽位 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index be2e44a..0d7f032 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1957,6 +1957,60 @@ fn mapped_opentype_cff_paints_reencoded_glyphs_and_embeds_the_original_table() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn mapped_truetype_sfd_selects_cmap_glyphs_and_tracks_the_definition() { + use texrra_tex_core::render::DisplayItem; + + let root = directory("mapped-truetype-sfd").canonicalize().unwrap(); + let sfd = root.join("glyphs.sfd"); + let font = include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf"); + let metrics = include_bytes!("../crates/texrra-tex-core/assets/cmr10.tfm"); + fs::write(root.join("face.ttf"), font).unwrap(); + fs::write(root.join("route00.tfm"), metrics).unwrap(); + fs::write(root.join("pdftex.map"), b"% no default entry\n").unwrap(); + fs::write(&sfd, b"# one subfont\n00 0x41: 0x56_0x57 \\\n 0x58\n").unwrap(); + fs::write( + root.join("main.tex"), + br"\catcode123=1 \catcode125=2 \pdfoutput=1 +\pdfmapline{+route@glyphs@ LiberationSerif PidEid=3, 1 { + assert!(!paint.glyph_paths[slot].is_empty()); + Some(*character) + } + _ => None, + } + }).collect(); + assert_eq!(glyphs, "VWX"); + assert!( + first.resources.trace.reads.contains(&file_version(&sfd).unwrap().unwrap()) + ); + + fs::write(&sfd, b"00 255: 0x41_0x42\n").unwrap(); + let error = compiler.compile_detailed(job).err().unwrap().error.to_string(); + assert!(error.contains("glyphs.sfd") && error.contains("subfont slots exceed 255"), "{error}"); + assert!(Arc::ptr_eq(&first, &compiler.latest().unwrap())); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn mapped_truetype_paints_and_embeds_the_actual_font() { use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};