Skip to main content

fontoxide_ttlib/tables/
cff.rs

1//! `CFF ` and `CFF2` tables (`fontTools.ttLib.tables.C_F_F_`, `C_F_F__2`).
2
3use fontoxide_misc::xml_reader::Element;
4use fontoxide_misc::xml_writer::XmlWriter;
5
6use crate::cff::compile::CompileContext;
7use crate::cff::font::CffFontSet;
8use crate::table::{Table, TableType, TableXml};
9use crate::{Error, Font, Result, Tag};
10
11macro_rules! cff_table {
12	($name:ident, $tag:literal, $cff2:literal, $doc:literal) => {
13		#[doc = $doc]
14		#[derive(Debug, Clone, Default, PartialEq)]
15		pub struct $name {
16			/// The font set (`cff`).
17			pub cff: CffFontSet,
18		}
19
20		impl TableType for $name {
21			const TAG: Tag = Tag::new($tag);
22
23			fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
24				let order = if $cff2 {
25					Some(font.glyph_order()?.names().to_vec())
26				} else {
27					None
28				};
29				let cff = CffFontSet::decompile(data, $cff2, order.as_deref())?;
30				if cff.font_names.len() != 1 {
31					return Err(Error::Assertion(
32						"can't deal with multi-font CFF tables.".into(),
33					));
34				}
35				Ok($name { cff })
36			}
37		}
38
39		impl Table for $name {
40			/// The charstrings are kept by glyph name, as in fontTools, so they
41			/// follow the glyph order by name: dropping glyphs is up to the caller.
42			fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
43				let _ = f;
44				Ok(())
45			}
46
47			fn tag(&self) -> Tag {
48				Self::TAG
49			}
50
51			fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
52				// `getGlyphOrder` takes the glyph order of a CFF font from this table,
53				// which is detached from the font while compiling.
54				if !$cff2 && !font.has_glyph_order() {
55					if let Ok(names) = self.cff.glyph_order() {
56						font.set_glyph_order(names);
57					}
58				}
59				let order = font.glyph_order()?;
60				let ctx = CompileContext {
61					glyph_order: order.names(),
62					recalc_bboxes: font.recalc_bboxes,
63					has_varc: font.contains(Tag::new(b"VARC")),
64				};
65				self.cff.compile($cff2, &ctx)
66			}
67
68			fn clone_table(&self) -> Box<dyn Table> {
69				Box::new(self.clone())
70			}
71		}
72
73		impl TableXml for $name {
74			fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
75				self.cff.to_xml(writer)
76			}
77
78			fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
79				self.cff.from_xml(element)
80			}
81		}
82	};
83}
84
85cff_table!(Cff, b"CFF ", false, "The `CFF ` table: a CFF font set.");
86cff_table!(Cff2, b"CFF2", true, "The `CFF2` table: a CFF2 font set.");