diff --git a/crates/texrra-tex-core/src/type1_outline.rs b/crates/texrra-tex-core/src/type1_outline.rs index 79c5fce..fa6c0ad 100644 --- a/crates/texrra-tex-core/src/type1_outline.rs +++ b/crates/texrra-tex-core/src/type1_outline.rs @@ -34,7 +34,7 @@ impl<'a> Tokens<'a> { Self { data, at: 0 } } - fn next(&mut self) -> Result, String> { + fn skip_trivia(&mut self) { loop { while self.data.get(self.at).is_some_and(u8::is_ascii_whitespace) { self.at += 1; @@ -51,6 +51,10 @@ impl<'a> Tokens<'a> { break; } } + } + + fn next(&mut self) -> Result, String> { + self.skip_trivia(); let Some(&first) = self.data.get(self.at) else { return Ok(None); }; @@ -92,6 +96,59 @@ impl<'a> Tokens<'a> { .map_err(|_| "unsupported non-UTF8 Type1 private token")?; Ok(Some(token.into())) } + /// Read a FontInfo literal string or name, preserving PostScript bytes. + fn font_info_string(&mut self) -> Result, String> { + self.skip_trivia(); + let start = self.at; + let token = self.required()?; + if self.data[start] != b'(' { + return Ok(token.trim_start_matches('/').as_bytes().to_vec()); + } + + let mut bytes = self.data[start + 1..self.at - 1].iter().copied().peekable(); + let mut output = Vec::new(); + while let Some(byte) = bytes.next() { + let (byte, escaped) = if byte == b'\\' { + (bytes.next().ok_or("truncated PostScript escape")?, true) + } else { + (byte, false) + }; + if byte == b'\r' && bytes.peek() == Some(&b'\n') { + bytes.next(); + } + if matches!(byte, b'\r' | b'\n') { + if !escaped { + output.push(b'\n'); + } + continue; + } + let byte = if escaped { + match byte { + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'b' => 8, + b'f' => 12, + b'0'..=b'7' => { + let mut value = byte - b'0'; + for _ in 0..2 { + let Some(next) = bytes.next_if(|b| (b'0'..=b'7').contains(b)) else { + break; + }; + value = value.wrapping_mul(8).wrapping_add(next - b'0'); + } + value + } + _ => byte, + } + } else { + byte + }; + output.push(byte); + } + Ok(output) + } + /// Locate a top-level file operator without interpreting the font. pub(super) fn after_currentfile(&mut self, operator: &str) -> Result { let mut previous = String::new(); diff --git a/crates/texrra-tex-core/src/type1_outline/cff.rs b/crates/texrra-tex-core/src/type1_outline/cff.rs index d95c1b1..65a57c0 100644 --- a/crates/texrra-tex-core/src/type1_outline/cff.rs +++ b/crates/texrra-tex-core/src/type1_outline/cff.rs @@ -85,7 +85,10 @@ fn operands(output: &mut Vec, values: &[f64]) -> Result<(), String> { Ok(()) } -fn charstring(glyph: Type1Glyph) -> Result<(Vec, Option<[f64; 4]>), String> { +fn charstring( + glyph: Type1Glyph, + default_width: f64, +) -> Result<(Vec, Option<[f64; 4]>), String> { let trace = glyph .cff .expect("Type 2 conversion captures glyph operations"); @@ -102,7 +105,7 @@ fn charstring(glyph: Type1Glyph) -> Result<(Vec, Option<[f64; 4]>), String> } let masks = trace.replaces_hints && !stems.is_empty(); let mut output = Vec::new(); - if glyph.width != 0. { + if glyph.width != default_width { operands(&mut output, &[glyph.width])?; } let horizontal = stems.partition_point(|stem| !stem.vertical); @@ -223,7 +226,7 @@ pub(crate) fn dict_number(output: &mut Vec, value: f64) -> Result<(), String Ok(()) } -fn private_dict(private: &[u8]) -> Result, String> { +fn private_dict(private: &[u8], default_width: f64) -> Result, String> { let mut tokens = Tokens::new(private); let mut previous = None; let mut entries = BTreeMap::new(); @@ -272,7 +275,9 @@ fn private_dict(private: &[u8]) -> Result, String> { .parse::() .map_err(|_| format!("invalid Type1 {token} hint"))?, }; - dict_number(&mut data, number - last)?; + if operator != [12, 14] || number != 0. { + dict_number(&mut data, number - last)?; + } if end.is_none() { break; } @@ -285,7 +290,12 @@ fn private_dict(private: &[u8]) -> Result, String> { } previous = None; } - Ok(entries.into_values().flatten().collect()) + let mut output = entries.into_values().flatten().collect(); + if default_width != 0. { + dict_number(&mut output, default_width)?; + output.push(20); // defaultWidthX + } + Ok(output) } pub(crate) fn index(items: &[impl AsRef<[u8]>]) -> Result, String> { @@ -310,6 +320,42 @@ pub(crate) fn index(items: &[impl AsRef<[u8]>]) -> Result, String> { Ok(output) } +fn string_sid(strings: &mut Vec>, value: &[u8]) -> Result { + if let Some(sid) = + (0..STANDARD_STRING_COUNT).find(|&sid| Sid::new(sid).resolve_standard().ok() == Some(value)) + { + return Ok(sid); + } + let position = strings.iter().position(|existing| existing == value); + let offset = + u16::try_from(position.unwrap_or(strings.len())).map_err(|_| "too many CFF strings")?; + let sid = STANDARD_STRING_COUNT + .checked_add(offset) + .ok_or("too many CFF strings")?; + if position.is_none() { + strings.push(value.to_vec()); + } + Ok(sid) +} + +fn font_info(header: &[u8]) -> Result>, String> { + let mut tokens = Tokens::new(header); + let mut info = BTreeMap::new(); + while let Some(token) = tokens.next()? { + let operator: &'static [u8] = match token.as_str() { + "/version" => &[0], + "/Notice" => &[1], + "/FullName" => &[2], + "/FamilyName" => &[3], + "/Weight" => &[4], + "/Copyright" => &[12, 0], + _ => continue, + }; + info.insert(operator, tokens.font_info_string()?); + } + Ok(info) +} + pub(crate) fn write_type1c( font: &Type1Font, subset_name: &str, @@ -331,9 +377,14 @@ pub(crate) fn write_type1c( } let mut programs = Vec::new(); let mut budget = 2_000_000; + let default_width = if outlines.has_glyph("space") { + outlines.glyph("space", 0, &mut budget, None)?.width + } else { + 500. + }; while let Some(&name) = glyphs.get(programs.len()) { let glyph = outlines.run_glyph(name, 0, &mut budget, None, Some(GlyphTrace::default()))?; - let (program, seac) = charstring(glyph)?; + let (program, seac) = charstring(glyph, default_width)?; programs.push(program); if let Some([_, _, base, accent]) = seac { for code in [base, accent] { @@ -349,13 +400,7 @@ pub(crate) fn write_type1c( let mut sids = BTreeMap::new(); let mut charset = vec![0]; for name in glyphs.into_iter().skip(1) { - let sid = (0..STANDARD_STRING_COUNT) - .find(|&sid| Sid::new(sid).resolve_standard().ok() == Some(name.as_bytes())) - .unwrap_or_else(|| { - let sid = STANDARD_STRING_COUNT + strings.len() as u16; - strings.push(name.as_bytes()); - sid - }); + let sid = string_sid(&mut strings, name.as_bytes())?; charset.extend(sid.to_be_bytes()); sids.insert(name, sid); } @@ -381,19 +426,25 @@ pub(crate) fn write_type1c( encoding.extend(sids[name].to_be_bytes()); } } - let private = private_dict(&private)?; + let private = private_dict(&private, default_width)?; let name = index(&[subset_name])?; - let strings = index(&strings)?; let programs = index(&programs)?; let mut attributes = Vec::new(); for value in font.bbox { dict_number(&mut attributes, f64::from(value))?; } attributes.push(5); // FontBBox - for value in outlines.matrix { - dict_number(&mut attributes, value)?; + for (operator, value) in font_info(&font.program[..font.length1])? { + let sid = string_sid(&mut strings, &value)?; + dict_number(&mut attributes, f64::from(sid))?; + attributes.extend_from_slice(operator); + } + if outlines.matrix != [0.001, 0., 0., 0.001, 0., 0.] { + for value in outlines.matrix { + dict_number(&mut attributes, value)?; + } + attributes.extend([12, 7]); // FontMatrix } - attributes.extend([12, 7]); // FontMatrix if font.is_fixed_pitch { attributes.extend([140, 12, 1]); // isFixedPitch } @@ -401,8 +452,11 @@ pub(crate) fn write_type1c( .italic_angle .parse::() .map_err(|_| "invalid Type1 ItalicAngle")?; - dict_number(&mut attributes, angle)?; - attributes.extend([12, 2]); + if angle != 0. { + dict_number(&mut attributes, angle)?; + attributes.extend([12, 2]); + } + let strings = index(&strings)?; let top = |offset: usize| -> Result, String> { let mut dict = attributes.clone(); let mut position = offset; @@ -541,13 +595,13 @@ pub(crate) fn write_type1_cid( glyphs.iter().filter_map(|(&cid, &glyph)| (cid != 0).then_some((cid, glyph))), ) { let glyph = outlines.run_glyph(glyph, 0, &mut budget, None, Some(GlyphTrace::default()))?; - let (program, seac) = charstring(glyph)?; + let (program, seac) = charstring(glyph, 0.)?; if seac.is_some() { return Err(format!("Type1 font {} uses seac in composite CID {cid}", font.name)); } programs.push((cid, program)); } - let private = private_dict(&private)?; + let private = private_dict(&private, 0.)?; CidCff { registry: "Adobe", ordering: "Identity", @@ -561,3 +615,56 @@ pub(crate) fn write_type1_cid( } .write(name) } + +#[cfg(test)] +mod tests { + use super::*; + use read_fonts::{ + FontData, FontRead, + ps::cff::{dict, v1::Cff}, + }; + + #[test] + fn type1c_keeps_font_info_and_widths() { + let font = + Type1Font::from_pfb(include_bytes!("../../../../assets/fonts/cmtt10.pfb")).unwrap(); + let (program, _) = + write_type1c(&font, "ABCDEF+CMTT10", &BTreeMap::from([(65, "A")])).unwrap(); + let cff = Cff::read(FontData::new(&program)).unwrap(); + let mut notice = None; + let mut default_width = None; + for entry in dict::entries(cff.top_dicts().get(0).unwrap(), None) { + match entry.unwrap() { + dict::Entry::Notice(sid) => notice = cff.string(sid), + dict::Entry::PrivateDictRange(range) => { + default_width = dict::entries(&program[range], None).find_map(|entry| { + match entry.unwrap() { + dict::Entry::DefaultWidthX(width) => Some(width.to_f64()), + _ => None, + } + }); + } + _ => {} + } + } + let notice = notice.unwrap(); + assert!(notice.starts_with(b"Copyright (c)")); + assert!(notice.ends_with(b"Reserved Font Name CMTT10.")); + assert_eq!(default_width, Some(525.)); + + let encoded = |width| { + charstring( + Type1Glyph { + commands: Vec::new(), + width, + cff: Some(GlyphTrace::default()), + }, + 525., + ) + .unwrap() + .0 + }; + assert_eq!(encoded(525.), [14]); + assert_eq!(encoded(0.), [139, 14]); + } +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 454ed61..2648506 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,34 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 XeTeX Type 1C 字体信息与字宽 + +原生从实际 Type 1 字体取 FontInfo 字符串,解析 PostScript 括号 +字符串中的转义和八进制字符。CFF 复用标准字符串 SID,其余字符串 +进入字体的字符串索引。默认字宽取源程序空格字形的实际宽度。 +Type 2 字形字宽等于默认值时省略宽度操作数,显式零宽继续写入。 +[字体信息规则](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/t1_load.c#L1055-L1071) · [默认字宽规则](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/type1.c#L197-L239) + +五种真实字体 LASY6、CMR10、CMSY10、CMTT10、MSBM10 的 FontInfo、 +提示字典和解码后的每个嵌入字形宽度与参考一致。定向见证包括原始 +内置编码和通过真实映射重编码。三项见证的词框与 144 DPI 光栅 +一致,另有一项定向回归验证默认字宽和显式零宽的区别。 +原样 xeCJK 六页、999 个词、词框、144 DPI 光栅、辅助文件以及 +实际嵌入 LASY6 字体的上述属性均与参考一致。LASY6 CFF 流目前 +为 425 字节,参考为 373 字节,程序编码和区段打包仍有差异。 + +原生三页会话替换外部文件中的实际字形后,复用了 1,037 个执行步, +字体子集随使用字形更新。仅第二页刷新,两侧页面光栅一致。 +PDF、绘制列表、SVG、来源映射和辅助文件与独立全量作业一致。 + +下阶段优先验证出页盒在重新执行后仍等价时的布局复用。当前局部 +页面复用要求原始节点列表共享底层存储。原样 NeurIPS 的对应编辑 +预览只刷新一页,但有十页仍需转换。后续按实际节点、资源和来源 +证据判定可复用范围,保持原有全量一致性及延迟门槛。 + +完整证据在 target/p3-xdv-type1c/metadata-widths/。SHA256SUMS 指纹为 +fe00ac172c196672c91e760cd25f7ca7b9ba31e94d24488e37bd393bdf4aa12e。 + ## 2026-11-29 XeTeX TrueType 稀疏 CID 与嵌入子集 XeTeX 的 TrueType 导出保留实际绘制字形的原始 CID。复合字形按