Skip to main content

fontoxide_ttlib/tables/graphite/
mod.rs

1//! Graphite tables: `Feat` (`F__e_a_t`), `Sill` (`S__i_l_l`), `Gloc`
2//! (`G__l_o_c`), `Glat` (`G__l_a_t`) and `Silf` (`S__i_l_f`), with the helpers of
3//! `grUtils`.
4//!
5//! See <https://graphite.sil.org/graphite_techAbout#graphite-font-tables>.
6//!
7//! fontTools refers to glyphs by name in these tables; here they are glyph IDs.
8//!
9//! # Compression
10//!
11//! `Silf` 5.0 and `Glat` 3.0 may be compressed with LZ4 (scheme 1). fontTools uses
12//! the `lz4` module (LZ4 HC at its highest level); fontoxide uses `lz4_flex`, which
13//! has no HC mode. Both read each other's output, and the decompressed tables are
14//! identical, but the compressed bytes differ, as with brotli in WOFF2.
15//!
16//! # Missing TTX elements
17//!
18//! LENIENT(L49): fontTools leaves the attributes of these tables unset until a TTX
19//! element or the binary sets them, so incomplete TTX fails with `AttributeError`
20//! when compiling or dumping. Here such fields default to zero (or empty).
21
22mod silf;
23
24use std::collections::BTreeMap;
25
26use fontoxide_misc::Tag;
27use fontoxide_misc::fixed_tools::{fixed_to_float, float_to_fixed, float_to_fixed_to_str};
28use fontoxide_misc::text_tools::{Literal, parse_int_radix, safe_eval};
29use fontoxide_misc::xml_reader::Element;
30use fontoxide_misc::xml_writer::XmlWriter;
31
32use crate::binary::{Reader, WriteBytes};
33use crate::table::{Table, TableType, TableXml};
34use crate::{Error, Font, Result};
35
36pub use silf::{Classes, Justify, Pass, Silf, SilfSubtable, assemble, disassemble};
37
38// ---------------------------------------------------------------------------
39// Python helpers
40
41/// Python's index into a sequence of `len` items, clamped as slicing does.
42fn py_index(len: usize, i: i64) -> usize {
43	if i < 0 {
44		(len as i64 + i).max(0) as usize
45	} else {
46		(i as usize).min(len)
47	}
48}
49
50/// `data[start:end]`, with Python's negative indices and clamping.
51pub(crate) fn py_slice<T>(data: &[T], start: i64, end: i64) -> &[T] {
52	let s = py_index(data.len(), start);
53	let e = py_index(data.len(), end);
54	if s >= e { &[] } else { &data[s..e] }
55}
56
57/// `data[start:]`.
58pub(crate) fn py_tail<T>(data: &[T], start: i64) -> &[T] {
59	py_slice(data, start, data.len() as i64)
60}
61
62/// `seq[i]`, with Python's negative indices.
63pub(crate) fn py_get<T>(seq: &[T], i: i64) -> Result<&T> {
64	let j = if i < 0 { seq.len() as i64 + i } else { i };
65	usize::try_from(j)
66		.ok()
67		.and_then(|j| seq.get(j))
68		.ok_or_else(|| Error::ttlib("IndexError: list index out of range"))
69}
70
71fn buffer_error(n: usize) -> Error {
72	Error::Struct(format!("unpack requires a buffer of {n} bytes"))
73}
74
75/// A reader over `data`, which `struct.unpack` requires to be exactly `n` bytes.
76pub(crate) fn exact(data: &[u8], n: usize) -> Result<Reader<'_>> {
77	if data.len() == n {
78		Ok(Reader::new(data))
79	} else {
80		Err(buffer_error(n))
81	}
82}
83
84/// A reader over `data`, which `struct.unpack_from` / `sstruct.unpack2` require
85/// to be at least `n` bytes.
86pub(crate) fn at_least(data: &[u8], n: usize) -> Result<Reader<'_>> {
87	if data.len() >= n {
88		Ok(Reader::new(data))
89	} else {
90		Err(buffer_error(n))
91	}
92}
93
94/// A count for a `struct` format (`"%dH" % n`): negative counts are errors.
95pub(crate) fn count(n: i64) -> Result<usize> {
96	usize::try_from(n).map_err(|_| Error::Struct("bad char in struct format".into()))
97}
98
99/// Packing with the range checks of `struct.pack`.
100pub(crate) trait Pack {
101	/// `B`.
102	fn pack_u8(&mut self, v: i64) -> Result<()>;
103	/// `b`.
104	fn pack_i8(&mut self, v: i64) -> Result<()>;
105	/// `H`.
106	fn pack_u16(&mut self, v: i64) -> Result<()>;
107	/// `h`.
108	fn pack_i16(&mut self, v: i64) -> Result<()>;
109	/// `L`.
110	fn pack_u32(&mut self, v: i64) -> Result<()>;
111	/// `16.16F` of `sstruct`.
112	fn pack_fixed(&mut self, v: f64) -> Result<()>;
113	/// `4s`: encoded, truncated or padded with NUL bytes.
114	fn pack_4s(&mut self, v: &[u8]);
115}
116
117impl Pack for Vec<u8> {
118	fn pack_u8(&mut self, v: i64) -> Result<()> {
119		let v = u8::try_from(v)
120			.map_err(|_| Error::Struct("ubyte format requires 0 <= number <= 255".into()))?;
121		self.put_u8(v);
122		Ok(())
123	}
124
125	fn pack_i8(&mut self, v: i64) -> Result<()> {
126		let v = i8::try_from(v)
127			.map_err(|_| Error::Struct("byte format requires -128 <= number <= 127".into()))?;
128		self.put_i8(v);
129		Ok(())
130	}
131
132	fn pack_u16(&mut self, v: i64) -> Result<()> {
133		let v = u16::try_from(v)
134			.map_err(|_| Error::Struct("'H' format requires 0 <= number <= 65535".into()))?;
135		self.put_u16(v);
136		Ok(())
137	}
138
139	fn pack_i16(&mut self, v: i64) -> Result<()> {
140		let v = i16::try_from(v)
141			.map_err(|_| Error::Struct("short format requires -32768 <= number <= 32767".into()))?;
142		self.put_i16(v);
143		Ok(())
144	}
145
146	fn pack_u32(&mut self, v: i64) -> Result<()> {
147		let v = u32::try_from(v)
148			.map_err(|_| Error::Struct("'L' format requires 0 <= number <= 4294967295".into()))?;
149		self.put_u32(v);
150		Ok(())
151	}
152
153	fn pack_fixed(&mut self, v: f64) -> Result<()> {
154		if !v.is_finite() {
155			return Err(Error::value("cannot convert float to integer"));
156		}
157		let v = i32::try_from(float_to_fixed(v, 16)).map_err(|_| {
158			Error::Struct("'l' format requires -2147483648 <= number <= 2147483647".into())
159		})?;
160		self.put_i32(v);
161		Ok(())
162	}
163
164	fn pack_4s(&mut self, v: &[u8]) {
165		let mut b = [0u8; 4];
166		for (d, s) in b.iter_mut().zip(v) {
167			*d = *s;
168		}
169		self.extend_from_slice(&b);
170	}
171}
172
173/// Reads a `16.16F` field (`fi2fl`).
174pub(crate) fn read_fixed(r: &mut Reader<'_>) -> Result<f64> {
175	Ok(fixed_to_float(r.i32()? as i64, 16))
176}
177
178/// `float(floatToFixedToStr(v, precisionBits=16))`.
179pub(crate) fn round_version(v: f64) -> Result<f64> {
180	float_to_fixed_to_str(v, 16)
181		.parse()
182		.map_err(|_| Error::value("could not convert string to float"))
183}
184
185fn eval_literal(s: &str) -> Result<Literal> {
186	safe_eval(s).ok_or_else(|| Error::value(format!("malformed node or string: {s:?}")))
187}
188
189/// `int(s)` for a string (base 10).
190pub(crate) fn py_int(s: &str) -> Result<i64> {
191	fontoxide_misc::py::parse_int(s)
192		.and_then(|v| i64::try_from(v).ok())
193		.ok_or_else(|| Error::value(format!("invalid literal for int() with base 10: {s:?}")))
194}
195
196/// `int(float(s))`.
197fn float_to_int(f: f64) -> Result<i64> {
198	if f.is_nan() {
199		return Err(Error::value("cannot convert float NaN to integer"));
200	}
201	if f.is_infinite() || f.abs() >= 9.2e18 {
202		return Err(Error::value("cannot convert float infinity to integer"));
203	}
204	Ok(f.trunc() as i64)
205}
206
207/// `int(safeEval(s))`.
208pub(crate) fn eval_int(s: &str) -> Result<i64> {
209	match eval_literal(s)? {
210		Literal::Int(i) => {
211			i64::try_from(i).map_err(|_| Error::value(format!("integer out of range: {s}")))
212		}
213		Literal::Bool(b) => Ok(b as i64),
214		Literal::Float(f) => float_to_int(f),
215		Literal::Str(t) => py_int(&t),
216		_ => Err(Error::value(format!(
217			"int() argument must be a number: {s:?}"
218		))),
219	}
220}
221
222/// `float(safeEval(s))`.
223pub(crate) fn eval_float(s: &str) -> Result<f64> {
224	match eval_literal(s)? {
225		Literal::Str(t) => fontoxide_misc::py::parse_float(&t)
226			.ok_or_else(|| Error::value(format!("could not convert string to float: {t:?}"))),
227		lit => lit
228			.as_float()
229			.ok_or_else(|| Error::value(format!("float() argument must be a number: {s:?}"))),
230	}
231}
232
233/// An attribute that fontTools reads with `attrs[name]`.
234pub(crate) fn attr<'a>(e: &'a Element, name: &str) -> Result<&'a str> {
235	e.attr(name)
236		.ok_or_else(|| Error::ttx(format!("KeyError: {name:?}")))
237}
238
239/// `content_string`: the text of an element, stripped.
240pub(crate) fn content_string(e: &Element) -> String {
241	fontoxide_misc::py::strip(&e.text()).to_owned()
242}
243
244/// Python's `str.split()`.
245pub(crate) fn py_split(s: &str) -> impl Iterator<Item = &str> {
246	s.split(fontoxide_misc::py::is_space)
247		.filter(|w| !w.is_empty())
248}
249
250// ---------------------------------------------------------------------------
251// grUtils
252
253/// `grUtils.decompress`: the table data, decompressed if it is compressed, and
254/// the compression scheme.
255///
256/// Without the `graphite` feature (fontTools without the lz4 module), LZ4 data
257/// is kept compressed, with a warning, as the other unknown schemes.
258pub fn decompress(data: &[u8]) -> Result<(Vec<u8>, i64)> {
259	let compression = exact(py_slice(data, 4, 8), 4)?.u32()?;
260	let scheme = compression >> 27;
261	#[cfg(feature = "graphite")]
262	let size = (compression & 0x07FF_FFFF) as usize;
263	match scheme {
264		0 => Ok((data.to_vec(), 0)),
265		#[cfg(feature = "graphite")]
266		1 => {
267			let res = lz4_flex::block::decompress(&data[8..], size).map_err(|e| {
268				Error::ttlib(format!(
269					"LZ4BlockError: Decompression failed: corrupt input or insufficient space in destination buffer ({e})"
270				))
271			})?;
272			if res.len() != size {
273				return Err(Error::ttlib(format!(
274					"LZ4BlockError: Decompressor wrote {} bytes, but {size} bytes expected from header",
275					res.len()
276				)));
277			}
278			Ok((res, 1))
279		}
280		_ => {
281			log::warn!("Table is compressed with an unsupported compression scheme");
282			Ok((data.to_vec(), scheme as i64))
283		}
284	}
285}
286
287/// `grUtils.compress`.
288///
289/// Scheme 1 compresses with `lz4_flex`, whose output differs from that of LZ4 HC
290/// (see the [module documentation](self)). Without the `graphite` feature
291/// (fontTools without the lz4 module), the data is left uncompressed, with a
292/// warning, as for the other unknown schemes.
293pub fn compress(scheme: i64, data: &[u8]) -> Result<Vec<u8>> {
294	let field = scheme
295		.checked_mul(1 << 27)
296		.and_then(|v| v.checked_add(data.len() as i64 & 0x07FF_FFFF))
297		.unwrap_or(-1);
298	let mut hdr = py_slice(data, 0, 4).to_vec();
299	hdr.pack_u32(field)?;
300	match scheme {
301		0 => Ok(data.to_vec()),
302		#[cfg(feature = "graphite")]
303		1 => {
304			hdr.extend(lz4_flex::block::compress(data));
305			Ok(hdr)
306		}
307		_ => {
308			log::warn!("Table failed to compress by unsupported compression scheme");
309			Ok(data.to_vec())
310		}
311	}
312}
313
314/// `grUtils.entries`: runs of consecutive keys (and, with `same_value`, equal
315/// values), as `(first key, count, values)`. As in fontTools, the last run is
316/// always yielded, even if empty.
317pub fn entries(attributes: &BTreeMap<i64, i64>, same_value: bool) -> Vec<(i64, usize, Vec<i64>)> {
318	let mut out = Vec::new();
319	let mut ak = 0;
320	let mut vals: Vec<i64> = Vec::new();
321	let mut lastv = 0;
322	for (&k, &v) in attributes {
323		if !vals.is_empty() && (k != ak + 1 || (same_value && v != lastv)) {
324			out.push((
325				ak - vals.len() as i64 + 1,
326				vals.len(),
327				std::mem::take(&mut vals),
328			));
329		}
330		ak = k;
331		vals.push(v);
332		lastv = v;
333	}
334	out.push((ak - vals.len() as i64 + 1, vals.len(), vals));
335	out
336}
337
338/// `grUtils.bininfo`: the binary search header of `num` items of `size` bytes.
339pub fn bininfo(num: i64, size: i64) -> Result<Vec<u8>> {
340	let mut out = Vec::with_capacity(8);
341	if num == 0 {
342		out.extend_from_slice(&[0; 8]);
343		return Ok(out);
344	}
345	let mut srange: i64 = 1;
346	let mut select: i64 = 0;
347	while srange <= num {
348		srange *= 2;
349		select += 1;
350	}
351	select -= 1;
352	srange /= 2;
353	srange *= size;
354	let shift = num * size - srange;
355	for v in [num, srange, select, shift] {
356		out.pack_u16(v)?;
357	}
358	Ok(out)
359}
360
361/// `grUtils.num2tag`: small numbers as decimal, others as tags.
362pub fn num2tag(n: u32) -> Result<String> {
363	if n < 0x20_0000 {
364		Ok(n.to_string())
365	} else {
366		let bytes: Vec<u8> = n.to_be_bytes().into_iter().filter(|&b| b != 0).collect();
367		String::from_utf8(bytes).map_err(|_| Error::value("UnicodeDecodeError: invalid utf-8"))
368	}
369}
370
371/// `grUtils.tag2num`: the inverse of [`num2tag`].
372pub fn tag2num(n: &str) -> Result<i64> {
373	if let Ok(v) = py_int(n) {
374		return Ok(v);
375	}
376	let chars: Vec<char> = n.chars().chain("    ".chars()).take(4).collect();
377	let mut v: i64 = 0;
378	for c in chars {
379		if !c.is_ascii() {
380			return Err(Error::value(
381				"UnicodeEncodeError: 'ascii' codec can't encode character",
382			));
383		}
384		v = v << 8 | c as i64;
385	}
386	Ok(v)
387}
388
389fn version_from_header(data: &[u8]) -> Result<f64> {
390	read_fixed(&mut at_least(data, 4)?)
391}
392
393fn name_id(label: i64) -> Option<u16> {
394	u16::try_from(label).ok()
395}
396
397/// Inserts into an insertion-ordered dict (`d[k] = v`).
398pub(crate) fn dict_set<K: PartialEq, V>(d: &mut Vec<(K, V)>, k: K, v: V) {
399	match d.iter_mut().find(|(key, _)| *key == k) {
400		Some(slot) => slot.1 = v,
401		None => d.push((k, v)),
402	}
403}
404
405// ---------------------------------------------------------------------------
406// Feat
407
408/// A Graphite feature (`Feature`).
409#[derive(Debug, Clone, PartialEq, Default)]
410pub struct Feature {
411	/// `flags`.
412	pub flags: i64,
413	/// The name ID of the feature (`label`).
414	pub label: i64,
415	/// The name ID of each setting (`settings`).
416	pub settings: BTreeMap<i64, i64>,
417	/// The default setting (`default`); `None` when read from a feature without
418	/// settings.
419	pub default: Option<i64>,
420	/// The position of the feature (`index`).
421	pub index: i64,
422}
423
424/// Graphite Feature table (`table_F__e_a_t`); not to be confused with the AAT
425/// `feat` table.
426#[derive(Debug, Clone, PartialEq, Default)]
427pub struct Feat {
428	/// The table version (`version`).
429	pub version: f64,
430	/// The features by ID (`num2tag`), in insertion order (`features`).
431	pub features: Vec<(String, Feature)>,
432}
433
434impl TableType for Feat {
435	const TAG: Tag = Tag::new(b"Feat");
436
437	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
438		let version = round_version(version_from_header(data)?)?;
439		let data = py_tail(data, 4);
440		let num_feats = exact(py_slice(data, 0, 2), 2)?.u16()? as i64;
441		let data = py_tail(data, 8);
442		let mut allfeats = Vec::new();
443		let mut maxsetting = 0;
444		for i in 0..num_feats {
445			let (fid, nums, offset, flags, lid) = if version >= 2.0 {
446				let mut r = exact(py_slice(data, 16 * i, 16 * (i + 1)), 16)?;
447				let fid = r.u32()?;
448				let nums = r.u16()? as i64;
449				r.u16()?;
450				let offset = r.u32()? as i64;
451				(
452					fid,
453					nums,
454					(offset - 12 - 16 * num_feats) / 4,
455					r.u16()?,
456					r.u16()?,
457				)
458			} else {
459				let mut r = exact(py_slice(data, 12 * i, 12 * (i + 1)), 12)?;
460				let fid = r.u16()? as u32;
461				let nums = r.u16()? as i64;
462				let offset = r.u32()? as i64;
463				(
464					fid,
465					nums,
466					(offset - 12 - 12 * num_feats) / 4,
467					r.u16()?,
468					r.u16()?,
469				)
470			};
471			allfeats.push((fid, nums, offset, flags, lid));
472			maxsetting = i64::max(maxsetting, offset + nums);
473		}
474		// UPSTREAM-BUG(B68): the settings are taken to start after 16-byte feature
475		// records even in version 1, whose records are 12 bytes.
476		let data = py_tail(data, 16 * num_feats);
477		let mut allsettings = Vec::new();
478		for i in 0..maxsetting {
479			if data.len() as i64 >= 4 * (i + 1) {
480				let mut r = Reader::new(py_slice(data, 4 * i, 4 * (i + 1)));
481				allsettings.push((r.u16()? as i64, r.u16()? as i64));
482			}
483		}
484		let mut feat = Feat {
485			version,
486			features: Vec::new(),
487		};
488		for (i, &(fid, nums, offset, flags, lid)) in allfeats.iter().enumerate() {
489			let mut f = Feature {
490				flags: flags as i64,
491				label: lid as i64,
492				settings: BTreeMap::new(),
493				default: None,
494				index: i as i64,
495			};
496			for j in offset..offset + nums {
497				if j >= allsettings.len() as i64 {
498					continue;
499				}
500				let &(vid, vlid) = py_get(&allsettings, j)?;
501				f.settings.insert(vid, vlid);
502				if f.default.is_none() {
503					f.default = Some(vid);
504				}
505			}
506			dict_set(&mut feat.features, num2tag(fid)?, f);
507		}
508		Ok(feat)
509	}
510}
511
512impl Table for Feat {
513	fn tag(&self) -> Tag {
514		Self::TAG
515	}
516
517	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
518		let mut order: Vec<usize> = (0..self.features.len()).collect();
519		order.sort_by_key(|&i| self.features[i].1.index);
520		'restart: loop {
521			let mut fdat = Vec::new();
522			let mut vdat = Vec::new();
523			let mut offset: i64 = 0;
524			let n = self.features.len() as i64;
525			for &i in &order {
526				let (f, v) = &self.features[i];
527				let fnum = tag2num(f)?;
528				let num_settings = v.settings.len() as i64;
529				if self.version >= 2.0 {
530					fdat.pack_u32(fnum)?;
531					fdat.pack_u16(num_settings)?;
532					fdat.pack_u16(0)?;
533					fdat.pack_u32(offset * 4 + 12 + 16 * n)?;
534				} else if fnum > 65535 {
535					// Self healing for alphabetic IDs.
536					self.version = 2.0;
537					continue 'restart;
538				} else {
539					fdat.pack_u16(fnum)?;
540					fdat.pack_u16(num_settings)?;
541					fdat.pack_u32(offset * 4 + 12 + 12 * n)?;
542				}
543				fdat.pack_u16(v.flags)?;
544				fdat.pack_u16(v.label)?;
545				let mut settings: Vec<(i64, i64)> =
546					v.settings.iter().map(|(&s, &l)| (s, l)).collect();
547				settings.sort_by_key(|&(s, l)| {
548					if Some(s) == v.default {
549						(-1, l)
550					} else {
551						(s, l)
552					}
553				});
554				for (s, l) in settings {
555					vdat.pack_u16(s)?;
556					vdat.pack_u16(l)?;
557				}
558				offset += num_settings;
559			}
560			let mut out = Vec::new();
561			out.pack_fixed(self.version)?;
562			out.pack_u16(n)?;
563			out.pack_u16(0)?;
564			out.pack_u32(0)?;
565			out.extend(fdat);
566			out.extend(vdat);
567			return Ok(out);
568		}
569	}
570
571	fn clone_table(&self) -> Box<dyn Table> {
572		Box::new(self.clone())
573	}
574
575	fn remap_glyphs(&mut self, _f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
576		Ok(())
577	}
578}
579
580impl TableXml for Feat {
581	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
582		writer.simpletag("version", &[("version", &self.version)]);
583		writer.newline();
584		let has_name = font.contains(Tag::new(b"name"));
585		let debug_name = |font: &mut Font, label: i64| -> Result<Option<String>> {
586			if !has_name {
587				return Ok(None);
588			}
589			let name = font.require::<crate::tables::Name>()?;
590			Ok(name_id(label).and_then(|id| name.get_debug_name(id)))
591		};
592		let mut features: Vec<&(String, Feature)> = self.features.iter().collect();
593		features.sort_by_key(|(_, v)| v.index);
594		for (f, v) in features {
595			if let Some(name) = debug_name(font, v.label)? {
596				writer.newline();
597				writer.comment(&name);
598				writer.newline();
599			}
600			writer.begintag(
601				"feature",
602				&[
603					("fid", f),
604					("label", &v.label),
605					("flags", &v.flags),
606					("default", &v.default.filter(|&d| d != 0).unwrap_or(0)),
607				],
608			);
609			writer.newline();
610			for (s, l) in &v.settings {
611				writer.simpletag("setting", &[("value", s), ("label", l)]);
612				if let Some(name) = debug_name(font, *l)? {
613					writer.write("  ");
614					writer.comment(&name);
615				}
616				writer.newline();
617			}
618			writer.endtag("feature");
619			writer.newline();
620		}
621		Ok(())
622	}
623
624	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
625		match element.name.as_str() {
626			"version" => self.version = eval_float(attr(element, "version")?)?,
627			"feature" => {
628				let fid = attr(element, "fid")?.to_owned();
629				let mut f = Feature {
630					flags: eval_int(attr(element, "flags")?)?,
631					label: eval_int(attr(element, "label")?)?,
632					default: Some(eval_int(element.attr("default").unwrap_or("0"))?),
633					index: self.features.len() as i64,
634					settings: BTreeMap::new(),
635				};
636				for e in element.elements() {
637					if e.name == "setting" {
638						f.settings
639							.insert(eval_int(attr(e, "value")?)?, eval_int(attr(e, "label")?)?);
640					}
641				}
642				dict_set(&mut self.features, fid, f);
643			}
644			_ => {}
645		}
646		Ok(())
647	}
648}
649
650// ---------------------------------------------------------------------------
651// Sill
652
653/// Graphite Languages table (`table_S__i_l_l`).
654#[derive(Debug, Clone, PartialEq, Default)]
655pub struct Sill {
656	/// The table version (`version`).
657	pub version: f64,
658	/// The `(feature ID, value)` settings of each language (`langs`).
659	pub langs: BTreeMap<String, Vec<(i64, i64)>>,
660}
661
662impl TableType for Sill {
663	const TAG: Tag = Tag::new(b"Sill");
664
665	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
666		let version = round_version(version_from_header(data)?)?;
667		let data = py_tail(data, 4);
668		let num_langs = exact(py_slice(data, 0, 2), 2)?.u16()? as i64;
669		let data = py_tail(data, 8);
670		let mut maxsetting = 0;
671		let mut langinfo = Vec::new();
672		for i in 0..num_langs {
673			let mut r = exact(py_slice(data, i * 8, (i + 1) * 8), 8)?;
674			let code: Vec<u8> = r.bytes(4)?.iter().copied().filter(|&b| b != 0).collect();
675			let num_settings = r.u16()? as i64;
676			let offset = r.u16()? as i64 / 8 - (num_langs + 1);
677			let code = String::from_utf8(code)
678				.map_err(|_| Error::value("UnicodeDecodeError: invalid utf-8"))?;
679			langinfo.push((code, num_settings, offset));
680			maxsetting = i64::max(maxsetting, offset + num_settings);
681		}
682		let data = py_tail(data, num_langs * 8);
683		let mut finfo = Vec::new();
684		for i in 0..maxsetting {
685			let mut r = exact(py_slice(data, i * 8, (i + 1) * 8), 8)?;
686			let fid = r.u32()? as i64;
687			finfo.push((fid, r.u16()? as i64));
688		}
689		let mut langs = BTreeMap::new();
690		for (c, n, o) in langinfo {
691			let mut settings = Vec::new();
692			for i in o..o + n {
693				settings.push(*py_get(&finfo, i)?);
694			}
695			langs.insert(c, settings);
696		}
697		Ok(Sill { version, langs })
698	}
699}
700
701impl Table for Sill {
702	fn tag(&self) -> Tag {
703		Self::TAG
704	}
705
706	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
707		let mut ldat = Vec::new();
708		let mut fdat = Vec::new();
709		let mut offset = self.langs.len() as i64;
710		for (c, inf) in &self.langs {
711			ldat.pack_4s(c.as_bytes());
712			ldat.pack_u16(inf.len() as i64)?;
713			ldat.pack_u16(8 * offset + 20)?;
714			for &(fid, val) in inf {
715				fdat.pack_u32(fid)?;
716				fdat.pack_u16(val)?;
717				fdat.pack_u16(0)?;
718			}
719			offset += inf.len() as i64;
720		}
721		ldat.pack_u32(0x8080_8080)?;
722		ldat.pack_u16(0)?;
723		ldat.pack_u16(8 * offset + 20)?;
724		let mut out = Vec::new();
725		out.pack_fixed(self.version)?;
726		out.extend(bininfo(self.langs.len() as i64, 1)?);
727		out.extend(ldat);
728		out.extend(fdat);
729		Ok(out)
730	}
731
732	fn clone_table(&self) -> Box<dyn Table> {
733		Box::new(self.clone())
734	}
735
736	fn remap_glyphs(&mut self, _f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
737		Ok(())
738	}
739}
740
741impl TableXml for Sill {
742	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
743		writer.simpletag("version", &[("version", &self.version)]);
744		writer.newline();
745		for (c, inf) in &self.langs {
746			writer.begintag("lang", &[("name", c)]);
747			writer.newline();
748			for &(fid, val) in inf {
749				let fid = u32::try_from(fid)
750					.map_err(|_| Error::Struct("argument out of range".into()))?;
751				writer.simpletag("feature", &[("fid", &num2tag(fid)?), ("val", &val)]);
752				writer.newline();
753			}
754			writer.endtag("lang");
755			writer.newline();
756		}
757		Ok(())
758	}
759
760	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
761		match element.name.as_str() {
762			"version" => self.version = eval_float(attr(element, "version")?)?,
763			"lang" => {
764				let c = attr(element, "name")?.to_owned();
765				let mut settings = Vec::new();
766				for e in element.elements() {
767					if e.name == "feature" {
768						settings.push((tag2num(attr(e, "fid")?)?, eval_int(attr(e, "val")?)?));
769					}
770				}
771				self.langs.insert(c, settings);
772			}
773			_ => {}
774		}
775		Ok(())
776	}
777}
778
779// ---------------------------------------------------------------------------
780// Gloc
781
782/// Graphite Index to Glyph Attributes table (`table_G__l_o_c`).
783#[derive(Debug, Clone, PartialEq, Default)]
784pub struct Gloc {
785	/// The version read from the binary; 1.0 is always written.
786	pub version: f64,
787	/// The number of attributes (`numAttribs`).
788	pub num_attribs: i64,
789	/// The offset of each glyph's attributes in `Glat`, and the end
790	/// (`locations`); set when `Glat` is compiled.
791	pub locations: Option<Vec<u32>>,
792	/// Whether the locations are 32-bit (the `I` type code of `locations`).
793	pub long_format: bool,
794	/// The attribute IDs (`attribIds`), if any.
795	pub attrib_ids: Option<Vec<u16>>,
796}
797
798impl Gloc {
799	/// Sets the locations, choosing their size (`set`).
800	pub fn set(&mut self, locations: Vec<u32>) {
801		self.long_format = locations.iter().max().is_some_and(|&m| m >= 65536);
802		self.locations = Some(locations);
803	}
804
805	/// The locations (`iter(gloc)`).
806	pub fn locations(&self) -> Result<&[u32]> {
807		self.locations.as_deref().ok_or_else(|| {
808			Error::ttlib("AttributeError: 'table_G__l_o_c' object has no attribute 'locations'")
809		})
810	}
811}
812
813fn from_bytes_error() -> Error {
814	Error::value("bytes length not a multiple of item size")
815}
816
817impl TableType for Gloc {
818	const TAG: Tag = Tag::new(b"Gloc");
819
820	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
821		let mut r = at_least(data, 8)?;
822		let version = read_fixed(&mut r)?;
823		let flags = r.u16()? as i64;
824		let num_attribs = r.u16()? as i64;
825		let data = r.rest();
826		let long_format = flags & 1 != 0;
827		let loc = py_slice(data, 0, data.len() as i64 - num_attribs * (flags & 2));
828		let size = if long_format { 4 } else { 2 };
829		if loc.len() % size != 0 {
830			return Err(from_bytes_error());
831		}
832		let mut lr = Reader::new(loc);
833		let locations = if long_format {
834			lr.u32_array(loc.len() / 4)?
835		} else {
836			lr.u16_array(loc.len() / 2)?
837				.into_iter()
838				.map(u32::from)
839				.collect()
840		};
841		let mut attrib_ids = Vec::new();
842		if flags & 2 != 0 {
843			let ids = py_tail(data, -num_attribs * 2);
844			if ids.len() % 2 != 0 {
845				return Err(from_bytes_error());
846			}
847			attrib_ids = Reader::new(ids).u16_array(ids.len() / 2)?;
848		}
849		Ok(Gloc {
850			version,
851			num_attribs,
852			locations: Some(locations),
853			long_format,
854			attrib_ids: Some(attrib_ids),
855		})
856	}
857}
858
859impl Table for Gloc {
860	fn tag(&self) -> Tag {
861		Self::TAG
862	}
863
864	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
865		let ids = self.attrib_ids.as_deref().filter(|ids| !ids.is_empty());
866		let locations = self.locations()?;
867		let mut data = Vec::new();
868		data.pack_fixed(1.0)?;
869		data.pack_u16(((ids.is_some() as i64) << 1) + self.long_format as i64)?;
870		data.pack_u16(self.num_attribs)?;
871		for &l in locations {
872			if self.long_format {
873				data.put_u32(l);
874			} else {
875				data.pack_u16(l as i64)?;
876			}
877		}
878		for &id in ids.unwrap_or_default() {
879			data.put_u16(id);
880		}
881		Ok(data)
882	}
883
884	fn clone_table(&self) -> Box<dyn Table> {
885		Box::new(self.clone())
886	}
887
888	fn remap_glyphs(&mut self, _f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
889		Ok(())
890	}
891}
892
893impl TableXml for Gloc {
894	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
895		writer.simpletag("attributes", &[("number", &self.num_attribs)]);
896		writer.newline();
897		Ok(())
898	}
899
900	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
901		if element.name == "attributes" {
902			self.num_attribs = eval_int(attr(element, "number")?)?;
903		}
904		Ok(())
905	}
906}
907
908// ---------------------------------------------------------------------------
909// Glat
910
911/// One of the subboxes of an [`Octabox`] (`Glat_format_3_subbox_entry`); values
912/// are in 255ths of the glyph's bounding box.
913#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
914pub struct Subbox {
915	/// `left`.
916	pub left: i64,
917	/// `right`.
918	pub right: i64,
919	/// `bottom`.
920	pub bottom: i64,
921	/// `top`.
922	pub top: i64,
923	/// `diagNegMin`.
924	pub diag_neg_min: i64,
925	/// `diagNegMax`.
926	pub diag_neg_max: i64,
927	/// `diagPosMin`.
928	pub diag_pos_min: i64,
929	/// `diagPosMax`.
930	pub diag_pos_max: i64,
931}
932
933impl Subbox {
934	const NAMES: [&'static str; 8] = [
935		"left",
936		"right",
937		"bottom",
938		"top",
939		"diagNegMin",
940		"diagNegMax",
941		"diagPosMin",
942		"diagPosMax",
943	];
944
945	fn fields_mut(&mut self) -> [&mut i64; 8] {
946		[
947			&mut self.left,
948			&mut self.right,
949			&mut self.bottom,
950			&mut self.top,
951			&mut self.diag_neg_min,
952			&mut self.diag_neg_max,
953			&mut self.diag_pos_min,
954			&mut self.diag_pos_max,
955		]
956	}
957
958	fn fields(&self) -> [i64; 8] {
959		[
960			self.left,
961			self.right,
962			self.bottom,
963			self.top,
964			self.diag_neg_min,
965			self.diag_neg_max,
966			self.diag_pos_min,
967			self.diag_pos_max,
968		]
969	}
970}
971
972/// The collision octabox of a glyph (`Glat_format_3_octabox_metrics`).
973#[derive(Debug, Clone, PartialEq, Eq, Default)]
974pub struct Octabox {
975	/// Which subboxes exist on a 4×4 grid (`subboxBitmap`).
976	pub subbox_bitmap: i64,
977	/// `diagNegMin`.
978	pub diag_neg_min: i64,
979	/// `diagNegMax`.
980	pub diag_neg_max: i64,
981	/// `diagPosMin`.
982	pub diag_pos_min: i64,
983	/// `diagPosMax`.
984	pub diag_pos_max: i64,
985	/// The subboxes (`subboxes`).
986	pub subboxes: Vec<Subbox>,
987}
988
989impl Octabox {
990	const NAMES: [&'static str; 4] = ["diagNegMin", "diagNegMax", "diagPosMin", "diagPosMax"];
991
992	fn diag_mut(&mut self) -> [&mut i64; 4] {
993		[
994			&mut self.diag_neg_min,
995			&mut self.diag_neg_max,
996			&mut self.diag_pos_min,
997			&mut self.diag_pos_max,
998		]
999	}
1000
1001	fn diag(&self) -> [i64; 4] {
1002		[
1003			self.diag_neg_min,
1004			self.diag_neg_max,
1005			self.diag_pos_min,
1006			self.diag_pos_max,
1007		]
1008	}
1009
1010	fn num_subboxes(&self) -> usize {
1011		// `bin(n).count("1")`, which counts the magnitude's bits.
1012		self.subbox_bitmap.unsigned_abs().count_ones() as usize
1013	}
1014}
1015
1016/// The attributes of a glyph (`_Dict`).
1017#[derive(Debug, Clone, PartialEq, Default)]
1018pub struct GlatAttributes {
1019	/// The attribute values by attribute number.
1020	pub values: BTreeMap<i64, i64>,
1021	/// The octabox (`octabox`), in version 3 tables with octaboxes.
1022	pub octabox: Option<Octabox>,
1023}
1024
1025/// Graphite Glyph Attributes table (`table_G__l_a_t`).
1026///
1027/// Compiling it also sets the locations of `Gloc`.
1028#[derive(Debug, Clone, PartialEq, Default)]
1029pub struct Glat {
1030	/// The table version (`version`).
1031	pub version: f64,
1032	/// The compression scheme (`scheme`).
1033	pub scheme: i64,
1034	/// The compression field of version 3 (`compression`).
1035	pub compression: i64,
1036	/// Whether the glyphs have octaboxes (`hasOctaboxes`); unset until read
1037	/// from a version 3 table or from TTX with octaboxes.
1038	pub has_octaboxes: Option<bool>,
1039	/// The attributes of each glyph (`attributes`).
1040	pub attributes: BTreeMap<u32, GlatAttributes>,
1041}
1042
1043/// Which entry format the attributes use.
1044#[derive(Clone, Copy, PartialEq)]
1045enum EntryFormat {
1046	/// `Glat_format_1_entry`: bytes.
1047	Bytes,
1048	/// `Glat_format_23_entry`: shorts.
1049	Shorts,
1050}
1051
1052impl EntryFormat {
1053	fn size(self) -> usize {
1054		match self {
1055			EntryFormat::Bytes => 2,
1056			EntryFormat::Shorts => 4,
1057		}
1058	}
1059}
1060
1061/// `decompileAttributes12`.
1062fn decompile_attributes12(mut data: &[u8], fmt: EntryFormat) -> Result<BTreeMap<i64, i64>> {
1063	let mut attributes = BTreeMap::new();
1064	while data.len() > 3 {
1065		let mut r = at_least(data, fmt.size())?;
1066		let (att_num, num) = match fmt {
1067			EntryFormat::Bytes => (r.u8()? as i64, r.u8()? as usize),
1068			EntryFormat::Shorts => (r.u16()? as i64, r.u16()? as usize),
1069		};
1070		data = r.rest();
1071		if data.len() >= 2 * num {
1072			let vals = Reader::new(data).i16_array(num)?;
1073			for (k, v) in (att_num..).zip(vals) {
1074				attributes.insert(k, v as i64);
1075			}
1076			data = &data[2 * num..];
1077		}
1078	}
1079	Ok(attributes)
1080}
1081
1082impl Glat {
1083	fn has_octaboxes(&self) -> Result<bool> {
1084		self.has_octaboxes.ok_or_else(|| {
1085			Error::ttlib("AttributeError: 'table_G__l_a_t' object has no attribute 'hasOctaboxes'")
1086		})
1087	}
1088
1089	/// `decompileAttributes3`.
1090	fn decompile_attributes3(&self, mut data: &[u8]) -> Result<GlatAttributes> {
1091		let mut octabox = None;
1092		if self.has_octaboxes()? {
1093			let mut r = at_least(data, 6)?;
1094			let mut o = Octabox {
1095				subbox_bitmap: r.u16()? as i64,
1096				..Default::default()
1097			};
1098			for f in o.diag_mut() {
1099				*f = r.u8()? as i64;
1100			}
1101			data = r.rest();
1102			for _ in 0..o.num_subboxes() {
1103				if data.len() >= 8 {
1104					let mut s = Subbox::default();
1105					for (f, &b) in s.fields_mut().into_iter().zip(&data[..8]) {
1106						*f = b as i64;
1107					}
1108					o.subboxes.push(s);
1109					data = &data[8..];
1110				}
1111			}
1112			octabox = Some(o);
1113		}
1114		Ok(GlatAttributes {
1115			values: decompile_attributes12(data, EntryFormat::Shorts)?,
1116			octabox,
1117		})
1118	}
1119
1120	/// `compileAttributes12`.
1121	fn compile_attributes12(attrs: &BTreeMap<i64, i64>, fmt: EntryFormat) -> Result<Vec<u8>> {
1122		let mut data = Vec::new();
1123		for (att_num, num, vals) in entries(attrs, false) {
1124			match fmt {
1125				EntryFormat::Bytes => {
1126					data.pack_u8(att_num)?;
1127					data.pack_u8(num as i64)?;
1128				}
1129				EntryFormat::Shorts => {
1130					data.pack_u16(att_num)?;
1131					data.pack_u16(num as i64)?;
1132				}
1133			}
1134			for v in vals {
1135				data.pack_i16(v)?;
1136			}
1137		}
1138		Ok(data)
1139	}
1140
1141	/// `compileAttributes3`.
1142	fn compile_attributes3(&self, attrs: &GlatAttributes) -> Result<Vec<u8>> {
1143		let mut data = Vec::new();
1144		if self.has_octaboxes()? {
1145			let o = attrs.octabox.as_ref().ok_or_else(|| {
1146				Error::ttlib("AttributeError: '_Dict' object has no attribute 'octabox'")
1147			})?;
1148			data.pack_u16(o.subbox_bitmap)?;
1149			for v in o.diag() {
1150				data.pack_u8(v)?;
1151			}
1152			for b in 0..o.num_subboxes() {
1153				let s = o
1154					.subboxes
1155					.get(b)
1156					.ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?;
1157				for v in s.fields() {
1158					data.pack_u8(v)?;
1159				}
1160			}
1161		}
1162		// LENIENT(L49), UPSTREAM-BUG(B81): without octaboxes, fontTools starts
1163		// from a `str` and fails to add the bytes to it, so it cannot compile
1164		// version 3 tables without octaboxes.
1165		data.extend(Self::compile_attributes12(
1166			&attrs.values,
1167			EntryFormat::Shorts,
1168		)?);
1169		Ok(data)
1170	}
1171}
1172
1173fn unbound_decoder() -> Error {
1174	Error::ttlib("UnboundLocalError: cannot access local variable 'decoder'")
1175}
1176
1177impl TableType for Glat {
1178	const TAG: Tag = Tag::new(b"Glat");
1179
1180	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
1181		let mut glat = Glat {
1182			version: round_version(version_from_header(data)?)?,
1183			..Default::default()
1184		};
1185		let mut data = data.to_vec();
1186		let fmt = if glat.version <= 1.9 {
1187			Some(EntryFormat::Bytes)
1188		} else if glat.version <= 2.9 {
1189			Some(EntryFormat::Shorts)
1190		} else if glat.version >= 3.0 {
1191			let (d, scheme) = decompress(&data)?;
1192			data = d;
1193			glat.scheme = scheme;
1194			let mut r = at_least(&data, 8)?;
1195			glat.version = read_fixed(&mut r)?;
1196			glat.compression = r.u32()? as i64;
1197			glat.has_octaboxes = Some(glat.compression & 1 == 1);
1198			None
1199		} else {
1200			return Err(unbound_decoder());
1201		};
1202		let gloc = font.require::<Gloc>()?.locations()?.to_vec();
1203		for (count, w) in gloc.windows(2).enumerate() {
1204			let chunk = py_slice(&data, w[0] as i64, w[1] as i64);
1205			let attrs = match fmt {
1206				Some(fmt) => GlatAttributes {
1207					values: decompile_attributes12(chunk, fmt)?,
1208					octabox: None,
1209				},
1210				None => glat.decompile_attributes3(chunk)?,
1211			};
1212			glat.attributes.insert(count as u32, attrs);
1213		}
1214		Ok(glat)
1215	}
1216}
1217
1218impl Table for Glat {
1219	fn tag(&self) -> Tag {
1220		Self::TAG
1221	}
1222
1223	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
1224		let mut data = Vec::new();
1225		data.pack_fixed(self.version)?;
1226		let fmt = if self.version <= 1.9 {
1227			Some(EntryFormat::Bytes)
1228		} else if self.version <= 2.9 {
1229			// UPSTREAM-BUG(B69): version 2 is written with the byte entries of version 1,
1230			// but read with the short entries.
1231			Some(EntryFormat::Bytes)
1232		} else if self.version >= 3.0 {
1233			let octaboxes = self.has_octaboxes()? as i64;
1234			self.compression = self
1235				.scheme
1236				.checked_mul(1 << 27)
1237				.and_then(|v| v.checked_add(octaboxes))
1238				.unwrap_or(-1);
1239			data.clear();
1240			data.pack_fixed(self.version)?;
1241			data.pack_u32(self.compression)?;
1242			None
1243		} else {
1244			return Err(unbound_decoder());
1245		};
1246		let mut glocs = Vec::with_capacity(self.attributes.len() + 1);
1247		let location = |len: usize| {
1248			u32::try_from(len)
1249				.map_err(|_| Error::ttlib("OverflowError: unsigned int is greater than maximum"))
1250		};
1251		for n in 0..self.attributes.len() as u32 {
1252			glocs.push(location(data.len())?);
1253			let attrs = self
1254				.attributes
1255				.get(&n)
1256				.ok_or_else(|| Error::ttlib(format!("KeyError: glyph {n}")))?;
1257			data.extend(match fmt {
1258				Some(fmt) => Self::compile_attributes12(&attrs.values, fmt)?,
1259				None => self.compile_attributes3(attrs)?,
1260			});
1261		}
1262		glocs.push(location(data.len())?);
1263		font.require::<Gloc>()?.set(glocs);
1264		if self.version >= 3.0 {
1265			data = compress(self.scheme, &data)?;
1266		}
1267		Ok(data)
1268	}
1269
1270	fn clone_table(&self) -> Box<dyn Table> {
1271		Box::new(self.clone())
1272	}
1273
1274	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
1275		self.attributes = crate::ot::aat::remap_keys(std::mem::take(&mut self.attributes), f)?;
1276		Ok(())
1277	}
1278}
1279
1280impl TableXml for Glat {
1281	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
1282		writer.simpletag(
1283			"version",
1284			&[
1285				("version", &self.version),
1286				("compressionScheme", &self.scheme),
1287			],
1288		);
1289		writer.newline();
1290		let order = font.glyph_order()?;
1291		for (&gid, a) in &self.attributes {
1292			writer.begintag("glyph", &[("name", &order.name(gid))]);
1293			writer.newline();
1294			if let Some(o) = &a.octabox {
1295				let percent = |v: i64| format!("{:.3}%", v as f64 * 100.0 / 255.0);
1296				let diag: Vec<String> = o.diag().into_iter().map(percent).collect();
1297				let bitmap = if o.subbox_bitmap < 0 {
1298					format!("-{:X}", o.subbox_bitmap.unsigned_abs())
1299				} else {
1300					format!("{:X}", o.subbox_bitmap)
1301				};
1302				let mut attrs: Vec<(&str, &dyn fontoxide_misc::xml_writer::AttrValue)> =
1303					Octabox::NAMES
1304						.iter()
1305						.zip(&diag)
1306						.map(|(&n, v)| (n, v as &dyn fontoxide_misc::xml_writer::AttrValue))
1307						.collect();
1308				attrs.push(("bitmap", &bitmap));
1309				writer.begintag("octaboxes", &attrs);
1310				writer.newline();
1311				for s in &o.subboxes {
1312					let vals: Vec<String> = s.fields().into_iter().map(percent).collect();
1313					let attrs: Vec<(&str, &dyn fontoxide_misc::xml_writer::AttrValue)> =
1314						Subbox::NAMES
1315							.iter()
1316							.zip(&vals)
1317							.map(|(&n, v)| (n, v as &dyn fontoxide_misc::xml_writer::AttrValue))
1318							.collect();
1319					writer.simpletag("octabox", &attrs);
1320					writer.newline();
1321				}
1322				writer.endtag("octaboxes");
1323				writer.newline();
1324			}
1325			for (k, v) in &a.values {
1326				writer.simpletag("attribute", &[("index", k), ("value", v)]);
1327				writer.newline();
1328			}
1329			writer.endtag("glyph");
1330			writer.newline();
1331		}
1332		Ok(())
1333	}
1334
1335	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
1336		if element.name == "version" {
1337			self.version = eval_float(attr(element, "version")?)?;
1338			self.scheme = eval_int(attr(element, "compressionScheme")?)?;
1339		}
1340		if element.name != "glyph" {
1341			return Ok(());
1342		}
1343		let gid = font.glyph_id(attr(element, "name")?)?;
1344		// `int(float(v[:-1]) * 255.0 / 100.0 + 0.5)`.
1345		let from_percent = |v: &str| -> Result<i64> {
1346			let mut chars = v.chars();
1347			chars.next_back();
1348			let f = fontoxide_misc::py::parse_float(chars.as_str())
1349				.ok_or_else(|| Error::value(format!("could not convert string to float: {v:?}")))?;
1350			float_to_int(f * 255.0 / 100.0 + 0.5)
1351		};
1352		let mut attributes = GlatAttributes::default();
1353		for e in element.elements() {
1354			match e.name.as_str() {
1355				"attribute" => {
1356					let k = eval_int(attr(e, "index")?)?;
1357					let v = eval_int(attr(e, "value")?)?;
1358					attributes.values.insert(k, v);
1359				}
1360				"octaboxes" => {
1361					self.has_octaboxes = Some(true);
1362					let bitmap = attr(e, "bitmap")?;
1363					let mut o = Octabox {
1364						subbox_bitmap: parse_int_radix(bitmap, 16)
1365							.and_then(|v| i64::try_from(v).ok())
1366							.ok_or_else(|| {
1367								Error::value(format!(
1368									"invalid literal for int() with base 16: {bitmap:?}"
1369								))
1370							})?,
1371						..Default::default()
1372					};
1373					for (k, v) in &e.attrs {
1374						if let Some(i) = Octabox::NAMES.iter().position(|n| n == k) {
1375							*o.diag_mut()[i] = from_percent(v)?;
1376						} else if k != "bitmap" {
1377							from_percent(v)?;
1378						}
1379					}
1380					for sub in e.elements() {
1381						let mut s = Subbox::default();
1382						for (k, v) in &sub.attrs {
1383							let value = from_percent(v)?;
1384							if let Some(i) = Subbox::NAMES.iter().position(|n| n == k) {
1385								*s.fields_mut()[i] = value;
1386							}
1387						}
1388						o.subboxes.push(s);
1389					}
1390					attributes.octabox = Some(o);
1391				}
1392				_ => {}
1393			}
1394		}
1395		self.attributes.insert(gid, attributes);
1396		Ok(())
1397	}
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402	use super::*;
1403
1404	#[test]
1405	fn grutils() -> Result<()> {
1406		assert_eq!(num2tag(1)?, "1");
1407		assert_eq!(num2tag(u32::from_be_bytes(*b"nom "))?, "nom ");
1408		assert_eq!(num2tag(u32::from_be_bytes(*b"ab\0\0"))?, "ab");
1409		assert_eq!(tag2num("1")?, 1);
1410		assert_eq!(tag2num("ab")?, i64::from(u32::from_be_bytes(*b"ab  ")));
1411		assert_eq!(bininfo(0, 1)?, [0; 8]);
1412		assert_eq!(bininfo(5, 6)?, [0, 5, 0, 24, 0, 2, 0, 6]);
1413		let attrs: BTreeMap<i64, i64> = [(1, 3), (2, 30), (4, 4), (5, 4)].into();
1414		assert_eq!(
1415			entries(&attrs, false),
1416			[(1, 2, vec![3, 30]), (4, 2, vec![4, 4])]
1417		);
1418		assert_eq!(entries(&BTreeMap::new(), false), [(1, 0, vec![])]);
1419		Ok(())
1420	}
1421
1422	/// fontTools without the lz4 module: `grUtils` warns and leaves the data as
1423	/// it is.
1424	#[test]
1425	#[cfg(not(feature = "graphite"))]
1426	fn lz4_without_the_module() -> Result<()> {
1427		let data = b"\0\x05\0\0\0\0\0\0hello hello hello hello".to_vec();
1428		assert_eq!(compress(1, &data)?, data);
1429		let compressed = b"\0\x05\0\0\x08\0\0\x1f\x01\x02".to_vec();
1430		assert_eq!(decompress(&compressed)?, (compressed, 1));
1431		Ok(())
1432	}
1433
1434	#[test]
1435	#[cfg(feature = "graphite")]
1436	fn lz4() -> Result<()> {
1437		let data = b"\0\x05\0\0\0\0\0\0hello hello hello hello".to_vec();
1438		let compressed = compress(1, &data)?;
1439		assert_eq!(&compressed[..8], b"\0\x05\0\0\x08\0\0\x1f");
1440		assert_eq!(decompress(&compressed)?, (data, 1));
1441		Ok(())
1442	}
1443
1444	#[test]
1445	fn slices() {
1446		let d = [1, 2, 3, 4];
1447		assert_eq!(py_slice(&d, 1, 3), [2, 3]);
1448		assert_eq!(py_slice(&d, -1, 9), [4]);
1449		assert_eq!(py_slice(&d, 3, 1), [] as [i32; 0]);
1450		assert_eq!(py_tail(&d, -0), d);
1451		assert_eq!(py_slice(&d, 0, -5), [] as [i32; 0]);
1452	}
1453}