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