//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face. use super::{ MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, composite::{self, Codes, CompositeFont}, map::{MapEntry, OutlineFiles}, }; use crate::{execution::SourceProvider, resources::ResourceKind}; use read_fonts::ps::cff::CffFontRef; use rustybuzz::ttf_parser::{Face, GlyphId, Tag}; use std::{collections::{BTreeMap, BTreeSet}, sync::Arc}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct OpenTypeCffProgram { pub(crate) name: String, pub(crate) data: Arc<[u8]>, #[serde(default)] pub(crate) face_index: u32, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) composite: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) composite_glyphs: Vec, } impl OpenTypeCffProgram { pub(crate) fn face(&self) -> Result, String> { Face::parse(&self.data, self.face_index) .map_err(|error| format!("invalid OpenType font {}: {error}", self.name)) } } pub(super) fn device_program( files: &mut impl SourceProvider, name: &str, from: &str, cid_keyed: bool, ) -> Result>, String> { let Some(selected) = files.pdf_cff(name, from, cid_keyed)? else { return Ok(None); }; let resource = super::verify_resource(selected.resource, ResourceKind::OpenType, name)?; use crate::resources::{PdfSfntKind, cff_program, exact_pdf_sfnt_name}; if exact_pdf_sfnt_name( &resource.data, selected.index, name, PdfSfntKind::Cff { cid_keyed }, ) .is_none() { return Err(format!( "PDF device font {name} does not match the selected CFF face" )); } let bytes = cff_program(&resource.data, selected.index, cid_keyed) .ok_or_else(|| format!("PDF device font {name} has an invalid CFF program"))?; Ok(Some(bytes.into())) } pub(super) fn resolve( files: &mut impl SourceProvider, outlines: &mut OutlineFiles, outline: &MapEntry, file: &str, font: &NativeFont, slots: BTreeSet, ) -> Result { if let Some(encoding) = &outline.xdv_encoding && let Some(codes) = Codes::load(encoding, outline, files)? { let mut raw_outline = outline.clone(); raw_outline.encoding = None; let MappedOutline { data, mut resources, program_index, .. } = raw_outline.read_outline(files, outlines, ResourceKind::OpenType, file)?; let face = Face::parse(&data, outline.face_index) .map_err(|error| format!("invalid OpenType font {file}: {error}"))?; if face.tables().cff.is_none() { return Err(format!("OpenType font has no supported CFF1 table: {file}")); } let composite::Glyphs { mapping, glyphs, names, glyph_paths } = composite::resolve(files, outline, &data, &face, slots, encoding, codes, &mut resources)?; let name = face.names().into_iter() .filter(|name| name.name_id == rustybuzz::ttf_parser::name_id::POST_SCRIPT_NAME) .find_map(|name| name.to_string()) .unwrap_or_else(|| outline.postscript_name().unwrap_or(&font.name).to_owned()); let bbox = scaled_bbox(&face); return Ok(NativeFontPaint { program: NativeFontProgram::OpenTypeCff(OpenTypeCffProgram { name, data, face_index: outline.face_index, composite: Some(mapping), composite_glyphs: glyphs, }), encoding: names, glyph_paths, bbox, stem_v: 0, subset: true, descriptor_flags: None, xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), xdv_unicode: None, resources, program_index: Some(program_index), }); } if outline.subset { return Err(format!("OTF fonts must be included entirely: {file}")); } let MappedOutline { data, encoding, resources, program_index, } = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?; let face = Face::parse(&data, outline.face_index).map_err(|error| format!("invalid OpenType font {file}: {error}"))?; let table = face .raw_face() .table(Tag::from_bytes(b"CFF ")) .ok_or_else(|| format!("OpenType font has no CFF table: {file}"))?; let cff = CffFontRef::new_cff(table, 0, None) .map_err(|error| format!("invalid CFF program {file}: {error:?}"))?; if cff.is_cid() { return Err(format!( "an eight-bit OpenType map needs a name-keyed CFF font: {file}" )); } let cff = face .tables() .cff .ok_or_else(|| format!("invalid CFF outlines: {file}"))?; let encoded_glyph = |slot| { if let Some(names) = &encoding { cff.glyph_index_by_name(&names[usize::from(slot)]) } else { cff.glyph_index(slot) } .unwrap_or(GlyphId(0)) }; let matrix = cff.matrix(); let scale = [ matrix.sx, matrix.ky, matrix.kx, matrix.sy, matrix.tx, matrix.ty, ] .map(|number| f64::from(number * 1000.)); let glyph_paths = slots .into_iter() .map(|slot| { ( slot, crate::opentype::outline_matrix(&face, encoded_glyph(slot).0, Some(scale)), ) }) .collect(); let encoding = encoding.unwrap_or_else(|| { (0..=255) .map(|slot| { cff.glyph_index(slot) .and_then(|glyph| cff.glyph_name(glyph)) .unwrap_or(".notdef") .to_owned() }) .collect() }); let bbox = scaled_bbox(&face); let program = OpenTypeCffProgram { name: outline.postscript_name().unwrap_or(&font.name).to_owned(), data, face_index: outline.face_index, composite: None, composite_glyphs: Vec::new(), }; Ok(NativeFontPaint { program: NativeFontProgram::OpenTypeCff(program), encoding, glyph_paths, bbox, stem_v: 0, subset: false, descriptor_flags: outline.descriptor_flags, xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), xdv_unicode: None, resources, program_index: Some(program_index), }) } fn scaled_bbox(face: &Face<'_>) -> [i32; 4] { let bbox = face.global_bounding_box(); [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] .map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em())) }