diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 9ee0038..0057ff7 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -492,8 +492,12 @@ impl OpenTypeFont { ] } + pub(crate) fn device_embolden(&self) -> i64 { + self.request.embolden_sp(self.size) + } + pub(crate) fn paint_embolden(&self) -> f64 { - let width = self.request.embolden_sp(self.size).max(0) as f64 / 65536.; + let width = self.device_embolden().max(0) as f64 / 65536.; // The XDV PDF device writes the line width to six decimal places. (width * 1_000_000.).round() / 1_000_000. } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 9c24708..b22e21a 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -6,7 +6,7 @@ use std::collections::BTreeSet; use std::collections::{BTreeMap, HashMap, HashSet}; use std::io::Write as _; -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock}; use flate2::Compression; use flate2::write::ZlibEncoder; @@ -732,7 +732,7 @@ fn page_content( cm_codes: &[Option<&BTreeMap>], fallback_ids: &[usize; FACE_COUNT], origin: PageOrigin, - opentype: &BTreeMap, + opentype: &BTreeMap>, font_opacities: &BTreeMap, ) -> Vec { let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits); @@ -2883,11 +2883,14 @@ fn write_pdf( } if !opentype.is_empty() { let open_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item { - DisplayItem::OpenTypeGlyph { font, .. } => Some(font.id), + DisplayItem::OpenTypeGlyph { font, .. } => { + let resource = &opentype[&font.id]; + Some((resource.resource, resource.object)) + } _ => None, }).collect(); - for id in open_fonts { - fonts.push_str(&format!(" /U{} {} 0 R", id.index(), opentype[&id].object)); + for (id, object) in open_fonts { + fonts.push_str(&format!(" /U{} {object} 0 R", id.index())); } } fonts diff --git a/crates/texrra-tex-core/src/pdf_opentype.rs b/crates/texrra-tex-core/src/pdf_opentype.rs index 12a4cb7..0535e09 100644 --- a/crates/texrra-tex-core/src/pdf_opentype.rs +++ b/crates/texrra-tex-core/src/pdf_opentype.rs @@ -12,11 +12,16 @@ use read_fonts::{ }; use rustybuzz::ttf_parser::{Face, GlyphId, RawFace, Tag}; use sha2::{Digest, Sha256}; -use std::{collections::BTreeMap, fmt::Write}; +use std::{ + collections::{BTreeMap, HashMap}, + fmt::Write, + sync::Arc, +}; use subsetter::GlyphRemapper; pub(super) struct EmbeddedFont { pub object: usize, + pub resource: FontId, glyphs: BTreeMap, units: u16, } @@ -64,12 +69,13 @@ impl TextRun { &mut self, output: &mut PageContent, font: FontId, + resource: FontId, size: i64, bp_per_unit: f64, embolden: f64, ) { let size_bp = size as f64 * bp_per_unit; - output.push_str(&format!("/U{} {size_bp:.4} Tf ", font.index())); + output.push_str(&format!("/U{} {size_bp:.4} Tf ", resource.index())); if embolden > 0. { output.push_str(&format!("2 Tr {embolden:.6} w ")); } else if self.emboldened { @@ -126,6 +132,12 @@ fn place_absolute( #[derive(Default)] pub(super) struct UsedFonts<'a>(BTreeMap)>); +struct FontUse<'a> { + font: &'a OpenTypeFont, + glyphs: BTreeMap, + instances: Vec, +} + impl<'a> UsedFonts<'a> { pub(super) fn observe( &mut self, @@ -152,13 +164,38 @@ impl<'a> UsedFonts<'a> { objects: &mut Vec>, compression: u8, options: Option>, - ) -> Result, String> { - self.0 - .into_iter() - .map(|(id, (font, glyphs))| { - write_font(objects, font, glyphs, compression, options).map(|face| (id, face)) - }) - .collect() + ) -> Result>, String> { + let xdv = options.is_some_and(|options| options.xdv_font_unicode); + let mut groups: Vec> = Vec::new(); + let mut resources = HashMap::new(); + for (id, (font, glyphs)) in self.0 { + if xdv { + let raw = RawFace::parse(&font.resource.data, font.face_index()) + .map_err(|error| format!("invalid OpenType font {}: {error}", font.name))?; + // The XDV TrueType font-map key includes device transforms. + // CFF aliases of the same physical face can share the Type0 font. + let transforms = raw.table(Tag::from_bytes(b"CFF ")).is_none().then(|| ( + font.device_transform().map(f64::to_bits), + font.device_embolden(), + )); + let key = (&font.resource.version, font.face_index(), font.is_vertical(), transforms); + let index = *resources.entry(key).or_insert(groups.len()); + if let Some(group) = groups.get_mut(index) { + // XDV's ToUnicode comes from the physical glyph, so this + // union is independent of shaping features or cluster text. + group.glyphs.extend(glyphs); + group.instances.push(id); + continue; + } + } + groups.push(FontUse { font, glyphs, instances: vec![id] }); + } + let mut embedded = BTreeMap::new(); + for group in groups { + let output = Arc::new(write_font(objects, group.font, group.glyphs, compression, options)?); + embedded.extend(group.instances.into_iter().map(|id| (id, output.clone()))); + } + Ok(embedded) } } @@ -458,7 +495,7 @@ fn write_font( || "/Registry (Adobe) /Ordering (Identity) /Supplement 0".to_owned(), CidCff::system_info, ); - let type0_name = if cid_cff.is_some() || (vertical && cff.is_some()) { + let type0_name = if cff.is_some() && (xdv.is_some() || vertical) { format!("{name}-{encoding}") } else { name.clone() @@ -476,6 +513,7 @@ fn write_font( } Ok(EmbeddedFont { object, + resource: font.id, glyphs: embedded, units: face.units_per_em(), }) @@ -619,7 +657,7 @@ impl EmbeddedFont { // Selecting a font ends the string but retains the text // line matrix. Recompute Tm only when its shape changes. output.push_str(">] TJ "); - run.select_font(output, font.id, size, bp_per_unit, embolden); + run.select_font(output, font.id, self.resource, size, bp_per_unit, embolden); if relative && state.matrix == (device, vertical) { run.place_line(output, [x, y], device, vertical, bp_per_unit); } else { @@ -661,7 +699,7 @@ impl EmbeddedFont { offset: 0, emboldened: false, }; - run.select_font(output, font.id, size, bp_per_unit, embolden); + run.select_font(output, font.id, self.resource, size, bp_per_unit, embolden); if start_relative { // At a new text object the XDV device reuses the font // matrix at the page origin, then positions the first line. diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4f00fc5..b6ca317 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,49 @@ 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 的 PDF 字体资源归并 + +同一实际 SimSun TTC 的两个字号在参考驱动中使用同一个 Type0 +字体,倾斜的 TrueType 和 TTC 的另一字面各用独立资源。Latin +Modern 的 CFF 字面即使使用倾斜、伸缩或合成粗体,仍可共用同一 +方向的 Type0 字体。字号和各变体的参数进入实际绘制。 + +原生 XDV 导出按真实资源版本、字面索引和横竖方向分组,TrueType +再核对 XDV 的伸缩、倾斜和粗体值。收集各实例实际绘制的字形后生成 +共用子集及物理字形的 ToUnicode。页面资源字典和文字命令使用同一 +资源名。CFF 的 Type0 名称按参考加方向后缀。 +[XDV 字体映射登记](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/fontmap.c#L1037-L1070) +[CID 字体缓存规则](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/cid.c#L353-L419) + +两页独立用例从 7 份嵌入字体降为与参考一致的 4 份。两份 SimSun、 +一份 NSimSun 和一份 Latin Modern 的字体名及编码相符,10 个 +词框和 144 DPI 灰度图完全一致。原样 xeCJK-example-CJKfntef.tex +使用同一格式、宏包和原始字体复编,SimSun 从两份 Type0 合为一份。 +六页 999 个词框、144 DPI 灰度图和 aux 均与参考一致。LASY6 的 +Type 1 嵌入及编码仍有差异,参考使用内建编码的 Type 1C 子集。 + +三页会话用两个字号共用一个嵌入子集。编辑第 2 页的字符使子集 +重建,复用 1,022 步并重放 3 次宿主调用,局部更新仅含第 2 页。 +独立光栅检查确认第 1、3 页像素保持相同。同路径替换物理字体后, +系统退回字体装载前的检查点,复用前 10 步,三个用字页全部刷新。 +两次修订的 PDF、测量页面、SVG、来源映射和 aux 与独立全量一致。 + +实际输入、参考 PDF、旧版差异和候选记录在 +target/p3-xetex-font-identity。版面与字体的 receipt.json +为 2a54abdc0f48d22e83a5ff92f48edc368b70569c760c31c82dae491d714c9a00。 +增量 revision.log 为 +69bec3a31854d5955e734a2b508f80993041d7e81cea1d66f6019a66907d5d47。 + +七项 XeTeX 共享管线测试通过。新回归同时核对字号共用、不同 +物理路径与倾斜字面分开、独立纵排资源,以及共用 ToUnicode +同时包含两个字号实际用到的字符。 + +下一处传统字体差异在 next-lasy6。原样 xeCJK 使用的槽位 58 +已单独对照原有 LASY6 TFM/PFB。两端单页的灰度图一致,参考 +为 Builtin 的 Type 1C 子集,原生为 Custom 的完整 Type 1。 +保留实际字形、两端产物与参考驱动日志,作为后续通用传统字体 +格式与字节编码对照的起点。 + ### 带段落形状的断行候选合并 用官方 BibLaTeX 索引 .ind 第 55 行保留首个断行差异。原版 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 4ffcba9..afb7efa 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -822,6 +822,79 @@ fn xetex_opentype_font_switch_uses_the_current_text_line_origin() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn xetex_truetype_subsets_follow_the_device_font_identity() { + use lopdf::{Document, Object, content::Content}; + use texrra_tex_core::execution::InputProfile; + + let root = directory("xetex-font-identity"); + let mut job = request(&root); + job.world = WorldConfig::new(&root); + job.input_profile = InputProfile::XeTeX; + let font = include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf"); + fs::write(root.join("face.ttf"), font).unwrap(); + fs::write(root.join("copy.ttf"), font).unwrap(); + fs::write( + root.join("main.tex"), + br#"\catcode123=1 \catcode125=2 +\font\small="[face.ttf]" at 9pt +\font\large="[face.ttf]:+kern" at 14pt +\font\shear="[face.ttf]:slant=.2" at 9pt +\font\copyface="[copy.ttf]" at 9pt +\font\vertical="[face.ttf]:vertical" at 9pt +\shipout\hbox{\small A\kern5pt\large B\kern5pt\shear C\kern5pt\copyface D\kern5pt\vertical E} +\end"#, + ) + .unwrap(); + + let result = NativeCompiler::default().compile(job).unwrap(); + let pdf = Document::load_mem(result.pdf.as_deref().unwrap()).unwrap(); + let page_id = pdf.get_pages()[&1]; + let content = Content::decode(&pdf.get_page_content(page_id).unwrap()).unwrap(); + let selections: Vec<_> = content + .operations + .iter() + .filter(|operation| operation.operator == "Tf") + .map(|operation| &operation.operands) + .collect(); + assert_eq!(selections.len(), 5); + assert_eq!( + selections[0][0].as_name().unwrap(), + selections[1][0].as_name().unwrap() + ); + assert_ne!( + selections[0][1].as_f64().unwrap(), + selections[1][1].as_f64().unwrap() + ); + let fonts = pdf.get_page_fonts(page_id); + let resources: std::collections::BTreeSet<_> = selections + .iter() + .map(|selection| selection[0].as_name().unwrap()) + .collect(); + assert_eq!(resources.len(), 4); + assert_eq!(fonts.len(), resources.len()); + let select = |index: usize| fonts[selections[index][0].as_name().unwrap()]; + let cmap = pdf + .dereference(select(0).get(b"ToUnicode").unwrap()) + .unwrap() + .1 + .as_stream() + .unwrap(); + let bytes = cmap + .decompressed_content() + .unwrap_or_else(|_| cmap.content.clone()); + let unicode = std::str::from_utf8(&bytes).unwrap(); + assert!(unicode.contains("<0041>") && unicode.contains("<0042>"), "{unicode}"); + assert_eq!( + select(4) + .get(b"Encoding") + .and_then(Object::as_name) + .unwrap(), + b"Identity-V" + ); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn xetex_content_special_scopes_graphics_and_emits_marked_content() { use lopdf::{Document, content::Content};