//! Resolve actual XDV character codes independently of the TeX font metrics. use super::{ cid_width, map::{MapEntry, XdvEncoding}, }; use crate::{ execution::SourceProvider, opentype::vertical::PdfMetrics, pdf_device::cmap::CMap, resources::ResourceVersion, }; use rustybuzz::ttf_parser::{Face, GlyphId, Tag}; use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) struct CompositeFont { pub(crate) registry: String, pub(crate) ordering: String, pub(crate) supplement: u32, 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)] pub(super) struct CompositeSlot { pub(super) cid: u16, pub(super) advance: u32, pub(super) unicode: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) vertical: Option<[i32; 3]>, } impl CompositeFont { pub(crate) fn cid(&self, slot: u8) -> u16 { self.slots[usize::from(slot)].cid } pub(crate) fn advance(&self, slot: u8) -> u32 { self.slots[usize::from(slot)].advance } pub(crate) fn vertical_override(&self, slot: u8) -> Option<[i32; 3]> { self.vertical?; self.slots[usize::from(slot)].vertical } pub(crate) fn vertical_slot(&self, slot: u8) -> Option<[f64; 3]> { let [advance, y] = self.vertical?; if let Some(metrics) = self.vertical_override(slot) { return Some(metrics.map(f64::from)); } Some([ f64::from(advance), f64::from(self.advance(slot)) / 2.0, f64::from(y), ]) } pub(crate) fn unicode(&self, slot: u8) -> Option<&str> { self.slots[usize::from(slot)].unicode.as_deref() } } pub(super) enum Codes { Unicode, Identity, Custom(Box), } impl Codes { pub(super) fn load( encoding: &XdvEncoding, outline: &MapEntry, files: &mut impl SourceProvider, ) -> Result, String> { let name = &encoding.name; Ok(Some(match name.as_str() { "unicode" => Self::Unicode, "Identity-H" | "Identity-V" => Self::Identity, _ => { let Some(map) = CMap::load_optional(name, &outline.from.to_string_lossy(), files)? else { return if outline.encoding.is_some() { Ok(None) } else { Err(format!("XDV encoding CMap {name} was not found")) }; }; Self::Custom(Box::new(map)) } })) } } pub(super) struct Glyphs { pub(super) mapping: CompositeFont, pub(super) glyphs: Vec, pub(super) names: Vec, pub(super) glyph_paths: BTreeMap, } pub(super) fn resolve( files: &mut impl SourceProvider, outline: &MapEntry, data: &[u8], face: &Face<'_>, slots: BTreeSet, encoding: &XdvEncoding, codes: Codes, resources: &mut Vec, ) -> Result { let (requested_registry, requested_ordering, requested_supplement) = match &codes { Codes::Custom(map) => { resources.extend(map.resources.iter().cloned()); map.collection() .ok_or_else(|| format!("CMap {} has no CID system info", encoding.name))? } _ => ("Adobe", "Identity", 0), }; let identity = requested_registry == "Adobe" && requested_ordering == "Identity"; let collection = cid_keyed_collection(face)?; let owns_collection = collection.is_some(); let same_collection = collection .as_ref() .is_some_and(|(registry, ordering, _, _)| { registry == requested_registry && ordering == requested_ordering }); if !identity && owns_collection && !same_collection { return Err(format!( "CMap {} uses a different collection from the CFF face", encoding.name )); } let vertical = encoding.vertical || encoding.name == "Identity-V" || matches!(&codes, Codes::Custom(map) if map.is_vertical()); let metrics = vertical.then(|| PdfMetrics::new(face)); let shaper = if vertical { Some( rustybuzz::Face::from_slice(data, outline.face_index) .ok_or("invalid vertical outline face")?, ) } else { None }; let collection_to_unicode = if !identity { let map = CMap::load( &format!("{requested_registry}-{requested_ordering}-UCS2"), &outline.from.to_string_lossy(), files, )?; resources.extend(map.resources.iter().cloned()); Some(map) } else { None }; let mut glyphs = vec![0; 256]; let mut names = vec![".notdef".to_owned(); 256]; let mut cells = vec![CompositeSlot::default(); 256]; let mut vertical_alternates = Vec::new(); let mut glyph_paths = BTreeMap::new(); let scale = 1000.0 / f64::from(face.units_per_em()); let reverse = if identity && !matches!(codes, Codes::Unicode) { let glyphs = (0..=255u8).filter_map(|slot| { let code = encoding.prefix | u32::from(slot); let glyph = match &codes { Codes::Custom(map) => map.cid(code)?, _ => u16::try_from(code).ok()?, }; (glyph != 0 && glyph < face.number_of_glyphs()).then_some(glyph) }); crate::pdf::opentype_unicode::map_glyphs(face, glyphs, None) } else { BTreeMap::new() }; // Resolve a complete byte table once. A subsequent page may activate any // of these slots while sharing this font's dictionary and subset. for slot in 0..=255u8 { let code = encoding.prefix | u32::from(slot); let glyph_for_direct_cid = |cid: u16| { if let Some((_, _, _, charset)) = &collection { charset .iter() .find_map(|(&glyph, &code)| (code == cid).then_some(glyph)) } else { (cid < face.number_of_glyphs()).then_some(cid) } }; let target = match &codes { Codes::Unicode => char::from_u32(code).and_then(|ch| { let gid = face.glyph_index(ch)?.0; Some((gid, gid, Some(ch.to_string()))) }), Codes::Identity => u16::try_from(code) .ok() .and_then(|cid| Some((cid, glyph_for_direct_cid(cid)?, None))), Codes::Custom(map) => map.cid(code).and_then(|cid| { if identity { return Some((cid, glyph_for_direct_cid(cid)?, None)); } let text = collection_to_unicode.as_ref()?.unicode(2, u32::from(cid)); if same_collection { return Some((cid, glyph_for_direct_cid(cid)?, text)); } let text = text?; let mut chars = text.chars(); let ch = chars.next()?; if chars.next().is_some() { return None; } let gid = face.glyph_index(ch)?.0; Some((cid, gid, Some(text))) }), }; let (mut cid, mut gid, text) = target.unwrap_or((0, 0, None)); let name = face.glyph_name(GlyphId(gid)).filter(|_| gid != 0); let text = text .or_else(|| reverse.get(&gid).cloned()) .or_else(|| name.and_then(crate::type1::glyph_unicode_text)); if vertical && gid != 0 && let (Some(shaper), Some(value)) = (&shaper, &text) && let Some(ch) = single_scalar(value) { let selected = vertical_glyph(shaper, ch, gid); if selected != gid { vertical_alternates.push((slot, selected)); } gid = selected; // The built-in Unicode mapping uses the selected glyph as its // CID; named CMaps preserve the CID and select its actual glyph. if matches!(codes, Codes::Unicode) { cid = gid; } } if let Some((_, _, _, charset)) = &collection { cid = charset.get(&gid).copied().unwrap_or(0); } let index = usize::from(slot); glyphs[index] = gid; cells[index] = CompositeSlot { cid, advance: cid_width(face, gid), unicode: text.clone(), vertical: metrics .as_ref() .and_then(|metrics| metrics.override_for(GlyphId(gid))) .map(|values| values.map(|value| value as i32)), }; if let Some(name) = name { names[index] = name.into(); } else if let Some(text) = &text && let Some(ch) = text.chars().next() { names[index] = format!("uni{:04X}", u32::from(ch)); } if slots.contains(&slot) { glyph_paths.insert( slot, crate::opentype::outline(face, gid, Some([scale, 0., scale])), ); } } if !vertical_alternates.is_empty() { let text = crate::pdf::opentype_unicode::map_glyphs( face, vertical_alternates.iter().map(|&(_, glyph)| glyph), None, ); for (slot, glyph) in vertical_alternates { if let Some(source) = text.get(&glyph) { cells[usize::from(slot)].unicode = Some(source.clone()); } } } let (registry, ordering, supplement) = collection.map_or_else( || { ( requested_registry.to_owned(), requested_ordering.to_owned(), requested_supplement, ) }, |(registry, ordering, supplement, _)| (registry, ordering, supplement), ); let mapping = CompositeFont { registry, ordering, supplement, slots: cells, vertical: metrics.map(|value| [value.advance as i32, value.origin_y as i32]), }; Ok(Glyphs { mapping, glyphs, names, glyph_paths, }) } fn single_scalar(text: &str) -> Option { let mut chars = text.chars(); let first = chars.next()?; chars.next().is_none().then_some(first) } fn vertical_glyph(face: &rustybuzz::Face<'_>, ch: char, default: u16) -> u16 { let mut buffer = rustybuzz::UnicodeBuffer::new(); buffer.push_str(ch.encode_utf8(&mut [0; 4])); buffer.set_direction(rustybuzz::Direction::TopToBottom); buffer.guess_segment_properties(); let result = rustybuzz::shape(face, &[], buffer); let [glyph] = result.glyph_infos() else { return default; }; u16::try_from(glyph.glyph_id) .ok() .filter(|&id| id != 0) .unwrap_or(default) } type Collection = (String, String, u32, BTreeMap); fn cid_keyed_collection(face: &Face<'_>) -> Result, String> { use read_fonts::{ FontData, FontRead, ps::cff::{CffFontRef, dict, v1::Cff}, }; let Some(data) = face.raw_face().table(Tag::from_bytes(b"CFF ")) else { return Ok(None); }; let error = || "invalid CID-keyed CFF charset".to_owned(); let cff = Cff::read(FontData::new(data)).map_err(|_| error())?; let top = cff.top_dicts().get(0).ok_or_else(error)?; for entry in dict::entries(top, None).flatten() { if let dict::Entry::Ros { registry, ordering, supplement, } = entry { let read = |sid| { let bytes = cff.string(sid).ok_or_else(error)?; String::from_utf8(bytes.to_vec()).map_err(|_| error()) }; let charset = CffFontRef::new_cff(data, 0, None) .ok() .and_then(|font| font.charset()) .ok_or_else(error)?; let map = charset .iter() .map(|(gid, cid)| { let glyph = u16::try_from(gid.to_u32()).map_err(|_| error())?; Ok((glyph, cid.to_u16())) }) .collect::, String>>()?; return Ok(Some(( read(registry)?, read(ordering)?, supplement.to_f64().max(0.) as u32, map, ))); } } Ok(None) }