Render vertical and CFF legacy XeLaTeX composite fonts
This commit is contained in:
1 parent
bbeeca0317
commit
ff52a9f66b
14 files changed
+877
-292
No files matched your search
@@ -13,6 +13,7 @@ use std::{
|
|||||||
sync::{Arc, Mutex, OnceLock},
|
sync::{Arc, Mutex, OnceLock},
|
||||||
};
|
};
|
||||||
mod cff;
|
mod cff;
|
||||||
|
mod composite;
|
||||||
mod device_type1;
|
mod device_type1;
|
||||||
mod map;
|
mod map;
|
||||||
mod sfd;
|
mod sfd;
|
||||||
@@ -85,9 +86,10 @@ impl NativeFontPaint {
|
|||||||
self.resources.get(self.program_index?)
|
self.resources.get(self.program_index?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn legacy_cid_font(&self) -> Option<&truetype::CompositeTrueType> {
|
pub(crate) fn legacy_cid_font(&self) -> Option<&composite::CompositeFont> {
|
||||||
match &self.program {
|
match &self.program {
|
||||||
NativeFontProgram::TrueType(program) => program.composite.as_ref(),
|
NativeFontProgram::TrueType(program) => program.composite.as_ref(),
|
||||||
|
NativeFontProgram::OpenTypeCff(program) => program.composite.as_ref(),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -660,21 +662,21 @@ fn resolve_physical_fonts(
|
|||||||
direct_resolved.insert(id, Arc::new(paint));
|
direct_resolved.insert(id, Arc::new(paint));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if let Some(file) = outline.open_type_file() {
|
||||||
|
let mut paint = cff::resolve(files, &mut outlines, outline, file, &font, slots)?;
|
||||||
|
paint.xdv_matrix = matrix;
|
||||||
|
direct_resolved.insert(id, Arc::new(paint));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if let Some(encoding) = &outline.xdv_encoding
|
if let Some(encoding) = &outline.xdv_encoding
|
||||||
&& (outline.encoding.is_none() || files.optional_font_file(
|
&& (outline.encoding.is_none() || files.optional_font_file(
|
||||||
ResourceKind::CMap, &encoding.name, &outline.from.to_string_lossy(),
|
ResourceKind::CMap, &encoding.name, &outline.from.to_string_lossy(),
|
||||||
)?.is_some())
|
)?.is_some())
|
||||||
{
|
{
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"native XDV composite encoding {} requires a TrueType program: {}", encoding.name, font.name,
|
"native XDV composite encoding {} requires a TrueType or OpenType CFF 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;
|
|
||||||
direct_resolved.insert(id, Arc::new(paint));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let file = outline.type1_file(&font.name)?;
|
let file = outline.type1_file(&font.name)?;
|
||||||
let version = outline.version.as_ref();
|
let version = outline.version.as_ref();
|
||||||
let transform = outline.transform;
|
let transform = outline.transform;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face.
|
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face.
|
||||||
use super::{
|
use super::{
|
||||||
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
||||||
|
composite::{self, Codes, CompositeFont},
|
||||||
map::{MapEntry, OutlineFiles},
|
map::{MapEntry, OutlineFiles},
|
||||||
};
|
};
|
||||||
use crate::{execution::SourceProvider, resources::ResourceKind};
|
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||||
@@ -11,12 +12,18 @@ use std::{collections::{BTreeMap, BTreeSet}, sync::Arc};
|
|||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct OpenTypeCffProgram {
|
pub struct OpenTypeCffProgram {
|
||||||
pub(crate) name: String,
|
pub(crate) name: String,
|
||||||
data: Arc<[u8]>,
|
pub(crate) data: Arc<[u8]>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) face_index: u32,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub(crate) composite: Option<CompositeFont>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub(crate) composite_glyphs: Vec<u16>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OpenTypeCffProgram {
|
impl OpenTypeCffProgram {
|
||||||
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
|
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 OpenType font {}: {error}", self.name))
|
.map_err(|error| format!("invalid OpenType font {}: {error}", self.name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,6 +64,43 @@ pub(super) fn resolve(
|
|||||||
font: &NativeFont,
|
font: &NativeFont,
|
||||||
slots: BTreeSet<u8>,
|
slots: BTreeSet<u8>,
|
||||||
) -> Result<NativeFontPaint, String> {
|
) -> Result<NativeFontPaint, String> {
|
||||||
|
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 {
|
if outline.subset {
|
||||||
return Err(format!("OTF fonts must be included entirely: {file}"));
|
return Err(format!("OTF fonts must be included entirely: {file}"));
|
||||||
}
|
}
|
||||||
@@ -67,7 +111,7 @@ pub(super) fn resolve(
|
|||||||
program_index,
|
program_index,
|
||||||
} = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
|
} = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
|
||||||
let face =
|
let face =
|
||||||
Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
|
Face::parse(&data, outline.face_index).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
|
||||||
let table = face
|
let table = face
|
||||||
.raw_face()
|
.raw_face()
|
||||||
.table(Tag::from_bytes(b"CFF "))
|
.table(Tag::from_bytes(b"CFF "))
|
||||||
@@ -116,12 +160,13 @@ pub(super) fn resolve(
|
|||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
});
|
});
|
||||||
let bbox = face.global_bounding_box();
|
let bbox = scaled_bbox(&face);
|
||||||
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 {
|
let program = OpenTypeCffProgram {
|
||||||
name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
|
name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
|
||||||
data,
|
data,
|
||||||
|
face_index: outline.face_index,
|
||||||
|
composite: None,
|
||||||
|
composite_glyphs: Vec::new(),
|
||||||
};
|
};
|
||||||
Ok(NativeFontPaint {
|
Ok(NativeFontPaint {
|
||||||
program: NativeFontProgram::OpenTypeCff(program),
|
program: NativeFontProgram::OpenTypeCff(program),
|
||||||
@@ -139,3 +184,9 @@ pub(super) fn resolve(
|
|||||||
program_index: Some(program_index),
|
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()))
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
//! Resolve actual XDV character codes independently of the TeX font metrics.
|
||||||
|
use super::{
|
||||||
|
cid_width,
|
||||||
|
map::{MapEntry, XdvEncoding},
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
execution::SourceProvider, opentype::vertical::PdfMetrics, pdf_device::cmap::CMap,
|
||||||
|
resources::ResourceVersion,
|
||||||
|
};
|
||||||
|
use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub(crate) struct CompositeFont {
|
||||||
|
pub(crate) registry: String,
|
||||||
|
pub(crate) ordering: String,
|
||||||
|
pub(crate) supplement: u32,
|
||||||
|
slots: Vec<CompositeSlot>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub(crate) vertical: Option<[i32; 2]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
|
struct CompositeSlot {
|
||||||
|
cid: u16,
|
||||||
|
advance: u32,
|
||||||
|
unicode: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
vertical: Option<[i32; 3]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CompositeFont {
|
||||||
|
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 vertical_override(&self, slot: u8) -> Option<[i32; 3]> {
|
||||||
|
self.vertical?;
|
||||||
|
self.slots[usize::from(slot)].vertical
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn vertical_slot(&self, slot: u8) -> Option<[f64; 3]> {
|
||||||
|
let [advance, y] = self.vertical?;
|
||||||
|
if let Some(metrics) = self.vertical_override(slot) {
|
||||||
|
return Some(metrics.map(f64::from));
|
||||||
|
}
|
||||||
|
Some([
|
||||||
|
f64::from(advance),
|
||||||
|
f64::from(self.advance(slot)) / 2.0,
|
||||||
|
f64::from(y),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn unicode(&self, slot: u8) -> Option<&str> {
|
||||||
|
self.slots[usize::from(slot)].unicode.as_deref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) enum Codes {
|
||||||
|
Unicode,
|
||||||
|
Identity,
|
||||||
|
Custom(Box<CMap>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Codes {
|
||||||
|
pub(super) fn load(
|
||||||
|
encoding: &XdvEncoding,
|
||||||
|
outline: &MapEntry,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<Option<Self>, String> {
|
||||||
|
let name = &encoding.name;
|
||||||
|
Ok(Some(match name.as_str() {
|
||||||
|
"unicode" => Self::Unicode,
|
||||||
|
"Identity-H" | "Identity-V" => 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"))
|
||||||
|
};
|
||||||
|
};
|
||||||
|
Self::Custom(Box::new(map))
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct Glyphs {
|
||||||
|
pub(super) mapping: CompositeFont,
|
||||||
|
pub(super) glyphs: Vec<u16>,
|
||||||
|
pub(super) names: Vec<String>,
|
||||||
|
pub(super) glyph_paths: BTreeMap<u8, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn resolve(
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
outline: &MapEntry,
|
||||||
|
data: &[u8],
|
||||||
|
face: &Face<'_>,
|
||||||
|
slots: BTreeSet<u8>,
|
||||||
|
encoding: &XdvEncoding,
|
||||||
|
codes: Codes,
|
||||||
|
resources: &mut Vec<ResourceVersion>,
|
||||||
|
) -> Result<Glyphs, String> {
|
||||||
|
let (requested_registry, requested_ordering, requested_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 = requested_registry == "Adobe" && requested_ordering == "Identity";
|
||||||
|
let collection = cid_keyed_collection(face)?;
|
||||||
|
let owns_collection = collection.is_some();
|
||||||
|
let same_collection = collection
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(registry, ordering, _, _)| {
|
||||||
|
registry == requested_registry && ordering == requested_ordering
|
||||||
|
});
|
||||||
|
if !identity && owns_collection && !same_collection {
|
||||||
|
return Err(format!(
|
||||||
|
"CMap {} uses a different collection from the CFF face",
|
||||||
|
encoding.name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let vertical = encoding.vertical
|
||||||
|
|| encoding.name == "Identity-V"
|
||||||
|
|| matches!(&codes, Codes::Custom(map) if map.is_vertical());
|
||||||
|
let metrics = vertical.then(|| PdfMetrics::new(face));
|
||||||
|
let shaper = if vertical {
|
||||||
|
Some(
|
||||||
|
rustybuzz::Face::from_slice(data, outline.face_index)
|
||||||
|
.ok_or("invalid vertical outline face")?,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let collection_to_unicode = if !identity {
|
||||||
|
let map = CMap::load(
|
||||||
|
&format!("{requested_registry}-{requested_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 vertical_alternates = Vec::new();
|
||||||
|
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 glyph_for_direct_cid = |cid: u16| {
|
||||||
|
if let Some((_, _, _, charset)) = &collection {
|
||||||
|
charset
|
||||||
|
.iter()
|
||||||
|
.find_map(|(&glyph, &code)| (code == cid).then_some(glyph))
|
||||||
|
} else {
|
||||||
|
(cid < face.number_of_glyphs()).then_some(cid)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
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()
|
||||||
|
.and_then(|cid| Some((cid, glyph_for_direct_cid(cid)?, None))),
|
||||||
|
Codes::Custom(map) => map.cid(code).and_then(|cid| {
|
||||||
|
if identity {
|
||||||
|
return Some((cid, glyph_for_direct_cid(cid)?, None));
|
||||||
|
}
|
||||||
|
let text = collection_to_unicode.as_ref()?.unicode(2, u32::from(cid));
|
||||||
|
if same_collection {
|
||||||
|
return Some((cid, glyph_for_direct_cid(cid)?, text));
|
||||||
|
}
|
||||||
|
let text = text?;
|
||||||
|
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 (mut cid, mut 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));
|
||||||
|
if vertical
|
||||||
|
&& gid != 0
|
||||||
|
&& let (Some(shaper), Some(value)) = (&shaper, &text)
|
||||||
|
&& let Some(ch) = single_scalar(value)
|
||||||
|
{
|
||||||
|
let selected = vertical_glyph(shaper, ch, gid);
|
||||||
|
if selected != gid {
|
||||||
|
vertical_alternates.push((slot, selected));
|
||||||
|
}
|
||||||
|
gid = selected;
|
||||||
|
// The built-in Unicode mapping uses the selected glyph as its
|
||||||
|
// CID; named CMaps preserve the CID and select its actual glyph.
|
||||||
|
if matches!(codes, Codes::Unicode) {
|
||||||
|
cid = gid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some((_, _, _, charset)) = &collection {
|
||||||
|
cid = charset.get(&gid).copied().unwrap_or(0);
|
||||||
|
}
|
||||||
|
let index = usize::from(slot);
|
||||||
|
glyphs[index] = gid;
|
||||||
|
cells[index] = CompositeSlot {
|
||||||
|
cid,
|
||||||
|
advance: cid_width(face, gid),
|
||||||
|
unicode: text.clone(),
|
||||||
|
vertical: metrics
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|metrics| metrics.override_for(GlyphId(gid)))
|
||||||
|
.map(|values| values.map(|value| value as i32)),
|
||||||
|
};
|
||||||
|
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])),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !vertical_alternates.is_empty() {
|
||||||
|
let text = crate::pdf::opentype_unicode::map_glyphs(
|
||||||
|
face,
|
||||||
|
vertical_alternates.iter().map(|&(_, glyph)| glyph),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
for (slot, glyph) in vertical_alternates {
|
||||||
|
if let Some(source) = text.get(&glyph) {
|
||||||
|
cells[usize::from(slot)].unicode = Some(source.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (registry, ordering, supplement) = collection.map_or_else(
|
||||||
|
|| {
|
||||||
|
(
|
||||||
|
requested_registry.to_owned(),
|
||||||
|
requested_ordering.to_owned(),
|
||||||
|
requested_supplement,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
|(registry, ordering, supplement, _)| (registry, ordering, supplement),
|
||||||
|
);
|
||||||
|
let mapping = CompositeFont {
|
||||||
|
registry,
|
||||||
|
ordering,
|
||||||
|
supplement,
|
||||||
|
slots: cells,
|
||||||
|
vertical: metrics.map(|value| [value.advance as i32, value.origin_y as i32]),
|
||||||
|
};
|
||||||
|
Ok(Glyphs {
|
||||||
|
mapping,
|
||||||
|
glyphs,
|
||||||
|
names,
|
||||||
|
glyph_paths,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn single_scalar(text: &str) -> Option<char> {
|
||||||
|
let mut chars = text.chars();
|
||||||
|
let first = chars.next()?;
|
||||||
|
chars.next().is_none().then_some(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vertical_glyph(face: &rustybuzz::Face<'_>, ch: char, default: u16) -> u16 {
|
||||||
|
let mut buffer = rustybuzz::UnicodeBuffer::new();
|
||||||
|
buffer.push_str(ch.encode_utf8(&mut [0; 4]));
|
||||||
|
buffer.set_direction(rustybuzz::Direction::TopToBottom);
|
||||||
|
buffer.guess_segment_properties();
|
||||||
|
let result = rustybuzz::shape(face, &[], buffer);
|
||||||
|
let [glyph] = result.glyph_infos() else {
|
||||||
|
return default;
|
||||||
|
};
|
||||||
|
u16::try_from(glyph.glyph_id)
|
||||||
|
.ok()
|
||||||
|
.filter(|&id| id != 0)
|
||||||
|
.unwrap_or(default)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Collection = (String, String, u32, BTreeMap<u16, u16>);
|
||||||
|
|
||||||
|
fn cid_keyed_collection(face: &Face<'_>) -> Result<Option<Collection>, String> {
|
||||||
|
use read_fonts::{
|
||||||
|
FontData, FontRead,
|
||||||
|
ps::cff::{CffFontRef, dict, v1::Cff},
|
||||||
|
};
|
||||||
|
let Some(data) = face.raw_face().table(Tag::from_bytes(b"CFF ")) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let error = || "invalid CID-keyed CFF charset".to_owned();
|
||||||
|
let cff = Cff::read(FontData::new(data)).map_err(|_| error())?;
|
||||||
|
let top = cff.top_dicts().get(0).ok_or_else(error)?;
|
||||||
|
for entry in dict::entries(top, None).flatten() {
|
||||||
|
if let dict::Entry::Ros {
|
||||||
|
registry,
|
||||||
|
ordering,
|
||||||
|
supplement,
|
||||||
|
} = entry
|
||||||
|
{
|
||||||
|
let read = |sid| {
|
||||||
|
let bytes = cff.string(sid).ok_or_else(error)?;
|
||||||
|
String::from_utf8(bytes.to_vec()).map_err(|_| error())
|
||||||
|
};
|
||||||
|
let charset = CffFontRef::new_cff(data, 0, None)
|
||||||
|
.ok()
|
||||||
|
.and_then(|font| font.charset())
|
||||||
|
.ok_or_else(error)?;
|
||||||
|
let map = charset
|
||||||
|
.iter()
|
||||||
|
.map(|(gid, cid)| {
|
||||||
|
let glyph = u16::try_from(gid.to_u32()).map_err(|_| error())?;
|
||||||
|
Ok((glyph, cid.to_u16()))
|
||||||
|
})
|
||||||
|
.collect::<Result<BTreeMap<_, _>, String>>()?;
|
||||||
|
return Ok(Some((
|
||||||
|
read(registry)?,
|
||||||
|
read(ordering)?,
|
||||||
|
supplement.to_f64().max(0.) as u32,
|
||||||
|
map,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
|
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
|
||||||
use super::{
|
use super::{
|
||||||
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
||||||
|
composite::{self, Codes, CompositeFont},
|
||||||
map::{MapEntry, OutlineFiles, XdvEncoding},
|
map::{MapEntry, OutlineFiles, XdvEncoding},
|
||||||
};
|
};
|
||||||
use crate::{execution::SourceProvider, pdf_device::cmap::CMap, resources::ResourceKind};
|
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||||
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
|
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
@@ -19,7 +20,7 @@ pub struct TrueTypeProgram {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub(crate) face_index: u32,
|
pub(crate) face_index: u32,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub(crate) composite: Option<CompositeTrueType>,
|
pub(crate) composite: Option<CompositeFont>,
|
||||||
pub(crate) reencoded: bool,
|
pub(crate) reencoded: bool,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
|
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
|
||||||
@@ -27,35 +28,6 @@ pub struct TrueTypeProgram {
|
|||||||
pub(crate) missing_subfont_cmap: Option<[u16; 2]>,
|
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 {
|
impl TrueTypeProgram {
|
||||||
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
|
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
|
||||||
Face::parse(&self.data, self.face_index)
|
Face::parse(&self.data, self.face_index)
|
||||||
@@ -143,34 +115,6 @@ pub(super) fn device_program(
|
|||||||
Ok(Some(data.into()))
|
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(
|
fn resolve_composite(
|
||||||
files: &mut impl SourceProvider,
|
files: &mut impl SourceProvider,
|
||||||
outlines: &mut OutlineFiles,
|
outlines: &mut OutlineFiles,
|
||||||
@@ -191,90 +135,12 @@ fn resolve_composite(
|
|||||||
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
|
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
|
||||||
return Err(format!("invalid TrueType outline tables in {file}"));
|
return Err(format!("invalid TrueType outline tables in {file}"));
|
||||||
}
|
}
|
||||||
let (registry, ordering, supplement) = match &codes {
|
let composite::Glyphs { mapping, glyphs, names, glyph_paths } =
|
||||||
Codes::Custom(map) => {
|
composite::resolve(files, outline, &data, &face, slots, encoding, codes, &mut resources)?;
|
||||||
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 name = font_name(&face, outline, font);
|
||||||
let bbox = font_bbox(&face);
|
let bbox = font_bbox(&face);
|
||||||
let composite = CompositeTrueType {
|
|
||||||
registry: registry.to_owned(), ordering: ordering.to_owned(), supplement, slots: cells,
|
|
||||||
};
|
|
||||||
let program = TrueTypeProgram {
|
let program = TrueTypeProgram {
|
||||||
name, data, glyphs, face_index: outline.face_index, composite: Some(composite),
|
name, data, glyphs, face_index: outline.face_index, composite: Some(mapping),
|
||||||
reencoded: false, subfont_codes: None, missing_subfont_cmap: None,
|
reencoded: false, subfont_codes: None, missing_subfont_cmap: None,
|
||||||
};
|
};
|
||||||
Ok(NativeFontPaint {
|
Ok(NativeFontPaint {
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ pub(crate) mod objects;
|
|||||||
#[path = "pdf_pk.rs"]
|
#[path = "pdf_pk.rs"]
|
||||||
mod pk_fonts;
|
mod pk_fonts;
|
||||||
mod cff_fonts;
|
mod cff_fonts;
|
||||||
|
mod cid_cff;
|
||||||
|
mod legacy_cid;
|
||||||
mod truetype_fonts;
|
mod truetype_fonts;
|
||||||
#[path = "pdf_opentype.rs"]
|
#[path = "pdf_opentype.rs"]
|
||||||
mod opentype_fonts;
|
mod opentype_fonts;
|
||||||
@@ -1921,8 +1923,8 @@ fn write_native_font(
|
|||||||
if let NativeFontProgram::Pk(pk) = &paint.program {
|
if let NativeFontProgram::Pk(pk) = &paint.program {
|
||||||
return Ok(pk_fonts::write_font(objects, face.id, pk, used, compression, target));
|
return Ok(pk_fonts::write_font(objects, face.id, pk, used, compression, target));
|
||||||
}
|
}
|
||||||
if let NativeFontProgram::TrueType(program) = &paint.program && program.composite.is_some() {
|
if paint.legacy_cid_font().is_some() {
|
||||||
return truetype_fonts::write_cid(objects, program, used.keys().copied(), compression, subset_tags, target);
|
return legacy_cid::write(objects, paint, used.keys().copied(), compression, subset_tags, target);
|
||||||
}
|
}
|
||||||
let id = target.unwrap_or_else(|| {
|
let id = target.unwrap_or_else(|| {
|
||||||
objects.push(Vec::new());
|
objects.push(Vec::new());
|
||||||
@@ -2521,10 +2523,13 @@ fn write_pdf(
|
|||||||
let mut owners = HashMap::new();
|
let mut owners = HashMap::new();
|
||||||
let mut cid_owners = HashMap::new();
|
let mut cid_owners = HashMap::new();
|
||||||
native_used.iter().filter_map(|(&id, (_, paint, _))| {
|
native_used.iter().filter_map(|(&id, (_, paint, _))| {
|
||||||
let owner = if let crate::native_font::NativeFontProgram::TrueType(program) = &paint.program
|
let owner = if let Some(composite) = paint.legacy_cid_font() {
|
||||||
&& let Some(composite) = &program.composite
|
let face_index = match &paint.program {
|
||||||
{
|
crate::native_font::NativeFontProgram::TrueType(program) => program.face_index,
|
||||||
*cid_owners.entry((paint.program_version()?, program.face_index, composite)).or_insert(id)
|
crate::native_font::NativeFontProgram::OpenTypeCff(program) => program.face_index,
|
||||||
|
_ => unreachable!("legacy CID program"),
|
||||||
|
};
|
||||||
|
*cid_owners.entry((paint.program_version()?, face_index, composite)).or_insert(id)
|
||||||
} else {
|
} else {
|
||||||
paint.xdv_descriptor?;
|
paint.xdv_descriptor?;
|
||||||
let key = (paint.type1_program_key()?, paint.encoding_version());
|
let key = (paint.type1_program_key()?, paint.encoding_version());
|
||||||
@@ -2661,10 +2666,10 @@ fn write_pdf(
|
|||||||
for (&id, (face, paint, used)) in &native_used {
|
for (&id, (face, paint, used)) in &native_used {
|
||||||
let target = registry.and_then(|objects| objects.font_number(id))
|
let target = registry.and_then(|objects| objects.font_number(id))
|
||||||
.map(|number| device_objects[&number] as usize);
|
.map(|number| device_objects[&number] as usize);
|
||||||
let encoding = if matches!(
|
let encoding = if paint.legacy_cid_font().is_none() && (matches!(
|
||||||
paint.program,
|
paint.program,
|
||||||
crate::native_font::NativeFontProgram::OpenTypeCff(_) | crate::native_font::NativeFontProgram::DeviceType1(_)
|
crate::native_font::NativeFontProgram::OpenTypeCff(_) | crate::native_font::NativeFontProgram::DeviceType1(_)
|
||||||
) || paint.xdv_descriptor.is_some() {
|
) || paint.xdv_descriptor.is_some()) {
|
||||||
mapped_encodings.mark(&mut objects, paint, used.keys().copied())
|
mapped_encodings.mark(&mut objects, paint, used.keys().copied())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
//! Embed CFF1 outlines under the CIDs selected by the XDV font map.
|
||||||
|
use read_fonts::{
|
||||||
|
FontData, FontRead,
|
||||||
|
ps::cff::{dict, index::Index1, v1::Cff},
|
||||||
|
};
|
||||||
|
use rustybuzz::ttf_parser::{Face, RawFace, Tag};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
native_font::{NativeFontPaint, OpenTypeCffProgram},
|
||||||
|
type1_outline::cff::{dict_long, dict_number, index},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn subset(
|
||||||
|
program: &OpenTypeCffProgram,
|
||||||
|
face: &Face<'_>,
|
||||||
|
paint: &NativeFontPaint,
|
||||||
|
glyphs: &BTreeMap<u16, u16>,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let mapping = paint.legacy_cid_font().expect("composite CFF mapping");
|
||||||
|
let table = face
|
||||||
|
.raw_face()
|
||||||
|
.table(Tag::from_bytes(b"CFF "))
|
||||||
|
.ok_or("missing composite CFF1 table")?;
|
||||||
|
let cff = Cff::read(FontData::new(table)).map_err(|_| "invalid composite CFF1 table")?;
|
||||||
|
let top = cff.top_dicts().get(0).ok_or("missing CFF top dictionary")?;
|
||||||
|
if dict::entries(top, None)
|
||||||
|
.flatten()
|
||||||
|
.any(|entry| matches!(entry, dict::Entry::Ros { .. }))
|
||||||
|
{
|
||||||
|
let subset = super::opentype_fonts::subset_cid_cff(
|
||||||
|
&program.data,
|
||||||
|
program.face_index,
|
||||||
|
&program.name,
|
||||||
|
glyphs.values().copied(),
|
||||||
|
)?;
|
||||||
|
let raw = RawFace::parse(&subset, 0).map_err(|_| "invalid CID CFF subset")?;
|
||||||
|
return raw
|
||||||
|
.table(Tag::from_bytes(b"CFF "))
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.ok_or_else(|| "missing CFF table in CID subset".into());
|
||||||
|
}
|
||||||
|
let mut charstrings = None;
|
||||||
|
let mut private = None;
|
||||||
|
for entry in dict::entries(top, None) {
|
||||||
|
match entry.map_err(|_| "invalid CFF dictionary")? {
|
||||||
|
dict::Entry::CharstringsOffset(offset) => charstrings = Some(offset),
|
||||||
|
dict::Entry::PrivateDictRange(range) => private = Some(range),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let invalid = || "invalid CFF index or offset".to_owned();
|
||||||
|
let at = |offset| table.get(offset..).ok_or_else(invalid);
|
||||||
|
let source_programs = Index1::read(FontData::new(at(
|
||||||
|
charstrings.ok_or("missing CFF charstrings")?
|
||||||
|
)?))
|
||||||
|
.map_err(|_| invalid())?;
|
||||||
|
let mut programs = vec![source_programs.get(0).ok_or("missing CFF .notdef")?];
|
||||||
|
let mut charset = vec![0]; // Format 0. Each entry is the actual CID, in CharStrings order.
|
||||||
|
for (&cid, &glyph) in glyphs {
|
||||||
|
if cid != 0 {
|
||||||
|
charset.extend(cid.to_be_bytes());
|
||||||
|
programs.push(
|
||||||
|
source_programs
|
||||||
|
.get(usize::from(glyph))
|
||||||
|
.ok_or_else(invalid)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let count = u16::try_from(programs.len()).map_err(|_| "too many glyphs for CFF1")?;
|
||||||
|
let programs = index(&programs)?;
|
||||||
|
let mut private_bytes = Vec::new();
|
||||||
|
let mut private_size = 0;
|
||||||
|
if let Some(range) = private {
|
||||||
|
let dictionary = table.get(range.clone()).ok_or_else(invalid)?;
|
||||||
|
private_size = dictionary.len();
|
||||||
|
private_bytes.extend(dictionary);
|
||||||
|
for entry in dict::entries(dictionary, None) {
|
||||||
|
if let dict::Entry::SubrsOffset(relative) =
|
||||||
|
entry.map_err(|_| "invalid CFF private dictionary")?
|
||||||
|
{
|
||||||
|
let offset = range.start.checked_add(relative).ok_or_else(invalid)?;
|
||||||
|
let subroutines =
|
||||||
|
Index1::read(FontData::new(at(offset)?)).map_err(|_| invalid())?;
|
||||||
|
let length = subroutines.size_in_bytes().ok_or_else(invalid)?;
|
||||||
|
let end = offset.checked_add(length).ok_or_else(invalid)?;
|
||||||
|
private_bytes.extend(table.get(range.end..end).ok_or_else(invalid)?);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Preserve real Type 2 hint programs, and the exact global and local
|
||||||
|
// subroutine indexes on which their operand biases depend.
|
||||||
|
let globals = cff.global_subrs();
|
||||||
|
let globals = index(
|
||||||
|
&(0..usize::from(globals.count()))
|
||||||
|
.map(|i| globals.get(i).ok_or_else(invalid))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?,
|
||||||
|
)?;
|
||||||
|
let name = index(&[name])?;
|
||||||
|
let strings = index(&[mapping.registry.as_bytes(), mapping.ordering.as_bytes()])?;
|
||||||
|
let fd_select = vec![0; usize::from(count) + 1];
|
||||||
|
let long = |out: &mut Vec<u8>, value: usize| -> Result<(), String> {
|
||||||
|
dict_long(
|
||||||
|
out,
|
||||||
|
i32::try_from(value).map_err(|_| "CFF offset overflow")?,
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
let font_dict = |private_offset| -> Result<Vec<u8>, String> {
|
||||||
|
let mut dict = Vec::new();
|
||||||
|
long(&mut dict, private_size)?;
|
||||||
|
long(&mut dict, private_offset)?;
|
||||||
|
dict.push(18);
|
||||||
|
index(&[dict])
|
||||||
|
};
|
||||||
|
let mut attributes = Vec::new();
|
||||||
|
// CFF1 reserves SIDs 0 through 390 for standard strings.
|
||||||
|
long(&mut attributes, 391)?;
|
||||||
|
long(&mut attributes, 392)?;
|
||||||
|
long(&mut attributes, mapping.supplement as usize)?;
|
||||||
|
attributes.extend([12, 30]); // ROS
|
||||||
|
let bbox = face.global_bounding_box();
|
||||||
|
for value in [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max] {
|
||||||
|
dict_number(&mut attributes, f64::from(value))?;
|
||||||
|
}
|
||||||
|
attributes.push(5);
|
||||||
|
let matrix = face.tables().cff.ok_or("missing CFF outlines")?.matrix();
|
||||||
|
for value in [
|
||||||
|
matrix.sx, matrix.ky, matrix.kx, matrix.sy, matrix.tx, matrix.ty,
|
||||||
|
] {
|
||||||
|
dict_number(&mut attributes, f64::from(value))?;
|
||||||
|
}
|
||||||
|
attributes.extend([12, 7]); // FontMatrix
|
||||||
|
long(
|
||||||
|
&mut attributes,
|
||||||
|
usize::from(glyphs.last_key_value().map_or(0, |(&cid, _)| cid)) + 1,
|
||||||
|
)?;
|
||||||
|
attributes.extend([12, 34]); // CIDCount
|
||||||
|
let top = |base| -> Result<Vec<u8>, String> {
|
||||||
|
let programs_offset = base + charset.len();
|
||||||
|
let select_offset = programs_offset + programs.len();
|
||||||
|
let fd_offset = select_offset + fd_select.len();
|
||||||
|
let mut top = attributes.clone();
|
||||||
|
for (offset, opcode) in [
|
||||||
|
(base, &[15][..]),
|
||||||
|
(programs_offset, &[17][..]),
|
||||||
|
(select_offset, &[12, 37][..]),
|
||||||
|
(fd_offset, &[12, 36][..]),
|
||||||
|
] {
|
||||||
|
long(&mut top, offset)?;
|
||||||
|
top.extend(opcode);
|
||||||
|
}
|
||||||
|
index(&[top])
|
||||||
|
};
|
||||||
|
let offset = 4 + name.len() + top(0)?.len() + strings.len() + globals.len();
|
||||||
|
let private_offset =
|
||||||
|
offset + charset.len() + programs.len() + fd_select.len() + font_dict(0)?.len();
|
||||||
|
let mut output = vec![1, 0, 4, 4];
|
||||||
|
for part in [
|
||||||
|
name,
|
||||||
|
top(offset)?,
|
||||||
|
strings,
|
||||||
|
globals,
|
||||||
|
charset,
|
||||||
|
programs,
|
||||||
|
fd_select,
|
||||||
|
font_dict(private_offset)?,
|
||||||
|
private_bytes,
|
||||||
|
] {
|
||||||
|
output.extend(part);
|
||||||
|
}
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
//! Write the PDF composite font for slots selected by legacy XDV output.
|
||||||
|
use super::{native_pdf_name, objects};
|
||||||
|
use crate::{
|
||||||
|
native_font::{NativeFontPaint, NativeFontProgram},
|
||||||
|
type1_outline::subset_tag,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
pub(super) fn write(
|
||||||
|
objects: &mut Vec<Vec<u8>>,
|
||||||
|
paint: &NativeFontPaint,
|
||||||
|
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 = paint.legacy_cid_font().expect("composite program");
|
||||||
|
let (name, face) = match &paint.program {
|
||||||
|
NativeFontProgram::TrueType(program) => (&program.name, program.face()?),
|
||||||
|
NativeFontProgram::OpenTypeCff(program) => (&program.name, program.face()?),
|
||||||
|
_ => unreachable!("legacy CID program"),
|
||||||
|
};
|
||||||
|
let mut vertical_widths = BTreeMap::new();
|
||||||
|
let mut glyphs = BTreeMap::new();
|
||||||
|
let mut unicode = BTreeMap::new();
|
||||||
|
for slot in slots {
|
||||||
|
let cid = mapping.cid(slot);
|
||||||
|
let glyph = match &paint.program {
|
||||||
|
NativeFontProgram::TrueType(program) => program.glyph_id(slot),
|
||||||
|
NativeFontProgram::OpenTypeCff(program) => program.composite_glyphs[usize::from(slot)],
|
||||||
|
_ => unreachable!("legacy CID program"),
|
||||||
|
};
|
||||||
|
if let Some(metrics) = mapping.vertical_override(slot) {
|
||||||
|
vertical_widths.insert(cid, metrics);
|
||||||
|
}
|
||||||
|
if glyphs.insert(cid, glyph).is_some_and(|old| old != glyph) {
|
||||||
|
return Err(format!("conflicting glyph for CID {cid} in {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(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(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 mut widths = if widths.is_empty() {
|
||||||
|
widths
|
||||||
|
} else {
|
||||||
|
format!(" /W [{widths}]]")
|
||||||
|
};
|
||||||
|
let encoding = if let Some([advance, origin]) = mapping.vertical {
|
||||||
|
write!(widths, " /DW2 [{origin} {}]", -advance).unwrap();
|
||||||
|
if !vertical_widths.is_empty() {
|
||||||
|
widths.push_str(" /W2 [");
|
||||||
|
for (cid, [advance, x, y]) in vertical_widths {
|
||||||
|
write!(widths, "{cid} {cid} {} {x} {y} ", -advance).unwrap();
|
||||||
|
}
|
||||||
|
widths.push(']');
|
||||||
|
}
|
||||||
|
"Identity-V"
|
||||||
|
} else {
|
||||||
|
"Identity-H"
|
||||||
|
};
|
||||||
|
let (subtype, file_key, file_option, subset) = match &paint.program {
|
||||||
|
NativeFontProgram::TrueType(program) => {
|
||||||
|
let subset = program.embed_cid_subset(&remapper)?;
|
||||||
|
(
|
||||||
|
"CIDFontType2",
|
||||||
|
"FontFile2",
|
||||||
|
format!("/Length1 {}", subset.len()),
|
||||||
|
subset,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
NativeFontProgram::OpenTypeCff(program) => (
|
||||||
|
"CIDFontType0",
|
||||||
|
"FontFile3",
|
||||||
|
"/Subtype /CIDFontType0C".to_owned(),
|
||||||
|
super::cid_cff::subset(program, &face, paint, &glyphs, &name)?,
|
||||||
|
),
|
||||||
|
_ => unreachable!("legacy CID program"),
|
||||||
|
};
|
||||||
|
let id = target.unwrap_or_else(|| {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
objects.len()
|
||||||
|
});
|
||||||
|
let fontfile = objects.len() + 1;
|
||||||
|
objects.push(objects::stream(&file_option, &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, file_key, 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 subtype == "CIDFontType0" {
|
||||||
|
String::new()
|
||||||
|
} else if identity {
|
||||||
|
" /CIDToGIDMap /Identity".to_owned()
|
||||||
|
} else {
|
||||||
|
objects.push(objects::stream("", &cid_to_gid, compression));
|
||||||
|
format!(" /CIDToGIDMap {} 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 /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry ({registry}) /Ordering ({ordering}) /Supplement {supplement} >> /FontDescriptor {descriptor} 0 R /DW {default}{widths}{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())
|
||||||
|
};
|
||||||
|
let type0_name = if subtype == "CIDFontType0" {
|
||||||
|
format!("{name}-{encoding}")
|
||||||
|
} else {
|
||||||
|
name
|
||||||
|
};
|
||||||
|
objects[id - 1] = format!(
|
||||||
|
"<< /Type /Font /Subtype /Type0 /BaseFont /{type0_name} /Encoding /{encoding} /DescendantFonts [{descendant} 0 R]{unicode_ref} >>"
|
||||||
|
).into_bytes();
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
@@ -62,111 +62,3 @@ pub(super) fn write(
|
|||||||
);
|
);
|
||||||
Ok((descriptor, name))
|
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)
|
|
||||||
}
|
|
||||||
@@ -256,15 +256,17 @@ impl<'a> CidCff<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn subset_cid_cff(
|
pub(super) fn subset_cid_cff(
|
||||||
font: &OpenTypeFont,
|
data: &[u8],
|
||||||
|
index: u32,
|
||||||
|
name: &str,
|
||||||
glyphs: impl Iterator<Item = u16>,
|
glyphs: impl Iterator<Item = u16>,
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, String> {
|
||||||
let invalid = |error| format!("invalid OpenType font {}: {error}", font.name);
|
let invalid = |error| format!("invalid OpenType font {name}: {error}");
|
||||||
let file = FileRef::new(&font.resource.data).map_err(invalid)?;
|
let file = FileRef::new(data).map_err(invalid)?;
|
||||||
let face = match file {
|
let face = match file {
|
||||||
FileRef::Font(face) => face,
|
FileRef::Font(face) => face,
|
||||||
FileRef::Collection(faces) => faces.get(font.face_index()).map_err(invalid)?,
|
FileRef::Collection(faces) => faces.get(index).map_err(invalid)?,
|
||||||
};
|
};
|
||||||
// Only the CFF program is embedded. No layout tables or character closure
|
// Only the CFF program is embedded. No layout tables or character closure
|
||||||
// are needed for glyphs that have already been shaped.
|
// are needed for glyphs that have already been shaped.
|
||||||
@@ -289,7 +291,7 @@ fn subset_cid_cff(
|
|||||||
&IntSet::empty(),
|
&IntSet::empty(),
|
||||||
);
|
);
|
||||||
skera::subset_font(&face, &plan)
|
skera::subset_font(&face, &plan)
|
||||||
.map_err(|error| format!("failed to embed OpenType CID font {}: {error}", font.name))
|
.map_err(|error| format!("failed to embed OpenType CID font {name}: {error}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_font(
|
fn write_font(
|
||||||
@@ -421,7 +423,7 @@ fn write_font(
|
|||||||
let name = format!("{tag}+{}", native_pdf_name(postscript_name));
|
let name = format!("{tag}+{}", native_pdf_name(postscript_name));
|
||||||
|
|
||||||
let subset = if cid_cff.is_some() {
|
let subset = if cid_cff.is_some() {
|
||||||
subset_cid_cff(font, remapper.remapped_gids())?
|
subset_cid_cff(&font.resource.data, font.face_index(), &font.name, remapper.remapped_gids())?
|
||||||
} else {
|
} else {
|
||||||
subsetter::subset(&font.resource.data, font.face_index(), &remapper)
|
subsetter::subset(&font.resource.data, font.face_index(), &remapper)
|
||||||
.map_err(|error| format!("failed to embed OpenType font {}: {error}", font.name))?
|
.map_err(|error| format!("failed to embed OpenType font {}: {error}", font.name))?
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ pub(super) struct NativeText {
|
|||||||
effective_size: i64,
|
effective_size: i64,
|
||||||
expansion: i32,
|
expansion: i32,
|
||||||
xdv: bool,
|
xdv: bool,
|
||||||
|
vertical_cid: bool,
|
||||||
xdv_matrix: XdvFontMatrix,
|
xdv_matrix: XdvFontMatrix,
|
||||||
v: i64,
|
v: i64,
|
||||||
start_h: i64,
|
start_h: i64,
|
||||||
@@ -40,10 +41,12 @@ impl NativeText {
|
|||||||
space: Option<SpaceUse>,
|
space: Option<SpaceUse>,
|
||||||
dedicated: Option<&ResolvedSpaceFont>,
|
dedicated: Option<&ResolvedSpaceFont>,
|
||||||
) -> Option<[f64; 2]> {
|
) -> Option<[f64; 2]> {
|
||||||
|
let composite = paint.legacy_cid_font();
|
||||||
|
let vertical = composite.is_some_and(|font| font.vertical.is_some());
|
||||||
let first = text.is_none();
|
let first = text.is_none();
|
||||||
let state = text.get_or_insert_with(|| {
|
let state = text.get_or_insert_with(|| {
|
||||||
out.push_str("BT\n");
|
out.push_str("BT\n");
|
||||||
if let Some(origin) = xdv_origin.filter(|_| paint.xdv_matrix.is_identity()) {
|
if let Some(origin) = xdv_origin.filter(|_| !vertical && paint.xdv_matrix.is_identity()) {
|
||||||
let [h, v] = out.origin.position();
|
let [h, v] = out.origin.position();
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
"1 0 0 1 {} {} Tm\n",
|
"1 0 0 1 {} {} Tm\n",
|
||||||
@@ -56,6 +59,7 @@ impl NativeText {
|
|||||||
effective_size: 0,
|
effective_size: 0,
|
||||||
expansion: 0,
|
expansion: 0,
|
||||||
xdv: xdv_origin.is_some(),
|
xdv: xdv_origin.is_some(),
|
||||||
|
vertical_cid: false,
|
||||||
xdv_matrix: XdvFontMatrix::default(),
|
xdv_matrix: XdvFontMatrix::default(),
|
||||||
v: xdv_origin.unwrap_or(height),
|
v: xdv_origin.unwrap_or(height),
|
||||||
start_h: xdv_origin.unwrap_or(0),
|
start_h: xdv_origin.unwrap_or(0),
|
||||||
@@ -86,8 +90,10 @@ impl NativeText {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let matrix_changed = state.xdv && state.xdv_matrix != paint.xdv_matrix;
|
let matrix_changed = state.xdv
|
||||||
|
&& (state.xdv_matrix != paint.xdv_matrix || state.vertical_cid != vertical);
|
||||||
state.xdv_matrix = paint.xdv_matrix;
|
state.xdv_matrix = paint.xdv_matrix;
|
||||||
|
state.vertical_cid = vertical;
|
||||||
let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size);
|
let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size);
|
||||||
let (v, v_out) = state.vertical_move(y, digits);
|
let (v, v_out) = state.vertical_move(y, digits);
|
||||||
let reset_line = if state.xdv {
|
let reset_line = if state.xdv {
|
||||||
@@ -102,14 +108,17 @@ impl NativeText {
|
|||||||
if first || reset_line || space == Some(SpaceUse::Dedicated)
|
if first || reset_line || space == Some(SpaceUse::Dedicated)
|
||||||
{
|
{
|
||||||
state.close_string(out);
|
state.close_string(out);
|
||||||
if state.xdv && (matrix_changed || !state.xdv_matrix.is_identity()) {
|
if state.xdv && (matrix_changed || vertical || !state.xdv_matrix.is_identity()) {
|
||||||
let [extend, slant] = state.xdv_matrix.coefficients();
|
let [extend, slant] = state.xdv_matrix.coefficients();
|
||||||
let [h, v] = out.origin.position();
|
let [h, v] = out.origin.position();
|
||||||
if !out.measuring {
|
if !out.measuring {
|
||||||
|
let matrix = if vertical {
|
||||||
|
format!("{slant:.5} 1 {:.5} 0", -extend)
|
||||||
|
} else {
|
||||||
|
format!("{extend:.5} 0 {slant:.5} 1")
|
||||||
|
};
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
"{extend:.5} 0 {slant:.5} 1 {} {} Tm\n",
|
"{matrix} {} {} Tm\n", print_sp(x - h, digits), print_sp(height - y - v, digits),
|
||||||
print_sp(x - h, digits),
|
|
||||||
print_sp(height - y - v, digits),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
state.start_h = x;
|
state.start_h = x;
|
||||||
@@ -149,7 +158,8 @@ impl NativeText {
|
|||||||
state.opened = true;
|
state.opened = true;
|
||||||
}
|
}
|
||||||
let cid_advance = out.track_legacy_cids.then(|| {
|
let cid_advance = out.track_legacy_cids.then(|| {
|
||||||
paint.legacy_cid_font().map(|program| f64::from(program.advance(slot)))
|
composite.map(|program| program.vertical_slot(slot)
|
||||||
|
.map_or_else(|| f64::from(program.advance(slot)), |metrics| metrics[0]))
|
||||||
}).flatten();
|
}).flatten();
|
||||||
let viewer_em = || {
|
let viewer_em = || {
|
||||||
// Tf uses 4 decimal places in bp. Convert the selected em back
|
// Tf uses 4 decimal places in bp. Convert the selected em back
|
||||||
@@ -165,12 +175,13 @@ impl NativeText {
|
|||||||
state.cursor_correction += shift as f64 * viewer_em() / 1000.0 - shift_out as f64;
|
state.cursor_correction += shift as f64 * viewer_em() / 1000.0 - shift_out as f64;
|
||||||
}
|
}
|
||||||
if !out.measuring {
|
if !out.measuring {
|
||||||
out.push_str(&format!(" {} ", -shift));
|
let adjustment = if vertical { shift } else { -shift };
|
||||||
|
out.push_str(&format!(" {adjustment} "));
|
||||||
}
|
}
|
||||||
state.delta_h += shift_out;
|
state.delta_h += shift_out;
|
||||||
}
|
}
|
||||||
if !out.measuring {
|
if !out.measuring {
|
||||||
if let Some(composite) = paint.legacy_cid_font() {
|
if let Some(composite) = composite {
|
||||||
out.push_str(&format!("<{:04X}>", composite.cid(slot)));
|
out.push_str(&format!("<{:04X}>", composite.cid(slot)));
|
||||||
} else {
|
} else {
|
||||||
out.push_str(&format!("<{slot:02X}>"));
|
out.push_str(&format!("<{slot:02X}>"));
|
||||||
|
|||||||
@@ -170,6 +170,7 @@ struct NativeSvgGlyph<'a> {
|
|||||||
glyph: &'a str,
|
glyph: &'a str,
|
||||||
unicode: Option<&'a str>,
|
unicode: Option<&'a str>,
|
||||||
device_width: Option<u32>,
|
device_width: Option<u32>,
|
||||||
|
vertical_origin: Option<[i32; 2]>,
|
||||||
path: &'a str,
|
path: &'a str,
|
||||||
scalable: bool,
|
scalable: bool,
|
||||||
}
|
}
|
||||||
@@ -203,6 +204,8 @@ impl DisplayItem {
|
|||||||
),
|
),
|
||||||
_ => format!("native SVG outline is not resolved for {} slot {slot}", font.name),
|
_ => format!("native SVG outline is not resolved for {} slot {slot}", font.name),
|
||||||
})?;
|
})?;
|
||||||
|
let composite = paint.legacy_cid_font();
|
||||||
|
let vertical = composite.and_then(|font| font.vertical_slot(*slot));
|
||||||
Ok(NativeSvgGlyph {
|
Ok(NativeSvgGlyph {
|
||||||
position: [*x, *y],
|
position: [*x, *y],
|
||||||
size: *size,
|
size: *size,
|
||||||
@@ -212,7 +215,8 @@ impl DisplayItem {
|
|||||||
font: paint.program.name(),
|
font: paint.program.name(),
|
||||||
glyph: &paint.encoding[usize::from(*slot)],
|
glyph: &paint.encoding[usize::from(*slot)],
|
||||||
unicode: paint.mapped_text(*slot),
|
unicode: paint.mapped_text(*slot),
|
||||||
device_width: paint.legacy_cid_font().map(|font| font.advance(*slot)),
|
device_width: composite.map(|font| vertical.map_or_else(|| font.advance(*slot), |v| v[0] as u32)),
|
||||||
|
vertical_origin: vertical.map(|[_, x, y]| [(x * 2.0) as i32, y as i32]),
|
||||||
path,
|
path,
|
||||||
scalable: !matches!(
|
scalable: !matches!(
|
||||||
paint.program,
|
paint.program,
|
||||||
@@ -562,6 +566,7 @@ impl DisplayList {
|
|||||||
glyph,
|
glyph,
|
||||||
unicode,
|
unicode,
|
||||||
device_width,
|
device_width,
|
||||||
|
vertical_origin,
|
||||||
path,
|
path,
|
||||||
scalable,
|
scalable,
|
||||||
} = item
|
} = item
|
||||||
@@ -595,7 +600,17 @@ impl DisplayList {
|
|||||||
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"",
|
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"",
|
||||||
escape(font), escape(glyph), escape(&label), path,
|
escape(font), escape(glyph), escape(&label), path,
|
||||||
).unwrap();
|
).unwrap();
|
||||||
if xdv_matrix.is_identity() {
|
if let Some([vx2, vy]) = vertical_origin {
|
||||||
|
let vx = f64::from(vx2) / 2.0;
|
||||||
|
let vy = f64::from(vy);
|
||||||
|
let [extend, slant] = xdv_matrix.coefficients();
|
||||||
|
let a = slant * horizontal_scale;
|
||||||
|
let b = -horizontal_scale;
|
||||||
|
let c = -extend * scale;
|
||||||
|
let e = x - a * vx - c * vy;
|
||||||
|
let f = y - b * vx;
|
||||||
|
write!(out, "matrix({a:.8} {b:.8} {c:.8} 0 {e:.5} {f:.5})").unwrap();
|
||||||
|
} else if xdv_matrix.is_identity() {
|
||||||
write!(out, "translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})").unwrap();
|
write!(out, "translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})").unwrap();
|
||||||
} else {
|
} else {
|
||||||
let [extend, slant] = xdv_matrix.coefficients();
|
let [extend, slant] = xdv_matrix.coefficients();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::type1::{Type1Font, font_matrix, standard_encoding};
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
mod subset;
|
mod subset;
|
||||||
mod cff;
|
pub(crate) mod cff;
|
||||||
pub(crate) use cff::write_type1c;
|
pub(crate) use cff::write_type1c;
|
||||||
pub(crate) use subset::{subset_tag, write_subset};
|
pub(crate) use subset::{subset_tag, write_subset};
|
||||||
use subset::{GlyphUse, ProgramRanges, SubrRange};
|
use subset::{GlyphUse, ProgramRanges, SubrRange};
|
||||||
|
|||||||
@@ -187,12 +187,12 @@ fn charstring(glyph: Type1Glyph) -> Result<(Vec<u8>, Option<[f64; 4]>), String>
|
|||||||
Ok((output, trace.seac))
|
Ok((output, trace.seac))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dict_long(output: &mut Vec<u8>, value: i32) {
|
pub(crate) fn dict_long(output: &mut Vec<u8>, value: i32) {
|
||||||
output.push(29);
|
output.push(29);
|
||||||
output.extend(value.to_be_bytes());
|
output.extend(value.to_be_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dict_number(output: &mut Vec<u8>, value: f64) -> Result<(), String> {
|
pub(crate) fn dict_number(output: &mut Vec<u8>, value: f64) -> Result<(), String> {
|
||||||
if !value.is_finite() {
|
if !value.is_finite() {
|
||||||
return Err("nonfinite CFF dictionary operand".into());
|
return Err("nonfinite CFF dictionary operand".into());
|
||||||
}
|
}
|
||||||
@@ -288,7 +288,7 @@ fn private_dict(private: &[u8]) -> Result<Vec<u8>, String> {
|
|||||||
Ok(entries.into_values().flatten().collect())
|
Ok(entries.into_values().flatten().collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn index(items: &[impl AsRef<[u8]>]) -> Result<Vec<u8>, String> {
|
pub(crate) fn index(items: &[impl AsRef<[u8]>]) -> Result<Vec<u8>, String> {
|
||||||
let count = u16::try_from(items.len()).map_err(|_| "CFF INDEX capacity exceeded")?;
|
let count = u16::try_from(items.len()).map_err(|_| "CFF INDEX capacity exceeded")?;
|
||||||
let mut output = count.to_be_bytes().to_vec();
|
let mut output = count.to_be_bytes().to_vec();
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
|
|||||||
@@ -18,6 +18,33 @@
|
|||||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||||
|
|
||||||
|
## 2026-11-28 XeLaTeX 旧 TFM 的竖排与复合 CFF
|
||||||
|
|
||||||
|
旧 TFM 设备字体支持 TrueType 和 OpenType CFF 的横排及竖排复合映射。
|
||||||
|
竖排采用实际字体的替代字形、竖向度量及对应 Unicode。PDF 与 SVG 共用按物理
|
||||||
|
字宽推进的文字游标,来源定位继续使用 TFM。嵌入的 CFF 保留原始字形程序和
|
||||||
|
hint。名称索引的 CFF 暂时保留原全局和本地子程序索引,CID 索引的 CFF
|
||||||
|
使用已有子集路径。Harano Aji 的横竖实例分别生成字体子集。
|
||||||
|
[参考竖排文字矩阵](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfdev.c)
|
||||||
|
[参考复合 CFF](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/cidtype0.c)
|
||||||
|
|
||||||
|
五个直接对照及使用原样 article.cls、hyperref.sty 的两页样例共七页。
|
||||||
|
和原版 XeTeX/xdvipdfmx 的 144 DPI 彩色页面逐像素一致,文字提取逐字节一致,
|
||||||
|
两页样例的 aux 也一致。十四项 XDV 定向检查通过。另保留命名 CMap 与
|
||||||
|
Adobe 字符集用例的文字提取及首页像素对照。SVG 连续两次竖排设备推进均为
|
||||||
|
10.03996 pt。
|
||||||
|
|
||||||
|
三页会话切换字体书写模式、替换 CFF 文件及恢复缺失字体后,各成功修订
|
||||||
|
只更新第 2 页,分别复用 65、1,606、65 个执行步。PDF、测量页、SVG、来源
|
||||||
|
映射和 aux 与独立全量编译一致。移除 CFF 的失败修订保留上次发布结果。
|
||||||
|
正式出版矩阵及编辑到可见页面 100 ms p95 门槛仍待同版验收。
|
||||||
|
|
||||||
|
本地回执在 target/p3-xdv-composite-vertical-cff/ 的 verification.txt
|
||||||
|
与 SHA256SUMS。下一入口为旧 Type1 PFB 的复合设备路径。已用实际 CMR10
|
||||||
|
和 Adobe Glyph List 生成原版参考,复用了上一批字体路径,缺口确认为
|
||||||
|
PFB 的复合字形选择和嵌入。
|
||||||
|
[Adobe Glyph List](https://github.com/adobe-type-tools/agl-aglfn/blob/master/glyphlist.txt)
|
||||||
|
|
||||||
## 2026-11-28 XeLaTeX 旧 TFM 与横排复合 TrueType
|
## 2026-11-28 XeLaTeX 旧 TFM 与横排复合 TrueType
|
||||||
|
|
||||||
旧 TFM 按出页字体映射将原始字码解析到复合 TrueType。
|
旧 TFM 按出页字体映射将原始字码解析到复合 TrueType。
|
||||||
|
|||||||
Reference in new issue
Block a user