Skip to main content

fontoxide_ttlib/tables/
json_tables.rs

1//! Tables holding a JSON document: `Debg` (`D__e_b_g`) and `bgcl` (`_b_g_c_l`).
2
3use fontoxide_misc::Tag;
4use fontoxide_misc::xml_reader::Element;
5use fontoxide_misc::xml_writer::XmlWriter;
6
7use crate::table::{DefaultTable, Table, TableType, TableXml};
8use crate::tables::json::{self, DumpOptions, JsonValue};
9use crate::{Error, Font, Result};
10
11/// The JSON text of a `<json>` element: its text chunks joined.
12fn element_text(element: &Element) -> String {
13	element.text()
14}
15
16/// Debug information table (`table_D__e_b_g`), as written by feaLib.
17#[derive(Debug, Clone, PartialEq)]
18pub struct Debg {
19	/// The decoded JSON document (`data`).
20	pub data: JsonValue,
21}
22
23impl Default for Debg {
24	fn default() -> Self {
25		Debg {
26			data: JsonValue::Object(Vec::new()),
27		}
28	}
29}
30
31impl TableType for Debg {
32	const TAG: Tag = Tag::new(b"Debg");
33
34	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
35		let data = json::loads_bytes(data).map_err(|e| Error::value(e.repr))?;
36		Ok(Debg { data })
37	}
38}
39
40impl Table for Debg {
41	fn tag(&self) -> Tag {
42		Self::TAG
43	}
44
45	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
46		Ok(json::dumps(&self.data, &DumpOptions::default()).into_bytes())
47	}
48
49	fn clone_table(&self) -> Box<dyn Table> {
50		Box::new(self.clone())
51	}
52
53	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
54		let _ = f;
55		Ok(())
56	}
57}
58
59impl TableXml for Debg {
60	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
61		// The JSON indentation inside the CDATA block matches the writer's.
62		let indent = " ".repeat(writer.indent_white().chars().count());
63		let data = json::dumps(&self.data, &DumpOptions::indented(&indent));
64		let prefix = writer.indent_white().repeat(writer.indent_level() + 1);
65		// textwrap.indent, except for a first line "{\n", which stays adjacent to
66		// "<![CDATA[{".
67		let mut cdata = String::new();
68		for line in data.split_inclusive('\n') {
69			if line != "{\n" {
70				cdata.push_str(&prefix);
71			}
72			cdata.push_str(line);
73		}
74		writer.begintag("json", &[]);
75		writer.newline();
76		writer.writecdata(&cdata);
77		writer.newline();
78		writer.endtag("json");
79		writer.newline();
80		Ok(())
81	}
82
83	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
84		if element.name == "json" {
85			self.data = json::loads(&element_text(element)).map_err(|e| Error::value(e.repr))?;
86		}
87		Ok(())
88	}
89}
90
91/// Apple Color Emoji background table (`table__b_g_c_l`): a JSON document.
92///
93/// Data that is not valid JSON is kept as is, with the error (`ERROR`), and is
94/// dumped as hex.
95#[derive(Debug, Clone, PartialEq, Default)]
96pub struct Bgcl {
97	/// The raw data (`data`).
98	pub data: Vec<u8>,
99	/// The decoded JSON document (`json`); `None` if decoding failed, in which
100	/// case `data` is compiled as is.
101	pub json: Option<JsonValue>,
102	/// The decoding error (`ERROR`).
103	pub error: Option<String>,
104}
105
106impl TableType for Bgcl {
107	const TAG: Tag = Tag::new(b"bgcl");
108
109	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
110		let mut table = Bgcl {
111			data: data.to_vec(),
112			json: None,
113			error: None,
114		};
115		let parsed = match std::str::from_utf8(data) {
116			Ok(text) => json::loads(text).map_err(|e| e.repr),
117			Err(e) => Err(utf8_error_repr(data, &e)),
118		};
119		match parsed {
120			Ok(value) => {
121				// Setting the convenience attributes is outside the try block.
122				if let Some(msg) = get_error(&value) {
123					return Err(Error::ttlib(format!("AttributeError: {msg}")));
124				}
125				table.json = Some(value);
126			}
127			Err(repr) => table.error = Some(format!("bgcl JSON parse error: {repr}")),
128		}
129		Ok(table)
130	}
131}
132
133/// `repr()` of the `UnicodeDecodeError` of `bytes.decode("utf_8")`.
134fn utf8_error_repr(data: &[u8], e: &std::str::Utf8Error) -> String {
135	let start = e.valid_up_to();
136	let (end, reason) = match e.error_len() {
137		Some(len) => {
138			let first = data[start];
139			let reason = if (0x80..0xC2).contains(&first) || first > 0xF4 {
140				"invalid start byte"
141			} else {
142				"invalid continuation byte"
143			};
144			(start + len, reason)
145		}
146		None => (data.len(), "unexpected end of data"),
147	};
148	format!(
149		"UnicodeDecodeError('utf-8', {}, {start}, {end}, '{reason}')",
150		fontoxide_misc::py::bytes_repr(data)
151	)
152}
153
154/// The `AttributeError` of `value.get(...)` for a document that is not an
155/// object, which fontTools raises when setting the convenience attributes.
156fn get_error(value: &JsonValue) -> Option<String> {
157	let type_name = match value {
158		JsonValue::Object(_) => return None,
159		JsonValue::Null => "NoneType",
160		JsonValue::Bool(_) => "bool",
161		JsonValue::Int(_) => "int",
162		JsonValue::Float(_) => "float",
163		JsonValue::Str(_) => "str",
164		JsonValue::Array(_) => "list",
165	};
166	Some(format!("'{type_name}' object has no attribute 'get'"))
167}
168
169impl Table for Bgcl {
170	fn tag(&self) -> Tag {
171		Self::TAG
172	}
173
174	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
175		match &self.json {
176			None => Ok(self.data.clone()),
177			Some(value) => {
178				let options = DumpOptions {
179					indent: None,
180					separators: (",", ":"),
181					ensure_ascii: false,
182				};
183				Ok(json::dumps(value, &options).into_bytes())
184			}
185		}
186	}
187
188	fn clone_table(&self) -> Box<dyn Table> {
189		Box::new(self.clone())
190	}
191
192	fn decompile_error(&self) -> Option<&str> {
193		self.error.as_deref()
194	}
195
196	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
197		let _ = f;
198		Ok(())
199	}
200}
201
202impl TableXml for Bgcl {
203	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
204		let Some(value) = &self.json else {
205			let raw = DefaultTable {
206				tag: Self::TAG,
207				data: self.data.clone(),
208				error: self.error.clone(),
209			};
210			return raw.to_xml(writer, font);
211		};
212		writer.begintag("json", &[]);
213		writer.newline();
214		let options = DumpOptions {
215			indent: Some("  "),
216			separators: (",", ": "),
217			ensure_ascii: false,
218		};
219		writer.writecdata(&json::dumps(value, &options));
220		writer.newline();
221		writer.endtag("json");
222		writer.newline();
223		Ok(())
224	}
225
226	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
227		if element.name != "json" {
228			// DefaultTable.fromXML: decompiles the hex data.
229			let mut raw = DefaultTable::new(Self::TAG, Vec::new());
230			raw.from_xml(element, font)?;
231			let decompiled = Bgcl::decompile(&raw.data, font)?;
232			self.data = decompiled.data;
233			self.json = decompiled.json;
234			// A previous error stays set, as the attribute does in fontTools.
235			if decompiled.error.is_some() {
236				self.error = decompiled.error;
237			}
238			return Ok(());
239		}
240		let text = element_text(element);
241		let text = fontoxide_misc::py::strip(&text);
242		match json::loads(text) {
243			Ok(value) => {
244				self.data = text.as_bytes().to_vec();
245				match get_error(&value) {
246					None => self.json = Some(value),
247					Some(msg) => {
248						self.json = None;
249						self.error = Some(format!(
250							"bgcl JSON parse error in fromXML: AttributeError({})",
251							fontoxide_misc::py::str_repr(&msg)
252						));
253					}
254				}
255			}
256			Err(e) => {
257				self.json = None;
258				self.error = Some(format!("bgcl JSON parse error in fromXML: {}", e.repr));
259			}
260		}
261		Ok(())
262	}
263}