Preserve source CIDs in native XeTeX CFF export

This commit is contained in:
gloamxun committed 2026-11-28 04:56:24 +08:00
1 parent 82e54894c4
commit 23ec506fa3
4 files changed
+313 -20

No files matched your search

+194 -16
View File
@@ -2,8 +2,10 @@
use super::{PageContent, native_pdf_name, objects, opentype_unicode, to_unicode_map};
use crate::{execution::FontId, opentype::OpenTypeFont};
use read_fonts::{
FontData, FontRead,
ps::cff::{dict, v1::Cff},
FileRef, FontData, FontRead,
collections::IntSet,
ps::cff::{CffFontRef, charset::Charset, dict, v1::Cff},
types::{GlyphId as SkeraGlyphId, Tag as SkeraTag},
};
use rustybuzz::ttf_parser::{Face, GlyphId, RawFace, Tag};
use sha2::{Digest, Sha256};
@@ -117,6 +119,99 @@ impl<'a> UsedFonts<'a> {
}
}
struct CidCff<'a> {
registry: &'a [u8],
ordering: &'a [u8],
supplement: i32,
name: &'a str,
charset: Charset<'a>,
}
impl<'a> CidCff<'a> {
fn read(face: &Face<'a>) -> Result<Option<Self>, String> {
let Some(data) = face.raw_face().table(Tag::from_bytes(b"CFF ")) else {
return Ok(None);
};
let invalid = || "invalid OpenType CFF character collection".to_owned();
let cff = Cff::read(FontData::new(data)).map_err(|_| invalid())?;
let top = cff.top_dicts().get(0).ok_or_else(invalid)?;
for entry in dict::entries(top, None).flatten() {
if let dict::Entry::Ros {
registry,
ordering,
supplement,
} = entry
{
let name = cff.name(0).and_then(|name| str::from_utf8(name).ok());
return Ok(Some(Self {
registry: cff.string(registry).ok_or_else(invalid)?,
ordering: cff.string(ordering).ok_or_else(invalid)?,
supplement: supplement.to_f64() as i32,
name: name.ok_or_else(invalid)?,
charset: CffFontRef::new_cff(data, 0, None)
.ok()
.and_then(|font| font.charset())
.ok_or_else(invalid)?,
}));
}
}
Ok(None)
}
fn system_info(&self) -> String {
let literal = |bytes: &[u8]| {
super::escape(&bytes.iter().copied().map(char::from).collect::<String>())
};
format!(
"/Registry ({}) /Ordering ({}) /Supplement {}",
literal(self.registry),
literal(self.ordering),
self.supplement
)
}
fn standard_adobe_collection(&self) -> bool {
self.registry == b"Adobe"
&& matches!(self.ordering, b"GB1" | b"CNS1" | b"Japan1" | b"Korea1")
}
}
fn subset_cid_cff(
font: &OpenTypeFont,
glyphs: impl Iterator<Item = u16>,
) -> Result<Vec<u8>, String> {
let invalid = |error| format!("invalid OpenType font {}: {error}", font.name);
let file = FileRef::new(&font.resource.data).map_err(invalid)?;
let face = match file {
FileRef::Font(face) => face,
FileRef::Collection(faces) => faces.get(font.face_index()).map_err(invalid)?,
};
// Only the CFF program is embedded. No layout tables or character closure
// are needed for glyphs that have already been shaped.
let cff_tag = SkeraTag::new(b"CFF ");
let drop_tables = face
.table_directory()
.table_records()
.iter()
.map(|record| record.tag())
.filter(|&tag| tag != cff_tag)
.collect();
let plan = skera::Plan::new(
&glyphs.map(SkeraGlyphId::from).collect(),
&IntSet::empty(),
&face,
skera::SubsetFlags::SUBSET_FLAGS_NOTDEF_OUTLINE
| skera::SubsetFlags::SUBSET_FLAGS_NO_LAYOUT_CLOSURE,
&drop_tables,
&IntSet::empty(),
&IntSet::empty(),
&IntSet::empty(),
&IntSet::empty(),
);
skera::subset_font(&face, &plan)
.map_err(|error| format!("failed to embed OpenType CID font {}: {error}", font.name))
}
fn write_font(
objects: &mut Vec<Vec<u8>>,
font: &OpenTypeFont,
@@ -126,40 +221,90 @@ fn write_font(
) -> Result<EmbeddedFont, String> {
let face = font.face()?;
let xdv = options.filter(|options| options.xdv_font_unicode);
let font_unicode = xdv.map(|options| {
let cid_cff = if xdv.is_some() {
CidCff::read(&face)?
} else {
None
};
// The standard Adobe character collections supply their Unicode mapping.
let implicit_unicode = cid_cff
.as_ref()
.is_some_and(CidCff::standard_adobe_collection);
let font_unicode = xdv.filter(|_| !implicit_unicode).map(|options| {
opentype_unicode::map_glyphs(&face, glyphs.keys().copied(), options.xdv_glyph_names)
});
let source_cids = cid_cff.as_ref().map(|font| {
let glyph_limit = glyphs
.keys()
.next_back()
.map_or(0, |&glyph| usize::from(glyph) + 1);
font.charset
.iter()
.take(glyph_limit)
.filter_map(|(glyph, cid)| {
let glyph = u16::try_from(glyph.to_u32()).ok()?;
glyphs.contains_key(&glyph).then_some((glyph, cid.to_u16()))
})
.collect::<BTreeMap<_, _>>()
});
let mut remapper = GlyphRemapper::new();
let mut fingerprint = Sha256::new();
fingerprint.update(font.resource.version.sha256.as_bytes());
fingerprint.update(font.face_index().to_be_bytes());
let mut widths = String::new();
let mut cid_widths = BTreeMap::new();
let mut cmap = BTreeMap::new();
let mut embedded = BTreeMap::new();
let width = |value: i64| (value as f64 * 1000. / f64::from(face.units_per_em())).round() as i32;
let default_advance = face.glyph_hor_advance(GlyphId(0)).unwrap_or(0);
let width_tenths =
|value: u16| (f64::from(value) * 10000. / f64::from(face.units_per_em())).round() as u32;
let default_width = width_tenths(default_advance);
for (glyph, source) in glyphs {
let outside_face = glyph >= face.number_of_glyphs();
let (cid, advance) = if outside_face {
// The XDV cursor advances zero for this unmapped glyph number.
(glyph, 0)
(if cid_cff.is_some() { 0 } else { glyph }, 0)
} else {
let advance = face.glyph_hor_advance(GlyphId(glyph)).ok_or_else(|| {
format!("OpenType font {} has no advance for glyph {glyph}", font.name)
format!(
"OpenType font {} has no advance for glyph {glyph}",
font.name
)
})?;
(remapper.remap(glyph), advance)
let subset_id = remapper.remap(glyph);
let cid = if let Some(cids) = &source_cids {
*cids.get(&glyph).ok_or_else(|| {
format!("OpenType font {} has no CID for glyph {glyph}", font.name)
})?
} else {
subset_id
};
(cid, advance)
};
fingerprint.update(glyph.to_be_bytes());
// The PDF device uses the default glyph width for unmapped CIDs,
// independently of the XDV glyph's layout advance.
let pdf_advance = if outside_face {
face.glyph_hor_advance(GlyphId(0)).unwrap_or(0)
default_advance
} else {
advance
};
write!(widths, "{cid} [{}] ", width(i64::from(pdf_advance))).unwrap();
let unicode = match &font_unicode {
Some(mapping) => mapping.get(&glyph).map(String::as_str),
None => (!source.is_empty()).then_some(source),
if cid_cff.is_some() {
let pdf_width = width_tenths(pdf_advance);
if pdf_width != default_width {
cid_widths.insert(cid, pdf_width);
}
} else {
write!(widths, "{cid} [{}] ", width(i64::from(pdf_advance))).unwrap();
}
let unicode = if xdv.is_some() {
font_unicode
.as_ref()
.and_then(|mapping| mapping.get(&glyph))
.map(String::as_str)
} else {
(!source.is_empty()).then_some(source)
};
if let Some(unicode) = unicode {
cmap.insert(cid, utf16_hex(unicode));
@@ -179,12 +324,20 @@ fn write_font(
.take(6)
.map(|byte| char::from(b'A' + byte % 26))
.collect();
let name = format!("{tag}+{}", native_pdf_name(&font.name));
let postscript_name = cid_cff.as_ref().map_or(font.name.as_str(), |cff| cff.name);
let name = format!("{tag}+{}", native_pdf_name(postscript_name));
let subset = subsetter::subset(&font.resource.data, font.face_index(), &remapper)
.map_err(|error| format!("failed to embed OpenType font {}: {error}", font.name))?;
let subset = if cid_cff.is_some() {
subset_cid_cff(font, remapper.remapped_gids())?
} else {
subsetter::subset(&font.resource.data, font.face_index(), &remapper)
.map_err(|error| format!("failed to embed OpenType font {}: {error}", font.name))?
};
let raw = RawFace::parse(&subset, 0).map_err(|_| "invalid OpenType subset font")?;
let cff = raw.table(Tag::from_bytes(b"CFF "));
if cid_cff.is_some() && cff.is_none() {
return Err(format!("OpenType CID font {} has no CFF subset", font.name));
}
let (subtype, mapping, file_key, file_options, program) = if let Some(cff) = cff {
(
"CIDFontType0",
@@ -212,11 +365,36 @@ fn write_font(
} else {
format!(" /ToUnicode {} 0 R", object + 4)
};
let (type0_name, system_info, width_entries) = if let Some(cff) = &cid_cff {
let mut entries = format!(" /DW {}", f64::from(default_width) / 10.);
if !cid_widths.is_empty() {
entries.push_str(" /W [");
let mut previous = None;
for (cid, width) in cid_widths {
if previous.and_then(|cid: u16| cid.checked_add(1)) != Some(cid) {
if previous.is_some() {
entries.push_str("] ");
}
write!(entries, "{cid} [").unwrap();
}
write!(entries, "{} ", f64::from(width) / 10.).unwrap();
previous = Some(cid);
}
entries.push_str("]]");
}
(format!("{name}-Identity-H"), cff.system_info(), entries)
} else {
(
name.clone(),
"/Registry (Adobe) /Ordering (Identity) /Supplement 0".to_owned(),
format!(" /W [{widths}]"),
)
};
objects.push(format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R]{unicode_reference} >>"
"<< /Type /Font /Subtype /Type0 /BaseFont /{type0_name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R]{unicode_reference} >>"
).into_bytes());
objects.push(format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /W [{widths}]{mapping} >>"
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << {system_info} >> /FontDescriptor {descriptor} 0 R{width_entries}{mapping} >>"
).into_bytes());
objects.push(font_descriptor(&face, &name, file_key, font_file));
objects.push(objects::stream(&file_options, program, compression));