Render and embed OpenType CFF fonts selected by pdfTeX maps
This commit is contained in:
1 parent
46ef76f890
commit
fd5ab59f42
11 files changed
+433
-57
No files matched your search
@@ -12,9 +12,11 @@ use std::{
|
||||
collections::{BTreeMap, VecDeque},
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
};
|
||||
mod cff;
|
||||
mod map;
|
||||
mod truetype;
|
||||
mod virtual_paint;
|
||||
pub use cff::OpenTypeCffProgram;
|
||||
pub use truetype::TrueTypeProgram;
|
||||
pub use map::PdfFontBindings;
|
||||
use map::{dedicated_space_map, find_map_entry, load_map, selected_outline};
|
||||
@@ -38,6 +40,13 @@ pub struct NativeFontPaint {
|
||||
program_index: Option<usize>,
|
||||
}
|
||||
|
||||
struct MappedOutline {
|
||||
data: Vec<u8>,
|
||||
encoding: Option<Vec<String>>,
|
||||
resources: Vec<ResourceVersion>,
|
||||
program_index: usize,
|
||||
}
|
||||
|
||||
pub(crate) type Type1ProgramKey<'a> = (&'a ResourceVersion, Type1Transform);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -62,11 +71,15 @@ impl NativeFontPaint {
|
||||
&& self.encoding[32] == "space"
|
||||
&& font.metrics().width(' ') > 65_782
|
||||
}
|
||||
pub(crate) fn encoding_version(&self) -> Option<&ResourceVersion> {
|
||||
self.resources.get(self.program_index? + 1)
|
||||
}
|
||||
|
||||
pub(crate) fn type1_program_key(&self) -> Option<Type1ProgramKey<'_>> {
|
||||
match &self.program {
|
||||
NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1))
|
||||
.map(|version| (version, font.transform)),
|
||||
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_) => None,
|
||||
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_) | NativeFontProgram::OpenTypeCff(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,6 +89,7 @@ pub enum NativeFontProgram {
|
||||
Type1(crate::type1::Type1Font),
|
||||
Pk(crate::pk_font::PkFontProgram),
|
||||
TrueType(TrueTypeProgram),
|
||||
OpenTypeCff(OpenTypeCffProgram),
|
||||
}
|
||||
impl NativeFontProgram {
|
||||
pub fn name(&self) -> &str {
|
||||
@@ -83,6 +97,7 @@ impl NativeFontProgram {
|
||||
Self::Type1(p) => &p.name,
|
||||
Self::Pk(p) => &p.name,
|
||||
Self::TrueType(p) => &p.name,
|
||||
Self::OpenTypeCff(p) => &p.name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -508,6 +523,11 @@ fn resolve_physical_fonts(
|
||||
direct_resolved.insert(id, Arc::new(paint));
|
||||
continue;
|
||||
}
|
||||
if let Some(file) = outline.open_type_file() {
|
||||
let paint = cff::resolve(files, outline, file, &font, slots)?;
|
||||
direct_resolved.insert(id, Arc::new(paint));
|
||||
continue;
|
||||
}
|
||||
let file = outline.type1_file(&font.name)?;
|
||||
let version = outline.version.as_ref();
|
||||
let key = (
|
||||
@@ -605,7 +625,9 @@ fn resolve_physical_fonts(
|
||||
{
|
||||
let p = resolved[&font.id].clone();
|
||||
*character = match &p.program {
|
||||
NativeFontProgram::Type1(_) | NativeFontProgram::TrueType(_) => {
|
||||
NativeFontProgram::Type1(_)
|
||||
| NativeFontProgram::TrueType(_)
|
||||
| NativeFontProgram::OpenTypeCff(_) => {
|
||||
crate::type1::glyph_unicode_text(&p.encoding[*slot as usize])
|
||||
.and_then(|text| text.chars().next())
|
||||
.unwrap_or('�')
|
||||
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -972,7 +972,7 @@ impl OpenTypeRun {
|
||||
|
||||
struct PathBuilder {
|
||||
path: String,
|
||||
transform: Option<[f64; 3]>,
|
||||
transform: Option<[f64; 6]>,
|
||||
}
|
||||
|
||||
impl PathBuilder {
|
||||
@@ -984,9 +984,9 @@ impl PathBuilder {
|
||||
if index != 0 {
|
||||
self.path.push(' ');
|
||||
}
|
||||
if let Some([extend, shear, vertical]) = self.transform {
|
||||
if let Some([a, b, c, d, tx, ty]) = self.transform {
|
||||
let (x, y) = (f64::from(x), f64::from(y));
|
||||
write!(self.path, "{:.9} {:.9}", extend * x + shear * y, vertical * y).unwrap();
|
||||
write!(self.path, "{:.9} {:.9}", a * x + c * y + tx, b * x + d * y + ty).unwrap();
|
||||
} else {
|
||||
write!(self.path, "{x} {y}").unwrap();
|
||||
}
|
||||
@@ -1016,6 +1016,15 @@ pub(crate) fn outline(
|
||||
face: &ttf_parser::Face<'_>,
|
||||
glyph: u16,
|
||||
transform: Option<[f64; 3]>,
|
||||
) -> String {
|
||||
let matrix = transform.map(|[extend, shear, vertical]| [extend, 0., shear, vertical, 0., 0.]);
|
||||
outline_matrix(face, glyph, matrix)
|
||||
}
|
||||
|
||||
pub(crate) fn outline_matrix(
|
||||
face: &ttf_parser::Face<'_>,
|
||||
glyph: u16,
|
||||
transform: Option<[f64; 6]>,
|
||||
) -> String {
|
||||
let mut path = PathBuilder { path: String::new(), transform };
|
||||
face.outline_glyph(GlyphId(glyph), &mut path);
|
||||
|
||||
@@ -26,6 +26,7 @@ pub(crate) mod type1_fonts;
|
||||
pub(crate) mod objects;
|
||||
#[path = "pdf_pk.rs"]
|
||||
mod pk_fonts;
|
||||
mod cff_fonts;
|
||||
mod truetype_fonts;
|
||||
#[path = "pdf_opentype.rs"]
|
||||
mod opentype_fonts;
|
||||
@@ -1524,7 +1525,12 @@ fn native_pdf(
|
||||
if page.units != crate::render::DisplayUnits::TeX && matches!(paint.program,crate::native_font::NativeFontProgram::Pk(_)) {
|
||||
return Err("native PK PDF requires actual shipout device coordinates".into());
|
||||
}
|
||||
if paint.encoding.len()!=256 || paint.encoding[*slot as usize]==".notdef" || !paint.glyph_paths.contains_key(slot) || !font.has_slot(*slot) {
|
||||
if paint.encoding.len() != 256
|
||||
|| (matches!(paint.program, crate::native_font::NativeFontProgram::Type1(_))
|
||||
&& paint.encoding[usize::from(*slot)] == ".notdef")
|
||||
|| !paint.glyph_paths.contains_key(slot)
|
||||
|| !font.has_slot(*slot)
|
||||
{
|
||||
return Err(format!("native font {} has no output encoding for slot {slot}",font.name));
|
||||
}
|
||||
if let Some((old_font,old_paint))=fonts.insert(font.id,(font,paint)) {
|
||||
@@ -1752,6 +1758,39 @@ fn native_type1_parameters(
|
||||
}
|
||||
}
|
||||
|
||||
fn write_sfnt_descriptor(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
metrics: &crate::tfm::TfmMetrics,
|
||||
face: &rustybuzz::ttf_parser::Face<'_>,
|
||||
paint: &crate::native_font::NativeFontPaint,
|
||||
name: &str,
|
||||
(file_key, font_file): (&str, usize),
|
||||
) -> usize {
|
||||
use rustybuzz::ttf_parser::Tag;
|
||||
let in_pdf_units = |value: i16| 1000 * i32::from(value) / i32::from(face.units_per_em());
|
||||
let ascent = in_pdf_units(face.tables().hhea.ascender);
|
||||
let descent = in_pdf_units(face.tables().hhea.descender);
|
||||
let pclt = face.raw_face().table(Tag::from_bytes(b"PCLT"));
|
||||
let pclt_height = |offset| {
|
||||
let bytes = pclt?.get(offset..offset + 2)?;
|
||||
Some(in_pdf_units(i16::from_be_bytes(bytes.try_into().ok()?)))
|
||||
};
|
||||
let size = native_pdf_font_size(metrics.size_sp());
|
||||
let cap = pclt_height(16)
|
||||
.unwrap_or_else(|| native_font_units(metrics.height('H'), size, 1000) as i32);
|
||||
let x_height =
|
||||
pclt_height(10).unwrap_or_else(|| native_font_units(metrics.x_height(), size, 1000) as i32);
|
||||
let stem = native_font_units(metrics.width('.') / 3, size, 1000);
|
||||
let angle = face.italic_angle().floor() as i32;
|
||||
let [left, bottom, right, top] = paint.bbox;
|
||||
let flags = paint.descriptor_flags.unwrap_or(4);
|
||||
|
||||
objects.push(format!(
|
||||
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /Ascent {ascent} /Descent {descent} /CapHeight {cap} /ItalicAngle {angle} /StemV {stem} /XHeight {x_height} /{file_key} {font_file} 0 R >>"
|
||||
).into_bytes());
|
||||
objects.len()
|
||||
}
|
||||
|
||||
fn pdf_font_owner(
|
||||
objects: Option<&crate::pdf_device::page_resources::PdfObjects>,
|
||||
id: crate::execution::FontId,
|
||||
@@ -1770,6 +1809,7 @@ fn write_native_font(
|
||||
reference: Option<&type1_fonts::Reference>,
|
||||
target: Option<usize>,
|
||||
subset_tags: &mut BTreeSet<String>,
|
||||
cff_encoding: Option<usize>,
|
||||
) -> Result<usize, String> {
|
||||
use crate::native_font::NativeFontProgram;
|
||||
if let NativeFontProgram::Pk(pk) = &paint.program {
|
||||
@@ -1818,6 +1858,13 @@ fn write_native_font(
|
||||
)?;
|
||||
("TrueType", descriptor, name, format!("{width_object} 0 R"), String::new(), program.reencoded)
|
||||
}
|
||||
NativeFontProgram::OpenTypeCff(program) => {
|
||||
let width_object = objects.len() + 1;
|
||||
objects.push(format!("[{widths}]").into_bytes());
|
||||
let (descriptor, name) = cff_fonts::write(objects, m, paint, program, compression)?;
|
||||
let encoding = cff_encoding.map_or_else(String::new, |id| format!(" /Encoding {id} 0 R"));
|
||||
("Type1", descriptor, name, format!("{width_object} 0 R"), encoding, cff_encoding.is_some())
|
||||
}
|
||||
NativeFontProgram::Pk(_) => unreachable!(),
|
||||
};
|
||||
let unicode = objects.len() + 1;
|
||||
@@ -2393,9 +2440,15 @@ fn write_pdf(
|
||||
.filter_map(|font| font.name.split_once('+').map(|(tag, _)| tag.to_owned()))
|
||||
.collect();
|
||||
let mut native_font_ids = BTreeMap::new();
|
||||
let mut cff_encodings = cff_fonts::Encodings::default();
|
||||
for (&id, (face, paint, used)) in &native_used {
|
||||
let target = registry.and_then(|objects| objects.font_number(id))
|
||||
.map(|number| device_objects[&number] as usize);
|
||||
let encoding = if matches!(paint.program, crate::native_font::NativeFontProgram::OpenTypeCff(_)) {
|
||||
cff_encodings.mark(&mut objects, paint, used.keys().copied())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
native_font_ids.insert(
|
||||
id,
|
||||
write_native_font(
|
||||
@@ -2409,9 +2462,11 @@ fn write_pdf(
|
||||
paint.type1_program_key().and_then(|key| type1_references.get(&key)),
|
||||
target,
|
||||
&mut subset_tags,
|
||||
encoding,
|
||||
)?,
|
||||
);
|
||||
}
|
||||
cff_encodings.write(&mut objects);
|
||||
for (font, owner) in aliases {
|
||||
let id = native_font_ids[&owner];
|
||||
native_font_ids.insert(font, id);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
use super::{native_pdf_name, objects, write_sfnt_descriptor};
|
||||
use crate::{
|
||||
native_font::{NativeFontPaint, OpenTypeCffProgram},
|
||||
resources::ResourceVersion,
|
||||
tfm::TfmMetrics,
|
||||
};
|
||||
use rustybuzz::ttf_parser::Tag;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
fmt::Write,
|
||||
};
|
||||
|
||||
pub(super) fn write(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
metrics: &TfmMetrics,
|
||||
paint: &NativeFontPaint,
|
||||
program: &OpenTypeCffProgram,
|
||||
compression: u8,
|
||||
) -> Result<(usize, String), String> {
|
||||
let face = program.face()?;
|
||||
let data = face
|
||||
.raw_face()
|
||||
.table(Tag::from_bytes(b"CFF "))
|
||||
.ok_or("missing CFF data in mapped OpenType font")?;
|
||||
let name = native_pdf_name(&program.name);
|
||||
let font_file = objects.len() + 1;
|
||||
objects.push(objects::stream("/Subtype /Type1C", data, compression));
|
||||
let descriptor = write_sfnt_descriptor(
|
||||
objects,
|
||||
metrics,
|
||||
&face,
|
||||
paint,
|
||||
&name,
|
||||
("FontFile3", font_file),
|
||||
);
|
||||
Ok((descriptor, name))
|
||||
}
|
||||
|
||||
struct Encoding<'a> {
|
||||
object: usize,
|
||||
names: BTreeMap<u8, &'a str>,
|
||||
}
|
||||
|
||||
/// A single encoding read is shared by all mapped CFF fonts that use it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Encodings<'a>(HashMap<&'a ResourceVersion, Encoding<'a>>);
|
||||
|
||||
impl<'a> Encodings<'a> {
|
||||
pub(super) fn mark(
|
||||
&mut self,
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
paint: &'a NativeFontPaint,
|
||||
slots: impl Iterator<Item = u8>,
|
||||
) -> Option<usize> {
|
||||
let version = paint.encoding_version()?;
|
||||
let encoding = self.0.entry(version).or_insert_with(|| {
|
||||
objects.push(Vec::new());
|
||||
Encoding {
|
||||
object: objects.len(),
|
||||
names: BTreeMap::new(),
|
||||
}
|
||||
});
|
||||
for slot in slots {
|
||||
let name = paint.encoding[usize::from(slot)].as_str();
|
||||
encoding.names.insert(slot, name);
|
||||
}
|
||||
Some(encoding.object)
|
||||
}
|
||||
|
||||
pub(super) fn write(self, objects: &mut [Vec<u8>]) {
|
||||
for encoding in self.0.into_values() {
|
||||
let mut value = "<< /Type /Encoding /Differences [".to_owned();
|
||||
let mut next = None;
|
||||
for (slot, name) in encoding.names {
|
||||
if next != Some(slot) {
|
||||
write!(value, " {slot}").unwrap();
|
||||
}
|
||||
write!(value, "/{}", native_pdf_name(name)).unwrap();
|
||||
next = slot.checked_add(1);
|
||||
}
|
||||
value.push_str("] >>");
|
||||
objects[encoding.object - 1] = value.into_bytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
use super::{native_font_units, native_pdf_font_size, native_pdf_name, objects};
|
||||
use super::{native_pdf_name, objects};
|
||||
use crate::{
|
||||
native_font::{NativeFontPaint, TrueTypeProgram},
|
||||
tfm::TfmMetrics,
|
||||
type1_outline::subset_tag,
|
||||
};
|
||||
use rustybuzz::ttf_parser::Tag;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub(super) fn write(
|
||||
@@ -38,23 +37,6 @@ pub(super) fn write(
|
||||
};
|
||||
let data = program.embed(slots.into_iter(), paint.subset)?;
|
||||
let face = program.face()?;
|
||||
let in_pdf_units = |value: i16| 1000 * i32::from(value) / i32::from(face.units_per_em());
|
||||
let ascent = in_pdf_units(face.tables().hhea.ascender);
|
||||
let descent = in_pdf_units(face.tables().hhea.descender);
|
||||
let pclt = face.raw_face().table(Tag::from_bytes(b"PCLT"));
|
||||
let pclt_height = |offset| {
|
||||
let bytes = pclt?.get(offset..offset + 2)?;
|
||||
Some(in_pdf_units(i16::from_be_bytes(bytes.try_into().ok()?)))
|
||||
};
|
||||
let size = native_pdf_font_size(metrics.size_sp());
|
||||
let cap = pclt_height(16)
|
||||
.unwrap_or_else(|| native_font_units(metrics.height('H'), size, 1000) as i32);
|
||||
let x_height =
|
||||
pclt_height(10).unwrap_or_else(|| native_font_units(metrics.x_height(), size, 1000) as i32);
|
||||
let stem = native_font_units(metrics.width('.') / 3, size, 1000);
|
||||
let angle = face.italic_angle().floor() as i32;
|
||||
let [left, bottom, right, top] = paint.bbox;
|
||||
let flags = paint.descriptor_flags.unwrap_or(4);
|
||||
|
||||
let font_file = objects.len() + 1;
|
||||
objects.push(objects::stream(
|
||||
@@ -62,9 +44,13 @@ pub(super) fn write(
|
||||
&data,
|
||||
compression,
|
||||
));
|
||||
let descriptor = objects.len() + 1;
|
||||
objects.push(format!(
|
||||
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /Ascent {ascent} /Descent {descent} /CapHeight {cap} /ItalicAngle {angle} /StemV {stem} /XHeight {x_height} /FontFile2 {font_file} 0 R >>"
|
||||
).into_bytes());
|
||||
let descriptor = super::write_sfnt_descriptor(
|
||||
objects,
|
||||
metrics,
|
||||
&face,
|
||||
paint,
|
||||
&name,
|
||||
("FontFile2", font_file),
|
||||
);
|
||||
Ok((descriptor, name))
|
||||
}
|
||||
@@ -157,8 +157,7 @@ impl NativeText {
|
||||
let expansion = if self.xdv { font.expansion } else { self.expansion };
|
||||
let advance = match &paint.program {
|
||||
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
|
||||
crate::native_font::NativeFontProgram::Type1(_)
|
||||
| crate::native_font::NativeFontProgram::TrueType(_) => {
|
||||
_ => {
|
||||
let factor = i64::from(1000 + expansion);
|
||||
let width = if !self.xdv || font.layout_metrics.is_some() {
|
||||
Self::round_scale(font.advance(slot), 1000, factor)
|
||||
@@ -266,11 +265,7 @@ pub(crate) struct FontHistory {
|
||||
impl FontHistory {
|
||||
fn record(&mut self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) {
|
||||
if self.used.insert(font.id)
|
||||
&& matches!(
|
||||
paint.program,
|
||||
crate::native_font::NativeFontProgram::Type1(_)
|
||||
| crate::native_font::NativeFontProgram::TrueType(_)
|
||||
)
|
||||
&& !matches!(paint.program, crate::native_font::NativeFontProgram::Pk(_))
|
||||
&& !self.first_scalable.contains_key(&font.name)
|
||||
{
|
||||
self.first_scalable.insert(font.name.clone(), font.id);
|
||||
|
||||
@@ -819,6 +819,33 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
|
||||
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
|
||||
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
|
||||
|
||||
### pdfTeX 映射的 OpenType CFF 字体
|
||||
|
||||
传统字体映射读取实际 OpenType、TFM 和可选编码文件。TeX 槽位
|
||||
使用 CFF 内建编码或映射指定的字形名。SVG 使用实际 CFF 轮廓及
|
||||
FontMatrix。PDF 以 Type1 字典引用 FontFile3 的原始 Type1C 表,
|
||||
字体名使用实际映射声明。同一编码资源的多个 CFF 字体共用
|
||||
Differences,包含实际使用的 .notdef 槽位。
|
||||
[原版整嵌写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writettf.c#L1326-L1364)
|
||||
[原版编码写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writeenc.c#L101-L144)
|
||||
|
||||
本轮开发构建的三项定向回归通过。Latin Modern 正体和斜体的
|
||||
五个原版对照覆盖内建编码、显式编码、映射别名、共享编码及
|
||||
未定义槽位。五页 144 DPI 灰度、词框、提取文字、字符宽度、
|
||||
描述符及 FontFile3 内的原始 CFF 表一致。请求 CFF 子集时
|
||||
两端都报错。字体和编码对象的编号仍有差异。
|
||||
|
||||
三页会话中,修改编码重新执行,正文修改及恢复缺失字体各
|
||||
复用 106 步。三次发布都只更新第 2 页,PDF、测量页面、完整
|
||||
SVG、来源映射及 aux 与独立全量一致。字体缺失的修订保留
|
||||
上一版预览和 aux。
|
||||
|
||||
证据在 target/p3-mapped-cff。receipt.json 的 SHA-256 为
|
||||
c5ce4efab121f6be71ad98a76eadca7d3409e6bd2801e2eb6b8630799d97442c。
|
||||
下一入口是 TrueType 的 SFD 子字体。next-truetype-sfd 保存真实
|
||||
Droid Sans Fallback、TFM、SFD 及原版子集 PDF。现用候选未消费
|
||||
SFD,查找 cjk00 的 PK 位图后报告缺失。
|
||||
|
||||
### pdfTeX 映射的 TrueType 字体
|
||||
|
||||
pdfTeX 的字体映射可读取实际 TrueType 程序和编码文件。
|
||||
|
||||
@@ -1888,6 +1888,75 @@ fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_opentype_cff_paints_reencoded_glyphs_and_embeds_the_original_table() {
|
||||
use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};
|
||||
|
||||
let root = directory("mapped-opentype-cff").canonicalize().unwrap();
|
||||
for name in ["lmroman10-regular.otf", "lm-ec.enc", "ec-lmr10.tfm"] {
|
||||
let file = Command::new("kpsewhich").arg(name).output().unwrap();
|
||||
assert!(file.status.success(), "missing reference resource {name}");
|
||||
fs::copy(String::from_utf8(file.stdout).unwrap().trim(), root.join(name)).unwrap();
|
||||
}
|
||||
let map = root.join("pdftex.map");
|
||||
fs::write(
|
||||
&map,
|
||||
b"ec-lmr10 LMRoman10-Regular <lm-ec.enc <<lmroman10-regular.otf\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("main.tex"),
|
||||
br"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfcompresslevel=0
|
||||
\pdfgentounicode=1 \pdfglyphtounicode{eacute}{00E9}
|
||||
\font\mapped=ec-lmr10 \shipout\hbox{\mapped \char233{} A}
|
||||
\end",
|
||||
)
|
||||
.unwrap();
|
||||
let mut job = request(&root);
|
||||
for kind in [
|
||||
ResourceKind::Map,
|
||||
ResourceKind::OpenType,
|
||||
ResourceKind::Encoding,
|
||||
ResourceKind::Tfm,
|
||||
] {
|
||||
job.world
|
||||
.paths
|
||||
.insert(kind, vec![SearchPath::directory(&root, false)]);
|
||||
}
|
||||
let compiler = NativeCompiler::default();
|
||||
let first = compiler.compile(job.clone()).unwrap();
|
||||
assert!(first.pages[0].items.iter().any(|item| {
|
||||
matches!(item, DisplayItem::NativeGlyph { slot: 233, character: 'é', paint: Some(paint), .. }
|
||||
if matches!(paint.program, NativeFontProgram::OpenTypeCff(_))
|
||||
&& !paint.glyph_paths[&233].is_empty())
|
||||
}));
|
||||
for name in ["pdftex.map", "lm-ec.enc", "lmroman10-regular.otf", "ec-lmr10.tfm"] {
|
||||
let version = file_version(&root.join(name)).unwrap().unwrap();
|
||||
assert!(first.resources.trace.reads.contains(&version));
|
||||
}
|
||||
let pdf = lopdf::Document::load_mem(first.pdf.as_deref().unwrap()).unwrap();
|
||||
let (_, font) = pdf.objects.iter().find_map(|(id, object)| {
|
||||
let dict = object.as_dict().ok()?;
|
||||
(dict.get(b"Subtype").ok()?.as_name().ok()? == b"Type1").then_some((id, dict))
|
||||
}).unwrap();
|
||||
assert!(font.get(b"ToUnicode").unwrap().as_reference().is_ok());
|
||||
assert!(font.get(b"Encoding").unwrap().as_reference().is_ok());
|
||||
let descriptor = font.get(b"FontDescriptor").unwrap().as_reference().unwrap();
|
||||
let descriptor = pdf.get_dictionary(descriptor).unwrap();
|
||||
let font_file = descriptor.get(b"FontFile3").unwrap().as_reference().unwrap();
|
||||
let embedded = pdf.get_object(font_file).unwrap().as_stream().unwrap();
|
||||
assert_eq!(embedded.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Type1C");
|
||||
let source = fs::read(root.join("lmroman10-regular.otf")).unwrap();
|
||||
assert_eq!(embedded.content[0], 1);
|
||||
assert!(source.windows(embedded.content.len()).any(|bytes| bytes == embedded.content));
|
||||
|
||||
fs::remove_file(root.join("lm-ec.enc")).unwrap();
|
||||
let error = compiler.compile_detailed(job).err().unwrap().error.to_string();
|
||||
assert!(error.contains("lm-ec.enc"), "{error}");
|
||||
assert!(Arc::ptr_eq(&first, &compiler.latest().unwrap()));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_truetype_paints_and_embeds_the_actual_font() {
|
||||
use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};
|
||||
|
||||
Reference in new issue
Block a user