Skip to main content

fontoxide_ttlib/tables/
meta.rs

1//! `meta`: the metadata table (`fontTools.ttLib.tables._m_e_t_a`).
2
3use std::collections::BTreeMap;
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::xml_reader::Element;
7use fontoxide_misc::xml_writer::XmlWriter;
8
9use crate::binary::fit;
10use crate::sstruct::{Bytes, U32};
11use crate::table::{Table, TableType, TableXml, read_hex};
12use crate::{Error, Font, Result};
13
14crate::sstruct! {
15	/// The header (`META_HEADER_FORMAT`).
16	pub struct MetaHeader = "META_HEADER_FORMAT" {
17		/// The table version (1).
18		pub version: u32 = "version" as U32,
19		/// Flags (0).
20		pub flags: u32 = "flags" as U32,
21		/// The offset of the data.
22		pub data_offset: u32 = "dataOffset" as U32,
23		/// The number of data maps.
24		pub num_data_maps: u32 = "numDataMaps" as U32,
25	}
26}
27
28crate::sstruct! {
29	/// A data map record (`DATA_MAP_FORMAT`).
30	pub struct DataMap = "DATA_MAP_FORMAT" {
31		/// The metadata tag.
32		pub tag: [u8; 4] = "tag" as Bytes<4>,
33		/// The offset of the data.
34		pub data_offset: u32 = "dataOffset" as U32,
35		/// The length of the data.
36		pub data_length: u32 = "dataLength" as U32,
37	}
38}
39
40/// A metadata value.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum MetaValue {
43	/// Text, for the `dlng` and `slng` tags (stored as UTF-8).
44	Text(String),
45	/// Binary data, for the other tags.
46	Binary(Vec<u8>),
47}
48
49/// Whether the data of a tag is text.
50fn is_text_tag(tag: &str) -> bool {
51	tag == "dlng" || tag == "slng"
52}
53
54/// Metadata table (`table__m_e_t_a`).
55///
56/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/meta>.
57#[derive(Debug, Clone, PartialEq, Default)]
58pub struct Meta {
59	/// The metadata by tag (`data`). Tags are sorted when compiling.
60	pub data: BTreeMap<String, MetaValue>,
61}
62
63impl TableType for Meta {
64	const TAG: Tag = Tag::new(b"meta");
65
66	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
67		let (header, _) = MetaHeader::unpack2(data)?;
68		if header.version != 1 {
69			return Err(Error::ttlib(format!(
70				"unsupported 'meta' version {}",
71				header.version
72			)));
73		}
74		let mut table = Meta::default();
75		for i in 0..header.num_data_maps as usize {
76			let start = (16 + i * 12).min(data.len());
77			let end = (start + 12).min(data.len());
78			let (map, _) = DataMap::unpack2(&data[start..end])?;
79			// sstruct decodes ASCII byte strings.
80			// Other tags would stay `bytes` in fontTools; fontoxide does not
81			// represent them and fails instead.
82			let tag = if map.tag.is_ascii() {
83				map.tag.iter().map(|&b| b as char).collect::<String>()
84			} else {
85				return Err(Error::ttlib(format!(
86					"unsupported 'meta' tag {}",
87					fontoxide_misc::py::bytes_repr(&map.tag)
88				)));
89			};
90			let offset = (map.data_offset as usize).min(data.len());
91			let end = offset
92				.saturating_add(map.data_length as usize)
93				.min(data.len());
94			let bytes = data[offset..end].to_vec();
95			let value = if is_text_tag(&tag) {
96				MetaValue::Text(
97					String::from_utf8(bytes)
98						.map_err(|e| Error::value(format!("UnicodeDecodeError: {e}")))?,
99				)
100			} else {
101				MetaValue::Binary(bytes)
102			};
103			table.data.insert(tag, value);
104		}
105		Ok(table)
106	}
107}
108
109impl Table for Meta {
110	fn tag(&self) -> Tag {
111		Self::TAG
112	}
113
114	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
115		let mut data_offset = 16 + self.data.len() * 12;
116		let mut out = Vec::new();
117		MetaHeader {
118			version: 1,
119			flags: 0,
120			data_offset: fit(data_offset, "dataOffset")?,
121			num_data_maps: fit(self.data.len(), "numDataMaps")?,
122		}
123		.pack(&mut out)?;
124		let mut blocks = Vec::new();
125		for (tag, value) in &self.data {
126			let bytes = match (is_text_tag(tag), value) {
127				(true, MetaValue::Text(s)) => s.as_bytes(),
128				(true, MetaValue::Binary(_)) => {
129					return Err(Error::ttlib(
130						"AttributeError: 'bytes' object has no attribute 'encode'",
131					));
132				}
133				(false, MetaValue::Binary(b)) => b.as_slice(),
134				(false, MetaValue::Text(_)) => {
135					return Err(Error::value(
136						"TypeError: sequence item: expected a bytes-like object, str found",
137					));
138				}
139			};
140			// struct.pack("4s") of the ASCII-encoded tag truncates or pads it.
141			if !tag.is_ascii() {
142				return Err(Error::value(format!(
143					"UnicodeEncodeError: 'ascii' codec can't encode tag {tag:?}"
144				)));
145			}
146			let mut tag_bytes = [0u8; 4];
147			let n = tag.len().min(4);
148			tag_bytes[..n].copy_from_slice(&tag.as_bytes()[..n]);
149			DataMap {
150				tag: tag_bytes,
151				data_offset: fit(data_offset, "dataOffset")?,
152				data_length: fit(bytes.len(), "dataLength")?,
153			}
154			.pack(&mut out)?;
155			blocks.push(bytes);
156			data_offset += bytes.len();
157		}
158		for block in blocks {
159			out.extend_from_slice(block);
160		}
161		Ok(out)
162	}
163
164	fn clone_table(&self) -> Box<dyn Table> {
165		Box::new(self.clone())
166	}
167
168	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
169		let _ = f;
170		Ok(())
171	}
172}
173
174impl TableXml for Meta {
175	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
176		for (tag, value) in &self.data {
177			match (is_text_tag(tag), value) {
178				(true, MetaValue::Text(text)) => {
179					writer.begintag("text", &[("tag", tag)]);
180					writer.newline();
181					writer.write(text);
182					writer.newline();
183					writer.endtag("text");
184					writer.newline();
185				}
186				(false, MetaValue::Binary(data)) => {
187					writer.begintag("hexdata", &[("tag", tag)]);
188					writer.newline();
189					let (Some(&min), Some(&max)) = (data.iter().min(), data.iter().max()) else {
190						return Err(Error::value("min() iterable argument is empty"));
191					};
192					if min >= 0x20 && max <= 0x7E {
193						let ascii: String = data.iter().map(|&b| b as char).collect();
194						writer.comment(&format!("ascii: {ascii}"));
195						writer.newline();
196					}
197					writer.dumphex(data);
198					writer.endtag("hexdata");
199					writer.newline();
200				}
201				_ => {
202					return Err(Error::value(format!(
203						"unexpected type of 'meta' data for tag {tag:?}"
204					)));
205				}
206			}
207		}
208		Ok(())
209	}
210
211	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
212		let tag = || {
213			element
214				.attr("tag")
215				.ok_or_else(|| Error::ttx(format!("missing 'tag' on <{}>", element.name)))
216		};
217		match element.name.as_str() {
218			"hexdata" => {
219				let data = read_hex(element)?;
220				self.data.insert(tag()?.to_owned(), MetaValue::Binary(data));
221			}
222			"text" if is_text_tag(tag()?) => {
223				let text = fontoxide_misc::py::strip(&element.text()).to_owned();
224				self.data.insert(tag()?.to_owned(), MetaValue::Text(text));
225			}
226			name => return Err(Error::ttlib(format!("can't handle '{name}' element"))),
227		}
228		Ok(())
229	}
230}
231
232#[cfg(test)]
233mod tests {
234	use super::*;
235
236	#[test]
237	fn formats_match_upstream() {
238		use crate::sstruct::tests::check;
239		check(MetaHeader::FORMAT_NAME, MetaHeader::FIELDS);
240		check(DataMap::FORMAT_NAME, DataMap::FIELDS);
241	}
242}