diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 7e2c63a..1eb182d 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -14,12 +14,14 @@ use std::{ }; mod cff; mod composite; +mod composite_type1; mod device_type1; mod map; mod sfd; mod truetype; mod virtual_paint; pub use cff::OpenTypeCffProgram; +pub use composite_type1::CompositeType1Program; pub use device_type1::DeviceType1Program; pub use truetype::TrueTypeProgram; pub(crate) use truetype::cid_width; @@ -90,6 +92,7 @@ impl NativeFontPaint { match &self.program { NativeFontProgram::TrueType(program) => program.composite.as_ref(), NativeFontProgram::OpenTypeCff(program) => program.composite.as_ref(), + NativeFontProgram::CompositeType1(program) => Some(&program.mapping), _ => None, } } @@ -118,7 +121,8 @@ impl NativeFontPaint { NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1)) .map(|version| (version, font.transform)), NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_) - | NativeFontProgram::OpenTypeCff(_) | NativeFontProgram::DeviceType1(_) => None, + | NativeFontProgram::OpenTypeCff(_) | NativeFontProgram::DeviceType1(_) + | NativeFontProgram::CompositeType1(_) => None, } } } @@ -129,6 +133,7 @@ pub enum NativeFontProgram { Pk(crate::pk_font::PkFontProgram), TrueType(TrueTypeProgram), OpenTypeCff(OpenTypeCffProgram), + CompositeType1(CompositeType1Program), DeviceType1(DeviceType1Program), } impl NativeFontProgram { @@ -138,6 +143,7 @@ impl NativeFontProgram { Self::Pk(p) => &p.name, Self::TrueType(p) => &p.name, Self::OpenTypeCff(p) => &p.name, + Self::CompositeType1(p) => &p.font.name, Self::DeviceType1(p) => &p.name, } } @@ -668,16 +674,14 @@ fn resolve_physical_fonts( direct_resolved.insert(id, Arc::new(paint)); continue; } - if let Some(encoding) = &outline.xdv_encoding - && (outline.encoding.is_none() || files.optional_font_file( - ResourceKind::CMap, &encoding.name, &outline.from.to_string_lossy(), - )?.is_some()) - { - return Err(format!( - "native XDV composite encoding {} requires a TrueType or OpenType CFF program: {}", encoding.name, font.name, - )); - } let file = outline.type1_file(&font.name)?; + if let Some(encoding) = &outline.xdv_encoding + && let Some(codes) = composite::Codes::load(encoding, outline, files)? + { + let paint = composite_type1::resolve(files, font_cache, outline, file, slots, encoding, codes)?; + direct_resolved.insert(id, Arc::new(paint)); + continue; + } let version = outline.version.as_ref(); let transform = outline.transform; let key = ( @@ -790,7 +794,8 @@ fn resolve_physical_fonts( NativeFontProgram::Type1(_) | NativeFontProgram::DeviceType1(_) | NativeFontProgram::TrueType(_) - | NativeFontProgram::OpenTypeCff(_) => { + | NativeFontProgram::OpenTypeCff(_) + | NativeFontProgram::CompositeType1(_) => { crate::type1::glyph_unicode_text(&p.encoding[*slot as usize]) .and_then(|text| text.chars().next()) .unwrap_or('�') diff --git a/crates/texrra-tex-core/src/native_font/composite.rs b/crates/texrra-tex-core/src/native_font/composite.rs index c64001b..56abf00 100644 --- a/crates/texrra-tex-core/src/native_font/composite.rs +++ b/crates/texrra-tex-core/src/native_font/composite.rs @@ -15,18 +15,18 @@ pub(crate) struct CompositeFont { pub(crate) registry: String, pub(crate) ordering: String, pub(crate) supplement: u32, - slots: Vec, + pub(super) slots: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) vertical: Option<[i32; 2]>, } #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] -struct CompositeSlot { - cid: u16, - advance: u32, - unicode: Option, +pub(super) struct CompositeSlot { + pub(super) cid: u16, + pub(super) advance: u32, + pub(super) unicode: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - vertical: Option<[i32; 3]>, + pub(super) vertical: Option<[i32; 3]>, } impl CompositeFont { diff --git a/crates/texrra-tex-core/src/native_font/composite_type1.rs b/crates/texrra-tex-core/src/native_font/composite_type1.rs new file mode 100644 index 0000000..c3e8219 --- /dev/null +++ b/crates/texrra-tex-core/src/native_font/composite_type1.rs @@ -0,0 +1,131 @@ +//! Resolve XDV character codes through an actual Type 1 CharStrings dictionary. +use super::{ + NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource, + composite::{Codes, CompositeFont, CompositeSlot}, + map::{MapEntry, XdvEncoding}, +}; +use crate::{ + execution::SourceProvider, pdf::opentype_unicode::XdvGlyphNames, resources::ResourceKind, + type1::Type1Font, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct CompositeType1Program { + pub(crate) font: Arc, + pub(crate) mapping: CompositeFont, + pub(crate) default_width: u32, +} + +pub(super) fn resolve( + files: &mut impl SourceProvider, + cache: &NativeFontCache, + outline: &MapEntry, + file: &str, + slots: BTreeSet, + encoding: &XdvEncoding, + codes: Codes, +) -> Result { + let from = outline.from.to_string_lossy(); + let resource = actual_resource(files, ResourceKind::Type1, file, &from)?; + // Slant and extension belong to the XDV text matrix for these fonts. + let decoded = cache.type1(&resource, Default::default())?; + let mut resources: Vec<_> = outline.version.iter().cloned().collect(); + let program_index = Some(resources.len()); + resources.push(resource.version); + let (glyph_text, lists) = XdvGlyphNames::load_tracked(files, &from)?; + resources.extend(lists); + if let Codes::Custom(map) = &codes { + resources.extend(map.resources.iter().cloned()); + } + + let outlines = &decoded.outlines; + let order = outlines.glyph_order(); + let mut by_scalar = BTreeMap::new(); + let text: Vec<_> = order.iter().map(|name| glyph_text.text(name)).collect(); + if matches!(codes, Codes::Unicode) { + for (cid, name) in order.iter().enumerate().skip(1) { + if !name.contains('.') { + for ch in glyph_text.type1_codes(name) { + by_scalar.insert(ch, cid as u16); + } + } + } + } + let vertical = encoding.name == "Identity-V" + || (matches!(codes, Codes::Unicode) && encoding.vertical) + || matches!(&codes, Codes::Custom(map) if map.is_vertical()); + let mut names = Vec::with_capacity(256); + let mut cells = Vec::with_capacity(256); + let mut glyph_paths = BTreeMap::new(); + let mut measured = BTreeMap::new(); + let (_, default_width) = outlines.glyph_path_and_width(".notdef")?; + let width = |value: i64| { + value + .saturating_add(5) + .div_euclid(10) + .clamp(0, i64::from(u32::MAX)) as u32 + }; + for slot in 0..=255u8 { + let code = encoding.prefix | u32::from(slot); + let cid = match &codes { + Codes::Unicode => char::from_u32(code).and_then(|ch| by_scalar.get(&ch).copied()), + Codes::Identity => u16::try_from(code).ok(), + Codes::Custom(map) => map.cid(code), + } + .filter(|&cid| usize::from(cid) < order.len()) + .unwrap_or(0); + let name = &order[usize::from(cid)]; + let mut cell = CompositeSlot { + cid, + unicode: text[usize::from(cid)].clone(), + ..Default::default() + }; + if slots.contains(&slot) { + let (path, advance) = match measured.entry(cid) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + entry.insert(outlines.glyph_path_and_width(name)?) + } + }; + glyph_paths.insert(slot, path.clone()); + cell.advance = width(*advance); + } + cells.push(cell); + names.push(name.clone()); + } + let mapping = CompositeFont { + registry: "Adobe".into(), + ordering: "Identity".into(), + supplement: 0, + slots: cells, + vertical: vertical.then_some([1000, 880]), + }; + Ok(NativeFontPaint { + program: NativeFontProgram::CompositeType1(CompositeType1Program { + font: Arc::clone(&decoded.program), + mapping, + default_width: width(default_width), + }), + encoding: names, + glyph_paths, + bbox: decoded.bbox, + stem_v: decoded.stem_v, + subset: true, + descriptor_flags: None, + xdv_descriptor: Some( + decoded + .xdv_descriptor + .get_or_init(|| outlines.xdv_descriptor()) + .clone()?, + ), + xdv_widths: BTreeMap::new(), + xdv_matrix: outline.xdv_text_matrix(), + xdv_unicode: None, + resources, + program_index, + }) +} diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index c43d354..1339dcb 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1924,7 +1924,9 @@ fn write_native_font( return Ok(pk_fonts::write_font(objects, face.id, pk, used, compression, target)); } if paint.legacy_cid_font().is_some() { - return legacy_cid::write(objects, paint, used.keys().copied(), compression, subset_tags, target); + return legacy_cid::write( + objects, paint, face.metrics(), used.keys().copied(), compression, subset_tags, target, + ); } let id = target.unwrap_or_else(|| { objects.push(Vec::new()); @@ -2031,7 +2033,7 @@ fn write_native_font( } ("Type1", descriptor, name, format!("{width_object} 0 R"), encoding, mapped_encoding.is_some()) } - NativeFontProgram::Pk(_) => unreachable!(), + NativeFontProgram::Pk(_) | NativeFontProgram::CompositeType1(_) => unreachable!(), }; let unicode = objects.len() + 1; let cmap = if let Some(texts) = &paint.xdv_unicode { @@ -2527,6 +2529,7 @@ fn write_pdf( let face_index = match &paint.program { crate::native_font::NativeFontProgram::TrueType(program) => program.face_index, crate::native_font::NativeFontProgram::OpenTypeCff(program) => program.face_index, + crate::native_font::NativeFontProgram::CompositeType1(_) => 0, _ => unreachable!("legacy CID program"), }; *cid_owners.entry((paint.program_version()?, face_index, composite)).or_insert(id) @@ -2559,7 +2562,10 @@ fn write_pdf( { return Err("shared PDF font has inconsistent output encoding or program".into()); } - if paint.xdv_descriptor.is_some() && xdv_font_aliases.contains_key(&id) { + if paint.legacy_cid_font().is_none() + && paint.xdv_descriptor.is_some() + && xdv_font_aliases.contains_key(&id) + { // Separate map entries can resolve to the same physical // program with disjoint sets of measured glyph widths. for slot in used.keys() { diff --git a/crates/texrra-tex-core/src/pdf/cid_cff.rs b/crates/texrra-tex-core/src/pdf/cid_cff.rs index 8f46bee..33c6b14 100644 --- a/crates/texrra-tex-core/src/pdf/cid_cff.rs +++ b/crates/texrra-tex-core/src/pdf/cid_cff.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use crate::{ native_font::{NativeFontPaint, OpenTypeCffProgram}, - type1_outline::cff::{dict_long, dict_number, index}, + type1_outline::cff::{CidCff, index}, }; pub(super) fn subset( @@ -56,20 +56,12 @@ pub(super) fn subset( charstrings.ok_or("missing CFF charstrings")? )?)) .map_err(|_| invalid())?; - let mut programs = vec![source_programs.get(0).ok_or("missing CFF .notdef")?]; - let mut charset = vec![0]; // Format 0. Each entry is the actual CID, in CharStrings order. + let mut programs = vec![(0, source_programs.get(0).ok_or("missing CFF .notdef")?)]; for (&cid, &glyph) in glyphs { if cid != 0 { - charset.extend(cid.to_be_bytes()); - programs.push( - source_programs - .get(usize::from(glyph)) - .ok_or_else(invalid)?, - ); + programs.push((cid, source_programs.get(usize::from(glyph)).ok_or_else(invalid)?)); } } - let count = u16::try_from(programs.len()).map_err(|_| "too many glyphs for CFF1")?; - let programs = index(&programs)?; let mut private_bytes = Vec::new(); let mut private_size = 0; if let Some(range) = private { @@ -98,78 +90,18 @@ pub(super) fn subset( .map(|i| globals.get(i).ok_or_else(invalid)) .collect::, _>>()?, )?; - let name = index(&[name])?; - let strings = index(&[mapping.registry.as_bytes(), mapping.ordering.as_bytes()])?; - let fd_select = vec![0; usize::from(count) + 1]; - let long = |out: &mut Vec, value: usize| -> Result<(), String> { - dict_long( - out, - i32::try_from(value).map_err(|_| "CFF offset overflow")?, - ); - Ok(()) - }; - let font_dict = |private_offset| -> Result, String> { - let mut dict = Vec::new(); - long(&mut dict, private_size)?; - long(&mut dict, private_offset)?; - dict.push(18); - index(&[dict]) - }; - let mut attributes = Vec::new(); - // CFF1 reserves SIDs 0 through 390 for standard strings. - long(&mut attributes, 391)?; - long(&mut attributes, 392)?; - long(&mut attributes, mapping.supplement as usize)?; - attributes.extend([12, 30]); // ROS let bbox = face.global_bounding_box(); - for value in [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] { - dict_number(&mut attributes, f64::from(value))?; - } - attributes.push(5); let matrix = face.tables().cff.ok_or("missing CFF outlines")?.matrix(); - for value in [ - matrix.sx, matrix.ky, matrix.kx, matrix.sy, matrix.tx, matrix.ty, - ] { - dict_number(&mut attributes, f64::from(value))?; + CidCff { + registry: &mapping.registry, + ordering: &mapping.ordering, + supplement: mapping.supplement, + bbox: [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max].map(f64::from), + matrix: [matrix.sx, matrix.ky, matrix.kx, matrix.sy, matrix.tx, matrix.ty].map(f64::from), + programs: &programs, + globals: &globals, + private: &private_bytes, + private_size, } - attributes.extend([12, 7]); // FontMatrix - long( - &mut attributes, - usize::from(glyphs.last_key_value().map_or(0, |(&cid, _)| cid)) + 1, - )?; - attributes.extend([12, 34]); // CIDCount - let top = |base| -> Result, String> { - let programs_offset = base + charset.len(); - let select_offset = programs_offset + programs.len(); - let fd_offset = select_offset + fd_select.len(); - let mut top = attributes.clone(); - for (offset, opcode) in [ - (base, &[15][..]), - (programs_offset, &[17][..]), - (select_offset, &[12, 37][..]), - (fd_offset, &[12, 36][..]), - ] { - long(&mut top, offset)?; - top.extend(opcode); - } - index(&[top]) - }; - let offset = 4 + name.len() + top(0)?.len() + strings.len() + globals.len(); - let private_offset = - offset + charset.len() + programs.len() + fd_select.len() + font_dict(0)?.len(); - let mut output = vec![1, 0, 4, 4]; - for part in [ - name, - top(offset)?, - strings, - globals, - charset, - programs, - fd_select, - font_dict(private_offset)?, - private_bytes, - ] { - output.extend(part); - } - Ok(output) + .write(name) } diff --git a/crates/texrra-tex-core/src/pdf/legacy_cid.rs b/crates/texrra-tex-core/src/pdf/legacy_cid.rs index 3518cc9..710ce76 100644 --- a/crates/texrra-tex-core/src/pdf/legacy_cid.rs +++ b/crates/texrra-tex-core/src/pdf/legacy_cid.rs @@ -9,6 +9,7 @@ use std::collections::BTreeSet; pub(super) fn write( objects: &mut Vec>, paint: &NativeFontPaint, + metrics: &crate::tfm::TfmMetrics, slots: impl Iterator, compression: u8, subset_tags: &mut BTreeSet, @@ -19,21 +20,30 @@ pub(super) fn write( use subsetter::GlyphRemapper; let mapping = paint.legacy_cid_font().expect("composite program"); - let (name, face) = match &paint.program { - NativeFontProgram::TrueType(program) => (&program.name, program.face()?), - NativeFontProgram::OpenTypeCff(program) => (&program.name, program.face()?), + let name = paint.program.name(); + let face = match &paint.program { + NativeFontProgram::TrueType(program) => Some(program.face()?), + NativeFontProgram::OpenTypeCff(program) => Some(program.face()?), + NativeFontProgram::CompositeType1(_) => None, _ => unreachable!("legacy CID program"), }; let mut vertical_widths = BTreeMap::new(); let mut glyphs = BTreeMap::new(); let mut unicode = BTreeMap::new(); + let mut advances = BTreeMap::new(); + let mut type1_names = BTreeMap::new(); for slot in slots { let cid = mapping.cid(slot); let glyph = match &paint.program { NativeFontProgram::TrueType(program) => program.glyph_id(slot), NativeFontProgram::OpenTypeCff(program) => program.composite_glyphs[usize::from(slot)], + NativeFontProgram::CompositeType1(_) => { + type1_names.insert(cid, paint.encoding[usize::from(slot)].as_str()); + cid + } _ => unreachable!("legacy CID program"), }; + advances.insert(cid, mapping.advance(slot)); if let Some(metrics) = mapping.vertical_override(slot) { vertical_widths.insert(cid, metrics); } @@ -61,8 +71,10 @@ pub(super) fn write( let max = usize::from(glyphs.keys().next_back().copied().unwrap_or(0)); let mut cid_to_gid = vec![0; (max + 1) * 2]; let mut cid_set = vec![0; max / 8 + 1]; - let width = |glyph| cid_width(&face, glyph); - let default = width(0); + let default = match &paint.program { + NativeFontProgram::CompositeType1(program) => program.default_width, + _ => cid_width(face.as_ref().expect("sfnt CID font"), 0), + }; let mut widths = String::new(); let mut previous: Option = None; let mut identity = true; @@ -74,7 +86,7 @@ pub(super) fn write( cid_set[index / 8] |= 1 << (7 - index % 8); } identity &= cid == subset_id; - let advance = width(glyph); + let advance = advances[&cid]; if advance == default { continue; } @@ -119,7 +131,13 @@ pub(super) fn write( "CIDFontType0", "FontFile3", "/Subtype /CIDFontType0C".to_owned(), - super::cid_cff::subset(program, &face, paint, &glyphs, &name)?, + super::cid_cff::subset(program, face.as_ref().expect("CFF face"), paint, &glyphs, &name)?, + ), + NativeFontProgram::CompositeType1(program) => ( + "CIDFontType0", + "FontFile3", + "/Subtype /CIDFontType0C".to_owned(), + crate::type1_outline::cff::write_type1_cid(&program.font, &name, &type1_names)?, ), _ => unreachable!("legacy CID program"), }; @@ -132,7 +150,15 @@ pub(super) fn write( let cid_set_id = objects.len() + 1; objects.push(objects::stream("", &cid_set, compression)); let descriptor = objects.len() + 1; - let mut contents = super::opentype_fonts::font_descriptor(&face, &name, file_key, fontfile); + let mut contents = match &paint.program { + NativeFontProgram::CompositeType1(program) => { + let parameters = super::native_type1_parameters(&program.font, paint, metrics); + 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, + ), + }; assert!(contents.ends_with(b" >>")); contents.truncate(contents.len() - 3); contents.extend_from_slice(format!(" /CIDSet {cid_set_id} 0 R >>").as_bytes()); diff --git a/crates/texrra-tex-core/src/pdf_opentype_unicode.rs b/crates/texrra-tex-core/src/pdf_opentype_unicode.rs index db63ece..56361a7 100644 --- a/crates/texrra-tex-core/src/pdf_opentype_unicode.rs +++ b/crates/texrra-tex-core/src/pdf_opentype_unicode.rs @@ -1,6 +1,9 @@ //! Unicode recovery for OpenType glyph IDs carried by native XDV runs. -use crate::{execution::SourceProvider, resources::ResourceKind}; +use crate::{ + execution::SourceProvider, + resources::{ResourceKind, ResourceVersion}, +}; use read_fonts::{ FontData, FontRead, tables::cmap::{Cmap, CmapIterLimits, CmapSubtable, PlatformId}, @@ -13,15 +16,25 @@ use rustybuzz::ttf_parser::{ use std::collections::{BTreeMap, BTreeSet}; /// Optional Adobe Glyph List resources from the current job's font map search path. -pub struct XdvGlyphNames(BTreeMap); +pub struct XdvGlyphNames(BTreeMap>); impl XdvGlyphNames { pub fn load(files: &mut impl SourceProvider, from: &str) -> Result { - let mut names = BTreeMap::new(); + Self::load_tracked(files, from).map(|(names, _)| names) + } + + pub(crate) fn load_tracked( + files: &mut impl SourceProvider, + from: &str, + ) -> Result<(Self, Vec), String> { + let mut names: BTreeMap> = BTreeMap::new(); + let mut versions = Vec::new(); for list in ["texglyphlist.txt", "pdfglyphlist.txt", "glyphlist.txt"] { let Some(resource) = files.optional_font_file(ResourceKind::Map, list, from)? else { continue; }; + let resource = crate::native_font::verify_resource(resource, ResourceKind::Map, list)?; + versions.push(resource.version); for line in resource.data.split(|byte| *byte == b'\n') { let Ok(line) = std::str::from_utf8(line) else { continue; @@ -42,11 +55,31 @@ impl XdvGlyphNames { .take(16) .collect(); if !scalars.is_empty() { - names.entry(name.trim().to_owned()).or_insert(scalars); + let entries = names.entry(name.trim().to_owned()).or_default(); + if !entries.contains(&scalars) { + entries.push(scalars); + } } } } - Ok(Self(names)) + Ok((Self(names), versions)) + } + + pub(crate) fn text(&self, name: &str) -> Option { + glyph_text(name, Some(self)).or_else(|| crate::type1::glyph_unicode_text(name)) + } + + pub(crate) fn type1_codes(&self, name: &str) -> impl Iterator { + // Direct Unicode names are interpreted before looking at AGL aliases. + let direct = glyph_text(name, None).or_else(|| { + (!self.0.contains_key(name)).then(|| crate::type1::glyph_unicode_text(name)).flatten() + }); + let entries = direct.is_none().then(|| self.0.get(name)).flatten(); + direct.into_iter().chain(entries.into_iter().flatten().cloned()).filter_map(|text| { + let mut chars = text.chars(); + let first = chars.next()?; + chars.next().is_none().then_some(first) + }) } } @@ -263,7 +296,7 @@ pub(super) fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option>>, glyphs: BTreeMap>, + glyph_order: Vec, matrix: [f64; 6], std_vw: Option, force_bold: bool, @@ -252,6 +253,7 @@ impl Type1Outlines { let mut tokens = Tokens::new(private); let (mut len_iv, mut subrs, mut glyphs, mut in_subrs) = (4i32, Vec::new(), BTreeMap::new(), false); + let mut glyph_order = vec![".notdef".to_owned()]; let mut std_vw = None; let mut force_bold = false; while let Some(token) = tokens.next()? { @@ -353,6 +355,9 @@ impl Type1Outlines { } let n = tokens.number()?; let bytes = tokens.binary(n)?; + if name != ".notdef" && !glyphs.contains_key(name) { + glyph_order.push(name.to_owned()); + } glyphs.insert(name.into(), bytes); if glyphs.len() > count { return Err("Type1 CharStrings dictionary capacity exceeded".into()); @@ -386,6 +391,7 @@ impl Type1Outlines { Ok(Self { subrs, glyphs, + glyph_order, matrix, std_vw, force_bold, @@ -461,6 +467,10 @@ impl Type1Outlines { }) } + pub(crate) fn glyph_order(&self) -> &[String] { + &self.glyph_order + } + pub fn has_glyph(&self, name: &str) -> bool { self.glyphs.contains_key(name) } diff --git a/crates/texrra-tex-core/src/type1_outline/cff.rs b/crates/texrra-tex-core/src/type1_outline/cff.rs index f260461..d95c1b1 100644 --- a/crates/texrra-tex-core/src/type1_outline/cff.rs +++ b/crates/texrra-tex-core/src/type1_outline/cff.rs @@ -437,3 +437,127 @@ pub(crate) fn write_type1c( included.remove(".notdef"); Ok((output, included.into_iter().map(str::to_owned).collect())) } + +/// A CFF1 subset with a single font dictionary and a CID-keyed charset. +pub(crate) struct CidCff<'a> { + pub registry: &'a str, + pub ordering: &'a str, + pub supplement: u32, + pub bbox: [f64; 4], + pub matrix: [f64; 6], + pub programs: &'a [(u16, &'a [u8])], + pub globals: &'a [u8], + pub private: &'a [u8], + pub private_size: usize, +} + +impl CidCff<'_> { + pub(crate) fn write(self, name: &str) -> Result, String> { + let count = u16::try_from(self.programs.len()).map_err(|_| "too many glyphs for CFF1")?; + let mut charset = vec![0]; // Format 0. CIDs follow CharStrings order. + for (cid, _) in self.programs.iter().skip(1) { + charset.extend(cid.to_be_bytes()); + } + let programs = index(&self.programs.iter().map(|(_, program)| *program).collect::>())?; + let name = index(&[name])?; + let strings = index(&[self.registry.as_bytes(), self.ordering.as_bytes()])?; + let fd_select = vec![0; usize::from(count) + 1]; + let long = |out: &mut Vec, value: usize| -> Result<(), String> { + dict_long(out, i32::try_from(value).map_err(|_| "CFF offset overflow")?); + Ok(()) + }; + let font_dict = |private_offset| -> Result, String> { + let mut dict = Vec::new(); + long(&mut dict, self.private_size)?; + long(&mut dict, private_offset)?; + dict.push(18); + index(&[dict]) + }; + let mut attributes = Vec::new(); + long(&mut attributes, usize::from(STANDARD_STRING_COUNT))?; + long(&mut attributes, usize::from(STANDARD_STRING_COUNT) + 1)?; + long(&mut attributes, self.supplement as usize)?; + attributes.extend([12, 30]); // ROS + for value in self.bbox { + dict_number(&mut attributes, value)?; + } + attributes.push(5); + for value in self.matrix { + dict_number(&mut attributes, value)?; + } + attributes.extend([12, 7]); // FontMatrix + long( + &mut attributes, + self.programs.last().map_or(1, |(cid, _)| usize::from(*cid) + 1), + )?; + attributes.extend([12, 34]); // CIDCount + let top = |base| -> Result, String> { + let programs_offset = base + charset.len(); + let select_offset = programs_offset + programs.len(); + let fd_offset = select_offset + fd_select.len(); + let mut top = attributes.clone(); + for (offset, opcode) in [ + (base, &[15][..]), + (programs_offset, &[17][..]), + (select_offset, &[12, 37][..]), + (fd_offset, &[12, 36][..]), + ] { + long(&mut top, offset)?; + top.extend(opcode); + } + index(&[top]) + }; + let offset = 4 + name.len() + top(0)?.len() + strings.len() + self.globals.len(); + let private_offset = + offset + charset.len() + programs.len() + fd_select.len() + font_dict(0)?.len(); + let mut output = vec![1, 0, 4, 4]; + for part in [ + name.as_slice(), + &top(offset)?, + &strings, + self.globals, + &charset, + &programs, + &fd_select, + &font_dict(private_offset)?, + self.private, + ] { + output.extend(part); + } + Ok(output) + } +} + +pub(crate) fn write_type1_cid( + font: &Type1Font, + name: &str, + glyphs: &BTreeMap, +) -> Result, String> { + let private = private_dictionary(font)?; + let outlines = Type1Outlines::from_private(font, &private, None)?; + let mut budget = 2_000_000; + let mut programs = Vec::with_capacity(glyphs.len() + 1); + for (cid, glyph) in [(0, ".notdef")].into_iter().chain( + 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)?; + 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)?; + CidCff { + registry: "Adobe", + ordering: "Identity", + supplement: 0, + bbox: font.bbox.map(f64::from), + matrix: outlines.matrix, + programs: &programs.iter().map(|(cid, program)| (*cid, program.as_slice())).collect::>(), + globals: &[0, 0], // Type 1 subroutines were expanded. + private: &private, + private_size: private.len(), + } + .write(name) +} diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 56aab37..fc903bc 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -1401,3 +1401,91 @@ fn xdv_text_mapping_uses_the_resource_active_at_each_shipped_special() { } assert_eq!(titles, [b"\xfe\xff\x65\xe5\x57\x0b".as_slice(), b"\xfe\xff\x65\xe5\x67\x2c", b"AB"]); } + +#[test] +fn xdv_type1_unicode_keeps_alternate_codes_for_the_same_charstring() { + use lopdf::Document; + use sha2::{Digest, Sha256}; + use texrra_tex_core::{ + native_font::resolve_native_fonts, + pdf::shipout_lists_to_native_pdf_document, + render::DisplayItem, + resources::{LoadedResource, ResourceKind, ResourceVersion}, + }; + + fn resource(name: &str, bytes: &[u8]) -> LoadedResource { + LoadedResource { + version: ResourceVersion { + path: name.into(), + bytes: bytes.len() as u64, + sha256: format!("{:x}", Sha256::digest(bytes)), + }, + data: bytes.to_vec(), + } + } + + struct Fonts; + impl SourceProvider for Fonts { + fn read(&mut self, name: &str, _: &str) -> Result { + Err(format!("unexpected input {name}")) + } + + fn default_pk_resolution(&mut self) -> Result { + Ok(600) + } + + fn resource( + &mut self, kind: ResourceKind, name: &str, _: &str, + ) -> Result { + let bytes: &[u8] = match (kind, name) { + (ResourceKind::Tfm, "mapped.tfm") => include_bytes!("../assets/cmr10.tfm"), + (ResourceKind::Type1, "cmr10.pfb") => include_bytes!("../../../assets/fonts/cmr10.pfb"), + _ => return Err(format!("unexpected font resource {kind:?} {name}")), + }; + Ok(resource(name, bytes)) + } + + fn optional_font_file( + &mut self, kind: ResourceKind, name: &str, from: &str, + ) -> Result, String> { + Ok(match (kind, name) { + (ResourceKind::Tfm, "mapped.tfm") => Some(self.resource(kind, name, from)?), + (ResourceKind::Map, "texglyphlist.txt") => Some(resource(name, b"A;005E\n")), + (ResourceKind::Map, "glyphlist.txt") => { + Some(resource(name, include_bytes!("../assets/glyphlist.txt"))) + } + _ => None, + }) + } + + fn optional_font_map(&mut self, _: &str, _: &str) -> Result, String> { + Ok(None) + } + } + + let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); + let execution = Executor::new(state, Limits::default()).with_native_pages().run( + source(r"\catcode123=1 \catcode125=2 + \font\proof=mapped at10pt + \shipout\hbox{\special{pdf:mapline mapped unicode cmr10.pfb -w 1}\proof A\char94B} + \end"), + &mut Fonts, + ).unwrap(); + let mut pages = execution.shipout_display_lists().unwrap(); + resolve_native_fonts(&mut pages, &mut Fonts).unwrap(); + let letters: Vec<_> = pages[0].items.iter().filter_map(|item| match item { + DisplayItem::NativeGlyph { character, slot, paint: Some(paint), .. } => { + Some((*character, &paint.glyph_paths[slot])) + } + _ => None, + }).collect(); + assert_eq!(letters.iter().map(|(character, _)| character).collect::(), "^^B"); + assert_eq!(letters[0].1, letters[1].1); + assert_ne!(letters[0].1, letters[2].1); + assert!(pages[0].try_to_svg().unwrap().contains("matrix(0.00000000 -0.01000000 -0.01000000 0 ")); + let output = shipout_lists_to_native_pdf_document(&pages, execution.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + assert!(pdf.objects.values().filter_map(|object| object.as_stream().ok()).any(|stream| { + stream.dict.get(b"Subtype").and_then(|value| value.as_name()).is_ok_and(|name| name == b"CIDFontType0C") + })); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index da3b062..47c76dc 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,32 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX 旧 TFM 与复合 Type 1 + +旧 TFM 可以通过 Unicode、Identity-H/V 和命名 CMap 选中原版 Type 1 +字形。CID 保留 PFB 字形程序的实际顺序。作业的 Adobe 字形表随资源版本 +进入依赖,Unicode 选字支持同一字形的多个输入码,ToUnicode 采用字形名的 +首选映射。PDF 嵌入转换后的 CID CFF,保留实际轮廓、字宽和 hint 程序。 +SVG 使用同一映射与设备游标。遇到 CID 字形中的 Type 1 seac 会报告诊断, +原版 xdvipdfmx 同样会在这条嵌入路径报错。混用横竖模式时目前分别写两份 +字体子集。 +[参考 Type 1 字形顺序](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/t1_load.c) +[参考 Type 1 转换与 Unicode 映射](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/cidtype0.c) + +实际 CMR10 与 Latin Modern 的八组原版对照共八页,144 DPI 彩色光栅 +和文字提取一致。覆盖横竖混排、日常命名映射的继承、重音和字体表别名。 +别名回归已加入测试,上一批名称索引 CFF 的控制 PDF 逐字节一致。 + +三页会话改字形表、替换 PFB、移除 PFB 后恢复。三个成功修订均只刷新第 +2 页,各复用 1,552 步,PDF、测量页、SVG、来源映射和 aux 与独立全量 +一致。缺失 PFB 时保留上次发布。正式出版模板矩阵、实时延迟门槛及 v1 +迁移仍待验收。 + +本地回执在 target/p3-xdv-composite-type1/ 的 verification.txt +和 SHA256SUMS。下一批将使用原样 longtable、booktabs 和 amsmath 核查 +数学表格跨页,以及双栏浮动与脚注的组合行为。两份样例的原版两轮输出 +共五页,记录在 target/p3-combined-layout/reference/。 + ## 2026-11-28 XeLaTeX 旧 TFM 的竖排与复合 CFF 旧 TFM 设备字体支持 TrueType 和 OpenType CFF 的横排及竖排复合映射。