Render legacy XeLaTeX composite TrueType fonts
This commit is contained in:
1 parent
7d460e0fa1
commit
bbeeca0317
11 files changed
+687
-55
No files matched your search
@@ -34,6 +34,21 @@ pub(super) struct MapEntry {
|
||||
xdv_matrix: XdvFontMatrix,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) xdv_to_unicode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) xdv_encoding: Option<XdvEncoding>,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub(super) face_index: u32,
|
||||
}
|
||||
|
||||
fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct XdvEncoding {
|
||||
pub(super) name: String,
|
||||
pub(super) prefix: u32,
|
||||
pub(super) vertical: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -97,6 +112,8 @@ impl MapEntry {
|
||||
subset: false,
|
||||
xdv_matrix: XdvFontMatrix::default(),
|
||||
xdv_to_unicode: None,
|
||||
xdv_encoding: None,
|
||||
face_index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,14 +375,14 @@ fn parse_xdv_map_line(
|
||||
.filter(|field| !matches!(*field, "default" | "none"))
|
||||
});
|
||||
if let Some(encoding) = fields.next().flatten() {
|
||||
if encoding == "unicode" || encoding.starts_with("Identity-") {
|
||||
return Err(format!("unsupported XDV composite map encoding {encoding} for {name}"));
|
||||
}
|
||||
entry.encoding = Some(if encoding.ends_with(".enc") {
|
||||
encoding.to_owned()
|
||||
if encoding.ends_with(".enc") {
|
||||
entry.encoding = Some(encoding.to_owned());
|
||||
} else {
|
||||
format!("{encoding}.enc")
|
||||
});
|
||||
entry.xdv_encoding = Some(XdvEncoding { name: encoding.into(), prefix: 0, vertical: false });
|
||||
if !matches!(encoding, "unicode" | "Identity-H" | "Identity-V") && !encoding.ends_with(".cmap") {
|
||||
entry.encoding = Some(format!("{encoding}.enc"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let file = fields.next().flatten().unwrap_or(name);
|
||||
if file.contains([':', ',']) || file.starts_with('!') {
|
||||
@@ -385,6 +402,31 @@ fn parse_xdv_map_line(
|
||||
.ok_or_else(|| format!("missing XDV map ToUnicode name for {name}"))?;
|
||||
entry.xdv_to_unicode = Some(name.into());
|
||||
}
|
||||
"-i" => {
|
||||
entry.face_index = words.next().and_then(|index| index.parse().ok())
|
||||
.ok_or_else(|| format!("invalid XDV map face index for {name}"))?;
|
||||
}
|
||||
"-w" | "-p" | "-m" => {
|
||||
let encoding = entry.xdv_encoding.as_mut().ok_or_else(|| format!("XDV map option {option} requires a CMap for {name}"))?;
|
||||
let operand = words.next().ok_or_else(|| format!("missing XDV map option {option} for {name}"))?;
|
||||
match option {
|
||||
"-w" if encoding.name == "unicode" => encoding.vertical = match operand {
|
||||
"0" => false,
|
||||
"1" => true,
|
||||
_ => return Err(format!("invalid XDV map writing mode for {name}")),
|
||||
},
|
||||
"-p" if encoding.name == "unicode" => {
|
||||
encoding.prefix = operand.parse::<u32>().ok().filter(|&n| n <= 16)
|
||||
.ok_or_else(|| format!("invalid XDV map Unicode plane for {name}"))? << 16;
|
||||
}
|
||||
"-m" if operand.starts_with("pad:") => {
|
||||
let pad = u8::from_str_radix(&operand[4..], 16)
|
||||
.map_err(|_| format!("invalid XDV map code padding for {name}"))?;
|
||||
encoding.prefix = (encoding.prefix & !0xff00) | (u32::from(pad) << 8);
|
||||
}
|
||||
_ => return Err(format!("unsupported XDV map option {option} for {name}: {operand}")),
|
||||
}
|
||||
}
|
||||
"-s" | "-e" => {
|
||||
let number = words.next().and_then(|word| word.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
@@ -973,5 +1015,7 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
|
||||
subset: false,
|
||||
xdv_matrix: XdvFontMatrix::default(),
|
||||
xdv_to_unicode: None,
|
||||
xdv_encoding: None,
|
||||
face_index: 0,
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
|
||||
use super::{
|
||||
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
||||
map::{MapEntry, OutlineFiles},
|
||||
map::{MapEntry, OutlineFiles, XdvEncoding},
|
||||
};
|
||||
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||
use crate::{execution::SourceProvider, pdf_device::cmap::CMap, resources::ResourceKind};
|
||||
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -16,6 +16,10 @@ pub struct TrueTypeProgram {
|
||||
pub(crate) name: String,
|
||||
data: Arc<[u8]>,
|
||||
glyphs: Vec<u16>,
|
||||
#[serde(default)]
|
||||
pub(crate) face_index: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) composite: Option<CompositeTrueType>,
|
||||
pub(crate) reencoded: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
|
||||
@@ -23,12 +27,50 @@ pub struct TrueTypeProgram {
|
||||
pub(crate) missing_subfont_cmap: Option<[u16; 2]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct CompositeTrueType {
|
||||
pub(crate) registry: String,
|
||||
pub(crate) ordering: String,
|
||||
pub(crate) supplement: u32,
|
||||
slots: Vec<CompositeSlot>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
struct CompositeSlot {
|
||||
cid: u16,
|
||||
advance: u32,
|
||||
unicode: Option<String>,
|
||||
}
|
||||
|
||||
impl CompositeTrueType {
|
||||
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 unicode(&self, slot: u8) -> Option<&str> {
|
||||
self.slots[usize::from(slot)].unicode.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl TrueTypeProgram {
|
||||
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
|
||||
Face::parse(&self.data, 0)
|
||||
Face::parse(&self.data, self.face_index)
|
||||
.map_err(|error| format!("invalid TrueType font {}: {error}", self.name))
|
||||
}
|
||||
|
||||
pub(crate) fn glyph_id(&self, slot: u8) -> u16 {
|
||||
self.glyphs[usize::from(slot)]
|
||||
}
|
||||
|
||||
pub(crate) fn embed_cid_subset(&self, remapper: &GlyphRemapper) -> Result<Vec<u8>, String> {
|
||||
subsetter::subset(&self.data, self.face_index, remapper)
|
||||
.map_err(|error| format!("failed to subset CID font {}: {error}", self.name))
|
||||
}
|
||||
|
||||
pub(crate) fn embed(
|
||||
&self,
|
||||
slots: impl Iterator<Item = u8>,
|
||||
@@ -51,7 +93,7 @@ impl TrueTypeProgram {
|
||||
let index = usize::from(slot);
|
||||
mapping[index] = remapper.remap(self.glyphs[index]);
|
||||
}
|
||||
let data = subsetter::subset(&self.data, 0, &remapper)
|
||||
let data = subsetter::subset(&self.data, self.face_index, &remapper)
|
||||
.map_err(|error| format!("failed to subset TrueType font {}: {error}", self.name))?;
|
||||
let face = RawFace::parse(&data, 0).map_err(|error| error.to_string())?;
|
||||
let mut tables = tables(&face)?;
|
||||
@@ -101,6 +143,157 @@ pub(super) fn device_program(
|
||||
Ok(Some(data.into()))
|
||||
}
|
||||
|
||||
enum Codes {
|
||||
Unicode,
|
||||
Identity,
|
||||
Custom(Box<CMap>),
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
fn load(encoding: &XdvEncoding, outline: &MapEntry, files: &mut impl SourceProvider) -> Result<Option<Self>, String> {
|
||||
let name = &encoding.name;
|
||||
if encoding.vertical || name == "Identity-V" {
|
||||
return Err(format!("XDV legacy composite vertical metrics are not implemented for {name}"));
|
||||
}
|
||||
Ok(Some(match name.as_str() {
|
||||
"unicode" => Self::Unicode,
|
||||
"Identity-H" => 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")) };
|
||||
};
|
||||
if map.is_vertical() {
|
||||
return Err(format!("XDV legacy composite vertical metrics are not implemented for {name}"));
|
||||
}
|
||||
Self::Custom(Box::new(map))
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_composite(
|
||||
files: &mut impl SourceProvider,
|
||||
outlines: &mut OutlineFiles,
|
||||
outline: &MapEntry,
|
||||
file: &str,
|
||||
font: &NativeFont,
|
||||
slots: BTreeSet<u8>,
|
||||
encoding: &XdvEncoding,
|
||||
codes: Codes,
|
||||
) -> Result<NativeFontPaint, String> {
|
||||
let mut outline_without_encoding = outline.clone();
|
||||
outline_without_encoding.encoding = None;
|
||||
let MappedOutline {
|
||||
data, mut resources, program_index, ..
|
||||
} = outline_without_encoding.read_outline(files, outlines, ResourceKind::TrueType, file)?;
|
||||
let face = Face::parse(&data, outline.face_index)
|
||||
.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 (registry, ordering, 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 = registry == "Adobe" && ordering == "Identity";
|
||||
let collection_to_unicode = if !identity {
|
||||
let map = CMap::load(&format!("{registry}-{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 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 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().filter(|&cid| cid < face.number_of_glyphs())
|
||||
.map(|cid| (cid, cid, None)),
|
||||
Codes::Custom(map) => map.cid(code).and_then(|cid| {
|
||||
if identity {
|
||||
return (cid < face.number_of_glyphs()).then_some((cid, cid, None));
|
||||
}
|
||||
let text = collection_to_unicode.as_ref()?.unicode(2, u32::from(cid))?;
|
||||
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 (cid, 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));
|
||||
let index = usize::from(slot);
|
||||
glyphs[index] = gid;
|
||||
cells[index] = CompositeSlot {
|
||||
cid,
|
||||
advance: cid_width(&face, gid),
|
||||
unicode: text.clone(),
|
||||
};
|
||||
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])));
|
||||
}
|
||||
}
|
||||
let name = font_name(&face, outline, font);
|
||||
let bbox = font_bbox(&face);
|
||||
let composite = CompositeTrueType {
|
||||
registry: registry.to_owned(), ordering: ordering.to_owned(), supplement, slots: cells,
|
||||
};
|
||||
let program = TrueTypeProgram {
|
||||
name, data, glyphs, face_index: outline.face_index, composite: Some(composite),
|
||||
reencoded: false, subfont_codes: None, missing_subfont_cmap: None,
|
||||
};
|
||||
Ok(NativeFontPaint {
|
||||
program: NativeFontProgram::TrueType(program),
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
outlines: &mut OutlineFiles,
|
||||
@@ -109,6 +302,11 @@ pub(super) fn resolve(
|
||||
font: &NativeFont,
|
||||
slots: BTreeSet<u8>,
|
||||
) -> Result<NativeFontPaint, String> {
|
||||
if let Some(encoding) = &outline.xdv_encoding
|
||||
&& let Some(codes) = Codes::load(encoding, outline, files)?
|
||||
{
|
||||
return resolve_composite(files, outlines, outline, file, font, slots, encoding, codes);
|
||||
}
|
||||
let MappedOutline {
|
||||
data,
|
||||
encoding,
|
||||
@@ -116,7 +314,7 @@ pub(super) fn resolve(
|
||||
program_index,
|
||||
} = outline.read_outline(files, outlines, ResourceKind::TrueType, file)?;
|
||||
let face =
|
||||
Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
|
||||
Face::parse(&data, outline.face_index).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}"));
|
||||
}
|
||||
@@ -195,15 +393,8 @@ pub(super) fn resolve(
|
||||
(slot, path)
|
||||
})
|
||||
.collect();
|
||||
let name = face
|
||||
.names()
|
||||
.into_iter()
|
||||
.filter(|name| name.name_id == 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 = 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 name = font_name(&face, outline, font);
|
||||
let bbox = font_bbox(&face);
|
||||
let missing_subfont_cmap = subfont
|
||||
.filter(|_| subfont_cmap.is_none())
|
||||
.map(|subfont| subfont.cmap);
|
||||
@@ -211,6 +402,8 @@ pub(super) fn resolve(
|
||||
name,
|
||||
data,
|
||||
glyphs,
|
||||
face_index: outline.face_index,
|
||||
composite: None,
|
||||
reencoded,
|
||||
subfont_codes: subfont.map(|subfont| subfont.codes.clone()),
|
||||
missing_subfont_cmap,
|
||||
@@ -232,6 +425,25 @@ pub(super) fn resolve(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn cid_width(face: &Face<'_>, glyph: u16) -> u32 {
|
||||
let advance = face.glyph_hor_advance(GlyphId(glyph)).unwrap_or(0);
|
||||
(f64::from(advance) * 1000.0 / f64::from(face.units_per_em())).round() as u32
|
||||
}
|
||||
|
||||
fn font_name(face: &Face<'_>, outline: &MapEntry, font: &NativeFont) -> String {
|
||||
face.names()
|
||||
.into_iter()
|
||||
.filter(|name| name.name_id == name_id::POST_SCRIPT_NAME)
|
||||
.find_map(|name| name.to_string())
|
||||
.unwrap_or_else(|| outline.postscript_name().unwrap_or(&font.name).to_owned())
|
||||
}
|
||||
|
||||
fn font_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()))
|
||||
}
|
||||
|
||||
fn platform_number(platform: PlatformId) -> u16 {
|
||||
match platform {
|
||||
PlatformId::Unicode => 0,
|
||||
|
||||
Reference in new issue
Block a user