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

+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"<")