Skip to main content

fontoxide_ttlib/
ttx.rs

1//! Reading TTX documents (`fontTools.misc.xmlReader.XMLReader`, the
2//! TTX-specific part), and the file names of TTX dumps split into several files
3//! (`saveXML(splitTables=True, splitGlyphs=True)`).
4
5use std::collections::HashSet;
6use std::path::{Path, PathBuf};
7
8use fontoxide_misc::Tag;
9use fontoxide_misc::text_tools::{Literal, safe_eval};
10use fontoxide_misc::xml_reader::Element;
11
12use crate::font::{TableKey, xml_to_tag};
13use crate::table::{DefaultTable, new_table, table_from_xml};
14use crate::{Error, Font, Result};
15
16/// Options for importing TTX.
17#[derive(Debug, Clone, Copy, Default)]
18pub struct TtxImportOptions {
19	/// Skip tables that fontoxide does not implement yet, instead of failing on
20	/// them (unless they are dumped as raw data). For testing only: the skipped
21	/// tables are missing from the font.
22	pub skip_unimplemented: bool,
23}
24
25/// One file of a TTX dump: its path and its contents.
26///
27/// A dump split into several files ([`crate::TtxOptions::split_tables`],
28/// [`crate::TtxOptions::split_glyphs`]) refers to the table and glyph files by
29/// their file names (`src` attributes), relative to the file that refers to
30/// them; the files go in the same directory.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct TtxFile {
33	/// The path, derived from the path of the main file.
34	pub path: String,
35	/// The TTX text.
36	pub contents: String,
37}
38
39/// Loads a file that a TTX file refers to (with a `src` attribute) as text.
40pub type TtxLoader<'a> = dyn FnMut(&Path) -> Result<String> + 'a;
41
42/// Reads a TTX file from the file system as UTF-8 text, without a byte order mark.
43pub fn read_ttx_file(path: &Path) -> Result<String> {
44	let text = std::fs::read_to_string(path)?;
45	Ok(match text.strip_prefix('\u{feff}') {
46		Some(rest) => rest.to_owned(),
47		None => text,
48	})
49}
50
51/// Where the `src` attributes of the file being read are resolved.
52pub(crate) struct SubFiles<'a, 'b> {
53	/// The directory of the file being read (`os.path.dirname(file.name)`), or
54	/// the current directory (empty) if it has no name.
55	pub dir: PathBuf,
56	/// Loads a file.
57	pub load: &'a mut TtxLoader<'b>,
58}
59
60impl SubFiles<'_, '_> {
61	/// Parses the file of a `src` attribute (`os.path.join(dirname, subFile)`),
62	/// whose root must be `ttFont`. Returns the file's root and its directory.
63	fn read(&mut self, src: &str) -> Result<(Element, PathBuf)> {
64		let path = self.dir.join(src);
65		let text = (self.load)(&path)?;
66		let root =
67			fontoxide_misc::xml_reader::parse(&text).map_err(|e| Error::ttx(e.to_string()))?;
68		if root.name != "ttFont" {
69			return Err(Error::ttx(format!("illegal root tag: {}", root.name)));
70		}
71		let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
72		Ok((root, dir))
73	}
74}
75
76/// Imports a parsed TTX document into `font`.
77pub(crate) fn import(
78	font: &mut Font,
79	root: &Element,
80	options: &TtxImportOptions,
81	files: &mut SubFiles<'_, '_>,
82) -> Result<()> {
83	if root.name != "ttFont" {
84		return Err(Error::ttx(format!("illegal root tag: {}", root.name)));
85	}
86	if font.reader().is_none()
87		&& font.tags().is_empty()
88		&& let Some(v) = root.attr("sfntVersion")
89	{
90		font.sfnt_version = parse_sfnt_version(v)?;
91	}
92	for element in root.elements() {
93		if let Some(src) = element.attr("src") {
94			// A table in a file of its own, read by a new `XMLReader`.
95			let (sub_root, dir) = files.read(src)?;
96			let mut sub_files = SubFiles {
97				dir,
98				load: &mut *files.load,
99			};
100			import(font, &sub_root, options, &mut sub_files)?;
101			continue;
102		}
103		let key = xml_to_tag(&element.name)
104			.ok_or_else(|| Error::ttx(format!("invalid table element: {}", element.name)))?;
105		log::info!("Parsing '{}' table...", element.name);
106		match key {
107			TableKey::GlyphOrder => import_glyph_order(font, element)?,
108			TableKey::Table(tag) => {
109				let raw = element.attr("ERROR").is_some()
110					|| element
111						.attr("raw")
112						.and_then(safe_eval)
113						.is_some_and(|v| v.is_truthy());
114				if options.skip_unimplemented && !raw && !crate::table::is_implemented(tag) {
115					log::warn!("skipping unimplemented '{tag}' table");
116					continue;
117				}
118				import_table(font, tag, element, files)?
119			}
120		}
121	}
122	Ok(())
123}
124
125/// The `sfntVersion` attribute: four characters, or a Python string literal body
126/// with escapes such as `\x00\x01\x00\x00`.
127fn parse_sfnt_version(v: &str) -> Result<Tag> {
128	let text = if v.chars().count() == 4 {
129		v.to_owned()
130	} else {
131		match safe_eval(&format!("\"{v}\"")) {
132			Some(Literal::Str(s)) => s,
133			_ => return Err(Error::ttx(format!("invalid sfntVersion: {v:?}"))),
134		}
135	};
136	let bytes = fontoxide_misc::py::latin1_encode(&text)
137		.ok_or_else(|| Error::ttx(format!("invalid sfntVersion: {v:?}")))?;
138	// Packed as "4s": truncated or padded with NUL bytes.
139	let mut tag = [0u8; 4];
140	let n = bytes.len().min(4);
141	tag[..n].copy_from_slice(&bytes[..n]);
142	Ok(Tag(tag))
143}
144
145fn import_glyph_order(font: &mut Font, element: &Element) -> Result<()> {
146	let mut names = Vec::new();
147	let mut any = false;
148	for e in element.elements() {
149		any = true;
150		if e.name == "GlyphID" {
151			let name = e
152				.attr("name")
153				.ok_or_else(|| Error::ttx("missing 'name' on <GlyphID>"))?;
154			names.push(name.to_owned());
155		}
156	}
157	// fontTools calls setGlyphOrder for every child element, so an empty element
158	// leaves the glyph order alone.
159	if any {
160		font.set_glyph_order(names);
161	}
162	Ok(())
163}
164
165fn import_table(
166	font: &mut Font,
167	tag: Tag,
168	element: &Element,
169	files: &mut SubFiles<'_, '_>,
170) -> Result<()> {
171	let raw = element.attr("ERROR").is_some()
172		|| element
173			.attr("raw")
174			.and_then(safe_eval)
175			.is_some_and(|v| v.is_truthy());
176	let is_loca = tag == Tag::new(b"loca") || tag == Tag::new(b"LOCA");
177	if is_loca && font.contains(tag) {
178		// The original 'loca' is needed if 'glyf' isn't recompiled.
179		font.load(tag)?;
180	} else if raw {
181		font.insert(Box::new(DefaultTable::new(tag, Vec::new())));
182	} else {
183		font.insert(new_table(tag));
184	}
185	for child in element.elements() {
186		if let Some(src) = child.attr("src") {
187			// An element in a file of its own (a glyph of a split `glyf` table),
188			// read by an `XMLReader` with `contentOnly=True`: the elements below
189			// the second level of that file each replace this one, so that the
190			// last one is read.
191			let (sub_root, _) = files.read(src)?;
192			let last = sub_root
193				.elements()
194				.flat_map(Element::elements)
195				.last()
196				.ok_or_else(|| {
197					Error::ttx(format!(
198						"TypeError: cannot unpack non-iterable NoneType object (no content in {src})"
199					))
200				})?;
201			font.with_table(tag, |table, font| table_from_xml(table, last, font))?;
202			continue;
203		}
204		font.with_table(tag, |table, font| table_from_xml(table, child, font))?;
205	}
206	Ok(())
207}
208
209// --- File names of split dumps
210
211/// The path separators of `os.path`.
212const SEPARATORS: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
213
214/// `os.path.splitext`: the extension starts at the last period of the file name,
215/// unless only periods precede it.
216pub(crate) fn splitext(path: &str) -> (&str, &str) {
217	let name_start = path.rfind(SEPARATORS).map_or(0, |i| i + 1);
218	let name = &path[name_start..];
219	let leading = name.len() - name.trim_start_matches('.').len();
220	match name[leading..].rfind('.') {
221		Some(at) => path.split_at(name_start + leading + at),
222		None => (path, ""),
223	}
224}
225
226/// `os.path.basename`.
227pub(crate) fn basename(path: &str) -> &str {
228	path.rfind(SEPARATORS).map_or(path, |i| &path[i + 1..])
229}
230
231/// `fontTools.misc.filenames.userNameToFileName`, which names the glyph files.
232pub(crate) fn user_name_to_file_name(
233	user_name: &str,
234	existing: &HashSet<String>,
235	prefix: &str,
236	suffix: &str,
237) -> Result<String> {
238	fontoxide_misc::filenames::user_name_to_file_name(user_name, existing, prefix, suffix)
239		.map_err(|e| Error::value(e.to_string()))
240}
241
242#[cfg(test)]
243mod tests {
244	use super::*;
245	#[test]
246	fn path_helpers() {
247		assert_eq!(splitext("a/b.c/font.ttx"), ("a/b.c/font", ".ttx"));
248		assert_eq!(splitext("a.b/font"), ("a.b/font", ""));
249		assert_eq!(splitext("dir/.hidden"), ("dir/.hidden", ""));
250		assert_eq!(splitext("font._g_l_y_f.ttx"), ("font._g_l_y_f", ".ttx"));
251		assert_eq!(basename("a/b/font.ttx"), "font.ttx");
252		assert_eq!(basename("font.ttx"), "font.ttx");
253	}
254}