Render and embed OpenType CFF fonts selected by pdfTeX maps

This commit is contained in:
gloamxun committed 2026-11-28 02:46:19 +08:00
1 parent 46ef76f890
commit fd5ab59f42
11 files changed
+433 -57

No files matched your search

@@ -0,0 +1,106 @@
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face.
use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
use crate::{execution::SourceProvider, resources::ResourceKind};
use read_fonts::ps::cff::CffFontRef;
use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
use std::{collections::BTreeSet, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct OpenTypeCffProgram {
pub(crate) name: String,
data: Arc<[u8]>,
}
impl OpenTypeCffProgram {
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
Face::parse(&self.data, 0)
.map_err(|error| format!("invalid OpenType font {}: {error}", self.name))
}
}
pub(super) fn resolve(
files: &mut impl SourceProvider,
outline: &MapEntry,
file: &str,
font: &NativeFont,
slots: BTreeSet<u8>,
) -> Result<NativeFontPaint, String> {
if outline.subset {
return Err(format!("OTF fonts must be included entirely: {file}"));
}
let MappedOutline {
data,
encoding,
resources,
program_index,
} = outline.read_outline(files, ResourceKind::OpenType, file)?;
let face =
Face::parse(&data, 0).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 = face.global_bounding_box();
let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max]
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
let program = OpenTypeCffProgram {
name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
data: data.into(),
};
Ok(NativeFontPaint {
program: NativeFontProgram::OpenTypeCff(program),
encoding,
glyph_paths,
bbox,
stem_v: 0,
subset: false,
descriptor_flags: outline.descriptor_flags,
xdv_descriptor: None,
resources,
program_index: Some(program_index),
})
}
+32 -2
View File
@@ -1,5 +1,5 @@
//! PDF font map entries, lookup bindings, and the lifetime of the default map.
use super::{MappedType1, NativeFont, verify_resource};
use super::{MappedOutline, MappedType1, NativeFont, actual_resource, encoding_vector, verify_resource};
use crate::{
execution::{FontId, SourceProvider},
resources::{LoadedResource, ResourceKind, ResourceVersion},
@@ -39,16 +39,46 @@ impl MapEntry {
}
pub(super) fn true_type_file(&self) -> Option<&str> {
self.outline_file(&["ttf", "ttc"])
}
pub(super) fn open_type_file(&self) -> Option<&str> {
self.outline_file(&["otf"])
}
fn outline_file(&self, extensions: &[&str]) -> Option<&str> {
self.file.as_deref().filter(|file| {
Path::new(file)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
extension.eq_ignore_ascii_case("ttf") || extension.eq_ignore_ascii_case("ttc")
extensions.iter().any(|name| extension.eq_ignore_ascii_case(name))
})
})
}
pub(super) fn read_outline(
&self,
files: &mut impl SourceProvider,
kind: ResourceKind,
file: &str,
) -> Result<MappedOutline, String> {
let from = self.from.to_string_lossy();
let program = actual_resource(files, kind, file, &from)?;
let mut resources: Vec<_> = self.version.iter().cloned().collect();
let program_index = resources.len();
resources.push(program.version);
let encoding = if let Some(name) = &self.encoding {
let file = actual_resource(files, ResourceKind::Encoding, name, &from)?;
let names = encoding_vector(&file.data)?;
resources.push(file.version);
Some(names)
} else {
None
};
Ok(MappedOutline { data: program.data, encoding, resources, program_index })
}
pub(super) fn postscript_name(&self) -> Option<&str> {
self.ps_name.as_deref()
}
@@ -1,5 +1,5 @@
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
use super::{NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
use crate::{execution::SourceProvider, resources::ResourceKind};
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
use std::{
@@ -70,25 +70,17 @@ pub(super) fn resolve(
font: &NativeFont,
slots: BTreeSet<u8>,
) -> Result<NativeFontPaint, String> {
let from = outline.from.to_string_lossy();
let resource = super::actual_resource(files, ResourceKind::TrueType, file, &from)?;
let face = Face::parse(&resource.data, 0)
.map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
let MappedOutline {
data,
encoding,
resources,
program_index,
} = outline.read_outline(files, ResourceKind::TrueType, file)?;
let face =
Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
return Err(format!("invalid TrueType outline tables in {file}"));
}
let mut resources: Vec<_> = outline.version.iter().cloned().collect();
let program_index = Some(resources.len());
resources.push(resource.version);
let encoding = if let Some(name) = &outline.encoding {
let enc = super::actual_resource(files, ResourceKind::Encoding, name, &from)?;
let encoding = super::encoding_vector(&enc.data)?;
resources.push(enc.version);
Some(encoding)
} else {
None
};
if outline.subset && encoding.is_none() {
return Err(format!(
"subset TrueType font {} needs a reencoding",
@@ -149,7 +141,7 @@ pub(super) fn resolve(
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
let program = TrueTypeProgram {
name,
data: resource.data.into(),
data: data.into(),
glyphs,
reencoded,
};
@@ -163,7 +155,7 @@ pub(super) fn resolve(
descriptor_flags: outline.descriptor_flags,
xdv_descriptor: None,
resources,
program_index,
program_index: Some(program_index),
})
}