511 lines
17 KiB
Rust
511 lines
17 KiB
Rust
//! Execute compiled TECkit font maps before OpenType shaping.
|
|
use crate::{
|
|
execution::FontResource,
|
|
provenance::{Derivation, PaintSource},
|
|
resources::ResourceVersion,
|
|
};
|
|
use std::{
|
|
hash::{Hash, Hasher},
|
|
io::Read,
|
|
ops::Range,
|
|
sync::OnceLock,
|
|
};
|
|
|
|
mod rule;
|
|
|
|
const INVALID: &str = "invalid compiled TECkit font mapping";
|
|
const MAX_MAPPING_BYTES: usize = 32 << 20;
|
|
const MAX_WORD_VALUES: usize = u16::MAX as usize;
|
|
|
|
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
|
pub(crate) struct FontMapping {
|
|
resource: FontResource,
|
|
#[serde(skip)]
|
|
program: OnceLock<Result<Program, String>>,
|
|
}
|
|
|
|
impl PartialEq for FontMapping {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.resource.version == other.resource.version
|
|
}
|
|
}
|
|
impl Eq for FontMapping {}
|
|
impl Hash for FontMapping {
|
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
self.resource.version.hash(state);
|
|
}
|
|
}
|
|
impl FontMapping {
|
|
pub(crate) fn new(resource: FontResource) -> Result<Self, String> {
|
|
let mapping = Self {
|
|
resource,
|
|
program: OnceLock::new(),
|
|
};
|
|
mapping.program()?;
|
|
Ok(mapping)
|
|
}
|
|
|
|
pub(crate) fn version(&self) -> &ResourceVersion {
|
|
&self.resource.version
|
|
}
|
|
|
|
fn program(&self) -> Result<&Program, String> {
|
|
self.program
|
|
.get_or_init(|| Program::parse(&self.resource.data))
|
|
.as_ref()
|
|
.map_err(|error| format!("{}: {error}", self.resource.version.path.display()))
|
|
}
|
|
|
|
pub(crate) fn apply(
|
|
&self,
|
|
text: &str,
|
|
sources: &[(usize, PaintSource)],
|
|
) -> Result<(String, Vec<(usize, PaintSource)>), String> {
|
|
let mut input = Vec::with_capacity(sources.len());
|
|
let mut source = sources.iter().peekable();
|
|
for (offset, character) in text.char_indices() {
|
|
let mut origin = PaintSource::default();
|
|
while source.peek().is_some_and(|(at, _)| *at == offset) {
|
|
origin.merge(&source.next().unwrap().1);
|
|
}
|
|
input.push(Entry {
|
|
value: u32::from(character),
|
|
source: origin,
|
|
});
|
|
}
|
|
let program = self.program()?;
|
|
for stage in &program.stages {
|
|
input = match stage {
|
|
Stage::Map(range) => {
|
|
Table::parse(Reader(&program.bytes[range.clone()]))?.convert(&input)?
|
|
}
|
|
Stage::Nfc => normalize(input, true)?,
|
|
Stage::Nfd => normalize(input, false)?,
|
|
};
|
|
}
|
|
let mut result = String::new();
|
|
let mut sources = Vec::with_capacity(input.len());
|
|
let mut units = 0;
|
|
for entry in input {
|
|
let character = char::from_u32(entry.value).ok_or(INVALID)?;
|
|
units += character.len_utf16();
|
|
if units > MAX_WORD_VALUES {
|
|
return Err("mapped OpenType word capacity exceeded".into());
|
|
}
|
|
sources.push((result.len(), entry.source));
|
|
result.push(character);
|
|
}
|
|
Ok((result, sources))
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct Entry {
|
|
value: u32,
|
|
source: PaintSource,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
enum Stage {
|
|
Map(Range<usize>),
|
|
Nfc,
|
|
Nfd,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct Program {
|
|
bytes: Vec<u8>,
|
|
stages: Vec<Stage>,
|
|
}
|
|
|
|
impl Program {
|
|
fn parse(data: &[u8]) -> Result<Self, String> {
|
|
let bytes = if data.starts_with(b"zQmp") {
|
|
let length = Reader(data).long(4)? as usize;
|
|
if length > MAX_MAPPING_BYTES {
|
|
return Err("TECkit mapping capacity exceeded".into());
|
|
}
|
|
let mut bytes = Vec::with_capacity(length);
|
|
flate2::read::ZlibDecoder::new(data.get(8..).ok_or(INVALID)?)
|
|
.take(length as u64 + 1)
|
|
.read_to_end(&mut bytes)
|
|
.map_err(|_| INVALID)?;
|
|
if bytes.len() != length {
|
|
return Err(INVALID.into());
|
|
}
|
|
bytes
|
|
} else {
|
|
if data.len() > MAX_MAPPING_BYTES {
|
|
return Err("TECkit mapping capacity exceeded".into());
|
|
}
|
|
data.to_vec()
|
|
};
|
|
|
|
let file = Reader(&bytes);
|
|
if !bytes.starts_with(b"qMap") || file.long(4)? >> 16 > 3 {
|
|
return Err(INVALID.into());
|
|
}
|
|
let header = file.offset(8)?;
|
|
let source_flags = file.long(12)?;
|
|
let target_flags = file.long(16)?;
|
|
if source_flags & target_flags & 0x10000 == 0 {
|
|
return Err("OpenType TECkit mappings require Unicode input and output".into());
|
|
}
|
|
let names = file.long(20)? as usize;
|
|
let forward = file.long(24)? as usize;
|
|
let reverse = file.long(28)? as usize;
|
|
if header < 32 || names.saturating_add(forward).saturating_add(reverse) > (header - 32) / 4
|
|
{
|
|
return Err(INVALID.into());
|
|
}
|
|
let mut stages = Vec::new();
|
|
if source_flags & 2 != 0 {
|
|
stages.push(Stage::Nfd);
|
|
} else if source_flags & 1 != 0 {
|
|
stages.push(Stage::Nfc);
|
|
}
|
|
let mut unicode = true;
|
|
for index in names..names + forward {
|
|
let start = file.offset(32 + 4 * index)?;
|
|
let table = Reader(bytes.get(start..).ok_or(INVALID)?);
|
|
let length = table.offset(8)?;
|
|
if start < header || length < 12 {
|
|
return Err(INVALID.into());
|
|
}
|
|
let stage = match table.data(0, 4)? {
|
|
b"NFC " if unicode => Stage::Nfc,
|
|
b"NFD " if unicode => Stage::Nfd,
|
|
_ => {
|
|
let table = Table::parse(Reader(table.data(0, length)?))?;
|
|
if table.input_unicode != unicode {
|
|
return Err(INVALID.into());
|
|
}
|
|
unicode = table.output_unicode;
|
|
Stage::Map(start..start + length)
|
|
}
|
|
};
|
|
stages.push(stage);
|
|
}
|
|
if !unicode {
|
|
return Err(INVALID.into());
|
|
}
|
|
Ok(Self { bytes, stages })
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
struct Reader<'a>(&'a [u8]);
|
|
|
|
impl<'a> Reader<'a> {
|
|
fn data(self, address: usize, length: usize) -> Result<&'a [u8], &'static str> {
|
|
self.0
|
|
.get(address..)
|
|
.and_then(|bytes| bytes.get(..length))
|
|
.ok_or(INVALID)
|
|
}
|
|
fn byte(self, address: usize) -> Result<u8, &'static str> {
|
|
self.0.get(address).copied().ok_or(INVALID)
|
|
}
|
|
fn short(self, address: usize) -> Result<u16, &'static str> {
|
|
Ok(u16::from_be_bytes(
|
|
self.data(address, 2)?.try_into().unwrap(),
|
|
))
|
|
}
|
|
fn long(self, address: usize) -> Result<u32, &'static str> {
|
|
Ok(u32::from_be_bytes(
|
|
self.data(address, 4)?.try_into().unwrap(),
|
|
))
|
|
}
|
|
fn offset(self, address: usize) -> Result<usize, &'static str> {
|
|
let offset = self.long(address)? as usize;
|
|
self.0.get(offset..).map(|_| offset).ok_or(INVALID)
|
|
}
|
|
}
|
|
|
|
struct Table<'a> {
|
|
data: Reader<'a>,
|
|
input_unicode: bool,
|
|
output_unicode: bool,
|
|
supplementary: bool,
|
|
pages: usize,
|
|
lookup: usize,
|
|
match_classes: usize,
|
|
replacement_classes: usize,
|
|
lists: usize,
|
|
rules: usize,
|
|
max_match: usize,
|
|
default_replacement: u32,
|
|
}
|
|
impl<'a> Table<'a> {
|
|
fn parse(data: Reader<'a>) -> Result<Self, &'static str> {
|
|
let (input_unicode, output_unicode) = match data.data(0, 4)? {
|
|
b"U->U" => (true, true),
|
|
b"U->B" => (true, false),
|
|
b"B->U" => (false, true),
|
|
b"B->B" => (false, false),
|
|
_ => return Err(INVALID),
|
|
};
|
|
Ok(Self {
|
|
data,
|
|
input_unicode,
|
|
output_unicode,
|
|
supplementary: data.long(12)? & 1 != 0,
|
|
pages: data.offset(16)?,
|
|
lookup: data.offset(20)?,
|
|
match_classes: data.offset(24)?,
|
|
replacement_classes: data.offset(28)?,
|
|
lists: data.offset(32)?,
|
|
rules: data.offset(36)?,
|
|
max_match: usize::from(data.byte(40)?),
|
|
default_replacement: data.long(44)?,
|
|
})
|
|
}
|
|
|
|
fn lookup(&self, input: &[Entry]) -> Result<(usize, usize), &'static str> {
|
|
let value = input[0].value;
|
|
if !self.input_unicode {
|
|
if value > 255 {
|
|
return Err(INVALID);
|
|
}
|
|
if self.pages != 0
|
|
&& let Some(next) = input.get(1)
|
|
{
|
|
let page = usize::from(self.data.byte(self.pages + value as usize)?);
|
|
if page != 0 {
|
|
if next.value > 255 {
|
|
return Err(INVALID);
|
|
}
|
|
let pair = self.lookup + 4 * (256 * page + next.value as usize);
|
|
if self.data.byte(pair)? != 0xfe {
|
|
return Ok((pair, 2));
|
|
}
|
|
}
|
|
}
|
|
return Ok((self.lookup + 4 * value as usize, 1));
|
|
}
|
|
|
|
let plane = (value >> 16) as usize;
|
|
let (pages, count, map) = if self.supplementary {
|
|
if plane >= 17 {
|
|
return Err(INVALID);
|
|
}
|
|
(
|
|
self.pages + 20,
|
|
usize::from(self.data.byte(self.pages + 17)?),
|
|
usize::from(self.data.byte(self.pages + plane)?),
|
|
)
|
|
} else {
|
|
(self.pages, 1, if plane == 0 { 0 } else { 255 })
|
|
};
|
|
if pages == self.lookup || map == 255 {
|
|
return Ok((self.lookup, 1));
|
|
}
|
|
if map >= count {
|
|
return Err(INVALID);
|
|
}
|
|
let page = usize::from(
|
|
self.data
|
|
.byte(pages + map * 256 + ((value as usize >> 8) & 255))?,
|
|
);
|
|
let index = if page == 255 {
|
|
0
|
|
} else {
|
|
let address = pages + count * 256 + 2 * (page * 256 + (value as usize & 255));
|
|
if address + 2 > self.lookup {
|
|
return Err(INVALID);
|
|
}
|
|
usize::from(self.data.short(address)?)
|
|
};
|
|
Ok((self.lookup + 4 * index, 1))
|
|
}
|
|
|
|
fn class(
|
|
&self,
|
|
base: usize,
|
|
class: usize,
|
|
unicode: bool,
|
|
) -> Result<(Reader<'a>, usize), &'static str> {
|
|
let data = Reader(self.data.0.get(base..).ok_or(INVALID)?);
|
|
let offset = data.offset(4 * class)?;
|
|
let count = data.long(offset)? as usize;
|
|
let size = if unicode {
|
|
if self.supplementary { 4 } else { 2 }
|
|
} else {
|
|
1
|
|
};
|
|
let length = count.checked_mul(size).ok_or(INVALID)?;
|
|
Ok((Reader(data.data(offset + 4, length)?), size))
|
|
}
|
|
|
|
fn match_class(&self, class: usize, value: u32) -> Result<Option<usize>, &'static str> {
|
|
let (members, size) = self.class(self.match_classes, class, self.input_unicode)?;
|
|
let mut left = 0;
|
|
let mut right = members.0.len() / size;
|
|
while left < right {
|
|
let middle = (left + right) / 2;
|
|
let code = class_member(members, size, middle)?;
|
|
match code.cmp(&value) {
|
|
std::cmp::Ordering::Less => left = middle + 1,
|
|
std::cmp::Ordering::Greater => right = middle,
|
|
std::cmp::Ordering::Equal => return Ok(Some(middle)),
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn replace_class(&self, class: usize, index: usize) -> Result<u32, &'static str> {
|
|
let (members, size) = self.class(self.replacement_classes, class, self.output_unicode)?;
|
|
class_member(members, size, index)
|
|
}
|
|
|
|
fn unmatched(&self, input: u32) -> u32 {
|
|
if self.input_unicode == self.output_unicode {
|
|
input
|
|
} else {
|
|
self.default_replacement
|
|
}
|
|
}
|
|
|
|
fn convert(&self, input: &[Entry]) -> Result<Vec<Entry>, &'static str> {
|
|
let mut output = Vec::with_capacity(input.len());
|
|
let mut budget = input.len().saturating_mul(4096).saturating_add(16384);
|
|
let mut start = 0;
|
|
while start < input.len() {
|
|
let (address, mut consumed) = self.lookup(&input[start..])?;
|
|
let entry = self.data.data(address, 4)?;
|
|
match entry[0] {
|
|
tag @ (0xff | 0x80..=0xbf) => {
|
|
let high = if tag == 0xff {
|
|
0
|
|
} else {
|
|
usize::from(tag & 0x3f)
|
|
};
|
|
let count = high * 256 + usize::from(entry[1]);
|
|
let index = usize::from(u16::from_be_bytes([entry[2], entry[3]]));
|
|
let mut matched = false;
|
|
let mut allow_insertion = true;
|
|
for i in index..index + count {
|
|
let offset = self.data.offset(self.lists + 4 * i)?;
|
|
let rule = rule::Rule::parse(Reader(
|
|
self.data.0.get(self.rules + offset..).ok_or(INVALID)?,
|
|
))?;
|
|
if let Some(hit) = rule.find(self, input, start, &mut budget)? {
|
|
if hit.end - start > self.max_match {
|
|
return Err(INVALID);
|
|
}
|
|
if hit.end == start && !allow_insertion {
|
|
continue;
|
|
}
|
|
rule.emit(self, input, start, &hit, &mut output)?;
|
|
if hit.end != start {
|
|
consumed = hit.end - start;
|
|
matched = true;
|
|
break;
|
|
}
|
|
allow_insertion = false;
|
|
}
|
|
}
|
|
if !matched {
|
|
consumed = 1;
|
|
push(
|
|
&mut output,
|
|
self.unmatched(input[start].value),
|
|
&input[start].source,
|
|
)?;
|
|
}
|
|
}
|
|
0xfd => {
|
|
let value = self.unmatched(input[start].value);
|
|
let source = direct_source(&input[start..start + consumed], value);
|
|
push(&mut output, value, &source)?;
|
|
}
|
|
_ if self.output_unicode => {
|
|
let value = u32::from_be_bytes(entry.try_into().unwrap());
|
|
// The direct Unicode deletion entry has no scalar value.
|
|
if value <= 0x10ffff {
|
|
let source = direct_source(&input[start..start + consumed], value);
|
|
push(&mut output, value, &source)?;
|
|
}
|
|
}
|
|
count @ 0..=3 => {
|
|
let bytes = &entry[1..1 + usize::from(count)];
|
|
let source = if let [value] = bytes {
|
|
direct_source(&input[start..start + consumed], u32::from(*value))
|
|
} else {
|
|
source_of(input, start..start + consumed).derived(Derivation::FontMapping)
|
|
};
|
|
for &value in bytes {
|
|
push(&mut output, u32::from(value), &source)?;
|
|
}
|
|
}
|
|
_ => return Err(INVALID),
|
|
}
|
|
start += consumed;
|
|
}
|
|
Ok(output)
|
|
}
|
|
}
|
|
|
|
fn class_member(data: Reader<'_>, size: usize, index: usize) -> Result<u32, &'static str> {
|
|
match size {
|
|
1 => data.byte(index).map(u32::from),
|
|
2 => data.short(2 * index).map(u32::from),
|
|
_ => data.long(4 * index),
|
|
}
|
|
}
|
|
|
|
fn source_of(input: &[Entry], range: Range<usize>) -> PaintSource {
|
|
let mut source = PaintSource::default();
|
|
for component in &input[range] {
|
|
source.merge(&component.source);
|
|
}
|
|
source
|
|
}
|
|
|
|
fn direct_source(input: &[Entry], value: u32) -> PaintSource {
|
|
if let [entry] = input
|
|
&& entry.value == value
|
|
{
|
|
return entry.source.clone();
|
|
}
|
|
source_of(input, 0..input.len()).derived(Derivation::FontMapping)
|
|
}
|
|
|
|
fn push(output: &mut Vec<Entry>, value: u32, source: &PaintSource) -> Result<(), &'static str> {
|
|
if output.len() == MAX_WORD_VALUES {
|
|
return Err("mapped OpenType word capacity exceeded");
|
|
}
|
|
output.push(Entry {
|
|
value,
|
|
source: source.clone(),
|
|
});
|
|
Ok(())
|
|
}
|
|
|
|
fn normalize(input: Vec<Entry>, composed: bool) -> Result<Vec<Entry>, &'static str> {
|
|
use unicode_normalization::char::decompose_canonical;
|
|
|
|
let mut decomposed = Vec::with_capacity(input.len());
|
|
for entry in input {
|
|
let character = char::from_u32(entry.value).ok_or(INVALID)?;
|
|
decompose_canonical(character, |c| {
|
|
let source = direct_source(std::slice::from_ref(&entry), c.into());
|
|
decomposed.push((c, source));
|
|
});
|
|
if decomposed.len() > MAX_WORD_VALUES {
|
|
return Err("mapped OpenType word capacity exceeded");
|
|
}
|
|
}
|
|
let normalized = crate::normalization::order_and_compose(decomposed, composed, |starter, mark| {
|
|
starter.merge(&mark);
|
|
*starter = std::mem::take(starter).derived(Derivation::FontMapping);
|
|
});
|
|
Ok(normalized
|
|
.into_iter()
|
|
.map(|(character, source)| Entry {
|
|
value: character.into(),
|
|
source,
|
|
})
|
|
.collect())
|
|
}
|