Preserve sparse XDV TrueType glyph subsets
This commit is contained in:
1 parent
9efededf6d
commit
d6e66cad12
5 files changed
+257
-14
No files matched your search
@@ -30,6 +30,7 @@ mod cff_fonts;
|
||||
mod cid_cff;
|
||||
mod legacy_cid;
|
||||
mod truetype_fonts;
|
||||
mod xdv_truetype;
|
||||
#[path = "pdf_opentype.rs"]
|
||||
mod opentype_fonts;
|
||||
#[path = "pdf_opentype_unicode.rs"]
|
||||
@@ -2496,10 +2497,15 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
}
|
||||
let pdf_version = pages
|
||||
.first()
|
||||
.and_then(|page| page.pdf.as_ref())
|
||||
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
|
||||
let opentype = opentype_used.write(
|
||||
&mut objects,
|
||||
final_compression.unwrap_or(0).clamp(0, 9) as u8,
|
||||
unicode,
|
||||
pdf_version.0 < 2,
|
||||
)?;
|
||||
for plan in paint_lists.iter().filter_map(|page| page.pdf_space_plan.as_ref()) {
|
||||
for id in &plan.in_font {
|
||||
@@ -2973,10 +2979,6 @@ fn write_pdf(
|
||||
let mut xdv_annotations = Vec::new();
|
||||
// Each triple records the bead, its page, and its rectangle object.
|
||||
let mut thread_rings: BTreeMap<u32, Vec<(usize, usize, usize)>> = BTreeMap::new();
|
||||
let pdf_version = pages
|
||||
.first()
|
||||
.and_then(|page| page.pdf.as_ref())
|
||||
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
|
||||
let mut unwritten_color_spaces = BTreeMap::new();
|
||||
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression, auxiliary, imports)| {
|
||||
let physical = |number: u32| device_objects[&number] as usize;
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Embedding for glyphs selected by the native OpenType shaper.
|
||||
use super::{PageContent, native_pdf_name, objects, opentype_unicode, to_unicode_map};
|
||||
use super::{PageContent, native_pdf_name, objects, opentype_unicode, to_unicode_map, xdv_truetype};
|
||||
use crate::{
|
||||
execution::FontId,
|
||||
opentype::{OpenTypeFont, vertical::PdfMetrics},
|
||||
@@ -164,6 +164,7 @@ impl<'a> UsedFonts<'a> {
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
compression: u8,
|
||||
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
|
||||
write_cid_set: bool,
|
||||
) -> Result<BTreeMap<FontId, Arc<EmbeddedFont>>, String> {
|
||||
let xdv = options.is_some_and(|options| options.xdv_font_unicode);
|
||||
let mut groups: Vec<FontUse<'a>> = Vec::new();
|
||||
@@ -192,7 +193,9 @@ impl<'a> UsedFonts<'a> {
|
||||
}
|
||||
let mut embedded = BTreeMap::new();
|
||||
for group in groups {
|
||||
let output = Arc::new(write_font(objects, group.font, group.glyphs, compression, options)?);
|
||||
let output = Arc::new(write_font(
|
||||
objects, group.font, group.glyphs, compression, options, write_cid_set,
|
||||
)?);
|
||||
embedded.extend(group.instances.into_iter().map(|id| (id, output.clone())));
|
||||
}
|
||||
Ok(embedded)
|
||||
@@ -300,6 +303,7 @@ fn write_font(
|
||||
glyphs: BTreeMap<u16, &str>,
|
||||
compression: u8,
|
||||
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
|
||||
write_cid_set: bool,
|
||||
) -> Result<EmbeddedFont, String> {
|
||||
let face = font.face()?;
|
||||
let xdv = options.filter(|options| options.xdv_font_unicode);
|
||||
@@ -332,6 +336,12 @@ fn write_font(
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>()
|
||||
});
|
||||
let true_type = xdv.is_some() && face.raw_face().table(Tag::from_bytes(b"glyf")).is_some();
|
||||
let ttf_subset = true_type.then(|| {
|
||||
let selected = glyphs.keys().copied().filter(|&gid| gid < face.number_of_glyphs());
|
||||
xdv_truetype::Subset::new(&font.resource.data, font.face_index(), &face, selected)
|
||||
.map_err(|error| format!("failed to embed XDV TrueType font {}: {error}", font.name))
|
||||
}).transpose()?;
|
||||
let mut remapper = GlyphRemapper::new();
|
||||
let mut fingerprint = Sha256::new();
|
||||
fingerprint.update(font.resource.version.sha256.as_bytes());
|
||||
@@ -339,11 +349,14 @@ fn write_font(
|
||||
let mut widths = String::new();
|
||||
let mut cid_widths = BTreeMap::new();
|
||||
let mut vertical_widths = BTreeMap::new();
|
||||
let device_cid_metrics = cid_cff.is_some() || vertical;
|
||||
let device_cid_metrics = cid_cff.is_some() || vertical || true_type;
|
||||
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 default_advance = ttf_subset.as_ref().map_or_else(
|
||||
|| face.glyph_hor_advance(GlyphId(0)).unwrap_or(0),
|
||||
|subset| subset.default_advance,
|
||||
);
|
||||
let default_width = width(i64::from(default_advance));
|
||||
for (glyph, source) in glyphs {
|
||||
let outside_face = glyph >= face.number_of_glyphs();
|
||||
@@ -357,7 +370,7 @@ fn write_font(
|
||||
font.name
|
||||
)
|
||||
})?;
|
||||
let subset_id = remapper.remap(glyph);
|
||||
let subset_id = if true_type { glyph } else { 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)
|
||||
@@ -422,7 +435,11 @@ fn write_font(
|
||||
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 = if cid_cff.is_some() {
|
||||
let cid_set = ttf_subset.as_ref().filter(|_| write_cid_set)
|
||||
.map(|subset| xdv_truetype::cid_set(subset.glyph_count));
|
||||
let subset = if let Some(subset) = ttf_subset {
|
||||
subset.bytes
|
||||
} else if cid_cff.is_some() {
|
||||
subset_cid_cff(&font.resource.data, font.face_index(), &font.name, remapper.remapped_gids())?
|
||||
} else {
|
||||
subsetter::subset(&font.resource.data, font.face_index(), &remapper)
|
||||
@@ -460,6 +477,7 @@ fn write_font(
|
||||
} else {
|
||||
format!(" /ToUnicode {} 0 R", object + 4)
|
||||
};
|
||||
let cid_set_id = cid_set.as_ref().map(|_| font_file + 1 + usize::from(!unicode_reference.is_empty()));
|
||||
let mut width_entries = if device_cid_metrics {
|
||||
let mut entries = format!(" /DW {default_width}");
|
||||
if !cid_widths.is_empty() {
|
||||
@@ -508,11 +526,14 @@ fn write_font(
|
||||
objects.push(format!(
|
||||
"<< /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(font_descriptor(&face, &name, file_key, font_file, cid_set_id));
|
||||
objects.push(objects::stream(&file_options, program, compression));
|
||||
if !unicode_reference.is_empty() {
|
||||
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
|
||||
}
|
||||
if let Some(cid_set) = cid_set {
|
||||
objects.push(objects::stream("", &cid_set, compression));
|
||||
}
|
||||
Ok(EmbeddedFont {
|
||||
object,
|
||||
resource: font.id,
|
||||
@@ -521,7 +542,9 @@ fn write_font(
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_file: usize) -> Vec<u8> {
|
||||
pub(super) fn font_descriptor(
|
||||
face: &Face<'_>, name: &str, file_key: &str, font_file: usize, cid_set: Option<usize>,
|
||||
) -> Vec<u8> {
|
||||
// XDV uses the OS/2 typographic values for PDF metadata independently
|
||||
// of the metrics selected by the layout engine.
|
||||
let os2 = face
|
||||
@@ -572,7 +595,11 @@ pub(super) fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_
|
||||
for byte in os2.map_or(&[0; 12][..], |table| &table[30..42]) {
|
||||
write!(descriptor, "{byte:02X}").unwrap();
|
||||
}
|
||||
write!(descriptor, "> >> /{file_key} {font_file} 0 R >>").unwrap();
|
||||
write!(descriptor, "> >> /{file_key} {font_file} 0 R").unwrap();
|
||||
if let Some(cid_set) = cid_set {
|
||||
write!(descriptor, " /CIDSet {cid_set} 0 R").unwrap();
|
||||
}
|
||||
descriptor.push_str(" >>");
|
||||
descriptor.into_bytes()
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,36 @@
|
||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||
|
||||
## 2026-11-29 XeTeX TrueType 稀疏 CID 与嵌入子集
|
||||
|
||||
XeTeX 的 TrueType 导出保留实际绘制字形的原始 CID。复合字形按
|
||||
发现顺序收集依赖组件,并把组件放入空闲槽位。子集保留实际字体
|
||||
的元数据和 TrueType 提示表。导出按真实保留字宽选取默认度量,
|
||||
PDF 2.0 之前写入 CIDSet,PDF 2.0 略过该项。
|
||||
[CIDType2 写出规则](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/cidtype2.c#L1018-L1049) · [复合字形与字宽](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/tt_glyf.c#L280-L405)
|
||||
|
||||
原样 xeCJK 六页的 999 个词、词框、144 DPI 光栅和 aux 与原版
|
||||
一致。SimSun 和 SimHei 分别保留 21,950 和 8,637 个字形槽位,
|
||||
304 和 3 个实际轮廓、元数据和提示表内容、默认字宽及 CIDSet
|
||||
均匹配。原生 PDF 头仍为 1.4,参考为 1.5。嵌入字体字节量仍有
|
||||
差异,主要来自原生子集使用完整字宽记录,参考压缩相同末尾字宽。
|
||||
另用原始 Liberation Sans 的复合字形主动声明 PDF 1.5 和 2.0,
|
||||
两种版本的光栅、字宽和 CIDSet 有无均与参考一致,1.5 的 CIDSet
|
||||
逐字节相同。复合组件编号和提示表的定向测试通过。
|
||||
|
||||
四页 XeTeX 会话从子文件替换实际字形,随后制造错误并恢复。三次
|
||||
成功编辑均只发布第二页的补丁,实际字体 CIDSet 随编辑变化。
|
||||
PDF、页面、SVG、来源映射和 aux 与各自独立全量一致,失败时
|
||||
保留最后一次预览。正式编辑到可见页面的延迟仍待统一验收。
|
||||
|
||||
功能批次优先处理影响项目迁移的通用缺口,阶段验证使用最少可区分
|
||||
新旧行为的实跑。下一批 Type 1C 以实际 LASY6 的 FontInfo 和默认
|
||||
字宽为首个见证。SFNT 字宽压缩和未显式声明时的 PDF 版本差异
|
||||
进入后续组合审计。完整模板矩阵和实时性保留既定门槛。
|
||||
|
||||
完整证据在 target/p3-xdv-ttf-subsets/。SHA256SUMS 指纹为
|
||||
b9e5dc95fc8affc8903ff9c9eee308db8c4808d952e6d33656cdd85c300daeff。
|
||||
|
||||
## 2026-11-29 XDV 设备字宽与原样 NeurIPS 导出
|
||||
|
||||
XDV 设备根据实际 TFM 的 fixword 舍入得到字形前进量,累加到
|
||||
|
||||
Reference in new issue
Block a user