Files
texrra-engine/crates/texrra-tex-core/src/pdf_device/cmap.rs
T

436 lines
15 KiB
Rust

//! 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],
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>,
}
#[derive(Debug)]
struct Mapping {
last: u32,
destination: Destination,
}
#[derive(Debug)]
struct CidRange {
last: u32,
cid: u16,
}
#[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_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())
}
fn load_inner(
name: &str,
from: &str,
files: &mut impl SourceProvider,
stack: &mut Vec<ResourceVersion>,
) -> 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}"));
}
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,
)?
.ok_or_else(|| format!("CMap {base} was not found"))?;
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(Some(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(),
cid_mappings: Default::default(),
notdef: Default::default(),
registry: None,
ordering: None,
supplement: None,
vertical: None,
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"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"/")
.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 matches!(token, b"beginbfchar" | b"begincidchar" | b"beginnotdefchar")
{
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()?;
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 {
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 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| 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"<")
.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))
}
}