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

195 lines
7.0 KiB
Rust

//! pdfTeX-profile glyph-name mappings. Values retain PDF hex strings, including
//! explicitly supplied UTF-16 code units; they are not Rust Unicode labels.
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
enum Mapping {
Undefined,
Hex(String),
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct GlyphUnicodeMap {
entries: BTreeMap<String, Mapping>,
}
fn upper_hex(s: &str) -> bool {
s.bytes()
.all(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(&b))
}
fn scalar_hex(value: u32) -> String {
if value <= 0xffff {
format!("{value:04X}")
} else {
let n = value - 0x10000;
format!("{:04X}{:04X}", 0xd800 + (n >> 10), 0xdc00 + (n & 1023))
}
}
impl GlyphUnicodeMap {
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub(crate) fn contains(&self, glyph: &str) -> bool {
self.entries.contains_key(glyph.split('\0').next().unwrap())
}
/// Invalid syntax leaves an existing entry intact. An out-of-range numeric
/// value installs an undefined entry, which also suppresses name fallback.
pub(crate) fn define(&mut self, glyph: String, value: &str) -> Option<String> {
// The byte profile's C-string arguments end at the first zero byte.
let glyph = glyph.split('\0').next().unwrap().to_owned();
let value = value.split('\0').next().unwrap().trim_matches(' ');
if glyph.is_empty()
|| glyph == ".notdef"
|| value.is_empty()
|| !value.split(' ').all(upper_hex)
{
return Some(format!(
"ToUnicode: invalid parameter(s): `{glyph}' => `{value}'"
));
}
let mut warning = None;
let mapping = if value.contains(' ') {
Mapping::Hex(value.replace(' ', ""))
} else {
// Leading zeroes do not make an otherwise small scalar overflow.
match u32::from_str_radix(value.trim_start_matches('0'), 16).or_else(|e| {
if value.bytes().all(|b| b == b'0') {
Ok(0)
} else {
Err(e)
}
}) {
Ok(n) if n <= 0x10ffff => Mapping::Hex(scalar_hex(n)),
_ => {
warning = Some(format!("ToUnicode: value out of range [0,10FFFF]: {value}"));
Mapping::Undefined
}
}
};
self.entries.insert(glyph, mapping);
warning
}
/// Resolve against the actual TFM namespace and encoding glyph name. An
/// absent table disables generation even for names of the form uniXXXX.
pub fn lookup(&self, tfm: &str, glyph: &str) -> Option<String> {
if self.is_empty() {
return None;
}
let glyph = glyph.split('.').next().unwrap();
if glyph.is_empty() {
return None;
}
if glyph.contains('_') {
return Some(
glyph
.split('_')
.filter_map(|s| self.lookup(tfm, s))
.collect(),
);
}
if let Some(mapping) = self
.entries
.get(&format!("tfm:{tfm}/{glyph}"))
.or_else(|| self.entries.get(glyph))
{
return match mapping {
Mapping::Undefined => None,
Mapping::Hex(s) => Some(s.clone()),
};
}
if let Some(hex) = glyph.strip_prefix("uni") {
if hex.is_empty() || hex.len() % 4 != 0 || !upper_hex(hex) {
return None;
}
return hex
.as_bytes()
.chunks(4)
.all(|chunk| {
let n = u16::from_str_radix(std::str::from_utf8(chunk).unwrap(), 16).unwrap();
!(0xd800..=0xdfff).contains(&n)
})
.then(|| hex.to_owned());
}
let hex = glyph.strip_prefix('u')?;
if !(4..=6).contains(&hex.len()) || !upper_hex(hex) {
return None;
}
let n = u32::from_str_radix(hex, 16).ok()?;
(n <= 0x10ffff && !(0xd800..=0xdfff).contains(&n)).then(|| scalar_hex(n))
}
}
pub use crate::pdf::opentype_unicode::XdvGlyphNames;
/// Parameters and job data consumed by the PDF writer after all shipouts.
#[derive(Clone, Copy)]
pub struct PdfFinalOptions<'a> {
pub compression: i32,
pub generate_unicode: i32,
pub(crate) omit_charset: bool,
pub(crate) omit_info: bool,
pub(crate) ptex_banner_separator: Option<char>,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub fonts: &'a crate::execution::FontCatalog,
pub page_tree_attributes: &'a [u8],
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
pub info: crate::pdf_device::PdfInfo<'a>,
pub xdv_glyph_names: Option<&'a XdvGlyphNames>,
/// Reuse physical font output after current-job resources were resolved.
pub font_cache: Option<&'a crate::native_font::NativeFontCache>,
pub(crate) xdv_font_unicode: bool,
pub(crate) xdv_keep_destinations: bool,
pub(crate) xdv_outline_open_depth: usize,
pub(crate) xdv_navigation: Option<&'a crate::pdf_device::xdv_navigation::Navigation>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_resolution_preserves_namespace_components_and_raw_code_units() {
let mut map = GlyphUnicodeMap::default();
assert_eq!(map.lookup("f", "uni0041"), None);
for (name, value) in [
("A", "0041"),
("tfm:f/A", "1F600"),
("B", "0066 0069"),
("A_B", "0043"),
("u0043", "110000"),
("odd", "0 41"),
("surrogate", "D800"),
] {
map.define(name.into(), value);
}
for (font, name, expected) in [
("g", "A.alt", Some("0041")),
("f", "A.alt", Some("D83DDE00")),
("g", "A_B", Some("004100660069")),
("g", "unknown_A_unknown", Some("0041")),
("g", "unknown_unknown", Some("")),
("g", "uni00410042", Some("00410042")),
("g", "u1F600", Some("D83DDE00")),
("g", "u0043", None),
("g", "u1f600", None),
("g", "uniD800", None),
("g", "uni0041D800", None),
("g", "u110000", None),
("g", "uFFF", None),
("g", ".notdef", None),
("g", "odd", Some("041")),
("g", "surrogate", Some("D800")),
] {
assert_eq!(map.lookup(font, name).as_deref(), expected, "{font}/{name}");
}
assert!(map.define("A".into(), "03b1").is_some());
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
assert!(map.define("tfm:f/A".into(), "110000").is_some());
assert_eq!(map.lookup("f", "A"), None);
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
}
}