Execute TECkit font mappings in native XeLaTeX jobs

This commit is contained in:
gloamxun committed 2026-11-21 12:39:29 +08:00
1 parent 752af43f32
commit c548ca8e9f
12 files changed
+1098 -17

No files matched your search

@@ -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(),
@@ -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"));
+532
View File
@@ -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<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::{
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<Entry> = Vec::with_capacity(decomposed.len());
let mut starter: Option<usize> = 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)
}
@@ -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<Self, &'static str> {
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<Option<Hit>, &'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<Entry>,
) -> 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<usize>,
class_index: Option<usize>,
}
pub(super) struct Hit {
pub(super) end: usize,
captures: Vec<Capture>,
}
#[derive(Clone)]
struct Cursor {
index: usize,
position: isize,
repeat: u8,
end: usize,
captures: Vec<Capture>,
groups: Vec<(usize, u8)>,
}
impl Pattern<'_> {
fn find(&self, position: isize, budget: &mut usize) -> Result<Option<Hit>, &'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;
}
+1
View File
@@ -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;
+31 -7
View File
@@ -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<String>,
script: Option<String>,
language: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mapping: Option<String>,
}
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::<Feature>()
@@ -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<Arc<FontMapping>>,
}
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<H: Hasher>(&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<Arc<FontMapping>>,
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<FontMapping>> {
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<OpenTypeRun, String> {
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
+1
View File
@@ -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 {
+6 -1
View File
@@ -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)]