Skip to main content

fontoxide_ttlib/
table.rs

1//! The table interface (`DefaultTable`) and the registry that maps tags to table
2//! implementations (`getTableClass`).
3
4use std::any::Any;
5use std::fmt;
6
7use fontoxide_misc::Tag;
8use fontoxide_misc::xml_reader::Element;
9use fontoxide_misc::xml_writer::XmlWriter;
10
11use crate::{Error, Font, Result};
12
13/// Upcasting to [`Any`], implemented for every sized `'static` type.
14pub trait AsAny: Any {
15	/// `self` as `&dyn Any`.
16	fn as_any(&self) -> &dyn Any;
17	/// `self` as `&mut dyn Any`.
18	fn as_any_mut(&mut self) -> &mut dyn Any;
19}
20
21impl<T: Any> AsAny for T {
22	fn as_any(&self) -> &dyn Any {
23		self
24	}
25	fn as_any_mut(&mut self) -> &mut dyn Any {
26		self
27	}
28}
29
30/// A font table (`DefaultTable` and its subclasses).
31///
32/// The methods take the [`Font`] because, as in fontTools, tables consult and even
33/// modify each other: `hmtx` needs `hhea` to decompile, compiling `maxp` updates the
34/// bounding box in `head`, and so on. While one of these methods runs, the table
35/// itself is detached from the font.
36pub trait Table: AsAny + fmt::Debug + Send + Sync {
37	/// The table tag (`tableTag`).
38	fn tag(&self) -> Tag;
39
40	/// Compiles the table to binary (`compile`).
41	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>>;
42
43	/// Writes the table's TTX content, without the enclosing table element
44	/// (`toXML`).
45	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()>;
46
47	/// Reads one child element of the table's TTX element (`fromXML`).
48	#[allow(clippy::wrong_self_convention)]
49	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()>;
50
51	/// A deep copy.
52	fn clone_table(&self) -> Box<dyn Table>;
53
54	/// Expands whatever was left compact when reading (`ensureDecompiled`).
55	fn ensure_decompiled(&mut self) {}
56
57	/// Maps every glyph ID in the table with `f`, as when the glyph order
58	/// changes (fontTools refers to glyphs by name, so this happens implicitly
59	/// there). `f` fails for glyphs that no longer exist.
60	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()>;
61
62	/// Whether this is a plain [`DefaultTable`], which TTX marks as `raw`.
63	fn is_raw(&self) -> bool {
64		false
65	}
66
67	/// The error message, if decompilation failed and the table was kept as raw
68	/// data (`ERROR`).
69	fn decompile_error(&self) -> Option<&str> {
70		None
71	}
72}
73
74impl Clone for Box<dyn Table> {
75	fn clone(&self) -> Self {
76		self.clone_table()
77	}
78}
79
80/// A table type with a fixed tag, which [`Font::get`] can return.
81pub trait TableType: Table + Sized {
82	/// The tag of this table type.
83	const TAG: Tag;
84
85	/// The tag of the beyond-64k companion that this type also implements, as
86	/// `GLYF` for `glyf`. [`Font::get`] prefers it, as fontTools does with its
87	/// `"GLYF" if "GLYF" in font else "glyf"`.
88	const COMPANION: Option<Tag> = None;
89
90	/// Parses the table (`decompile`).
91	fn decompile(data: &[u8], font: &mut Font) -> Result<Self>;
92
93	/// Parses the table under one of its tags.
94	fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
95		let _ = tag;
96		Self::decompile(data, font)
97	}
98
99	/// An empty table with one of its tags (`newTable`).
100	fn new_as(tag: Tag) -> Self
101	where
102		Self: Default,
103	{
104		let _ = tag;
105		Self::default()
106	}
107}
108
109/// A table kept as raw bytes (`DefaultTable`): used for tables fontoxide does not
110/// implement, and for tables that failed to decompile when decompile errors are
111/// ignored.
112#[derive(Clone, PartialEq, Eq)]
113pub struct DefaultTable {
114	/// The table tag.
115	pub tag: Tag,
116	/// The table data.
117	pub data: Vec<u8>,
118	/// The decompilation error, if this table replaces one that failed (`ERROR`).
119	pub error: Option<String>,
120}
121
122impl fmt::Debug for DefaultTable {
123	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124		f.debug_struct("DefaultTable")
125			.field("tag", &self.tag)
126			.field("len", &self.data.len())
127			.field("error", &self.error)
128			.finish()
129	}
130}
131
132impl DefaultTable {
133	/// A raw table with the given data.
134	pub fn new(tag: Tag, data: Vec<u8>) -> Self {
135		DefaultTable {
136			tag,
137			data,
138			error: None,
139		}
140	}
141}
142
143impl Table for DefaultTable {
144	/// Raw data is passed through unchanged.
145	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
146		let _ = f;
147		Ok(())
148	}
149
150	fn tag(&self) -> Tag {
151		self.tag
152	}
153
154	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
155		Ok(self.data.clone())
156	}
157
158	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
159		if let Some(error) = &self.error {
160			writer.comment("An error occurred during the decompilation of this table");
161			writer.newline();
162			writer.comment(error);
163			writer.newline();
164		}
165		writer.begintag("hexdata", &[]);
166		writer.newline();
167		writer.dumphex(&self.data);
168		writer.endtag("hexdata");
169		writer.newline();
170		Ok(())
171	}
172
173	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
174		if element.name != "hexdata" {
175			return Err(Error::ttlib(format!(
176				"can't handle '{}' element",
177				element.name
178			)));
179		}
180		self.data = read_hex(element)?;
181		Ok(())
182	}
183
184	fn clone_table(&self) -> Box<dyn Table> {
185		Box::new(self.clone())
186	}
187
188	fn is_raw(&self) -> bool {
189		true
190	}
191
192	fn decompile_error(&self) -> Option<&str> {
193		self.error.as_deref()
194	}
195}
196
197/// `readHex(content)` for an element.
198pub fn read_hex(element: &Element) -> Result<Vec<u8>> {
199	fontoxide_misc::text_tools::read_hex(element.text_chunks())
200		.ok_or_else(|| Error::value("invalid hex data"))
201}
202
203macro_rules! registry {
204	($($tag:literal => $ty:ty),* $(,)?) => {
205		/// Decompiles a table with the implementation registered for its tag, or as a
206		/// [`DefaultTable`] if there is none (`getTableClass(tag)().decompile(...)`).
207		pub fn decompile_table(tag: Tag, data: &[u8], font: &mut Font) -> Result<Box<dyn Table>> {
208			match &tag.0 {
209				$($tag => Ok(Box::new(<$ty as TableType>::decompile_as(tag, data, font)?)),)*
210				_ => Ok(Box::new(DefaultTable::new(tag, data.to_vec()))),
211			}
212		}
213
214		/// An empty table of the type registered for `tag`, for filling from TTX
215		/// (`newTable`).
216		pub fn new_table(tag: Tag) -> Box<dyn Table> {
217			match &tag.0 {
218				$($tag => Box::new(<$ty as TableType>::new_as(tag)),)*
219				_ => Box::new(DefaultTable::new(tag, Vec::new())),
220			}
221		}
222
223		/// Whether fontoxide implements the table as fontTools does: with a table
224		/// type of its own, or, for tags that fontTools has no table class for
225		/// either (such as `MERG` and `PCLT`), as a raw [`DefaultTable`], which is
226		/// what fontTools uses for them too.
227		pub fn is_implemented(tag: Tag) -> bool {
228			matches!(&tag.0, $($tag)|*)
229				|| !crate::generated::tables::FONTTOOLS_TABLES.contains(&tag)
230		}
231	};
232}
233
234registry! {
235	b"cvt " => crate::tables::Cvt,
236	b"CFF " => crate::tables::Cff,
237	b"CFF2" => crate::tables::Cff2,
238	b"BASE" => crate::tables::otl::Base,
239	b"GDEF" => crate::tables::otl::Gdef,
240	b"GPOS" => crate::tables::otl::Gpos,
241	b"GSUB" => crate::tables::otl::Gsub,
242	b"HVAR" => crate::tables::otl::Hvar,
243	b"IFT " => crate::tables::otl::Ift,
244	b"IFTX" => crate::tables::otl::Iftx,
245	b"JSTF" => crate::tables::otl::Jstf,
246	b"MATH" => crate::tables::otl::Math,
247	b"MVAR" => crate::tables::otl::Mvar,
248	b"STAT" => crate::tables::otl::Stat,
249	b"TSIC" => crate::tables::otl::Tsic,
250	b"VARC" => crate::tables::otl::Varc,
251	b"VVAR" => crate::tables::otl::Vvar,
252	b"ankr" => crate::tables::otl::Ankr,
253	b"bsln" => crate::tables::otl::Bsln,
254	b"cidg" => crate::tables::otl::Cidg,
255	b"feat" => crate::tables::otl::Feat,
256	b"gcid" => crate::tables::otl::Gcid,
257	b"lcar" => crate::tables::otl::Lcar,
258	b"mort" => crate::tables::otl::Mort,
259	b"morx" => crate::tables::otl::Morx,
260	b"opbd" => crate::tables::otl::Opbd,
261	b"prop" => crate::tables::otl::Prop,
262	b"FFTM" => crate::tables::Fftm,
263	b"avar" => crate::tables::Avar,
264	b"fpgm" => crate::tables::Fpgm,
265	b"prep" => crate::tables::Prep,
266	b"CBDT" => crate::tables::Cbdt,
267	b"CBLC" => crate::tables::Cblc,
268	b"COLR" => crate::tables::Colr,
269	b"CPAL" => crate::tables::Cpal,
270	b"EBDT" => crate::tables::Ebdt,
271	b"EBLC" => crate::tables::Eblc,
272	b"bdat" => crate::tables::Bdat,
273	b"bloc" => crate::tables::Bloc,
274	b"fvar" => crate::tables::Fvar,
275	b"gasp" => crate::tables::Gasp,
276	b"glyf" => crate::tables::Glyf,
277	b"GLYF" => crate::tables::Glyf,
278	b"gvar" => crate::tables::Gvar,
279	b"GVAR" => crate::tables::Gvar,
280	b"cvar" => crate::tables::Cvar,
281	b"loca" => crate::tables::Loca,
282	b"LOCA" => crate::tables::Loca,
283	b"cmap" => crate::tables::Cmap,
284	b"DMAP" => crate::tables::Dmap,
285	b"DSIG" => crate::tables::Dsig,
286	b"SVG " => crate::tables::Svg,
287	b"kern" => crate::tables::Kern,
288	b"hdmx" => crate::tables::Hdmx,
289	b"head" => crate::tables::Head,
290	b"bhed" => crate::tables::Bhed,
291	b"LTSH" => crate::tables::Ltsh,
292	b"hhea" => crate::tables::Hhea,
293	b"HHEA" => crate::tables::Hhea,
294	b"hmtx" => crate::tables::Hmtx,
295	b"HMTX" => crate::tables::Hmtx,
296	b"ltag" => crate::tables::Ltag,
297	b"maxp" => crate::tables::Maxp,
298	b"MAXP" => crate::tables::Maxp,
299	b"name" => crate::tables::Name,
300	b"OS/2" => crate::tables::Os2,
301	b"post" => crate::tables::Post,
302	b"sbix" => crate::tables::Sbix,
303	b"vhea" => crate::tables::Vhea,
304	b"VHEA" => crate::tables::Vhea,
305	b"vmtx" => crate::tables::Vmtx,
306	b"VMTX" => crate::tables::Vmtx,
307	b"VORG" => crate::tables::Vorg,
308	b"Debg" => crate::tables::Debg,
309	b"bgcl" => crate::tables::Bgcl,
310	b"EBSC" => crate::tables::Ebsc,
311	b"meta" => crate::tables::Meta,
312	b"trak" => crate::tables::Trak,
313	b"VDMX" => crate::tables::Vdmx,
314	b"TSI0" => crate::tables::TsiIndex,
315	b"TSI2" => crate::tables::TsiIndex,
316	b"TSI1" => crate::tables::TsiPrograms,
317	b"TSI3" => crate::tables::TsiPrograms,
318	b"TSI5" => crate::tables::Tsi5,
319	b"TSIB" => crate::tables::AsciiTable,
320	b"TSID" => crate::tables::AsciiTable,
321	b"TSIJ" => crate::tables::AsciiTable,
322	b"TSIP" => crate::tables::AsciiTable,
323	b"TSIS" => crate::tables::AsciiTable,
324	b"TSIV" => crate::tables::AsciiTable,
325	b"TTFA" => crate::tables::AsciiTable,
326	b"Feat" => crate::tables::graphite::Feat,
327	b"Glat" => crate::tables::Glat,
328	b"Gloc" => crate::tables::Gloc,
329	b"Silf" => crate::tables::Silf,
330	b"Sill" => crate::tables::Sill,
331}
332
333/// The tables that must be compiled before `tag` (`dependencies`), as declared by
334/// the fontTools table classes.
335pub fn dependencies(tag: Tag) -> &'static [Tag] {
336	crate::generated::tables::dependencies(tag)
337}