Render vertical and CFF legacy XeLaTeX composite fonts

This commit is contained in:
gloamxun committed 2026-11-28 22:17:46 +08:00
1 parent bbeeca0317
commit ff52a9f66b
14 files changed
+877 -292

No files matched your search

+175
View File
@@ -0,0 +1,175 @@
//! Embed CFF1 outlines under the CIDs selected by the XDV font map.
use read_fonts::{
FontData, FontRead,
ps::cff::{dict, index::Index1, v1::Cff},
};
use rustybuzz::ttf_parser::{Face, RawFace, Tag};
use std::collections::BTreeMap;
use crate::{
native_font::{NativeFontPaint, OpenTypeCffProgram},
type1_outline::cff::{dict_long, dict_number, index},
};
pub(super) fn subset(
program: &OpenTypeCffProgram,
face: &Face<'_>,
paint: &NativeFontPaint,
glyphs: &BTreeMap<u16, u16>,
name: &str,
) -> Result<Vec<u8>, String> {
let mapping = paint.legacy_cid_font().expect("composite CFF mapping");
let table = face
.raw_face()
.table(Tag::from_bytes(b"CFF "))
.ok_or("missing composite CFF1 table")?;
let cff = Cff::read(FontData::new(table)).map_err(|_| "invalid composite CFF1 table")?;
let top = cff.top_dicts().get(0).ok_or("missing CFF top dictionary")?;
if dict::entries(top, None)
.flatten()
.any(|entry| matches!(entry, dict::Entry::Ros { .. }))
{
let subset = super::opentype_fonts::subset_cid_cff(
&program.data,
program.face_index,
&program.name,
glyphs.values().copied(),
)?;
let raw = RawFace::parse(&subset, 0).map_err(|_| "invalid CID CFF subset")?;
return raw
.table(Tag::from_bytes(b"CFF "))
.map(ToOwned::to_owned)
.ok_or_else(|| "missing CFF table in CID subset".into());
}
let mut charstrings = None;
let mut private = None;
for entry in dict::entries(top, None) {
match entry.map_err(|_| "invalid CFF dictionary")? {
dict::Entry::CharstringsOffset(offset) => charstrings = Some(offset),
dict::Entry::PrivateDictRange(range) => private = Some(range),
_ => {}
}
}
let invalid = || "invalid CFF index or offset".to_owned();
let at = |offset| table.get(offset..).ok_or_else(invalid);
let source_programs = Index1::read(FontData::new(at(
charstrings.ok_or("missing CFF charstrings")?
)?))
.map_err(|_| invalid())?;
let mut programs = vec![source_programs.get(0).ok_or("missing CFF .notdef")?];
let mut charset = vec![0]; // Format 0. Each entry is the actual CID, in CharStrings order.
for (&cid, &glyph) in glyphs {
if cid != 0 {
charset.extend(cid.to_be_bytes());
programs.push(
source_programs
.get(usize::from(glyph))
.ok_or_else(invalid)?,
);
}
}
let count = u16::try_from(programs.len()).map_err(|_| "too many glyphs for CFF1")?;
let programs = index(&programs)?;
let mut private_bytes = Vec::new();
let mut private_size = 0;
if let Some(range) = private {
let dictionary = table.get(range.clone()).ok_or_else(invalid)?;
private_size = dictionary.len();
private_bytes.extend(dictionary);
for entry in dict::entries(dictionary, None) {
if let dict::Entry::SubrsOffset(relative) =
entry.map_err(|_| "invalid CFF private dictionary")?
{
let offset = range.start.checked_add(relative).ok_or_else(invalid)?;
let subroutines =
Index1::read(FontData::new(at(offset)?)).map_err(|_| invalid())?;
let length = subroutines.size_in_bytes().ok_or_else(invalid)?;
let end = offset.checked_add(length).ok_or_else(invalid)?;
private_bytes.extend(table.get(range.end..end).ok_or_else(invalid)?);
break;
}
}
}
// Preserve real Type 2 hint programs, and the exact global and local
// subroutine indexes on which their operand biases depend.
let globals = cff.global_subrs();
let globals = index(
&(0..usize::from(globals.count()))
.map(|i| globals.get(i).ok_or_else(invalid))
.collect::<Result<Vec<_>, _>>()?,
)?;
let name = index(&[name])?;
let strings = index(&[mapping.registry.as_bytes(), mapping.ordering.as_bytes()])?;
let fd_select = vec![0; usize::from(count) + 1];
let long = |out: &mut Vec<u8>, value: usize| -> Result<(), String> {
dict_long(
out,
i32::try_from(value).map_err(|_| "CFF offset overflow")?,
);
Ok(())
};
let font_dict = |private_offset| -> Result<Vec<u8>, String> {
let mut dict = Vec::new();
long(&mut dict, private_size)?;
long(&mut dict, private_offset)?;
dict.push(18);
index(&[dict])
};
let mut attributes = Vec::new();
// CFF1 reserves SIDs 0 through 390 for standard strings.
long(&mut attributes, 391)?;
long(&mut attributes, 392)?;
long(&mut attributes, mapping.supplement as usize)?;
attributes.extend([12, 30]); // ROS
let bbox = face.global_bounding_box();
for value in [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] {
dict_number(&mut attributes, f64::from(value))?;
}
attributes.push(5);
let matrix = face.tables().cff.ok_or("missing CFF outlines")?.matrix();
for value in [
matrix.sx, matrix.ky, matrix.kx, matrix.sy, matrix.tx, matrix.ty,
] {
dict_number(&mut attributes, f64::from(value))?;
}
attributes.extend([12, 7]); // FontMatrix
long(
&mut attributes,
usize::from(glyphs.last_key_value().map_or(0, |(&cid, _)| cid)) + 1,
)?;
attributes.extend([12, 34]); // CIDCount
let top = |base| -> Result<Vec<u8>, String> {
let programs_offset = base + charset.len();
let select_offset = programs_offset + programs.len();
let fd_offset = select_offset + fd_select.len();
let mut top = attributes.clone();
for (offset, opcode) in [
(base, &[15][..]),
(programs_offset, &[17][..]),
(select_offset, &[12, 37][..]),
(fd_offset, &[12, 36][..]),
] {
long(&mut top, offset)?;
top.extend(opcode);
}
index(&[top])
};
let offset = 4 + name.len() + top(0)?.len() + strings.len() + globals.len();
let private_offset =
offset + charset.len() + programs.len() + fd_select.len() + font_dict(0)?.len();
let mut output = vec![1, 0, 4, 4];
for part in [
name,
top(offset)?,
strings,
globals,
charset,
programs,
fd_select,
font_dict(private_offset)?,
private_bytes,
] {
output.extend(part);
}
Ok(output)
}
@@ -0,0 +1,174 @@
//! Write the PDF composite font for slots selected by legacy XDV output.
use super::{native_pdf_name, objects};
use crate::{
native_font::{NativeFontPaint, NativeFontProgram},
type1_outline::subset_tag,
};
use std::collections::BTreeSet;
pub(super) fn write(
objects: &mut Vec<Vec<u8>>,
paint: &NativeFontPaint,
slots: impl Iterator<Item = u8>,
compression: u8,
subset_tags: &mut BTreeSet<String>,
target: Option<usize>,
) -> Result<usize, String> {
use crate::native_font::cid_width;
use std::{collections::BTreeMap, fmt::Write as _};
use subsetter::GlyphRemapper;
let mapping = paint.legacy_cid_font().expect("composite program");
let (name, face) = match &paint.program {
NativeFontProgram::TrueType(program) => (&program.name, program.face()?),
NativeFontProgram::OpenTypeCff(program) => (&program.name, program.face()?),
_ => unreachable!("legacy CID program"),
};
let mut vertical_widths = BTreeMap::new();
let mut glyphs = BTreeMap::new();
let mut unicode = BTreeMap::new();
for slot in slots {
let cid = mapping.cid(slot);
let glyph = match &paint.program {
NativeFontProgram::TrueType(program) => program.glyph_id(slot),
NativeFontProgram::OpenTypeCff(program) => program.composite_glyphs[usize::from(slot)],
_ => unreachable!("legacy CID program"),
};
if let Some(metrics) = mapping.vertical_override(slot) {
vertical_widths.insert(cid, metrics);
}
if glyphs.insert(cid, glyph).is_some_and(|old| old != glyph) {
return Err(format!("conflicting glyph for CID {cid} in {name}"));
}
if cid != 0
&& let Some(text) = mapping.unicode(slot)
{
unicode.entry(cid).or_insert_with(|| {
text.encode_utf16()
.map(|unit| format!("{unit:04X}"))
.collect()
});
}
}
let names = glyphs.keys().map(|cid| format!("/c{cid:04X}")).collect();
let tag = (0..100)
.map(|salt| subset_tag(name, &names, salt))
.find(|tag| subset_tags.insert(tag.clone()))
.ok_or("CID subset name collision limit exceeded")?;
let name = format!("{tag}+{}", native_pdf_name(name));
let mut remapper = GlyphRemapper::new();
let max = usize::from(glyphs.keys().next_back().copied().unwrap_or(0));
let mut cid_to_gid = vec![0; (max + 1) * 2];
let mut cid_set = vec![0; max / 8 + 1];
let width = |glyph| cid_width(&face, glyph);
let default = width(0);
let mut widths = String::new();
let mut previous: Option<u16> = None;
let mut identity = true;
for (&cid, &glyph) in &glyphs {
let subset_id = remapper.remap(glyph);
let index = usize::from(cid);
cid_to_gid[index * 2..index * 2 + 2].copy_from_slice(&subset_id.to_be_bytes());
if cid != 0 {
cid_set[index / 8] |= 1 << (7 - index % 8);
}
identity &= cid == subset_id;
let advance = width(glyph);
if advance == default {
continue;
}
if previous.and_then(|id| id.checked_add(1)) != Some(cid) {
if previous.is_some() {
widths.push_str("] ");
}
write!(widths, "{cid} [").unwrap();
}
write!(widths, "{advance} ").unwrap();
previous = Some(cid);
}
let mut widths = if widths.is_empty() {
widths
} else {
format!(" /W [{widths}]]")
};
let encoding = if let Some([advance, origin]) = mapping.vertical {
write!(widths, " /DW2 [{origin} {}]", -advance).unwrap();
if !vertical_widths.is_empty() {
widths.push_str(" /W2 [");
for (cid, [advance, x, y]) in vertical_widths {
write!(widths, "{cid} {cid} {} {x} {y} ", -advance).unwrap();
}
widths.push(']');
}
"Identity-V"
} else {
"Identity-H"
};
let (subtype, file_key, file_option, subset) = match &paint.program {
NativeFontProgram::TrueType(program) => {
let subset = program.embed_cid_subset(&remapper)?;
(
"CIDFontType2",
"FontFile2",
format!("/Length1 {}", subset.len()),
subset,
)
}
NativeFontProgram::OpenTypeCff(program) => (
"CIDFontType0",
"FontFile3",
"/Subtype /CIDFontType0C".to_owned(),
super::cid_cff::subset(program, &face, paint, &glyphs, &name)?,
),
_ => unreachable!("legacy CID program"),
};
let id = target.unwrap_or_else(|| {
objects.push(Vec::new());
objects.len()
});
let fontfile = objects.len() + 1;
objects.push(objects::stream(&file_option, &subset, compression));
let cid_set_id = objects.len() + 1;
objects.push(objects::stream("", &cid_set, compression));
let descriptor = objects.len() + 1;
let mut contents = super::opentype_fonts::font_descriptor(&face, &name, file_key, fontfile);
assert!(contents.ends_with(b" >>"));
contents.truncate(contents.len() - 3);
contents.extend_from_slice(format!(" /CIDSet {cid_set_id} 0 R >>").as_bytes());
objects.push(contents);
let cid_mapping = if subtype == "CIDFontType0" {
String::new()
} else if identity {
" /CIDToGIDMap /Identity".to_owned()
} else {
objects.push(objects::stream("", &cid_to_gid, compression));
format!(" /CIDToGIDMap {} 0 R", objects.len())
};
let descendant = objects.len() + 1;
let registry = super::escape(&mapping.registry);
let ordering = super::escape(&mapping.ordering);
let supplement = mapping.supplement;
objects.push(format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry ({registry}) /Ordering ({ordering}) /Supplement {supplement} >> /FontDescriptor {descriptor} 0 R /DW {default}{widths}{cid_mapping} >>"
).into_bytes());
let unicode_ref = if unicode.is_empty() {
String::new()
} else {
objects.push(objects::stream(
"",
&super::to_unicode_map(&unicode, 4),
compression,
));
format!(" /ToUnicode {} 0 R", objects.len())
};
let type0_name = if subtype == "CIDFontType0" {
format!("{name}-{encoding}")
} else {
name
};
objects[id - 1] = format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{type0_name} /Encoding /{encoding} /DescendantFonts [{descendant} 0 R]{unicode_ref} >>"
).into_bytes();
Ok(id)
}
@@ -62,111 +62,3 @@ pub(super) fn write(
);
Ok((descriptor, name))
}
pub(super) fn write_cid(
objects: &mut Vec<Vec<u8>>,
program: &TrueTypeProgram,
slots: impl Iterator<Item = u8>,
compression: u8,
subset_tags: &mut BTreeSet<String>,
target: Option<usize>,
) -> Result<usize, String> {
use crate::native_font::cid_width;
use std::{collections::BTreeMap, fmt::Write as _};
use subsetter::GlyphRemapper;
let mapping = program.composite.as_ref().expect("composite TrueType program");
let face = program.face()?;
let mut glyphs = BTreeMap::new();
let mut unicode = BTreeMap::new();
for slot in slots {
let cid = mapping.cid(slot);
let glyph = program.glyph_id(slot);
if glyphs.insert(cid, glyph).is_some_and(|old| old != glyph) {
return Err(format!("conflicting glyph for CID {cid} in {}", program.name));
}
if cid != 0
&& let Some(text) = mapping.unicode(slot)
{
unicode.entry(cid).or_insert_with(|| {
text.encode_utf16().map(|unit| format!("{unit:04X}")).collect()
});
}
}
let names = glyphs.keys().map(|cid| format!("/c{cid:04X}")).collect();
let tag = (0..100).map(|salt| subset_tag(&program.name, &names, salt))
.find(|tag| subset_tags.insert(tag.clone()))
.ok_or("CID subset name collision limit exceeded")?;
let name = format!("{tag}+{}", native_pdf_name(&program.name));
let mut remapper = GlyphRemapper::new();
let max = usize::from(glyphs.keys().next_back().copied().unwrap_or(0));
let mut cid_to_gid = vec![0; (max + 1) * 2];
let mut cid_set = vec![0; max / 8 + 1];
let width = |glyph| cid_width(&face, glyph);
let default = width(0);
let mut widths = String::new();
let mut previous: Option<u16> = None;
let mut identity = true;
for (&cid, &glyph) in &glyphs {
let subset_id = remapper.remap(glyph);
let index = usize::from(cid);
cid_to_gid[index * 2..index * 2 + 2].copy_from_slice(&subset_id.to_be_bytes());
if cid != 0 {
cid_set[index / 8] |= 1 << (7 - index % 8);
}
identity &= cid == subset_id;
let advance = width(glyph);
if advance == default {
continue;
}
if previous.and_then(|id| id.checked_add(1)) != Some(cid) {
if previous.is_some() {
widths.push_str("] ");
}
write!(widths, "{cid} [").unwrap();
}
write!(widths, "{advance} ").unwrap();
previous = Some(cid);
}
let widths = if widths.is_empty() { widths } else { format!(" /W [{widths}]]") };
let subset = program.embed_cid_subset(&remapper)?;
let id = target.unwrap_or_else(|| {
objects.push(Vec::new());
objects.len()
});
let fontfile = objects.len() + 1;
objects.push(objects::stream(&format!("/Length1 {}", subset.len()), &subset, compression));
let cid_set_id = objects.len() + 1;
objects.push(objects::stream("", &cid_set, compression));
let descriptor = objects.len() + 1;
let mut contents = super::opentype_fonts::font_descriptor(&face, &name, "FontFile2", fontfile);
assert!(contents.ends_with(b" >>"));
contents.truncate(contents.len() - 3);
contents.extend_from_slice(format!(" /CIDSet {cid_set_id} 0 R >>").as_bytes());
objects.push(contents);
let cid_mapping = if identity {
"/Identity".to_owned()
} else {
objects.push(objects::stream("", &cid_to_gid, compression));
format!("{} 0 R", objects.len())
};
let descendant = objects.len() + 1;
let registry = super::escape(&mapping.registry);
let ordering = super::escape(&mapping.ordering);
let supplement = mapping.supplement;
objects.push(format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} /CIDSystemInfo << /Registry ({registry}) /Ordering ({ordering}) /Supplement {supplement} >> /FontDescriptor {descriptor} 0 R /DW {default}{widths} /CIDToGIDMap {cid_mapping} >>"
).into_bytes());
let unicode_ref = if unicode.is_empty() {
String::new()
} else {
objects.push(objects::stream("", &super::to_unicode_map(&unicode, 4), compression));
format!(" /ToUnicode {} 0 R", objects.len())
};
objects[id - 1] = format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{descendant} 0 R]{unicode_ref} >>"
).into_bytes();
Ok(id)
}