Apply XeLaTeX CMaps to document text and embedded fonts

This commit is contained in:
gloamxun committed 2026-11-28 21:40:17 +08:00
1 parent af6466cd98
commit 7d460e0fa1
20 files changed
+747 -65

No files matched your search

@@ -0,0 +1,306 @@
//! Character-code maps read from actual CMap resources.
use std::{collections::BTreeMap, sync::Arc};
use super::xdv_object::{split_string, trim_pdf};
use crate::{
execution::SourceProvider,
resources::{ResourceKind, ResourceVersion},
};
const MAX_CMAP_DEPTH: usize = 16;
const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug)]
pub(crate) struct CMap {
codespaces: [Vec<[u32; 2]>; 4],
mappings: [BTreeMap<u32, Mapping>; 4],
inherited: Option<Arc<CMap>>,
pub(crate) resources: Vec<ResourceVersion>,
}
#[derive(Debug)]
struct Mapping {
last: u32,
destination: Destination,
}
#[derive(Debug)]
enum Destination {
Sequential(Vec<u8>),
Explicit(Vec<Vec<u8>>),
}
impl CMap {
pub(crate) fn load(
name: &str,
from: &str,
files: &mut impl SourceProvider,
) -> Result<Self, String> {
Self::load_inner(name, from, files, &mut Vec::new())
}
fn load_inner(
name: &str,
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"))?;
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}"));
}
if resource.data.len() > MAX_CMAP_BYTES {
return Err(format!("CMap {name} exceeds the input limit"));
}
stack.push(resource.version.clone());
let (mut map, base) =
Self::parse(&resource.data).map_err(|error| format!("{name}: {error}"))?;
map.resources.push(resource.version.clone());
if let Some(base) = base {
let inherited = Self::load_inner(
&base,
&resource.version.path.to_string_lossy(),
files,
stack,
)?;
map.resources.extend(inherited.resources.iter().cloned());
map.inherited = Some(Arc::new(inherited));
}
stack.pop();
if map.codespaces.iter().all(Vec::is_empty) && map.inherited.is_none() {
return Err(format!("CMap {name} has no code space"));
}
Ok(map)
}
fn parse(data: &[u8]) -> Result<(Self, Option<String>), String> {
let mut lexer = Lexer(data);
let mut map = Self {
codespaces: Default::default(),
mappings: Default::default(),
inherited: None,
resources: Vec::new(),
};
let mut previous = &[][..];
let mut inherits = None;
let mut ended = false;
while let Some(token) = lexer.next()? {
let end = match token {
b"begincodespacerange" => b"endcodespacerange".as_slice(),
b"beginbfchar" => b"endbfchar",
b"beginbfrange" => b"endbfrange",
b"usecmap" => {
let name = previous
.strip_prefix(b"/")
.filter(|name| !name.is_empty())
.ok_or("missing CMap base name")?;
if inherits.is_some() {
return Err("more than one CMap base".into());
}
inherits = Some(
std::str::from_utf8(name)
.map_err(|_| "invalid CMap base name")?
.into(),
);
previous = token;
continue;
}
b"endcmap" => {
ended = true;
break;
}
_ => {
previous = token;
continue;
}
};
let count = std::str::from_utf8(previous)
.ok()
.and_then(|n| n.parse::<usize>().ok())
.filter(|&n| n <= data.len())
.ok_or("invalid CMap block count")?;
for _ in 0..count {
let (width, first) = read_code(lexer.required()?)?;
let last = if token == b"beginbfchar" {
first
} else {
let (end_width, last) = read_code(lexer.required()?)?;
if width != end_width || last < first {
return Err("invalid CMap source range".into());
}
last
};
if token == b"begincodespacerange" {
map.codespaces[width - 1].push([first, last]);
continue;
}
let value = lexer.required()?;
let destination = if value == b"[" && token == b"beginbfrange" {
let len = u64::from(last) - u64::from(first) + 1;
if len > data.len() as u64 {
return Err("invalid CMap array range".into());
}
let values = (0..len)
.map(|_| read_hex(lexer.required()?))
.collect::<Result<_, _>>()?;
if lexer.required()? != b"]" {
return Err("invalid CMap range array".into());
}
Destination::Explicit(values)
} else {
Destination::Sequential(read_hex(value)?)
};
map.mappings[width - 1].insert(first, Mapping { last, destination });
}
if lexer.required()? != end {
return Err("incorrect CMap block length".into());
}
previous = &[];
}
if !ended {
return Err("missing CMap end marker".into());
}
Ok((map, inherits))
}
fn lookup(&self, width: usize, code: u32) -> Option<Vec<u8>> {
if let Some((&first, mapping)) = self.mappings[width - 1].range(..=code).next_back()
&& code <= mapping.last
{
let offset = code - first;
return match &mapping.destination {
Destination::Explicit(values) => values.get(offset as usize).cloned(),
Destination::Sequential(value) => {
let mut carry = u64::from(offset);
let mut bytes = value.clone();
for byte in bytes.iter_mut().rev() {
if carry == 0 {
break;
}
carry += u64::from(*byte);
*byte = carry as u8;
carry >>= 8;
}
(carry == 0).then_some(bytes)
}
};
}
self.inherited.as_ref()?.lookup(width, code)
}
fn in_codespace(&self, width: usize, code: u32) -> bool {
self.codespaces[width - 1]
.iter()
.any(|&[lo, hi]| (lo..=hi).contains(&code))
|| self
.inherited
.as_ref()
.is_some_and(|base| base.in_codespace(width, code))
}
pub(crate) fn to_utf16(&self, mut input: &[u8]) -> Result<Vec<u8>, String> {
let mut output = Vec::with_capacity(2 + input.len());
output.extend_from_slice(&[0xfe, 0xff]);
while !input.is_empty() {
let mut code = 0;
let mut consumed = 1;
let mut decoded = None;
for (index, &byte) in input.iter().take(4).enumerate() {
code = (code << 8) | u32::from(byte);
let width = index + 1;
if self.in_codespace(width, code) {
consumed = width;
decoded = self.lookup(width, code);
break;
}
}
let bytes = decoded.as_deref().unwrap_or(&[0xff, 0xfd]);
if output.len().saturating_add(bytes.len()) > MAX_CMAP_BYTES {
return Err("CMap output exceeds the text limit".into());
}
output.extend_from_slice(bytes);
input = &input[consumed..];
}
Ok(output)
}
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()?))
})
.collect()
}
}
fn read_hex(token: &[u8]) -> Result<Vec<u8>, String> {
let digits = token
.strip_prefix(b"<")
.and_then(|s| s.strip_suffix(b">"))
.ok_or("expected a CMap hexadecimal string")?;
let nibbles = digits
.iter()
.filter(|b| !b.is_ascii_whitespace())
.map(|&b| {
char::from(b)
.to_digit(16)
.map(|n| n as u8)
.ok_or("invalid CMap hexadecimal digit")
})
.collect::<Result<Vec<_>, _>>()?;
Ok(nibbles
.chunks(2)
.map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0))
.collect())
}
fn read_code(token: &[u8]) -> Result<(usize, u32), String> {
let code = read_hex(token)?;
if !(1..=4).contains(&code.len()) {
return Err("invalid CMap code length".into());
}
Ok((
code.len(),
code.iter().fold(0, |n, &b| (n << 8) | u32::from(b)),
))
}
struct Lexer<'a>(&'a [u8]);
impl<'a> Lexer<'a> {
fn required(&mut self) -> Result<&'a [u8], String> {
self.next()?.ok_or_else(|| "unexpected end of CMap".into())
}
fn next(&mut self) -> Result<Option<&'a [u8]>, String> {
let input = trim_pdf(self.0);
let token = match input {
[] => return Ok(None),
[b'<', b'<', ..] | [b'>', b'>', ..] => &input[..2],
[b'<' | b'(', ..] => split_string(input)?.0,
[b'[' | b']' | b'{' | b'}' | b')' | b'>', ..] => &input[..1],
_ => {
let end = input
.iter()
.enumerate()
.skip(1)
.find(|(_, b)| b.is_ascii_whitespace() || b"[]{}()<>/%".contains(b))
.map_or(input.len(), |(i, _)| i);
&input[..end]
}
};
self.0 = &input[token.len()..];
Ok(Some(token))
}
}