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

+57 -6
View File
@@ -1,6 +1,7 @@
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face.
use super::{
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
composite::{self, Codes, CompositeFont},
map::{MapEntry, OutlineFiles},
};
use crate::{execution::SourceProvider, resources::ResourceKind};
@@ -11,12 +12,18 @@ use std::{collections::{BTreeMap, BTreeSet}, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct OpenTypeCffProgram {
pub(crate) name: String,
data: Arc<[u8]>,
pub(crate) data: Arc<[u8]>,
#[serde(default)]
pub(crate) face_index: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) composite: Option<CompositeFont>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) composite_glyphs: Vec<u16>,
}
impl OpenTypeCffProgram {
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
Face::parse(&self.data, 0)
Face::parse(&self.data, self.face_index)
.map_err(|error| format!("invalid OpenType font {}: {error}", self.name))
}
}
@@ -57,6 +64,43 @@ pub(super) fn resolve(
font: &NativeFont,
slots: BTreeSet<u8>,
) -> Result<NativeFontPaint, String> {
if let Some(encoding) = &outline.xdv_encoding
&& let Some(codes) = Codes::load(encoding, outline, files)?
{
let mut raw_outline = outline.clone();
raw_outline.encoding = None;
let MappedOutline { data, mut resources, program_index, .. } =
raw_outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
let face = Face::parse(&data, outline.face_index)
.map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
if face.tables().cff.is_none() {
return Err(format!("OpenType font has no supported CFF1 table: {file}"));
}
let composite::Glyphs { mapping, glyphs, names, glyph_paths } =
composite::resolve(files, outline, &data, &face, slots, encoding, codes, &mut resources)?;
let name = face.names().into_iter()
.filter(|name| name.name_id == rustybuzz::ttf_parser::name_id::POST_SCRIPT_NAME)
.find_map(|name| name.to_string())
.unwrap_or_else(|| outline.postscript_name().unwrap_or(&font.name).to_owned());
let bbox = scaled_bbox(&face);
return Ok(NativeFontPaint {
program: NativeFontProgram::OpenTypeCff(OpenTypeCffProgram {
name, data, face_index: outline.face_index, composite: Some(mapping), composite_glyphs: glyphs,
}),
encoding: names,
glyph_paths,
bbox,
stem_v: 0,
subset: true,
descriptor_flags: None,
xdv_descriptor: None,
xdv_widths: BTreeMap::new(),
xdv_matrix: Default::default(),
xdv_unicode: None,
resources,
program_index: Some(program_index),
});
}
if outline.subset {
return Err(format!("OTF fonts must be included entirely: {file}"));
}
@@ -67,7 +111,7 @@ pub(super) fn resolve(
program_index,
} = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
let face =
Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
Face::parse(&data, outline.face_index).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
let table = face
.raw_face()
.table(Tag::from_bytes(b"CFF "))
@@ -116,12 +160,13 @@ pub(super) fn resolve(
})
.collect()
});
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 bbox = scaled_bbox(&face);
let program = OpenTypeCffProgram {
name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
data,
face_index: outline.face_index,
composite: None,
composite_glyphs: Vec::new(),
};
Ok(NativeFontPaint {
program: NativeFontProgram::OpenTypeCff(program),
@@ -139,3 +184,9 @@ pub(super) fn resolve(
program_index: Some(program_index),
})
}
fn scaled_bbox(face: &Face<'_>) -> [i32; 4] {
let bbox = face.global_bounding_box();
[bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max]
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()))
}
@@ -0,0 +1,365 @@
//! Resolve actual XDV character codes independently of the TeX font metrics.
use super::{
cid_width,
map::{MapEntry, XdvEncoding},
};
use crate::{
execution::SourceProvider, opentype::vertical::PdfMetrics, pdf_device::cmap::CMap,
resources::ResourceVersion,
};
use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct CompositeFont {
pub(crate) registry: String,
pub(crate) ordering: String,
pub(crate) supplement: u32,
slots: Vec<CompositeSlot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) vertical: Option<[i32; 2]>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
struct CompositeSlot {
cid: u16,
advance: u32,
unicode: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
vertical: Option<[i32; 3]>,
}
impl CompositeFont {
pub(crate) fn cid(&self, slot: u8) -> u16 {
self.slots[usize::from(slot)].cid
}
pub(crate) fn advance(&self, slot: u8) -> u32 {
self.slots[usize::from(slot)].advance
}
pub(crate) fn vertical_override(&self, slot: u8) -> Option<[i32; 3]> {
self.vertical?;
self.slots[usize::from(slot)].vertical
}
pub(crate) fn vertical_slot(&self, slot: u8) -> Option<[f64; 3]> {
let [advance, y] = self.vertical?;
if let Some(metrics) = self.vertical_override(slot) {
return Some(metrics.map(f64::from));
}
Some([
f64::from(advance),
f64::from(self.advance(slot)) / 2.0,
f64::from(y),
])
}
pub(crate) fn unicode(&self, slot: u8) -> Option<&str> {
self.slots[usize::from(slot)].unicode.as_deref()
}
}
pub(super) enum Codes {
Unicode,
Identity,
Custom(Box<CMap>),
}
impl Codes {
pub(super) fn load(
encoding: &XdvEncoding,
outline: &MapEntry,
files: &mut impl SourceProvider,
) -> Result<Option<Self>, String> {
let name = &encoding.name;
Ok(Some(match name.as_str() {
"unicode" => Self::Unicode,
"Identity-H" | "Identity-V" => Self::Identity,
_ => {
let Some(map) = CMap::load_optional(name, &outline.from.to_string_lossy(), files)?
else {
return if outline.encoding.is_some() {
Ok(None)
} else {
Err(format!("XDV encoding CMap {name} was not found"))
};
};
Self::Custom(Box::new(map))
}
}))
}
}
pub(super) struct Glyphs {
pub(super) mapping: CompositeFont,
pub(super) glyphs: Vec<u16>,
pub(super) names: Vec<String>,
pub(super) glyph_paths: BTreeMap<u8, String>,
}
pub(super) fn resolve(
files: &mut impl SourceProvider,
outline: &MapEntry,
data: &[u8],
face: &Face<'_>,
slots: BTreeSet<u8>,
encoding: &XdvEncoding,
codes: Codes,
resources: &mut Vec<ResourceVersion>,
) -> Result<Glyphs, String> {
let (requested_registry, requested_ordering, requested_supplement) = match &codes {
Codes::Custom(map) => {
resources.extend(map.resources.iter().cloned());
map.collection()
.ok_or_else(|| format!("CMap {} has no CID system info", encoding.name))?
}
_ => ("Adobe", "Identity", 0),
};
let identity = requested_registry == "Adobe" && requested_ordering == "Identity";
let collection = cid_keyed_collection(face)?;
let owns_collection = collection.is_some();
let same_collection = collection
.as_ref()
.is_some_and(|(registry, ordering, _, _)| {
registry == requested_registry && ordering == requested_ordering
});
if !identity && owns_collection && !same_collection {
return Err(format!(
"CMap {} uses a different collection from the CFF face",
encoding.name
));
}
let vertical = encoding.vertical
|| encoding.name == "Identity-V"
|| matches!(&codes, Codes::Custom(map) if map.is_vertical());
let metrics = vertical.then(|| PdfMetrics::new(face));
let shaper = if vertical {
Some(
rustybuzz::Face::from_slice(data, outline.face_index)
.ok_or("invalid vertical outline face")?,
)
} else {
None
};
let collection_to_unicode = if !identity {
let map = CMap::load(
&format!("{requested_registry}-{requested_ordering}-UCS2"),
&outline.from.to_string_lossy(),
files,
)?;
resources.extend(map.resources.iter().cloned());
Some(map)
} else {
None
};
let mut glyphs = vec![0; 256];
let mut names = vec![".notdef".to_owned(); 256];
let mut cells = vec![CompositeSlot::default(); 256];
let mut vertical_alternates = Vec::new();
let mut glyph_paths = BTreeMap::new();
let scale = 1000.0 / f64::from(face.units_per_em());
let reverse = if identity && !matches!(codes, Codes::Unicode) {
let glyphs = (0..=255u8).filter_map(|slot| {
let code = encoding.prefix | u32::from(slot);
let glyph = match &codes {
Codes::Custom(map) => map.cid(code)?,
_ => u16::try_from(code).ok()?,
};
(glyph != 0 && glyph < face.number_of_glyphs()).then_some(glyph)
});
crate::pdf::opentype_unicode::map_glyphs(face, glyphs, None)
} else {
BTreeMap::new()
};
// Resolve a complete byte table once. A subsequent page may activate any
// of these slots while sharing this font's dictionary and subset.
for slot in 0..=255u8 {
let code = encoding.prefix | u32::from(slot);
let glyph_for_direct_cid = |cid: u16| {
if let Some((_, _, _, charset)) = &collection {
charset
.iter()
.find_map(|(&glyph, &code)| (code == cid).then_some(glyph))
} else {
(cid < face.number_of_glyphs()).then_some(cid)
}
};
let target = match &codes {
Codes::Unicode => char::from_u32(code).and_then(|ch| {
let gid = face.glyph_index(ch)?.0;
Some((gid, gid, Some(ch.to_string())))
}),
Codes::Identity => u16::try_from(code)
.ok()
.and_then(|cid| Some((cid, glyph_for_direct_cid(cid)?, None))),
Codes::Custom(map) => map.cid(code).and_then(|cid| {
if identity {
return Some((cid, glyph_for_direct_cid(cid)?, None));
}
let text = collection_to_unicode.as_ref()?.unicode(2, u32::from(cid));
if same_collection {
return Some((cid, glyph_for_direct_cid(cid)?, text));
}
let text = text?;
let mut chars = text.chars();
let ch = chars.next()?;
if chars.next().is_some() {
return None;
}
let gid = face.glyph_index(ch)?.0;
Some((cid, gid, Some(text)))
}),
};
let (mut cid, mut gid, text) = target.unwrap_or((0, 0, None));
let name = face.glyph_name(GlyphId(gid)).filter(|_| gid != 0);
let text = text
.or_else(|| reverse.get(&gid).cloned())
.or_else(|| name.and_then(crate::type1::glyph_unicode_text));
if vertical
&& gid != 0
&& let (Some(shaper), Some(value)) = (&shaper, &text)
&& let Some(ch) = single_scalar(value)
{
let selected = vertical_glyph(shaper, ch, gid);
if selected != gid {
vertical_alternates.push((slot, selected));
}
gid = selected;
// The built-in Unicode mapping uses the selected glyph as its
// CID; named CMaps preserve the CID and select its actual glyph.
if matches!(codes, Codes::Unicode) {
cid = gid;
}
}
if let Some((_, _, _, charset)) = &collection {
cid = charset.get(&gid).copied().unwrap_or(0);
}
let index = usize::from(slot);
glyphs[index] = gid;
cells[index] = CompositeSlot {
cid,
advance: cid_width(face, gid),
unicode: text.clone(),
vertical: metrics
.as_ref()
.and_then(|metrics| metrics.override_for(GlyphId(gid)))
.map(|values| values.map(|value| value as i32)),
};
if let Some(name) = name {
names[index] = name.into();
} else if let Some(text) = &text
&& let Some(ch) = text.chars().next()
{
names[index] = format!("uni{:04X}", u32::from(ch));
}
if slots.contains(&slot) {
glyph_paths.insert(
slot,
crate::opentype::outline(face, gid, Some([scale, 0., scale])),
);
}
}
if !vertical_alternates.is_empty() {
let text = crate::pdf::opentype_unicode::map_glyphs(
face,
vertical_alternates.iter().map(|&(_, glyph)| glyph),
None,
);
for (slot, glyph) in vertical_alternates {
if let Some(source) = text.get(&glyph) {
cells[usize::from(slot)].unicode = Some(source.clone());
}
}
}
let (registry, ordering, supplement) = collection.map_or_else(
|| {
(
requested_registry.to_owned(),
requested_ordering.to_owned(),
requested_supplement,
)
},
|(registry, ordering, supplement, _)| (registry, ordering, supplement),
);
let mapping = CompositeFont {
registry,
ordering,
supplement,
slots: cells,
vertical: metrics.map(|value| [value.advance as i32, value.origin_y as i32]),
};
Ok(Glyphs {
mapping,
glyphs,
names,
glyph_paths,
})
}
fn single_scalar(text: &str) -> Option<char> {
let mut chars = text.chars();
let first = chars.next()?;
chars.next().is_none().then_some(first)
}
fn vertical_glyph(face: &rustybuzz::Face<'_>, ch: char, default: u16) -> u16 {
let mut buffer = rustybuzz::UnicodeBuffer::new();
buffer.push_str(ch.encode_utf8(&mut [0; 4]));
buffer.set_direction(rustybuzz::Direction::TopToBottom);
buffer.guess_segment_properties();
let result = rustybuzz::shape(face, &[], buffer);
let [glyph] = result.glyph_infos() else {
return default;
};
u16::try_from(glyph.glyph_id)
.ok()
.filter(|&id| id != 0)
.unwrap_or(default)
}
type Collection = (String, String, u32, BTreeMap<u16, u16>);
fn cid_keyed_collection(face: &Face<'_>) -> Result<Option<Collection>, String> {
use read_fonts::{
FontData, FontRead,
ps::cff::{CffFontRef, dict, v1::Cff},
};
let Some(data) = face.raw_face().table(Tag::from_bytes(b"CFF ")) else {
return Ok(None);
};
let error = || "invalid CID-keyed CFF charset".to_owned();
let cff = Cff::read(FontData::new(data)).map_err(|_| error())?;
let top = cff.top_dicts().get(0).ok_or_else(error)?;
for entry in dict::entries(top, None).flatten() {
if let dict::Entry::Ros {
registry,
ordering,
supplement,
} = entry
{
let read = |sid| {
let bytes = cff.string(sid).ok_or_else(error)?;
String::from_utf8(bytes.to_vec()).map_err(|_| error())
};
let charset = CffFontRef::new_cff(data, 0, None)
.ok()
.and_then(|font| font.charset())
.ok_or_else(error)?;
let map = charset
.iter()
.map(|(gid, cid)| {
let glyph = u16::try_from(gid.to_u32()).map_err(|_| error())?;
Ok((glyph, cid.to_u16()))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
return Ok(Some((
read(registry)?,
read(ordering)?,
supplement.to_f64().max(0.) as u32,
map,
)));
}
}
Ok(None)
}
@@ -1,9 +1,10 @@
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
use super::{
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
composite::{self, Codes, CompositeFont},
map::{MapEntry, OutlineFiles, XdvEncoding},
};
use crate::{execution::SourceProvider, pdf_device::cmap::CMap, resources::ResourceKind};
use crate::{execution::SourceProvider, resources::ResourceKind};
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
use std::{
collections::{BTreeMap, BTreeSet},
@@ -19,7 +20,7 @@ pub struct TrueTypeProgram {
#[serde(default)]
pub(crate) face_index: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) composite: Option<CompositeTrueType>,
pub(crate) composite: Option<CompositeFont>,
pub(crate) reencoded: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
@@ -27,35 +28,6 @@ pub struct TrueTypeProgram {
pub(crate) missing_subfont_cmap: Option<[u16; 2]>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct CompositeTrueType {
pub(crate) registry: String,
pub(crate) ordering: String,
pub(crate) supplement: u32,
slots: Vec<CompositeSlot>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
struct CompositeSlot {
cid: u16,
advance: u32,
unicode: Option<String>,
}
impl CompositeTrueType {
pub(crate) fn cid(&self, slot: u8) -> u16 {
self.slots[usize::from(slot)].cid
}
pub(crate) fn advance(&self, slot: u8) -> u32 {
self.slots[usize::from(slot)].advance
}
pub(crate) fn unicode(&self, slot: u8) -> Option<&str> {
self.slots[usize::from(slot)].unicode.as_deref()
}
}
impl TrueTypeProgram {
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
Face::parse(&self.data, self.face_index)
@@ -143,34 +115,6 @@ pub(super) fn device_program(
Ok(Some(data.into()))
}
enum Codes {
Unicode,
Identity,
Custom(Box<CMap>),
}
impl Codes {
fn load(encoding: &XdvEncoding, outline: &MapEntry, files: &mut impl SourceProvider) -> Result<Option<Self>, String> {
let name = &encoding.name;
if encoding.vertical || name == "Identity-V" {
return Err(format!("XDV legacy composite vertical metrics are not implemented for {name}"));
}
Ok(Some(match name.as_str() {
"unicode" => Self::Unicode,
"Identity-H" => Self::Identity,
_ => {
let Some(map) = CMap::load_optional(name, &outline.from.to_string_lossy(), files)? else {
return if outline.encoding.is_some() { Ok(None) } else { Err(format!("XDV encoding CMap {name} was not found")) };
};
if map.is_vertical() {
return Err(format!("XDV legacy composite vertical metrics are not implemented for {name}"));
}
Self::Custom(Box::new(map))
}
}))
}
}
fn resolve_composite(
files: &mut impl SourceProvider,
outlines: &mut OutlineFiles,
@@ -191,90 +135,12 @@ fn resolve_composite(
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
return Err(format!("invalid TrueType outline tables in {file}"));
}
let (registry, ordering, supplement) = match &codes {
Codes::Custom(map) => {
resources.extend(map.resources.iter().cloned());
map.collection().ok_or_else(|| format!("CMap {} has no CID system info", encoding.name))?
}
_ => ("Adobe", "Identity", 0),
};
let identity = registry == "Adobe" && ordering == "Identity";
let collection_to_unicode = if !identity {
let map = CMap::load(&format!("{registry}-{ordering}-UCS2"), &outline.from.to_string_lossy(), files)?;
resources.extend(map.resources.iter().cloned());
Some(map)
} else {
None
};
let mut glyphs = vec![0; 256];
let mut names = vec![".notdef".to_owned(); 256];
let mut cells = vec![CompositeSlot::default(); 256];
let mut glyph_paths = BTreeMap::new();
let scale = 1000.0 / f64::from(face.units_per_em());
let reverse = if identity && !matches!(codes, Codes::Unicode) {
let glyphs = (0..=255u8).filter_map(|slot| {
let code = encoding.prefix | u32::from(slot);
let glyph = match &codes {
Codes::Custom(map) => map.cid(code)?,
_ => u16::try_from(code).ok()?,
};
(glyph != 0 && glyph < face.number_of_glyphs()).then_some(glyph)
});
crate::pdf::opentype_unicode::map_glyphs(&face, glyphs, None)
} else {
BTreeMap::new()
};
// Resolve a complete byte table once. A subsequent page may activate any
// of these slots while sharing this font's dictionary and subset.
for slot in 0..=255u8 {
let code = encoding.prefix | u32::from(slot);
let target = match &codes {
Codes::Unicode => char::from_u32(code).and_then(|ch| {
let gid = face.glyph_index(ch)?.0;
Some((gid, gid, Some(ch.to_string())))
}),
Codes::Identity => u16::try_from(code).ok().filter(|&cid| cid < face.number_of_glyphs())
.map(|cid| (cid, cid, None)),
Codes::Custom(map) => map.cid(code).and_then(|cid| {
if identity {
return (cid < face.number_of_glyphs()).then_some((cid, cid, None));
}
let text = collection_to_unicode.as_ref()?.unicode(2, u32::from(cid))?;
let mut chars = text.chars();
let ch = chars.next()?;
if chars.next().is_some() {
return None;
}
let gid = face.glyph_index(ch)?.0;
Some((cid, gid, Some(text)))
}),
};
let (cid, gid, text) = target.unwrap_or((0, 0, None));
let name = face.glyph_name(GlyphId(gid)).filter(|_| gid != 0);
let text = text.or_else(|| reverse.get(&gid).cloned()).or_else(|| name.and_then(crate::type1::glyph_unicode_text));
let index = usize::from(slot);
glyphs[index] = gid;
cells[index] = CompositeSlot {
cid,
advance: cid_width(&face, gid),
unicode: text.clone(),
};
if let Some(name) = name {
names[index] = name.into();
} else if let Some(text) = &text && let Some(ch) = text.chars().next() {
names[index] = format!("uni{:04X}", u32::from(ch));
}
if slots.contains(&slot) {
glyph_paths.insert(slot, crate::opentype::outline(&face, gid, Some([scale, 0., scale])));
}
}
let composite::Glyphs { mapping, glyphs, names, glyph_paths } =
composite::resolve(files, outline, &data, &face, slots, encoding, codes, &mut resources)?;
let name = font_name(&face, outline, font);
let bbox = font_bbox(&face);
let composite = CompositeTrueType {
registry: registry.to_owned(), ordering: ordering.to_owned(), supplement, slots: cells,
};
let program = TrueTypeProgram {
name, data, glyphs, face_index: outline.face_index, composite: Some(composite),
name, data, glyphs, face_index: outline.face_index, composite: Some(mapping),
reencoded: false, subfont_codes: None, missing_subfont_cmap: None,
};
Ok(NativeFontPaint {