diff --git a/Cargo.lock b/Cargo.lock index c17dc18..a60b0a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1490,6 +1490,7 @@ dependencies = [ "sha2", "subsetter", "unicode-bidi", + "unicode-normalization", ] [[package]] @@ -1553,6 +1554,12 @@ dependencies = [ "log", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "ttf-parser" version = "0.25.1" @@ -1592,6 +1599,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.5" diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index cebf817..cc245ad 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -18,6 +18,7 @@ serde = { version = "1.0", features = ["derive", "rc"] } serde_json = "1.0" sha2 = "=0.10.9" hyphenate = { path = "../../vendor/hyphenate" } +unicode-normalization = "=0.1.25" [target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies] libc = "0.2" diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index 77a3354..49622ca 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -369,8 +369,28 @@ impl FontCatalog { return Err("font resource version does not match its actual OpenType bytes".into()); } let resource = FontResource { version: loaded.version, data: Arc::new(loaded.data) }; + let mapping = if let Some(name) = &request.mapping { + let loaded = files.resource(super::super::resources::ResourceKind::FontMapping, name, from)?; + if loaded.version.bytes != loaded.data.len() as u64 + || loaded.version.sha256 != format!("{:x}", Sha256::digest(&loaded.data)) + { + return Err("font resource version does not match its actual TECkit bytes".into()); + } + let existing = self.fonts.iter() + .filter_map(|instance| instance.opentype()?.mapping()) + .find(|mapping| mapping.version() == &loaded.version); + Some(match existing { + Some(mapping) => mapping.clone(), + None => Arc::new(crate::font_mapping::FontMapping::new(FontResource { + version: loaded.version, + data: Arc::new(loaded.data), + })?), + }) + } else { + None + }; let id = FontId(self.fonts.len() as u32); - let (font, parameters) = OpenTypeFont::new(id, resource, request, size)?; + let (font, parameters) = OpenTypeFont::new(id, resource, request, mapping, size)?; let resource = self.intern_resource(font.resource.clone()); self.fonts.push(FontInstance { name: spec.to_owned(), diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 008879a..489e30f 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 60; -const COMPATIBLE_SCHEMAS: [u32; 29] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, SCHEMA, +const SCHEMA: u32 = 61; +const COMPATIBLE_SCHEMAS: [u32; 30] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/font_mapping.rs b/crates/texrra-tex-core/src/font_mapping.rs new file mode 100644 index 0000000..80f1b09 --- /dev/null +++ b/crates/texrra-tex-core/src/font_mapping.rs @@ -0,0 +1,532 @@ +//! 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>, +} + +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(&self, state: &mut H) { + self.resource.version.hash(state); + } +} +impl FontMapping { + pub(crate) fn new(resource: FontResource) -> Result { + 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), + Nfc, + Nfd, +} + +#[derive(Debug)] +struct Program { + bytes: Vec, + stages: Vec, +} + +impl Program { + fn parse(data: &[u8]) -> Result { + 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 { + self.0.get(address).copied().ok_or(INVALID) + } + fn short(self, address: usize) -> Result { + Ok(u16::from_be_bytes( + self.data(address, 2)?.try_into().unwrap(), + )) + } + fn long(self, address: usize) -> Result { + Ok(u32::from_be_bytes( + self.data(address, 4)?.try_into().unwrap(), + )) + } + fn offset(self, address: usize) -> Result { + 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 { + 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, &'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 { + 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, &'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 { + 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) -> 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, 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, composed: bool) -> Result, &'static str> { + use unicode_normalization::char::{ + canonical_combining_class as ccc, compose, 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 mut marks = 0; + for i in 0..decomposed.len() { + if ccc(decomposed[i].0) == 0 { + decomposed[marks..i].sort_by_key(|(c, _)| ccc(*c)); + marks = i + 1; + } + } + decomposed[marks..].sort_by_key(|(c, _)| ccc(*c)); + let mut output: Vec = Vec::with_capacity(decomposed.len()); + let mut starter: Option = None; + let mut last_class = 0; + for (character, source) in decomposed { + let class = ccc(character); + if composed + && (last_class == 0 || last_class < class) + && let Some(index) = starter + && let Some(joined) = compose(char::from_u32(output[index].value).unwrap(), character) + { + output[index].value = joined.into(); + output[index].source.merge(&source); + output[index].source = + std::mem::take(&mut output[index].source).derived(Derivation::FontMapping); + continue; + } + if class == 0 { + starter = Some(output.len()); + } + last_class = class; + push(&mut output, character.into(), &source)?; + } + Ok(output) +} diff --git a/crates/texrra-tex-core/src/font_mapping/rule.rs b/crates/texrra-tex-core/src/font_mapping/rule.rs new file mode 100644 index 0000000..37893bb --- /dev/null +++ b/crates/texrra-tex-core/src/font_mapping/rule.rs @@ -0,0 +1,310 @@ +use super::{Derivation, Entry, INVALID, Reader, Table, push, source_of}; +use std::ops::Range; + +const SCALAR_MASK: u32 = 0x001f_ffff; +const CLASS: u8 = 1; +const GROUP: u8 = 2; +const END_GROUP: u8 = 3; +const ALTERNATIVE: u8 = 4; +const ANY: u8 = 5; +const END_OF_TEXT: u8 = 6; +const COPY: u8 = 7; +const UNMAPPED: u8 = 15; + +pub(super) struct Rule<'a> { + forward: Reader<'a>, + previous: Reader<'a>, + replacement: Reader<'a>, + matched_elements: usize, +} + +impl<'a> Rule<'a> { + pub(super) fn parse(data: Reader<'a>) -> Result { + let matched_elements = usize::from(data.byte(0)?); + let forward = 4 * (matched_elements + usize::from(data.byte(1)?)); + let previous = 4 * usize::from(data.byte(2)?); + let replacement = 4 * usize::from(data.byte(3)?); + Ok(Self { + forward: Reader(data.data(4, forward)?), + previous: Reader(data.data(4 + forward, previous)?), + replacement: Reader(data.data(4 + forward + previous, replacement)?), + matched_elements, + }) + } + + pub(super) fn find( + &self, + table: &Table<'_>, + input: &[Entry], + start: usize, + budget: &mut usize, + ) -> Result, &'static str> { + let Some(hit) = (Pattern { + table, + elements: self.forward, + input, + step: 1, + capture_count: self.matched_elements, + }) + .find(start as isize, budget)? + else { + return Ok(None); + }; + if hit.end < start || hit.end > input.len() { + return Err(INVALID); + } + if !self.previous.0.is_empty() + && (Pattern { + table, + elements: self.previous, + input, + step: -1, + capture_count: 0, + }) + .find(start as isize - 1, budget)? + .is_none() + { + return Ok(None); + } + Ok(Some(hit)) + } + + pub(super) fn emit( + &self, + table: &Table<'_>, + input: &[Entry], + start: usize, + hit: &Hit, + output: &mut Vec, + ) -> Result<(), &'static str> { + let claimed = if start == hit.end { + start..start + 1 + } else { + start..hit.end + }; + let rule_source = source_of(input, claimed).derived(Derivation::FontMapping); + for element in self.replacement.0.chunks_exact(4) { + let capture = || hit.captures.get(usize::from(element[1])).ok_or(INVALID); + match element[0] { + 0 => push( + output, + u32::from_be_bytes(element.try_into().unwrap()), + &rule_source, + )?, + CLASS => { + let capture = capture()?; + if !capture.span.is_empty() { + let index = capture.class_index.ok_or(INVALID)?; + let class = usize::from(u16::from_be_bytes([element[2], element[3]])); + let value = table.replace_class(class, index)?; + let source = + source_of(input, capture.span.clone()).derived(Derivation::FontMapping); + push(output, value, &source)?; + } + } + COPY => { + for entry in input.get(capture()?.span.clone()).ok_or(INVALID)? { + push(output, entry.value, &entry.source)?; + } + } + UNMAPPED => push( + output, + table.unmatched(input[start].value), + &input[start].source, + )?, + _ => return Err(INVALID), + } + } + Ok(()) + } +} + +struct Pattern<'a> { + table: &'a Table<'a>, + elements: Reader<'a>, + input: &'a [Entry], + step: isize, + capture_count: usize, +} + +#[derive(Clone, Default)] +struct Capture { + span: Range, + class_index: Option, +} +pub(super) struct Hit { + pub(super) end: usize, + captures: Vec, +} + +#[derive(Clone)] +struct Cursor { + index: usize, + position: isize, + repeat: u8, + end: usize, + captures: Vec, + groups: Vec<(usize, u8)>, +} + +impl Pattern<'_> { + fn find(&self, position: isize, budget: &mut usize) -> Result, &'static str> { + let count = self.elements.0.len() / 4; + let mut pending = vec![Cursor { + index: 0, + position, + repeat: 0, + end: position.max(0) as usize, + captures: vec![Capture::default(); self.capture_count], + groups: Vec::new(), + }]; + while let Some(mut cursor) = pending.pop() { + loop { + *budget = budget + .checked_sub(1) + .ok_or("TECkit rule matching step limit exceeded")?; + let index = cursor.index; + if cursor.repeat == 0 { + if index == self.capture_count { + cursor.end = cursor.position.max(0) as usize; + } + if let Some(capture) = cursor.captures.get_mut(index) { + let start = cursor.position.max(0) as usize; + capture.span = start..start; + capture.class_index = None; + } + } + if index == count { + return Ok(Some(Hit { + end: cursor.end, + captures: cursor.captures, + })); + } + let [repeat, tag, a, b] = self.elements.data(index * 4, 4)?.try_into().unwrap(); + let minimum = repeat >> 4; + let maximum = repeat & 0x0f; + if minimum > maximum { + return Err(INVALID); + } + let kind = if tag & 0x40 == 0 { 0 } else { tag & 0x3f }; + match kind { + GROUP => { + let after = index + usize::from(b); + if after > count || after <= index + 1 { + return Err(INVALID); + } + if cursor.repeat >= minimum { + let mut continuation = cursor.clone(); + continuation.index = after; + continuation.repeat = 0; + finish_capture(&mut continuation, index); + pending.push(continuation); + } + if cursor.repeat >= maximum { + break; + } + let mut alternatives = vec![index + 1]; + let mut delimiter = index; + loop { + let distance = usize::from(self.elements.byte(delimiter * 4 + 2)?); + delimiter += distance; + if distance == 0 || delimiter >= after { + return Err(INVALID); + } + let tag = self.elements.byte(delimiter * 4 + 1)? & 0x7f; + if tag == 0x40 | END_GROUP { + break; + } + if tag != 0x40 | ALTERNATIVE { + return Err(INVALID); + } + alternatives.push(delimiter + 1); + } + cursor.groups.push((index, cursor.repeat + 1)); + cursor.repeat = 0; + for &alternative in alternatives[1..].iter().rev() { + let mut next = cursor.clone(); + next.index = alternative; + pending.push(next); + } + cursor.index = alternatives[0]; + } + END_GROUP | ALTERNATIVE => { + let (group, repeat) = cursor.groups.pop().ok_or(INVALID)?; + if index.checked_sub(usize::from(b)) != Some(group) { + return Err(INVALID); + } + cursor.index = group; + cursor.repeat = repeat; + } + 0 | CLASS | ANY | END_OF_TEXT => { + if cursor.repeat < maximum { + let value = usize::try_from(cursor.position) + .ok() + .and_then(|at| self.input.get(at)) + .map(|entry| entry.value); + let class_index = if kind == CLASS { + value + .map(|value| { + self.table.match_class( + usize::from(u16::from_be_bytes([a, b])), + value, + ) + }) + .transpose()? + .flatten() + } else { + None + }; + let matches = match kind { + 0 => { + value + == Some( + u32::from_be_bytes([repeat, tag, a, b]) & SCALAR_MASK, + ) + } + CLASS => class_index.is_some(), + ANY => value.is_some(), + END_OF_TEXT => value.is_none(), + _ => unreachable!(), + }; + if matches != (tag & 0x80 != 0) { + if cursor.repeat >= minimum { + let mut continuation = cursor.clone(); + advance(&mut continuation); + pending.push(continuation); + } + if cursor.repeat == 0 + && let Some(capture) = cursor.captures.get_mut(index) + { + capture.class_index = class_index; + } + cursor.position += self.step; + cursor.repeat += 1; + continue; + } + } + if cursor.repeat < minimum { + break; + } + advance(&mut cursor); + } + _ => return Err(INVALID), + } + } + } + Ok(None) + } +} + +fn finish_capture(cursor: &mut Cursor, index: usize) { + if let Some(capture) = cursor.captures.get_mut(index) { + capture.span.end = cursor.position.max(0) as usize; + } +} + +fn advance(cursor: &mut Cursor) { + finish_capture(cursor, cursor.index); + cursor.index += 1; + cursor.repeat = 0; +} diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 29e1a01..81fd7b3 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -4,6 +4,7 @@ pub mod execution; pub mod math; pub mod math_engine_tex; pub mod math_font; +mod font_mapping; pub mod opentype; pub mod native_font; pub mod output; diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 01e8f78..8c192dc 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -1,6 +1,7 @@ //! Sized OpenType faces and shaped runs for native XeTeX text. use crate::{ execution::{FontId, FontResource}, + font_mapping::FontMapping, provenance::PaintSource, resources::ResourceKind, tfm::FontSize, @@ -23,6 +24,8 @@ pub(crate) struct Request { features: Vec, script: Option, language: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mapping: Option, } impl Request { @@ -63,6 +66,7 @@ impl Request { features: Vec::new(), script: None, language: None, + mapping: None, }; for feature in features .split([';', ',']) @@ -76,6 +80,12 @@ impl Request { request.script = Some(script.to_owned()); } else if let Some(language) = feature.strip_prefix("language=") { request.language = Some(language.to_owned()); + } else if let Some(mapping) = feature.strip_prefix("mapping=") { + let name = mapping.trim(); + if name.is_empty() { + return Err("empty TECkit font mapping name".into()); + } + request.mapping = Some(format!("{name}.tec")); } else { feature .parse::() @@ -118,23 +128,26 @@ pub struct OpenTypeFont { pub ascent: i64, pub descent: i64, request: Request, + #[serde(default, skip_serializing_if = "Option::is_none")] + mapping: Option>, } impl PartialEq for OpenTypeFont { fn eq(&self, other: &Self) -> bool { - (self.id, &self.resource.version, &self.request, self.size) - == ( - other.id, - &other.resource.version, - &other.request, - other.size, - ) + self.id == other.id + && self.resource.version == other.resource.version + && self.request == other.request + && self.size == other.size + && self.mapping == other.mapping } } impl Eq for OpenTypeFont {} impl Hash for OpenTypeFont { fn hash(&self, state: &mut H) { (self.id, &self.resource.version, &self.request, self.size).hash(state); + if let Some(mapping) = &self.mapping { + mapping.hash(state); + } } } @@ -143,6 +156,7 @@ impl OpenTypeFont { id: FontId, resource: FontResource, request: Request, + mapping: Option>, size: FontSize, ) -> Result<(Self, [i32; 8]), String> { let face = ttf_parser::Face::parse(&resource.data, request.index).map_err(|error| { @@ -206,6 +220,7 @@ impl OpenTypeFont { ascent, descent, request, + mapping, }, params, )) @@ -228,6 +243,10 @@ impl OpenTypeFont { }) } + pub(crate) fn mapping(&self) -> Option<&Arc> { + self.mapping.as_ref() + } + pub(crate) fn face_index(&self) -> u32 { self.request.index } @@ -263,6 +282,11 @@ impl OpenTypeFont { text: String, sources: Vec<(usize, PaintSource)>, ) -> Result { + let (text, sources) = if let Some(mapping) = &self.mapping { + mapping.apply(&text, &sources)? + } else { + (text, sources) + }; let face = Face::from_slice(&self.resource.data, self.request.index) .ok_or("invalid OpenType shaping face")?; let features: Vec<_> = self diff --git a/crates/texrra-tex-core/src/provenance.rs b/crates/texrra-tex-core/src/provenance.rs index 595fa08..c892032 100644 --- a/crates/texrra-tex-core/src/provenance.rs +++ b/crates/texrra-tex-core/src/provenance.rs @@ -11,6 +11,7 @@ pub enum Derivation { Accent, MathVariant, MathRule, + FontMapping, } #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct PaintSource { diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index 10440de..c8276f8 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -30,6 +30,7 @@ pub enum ResourceKind { Map, Format, Config, + FontMapping, } impl ResourceKind { fn directory(self) -> &'static str { @@ -44,6 +45,7 @@ impl ResourceKind { Self::Encoding => "fonts/enc", Self::Map => "fonts/map", Self::Format | Self::Config => "web2c", + Self::FontMapping => "fonts/misc", } } fn environment(self) -> &'static str { @@ -59,6 +61,7 @@ impl ResourceKind { Self::Map => "TEXFONTMAPS", Self::Format => "TEXFORMATS", Self::Config => "TEXMFCNF", + Self::FontMapping => "MISCFONTS", } } fn extensions(self) -> &'static [&'static str] { @@ -74,9 +77,10 @@ impl ResourceKind { Self::Map => &["map"], Self::Format => &["fmt"], Self::Config => &["cnf"], + Self::FontMapping => &["tec"], } } - const ALL: [Self; 11] = [ + const ALL: [Self; 12] = [ Self::Tex, Self::Tfm, Self::Vf, @@ -88,6 +92,7 @@ impl ResourceKind { Self::Map, Self::Format, Self::Config, + Self::FontMapping, ]; } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3458910..8d92f63 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,40 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### TECkit 字体映射与原样 XeLaTeX article + +原样 xelatex.ini 在明确的 XeTeX 模式下执行到 \dump。优化版读取实际 +Unicode 数据与断字配置,写出 schema60 格式。作业状态为 0,格式与 +输入清单位于 target/p3-xetex-profile/xelatex-native-final。源相同的官方 +XeTeX 0.999998 对照格式位于同目录的 xelatex-reference。早期调试作业 +由完成的优化版替代,保留其原日志与停止记录。 + +OpenType 字体定义从实际项目或发行版的 fonts/misc 读取编译后的 .tec, +亦可用 MISCFONTS 指定目录。映射纳入资源版本和恢复流程。映射程序在 shaping 前按表执行字串、类别、上下文、 +重复、分组、增删及连续转换阶段,规范化采用 Unicode 17.0 数据。替换字形 +保留匹配输入的 token 来源。两组独立对照分别使用发行版 tex-text.tec 与由 +TECkit 编译的自定义映射,源字节和字体一致,600 dpi 灰度图逐像素一致。 +自定义对照含类别替换、重复和备选项、前后文、删除及串联阶段。 + +9 项定向回归通过。三页会话中损坏 .tec 时保留前一版 PDF,恢复为新的 +映射后复用 948 步,只替换第二页。PDF、页面和来源映射与独立全量一致。 +新 schema61 重载会在文档阶段执行格式中保存的字体定义。直接把 OpenType +字体装入 INITEX 后调用 \dump 会触发参考和原生的字体限制,两侧现场保留 +在 format-openfont-reference 和 format61。 + + +原样 article 经原版 size10.clo、TU 字体定义与 l3backend-xetex.def 输出一页 +PDF。与参考的 49 个字形编号及横向位置完全一致,Unicode 大小写诊断 +和实际 aux 字节一致。当前纵向坐标仍有 412404 和 702833 sp 的差异。 +LaTeX 默认在第 22125 行同时启用 \XeTeXuseglyphmetrics 和 +\XeTeXdashbreakstate。参考探测在 glyph metrics 开关两侧测得实际盒高 +和深度改变,内嵌映射破折号处的断行也由一行变两行。两项仍需接入真实 +字形外框与段落断行。原始输入、前期失败和参考产物均保留于 +target/p3-xetex-teckit。 + +[TECkit 编译表格式](https://github.com/silnrsi/teckit/blob/v2.5.13/source/TECkit_Format.h) +[字体映射的 XeTeX 执行路径](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L22482-L22520) + ### XeTeX 兼容入口与原样格式 CLI 经 `--input-profile xetex --etex`、库经 `InputProfile::XeTeX` @@ -2193,11 +2227,9 @@ schema60 保存模式和宽表。新格式重载能实际出页并执行 PDF lit 报告格式身份不匹配。14 项定向回归通过,详见 target/p3-xetex-profile/targeted-profile-final.log。 -发行版原样 xelatex.ini 的参考作业已生成格式。原生原样作业仍在运行, -现场位于 target/p3-xetex-profile/xelatex-native 与 xelatex-native-final。 -独立 TU 字体探测用发行版原样 tex-text.tec 确认真实映射行为。原生 -在解析字体映射选项时报错,保留 tex-text-reference 和 tex-text-native -的对照产物。接续实际字体映射及待核对的类包和输出路径。 +该阶段启动发行版原样 xelatex.ini 的参考和原生作业。最终格式和 +原样 article 的结果见上方 TECkit 阶段,早期字体映射报错保留在 +target/p3-xetex-profile/tex-text-native。 [XeTeX 版本与命令类型](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L28436-L28446) [XeTeX 字体映射资源](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c#L564-L604) diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index df80ba8..516b636 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -568,6 +568,145 @@ fn unicode_math_code_edit_updates_the_page_that_reads_the_table() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn font_mapping_changes_recover_and_update_the_page_that_used_the_resource() { + use std::io::Write; + use texrra_tex_core::{execution::InputProfile, provenance::Derivation}; + + fn mapping(replacement: u32) -> Arc<[u8]> { + // A TECkit forward table with one Unicode plane, one page, and one + // two-character rule keyed by the ASCII hyphen. + const PAGES: u32 = 48; + const LOOKUP: u32 = PAGES + 256 + 512; + const LIST: u32 = LOOKUP + 8; + const RULE: u32 = LIST + 4; + const END: u32 = RULE + 16; + let mut bytes = b"qMap".to_vec(); + for word in [0x0002_0001u32, 36, 0x10000, 0x10000, 0, 1, 0, 36] { + bytes.extend(word.to_be_bytes()); + } + bytes.extend(b"U->U"); + for word in [0x20000, END, 0, PAGES, LOOKUP, LIST, LIST, LIST, RULE] { + bytes.extend(word.to_be_bytes()); + } + bytes.extend([2, 0, 0, 1]); + bytes.extend(0xfffdu32.to_be_bytes()); + bytes.push(0); + bytes.extend([255; 255]); + let mut code_table = [0; 512]; + code_table[usize::from(b'-') * 2 + 1] = 1; + bytes.extend(code_table); + bytes.extend([0xfd, 0, 0, 0, 0xff, 1, 0, 0]); + bytes.extend(0u32.to_be_bytes()); + bytes.extend([2, 0, 0, 1, 0x11, 0, 0, b'-', 0x11, 0, 0, b'-']); + bytes.extend(replacement.to_be_bytes()); + + let mut compressed = b"zQmp".to_vec(); + compressed.extend((bytes.len() as u32).to_be_bytes()); + let mut encoder = + flate2::write::ZlibEncoder::new(compressed, flate2::Compression::default()); + encoder.write_all(&bytes).unwrap(); + Arc::from(encoder.finish().unwrap()) + } + + let p = directory("font-mapping"); + let mut request = request(&p); + request.world = WorldConfig::new(&p); + request.input_profile = InputProfile::XeTeX; + let mapping_path = p.join("replace.tec"); + let padding = format!("{}\n", "\\relax ".repeat(26)).repeat(45); + let source = format!( + r#"\catcode123=1 \catcode125=2 + \shipout\hbox{{\vrule width7pt height8pt}} + {padding} + \font\mapped="[LiberationSerif-Regular.ttf]:mapping=replace;" + \shipout\hbox{{\mapped --}} + \shipout\hbox{{\vrule width9pt height8pt}} + \end + "# + ); + let hyphens = source.find("--").unwrap(); + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: request.world.clone(), + revision: 1, + roots: [p.clone()].into(), + files: [ + (p.join("main.tex"), Arc::from(source.into_bytes())), + ( + p.join("LiberationSerif-Regular.ttf"), + Arc::from( + include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf").as_slice(), + ), + ), + (mapping_path.clone(), mapping(b'A'.into())), + ] + .into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [p.clone()].into(), + generated: Default::default(), + }) + .unwrap(); + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let before = compiler + .compile(request.clone().with_project(project.clone())) + .unwrap(); + let broken = project + .with_file_edits( + 2, + [(mapping_path.clone(), Arc::from(b"zQmp".as_slice()))].into(), + ) + .unwrap(); + let Err(error) = compiler.compile(request.clone().with_project(broken.clone())) else { + panic!("a truncated font mapping must fail"); + }; + assert!( + error + .to_string() + .contains("invalid compiled TECkit font mapping") + ); + assert_eq!( + fs::read(p.join("job.pdf")).unwrap(), + before.pdf.as_deref().unwrap() + ); + + let edited = broken + .with_file_edits(3, [(mapping_path, mapping(b'B'.into()))].into()) + .unwrap(); + let request = request.with_project(edited); + let resumed = compiler.compile(request.clone()).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + assert!(resumed.entry_checkpoint_work.reused_steps > 0); + assert_eq!(resumed.pdf, full.pdf); + assert_ne!(resumed.pdf, before.pdf); + assert_eq!(resumed.pages, full.pages); + assert_eq!(resumed.source_map.pages, full.source_map.pages); + let source = &resumed.source_map.pages[1].entries[0].source; + assert_eq!( + source + .tokens + .iter() + .map(|token| token.span.start) + .collect::>(), + [hyphens, hyphens + 1], + ); + assert!(source.derivations.contains(&Derivation::FontMapping)); + let changed = resumed.preview_since(Some(before.revision())).unwrap(); + assert_eq!( + changed + .pages + .iter() + .map(|page| page.index) + .collect::>(), + [1] + ); + eprintln!( + "TECkit edit reused {} steps", + resumed.entry_checkpoint_work.reused_steps + ); + fs::remove_dir_all(p).unwrap(); +} + #[test] fn checkpoint_keeps_late_special_tokens_until_the_updated_page_is_shipped() { let p = directory("late-special");