1use std::collections::BTreeMap;
11
12use fontoxide_misc::Tag;
13use fontoxide_misc::xml_reader::Element;
14use fontoxide_misc::xml_writer::XmlWriter;
15
16use crate::binary::{Reader, WriteBytes, fit};
17use crate::sstruct::eval;
18use crate::table::{DefaultTable, Table, TableType, TableXml};
19use crate::tables::Maxp;
20use crate::{Error, Font, Result};
21
22const TSI0: Tag = Tag::new(b"TSI0");
23const TSI1: Tag = Tag::new(b"TSI1");
24const TSI2: Tag = Tag::new(b"TSI2");
25const TSI3: Tag = Tag::new(b"TSI3");
26
27const MAGIC: TsiEntry = (0xFFFE, 0, 0xABFC_1F34);
29
30pub type TsiEntry = (u32, u32, u32);
33
34#[derive(Debug, Clone, PartialEq)]
39pub struct TsiIndex {
40 pub tag: Tag,
42 pub indices: Option<Vec<TsiEntry>>,
46 pub extra_indices: Vec<TsiEntry>,
48}
49
50impl Default for TsiIndex {
51 fn default() -> Self {
52 TsiIndex::new_as(TSI0)
53 }
54}
55
56impl TsiIndex {
57 pub fn set(&mut self, indices: Vec<TsiEntry>, extra_indices: Vec<TsiEntry>) {
59 self.indices = Some(indices);
60 self.extra_indices = extra_indices;
61 }
62
63 pub fn decompile_records(&mut self, data: &[u8], num_glyphs: usize) -> Result<()> {
65 let num_entries = data.len() / 8;
66 if num_entries != num_glyphs + 5 {
67 let diff = num_entries as i64 - num_glyphs as i64 - 5;
68 log::warn!(
69 "Number of glyphPrograms differs from the number of glyphs in the font by {} ({} programs vs. {num_glyphs} glyphs).",
70 diff.abs(),
71 num_entries as i64 - 5
72 );
73 }
74 let mut r = Reader::new(data);
75 let mut indices = Vec::with_capacity(num_entries);
76 for _ in 0..num_entries {
77 indices.push((u32::from(r.u16()?), u32::from(r.u16()?), r.u32()?));
78 }
79 if r.remaining() != 0 {
80 return Err(Error::Assertion(String::new()));
81 }
82 if indices.len() < 5 {
83 return Err(Error::ttlib("IndexError: list index out of range"));
84 }
85 if indices[indices.len() - 5] != MAGIC {
86 return Err(Error::Assertion("bad magic number".into()));
87 }
88 self.extra_indices = indices[indices.len() - 4..].to_vec();
89 indices.truncate(indices.len() - 5);
90 self.indices = Some(indices);
91 Ok(())
92 }
93
94 pub fn compile_records(&self) -> Result<Vec<u8>> {
96 let Some(indices) = &self.indices else {
97 return Ok(Vec::new());
100 };
101 let mut data = Vec::new();
102 for &(index, length, offset) in indices
103 .iter()
104 .chain(std::iter::once(&MAGIC))
105 .chain(&self.extra_indices)
106 {
107 data.put_u16(fit(index, "glyphID")?);
108 data.put_u16(fit(length, "textLength")?);
109 data.put_u32(offset);
110 }
111 Ok(data)
112 }
113}
114
115impl TableType for TsiIndex {
116 const TAG: Tag = TSI0;
117
118 fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
119 Self::decompile_as(TSI0, data, font)
120 }
121
122 fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
123 let num_glyphs = font.require::<Maxp>()?.num_glyphs as usize;
124 let mut table = Self::new_as(tag);
125 table.decompile_records(data, num_glyphs)?;
126 Ok(table)
127 }
128
129 fn new_as(tag: Tag) -> Self {
130 TsiIndex {
131 tag,
132 indices: None,
133 extra_indices: Vec::new(),
134 }
135 }
136}
137
138impl Table for TsiIndex {
139 fn tag(&self) -> Tag {
140 self.tag
141 }
142
143 fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
144 self.compile_records()
145 }
146
147 fn clone_table(&self) -> Box<dyn Table> {
148 Box::new(self.clone())
149 }
150
151 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
153 let _ = f;
154 Ok(())
155 }
156}
157
158impl TableXml for TsiIndex {
159 fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
160 writer.comment("This table will be calculated by the compiler");
161 writer.newline();
162 Ok(())
163 }
164
165 fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
167 let mut raw = DefaultTable::new(self.tag, Vec::new());
168 raw.from_xml(element, font)?;
169 *self = Self::decompile_as(self.tag, &raw.data, font)?;
170 Ok(())
171 }
172}
173
174const TSI1_EXTRAS: [(u32, &str); 4] = [
176 (0xFFFA, "ppgm"),
177 (0xFFFB, "cvt"),
178 (0xFFFC, "reserved"),
179 (0xFFFD, "fpgm"),
180];
181
182const TSI3_EXTRAS: [(u32, &str); 4] = [
184 (0xFFFA, "reserved0"),
185 (0xFFFB, "reserved1"),
186 (0xFFFC, "reserved2"),
187 (0xFFFD, "reserved3"),
188];
189
190#[derive(Debug, Clone, PartialEq)]
198pub struct TsiPrograms {
199 pub tag: Tag,
201 pub glyph_programs: BTreeMap<u32, String>,
204 pub extra_programs: BTreeMap<String, String>,
206}
207
208impl Default for TsiPrograms {
209 fn default() -> Self {
210 TsiPrograms::new_as(TSI1)
211 }
212}
213
214impl TsiPrograms {
215 pub fn index_tag(&self) -> Tag {
217 if self.tag == TSI3 { TSI2 } else { TSI0 }
218 }
219
220 pub fn extras(&self) -> &'static [(u32, &'static str); 4] {
222 if self.tag == TSI3 {
223 &TSI3_EXTRAS
224 } else {
225 &TSI1_EXTRAS
226 }
227 }
228
229 pub fn decompile_with_index(
231 &mut self,
232 data: &[u8],
233 index: &TsiIndex,
234 font: &mut Font,
235 ) -> Result<()> {
236 let total_length = data.len() as u64;
237 let indices = index
238 .indices
239 .as_ref()
240 .ok_or_else(|| Error::ttlib("AttributeError: 'indices'"))?;
241 for (records, is_extra) in [(indices, false), (&index.extra_indices, true)] {
242 let mut glyph_programs = BTreeMap::new();
243 let mut extra_programs = BTreeMap::new();
244 for (i, &(glyph_id, text_length, text_offset)) in records.iter().enumerate() {
245 let name = if is_extra {
246 let (_, name) = self
247 .extras()
248 .iter()
249 .find(|(code, _)| *code == glyph_id)
250 .ok_or_else(|| Error::ttlib(format!("KeyError: {glyph_id}")))?;
251 (*name).to_owned()
252 } else {
253 font.glyph_name(glyph_id)?
254 };
255 let text_offset = u64::from(text_offset);
256 if text_offset > total_length {
257 log::warn!(
258 "textOffset > totalLength; {} skipped",
259 fontoxide_misc::py::str_repr(&name)
260 );
261 continue;
262 }
263 let mut text_length = u64::from(text_length);
264 if text_length == 0x8000 {
265 let is_last = i == records.len() - 1;
266 let mut next_text_offset = if !is_last {
267 u64::from(records[i + 1].2)
268 } else if is_extra {
269 total_length
271 } else {
272 let first = index
274 .extra_indices
275 .first()
276 .ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?;
277 u64::from(first.2)
278 };
279 if next_text_offset < text_offset {
280 return Err(Error::Assertion("entries not sorted by offset".into()));
281 }
282 if next_text_offset > total_length {
283 log::warn!(
284 "nextTextOffset > totalLength; {} truncated",
285 fontoxide_misc::py::str_repr(&name)
286 );
287 next_text_offset = total_length;
288 }
289 text_length = next_text_offset - text_offset;
290 } else if text_length > 0x8000 {
291 return Err(Error::ttlib(format!(
292 "{} textLength ({text_length}) must not be > 32768",
293 fontoxide_misc::py::str_repr(&name)
294 )));
295 }
296 let end = (text_offset + text_length).min(total_length);
297 let text = &data[text_offset as usize..end as usize];
298 if text.len() as u64 != text_length {
299 return Err(Error::Assertion(String::new()));
300 }
301 let text = std::str::from_utf8(text)
302 .map_err(|e| Error::value(format!("UnicodeDecodeError: {e}")))?;
303 if !text.is_empty() {
304 if is_extra {
305 extra_programs.insert(name, text.to_owned());
306 } else {
307 glyph_programs.insert(glyph_id, text.to_owned());
308 }
309 }
310 }
311 if is_extra {
312 self.extra_programs = extra_programs;
313 } else {
314 self.glyph_programs = glyph_programs;
315 }
316 }
317 Ok(())
318 }
319
320 pub fn compile_with_index(
323 &self,
324 font: &mut Font,
325 ) -> Result<(Vec<u8>, Vec<TsiEntry>, Vec<TsiEntry>)> {
326 let mut data: Vec<u8> = Vec::new();
327 let num_glyphs = font.glyph_order()?.len();
328 let align = |data: &mut Vec<u8>| {
330 if !data.len().is_multiple_of(2) {
331 data.push(b'\r');
332 }
333 };
334 let mut indices = Vec::with_capacity(num_glyphs);
335 for gid in 0..num_glyphs as u32 {
336 align(&mut data);
337 let text = self
338 .glyph_programs
339 .get(&gid)
340 .map_or(&[][..], |t| t.as_bytes());
341 let length = text.len().min(0x8000) as u32;
342 indices.push((gid, length, fit(data.len(), "textOffset")?));
343 data.extend_from_slice(text);
344 }
345 let mut extra_indices = Vec::with_capacity(4);
346 for &(code, name) in self.extras() {
347 align(&mut data);
348 let text = self
349 .extra_programs
350 .get(name)
351 .map_or(&[][..], |t| t.as_bytes());
352 let length = text.len().min(0x8000) as u32;
353 extra_indices.push((code, length, fit(data.len(), "textOffset")?));
354 data.extend_from_slice(text);
355 }
356 Ok((data, indices, extra_indices))
357 }
358}
359
360impl TableType for TsiPrograms {
361 const TAG: Tag = TSI1;
362
363 fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
364 Self::decompile_as(TSI1, data, font)
365 }
366
367 fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
368 let mut table = Self::new_as(tag);
369 let index_tag = table.index_tag();
370 let index = font
371 .get_at::<TsiIndex>(index_tag)?
372 .ok_or(Error::TableNotFound(index_tag))?
373 .clone();
374 table.decompile_with_index(data, &index, font)?;
375 Ok(table)
376 }
377
378 fn new_as(tag: Tag) -> Self {
379 TsiPrograms {
380 tag,
381 glyph_programs: BTreeMap::new(),
382 extra_programs: BTreeMap::new(),
383 }
384 }
385}
386
387fn write_source(writer: &mut XmlWriter, element: &str, name: &str, text: &str) {
389 writer.begintag(element, &[("name", &name)]);
390 writer.newline();
391 writer.write_noindent(&text.replace('\r', "\n"));
392 writer.newline();
393 writer.endtag(element);
394 writer.newline();
395}
396
397fn inner_lines(element: &Element, cr: bool) -> Vec<String> {
400 let mut text = element.text();
401 if cr {
402 text = text.replace('\r', "\n");
403 }
404 let lines: Vec<&str> = text.split('\n').collect();
405 if lines.len() < 2 {
406 return Vec::new();
407 }
408 lines[1..lines.len() - 1]
409 .iter()
410 .map(|l| (*l).to_owned())
411 .collect()
412}
413
414impl Table for TsiPrograms {
415 fn tag(&self) -> Tag {
416 self.tag
417 }
418
419 fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
420 let (data, indices, extra_indices) = self.compile_with_index(font)?;
421 let index_tag = self.index_tag();
422 font.get_at::<TsiIndex>(index_tag)?
423 .ok_or(Error::TableNotFound(index_tag))?
424 .set(indices, extra_indices);
425 Ok(data)
426 }
427
428 fn clone_table(&self) -> Box<dyn Table> {
429 Box::new(self.clone())
430 }
431
432 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
435 let mut programs = BTreeMap::new();
436 for (gid, text) in std::mem::take(&mut self.glyph_programs) {
437 if let Ok(new) = f(gid) {
438 programs.insert(new, text);
439 }
440 }
441 self.glyph_programs = programs;
442 Ok(())
443 }
444}
445
446impl TableXml for TsiPrograms {
447 fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
448 let order = font.glyph_order()?;
449 let mut glyph_programs: Vec<(String, &String)> = self
450 .glyph_programs
451 .iter()
452 .map(|(&gid, text)| (order.name(gid).into_owned(), text))
453 .collect();
454 glyph_programs.sort();
455 writer.newline();
456 for (name, text) in glyph_programs {
457 if text.is_empty() {
458 continue;
459 }
460 write_source(writer, "glyphProgram", &name, text);
461 writer.newline();
462 }
463 for (name, text) in &self.extra_programs {
464 if text.is_empty() {
465 continue;
466 }
467 write_source(writer, "extraProgram", name, text);
468 writer.newline();
469 }
470 Ok(())
471 }
472
473 fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
474 let text = inner_lines(element, true).join("\r");
475 let name = || {
476 element
477 .attr("name")
478 .ok_or_else(|| Error::ttx(format!("missing 'name' on <{}>", element.name)))
479 };
480 match element.name.as_str() {
481 "glyphProgram" => {
482 let gid = font.glyph_id(name()?)?;
483 self.glyph_programs.insert(gid, text);
484 }
485 "extraProgram" => {
486 self.extra_programs.insert(name()?.to_owned(), text);
487 }
488 _ => {}
489 }
490 Ok(())
491 }
492}
493
494#[derive(Debug, Clone, PartialEq, Default)]
496pub struct Tsi5 {
497 pub glyph_grouping: BTreeMap<u32, i64>,
500}
501
502impl TableType for Tsi5 {
503 const TAG: Tag = Tag::new(b"TSI5");
504
505 fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
506 let num_glyphs = font.require::<Maxp>()?.num_glyphs as usize;
507 if !data.len().is_multiple_of(2) {
508 return Err(Error::value("bytes length not a multiple of item size"));
509 }
510 let num_entries = data.len() / 2;
511 if num_entries != num_glyphs {
512 let diff = num_entries as i64 - num_glyphs as i64;
513 log::warn!(
514 "Number of entries differs from the number of glyphs in the font by {} ({num_entries} entries vs. {num_glyphs} glyphs).",
515 diff.abs()
516 );
517 }
518 let mut glyph_grouping = BTreeMap::new();
519 for (i, &v) in data.as_chunks::<2>().0.iter().enumerate() {
520 glyph_grouping.insert(i as u32, i64::from(u16::from_be_bytes(v)));
521 }
522 Ok(Tsi5 { glyph_grouping })
523 }
524}
525
526impl Table for Tsi5 {
527 fn tag(&self) -> Tag {
528 Self::TAG
529 }
530
531 fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
532 let num_glyphs = font.glyph_order()?.len() as u32;
533 let mut data = Vec::new();
534 for gid in 0..num_glyphs {
535 let v = self.glyph_grouping.get(&gid).copied().unwrap_or(0);
536 data.put_u16(fit(v, "glyphgroup")?);
537 }
538 Ok(data)
539 }
540
541 fn clone_table(&self) -> Box<dyn Table> {
542 Box::new(self.clone())
543 }
544
545 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
548 let mut grouping = BTreeMap::new();
549 for (gid, v) in std::mem::take(&mut self.glyph_grouping) {
550 if let Ok(new) = f(gid) {
551 grouping.insert(new, v);
552 }
553 }
554 self.glyph_grouping = grouping;
555 Ok(())
556 }
557}
558
559impl TableXml for Tsi5 {
560 fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
561 let order = font.glyph_order()?;
562 let mut groups: Vec<(String, i64)> = self
563 .glyph_grouping
564 .iter()
565 .map(|(&gid, &v)| (order.name(gid).into_owned(), v))
566 .collect();
567 groups.sort();
568 for (name, value) in groups {
569 writer.simpletag("glyphgroup", &[("name", &name), ("value", &value)]);
570 writer.newline();
571 }
572 Ok(())
573 }
574
575 fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
576 if element.name != "glyphgroup" {
577 return Ok(());
578 }
579 let attr = |name: &str| {
580 element
581 .attr(name)
582 .ok_or_else(|| Error::ttx(format!("missing '{name}' on <glyphgroup>")))
583 };
584 let gid = font.glyph_id(attr("name")?)?;
585 let value = eval(attr("value")?)?
586 .as_int()
587 .ok_or_else(|| Error::value("invalid glyphgroup value"))?;
588 self.glyph_grouping.insert(gid, fit(value, "glyphgroup")?);
589 Ok(())
590 }
591}
592
593#[derive(Debug, Clone, PartialEq)]
597pub struct AsciiTable {
598 pub tag: Tag,
600 pub data: Vec<u8>,
602}
603
604impl Default for AsciiTable {
605 fn default() -> Self {
606 AsciiTable::new_as(Tag::new(b"TTFA"))
607 }
608}
609
610impl AsciiTable {
611 fn is_vtt(&self) -> bool {
613 self.tag != Tag::new(b"TTFA")
614 }
615}
616
617impl TableType for AsciiTable {
618 const TAG: Tag = Tag::new(b"TTFA");
619
620 fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
621 Self::decompile_as(Self::TAG, data, font)
622 }
623
624 fn decompile_as(tag: Tag, data: &[u8], _font: &mut Font) -> Result<Self> {
625 Ok(AsciiTable {
626 tag,
627 data: data.to_vec(),
628 })
629 }
630
631 fn new_as(tag: Tag) -> Self {
632 AsciiTable {
633 tag,
634 data: Vec::new(),
635 }
636 }
637}
638
639fn ascii_error(data: &[u8]) -> Error {
640 let pos = data.iter().position(|b| !b.is_ascii()).unwrap_or_default();
641 Error::value(format!(
642 "UnicodeDecodeError: 'ascii' codec can't decode byte 0x{:02x} in position {pos}: ordinal not in range(128)",
643 data.get(pos).copied().unwrap_or_default()
644 ))
645}
646
647impl Table for AsciiTable {
648 fn tag(&self) -> Tag {
649 self.tag
650 }
651
652 fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
653 Ok(self.data.clone())
654 }
655
656 fn clone_table(&self) -> Box<dyn Table> {
657 Box::new(self.clone())
658 }
659
660 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
661 let _ = f;
662 Ok(())
663 }
664}
665
666impl TableXml for AsciiTable {
667 fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
668 if !self.data.is_ascii() {
669 return Err(ascii_error(&self.data));
670 }
671 let text: String = self
673 .data
674 .iter()
675 .filter(|&&b| b != 0)
676 .map(|&b| b as char)
677 .collect();
678 let text = if self.is_vtt() {
679 text.replace('\r', "\n")
680 } else {
681 text
682 };
683 writer.begintag("source", &[]);
684 writer.newline();
685 writer.write_noindent(&text);
686 writer.newline();
687 writer.endtag("source");
688 writer.newline();
689 Ok(())
690 }
691
692 fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
694 let separator = if self.is_vtt() { "\r" } else { "\n" };
695 let text = inner_lines(element, false).join(separator);
696 if !text.is_ascii() {
697 let pos = text.chars().position(|c| !c.is_ascii()).unwrap_or_default();
698 return Err(Error::value(format!(
699 "UnicodeEncodeError: 'ascii' codec can't encode character in position {pos}: ordinal not in range(128)"
700 )));
701 }
702 self.data = text.into_bytes();
703 Ok(())
704 }
705}