diff --git a/Cargo.lock b/Cargo.lock index 0878d4c..4deb945 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,6 +541,12 @@ dependencies = [ "weezl", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "hayro-ccitt" version = "0.5.0" @@ -570,7 +576,7 @@ dependencies = [ "phf", "rustc-hash", "siphasher", - "skrifa", + "skrifa 0.49.0", ] [[package]] @@ -1090,6 +1096,20 @@ dependencies = [ "yoke", ] +[[package]] +name = "read-fonts" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a39d2f8f681030a7bcbbcf3e8568775ac2393afd51401a2e2133ee89e3953897" +dependencies = [ + "bytemuck", + "foldhash", + "font-types", + "once_cell", + "smallvec", + "yoke", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -1267,6 +1287,20 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skera" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02fa4a4dc04b2d2326e4cfdcf890234a58419d00953e512fbf2823d33965d26b" +dependencies = [ + "foldhash", + "hashbrown", + "read-fonts 0.47.0", + "skrifa 0.50.0", + "thiserror", + "write-fonts", +] + [[package]] name = "skrifa" version = "0.49.0" @@ -1275,7 +1309,20 @@ checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" dependencies = [ "bytemuck", "once_cell", - "read-fonts", + "read-fonts 0.46.0", + "smallvec", + "yoke", +] + +[[package]] +name = "skrifa" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e85ba678a6023a063d0a78c8770f1c166674ef46af13523d05eff67430f79dfe" +dependencies = [ + "bytemuck", + "once_cell", + "read-fonts 0.47.0", "smallvec", "yoke", ] @@ -1536,18 +1583,39 @@ dependencies = [ "lopdf", "md5", "png 0.18.1", - "read-fonts", + "read-fonts 0.47.0", "rusttype", "rustybuzz", "serde", "serde_json", "sha2", + "skera", "stacker", "subsetter", "unicode-bidi", "unicode-normalization", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tiff" version = "0.6.1" @@ -1828,6 +1896,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "write-fonts" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "944049531d52f9002812ea9de23ec8aa4e9577a7bee6869a1d0f297c679817ea" +dependencies = [ + "font-types", + "log", + "read-fonts 0.47.0", +] + [[package]] name = "xmlwriter" version = "0.1.0" diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index c11b5de..22d7040 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -13,8 +13,9 @@ libloading = "=0.8.9" md5 = "0.8" png = "0.18.1" rusttype = "0.8.3" -read-fonts = { version = "=0.46.0", default-features = false } +read-fonts = { version = "=0.47.0", default-features = false } rustybuzz = "=0.20.1" +skera = { version = "=0.10.0", default-features = false } subsetter = { version = "=0.2.3", default-features = false } unicode-bidi = "=0.3.18" serde = { version = "1.0", features = ["derive", "rc"] } diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 4c41dbd..97c5404 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -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, 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::()) + }; + 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, +) -> Result, 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>, font: &OpenTypeFont, @@ -126,40 +221,90 @@ fn write_font( ) -> Result { 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::>() + }); 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)); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 8af9e78..92d5b63 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,41 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### XeTeX 直接排版的 CID CFF 字体 + +XeTeX profile 从选定 OTF 或字体集合字面读取 CFF 的原始 CID 与 +Registry、Ordering、Supplement。PDF 页面码、宽度表和嵌入的子集 +使用同一组 CID。Skera 0.10.0 只对已成形 glyph 所用的 CFF 程序 +做子集化,保留原 CID 字符集、轮廓和提示。PDF 使用实际默认宽度、 +按 CID 排序的宽度组及 Identity-H 的 Type0 名称。GB1、CNS1、 +Japan1 和 Korea1 由标准集合提供 Unicode 映射。自定义集合生成 +实际用到的 ToUnicode 条目。越界显式字形转为 CID 0,布局前进为零。 +[TeX Live CID CFF 导出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/cidtype0.c#L804-L947) +[TeX Live Type0 映射](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/type0.c#L72-L149) +[Skera 0.10.0 的 CFF 子集实现](https://docs.rs/crate/skera/0.10.0/source/src/cff/subset.rs) + +固定 TeX Live XeTeX 和 xdvipdfmx,对照四个 CID 用例及一个 +Latin Modern 名称编码控制。六页的词框和 144 DPI 灰度图一致。 +CID 用例的内容码、PDF/CFF 字符集、默认与显式宽度、实际轮廓及 +Unicode 映射逐项一致。原样 Harano Aji 仍为 Adobe-Japan1-7, +「日本語」使用 CID 3284、3722、1952。真实字体派生子集中 GID 10 +仍出为 CID 3284,无效 GID 65535 出为 CID 0。基线的解压字体 +子集为 2115 字节,参考为 3003 字节。子集前缀和二进制编码有所不同。 +TrueType XeTeX 会话和 pdfTeX 映射 CFF 各一项定向回归通过。 + +四页 XeTeX 会话实际更换一个「日」的轮廓、编辑子文件并恢复字体。 +三次成功修订均只更新第 2 页,子文件编辑及恢复各复用 66 步。 +发布 PDF、测量页面、SVG、来源映射和 aux 与独立全量作业一致。 +缺字体时保留上次成功预览与 aux。证据在 target/p3-xetex-cid-cff。 +receipt.json 为 21fc24faecb9c6aa58bcfea09c334a9b40ff6edd68e537d2857425938225d96f, +revision.log 为 e55443174ab5b28e8f3c03a517b79ba02ae42c59daf4358c4868abba22bfc7d9。 + +下一入口是 XeTeX 的 vertical 字体选项与纵排输出。同一真实 +Harano Aji 的次级探针由参考引擎生成 XDV 与 Identity-V PDF, +原生在实际字体选项处报错。保留源、参考产物、灰度图和诊断在 +target/p3-xetex-cid-cff/next-vertical。后续从真实纵排度量与 +字形选择接入布局和 PDF,覆盖资源失效和增量出页。 + ### 导入 PDF 的 OpenType CFF 设备字体 复用实际 SFNT 名称查找及版本化资源。未嵌入的 Type1 字典先