Resolve pdfTeX SFD subfonts against actual TrueType cmaps

This commit is contained in:
gloamxun committed 2026-11-28 03:04:48 +08:00
1 parent fd5ab59f42
commit 868814288c
10 files changed
+481 -43

No files matched your search

+7 -4
View File
@@ -14,6 +14,7 @@ use std::{
}; };
mod cff; mod cff;
mod map; mod map;
mod sfd;
mod truetype; mod truetype;
mod virtual_paint; mod virtual_paint;
pub use cff::OpenTypeCffProgram; pub use cff::OpenTypeCffProgram;
@@ -41,7 +42,7 @@ pub struct NativeFontPaint {
} }
struct MappedOutline { struct MappedOutline {
data: Vec<u8>, data: Arc<[u8]>,
encoding: Option<Vec<String>>, encoding: Option<Vec<String>>,
resources: Vec<ResourceVersion>, resources: Vec<ResourceVersion>,
program_index: usize, program_index: usize,
@@ -434,6 +435,8 @@ fn resolve_physical_fonts(
.or_else(|| default_map.as_ref().map(|map| &map.version)); .or_else(|| default_map.as_ref().map(|map| &map.version));
let mut resolved = BTreeMap::new(); let mut resolved = BTreeMap::new();
let mut direct_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 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 xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv);
let device = device.map(|pdf| pdf.file.clone()); let device = device.map(|pdf| pdf.file.clone());
@@ -444,7 +447,7 @@ fn resolve_physical_fonts(
} else if let Some(bindings) = captured { } else if let Some(bindings) = captured {
bindings.font(&font)? bindings.font(&font)?
} else if let Some(map) = &default_map { } 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 { } else {
None None
}; };
@@ -519,12 +522,12 @@ fn resolve_physical_fonts(
continue; continue;
}; };
if let Some(file) = outline.true_type_file() { 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)); direct_resolved.insert(id, Arc::new(paint));
continue; continue;
} }
if let Some(file) = outline.open_type_file() { 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)); direct_resolved.insert(id, Arc::new(paint));
continue; continue;
} }
@@ -1,5 +1,8 @@
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face. //! 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 crate::{execution::SourceProvider, resources::ResourceKind};
use read_fonts::ps::cff::CffFontRef; use read_fonts::ps::cff::CffFontRef;
use rustybuzz::ttf_parser::{Face, GlyphId, Tag}; use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
@@ -20,6 +23,7 @@ impl OpenTypeCffProgram {
pub(super) fn resolve( pub(super) fn resolve(
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
outlines: &mut OutlineFiles,
outline: &MapEntry, outline: &MapEntry,
file: &str, file: &str,
font: &NativeFont, font: &NativeFont,
@@ -33,7 +37,7 @@ pub(super) fn resolve(
encoding, encoding,
resources, resources,
program_index, program_index,
} = outline.read_outline(files, ResourceKind::OpenType, file)?; } = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
let face = let face =
Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?; Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
let table = face let table = face
@@ -89,7 +93,7 @@ pub(super) fn resolve(
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em())); .map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
let program = OpenTypeCffProgram { let program = OpenTypeCffProgram {
name: outline.postscript_name().unwrap_or(&font.name).to_owned(), name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
data: data.into(), data,
}; };
Ok(NativeFontPaint { Ok(NativeFontPaint {
program: NativeFontProgram::OpenTypeCff(program), program: NativeFontProgram::OpenTypeCff(program),
+131 -20
View File
@@ -1,5 +1,5 @@
//! PDF font map entries, lookup bindings, and the lifetime of the default map. //! 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::{ use crate::{
execution::{FontId, SourceProvider}, execution::{FontId, SourceProvider},
resources::{LoadedResource, ResourceKind, ResourceVersion}, resources::{LoadedResource, ResourceKind, ResourceVersion},
@@ -19,6 +19,10 @@ pub(super) struct MapEntry {
#[serde(default, skip_serializing_if = "std::ops::Not::not")] #[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub(super) subset: bool, pub(super) subset: bool,
pub encoding: Option<String>, pub encoding: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) subfont: Option<sfd::Subfont>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cmap: Option<[u16; 2]>,
postscript_name: bool, postscript_name: bool,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
ps_name: Option<String>, ps_name: Option<String>,
@@ -29,6 +33,30 @@ pub(super) struct MapEntry {
} }
type PostscriptKey = (String, i32, i32); 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<OutlineKey, (ResourceVersion, Arc<[u8]>)>);
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 { impl MapEntry {
fn postscript_key(&self) -> Option<PostscriptKey> { fn postscript_key(&self) -> Option<PostscriptKey> {
@@ -60,14 +88,18 @@ impl MapEntry {
pub(super) fn read_outline( pub(super) fn read_outline(
&self, &self,
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
outlines: &mut OutlineFiles,
kind: ResourceKind, kind: ResourceKind,
file: &str, file: &str,
) -> Result<MappedOutline, String> { ) -> Result<MappedOutline, String> {
let from = self.from.to_string_lossy(); 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(); 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(); let program_index = resources.len();
resources.push(program.version); resources.push(program);
let encoding = if let Some(name) = &self.encoding { let encoding = if let Some(name) = &self.encoding {
let file = actual_resource(files, ResourceKind::Encoding, name, &from)?; let file = actual_resource(files, ResourceKind::Encoding, name, &from)?;
let names = encoding_vector(&file.data)?; let names = encoding_vector(&file.data)?;
@@ -76,7 +108,20 @@ impl MapEntry {
} else { } else {
None 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> { pub(super) fn postscript_name(&self) -> Option<&str> {
@@ -140,12 +185,15 @@ fn parse_map_line(
file: None, file: None,
subset: false, subset: false,
encoding: None, encoding: None,
subfont: None,
cmap: None,
postscript_name: false, postscript_name: false,
ps_name: None, ps_name: None,
descriptor_flags: None, descriptor_flags: None,
transform: Type1Transform::default(), 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 { if quote {
let mut previous = ""; let mut previous = "";
for word in value.split_ascii_whitespace() { for word in value.split_ascii_whitespace() {
@@ -166,6 +214,22 @@ fn parse_map_line(
} }
previous = word; 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('<') { } else if value.starts_with('<') {
let path = value.trim_start_matches('<').trim_start_matches('['); let path = value.trim_start_matches('<').trim_start_matches('[');
if path.ends_with(".enc") { if path.ends_with(".enc") {
@@ -202,6 +266,11 @@ fn parse_map_line(
"SlantFont/ExtendFont require an embedded Type1 program for {name}" "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))) Ok(Some((name, entry)))
} }
@@ -237,6 +306,7 @@ pub(super) struct JobFontMap {
pending_fonts: Vec<(FontId, String)>, pending_fonts: Vec<(FontId, String)>,
pending_ids: BTreeSet<FontId>, pending_ids: BTreeSet<FontId>,
entries: Arc<BTreeMap<String, Arc<MapEntry>>>, entries: Arc<BTreeMap<String, Arc<MapEntry>>>,
subfonts: sfd::Files,
used_names: BTreeSet<String>, used_names: BTreeSet<String>,
// PDF inclusion addresses the PostScript name independently of the TFM. // PDF inclusion addresses the PostScript name independently of the TFM.
postscript_entries: Arc<BTreeMap<PostscriptKey, (String, Arc<MapEntry>)>>, postscript_entries: Arc<BTreeMap<PostscriptKey, (String, Arc<MapEntry>)>>,
@@ -310,7 +380,7 @@ impl JobFontMap {
let from = self.first_font_source.as_deref().unwrap_or(from); let from = self.first_font_source.as_deref().unwrap_or(from);
if let Some(read) = load_map(files, "pdftex.map", from)? { if let Some(read) = load_map(files, "pdftex.map", from)? {
let mut ignored = Vec::new(); 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); bindings.default_map = Some(read.version);
} }
} }
@@ -384,13 +454,13 @@ impl JobFontMap {
}; };
match load_map(files, &name, from)? { match load_map(files, &name, from)? {
Some(read) => { 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}")), None => warnings.push(format!("cannot open font map file {name}")),
} }
} }
} else { } 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) Ok(warnings)
} }
@@ -401,6 +471,7 @@ impl JobFontMap {
mode: MapMode, mode: MapMode,
suppress_duplicates: bool, suppress_duplicates: bool,
warnings: &mut Vec<String>, warnings: &mut Vec<String>,
files: &mut impl SourceProvider,
) -> Result<(), String> { ) -> Result<(), String> {
let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?; let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?;
for line in text.lines() { for line in text.lines() {
@@ -411,7 +482,8 @@ impl JobFontMap {
mode, mode,
suppress_duplicates, suppress_duplicates,
warnings, warnings,
); files,
)?;
} }
Ok(()) Ok(())
} }
@@ -424,15 +496,39 @@ impl JobFontMap {
mode: MapMode, mode: MapMode,
suppress_duplicates: bool, suppress_duplicates: bool,
warnings: &mut Vec<String>, warnings: &mut Vec<String>,
) { files: &mut impl SourceProvider,
) -> Result<(), String> {
let (name, entry) = match parse_map_line(line, from, version) { let (name, entry) = match parse_map_line(line, from, version) {
Ok(Some(entry)) => entry, Ok(Some(entry)) => entry,
Ok(None) => return, Ok(None) => return Ok(()),
Err(error) => { Err(error) => {
warnings.push(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<String>,
) {
if self.entries.contains_key(&name) { if self.entries.contains_key(&name) {
if mode == MapMode::Add { if mode == MapMode::Add {
if !suppress_duplicates { if !suppress_duplicates {
@@ -503,15 +599,28 @@ pub(super) fn load_map(
.transpose() .transpose()
} }
pub(super) fn find_map_entry(map: &LoadedResource, name: &str) -> Result<Option<MapEntry>, String> { pub(super) fn find_map_entry(
map: &LoadedResource,
name: &str,
files: &mut impl SourceProvider,
definitions: &mut sfd::Files,
) -> Result<Option<MapEntry>, String> {
let text = std::str::from_utf8(&map.data).map_err(|_| "font map is not UTF-8/ASCII")?; let text = std::str::from_utf8(&map.data).map_err(|_| "font map is not UTF-8/ASCII")?;
let Some(line) = text for line in text.lines() {
.lines() let Some(candidate) = line.split_ascii_whitespace().next() else { continue };
.find(|line| line.split_ascii_whitespace().next() == Some(name)) if candidate == name {
else { return Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry));
return Ok(None); }
}; if let Some((prefix, file)) = sfd::template(candidate)
Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry)) && 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>( pub(super) fn selected_outline<'a>(
@@ -532,6 +641,8 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
version: None, version: None,
file: Some("pdftexspace.pfb".into()), file: Some("pdftexspace.pfb".into()),
encoding: None, encoding: None,
subfont: None,
cmap: None,
postscript_name: false, postscript_name: false,
ps_name: None, ps_name: None,
descriptor_flags: None, descriptor_flags: None,
@@ -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<u16>]>;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) struct Subfont {
pub(super) version: Arc<ResourceVersion>,
pub(super) codes: Codes,
pub(super) cmap: [u16; 2],
}
pub(super) struct Definition {
pub(super) version: Arc<ResourceVersion>,
pub(super) subfonts: Vec<(String, Codes)>,
}
#[derive(Clone, Default)]
pub(super) struct Files(BTreeMap<(PathBuf, String), Arc<Definition>>);
impl Files {
pub(super) fn get(
&mut self,
files: &mut impl SourceProvider,
name: &str,
from: &Path,
) -> Result<Option<Arc<Definition>>, 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<Vec<(String, Codes)>, 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<Codes, String> {
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<i64> {
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<i64, String> {
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:?}"))
}
@@ -1,5 +1,8 @@
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM. //! 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 crate::{execution::SourceProvider, resources::ResourceKind};
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id}; use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
use std::{ use std::{
@@ -14,6 +17,10 @@ pub struct TrueTypeProgram {
data: Arc<[u8]>, data: Arc<[u8]>,
glyphs: Vec<u16>, glyphs: Vec<u16>,
pub(crate) reencoded: bool, pub(crate) reencoded: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) missing_subfont_cmap: Option<[u16; 2]>,
} }
impl TrueTypeProgram { impl TrueTypeProgram {
@@ -53,6 +60,16 @@ impl TrueTypeProgram {
.map_err(|error| error.to_string())? .map_err(|error| error.to_string())?
.number_of_glyphs(); .number_of_glyphs();
tables.insert(tag(b"cmap"), slot_cmap(&mapping, glyph_count)); 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")) { if let Some(os2) = original.raw_face().table(tag(b"OS/2")) {
tables.insert(tag(b"OS/2"), symbol_os2(os2)?); tables.insert(tag(b"OS/2"), symbol_os2(os2)?);
} }
@@ -65,6 +82,7 @@ impl TrueTypeProgram {
pub(super) fn resolve( pub(super) fn resolve(
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
outlines: &mut OutlineFiles,
outline: &MapEntry, outline: &MapEntry,
file: &str, file: &str,
font: &NativeFont, font: &NativeFont,
@@ -75,13 +93,20 @@ pub(super) fn resolve(
encoding, encoding,
resources, resources,
program_index, program_index,
} = outline.read_outline(files, ResourceKind::TrueType, file)?; } = outline.read_outline(files, outlines, ResourceKind::TrueType, file)?;
let face = let face =
Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?; Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 { if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
return Err(format!("invalid TrueType outline tables in {file}")); 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!( return Err(format!(
"subset TrueType font {} needs a reencoding", "subset TrueType font {} needs a reencoding",
font.name font.name
@@ -89,7 +114,16 @@ pub(super) fn resolve(
} }
let reencoded = encoding.is_some(); 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(); let encoding = encoding.as_ref().unwrap();
encoding encoding
.iter() .iter()
@@ -108,9 +142,19 @@ pub(super) fn resolve(
if let Some(name) = face.glyph_name(GlyphId(glyph)) { if let Some(name) = face.glyph_name(GlyphId(glyph)) {
return name.to_owned(); return name.to_owned();
} }
let character = win_ansi(slot as u8); let unicode = if let Some(subfont) = subfont {
if glyph != 0 && face.glyph_index(character) == Some(GlyphId(glyph)) { subfont.codes[slot]
format!("uni{:04X}", u32::from(character)) .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 { } else {
".notdef".to_owned() ".notdef".to_owned()
} }
@@ -139,11 +183,16 @@ pub(super) fn resolve(
let bbox = face.global_bounding_box(); let bbox = face.global_bounding_box();
let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] 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())); .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 { let program = TrueTypeProgram {
name, name,
data: data.into(), data,
glyphs, glyphs,
reencoded, reencoded,
subfont_codes: subfont.map(|subfont| subfont.codes.clone()),
missing_subfont_cmap,
}; };
Ok(NativeFontPaint { Ok(NativeFontPaint {
program: NativeFontProgram::TrueType(program), 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 { fn builtin_glyph(face: &Face<'_>, slot: u8) -> GlyphId {
let code = u32::from(slot); let code = u32::from(slot);
if let Some(cmap) = face.tables().cmap { if let Some(cmap) = face.tables().cmap {
+8
View File
@@ -1851,6 +1851,14 @@ fn write_native_font(
("Type1", descriptor, name, format!("[{widths}]"), encoding, true) ("Type1", descriptor, name, format!("[{widths}]"), encoding, true)
} }
NativeFontProgram::TrueType(program) => { 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; let width_object = objects.len() + 1;
objects.push(format!("[{widths}]").into_bytes()); objects.push(format!("[{widths}]").into_bytes());
let (descriptor, name) = truetype_fonts::write( let (descriptor, name) = truetype_fonts::write(
@@ -17,17 +17,25 @@ pub(super) fn write(
) -> Result<(usize, String), String> { ) -> Result<(usize, String), String> {
let mut slots: BTreeSet<_> = used.collect(); let mut slots: BTreeSet<_> = used.collect();
let name = if paint.subset { let name = if paint.subset {
let names = slots let names = if let Some(codes) = &program.subfont_codes {
.iter() slots
.map(|&slot| &paint.encoding[usize::from(slot)]) .iter()
.filter(|name| *name != ".notdef") .filter_map(|&slot| codes[usize::from(slot)])
.cloned() .map(|code| format!("/c{code:04X}"))
.collect(); .collect()
} else {
slots
.iter()
.map(|&slot| &paint.encoding[usize::from(slot)])
.filter(|name| *name != ".notdef")
.cloned()
.collect()
};
let tag = (0..100) let tag = (0..100)
.map(|salt| subset_tag(&program.name, &names, salt)) .map(|salt| subset_tag(&program.name, &names, salt))
.find(|tag| subset_tags.insert(tag.clone())) .find(|tag| subset_tags.insert(tag.clone()))
.ok_or("TrueType subset name collision limit exceeded")?; .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. // Match pdfTeX's additional glyph for older PDF readers.
slots.insert(b'a'); slots.insert(b'a');
} }
+6 -1
View File
@@ -34,6 +34,7 @@ pub enum ResourceKind {
Config, Config,
FontMapping, FontMapping,
PdfImage, PdfImage,
Sfd,
} }
impl ResourceKind { impl ResourceKind {
fn directory(self) -> &'static str { fn directory(self) -> &'static str {
@@ -49,6 +50,7 @@ impl ResourceKind {
Self::Map => "fonts/map", Self::Map => "fonts/map",
Self::Format | Self::Config => "web2c", Self::Format | Self::Config => "web2c",
Self::FontMapping => "fonts/misc", Self::FontMapping => "fonts/misc",
Self::Sfd => "fonts/sfd",
} }
} }
fn environment(self) -> &'static str { fn environment(self) -> &'static str {
@@ -65,6 +67,7 @@ impl ResourceKind {
Self::Format => "TEXFORMATS", Self::Format => "TEXFORMATS",
Self::Config => "TEXMFCNF", Self::Config => "TEXMFCNF",
Self::FontMapping => "MISCFONTS", Self::FontMapping => "MISCFONTS",
Self::Sfd => "SFDFONTS",
} }
} }
fn extensions(self) -> &'static [&'static str] { fn extensions(self) -> &'static [&'static str] {
@@ -81,9 +84,10 @@ impl ResourceKind {
Self::Format => &["fmt"], Self::Format => &["fmt"],
Self::Config => &["cnf"], Self::Config => &["cnf"],
Self::FontMapping => &["tec"], Self::FontMapping => &["tec"],
Self::Sfd => &["sfd"],
} }
} }
const ALL: [Self; 12] = [ const ALL: [Self; 13] = [
Self::Tex, Self::Tex,
Self::Tfm, Self::Tfm,
Self::Vf, Self::Vf,
@@ -96,6 +100,7 @@ impl ResourceKind {
Self::Format, Self::Format,
Self::Config, Self::Config,
Self::FontMapping, Self::FontMapping,
Self::Sfd,
]; ];
} }
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+28
View File
@@ -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#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) [原版格式所写字体字段](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 字体 ### pdfTeX 映射的 OpenType CFF 字体
传统字体映射读取实际 OpenType、TFM 和可选编码文件。TeX 槽位 传统字体映射读取实际 OpenType、TFM 和可选编码文件。TeX 槽位
+54
View File
@@ -1957,6 +1957,60 @@ fn mapped_opentype_cff_paints_reencoded_glyphs_and_embeds_the_original_table() {
fs::remove_dir_all(root).unwrap(); 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 <face.ttf}
\font\mapped=route00 \shipout\hbox{\mapped ABC}
\end",
)
.unwrap();
let mut job = request(&root);
for kind in [
ResourceKind::Map,
ResourceKind::TrueType,
ResourceKind::Tfm,
ResourceKind::Sfd,
] {
job.world
.paths
.insert(kind, vec![SearchPath::directory(&root, false)]);
}
let compiler = NativeCompiler::default();
let first = compiler.compile(job.clone()).unwrap();
let glyphs: String = first.pages[0].items.iter().filter_map(|item| {
match item {
DisplayItem::NativeGlyph { character, slot, paint: Some(paint), .. } => {
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] #[test]
fn mapped_truetype_paints_and_embeds_the_actual_font() { fn mapped_truetype_paints_and_embeds_the_actual_font() {
use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem}; use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};