Render legacy XeLaTeX composite TrueType fonts

This commit is contained in:
gloamxun committed 2026-11-28 21:59:30 +08:00
1 parent 7d460e0fa1
commit bbeeca0317
11 files changed
+687 -55

No files matched your search

+30 -1
View File
@@ -21,6 +21,7 @@ mod virtual_paint;
pub use cff::OpenTypeCffProgram;
pub use device_type1::DeviceType1Program;
pub use truetype::TrueTypeProgram;
pub(crate) use truetype::cid_width;
pub use map::PdfFontBindings;
pub(crate) use map::XdvFontMatrix;
use map::{dedicated_space_map, find_map_entry, load_map, selected_outline};
@@ -80,6 +81,22 @@ impl MappedType1 {
}
impl NativeFontPaint {
pub(crate) fn program_version(&self) -> Option<&ResourceVersion> {
self.resources.get(self.program_index?)
}
pub(crate) fn legacy_cid_font(&self) -> Option<&truetype::CompositeTrueType> {
match &self.program {
NativeFontProgram::TrueType(program) => program.composite.as_ref(),
_ => None,
}
}
pub(crate) fn mapped_text(&self, slot: u8) -> Option<&str> {
self.xdv_unicode.as_ref().and_then(|map| map.texts.get(&slot)).map(String::as_str)
.or_else(|| self.legacy_cid_font()?.unicode(slot))
}
pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool {
// pdfTeX requires the space name in an actual map re-encoding.
self.encoding_version().is_some()
@@ -464,6 +481,9 @@ fn resolve_xdv_unicode(
let mut owners: std::collections::HashMap<_, Option<Arc<XdvFontUnicode>>> = std::collections::HashMap::new();
for (id, font_name) in used {
let paint = resolved.get_mut(&id).expect("resolved device font");
if paint.legacy_cid_font().is_some() {
continue;
}
// The PDF writer shares one Type 1 resource and encoding among all
// sizes and aliases of the same physical program.
let owner_key = paint.xdv_descriptor.and_then(|_| paint.type1_program_key())
@@ -640,6 +660,15 @@ fn resolve_physical_fonts(
direct_resolved.insert(id, Arc::new(paint));
continue;
}
if let Some(encoding) = &outline.xdv_encoding
&& (outline.encoding.is_none() || files.optional_font_file(
ResourceKind::CMap, &encoding.name, &outline.from.to_string_lossy(),
)?.is_some())
{
return Err(format!(
"native XDV composite encoding {} requires a TrueType program: {}", encoding.name, font.name,
));
}
if let Some(file) = outline.open_type_file() {
let mut paint = cff::resolve(files, &mut outlines, outline, file, &font, slots)?;
paint.xdv_matrix = matrix;
@@ -754,7 +783,7 @@ fn resolve_physical_fonts(
} = item
{
let p = resolved[&font.id].clone();
*character = p.xdv_unicode.as_ref().and_then(|map| map.texts.get(slot))
*character = p.mapped_text(*slot)
.and_then(|text| text.chars().next()).unwrap_or_else(|| match &p.program {
NativeFontProgram::Type1(_)
| NativeFontProgram::DeviceType1(_)
+51 -7
View File
@@ -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,
+18 -5
View File
@@ -626,6 +626,7 @@ struct PageContent {
bytes: Vec<u8>,
origin: crate::pdf_device::DeviceOrigin,
measuring: bool,
track_legacy_cids: bool,
}
impl PageContent {
@@ -724,6 +725,8 @@ pub(crate) fn prepare_text_spaces(
Ok(())
}
pub(crate) use native_text::legacy_cid_positions;
fn page_content(
list: &DisplayList,
height: i64,
@@ -895,7 +898,7 @@ fn page_content(
if tex_text.is_none() {
content.move_origin(page_origin, list.units, digits);
}
native_text::NativeText::glyph(
let _ = native_text::NativeText::glyph(
&mut tex_text,
&mut content,
*x,
@@ -1918,6 +1921,9 @@ fn write_native_font(
if let NativeFontProgram::Pk(pk) = &paint.program {
return Ok(pk_fonts::write_font(objects, face.id, pk, used, compression, target));
}
if let NativeFontProgram::TrueType(program) = &paint.program && program.composite.is_some() {
return truetype_fonts::write_cid(objects, program, used.keys().copied(), compression, subset_tags, target);
}
let id = target.unwrap_or_else(|| {
objects.push(Vec::new());
objects.len()
@@ -2513,10 +2519,17 @@ fn write_pdf(
let xdv_font_aliases: BTreeMap<_, _> = {
let mut owners = HashMap::new();
let mut cid_owners = HashMap::new();
native_used.iter().filter_map(|(&id, (_, paint, _))| {
paint.xdv_descriptor?;
let key = (paint.type1_program_key()?, paint.encoding_version());
let owner = *owners.entry(key).or_insert(id);
let owner = if let crate::native_font::NativeFontProgram::TrueType(program) = &paint.program
&& let Some(composite) = &program.composite
{
*cid_owners.entry((paint.program_version()?, program.face_index, composite)).or_insert(id)
} else {
paint.xdv_descriptor?;
let key = (paint.type1_program_key()?, paint.encoding_version());
*owners.entry(key).or_insert(id)
};
(owner != id).then_some((id, owner))
}).collect()
};
@@ -2541,7 +2554,7 @@ fn write_pdf(
{
return Err("shared PDF font has inconsistent output encoding or program".into());
}
if xdv_font_aliases.contains_key(&id) {
if paint.xdv_descriptor.is_some() && xdv_font_aliases.contains_key(&id) {
// Separate map entries can resolve to the same physical
// program with disjoint sets of measured glyph widths.
for slot in used.keys() {
@@ -62,3 +62,111 @@ pub(super) fn write(
);
Ok((descriptor, name))
}
pub(super) fn write_cid(
objects: &mut Vec<Vec<u8>>,
program: &TrueTypeProgram,
slots: impl Iterator<Item = u8>,
compression: u8,
subset_tags: &mut BTreeSet<String>,
target: Option<usize>,
) -> Result<usize, String> {
use crate::native_font::cid_width;
use std::{collections::BTreeMap, fmt::Write as _};
use subsetter::GlyphRemapper;
let mapping = program.composite.as_ref().expect("composite TrueType program");
let face = program.face()?;
let mut glyphs = BTreeMap::new();
let mut unicode = BTreeMap::new();
for slot in slots {
let cid = mapping.cid(slot);
let glyph = program.glyph_id(slot);
if glyphs.insert(cid, glyph).is_some_and(|old| old != glyph) {
return Err(format!("conflicting glyph for CID {cid} in {}", program.name));
}
if cid != 0
&& let Some(text) = mapping.unicode(slot)
{
unicode.entry(cid).or_insert_with(|| {
text.encode_utf16().map(|unit| format!("{unit:04X}")).collect()
});
}
}
let names = glyphs.keys().map(|cid| format!("/c{cid:04X}")).collect();
let tag = (0..100).map(|salt| subset_tag(&program.name, &names, salt))
.find(|tag| subset_tags.insert(tag.clone()))
.ok_or("CID subset name collision limit exceeded")?;
let name = format!("{tag}+{}", native_pdf_name(&program.name));
let mut remapper = GlyphRemapper::new();
let max = usize::from(glyphs.keys().next_back().copied().unwrap_or(0));
let mut cid_to_gid = vec![0; (max + 1) * 2];
let mut cid_set = vec![0; max / 8 + 1];
let width = |glyph| cid_width(&face, glyph);
let default = width(0);
let mut widths = String::new();
let mut previous: Option<u16> = None;
let mut identity = true;
for (&cid, &glyph) in &glyphs {
let subset_id = remapper.remap(glyph);
let index = usize::from(cid);
cid_to_gid[index * 2..index * 2 + 2].copy_from_slice(&subset_id.to_be_bytes());
if cid != 0 {
cid_set[index / 8] |= 1 << (7 - index % 8);
}
identity &= cid == subset_id;
let advance = width(glyph);
if advance == default {
continue;
}
if previous.and_then(|id| id.checked_add(1)) != Some(cid) {
if previous.is_some() {
widths.push_str("] ");
}
write!(widths, "{cid} [").unwrap();
}
write!(widths, "{advance} ").unwrap();
previous = Some(cid);
}
let widths = if widths.is_empty() { widths } else { format!(" /W [{widths}]]") };
let subset = program.embed_cid_subset(&remapper)?;
let id = target.unwrap_or_else(|| {
objects.push(Vec::new());
objects.len()
});
let fontfile = objects.len() + 1;
objects.push(objects::stream(&format!("/Length1 {}", subset.len()), &subset, compression));
let cid_set_id = objects.len() + 1;
objects.push(objects::stream("", &cid_set, compression));
let descriptor = objects.len() + 1;
let mut contents = super::opentype_fonts::font_descriptor(&face, &name, "FontFile2", fontfile);
assert!(contents.ends_with(b" >>"));
contents.truncate(contents.len() - 3);
contents.extend_from_slice(format!(" /CIDSet {cid_set_id} 0 R >>").as_bytes());
objects.push(contents);
let cid_mapping = if identity {
"/Identity".to_owned()
} else {
objects.push(objects::stream("", &cid_to_gid, compression));
format!("{} 0 R", objects.len())
};
let descendant = objects.len() + 1;
let registry = super::escape(&mapping.registry);
let ordering = super::escape(&mapping.ordering);
let supplement = mapping.supplement;
objects.push(format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} /CIDSystemInfo << /Registry ({registry}) /Ordering ({ordering}) /Supplement {supplement} >> /FontDescriptor {descriptor} 0 R /DW {default}{widths} /CIDToGIDMap {cid_mapping} >>"
).into_bytes());
let unicode_ref = if unicode.is_empty() {
String::new()
} else {
objects.push(objects::stream("", &super::to_unicode_map(&unicode, 4), compression));
format!(" /ToUnicode {} 0 R", objects.len())
};
objects[id - 1] = format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{descendant} 0 R]{unicode_ref} >>"
).into_bytes();
Ok(id)
}
+147 -18
View File
@@ -14,6 +14,12 @@ const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024;
pub(crate) struct CMap {
codespaces: [Vec<[u32; 2]>; 4],
mappings: [BTreeMap<u32, Mapping>; 4],
cid_mappings: [BTreeMap<u32, CidRange>; 4],
notdef: [BTreeMap<u32, CidRange>; 4],
registry: Option<String>,
ordering: Option<String>,
supplement: Option<u32>,
vertical: Option<bool>,
inherited: Option<Arc<CMap>>,
pub(crate) resources: Vec<ResourceVersion>,
}
@@ -24,6 +30,12 @@ struct Mapping {
destination: Destination,
}
#[derive(Debug)]
struct CidRange {
last: u32,
cid: u16,
}
#[derive(Debug)]
enum Destination {
Sequential(Vec<u8>),
@@ -36,6 +48,14 @@ impl CMap {
from: &str,
files: &mut impl SourceProvider,
) -> Result<Self, String> {
Self::load_optional(name, from, files)?.ok_or_else(|| format!("CMap {name} was not found"))
}
pub(crate) fn load_optional(
name: &str,
from: &str,
files: &mut impl SourceProvider,
) -> Result<Option<Self>, String> {
Self::load_inner(name, from, files, &mut Vec::new())
}
@@ -44,10 +64,10 @@ impl CMap {
from: &str,
files: &mut impl SourceProvider,
stack: &mut Vec<ResourceVersion>,
) -> Result<Self, String> {
let resource = files
.optional_font_file(ResourceKind::CMap, name, from)?
.ok_or_else(|| format!("CMap {name} was not found"))?;
) -> Result<Option<Self>, String> {
let Some(resource) = files.optional_font_file(ResourceKind::CMap, name, from)? else {
return Ok(None);
};
let resource = crate::native_font::verify_resource(resource, ResourceKind::CMap, name)?;
if stack.len() == MAX_CMAP_DEPTH || stack.iter().any(|v| v.path == resource.version.path) {
return Err(format!("invalid CMap inheritance for {name}"));
@@ -65,7 +85,8 @@ impl CMap {
&resource.version.path.to_string_lossy(),
files,
stack,
)?;
)?
.ok_or_else(|| format!("CMap {base} was not found"))?;
map.resources.extend(inherited.resources.iter().cloned());
map.inherited = Some(Arc::new(inherited));
}
@@ -73,7 +94,7 @@ impl CMap {
if map.codespaces.iter().all(Vec::is_empty) && map.inherited.is_none() {
return Err(format!("CMap {name} has no code space"));
}
Ok(map)
Ok(Some(map))
}
fn parse(data: &[u8]) -> Result<(Self, Option<String>), String> {
@@ -81,6 +102,12 @@ impl CMap {
let mut map = Self {
codespaces: Default::default(),
mappings: Default::default(),
cid_mappings: Default::default(),
notdef: Default::default(),
registry: None,
ordering: None,
supplement: None,
vertical: None,
inherited: None,
resources: Vec::new(),
};
@@ -92,6 +119,40 @@ impl CMap {
b"begincodespacerange" => b"endcodespacerange".as_slice(),
b"beginbfchar" => b"endbfchar",
b"beginbfrange" => b"endbfrange",
b"begincidchar" => b"endcidchar",
b"begincidrange" => b"endcidrange",
b"beginnotdefchar" => b"endnotdefchar",
b"beginnotdefrange" => b"endnotdefrange",
b"/Registry" | b"/Ordering" => {
let bytes = super::page_resources::parse_value(lexer.required()?)?
.as_str()
.map_err(|_| "invalid CMap character collection")?
.to_vec();
let value = Some(
String::from_utf8(bytes)
.map_err(|_| "invalid CMap character collection")?,
);
if token == b"/Registry" {
map.registry = value;
} else {
map.ordering = value;
}
previous = &[];
continue;
}
b"/Supplement" | b"/WMode" => {
let value = decimal(lexer.required()?)?;
if token == b"/Supplement" {
map.supplement = Some(value);
} else {
if value > 1 {
return Err("invalid CMap writing mode".into());
}
map.vertical = Some(value != 0);
}
previous = &[];
continue;
}
b"usecmap" => {
let name = previous
.strip_prefix(b"/")
@@ -124,7 +185,8 @@ impl CMap {
.ok_or("invalid CMap block count")?;
for _ in 0..count {
let (width, first) = read_code(lexer.required()?)?;
let last = if token == b"beginbfchar" {
let last = if matches!(token, b"beginbfchar" | b"begincidchar" | b"beginnotdefchar")
{
first
} else {
let (end_width, last) = read_code(lexer.required()?)?;
@@ -138,6 +200,22 @@ impl CMap {
continue;
}
let value = lexer.required()?;
if matches!(
token,
b"begincidchar" | b"begincidrange" | b"beginnotdefchar" | b"beginnotdefrange"
) {
let cid = u16::try_from(decimal(value)?).map_err(|_| "CID out of range")?;
let ranges = if matches!(token, b"beginnotdefchar" | b"beginnotdefrange") {
&mut map.notdef
} else {
if u32::from(cid).saturating_add(last - first) > u32::from(u16::MAX) {
return Err("CID range out of bounds".into());
}
&mut map.cid_mappings
};
ranges[width - 1].insert(first, CidRange { last, cid });
continue;
}
let destination = if value == b"[" && token == b"beginbfrange" {
let len = u64::from(last) - u64::from(first) + 1;
if len > data.len() as u64 {
@@ -227,23 +305,74 @@ impl CMap {
Ok(output)
}
pub(crate) fn collection(&self) -> Option<(&str, &str, u32)> {
match (&self.registry, &self.ordering) {
(Some(registry), Some(ordering)) => {
Some((registry, ordering, self.supplement.unwrap_or(0)))
}
_ => self.inherited.as_ref()?.collection(),
}
}
pub(crate) fn is_vertical(&self) -> bool {
self.vertical.unwrap_or_else(|| {
self.inherited
.as_ref()
.is_some_and(|base| base.is_vertical())
})
}
pub(crate) fn cid(&self, code: u32) -> Option<u16> {
let width = (1..=4).find(|&width| self.in_codespace(width, code))?;
self.find_cid(width, code)
}
fn find_cid(&self, width: usize, code: u32) -> Option<u16> {
if let Some((&first, range)) = self.cid_mappings[width - 1].range(..=code).next_back()
&& code <= range.last
{
return Some(range.cid + (code - first) as u16);
}
if let Some(cid) = self
.inherited
.as_ref()
.and_then(|base| base.find_cid(width, code))
{
return Some(cid);
}
self.notdef[width - 1]
.range(..=code)
.next_back()
.filter(|(_, range)| code <= range.last)
.map(|(_, range)| range.cid)
}
pub(crate) fn unicode(&self, width: usize, code: u32) -> Option<String> {
let bytes = self.lookup(width, code)?;
if bytes.is_empty() || bytes.len() % 2 != 0 {
return None;
}
let units: Vec<_> = bytes
.chunks_exact(2)
.map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
.collect();
String::from_utf16(&units).ok()
}
pub(crate) fn simple_unicode(&self) -> BTreeMap<u8, String> {
(0..=255)
.filter_map(|slot| {
let bytes = self.lookup(1, u32::from(slot))?;
if bytes.is_empty() || bytes.len() % 2 != 0 {
return None;
}
let units: Vec<_> = bytes
.chunks_exact(2)
.map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
.collect();
Some((slot, String::from_utf16(&units).ok()?))
})
.filter_map(|slot| Some((slot, self.unicode(1, u32::from(slot))?)))
.collect()
}
}
fn decimal(token: &[u8]) -> Result<u32, String> {
std::str::from_utf8(token)
.ok()
.and_then(|value| value.parse().ok())
.ok_or_else(|| "invalid CMap number".into())
}
fn read_hex(token: &[u8]) -> Result<Vec<u8>, String> {
let digits = token
.strip_prefix(b"<")
+1 -1
View File
@@ -519,7 +519,7 @@ fn write_font(
})
}
fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_file: usize) -> Vec<u8> {
pub(super) fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_file: usize) -> Vec<u8> {
// XDV uses the OS/2 typographic values for PDF metadata independently
// of the metrics selected by the layout engine.
let os2 = face
@@ -50,7 +50,7 @@ impl XdvGlyphNames {
}
}
pub(super) fn map_glyphs(
pub(crate) fn map_glyphs(
face: &Face<'_>,
glyphs: impl Iterator<Item = u16>,
names: Option<&XdvGlyphNames>,
+61 -4
View File
@@ -21,6 +21,7 @@ pub(super) struct NativeText {
v: i64,
start_h: i64,
delta_h: i64,
cursor_correction: f64,
opened: bool,
}
impl NativeText {
@@ -38,7 +39,7 @@ impl NativeText {
digits: u8,
space: Option<SpaceUse>,
dedicated: Option<&ResolvedSpaceFont>,
) {
) -> Option<[f64; 2]> {
let first = text.is_none();
let state = text.get_or_insert_with(|| {
out.push_str("BT\n");
@@ -59,6 +60,7 @@ impl NativeText {
v: xdv_origin.unwrap_or(height),
start_h: xdv_origin.unwrap_or(0),
delta_h: 0,
cursor_correction: 0.0,
opened: false,
}
});
@@ -139,22 +141,49 @@ impl NativeText {
state.v -= v_out;
}
state.delta_h = 0;
state.cursor_correction = 0.0;
shift = 0;
}
if !state.opened {
out.push(b'[');
state.opened = true;
}
let cid_advance = out.track_legacy_cids.then(|| {
paint.legacy_cid_font().map(|program| f64::from(program.advance(slot)))
}).flatten();
let viewer_em = || {
// Tf uses 4 decimal places in bp. Convert the selected em back
// to display coordinates before applying Tz and Tm.
let (number, _) = divide_scaled(font.size_sp(), 6_578_176, 6);
let sp_per_bp = 65_536.0 * 803.0 / 800.0;
number as f64 * sp_per_bp / 10_000.0
* f64::from(1000 + font.expansion) / 1000.0
* paint.xdv_matrix.coefficients()[0]
};
if shift != 0 {
if cid_advance.is_some() {
state.cursor_correction += shift as f64 * viewer_em() / 1000.0 - shift_out as f64;
}
if !out.measuring {
out.push_str(&format!(" {} ", -shift));
}
state.delta_h += shift_out;
}
if !out.measuring {
out.push_str(&format!("<{slot:02X}>"));
if let Some(composite) = paint.legacy_cid_font() {
out.push_str(&format!("<{:04X}>", composite.cid(slot)));
} else {
out.push_str(&format!("<{slot:02X}>"));
}
}
state.delta_h += state.char_advance(font, paint, slot, state.effective_size);
let advance = state.char_advance(font, paint, slot, state.effective_size);
let position = cid_advance.map(|width| {
let x = (state.start_h + state.delta_h) as f64 + state.cursor_correction;
state.cursor_correction += width * viewer_em() / 1000.0 - advance as f64;
[x, state.v as f64]
});
state.delta_h += advance;
position
}
fn select_font(&mut self, out: &mut PageContent, font: &NativeFont, resource: FontId) {
@@ -260,7 +289,7 @@ impl NativeText {
digits: u8,
dedicated: &ResolvedSpaceFont,
) {
Self::glyph(
let _ = Self::glyph(
text,
out,
x,
@@ -301,6 +330,34 @@ impl NativeText {
}
}
/// Reuse the output device's selection, position and TJ logic when a CID
/// font's PDF advances differ from the TFM used for TeX layout.
pub(crate) fn legacy_cid_positions(page: &DisplayList) -> BTreeMap<usize, [f64; 2]> {
let mut positions = BTreeMap::new();
let Some(pdf) = &page.pdf else { return positions };
if pdf.driver != crate::pdf_device::PdfDriver::Xdv {
return positions;
}
let digits = pdf.file.decimal_digits;
let origin = crate::pdf_device::xdv_page_origin(page.units, page.height, page.magnification);
let mut output = PageContent { track_legacy_cids: true, ..PageContent::measuring() };
output.move_origin(origin, page.units, digits);
let mut run = None;
for (index, item) in page.items.iter().enumerate() {
if let DisplayItem::NativeGlyph { x, y, font, slot, paint: Some(paint), .. } = item {
if let Some(position) = NativeText::glyph(
&mut run, &mut output, *x, *y, font, font.id, paint, *slot,
page.height, Some(origin[0]), digits, None, None,
) {
positions.insert(index, position);
}
} else {
NativeText::finish(&mut run, &mut output);
}
}
positions
}
#[derive(Clone, Default)]
pub(crate) struct FontHistory {
used: BTreeSet<FontId>,
+14 -4
View File
@@ -169,6 +169,7 @@ struct NativeSvgGlyph<'a> {
font: &'a str,
glyph: &'a str,
unicode: Option<&'a str>,
device_width: Option<u32>,
path: &'a str,
scalable: bool,
}
@@ -210,7 +211,8 @@ impl DisplayItem {
slot: *slot,
font: paint.program.name(),
glyph: &paint.encoding[usize::from(*slot)],
unicode: paint.xdv_unicode.as_ref().and_then(|map| map.texts.get(slot)).map(String::as_str),
unicode: paint.mapped_text(*slot),
device_width: paint.legacy_cid_font().map(|font| font.advance(*slot)),
path,
scalable: !matches!(
paint.program,
@@ -544,7 +546,8 @@ impl DisplayList {
let mut transparency = SvgTransparency::default();
let mut graphics = Vec::new();
let mut open_transforms = 0;
for item in &self.items {
let mut cid_positions = None;
for (index, item) in self.items.iter().enumerate() {
let fill_opacity = &transparency.fill;
let stroke_opacity = &transparency.stroke;
match item {
@@ -558,14 +561,21 @@ impl DisplayList {
font,
glyph,
unicode,
device_width,
path,
scalable,
} = item
.native_svg_glyph()
.unwrap()
.expect("resolved native SVG glyph");
let x = x as f64 / 65_536.0;
let y = y as f64 / 65_536.0;
let [x, y] = if device_width.is_some() {
cid_positions.get_or_insert_with(|| crate::pdf::legacy_cid_positions(self))
.get(&index).copied().unwrap_or([x as f64, y as f64])
} else {
[x as f64, y as f64]
};
let x = x / 65_536.0;
let y = y / 65_536.0;
let scale = size as f64 / 65_536_000.0;
let horizontal_scale = if expansion == 0 {
scale
+30
View File
@@ -18,6 +18,36 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-28 XeLaTeX 旧 TFM 与横排复合 TrueType
旧 TFM 按出页字体映射将原始字码解析到复合 TrueType。
支持 Unicode、Identity-H、命名 CMap 的 CID 范围和继承,
以及实际 Adobe 字符集到 Unicode 的转换。字体子集、CID 映射、
物理字宽及可提取文本由实际轮廓和映射生成。不同字号可共用
字体资源。SVG 使用同一 PDF 文字游标处理物理字宽差异,TeX
布局和来源定位保留原始 TFM 度量。
[参考复合字体选择](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdffont.c)
[参考 CID TrueType 子集](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/cidtype2.c)
直接对照包括 NotoSans、DroidSansJapanese、平假名字码和实际
Adobe-Japan1-UCS2。跨字号的两页共用一个字体对象。四组直接
作业和原样 article.cls、hyperref.sty 共七页,144 DPI 彩色
逐像素一致,全文提取及 article 的 aux 逐字节一致。原生使用
紧凑 TrueType 子集及必要的 CIDToGIDMap 流,并为 Japan1 样例
附加实际 ToUnicode。十四项 XDV 定向检查通过。
三页会话修改基础和覆盖 CMap、移除资源后恢复,每个成功修订
只更新第 2 页并复用 1,600 个执行步。PDF、测量页、SVG、来源
映射及 aux 与独立全量编译一致。缺失的基础 CMap 会保留上次
发布结果。SVG 日文字形连续两次推进均为 9.99996 pt,证明预览
采用导出的字宽并保留原始 TeX 坐标。
回执在 `target/p3-xdv-composite-legacy/receipt.json`,
SHA-256 为 `547b0f6f4f575703cf4b0faeb8265a7b71bdbf9283206b194b601ec62c45a473`。下一批扩展到竖排 CID TrueType 和
复合 CFF。`target/p3-xdv-composite-vertical-cff` 已有
真实 Identity-V 和 CID Type 0C 的参考输出及当前原生诊断。
完整出版模板矩阵与 100 ms 可见时延按既定门槛统一验收。
## 2026-11-28 XeLaTeX CMap 与 PDF Unicode 文本
`pdf:tounicode` 按实际出页顺序作用于标题、注释、书签和目录