1use 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#[derive(Debug, Clone, Copy, Default)]
18pub struct TtxImportOptions {
19 pub skip_unimplemented: bool,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct TtxFile {
33 pub path: String,
35 pub contents: String,
37}
38
39pub type TtxLoader<'a> = dyn FnMut(&Path) -> Result<String> + 'a;
41
42pub 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
51pub(crate) struct SubFiles<'a, 'b> {
53 pub dir: PathBuf,
56 pub load: &'a mut TtxLoader<'b>,
58}
59
60impl SubFiles<'_, '_> {
61 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
76pub(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 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
125fn 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 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 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 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 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
209const SEPARATORS: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
213
214pub(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
226pub(crate) fn basename(path: &str) -> &str {
228 path.rfind(SEPARATORS).map_or(path, |i| &path[i + 1..])
229}
230
231pub(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}