1use std::collections::{BTreeMap, HashMap};
4use std::sync::Arc;
5
6use fontoxide_misc::Tag;
7use fontoxide_misc::xml_writer::{INDENT, XmlWriter};
8
9use crate::glyph_order::{GlyphOrder, make_glyph_name};
10use crate::sfnt::{
11 Flavor, FlavorData, SfntReader, SfntReaderOptions, SfntWriter, reorder_font_tables,
12};
13use crate::table::{Table, TableType, decompile_table, dependencies};
14use crate::{Error, Result};
15
16#[derive(Debug, Clone, Copy)]
18pub struct ReadOptions {
19 pub font_number: Option<usize>,
21 pub check_checksums: u8,
24 pub recalc_bboxes: bool,
27 pub recalc_timestamp: bool,
29 pub ignore_decompile_errors: bool,
32 pub use_legacy_ttc: bool,
35 pub use_harfbuzz_repacker: Option<bool>,
37 pub optimize_font_speed: bool,
39 pub woff_limits: crate::sfnt::WoffLimits,
42}
43
44impl Default for ReadOptions {
45 fn default() -> Self {
46 ReadOptions {
47 font_number: None,
48 check_checksums: 0,
49 recalc_bboxes: true,
50 recalc_timestamp: true,
51 ignore_decompile_errors: false,
52 use_legacy_ttc: false,
53 use_harfbuzz_repacker: None,
54 optimize_font_speed: false,
55 woff_limits: crate::sfnt::WoffLimits::DEFAULT,
56 }
57 }
58}
59
60pub type Progress = std::rc::Rc<dyn Fn(f64)>;
63
64#[derive(Clone)]
66pub struct WriteOptions {
67 pub reorder_tables: Option<bool>,
71 pub woff2_quality: u32,
74 pub woff2_progress: Option<Progress>,
79 pub use_zopfli: bool,
83}
84
85impl Default for WriteOptions {
86 fn default() -> Self {
87 WriteOptions {
88 reorder_tables: Some(true),
89 woff2_quality: 11,
90 woff2_progress: None,
91 use_zopfli: false,
92 }
93 }
94}
95
96impl std::fmt::Debug for WriteOptions {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("WriteOptions")
99 .field("reorder_tables", &self.reorder_tables)
100 .field("woff2_quality", &self.woff2_quality)
101 .field("use_zopfli", &self.use_zopfli)
102 .field(
103 "woff2_progress",
104 &self.woff2_progress.as_ref().map(|_| ".."),
105 )
106 .finish()
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
112pub enum TableKey {
113 GlyphOrder,
115 Table(Tag),
117}
118
119impl From<Tag> for TableKey {
120 fn from(tag: Tag) -> Self {
121 TableKey::Table(tag)
122 }
123}
124
125#[derive(Debug, Clone)]
127pub struct TtxOptions {
128 pub tables: Vec<TableKey>,
130 pub skip_tables: Vec<TableKey>,
132 pub write_version: bool,
134 pub newline: String,
136 pub disassemble_instructions: bool,
138 pub bitmap_glyph_data_format: String,
141 pub split_tables: bool,
144 pub split_glyphs: bool,
147}
148
149impl Default for TtxOptions {
150 fn default() -> Self {
151 TtxOptions {
152 tables: Vec::new(),
153 skip_tables: Vec::new(),
154 write_version: true,
155 newline: "\n".into(),
156 disassemble_instructions: true,
157 bitmap_glyph_data_format: "raw".into(),
158 split_tables: false,
159 split_glyphs: false,
160 }
161 }
162}
163
164pub(crate) type TableCache = HashMap<(Tag, Vec<u8>), crate::sfnt::DirectoryEntry>;
167
168#[derive(Debug)]
169enum Slot {
170 Loaded(Box<dyn Table>),
171 Busy,
173}
174
175#[derive(Debug)]
180pub struct Font {
181 reader: Option<SfntReader>,
182 tables: BTreeMap<Tag, Slot>,
183 glyph_order: Option<Arc<GlyphOrder>>,
184 pub sfnt_version: Tag,
186 pub flavor: Option<Flavor>,
188 pub flavor_data: Option<FlavorData>,
190 pub recalc_bboxes: bool,
192 pub recalc_timestamp: bool,
194 pub ignore_decompile_errors: bool,
196 pub disassemble_instructions: bool,
198 pub bitmap_glyph_data_format: String,
200 pub use_harfbuzz_repacker: Option<bool>,
205 gpos_compression_level: u8,
209 pub write_gpos7: bool,
213 pub optimize_font_speed: bool,
220 pub(crate) skip_post_glyph_names: bool,
222 pub(crate) stat_axis_names: Option<Vec<Option<String>>>,
227}
228
229impl Clone for Font {
230 fn clone(&self) -> Self {
231 Font {
232 reader: self.reader.clone(),
233 tables: self
234 .tables
235 .iter()
236 .filter_map(|(tag, slot)| match slot {
237 Slot::Loaded(t) => Some((*tag, Slot::Loaded(t.clone_table()))),
238 Slot::Busy => None,
239 })
240 .collect(),
241 glyph_order: self.glyph_order.clone(),
242 sfnt_version: self.sfnt_version,
243 flavor: self.flavor,
244 flavor_data: self.flavor_data.clone(),
245 recalc_bboxes: self.recalc_bboxes,
246 recalc_timestamp: self.recalc_timestamp,
247 ignore_decompile_errors: self.ignore_decompile_errors,
248 disassemble_instructions: self.disassemble_instructions,
249 bitmap_glyph_data_format: self.bitmap_glyph_data_format.clone(),
250 use_harfbuzz_repacker: self.use_harfbuzz_repacker,
251 gpos_compression_level: self.gpos_compression_level,
252 write_gpos7: self.write_gpos7,
253 optimize_font_speed: self.optimize_font_speed,
254 skip_post_glyph_names: self.skip_post_glyph_names,
255 stat_axis_names: self.stat_axis_names.clone(),
256 }
257 }
258}
259
260impl Default for Font {
261 fn default() -> Self {
262 Self::new()
263 }
264}
265
266const MAXP: Tag = Tag::new(b"maxp");
267const MAXP_32: Tag = Tag::new(b"MAXP");
268const HEAD: Tag = Tag::new(b"head");
269const POST: Tag = Tag::new(b"post");
270const CFF: Tag = Tag::new(b"CFF ");
271const CMAP: Tag = Tag::new(b"cmap");
272const DMAP: Tag = Tag::new(b"DMAP");
273const FVAR: Tag = Tag::new(b"fvar");
274const AVAR: Tag = Tag::new(b"avar");
275
276fn normalize_value(v: f64, (lower, default, upper): (f64, f64, f64)) -> Result<f64> {
278 if !(lower <= default && default <= upper) {
279 return Err(Error::value(format!(
280 "Invalid axis values, must be minimum, default, maximum: {lower:.3}, {default:.3}, {upper:.3}"
281 )));
282 }
283 let v = v.min(upper).max(lower);
284 if v == default || lower == upper {
285 return Ok(0.0);
286 }
287 if (v < default && lower != default) || (v > default && upper == default) {
288 Ok((v - default) / (default - lower))
289 } else {
290 Ok((v - default) / (upper - default))
291 }
292}
293
294pub(crate) fn piecewise_linear_map(v: f64, mapping: &[(f64, f64)]) -> f64 {
297 if mapping.is_empty() {
298 return v;
299 }
300 if let Some(&(_, to)) = mapping.iter().find(|(from, _)| *from == v) {
301 return to;
302 }
303 let extreme = |pick: fn(f64, f64) -> f64| {
304 mapping
305 .iter()
306 .copied()
307 .reduce(|a, b| if pick(a.0, b.0) == a.0 { a } else { b })
308 };
309 if let Some((k, to)) = extreme(f64::min)
310 && v < k
311 {
312 return v + to - k;
313 }
314 if let Some((k, to)) = extreme(f64::max)
315 && v > k
316 {
317 return v + to - k;
318 }
319 let below = mapping
320 .iter()
321 .copied()
322 .filter(|(k, _)| *k < v)
323 .reduce(|a, b| if a.0 >= b.0 { a } else { b });
324 let above = mapping
325 .iter()
326 .copied()
327 .filter(|(k, _)| *k > v)
328 .reduce(|a, b| if a.0 <= b.0 { a } else { b });
329 match (below, above) {
330 (Some((a, va)), Some((b, vb))) => va + (vb - va) * (v - a) / (b - a),
331 _ => v,
332 }
333}
334
335impl Font {
336 pub fn new() -> Self {
338 Font {
339 reader: None,
340 tables: BTreeMap::new(),
341 glyph_order: None,
342 sfnt_version: Tag::new(b"\0\x01\0\0"),
343 flavor: None,
344 flavor_data: None,
345 recalc_bboxes: true,
346 recalc_timestamp: true,
347 ignore_decompile_errors: false,
348 disassemble_instructions: true,
349 bitmap_glyph_data_format: "raw".into(),
350 use_harfbuzz_repacker: None,
351 gpos_compression_level: 0,
352 write_gpos7: false,
353 optimize_font_speed: false,
354 skip_post_glyph_names: false,
355 stat_axis_names: None,
356 }
357 }
358
359 pub fn load_post_without_glyph_names(&mut self) -> Result<()> {
363 self.skip_post_glyph_names = true;
364 let post = self.require::<crate::tables::Post>().map(|post| {
365 if post.format_type == 2.0 {
366 post.format_type = 3.0;
367 }
368 });
369 self.skip_post_glyph_names = false;
370 post
371 }
372
373 pub fn remap_glyphs(
378 &mut self,
379 f: &mut dyn FnMut(u32) -> Result<u32>,
380 new_order: Vec<String>,
381 ) -> Result<()> {
382 for slot in self.tables.values_mut() {
383 if let Slot::Loaded(t) = slot {
384 t.remap_glyphs(f)?;
385 }
386 }
387 self.set_glyph_order(new_order);
388 Ok(())
389 }
390
391 pub fn read(data: impl Into<Arc<[u8]>>, options: ReadOptions) -> Result<Self> {
393 let reader = SfntReader::with_woff_limits(
394 data,
395 SfntReaderOptions {
396 check_checksums: options.check_checksums,
397 font_number: options.font_number,
398 use_legacy_ttc: options.use_legacy_ttc,
399 },
400 options.woff_limits,
401 )?;
402 let mut font = Font::new();
403 font.sfnt_version = reader.sfnt_version;
404 font.flavor = reader.flavor;
405 font.flavor_data = reader.flavor_data.clone();
406 font.recalc_bboxes = options.recalc_bboxes;
407 font.recalc_timestamp = options.recalc_timestamp;
408 font.ignore_decompile_errors = options.ignore_decompile_errors;
409 font.use_harfbuzz_repacker = options.use_harfbuzz_repacker;
410 font.optimize_font_speed = options.optimize_font_speed;
411 font.reader = Some(reader);
412 Ok(font)
413 }
414
415 pub fn reader(&self) -> Option<&SfntReader> {
417 self.reader.as_ref()
418 }
419
420 pub fn contains(&self, tag: Tag) -> bool {
422 self.tables.contains_key(&tag) || self.reader.as_ref().is_some_and(|r| r.contains(tag))
423 }
424
425 pub fn is_loaded(&self, tag: Tag) -> bool {
427 self.tables.contains_key(&tag)
428 }
429
430 pub fn tags(&self) -> Vec<Tag> {
433 let mut tags: Vec<Tag> = self.tables.keys().copied().collect();
434 if let Some(r) = &self.reader {
435 for tag in r.tags() {
436 if !self.tables.contains_key(&tag) {
437 tags.push(tag);
438 }
439 }
440 }
441 sorted_tag_list(&tags, None)
442 }
443
444 pub fn load(&mut self, tag: Tag) -> Result<bool> {
446 match self.tables.get(&tag) {
447 Some(Slot::Loaded(_)) => return Ok(true),
448 Some(Slot::Busy) => return Err(Error::TableBusy(tag)),
449 None => {}
450 }
451 let Some(reader) = &self.reader else {
452 return Ok(false);
453 };
454 if !reader.contains(tag) {
455 return Ok(false);
456 }
457 let data = reader.table_data(tag)?;
458 self.tables.insert(tag, Slot::Busy);
459 let table = match decompile_table(tag, &data, self) {
460 Ok(t) => t,
461 Err(e) if self.ignore_decompile_errors => {
462 log::error!(
463 "An exception occurred during the decompilation of the '{tag}' table: {e}"
464 );
465 let mut t = crate::table::DefaultTable::new(tag, data.to_vec());
466 t.error = Some(e.to_string());
467 Box::new(t)
468 }
469 Err(e) => {
470 self.tables.remove(&tag);
471 return Err(Error::Decompile {
472 tag,
473 source: Box::new(e),
474 });
475 }
476 };
477 self.tables.insert(tag, Slot::Loaded(table));
478 Ok(true)
479 }
480
481 pub fn family_tag<T: TableType>(&self) -> Tag {
484 match T::COMPANION {
485 Some(upper) if self.contains(upper) => upper,
486 _ => T::TAG,
487 }
488 }
489
490 pub fn has<T: TableType>(&self) -> bool {
492 self.contains(self.family_tag::<T>())
493 }
494
495 pub fn get<T: TableType>(&mut self) -> Result<Option<&mut T>> {
498 let tag = self.family_tag::<T>();
499 self.get_at::<T>(tag)
500 }
501
502 pub fn get_at<T: TableType>(&mut self, tag: Tag) -> Result<Option<&mut T>> {
504 if !self.load(tag)? {
505 return Ok(None);
506 }
507 match self.tables.get_mut(&tag) {
508 Some(Slot::Loaded(t)) => (**t)
509 .as_any_mut()
510 .downcast_mut::<T>()
511 .map(Some)
512 .ok_or(Error::WrongTableType(tag)),
513 Some(Slot::Busy) => Err(Error::TableBusy(tag)),
514 None => Ok(None),
515 }
516 }
517
518 pub fn locked_tag<T: TableType>(extended: bool) -> Tag {
521 match T::COMPANION {
522 Some(upper) if extended => upper,
523 _ => T::TAG,
524 }
525 }
526
527 pub fn get_locked<T: TableType>(&mut self, extended: bool) -> Result<Option<&mut T>> {
529 self.get_at::<T>(Self::locked_tag::<T>(extended))
530 }
531
532 pub fn require_locked<T: TableType>(&mut self, extended: bool) -> Result<&mut T> {
534 let tag = Self::locked_tag::<T>(extended);
535 self.get_at::<T>(tag)?.ok_or(Error::TableNotFound(tag))
536 }
537
538 pub fn require<T: TableType>(&mut self) -> Result<&mut T> {
540 let tag = self.family_tag::<T>();
541 self.get_at::<T>(tag)?.ok_or(Error::TableNotFound(tag))
542 }
543
544 pub fn loaded<T: TableType>(&self) -> Option<&T> {
546 match self.tables.get(&self.family_tag::<T>()) {
547 Some(Slot::Loaded(t)) => (**t).as_any().downcast_ref::<T>(),
548 _ => None,
549 }
550 }
551
552 pub fn get_dyn(&mut self, tag: Tag) -> Result<Option<&mut dyn Table>> {
554 if !self.load(tag)? {
555 return Ok(None);
556 }
557 match self.tables.get_mut(&tag) {
558 Some(Slot::Loaded(t)) => Ok(Some(t.as_mut())),
559 Some(Slot::Busy) => Err(Error::TableBusy(tag)),
560 None => Ok(None),
561 }
562 }
563
564 pub fn insert(&mut self, table: Box<dyn Table>) {
566 self.tables.insert(table.tag(), Slot::Loaded(table));
567 }
568
569 pub fn remove(&mut self, tag: Tag) -> bool {
571 let loaded = self.tables.remove(&tag).is_some();
572 let read = self.reader.as_mut().is_some_and(|r| r.remove(tag));
573 loaded || read
574 }
575
576 pub fn with_table<R>(
579 &mut self,
580 tag: Tag,
581 f: impl FnOnce(&mut dyn Table, &mut Font) -> Result<R>,
582 ) -> Result<R> {
583 if !self.load(tag)? {
584 return Err(Error::TableNotFound(tag));
585 }
586 let mut table = match self.tables.insert(tag, Slot::Busy) {
587 Some(Slot::Loaded(t)) => t,
588 _ => return Err(Error::TableBusy(tag)),
589 };
590 let result = f(table.as_mut(), self);
591 self.tables.insert(tag, Slot::Loaded(table));
592 result
593 }
594
595 pub fn table_data(&mut self, tag: Tag) -> Result<Vec<u8>> {
598 if self.is_loaded(tag) {
599 return self
600 .with_table(tag, |t, font| t.compile(font))
601 .map_err(|e| match e {
602 e @ (Error::Compile { .. } | Error::TableBusy(_)) => e,
603 e => Error::Compile {
604 tag,
605 source: Box::new(e),
606 },
607 });
608 }
609 match &self.reader {
610 Some(r) if r.contains(tag) => Ok(r.table_data(tag)?.to_vec()),
611 _ => Err(Error::TableNotFound(tag)),
612 }
613 }
614
615 pub fn ensure_decompiled(&mut self) -> Result<()> {
617 self.glyph_order()?;
618 for tag in self.tags() {
619 self.load(tag)?;
620 if let Some(t) = self.get_dyn(tag)? {
621 t.ensure_decompiled();
622 }
623 }
624 Ok(())
625 }
626
627 pub fn glyph_count(&mut self) -> Result<usize> {
629 Ok(self.require::<crate::tables::maxp::Maxp>()?.num_glyphs as usize)
630 }
631
632 pub fn has_glyph_order(&self) -> bool {
634 self.glyph_order.is_some()
635 }
636
637 pub fn gpos_compression_level(&self) -> u8 {
641 self.gpos_compression_level
642 }
643
644 pub fn set_gpos_compression_level(&mut self, level: u8) -> Result<()> {
649 if level > 9 {
650 return Err(Error::value(format!(
651 "Config option fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL: value is invalid (given {level})"
652 )));
653 }
654 self.gpos_compression_level = level;
655 Ok(())
656 }
657
658 pub fn set_glyph_order(&mut self, names: Vec<String>) {
660 self.glyph_order = Some(Arc::new(GlyphOrder::new(names)));
661 }
662
663 pub fn glyph_order(&mut self) -> Result<Arc<GlyphOrder>> {
666 if let Some(order) = &self.glyph_order {
667 return Ok(order.clone());
668 }
669 if self.contains(CFF) {
670 let names = self.require::<crate::tables::Cff>()?.cff.glyph_order()?;
671 self.set_glyph_order(names);
672 } else if self.contains(POST) {
673 let names = self
674 .require::<crate::tables::post::Post>()?
675 .take_glyph_order()?;
676 match names {
677 None => self.glyph_names_from_cmap()?,
678 Some(names) if names.len() < self.glyph_count()? => {
679 log::warn!(
680 "Not enough names found in the 'post' table, generating them from cmap instead"
681 );
682 self.glyph_names_from_cmap()?;
683 }
684 Some(names) => self.set_glyph_order(names),
685 }
686 } else {
687 self.glyph_names_from_cmap()?;
688 }
689 Ok(self.glyph_order.clone().unwrap_or_default())
690 }
691
692 pub fn get_best_cmap(
696 &mut self,
697 preferences: &[(u16, u16)],
698 ) -> Result<Option<crate::tables::cmap::CharMap>> {
699 let cmap = match self.get::<crate::tables::Cmap>()? {
700 Some(t) => t.get_best_cmap(preferences).cloned(),
701 None => None,
702 };
703 let dmap = match self.get::<crate::tables::Dmap>()? {
704 Some(t) => t.0.get_best_cmap(preferences).cloned(),
705 None => None,
706 };
707 let Some(mut dmap) = dmap else {
708 return Ok(cmap);
709 };
710 dmap.retain(|_, g| *g != 0);
712 let Some(mut cmap) = cmap else {
713 return Ok(Some(dmap));
714 };
715 cmap.extend(dmap);
716 Ok(Some(cmap))
717 }
718
719 pub fn normalize_location(
725 &mut self,
726 location: &BTreeMap<String, f64>,
727 ) -> Result<crate::var::Location> {
728 if !self.contains(FVAR) {
729 return Err(Error::ttlib("Not a variable font"));
730 }
731 let axes: Vec<(String, (f64, f64, f64))> = self
732 .require::<crate::tables::Fvar>()?
733 .axes
734 .iter()
735 .map(|a| (a.tag_text(), (a.min_value, a.default_value, a.max_value)))
736 .collect();
737 let mut out = crate::var::Location::new();
739 for (tag, triple) in &axes {
740 let v = location.get(tag).copied().unwrap_or(triple.1);
741 out.insert(tag.clone(), normalize_value(v, *triple)?);
742 }
743 if !self.contains(AVAR) {
744 return Ok(out);
745 }
746 let avar = self.require::<crate::tables::Avar>()?;
748 if !matches!(avar.major_version, 1 | 2) {
749 return Err(Error::ttlib(
750 "NotImplementedError: Unknown avar table version",
751 ));
752 }
753 for (tag, value) in &mut out {
754 let mapping = Tag::from_str_padded(tag).and_then(|t| avar.segments.get(&t));
755 if let Some(mapping) = mapping {
756 *value = piecewise_linear_map(*value, mapping);
757 }
758 }
759 if avar.major_version < 2 {
760 return Ok(out);
761 }
762 let tags: Vec<String> = axes.into_iter().map(|(tag, _)| tag).collect();
763 let store = avar.table.var_store.as_deref();
764 let map = avar.table.var_idx_map.as_deref();
765 let instancer = crate::var::VarStoreInstancer::new(store, &tags, out.clone());
766 let mut renormalized = crate::var::Location::new();
767 for (index, tag) in tags.iter().enumerate() {
768 let mut v = fontoxide_misc::fixed_tools::float_to_fixed(
769 out.get(tag).copied().unwrap_or(0.0),
770 14,
771 );
772 let var_idx = match map {
773 Some(map) => map
775 .mapping
776 .get(index)
777 .or(map.mapping.last())
778 .copied()
779 .ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?,
780 None => index as u64,
781 };
782 if store.is_some() {
783 v += fontoxide_misc::round_tools::ot_round(instancer.get(var_idx)?);
784 v = v.clamp(-(1 << 14), 1 << 14);
785 }
786 if v != 0 {
788 renormalized.insert(
789 tag.clone(),
790 fontoxide_misc::fixed_tools::fixed_to_float(v, 14),
791 );
792 }
793 }
794 Ok(renormalized)
795 }
796
797 pub fn glyph_name(&mut self, gid: u32) -> Result<String> {
799 Ok(self.glyph_order()?.name(gid).into_owned())
800 }
801
802 pub fn glyph_id(&mut self, name: &str) -> Result<u32> {
804 self.glyph_order()?
805 .id(name)
806 .ok_or_else(|| Error::GlyphNotFound(name.to_owned()))
807 }
808
809 fn glyph_names_from_cmap(&mut self) -> Result<()> {
815 let num_glyphs = self.glyph_count()?;
816 let mut names: Vec<String> = (0..num_glyphs)
817 .map(|i| crate::glyph_order::synthesized_name(i as u32))
818 .collect();
819 if let Some(first) = names.first_mut() {
820 *first = ".notdef".into();
821 }
822 self.set_glyph_order(names.clone());
824
825 let read =
826 |font: &Font, tag: Tag| -> Result<Option<Vec<crate::tables::cmap::UnicodeMapping>>> {
827 match &font.reader {
828 Some(r) if r.contains(tag) => {
829 let data = r.table_data(tag)?;
830 Ok(Some(crate::tables::cmap::unicode_mappings(tag, &data)?))
831 }
832 _ => Ok(None),
833 }
834 };
835 let cmap = read(self, CMAP)?;
836 let dmap = read(self, DMAP)?;
837 let dmap_codepoints: std::collections::HashSet<u32> = dmap
838 .iter()
839 .flatten()
840 .flat_map(|m| m.cmap.keys().copied())
841 .collect();
842 let mut reverse: HashMap<u32, u32> = HashMap::new();
844 for (is_cmap, tables) in [(true, &cmap), (false, &dmap)] {
845 for table in tables.iter().flatten() {
846 for (&codepoint, &gid) in &table.cmap {
847 if is_cmap && dmap_codepoints.contains(&codepoint) {
848 continue;
849 }
850 reverse
851 .entry(gid)
852 .and_modify(|c| *c = (*c).min(codepoint))
853 .or_insert(codepoint);
854 }
855 }
856 }
857 let mut use_count: HashMap<String, usize> = HashMap::new();
858 for (gid, name) in names.iter_mut().enumerate() {
859 if let Some(&codepoint) = reverse.get(&(gid as u32)) {
860 let mut glyph_name = make_glyph_name(codepoint);
861 let n = use_count.entry(glyph_name.clone()).or_default();
862 *n += 1;
863 if *n > 1 {
864 glyph_name = format!("{glyph_name}.alt{}", *n - 1);
865 }
866 *name = glyph_name;
867 }
868 }
869 self.set_glyph_order(names);
870 Ok(())
871 }
872
873 pub fn write(&mut self, options: &WriteOptions) -> Result<Vec<u8>> {
875 let (data, writer_reorders) = self.save_into(Vec::new(), None, Some(options))?;
876 match options.reorder_tables {
877 None => Ok(data),
878 _ if writer_reorders => Ok(data),
879 Some(false) => match &self.reader {
880 None => Ok(data),
881 Some(r) => {
882 let order: Vec<Tag> = r.tags().collect();
883 reorder_font_tables(data, Some(&order), options.use_zopfli)
884 }
885 },
886 Some(true) => reorder_font_tables(data, None, options.use_zopfli),
887 }
888 }
889
890 pub(crate) fn save_into(
895 &mut self,
896 file: Vec<u8>,
897 mut cache: Option<&mut TableCache>,
898 options: Option<&WriteOptions>,
899 ) -> Result<(Vec<u8>, bool)> {
900 if self.recalc_timestamp && self.contains(HEAD) {
901 self.load(HEAD)?;
902 }
903 let tags = self.tags();
904 if self.flavor == Some(crate::sfnt::Flavor::Woff2) && !crate::woff2::HAVE_BROTLI {
905 crate::woff2::log_no_brotli("encoder");
907 return Err(crate::woff2::no_brotli());
908 }
909 let mut writer = SfntWriter::with_buffer(
910 file,
911 tags.len(),
912 self.sfnt_version,
913 self.flavor,
914 self.flavor_data.clone(),
915 );
916 if let Some(options) = options {
917 writer.set_woff2_compression(options.woff2_quality, options.woff2_progress.clone());
918 writer.set_use_zopfli(options.use_zopfli);
919 }
920 let mut done = Vec::new();
921 for &tag in &tags {
922 self.write_table(tag, &mut writer, &mut done, cache.as_deref_mut())?;
923 }
924 let writer_reorders = writer.reorders_tables();
925 Ok((writer.close()?, writer_reorders))
926 }
927
928 fn write_table(
929 &mut self,
930 tag: Tag,
931 writer: &mut SfntWriter,
932 done: &mut Vec<Tag>,
933 mut cache: Option<&mut TableCache>,
934 ) -> Result<()> {
935 if done.contains(&tag) {
936 return Ok(());
937 }
938 for &master in dependencies(tag) {
939 if !done.contains(&master) {
940 if self.contains(master) {
941 self.write_table(master, writer, done, cache.as_deref_mut())?;
942 } else {
943 done.push(master);
944 }
945 }
946 }
947 done.push(tag);
948 let data = self.table_data(tag)?;
949 if let Some(cache) = cache {
950 if let Some(entry) = cache.get(&(tag, data.clone())) {
951 log::debug!("reusing '{tag}' table");
952 return writer.set_entry(entry.clone());
953 }
954 writer.add(tag, &data)?;
955 if let Some(entry) = writer.entry(tag) {
956 cache.insert((tag, data), entry.clone());
957 }
958 return Ok(());
959 }
960 writer.add(tag, &data)
961 }
962
963 pub fn to_ttx(&mut self, options: &TtxOptions) -> Result<String> {
967 let mut writer = XmlWriter::with_options(INDENT, &options.newline);
968 self.save_xml(&mut writer, options)?;
969 Ok(writer.into_string())
970 }
971
972 pub fn to_ttx_files(
978 &mut self,
979 path: &str,
980 options: &TtxOptions,
981 ) -> Result<Vec<crate::ttx::TtxFile>> {
982 let mut writer = XmlWriter::with_options(INDENT, &options.newline);
983 let mut files = Vec::new();
984 self.save_xml_impl(&mut writer, options, Some(path), &mut files)?;
985 files.insert(
986 0,
987 crate::ttx::TtxFile {
988 path: path.to_owned(),
989 contents: writer.into_string(),
990 },
991 );
992 Ok(files)
993 }
994
995 pub(crate) fn save_xml(&mut self, writer: &mut XmlWriter, options: &TtxOptions) -> Result<()> {
996 self.save_xml_impl(writer, options, None, &mut Vec::new())
997 }
998
999 fn save_xml_impl(
1003 &mut self,
1004 writer: &mut XmlWriter,
1005 options: &TtxOptions,
1006 path: Option<&str>,
1007 files: &mut Vec<crate::ttx::TtxFile>,
1008 ) -> Result<()> {
1009 self.disassemble_instructions = options.disassemble_instructions;
1010 self.bitmap_glyph_data_format = options.bitmap_glyph_data_format.clone();
1011 let tables: Vec<TableKey> = if options.tables.is_empty() {
1012 std::iter::once(TableKey::GlyphOrder)
1013 .chain(self.tags().into_iter().map(TableKey::Table))
1014 .filter(|k| !options.skip_tables.contains(k))
1015 .collect()
1016 } else {
1017 options.tables.clone()
1018 };
1019 let sfnt_version = fontoxide_misc::py::str_repr(&self.sfnt_version.as_string());
1020 let sfnt_version = &sfnt_version[1..sfnt_version.len() - 1];
1021 if options.write_version {
1022 writer.begintag(
1023 "ttFont",
1024 &[
1025 ("sfntVersion", &sfnt_version),
1026 ("ttLibVersion", &TTLIB_VERSION),
1027 ],
1028 );
1029 } else {
1030 writer.begintag("ttFont", &[("sfntVersion", &sfnt_version)]);
1031 }
1032 writer.newline();
1033 let split_tables = options.split_tables || options.split_glyphs;
1035 let split_path = if split_tables {
1036 let Some(path) = path else {
1037 return Err(Error::ttlib(
1038 "splitTables requires the file name to be a file system path, not a stream.",
1039 ));
1040 };
1041 Some(crate::ttx::splitext(path))
1042 } else {
1043 writer.newline();
1044 None
1045 };
1046 for key in tables {
1047 let Some((stem, ext)) = split_path else {
1048 self.table_to_xml(writer, key, None, files)?;
1049 continue;
1050 };
1051 let identifier = match key {
1052 TableKey::GlyphOrder => "GlyphOrder".to_owned(),
1053 TableKey::Table(tag) => tag_to_identifier(tag),
1054 };
1055 let table_path = format!("{stem}.{identifier}{ext}");
1056 let mut table_writer = XmlWriter::with_options(INDENT, writer.newline_str());
1057 table_writer.begintag("ttFont", &[("ttLibVersion", &TTLIB_VERSION)]);
1062 table_writer.newline();
1063 table_writer.newline();
1064 let xml_tag = match key {
1065 TableKey::GlyphOrder => "GlyphOrder".to_owned(),
1066 TableKey::Table(tag) => tag_to_xml(tag),
1067 };
1068 writer.simpletag(&xml_tag, &[("src", &crate::ttx::basename(&table_path))]);
1069 writer.newline();
1070 let glyphs_path = options.split_glyphs.then_some(table_path.as_str());
1071 self.table_to_xml(&mut table_writer, key, glyphs_path, files)?;
1072 table_writer.endtag("ttFont");
1073 table_writer.newline();
1074 files.push(crate::ttx::TtxFile {
1075 path: table_path,
1076 contents: table_writer.into_string(),
1077 });
1078 }
1079 writer.endtag("ttFont");
1080 writer.newline();
1081 Ok(())
1082 }
1083
1084 fn table_to_xml(
1087 &mut self,
1088 writer: &mut XmlWriter,
1089 key: TableKey,
1090 split_glyphs: Option<&str>,
1091 files: &mut Vec<crate::ttx::TtxFile>,
1092 ) -> Result<()> {
1093 let tag = match key {
1094 TableKey::GlyphOrder => {
1095 log::info!("Dumping 'GlyphOrder' table...");
1096 let order = self.glyph_order()?;
1097 writer.begintag("GlyphOrder", &[]);
1098 writer.newline();
1099 writer.comment("The 'id' attribute is only for humans; it is ignored when parsed.");
1100 writer.newline();
1101 for (i, name) in order.names().iter().enumerate() {
1102 writer.simpletag("GlyphID", &[("id", &i), ("name", name)]);
1103 writer.newline();
1104 }
1105 writer.endtag("GlyphOrder");
1106 writer.newline();
1107 writer.newline();
1108 return Ok(());
1109 }
1110 TableKey::Table(tag) => tag,
1111 };
1112 if !self.contains(tag) {
1113 log::info!("No '{tag}' table found.");
1114 return Ok(());
1115 }
1116 log::info!("Dumping '{tag}' table...");
1117 let xml_tag = tag_to_xml(tag);
1118 self.with_table(tag, |table, font| {
1119 let error = table.decompile_error().is_some();
1120 let raw = table.is_raw();
1121 match (error, raw) {
1122 (true, true) => writer.begintag(
1123 &xml_tag,
1124 &[("ERROR", &"decompilation error"), ("raw", &true)],
1125 ),
1126 (true, false) => writer.begintag(&xml_tag, &[("ERROR", &"decompilation error")]),
1127 (false, true) => writer.begintag(&xml_tag, &[("raw", &true)]),
1128 (false, false) => writer.begintag(&xml_tag, &[]),
1129 }
1130 writer.newline();
1131 let glyf = table.as_any().downcast_ref::<crate::tables::Glyf>();
1132 match (split_glyphs, glyf) {
1133 (Some(path), Some(glyf)) => files.extend(glyf.to_xml_split(writer, font, path)?),
1134 _ => crate::table::table_to_xml(table, writer, font)?,
1136 }
1137 writer.endtag(&xml_tag);
1138 writer.newline();
1139 writer.newline();
1140 Ok(())
1141 })
1142 }
1143
1144 pub fn from_ttx(text: &str) -> Result<Self> {
1146 let mut font = Font::new();
1147 font.import_ttx(text)?;
1148 Ok(font)
1149 }
1150
1151 pub fn import_ttx(&mut self, text: &str) -> Result<()> {
1153 self.import_ttx_with(text, &crate::ttx::TtxImportOptions::default())
1154 }
1155
1156 pub fn import_ttx_with(
1162 &mut self,
1163 text: &str,
1164 options: &crate::ttx::TtxImportOptions,
1165 ) -> Result<()> {
1166 self.import_ttx_split(text, None, options, &mut crate::ttx::read_ttx_file)
1167 }
1168
1169 pub fn import_ttx_file(&mut self, path: impl AsRef<std::path::Path>) -> Result<()> {
1172 let path = path.as_ref();
1173 let text = crate::ttx::read_ttx_file(path)?;
1174 self.import_ttx_split(
1175 &text,
1176 Some(path),
1177 &crate::ttx::TtxImportOptions::default(),
1178 &mut crate::ttx::read_ttx_file,
1179 )
1180 }
1181
1182 pub fn import_ttx_split(
1188 &mut self,
1189 text: &str,
1190 path: Option<&std::path::Path>,
1191 options: &crate::ttx::TtxImportOptions,
1192 load: &mut crate::ttx::TtxLoader<'_>,
1193 ) -> Result<()> {
1194 if (self.contains(MAXP_32) || self.contains(MAXP)) && self.contains(POST) {
1195 self.glyph_order()?;
1199 }
1200 let root =
1201 fontoxide_misc::xml_reader::parse(text).map_err(|e| Error::ttx(e.to_string()))?;
1202 let dir = path
1203 .and_then(std::path::Path::parent)
1204 .map(std::path::Path::to_path_buf)
1205 .unwrap_or_default();
1206 let mut files = crate::ttx::SubFiles { dir, load };
1207 crate::ttx::import(self, &root, options, &mut files)
1208 }
1209}
1210
1211pub const TTLIB_VERSION: &str = {
1213 let v = crate::FONTTOOLS_VERSION.as_bytes();
1215 let mut dots = 0;
1216 let mut i = 0;
1217 while i < v.len() {
1218 if v[i] == b'.' {
1219 dots += 1;
1220 if dots == 2 {
1221 break;
1222 }
1223 }
1224 i += 1;
1225 }
1226 match std::str::from_utf8(v.split_at(i).0) {
1227 Ok(s) => s,
1228 Err(_) => panic!("FONTTOOLS_VERSION is ASCII"),
1229 }
1230};
1231
1232pub const TTF_TABLE_ORDER: [Tag; 20] = [
1235 Tag::new(b"head"),
1236 Tag::new(b"hhea"),
1237 Tag::new(b"maxp"),
1238 Tag::new(b"OS/2"),
1239 Tag::new(b"hmtx"),
1240 Tag::new(b"LTSH"),
1241 Tag::new(b"VDMX"),
1242 Tag::new(b"hdmx"),
1243 Tag::new(b"DMAP"),
1244 Tag::new(b"cmap"),
1245 Tag::new(b"fpgm"),
1246 Tag::new(b"prep"),
1247 Tag::new(b"cvt "),
1248 Tag::new(b"loca"),
1249 Tag::new(b"glyf"),
1250 Tag::new(b"kern"),
1251 Tag::new(b"name"),
1252 Tag::new(b"post"),
1253 Tag::new(b"gasp"),
1254 Tag::new(b"PCLT"),
1255];
1256
1257pub const OTF_TABLE_ORDER: [Tag; 9] = [
1259 Tag::new(b"head"),
1260 Tag::new(b"hhea"),
1261 Tag::new(b"maxp"),
1262 Tag::new(b"OS/2"),
1263 Tag::new(b"name"),
1264 Tag::new(b"DMAP"),
1265 Tag::new(b"cmap"),
1266 Tag::new(b"post"),
1267 Tag::new(b"CFF "),
1268];
1269
1270pub fn sorted_tag_list(tags: &[Tag], table_order: Option<&[Tag]>) -> Vec<Tag> {
1273 let mut tags = tags.to_vec();
1274 tags.sort();
1275 let order: &[Tag] = match table_order {
1276 Some(order) => order,
1277 None => {
1278 let dsig = Tag::new(b"DSIG");
1279 if let Some(i) = tags.iter().position(|t| *t == dsig) {
1280 tags.remove(i);
1281 tags.push(dsig);
1282 }
1283 if tags.contains(&CFF) {
1284 &OTF_TABLE_ORDER
1285 } else {
1286 &TTF_TABLE_ORDER
1287 }
1288 }
1289 };
1290 let mut ordered = Vec::with_capacity(tags.len());
1291 for tag in order {
1292 if let Some(i) = tags.iter().position(|t| t == tag) {
1293 ordered.push(tags.remove(i));
1294 }
1295 }
1296 ordered.extend(tags);
1297 ordered
1298}
1299
1300pub fn tag_to_identifier(tag: Tag) -> String {
1304 let mut bytes: &[u8] = &tag.0;
1305 while bytes.len() > 1 && bytes.last() == Some(&b' ') {
1306 bytes = &bytes[..bytes.len() - 1];
1307 }
1308 let mut ident = String::new();
1309 for &c in bytes {
1310 if c.is_ascii_lowercase() || c.is_ascii_digit() {
1311 ident.push('_');
1312 ident.push(c as char);
1313 } else if c.is_ascii_uppercase() {
1314 ident.push(c as char);
1315 ident.push('_');
1316 } else {
1317 ident.push_str(&format!("{c:x}"));
1318 }
1319 }
1320 if ident.starts_with(|c: char| c.is_ascii_digit()) {
1321 ident.insert(0, '_');
1322 }
1323 ident
1324}
1325
1326pub fn identifier_to_tag(ident: &str) -> Option<Tag> {
1328 let mut ident = ident.as_bytes();
1329 if ident.len() % 2 == 1 && ident.first() == Some(&b'_') {
1330 ident = &ident[1..];
1331 }
1332 if ident.len() % 2 == 1 {
1333 return None;
1334 }
1335 let mut tag = Vec::new();
1336 for pair in ident.chunks(2) {
1337 if pair[0] == b'_' {
1338 tag.push(pair[1]);
1339 } else if pair[1] == b'_' {
1340 tag.push(pair[0]);
1341 } else {
1342 tag.push(u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()?);
1343 }
1344 }
1345 if tag.len() > 4 {
1346 return None;
1347 }
1348 tag.resize(4, b' ');
1349 Some(Tag(tag.try_into().ok()?))
1350}
1351
1352pub fn tag_to_xml(tag: Tag) -> String {
1354 if tag == *b"OS/2" {
1355 return "OS_2".into();
1356 }
1357 let s = tag.as_string();
1358 let trimmed = s.trim_end_matches(' ');
1360 let valid = trimmed
1361 .bytes()
1362 .next()
1363 .is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
1364 && trimmed
1365 .bytes()
1366 .all(|c| c.is_ascii_alphanumeric() || c == b'_');
1367 if valid {
1368 s.trim().to_owned()
1369 } else {
1370 tag_to_identifier(tag)
1371 }
1372}
1373
1374pub fn xml_to_tag(name: &str) -> Option<TableKey> {
1376 if name == "GlyphOrder" {
1377 return Some(TableKey::GlyphOrder);
1378 }
1379 if name == "OS_2" {
1380 return Some(TableKey::Table(Tag::new(b"OS/2")));
1381 }
1382 if name.len() == 8 {
1383 return identifier_to_tag(name).map(TableKey::Table);
1384 }
1385 Tag::from_str_padded(name).map(TableKey::Table)
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390 use super::*;
1391
1392 #[test]
1393 fn tag_identifiers() {
1394 assert_eq!(tag_to_identifier(Tag::new(b"glyf")), "_g_l_y_f");
1395 assert_eq!(tag_to_identifier(Tag::new(b"cvt ")), "_c_v_t");
1396 assert_eq!(tag_to_identifier(Tag::new(b"OS/2")), "O_S_2f_2");
1397 assert_eq!(tag_to_identifier(Tag::new(b"CFF ")), "C_F_F_");
1398 assert_eq!(identifier_to_tag("O_S_2f_2"), Some(Tag::new(b"OS/2")));
1399 assert_eq!(identifier_to_tag("_c_v_t"), Some(Tag::new(b"cvt ")));
1400 assert_eq!(tag_to_xml(Tag::new(b"cvt ")), "cvt");
1401 assert_eq!(tag_to_xml(Tag::new(b"OS/2")), "OS_2");
1402 assert_eq!(tag_to_xml(Tag::new(b"CFF ")), "CFF");
1403 assert_eq!(xml_to_tag("cvt"), Some(TableKey::Table(Tag::new(b"cvt "))));
1404 assert_eq!(TTLIB_VERSION, "4.69");
1405 }
1406
1407 #[test]
1408 fn table_order() {
1409 let tags: Vec<Tag> = [b"name", b"DSIG", b"cmap", b"head", b"GSUB"]
1410 .iter()
1411 .map(|t| Tag::new(t))
1412 .collect();
1413 let sorted = sorted_tag_list(&tags, None);
1414 let s: Vec<String> = sorted.iter().map(|t| t.to_string()).collect();
1415 assert_eq!(s, ["head", "cmap", "name", "GSUB", "DSIG"]);
1416 }
1417}