Preserve sparse XDV TrueType glyph subsets

This commit is contained in:
gloamxun committed 2026-11-29 04:03:12 +08:00
1 parent 9efededf6d
commit d6e66cad12
5 files changed
+257 -14

No files matched your search

+1 -1
View File
@@ -156,7 +156,7 @@ pub(super) fn write(
format!("<< /Type /FontDescriptor /FontName /{name} {parameters} /{file_key} {fontfile} 0 R >>").into_bytes()
}
_ => super::opentype_fonts::font_descriptor(
face.as_ref().expect("sfnt CID font"), &name, file_key, fontfile,
face.as_ref().expect("sfnt CID font"), &name, file_key, fontfile, None,
),
};
assert!(contents.ends_with(b" >>"));
@@ -0,0 +1,184 @@
//! Sparse glyph numbering for TrueType fonts embedded by the XDV device.
use read_fonts::{
FileRef, TableProvider,
collections::IntSet,
tables::glyf::Glyph,
types::{GlyphId, Tag},
};
use rustybuzz::ttf_parser::{Face, GlyphId as TtfGlyphId};
use std::collections::{BTreeMap, btree_map::Entry};
pub(super) struct Subset {
pub bytes: Vec<u8>,
pub glyph_count: usize,
pub default_advance: u16,
}
impl Subset {
pub(super) fn new(
data: &[u8],
index: u32,
metrics: &Face<'_>,
selected: impl Iterator<Item = u16>,
) -> Result<Self, String> {
let face = match FileRef::new(data).map_err(|error| error.to_string())? {
FileRef::Font(face) => face,
FileRef::Collection(faces) => faces.get(index).map_err(|error| error.to_string())?,
};
let glyf = face.glyf().map_err(|error| error.to_string())?;
let loca = face.loca(None).map_err(|error| error.to_string())?;
let mut glyphs: Vec<_> = std::iter::once(0)
.chain(selected.filter(|&gid| gid != 0))
.map(GlyphId::from)
.collect();
let mut occupied: IntSet<_> = glyphs.iter().copied().collect();
let mut mapping: BTreeMap<_, _> = glyphs.iter().map(|&gid| (gid, gid)).collect();
let mut free = 1;
let mut cursor = 0;
let mut widths = BTreeMap::<_, usize>::new();
// Painted glyphs keep their original CIDs. Components of their
// outlines are appended in discovery order into unused slots.
while let Some(&gid) = glyphs.get(cursor) {
cursor += 1;
let raw = TtfGlyphId(gid.to_u32() as u16);
if let Some(width) = metrics.glyph_hor_advance(raw)
&& width <= metrics.units_per_em()
{
*widths.entry(width).or_default() += 1;
}
let Some(Glyph::Composite(composite)) = loca
.get(gid, &glyf)
.ok_or("invalid outline location in TrueType font")?
.into_glyph()
else {
continue;
};
for (component, _) in composite.component_glyphs_and_flags() {
if component.to_u32() >= u32::from(metrics.number_of_glyphs()) {
return Err("invalid component glyph in TrueType font".into());
}
if let Entry::Vacant(entry) = mapping.entry(component) {
while occupied.contains(GlyphId::new(free)) {
free += 1;
}
let slot = GlyphId::new(free);
occupied.insert(slot);
entry.insert(slot);
glyphs.push(component);
}
}
}
let default_advance = widths
.into_iter()
.max_by_key(|&(width, count)| (count, std::cmp::Reverse(width)))
.map_or(0, |(width, _)| width);
let default_advance = if default_advance == 0 {
metrics.glyph_hor_advance(TtfGlyphId(0)).unwrap_or(0)
} else {
default_advance
};
const TABLES: [&[u8; 4]; 11] = [
b"OS/2", b"head", b"hhea", b"loca", b"maxp", b"name", b"glyf", b"hmtx", b"fpgm",
b"cvt ", b"prep",
];
let drop_tables = face
.table_directory()
.table_records()
.iter()
.map(|record| record.tag())
.filter(|tag| !TABLES.iter().any(|name| *tag == Tag::new(name)))
.collect();
let mut plan = skera::Plan::new_with_glyph_map(
&glyphs.into_iter().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(),
&mapping.into_iter().collect(),
)
.map_err(|error| error.to_string())?;
// Keep the source metadata and all shared TrueType hints intact.
let preserved = [b"OS/2", b"name", b"cvt ", b"fpgm", b"prep"];
plan.set_no_subset_tables(&preserved.into_iter().map(Tag::new).collect());
let bytes = skera::subset_font(&face, &plan).map_err(|error| error.to_string())?;
let glyph_count = usize::from(
read_fonts::FontRef::new(&bytes)
.and_then(|font| font.maxp())
.map_err(|error| error.to_string())?
.num_glyphs(),
);
if glyph_count == 0 {
return Err("empty TrueType subset".into());
}
Ok(Self {
bytes,
glyph_count,
default_advance,
})
}
}
/// XDV describes the entire embedded range, including empty slots and
/// component glyphs. Only the .notdef glyph is omitted from that range.
pub(super) fn cid_set(glyph_count: usize) -> Vec<u8> {
let last = glyph_count - 1;
let mut used = vec![255; last / 8 + 1];
used[0] &= 0x7f;
used[last / 8] &= 255 << (7 - last % 8);
used
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn visible_cid_stays_fixed_and_composite_components_fill_unused_slots() {
let data = include_bytes!("../../../../assets/fonts-subset/LiberationSans-Regular.ttf");
let metrics = Face::parse(data, 0).unwrap();
let cid = metrics.glyph_index('é').unwrap().0;
assert!(cid > 2);
let subset = Subset::new(data, 0, &metrics, std::iter::once(cid)).unwrap();
assert_eq!(subset.glyph_count, usize::from(cid) + 1);
let font = read_fonts::FontRef::new(&subset.bytes).unwrap();
let original = read_fonts::FontRef::new(data).unwrap();
for tag in [Tag::new(b"fpgm"), Tag::new(b"prep"), Tag::new(b"cvt ")] {
assert_eq!(
font.data_for_tag(tag).map(|table| table.as_bytes()),
original.data_for_tag(tag).map(|table| table.as_bytes()),
);
}
let glyf = font.glyf().unwrap();
let loca = font.loca(None).unwrap();
let Some(Glyph::Composite(glyph)) =
loca.get(GlyphId::from(cid), &glyf).unwrap().into_glyph()
else {
panic!("the visible CID must still hold the accented glyph");
};
let components: Vec<_> = glyph
.component_glyphs_and_flags()
.map(|(gid, _)| gid.to_u32())
.collect();
assert_eq!(components, [1, 2]);
assert!(
loca.get(GlyphId::new(3), &glyf)
.unwrap()
.into_glyph()
.is_none()
);
assert_eq!(
cid_set(subset.glyph_count)
.iter()
.map(|b| b.count_ones())
.sum::<u32>(),
u32::from(cid)
);
}
}