Skip to main content

fontoxide_ttlib/tables/
glyf.rs

1//! `glyf`: Glyph Data table (`fontTools.ttLib.tables._g_l_y_f`).
2
3use std::collections::{BTreeMap, HashMap, HashSet};
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::fixed_tools::{
7	fixed_to_float, float_to_fixed, float_to_fixed_to_str, str_to_fixed_to_float,
8};
9use fontoxide_misc::py::float_repr;
10use fontoxide_misc::round_tools::ot_round;
11use fontoxide_misc::text_tools::Literal;
12use fontoxide_misc::transform::Transform;
13use fontoxide_misc::xml_reader::Element;
14use fontoxide_misc::xml_writer::{AttrValue, XmlWriter};
15
16use fontoxide_pens::{Pen, PointPen, SegmentType};
17
18use crate::binary::fit;
19use crate::glyph_order::GlyphOrder;
20use crate::sstruct::eval;
21use crate::table::{Table, TableType, TableXml};
22use crate::tables::tt_program::Program;
23use crate::tables::{Loca, Maxp};
24use crate::{Error, Font, Result};
25
26/// The point is on the curve.
27pub const FLAG_ON_CURVE: u8 = 0x01;
28const FLAG_X_SHORT: u8 = 0x02;
29const FLAG_Y_SHORT: u8 = 0x04;
30const FLAG_REPEAT: u8 = 0x08;
31const FLAG_X_SAME: u8 = 0x10;
32const FLAG_Y_SAME: u8 = 0x20;
33/// The contours may overlap (in the first point's flags).
34pub const FLAG_OVERLAP_SIMPLE: u8 = 0x40;
35/// The point is a cubic off-curve point (`glyf` version 1, `GLYF`).
36pub const FLAG_CUBIC: u8 = 0x80;
37/// The flags kept after decompiling, for `glyf` (`keepFlags & ~flagCubic`).
38const KEEP_FLAGS: u8 = FLAG_ON_CURVE | FLAG_OVERLAP_SIMPLE;
39
40const ARG_1_AND_2_ARE_WORDS: i64 = 0x0001;
41const ARGS_ARE_XY_VALUES: i64 = 0x0002;
42const ROUND_XY_TO_GRID: i64 = 0x0004;
43const WE_HAVE_A_SCALE: i64 = 0x0008;
44const NON_OVERLAPPING: i64 = 0x0010;
45const MORE_COMPONENTS: i64 = 0x0020;
46const WE_HAVE_AN_X_AND_Y_SCALE: i64 = 0x0040;
47const WE_HAVE_A_TWO_BY_TWO: i64 = 0x0080;
48const WE_HAVE_INSTRUCTIONS: i64 = 0x0100;
49const USE_MY_METRICS: i64 = 0x0200;
50const OVERLAP_COMPOUND: i64 = 0x0400;
51const SCALED_COMPONENT_OFFSET: i64 = 0x0800;
52const UNSCALED_COMPONENT_OFFSET: i64 = 0x1000;
53const GID_IS_24_BIT: i64 = 0x2000;
54
55/// The component flags that are kept; the others are computed when writing.
56const KEPT_COMPONENT_FLAGS: i64 = ROUND_XY_TO_GRID
57	| USE_MY_METRICS
58	| SCALED_COMPONENT_OFFSET
59	| UNSCALED_COMPONENT_OFFSET
60	| NON_OVERLAPPING
61	| OVERLAP_COMPOUND;
62
63/// The most points a composite glyph may flatten to (`MAX_COMPOSITE_POINTS`).
64const MAX_COMPOSITE_POINTS: usize = 0xFFFF;
65
66/// A number that keeps whether it is a Python `int` or `float`, which shows in
67/// TTX and decides how it is written.
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub enum Number {
70	/// An `int`.
71	Int(i64),
72	/// A `float`.
73	Float(f64),
74}
75
76impl Number {
77	/// The value.
78	pub fn value(self) -> f64 {
79		match self {
80			Number::Int(i) => i as f64,
81			Number::Float(f) => f,
82		}
83	}
84
85	/// `str(value)`.
86	pub fn repr(self) -> String {
87		match self {
88			Number::Int(i) => i.to_string(),
89			Number::Float(f) => float_repr(f),
90		}
91	}
92
93	/// `otRound(value)`.
94	fn rounded(self) -> i64 {
95		match self {
96			Number::Int(i) => i,
97			Number::Float(f) => ot_round(f),
98		}
99	}
100
101	fn from_literal(l: &Literal, what: &str) -> Result<Self> {
102		match l {
103			Literal::Int(i) => Ok(Number::Int(int64(*i)?)),
104			Literal::Bool(b) => Ok(Number::Int(*b as i64)),
105			Literal::Float(f) => Ok(Number::Float(*f)),
106			_ => Err(Error::value(format!("invalid {what}"))),
107		}
108	}
109}
110
111fn int64(v: i128) -> Result<i64> {
112	i64::try_from(v).map_err(|_| Error::Struct(format!("value {v} out of range")))
113}
114
115/// A coordinate as `GlyphCoordinates.__getitem__` returns it: an `int` if it is
116/// integral.
117fn coord_repr(v: f64) -> String {
118	if v.fract() == 0.0 && v.is_finite() && v.abs() < 1e18 {
119		(v as i64).to_string()
120	} else {
121		float_repr(v)
122	}
123}
124
125fn i16_of(v: i64) -> Result<i16> {
126	i16::try_from(v)
127		.map_err(|_| Error::Struct("'h' format requires -32768 <= number <= 32767".into()))
128}
129
130fn u16_of(v: i64) -> Result<u16> {
131	u16::try_from(v).map_err(|_| Error::Struct("'H' format requires 0 <= number <= 65535".into()))
132}
133
134/// How a component is placed.
135#[derive(Debug, Clone, Copy, PartialEq)]
136pub enum ComponentPlacement {
137	/// By an offset (`x`, `y`).
138	Offset {
139		/// `x`.
140		x: Number,
141		/// `y`.
142		y: Number,
143	},
144	/// By matching a point of the glyph so far with one of the component
145	/// (`firstPt`, `secondPt`).
146	Points {
147		/// `firstPt`.
148		first: i64,
149		/// `secondPt`.
150		second: i64,
151	},
152}
153
154/// A component of a composite glyph (`GlyphComponent`).
155#[derive(Debug, Clone, PartialEq)]
156pub struct GlyphComponent {
157	/// The component glyph (`glyphName`).
158	pub glyph: u32,
159	/// The flags that are kept (`flags`).
160	pub flags: i64,
161	/// Where the component goes.
162	pub placement: ComponentPlacement,
163	/// The 2×2 matrix (`transform`), if any.
164	pub transform: Option<[[f64; 2]; 2]>,
165}
166
167impl GlyphComponent {
168	/// `decompile`: the component, whether more follow and whether the glyph has
169	/// instructions, and the bytes read.
170	pub(crate) fn decompile(
171		data: &[u8],
172		num_glyph_names: usize,
173	) -> Result<(Self, bool, bool, usize)> {
174		Self::decompile_ext(data, num_glyph_names, false)
175	}
176
177	/// [`GlyphComponent::decompile`] for `glyf` or the `extended` `GLYF`.
178	pub fn decompile_ext(
179		data: &[u8],
180		num_glyph_names: usize,
181		extended: bool,
182	) -> Result<(Self, bool, bool, usize)> {
183		let short = |n: usize| Error::Struct(format!("unpack requires a buffer of {n} bytes"));
184		let take = |pos: usize, n: usize| data.get(pos..pos + n).ok_or_else(|| short(n));
185		let b = take(0, 2)?;
186		let raw_flags = u16::from_be_bytes([b[0], b[1]]) as i64;
187		// glyf (not GLYF) always uses 16-bit glyph IDs.
188		let gid_size = if extended && raw_flags & GID_IS_24_BIT != 0 {
189			3
190		} else {
191			2
192		};
193		let gid = data
194			.get(2..(2 + gid_size).min(data.len()))
195			.unwrap_or_default()
196			.iter()
197			.fold(0u32, |acc, &b| acc << 8 | u32::from(b));
198		if gid as usize >= num_glyph_names {
199			return Err(Error::ttlib("IndexError: list index out of range"));
200		}
201		let mut pos = (2 + gid_size).min(data.len());
202		let placement = if raw_flags & ARG_1_AND_2_ARE_WORDS != 0 {
203			let b = take(pos, 4)?;
204			pos += 4;
205			if raw_flags & ARGS_ARE_XY_VALUES != 0 {
206				ComponentPlacement::Offset {
207					x: Number::Int(i16::from_be_bytes([b[0], b[1]]) as i64),
208					y: Number::Int(i16::from_be_bytes([b[2], b[3]]) as i64),
209				}
210			} else {
211				ComponentPlacement::Points {
212					first: u16::from_be_bytes([b[0], b[1]]) as i64,
213					second: u16::from_be_bytes([b[2], b[3]]) as i64,
214				}
215			}
216		} else {
217			let b = take(pos, 2)?;
218			pos += 2;
219			if raw_flags & ARGS_ARE_XY_VALUES != 0 {
220				ComponentPlacement::Offset {
221					x: Number::Int(b[0] as i8 as i64),
222					y: Number::Int(b[1] as i8 as i64),
223				}
224			} else {
225				ComponentPlacement::Points {
226					first: b[0] as i64,
227					second: b[1] as i64,
228				}
229			}
230		};
231		let f2 =
232			|b: &[u8], i: usize| fixed_to_float(i16::from_be_bytes([b[i], b[i + 1]]) as i64, 14);
233		let transform = if raw_flags & WE_HAVE_A_SCALE != 0 {
234			let b = take(pos, 2)?;
235			pos += 2;
236			let s = f2(b, 0);
237			Some([[s, 0.0], [0.0, s]])
238		} else if raw_flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
239			let b = take(pos, 4)?;
240			pos += 4;
241			Some([[f2(b, 0), 0.0], [0.0, f2(b, 2)]])
242		} else if raw_flags & WE_HAVE_A_TWO_BY_TWO != 0 {
243			let b = take(pos, 8)?;
244			pos += 8;
245			Some([[f2(b, 0), f2(b, 2)], [f2(b, 4), f2(b, 6)]])
246		} else {
247			None
248		};
249		let component = GlyphComponent {
250			glyph: gid,
251			flags: raw_flags & KEPT_COMPONENT_FLAGS,
252			placement,
253			transform,
254		};
255		Ok((
256			component,
257			raw_flags & MORE_COMPONENTS != 0,
258			raw_flags & WE_HAVE_INSTRUCTIONS != 0,
259			pos,
260		))
261	}
262
263	/// `compile`.
264	pub(crate) fn compile(
265		&self,
266		more: bool,
267		have_instructions: bool,
268		num_glyphs: usize,
269	) -> Result<Vec<u8>> {
270		self.compile_ext(more, have_instructions, num_glyphs, false)
271	}
272
273	/// [`GlyphComponent::compile`] for `glyf` or the `extended` `GLYF`.
274	pub fn compile_ext(
275		&self,
276		more: bool,
277		have_instructions: bool,
278		num_glyphs: usize,
279		extended: bool,
280	) -> Result<Vec<u8>> {
281		let mut data = Vec::new();
282		let mut flags = self.flags & KEPT_COMPONENT_FLAGS;
283		if more {
284			flags |= MORE_COMPONENTS;
285		}
286		if have_instructions {
287			flags |= WE_HAVE_INSTRUCTIONS;
288		}
289		match self.placement {
290			ComponentPlacement::Points { first, second } => {
291				if (0..=255).contains(&first) && (0..=255).contains(&second) {
292					data.extend_from_slice(&[first as u8, second as u8]);
293				} else {
294					data.extend_from_slice(&u16_of(first)?.to_be_bytes());
295					data.extend_from_slice(&u16_of(second)?.to_be_bytes());
296					flags |= ARG_1_AND_2_ARE_WORDS;
297				}
298			}
299			ComponentPlacement::Offset { x, y } => {
300				let (x, y) = (x.rounded(), y.rounded());
301				flags |= ARGS_ARE_XY_VALUES;
302				if (-128..=127).contains(&x) && (-128..=127).contains(&y) {
303					data.extend_from_slice(&[x as i8 as u8, y as i8 as u8]);
304				} else {
305					data.extend_from_slice(&i16_of(x)?.to_be_bytes());
306					data.extend_from_slice(&i16_of(y)?.to_be_bytes());
307					flags |= ARG_1_AND_2_ARE_WORDS;
308				}
309			}
310		}
311		if let Some(t) = self.transform {
312			let f = |v: f64| i16_of(float_to_fixed(v, 14));
313			let t = [[f(t[0][0])?, f(t[0][1])?], [f(t[1][0])?, f(t[1][1])?]];
314			if t[0][1] != 0 || t[1][0] != 0 {
315				flags |= WE_HAVE_A_TWO_BY_TWO;
316				for v in [t[0][0], t[0][1], t[1][0], t[1][1]] {
317					data.extend_from_slice(&v.to_be_bytes());
318				}
319			} else if t[0][0] != t[1][1] {
320				flags |= WE_HAVE_AN_X_AND_Y_SCALE;
321				data.extend_from_slice(&t[0][0].to_be_bytes());
322				data.extend_from_slice(&t[1][1].to_be_bytes());
323			} else {
324				flags |= WE_HAVE_A_SCALE;
325				data.extend_from_slice(&t[0][0].to_be_bytes());
326			}
327		}
328		if self.glyph as usize >= num_glyphs {
329			return Err(Error::value(format!("{}", self.glyph)));
330		}
331		let mut out = Vec::with_capacity(5 + data.len());
332		if extended && self.glyph > 0xFFFF {
333			if self.glyph > 0xFF_FFFF {
334				return Err(Error::Struct("int too big to convert".into()));
335			}
336			flags |= GID_IS_24_BIT;
337			out.extend_from_slice(&u16_of(flags)?.to_be_bytes());
338			out.extend_from_slice(&self.glyph.to_be_bytes()[1..]);
339		} else {
340			flags &= !GID_IS_24_BIT;
341			let gid = u16::try_from(self.glyph)
342				.map_err(|_| Error::Struct("int too big to convert".into()))?;
343			out.extend_from_slice(&u16_of(flags)?.to_be_bytes());
344			out.extend_from_slice(&gid.to_be_bytes());
345		}
346		out.extend(data);
347		Ok(out)
348	}
349
350	/// `toXML`.
351	pub fn to_xml(&self, writer: &mut XmlWriter, order: &GlyphOrder) {
352		let name = order.name(self.glyph).into_owned();
353		let mut attrs: Vec<(&str, String)> = vec![("glyphName", name)];
354		match self.placement {
355			ComponentPlacement::Offset { x, y } => {
356				attrs.push(("x", x.repr()));
357				attrs.push(("y", y.repr()));
358			}
359			ComponentPlacement::Points { first, second } => {
360				attrs.push(("firstPt", first.to_string()));
361				attrs.push(("secondPt", second.to_string()));
362			}
363		}
364		if let Some(t) = self.transform {
365			let s = |v: f64| float_to_fixed_to_str(v, 14);
366			if t[0][1] != 0.0 || t[1][0] != 0.0 {
367				attrs.push(("scalex", s(t[0][0])));
368				attrs.push(("scale01", s(t[0][1])));
369				attrs.push(("scale10", s(t[1][0])));
370				attrs.push(("scaley", s(t[1][1])));
371			} else if t[0][0] != t[1][1] {
372				attrs.push(("scalex", s(t[0][0])));
373				attrs.push(("scaley", s(t[1][1])));
374			} else {
375				attrs.push(("scale", s(t[0][0])));
376			}
377		}
378		attrs.push(("flags", py_hex(self.flags)));
379		let refs: Vec<(&str, &dyn AttrValue)> = attrs
380			.iter()
381			.map(|(n, v)| (*n, v as &dyn AttrValue))
382			.collect();
383		writer.simpletag_ordered("component", &refs);
384		writer.newline();
385	}
386
387	/// `fromXML`: the component of a `<component>` element; its glyph name is
388	/// looked up in the glyph order of `font`.
389	pub fn from_xml(e: &Element, font: &mut Font) -> Result<Self> {
390		let attr = |name: &str| {
391			e.attr(name)
392				.ok_or_else(|| Error::ttx(format!("KeyError: {name:?}")))
393		};
394		let glyph = font.glyph_id(attr("glyphName")?)?;
395		let int = |name: &str| -> Result<i64> {
396			let v = attr(name)?;
397			eval(v)?
398				.as_int()
399				.ok_or_else(|| Error::value(format!("invalid {name}: {v:?}")))
400				.and_then(int64)
401		};
402		let placement = if e.attr("firstPt").is_some() {
403			ComponentPlacement::Points {
404				first: int("firstPt")?,
405				second: int("secondPt")?,
406			}
407		} else {
408			ComponentPlacement::Offset {
409				x: Number::from_literal(&eval(attr("x")?)?, "x")?,
410				y: Number::from_literal(&eval(attr("y")?)?, "y")?,
411			}
412		};
413		let fixed = |name: &str| -> Result<f64> {
414			let v = attr(name)?;
415			str_to_fixed_to_float(v, 14)
416				.ok_or_else(|| Error::value(format!("could not convert string to float: {v:?}")))
417		};
418		let transform = if e.attr("scale01").is_some() {
419			Some([
420				[fixed("scalex")?, fixed("scale01")?],
421				[fixed("scale10")?, fixed("scaley")?],
422			])
423		} else if e.attr("scalex").is_some() {
424			Some([[fixed("scalex")?, 0.0], [0.0, fixed("scaley")?]])
425		} else if e.attr("scale").is_some() {
426			let s = fixed("scale")?;
427			Some([[s, 0.0], [0.0, s]])
428		} else {
429			None
430		};
431		Ok(GlyphComponent {
432			glyph,
433			flags: int("flags")?,
434			placement,
435			transform,
436		})
437	}
438
439	/// `_hasOnlyIntegerTranslate`.
440	fn has_only_integer_translate(&self) -> bool {
441		match self.placement {
442			ComponentPlacement::Offset { x, y } => {
443				self.transform.is_none() && x.value().fract() == 0.0 && y.value().fract() == 0.0
444			}
445			ComponentPlacement::Points { .. } => false,
446		}
447	}
448}
449
450/// `hex(value)`.
451fn py_hex(v: i64) -> String {
452	if v < 0 {
453		format!("-{:#x}", v.unsigned_abs())
454	} else {
455		format!("{v:#x}")
456	}
457}
458
459/// A glyph (`Glyph`): simple (contours), composite (components) or empty.
460#[derive(Debug, Clone, Default, PartialEq)]
461pub struct Glyph {
462	/// The number of contours; -1 for a composite glyph (`numberOfContours`).
463	pub number_of_contours: i64,
464	/// `xMin`.
465	pub x_min: i64,
466	/// `yMin`.
467	pub y_min: i64,
468	/// `xMax`.
469	pub x_max: i64,
470	/// `yMax`.
471	pub y_max: i64,
472	/// The last point of each contour (`endPtsOfContours`).
473	pub end_pts_of_contours: Vec<i64>,
474	/// The points (`coordinates`).
475	pub coordinates: Vec<(f64, f64)>,
476	/// The point flags (`flags`).
477	pub flags: Vec<u8>,
478	/// The components of a composite glyph (`components`).
479	pub components: Vec<GlyphComponent>,
480	/// The instructions (`program`), if the glyph has them.
481	pub program: Option<Program>,
482	/// The compact data while the glyph is not expanded (`data`). The other
483	/// fields are always parsed, but as in fontTools, a glyph that was read
484	/// and not expanded is written as these bytes unless bounding boxes are
485	/// recalculated. Clear it when changing the glyph.
486	pub data: Option<Vec<u8>>,
487}
488
489impl Glyph {
490	/// Whether the glyph is composite (`isComposite`).
491	pub fn is_composite(&self) -> bool {
492		self.number_of_contours == -1
493	}
494
495	/// The component glyph and its transformation (`getComponentInfo`).
496	pub fn component_info(c: &GlyphComponent) -> Result<(u32, Transform)> {
497		let ComponentPlacement::Offset { x, y } = c.placement else {
498			return Err(Error::ttlib(
499				"AttributeError: 'GlyphComponent' object has no attribute 'x'",
500			));
501		};
502		let [[xx, xy], [yx, yy]] = c.transform.unwrap_or([[1.0, 0.0], [0.0, 1.0]]);
503		Ok((
504			c.glyph,
505			Transform::new(xx, xy, yx, yy, x.value(), y.value()),
506		))
507	}
508
509	/// Draws the glyph onto `pen`, moved right by `offset` (`draw`). Components
510	/// are passed on to the pen.
511	pub fn draw(&self, order: &GlyphOrder, pen: &mut dyn Pen, offset: f64) -> Result<()> {
512		if self.is_composite() {
513			for c in &self.components {
514				let (gid, t) = Self::component_info(c)?;
515				pen.add_component(&order.name(gid), t)?;
516			}
517			return Ok(());
518		}
519		if self.number_of_contours <= 0 {
520			return Ok(());
521		}
522		let mut coordinates = self.coordinates.clone();
523		if offset != 0.0 {
524			translate(&mut coordinates, (offset, 0.0));
525		}
526		let assertion = |what: &str| Error::Assertion(what.to_owned());
527		let mid = |a: (f64, f64), b: (f64, f64)| ((a.0 + b.0) * 0.5, (a.1 + b.1) * 0.5);
528		let mut start = 0;
529		for &end in &self.end_pts_of_contours {
530			let end = usize::try_from(end + 1)
531				.unwrap_or(0)
532				.clamp(start, coordinates.len());
533			let mut contour = coordinates[start..end].to_vec();
534			let mut c_flags: Vec<bool> = self.flags
535				[start.min(self.flags.len())..end.min(self.flags.len())]
536				.iter()
537				.map(|f| f & FLAG_ON_CURVE != 0)
538				.collect();
539			let mut cu_flags: Vec<bool> = self.flags
540				[start.min(self.flags.len())..end.min(self.flags.len())]
541				.iter()
542				.map(|f| f & FLAG_CUBIC != 0)
543				.collect();
544			start = end;
545			match c_flags.iter().position(|&f| f) {
546				None => {
547					let all = cu_flags.iter().all(|&f| f);
548					if !all && cu_flags.iter().any(|&f| f) {
549						return Err(assertion("all(cuFlags) or not any(cuFlags)"));
550					}
551					if all {
552						let count = contour.len();
553						if !count.is_multiple_of(2) {
554							return Err(assertion("Odd number of cubic off-curves undefined"));
555						}
556						let (Some(&l), Some(&f)) = (contour.last(), contour.first()) else {
557							return Err(Error::ttlib("IndexError: array index out of range"));
558						};
559						pen.move_to(mid(l, f))?;
560						for i in (0..count).step_by(2) {
561							let p1 = contour[i];
562							let p2 = contour[i + 1];
563							let p4 = contour[if i + 2 < count { i + 2 } else { 0 }];
564							pen.curve_to(&[p1, p2, mid(p2, p4)])?;
565						}
566					} else {
567						// No on-curve point at all: `qCurveTo` with `None` as the
568						// on-curve point.
569						pen.q_curve_to(&contour, None)?;
570					}
571				}
572				Some(first) => {
573					// Rotate the points so that the contour ends in an on-curve
574					// point, which is used for the `moveTo`.
575					let first = first + 1;
576					contour.rotate_left(first);
577					c_flags.rotate_left(first);
578					cu_flags.rotate_left(first);
579					pen.move_to(contour[contour.len() - 1])?;
580					while !contour.is_empty() {
581						let next = c_flags
582							.iter()
583							.position(|&f| f)
584							.ok_or_else(|| Error::value("ValueError: 1 is not in list"))?
585							+ 1;
586						if next == 1 {
587							// A final `lineTo` is implied by `closePath`.
588							if contour.len() > 1 {
589								pen.line_to(contour[0])?;
590							}
591						} else {
592							let cubic_flags = &cu_flags[..next - 1];
593							let all = cubic_flags.iter().all(|&f| f);
594							let any = cubic_flags.iter().any(|&f| f);
595							if !all && any {
596								return Err(assertion("all(cubicFlags) or not any(cubicFlags)"));
597							}
598							if any {
599								let count = next;
600								if count < 3 {
601									return Err(assertion(
602										"At least two cubic off-curve points required",
603									));
604								}
605								if (count - 1) % 2 != 0 {
606									return Err(assertion(
607										"Odd number of cubic off-curves undefined",
608									));
609								}
610								for i in (0..count - 3).step_by(2) {
611									let p1 = contour[i];
612									let p2 = contour[i + 1];
613									let p4 = contour[i + 2];
614									pen.curve_to(&[p1, p2, mid(p2, p4)])?;
615								}
616								pen.curve_to(&contour[count - 3..count])?;
617							} else {
618								pen.q_curve_to(&contour[..next - 1], Some(contour[next - 1]))?;
619							}
620						}
621						contour.drain(..next);
622						c_flags.drain(..next);
623						cu_flags.drain(..next);
624					}
625				}
626			}
627			pen.close_path()?;
628		}
629		Ok(())
630	}
631
632	/// Draws the glyph onto a point pen, moved right by `offset`
633	/// (`drawPoints`). Unlike [`Glyph::draw`], the point indices are kept;
634	/// cubic contours without on-curve points cannot be drawn this way
635	/// (`NotImplementedError`). Components are passed on to the pen.
636	pub fn draw_points(
637		&self,
638		order: &GlyphOrder,
639		pen: &mut dyn PointPen,
640		offset: f64,
641	) -> Result<()> {
642		if self.is_composite() {
643			for c in &self.components {
644				let (gid, t) = Self::component_info(c)?;
645				pen.add_component(&order.name(gid), t, None)?;
646			}
647			return Ok(());
648		}
649		if self.number_of_contours <= 0 {
650			return Ok(());
651		}
652		let flag = |i: usize| self.flags.get(i).copied().unwrap_or(0);
653		let ends: Vec<usize> = self
654			.end_pts_of_contours
655			.iter()
656			.map(|&e| usize::try_from(e + 1).unwrap_or(0))
657			.collect();
658		// Validate every contour before drawing.
659		let mut start = 0;
660		for &end in &ends {
661			let range = start..end.max(start);
662			start = end;
663			if !range.clone().any(|i| flag(i) & FLAG_ON_CURVE != 0)
664				&& range.clone().any(|i| flag(i) & FLAG_CUBIC != 0)
665			{
666				return Err(Error::ttlib(
667					"NotImplementedError: All-off-curve cubic contours are not supported by drawPoints; use draw instead",
668				));
669			}
670		}
671		let mut coordinates = self.coordinates.clone();
672		if offset != 0.0 {
673			translate(&mut coordinates, (offset, 0.0));
674		}
675		let mut start = 0;
676		for &end in &ends {
677			let end = end.clamp(start, coordinates.len());
678			let contour = &coordinates[start..end];
679			let first = start;
680			start = end;
681			pen.begin_path(None)?;
682			// Start with the type of the final segment.
683			let last = flag(end.saturating_sub(1));
684			let mut segment_type = if last & FLAG_ON_CURVE != 0 {
685				SegmentType::Line
686			} else if last & FLAG_CUBIC != 0 {
687				SegmentType::Curve
688			} else {
689				SegmentType::QCurve
690			};
691			for (i, &pt) in contour.iter().enumerate() {
692				let f = flag(first + i);
693				if f & FLAG_ON_CURVE != 0 {
694					pen.add_point(pt, Some(segment_type), false, None, None)?;
695					segment_type = SegmentType::Line;
696				} else {
697					pen.add_point(pt, None, false, None, None)?;
698					segment_type = if f & FLAG_CUBIC != 0 {
699						SegmentType::Curve
700					} else {
701						SegmentType::QCurve
702					};
703				}
704			}
705			pen.end_path()?;
706		}
707		Ok(())
708	}
709
710	/// Parses a glyph (`Glyph(data)` + `expand`). Component glyph IDs must be
711	/// below `num_glyph_names`.
712	pub fn decompile(data: &[u8], num_glyph_names: usize) -> Result<Self> {
713		Self::decompile_ext(data, num_glyph_names, false)
714	}
715
716	/// [`Glyph::decompile`] for `glyf` or the `extended` `GLYF`.
717	pub fn decompile_ext(data: &[u8], num_glyph_names: usize, extended: bool) -> Result<Self> {
718		let mut g = Glyph::default();
719		if data.is_empty() {
720			return Ok(g);
721		}
722		let header = data
723			.get(..10)
724			.ok_or_else(|| Error::Struct("unpack requires a buffer of 10 bytes".into()))?;
725		let h = |i: usize| i16::from_be_bytes([header[i], header[i + 1]]) as i64;
726		g.number_of_contours = h(0);
727		g.x_min = h(2);
728		g.y_min = h(4);
729		g.x_max = h(6);
730		g.y_max = h(8);
731		let data = &data[10..];
732		if g.number_of_contours == 0 {
733			// Zero-contour glyphs may have instructions for the phantom points.
734			if data.len() >= 2 {
735				let n = u16::from_be_bytes([data[0], data[1]]) as usize;
736				g.program = Some(Program::from_bytecode(&data[2..(2 + n).min(data.len())]));
737			}
738			return Ok(g);
739		}
740		if g.is_composite() {
741			g.decompile_components(data, num_glyph_names, extended)?;
742		} else if g.number_of_contours < 0 {
743			// LENIENT(L11): fontTools reads such a glyph as a simple glyph with
744			// Python slicing on negative sizes, which yields garbage or fails.
745			return Err(Error::ttlib(format!(
746				"unsupported numberOfContours: {}",
747				g.number_of_contours
748			)));
749		} else {
750			g.decompile_coordinates(data, extended)?;
751		}
752		Ok(g)
753	}
754
755	fn decompile_components(
756		&mut self,
757		data: &[u8],
758		num_glyph_names: usize,
759		extended: bool,
760	) -> Result<()> {
761		let mut pos = 0;
762		let mut have_instructions = false;
763		loop {
764			let (c, more, instr, used) =
765				GlyphComponent::decompile_ext(&data[pos..], num_glyph_names, extended)?;
766			pos += used;
767			have_instructions |= instr;
768			self.components.push(c);
769			if !more {
770				break;
771			}
772		}
773		if have_instructions {
774			let b = data
775				.get(pos..pos + 2)
776				.ok_or_else(|| Error::Struct("unpack requires a buffer of 2 bytes".into()))?;
777			let n = u16::from_be_bytes([b[0], b[1]]) as usize;
778			pos += 2;
779			let end = (pos + n).min(data.len());
780			self.program = Some(Program::from_bytecode(&data[pos..end]));
781			let excess = data.len() - end;
782			if excess >= 4 {
783				log::warn!(
784					"too much glyph data at the end of composite glyph: {excess} excess bytes"
785				);
786			}
787		}
788		Ok(())
789	}
790
791	fn decompile_coordinates(&mut self, data: &[u8], extended: bool) -> Result<()> {
792		let n = self.number_of_contours as usize;
793		let end_bytes = &data[..(2 * n).min(data.len())];
794		if !end_bytes.len().is_multiple_of(2) {
795			return Err(Error::value("bytes length not a multiple of item size"));
796		}
797		self.end_pts_of_contours = end_bytes
798			.as_chunks::<2>()
799			.0
800			.iter()
801			.map(|&c| u16::from_be_bytes(c) as i64)
802			.collect();
803		let mut pos = 2 * n;
804		let b = data
805			.get(pos..pos + 2)
806			.ok_or_else(|| Error::Struct("unpack requires a buffer of 2 bytes".into()))?;
807		let instruction_length = u16::from_be_bytes([b[0], b[1]]) as usize;
808		let start = (pos + 2).min(data.len());
809		let end = (pos + 2 + instruction_length).min(data.len());
810		self.program = Some(Program::from_bytecode(&data[start..end]));
811		pos += 2 + instruction_length;
812		let last = *self
813			.end_pts_of_contours
814			.last()
815			.ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?;
816		let count = last as usize + 1;
817		let index = || Error::ttlib("IndexError: index out of range");
818		// Flags, with repeats expanded.
819		let mut flags = vec![0u8; count];
820		let mut j = 0;
821		let (mut x_len, mut y_len) = (0usize, 0usize);
822		loop {
823			let flag = *data.get(pos).ok_or_else(index)?;
824			pos += 1;
825			let mut repeat = 1;
826			if flag & FLAG_REPEAT != 0 {
827				repeat = *data.get(pos).ok_or_else(index)? as usize + 1;
828				pos += 1;
829			}
830			for _ in 0..repeat {
831				if flag & FLAG_X_SHORT != 0 {
832					x_len += 1;
833				} else if flag & FLAG_X_SAME == 0 {
834					x_len += 2;
835				}
836				if flag & FLAG_Y_SHORT != 0 {
837					y_len += 1;
838				} else if flag & FLAG_Y_SAME == 0 {
839					y_len += 2;
840				}
841				*flags
842					.get_mut(j)
843					.ok_or_else(|| Error::ttlib("IndexError: bytearray index out of range"))? =
844					flag;
845				j += 1;
846			}
847			if j >= count {
848				break;
849			}
850		}
851		let excess = data.len() as i64 - pos as i64 - (x_len + y_len) as i64;
852		if excess >= 4 {
853			log::warn!("too much glyph data: {excess} excess bytes");
854		}
855		let unpack = |at: usize, n: usize| {
856			data.get(at..at + n)
857				.ok_or_else(|| Error::Struct(format!("unpack requires a buffer of {n} bytes")))
858		};
859		let xs = unpack(pos, x_len)?;
860		let ys = unpack(pos + x_len, y_len)?;
861		let (mut xi, mut yi) = (0, 0);
862		let mut coordinates = Vec::with_capacity(count);
863		let (mut x, mut y) = (0.0, 0.0);
864		for &flag in &flags {
865			let dx = if flag & FLAG_X_SHORT != 0 {
866				let v = xs[xi] as f64;
867				xi += 1;
868				if flag & FLAG_X_SAME != 0 { v } else { -v }
869			} else if flag & FLAG_X_SAME != 0 {
870				0.0
871			} else {
872				let v = i16::from_be_bytes([xs[xi], xs[xi + 1]]) as f64;
873				xi += 2;
874				v
875			};
876			let dy = if flag & FLAG_Y_SHORT != 0 {
877				let v = ys[yi] as f64;
878				yi += 1;
879				if flag & FLAG_Y_SAME != 0 { v } else { -v }
880			} else if flag & FLAG_Y_SAME != 0 {
881				0.0
882			} else {
883				let v = i16::from_be_bytes([ys[yi], ys[yi + 1]]) as f64;
884				yi += 2;
885				v
886			};
887			x += dx;
888			y += dy;
889			coordinates.push((x, y));
890		}
891		self.coordinates = coordinates;
892		// Discard all flags except these.
893		let kept = if extended {
894			KEEP_FLAGS | FLAG_CUBIC
895		} else {
896			KEEP_FLAGS
897		};
898		self.flags = flags.into_iter().map(|f| f & kept).collect();
899		Ok(())
900	}
901
902	/// `getMaxpValues`: points and contours.
903	fn maxp_values(&self) -> (usize, usize) {
904		(self.coordinates.len(), self.end_pts_of_contours.len())
905	}
906
907	/// `compileCoordinates`: packed for size (`compileDeltasGreedy`) if
908	/// `optimize_size`, else for speed (`compileDeltasForSpeed`).
909	fn compile_coordinates(&self, extended: bool, optimize_size: bool) -> Result<Vec<u8>> {
910		if self.coordinates.len() != self.flags.len() {
911			return Err(Error::Assertion(
912				"len(self.coordinates) == len(self.flags)".into(),
913			));
914		}
915		let mut data = Vec::new();
916		for &e in &self.end_pts_of_contours {
917			let e = u16::try_from(e).map_err(|_| {
918				Error::value("OverflowError: unsigned short is greater than maximum")
919			})?;
920			data.extend_from_slice(&e.to_be_bytes());
921		}
922		// UPSTREAM-BUG(B14): a simple glyph read from TTX without an
923		// `<instructions>` element has no program, and writing it fails.
924		let program = self.program.as_ref().ok_or_else(|| {
925			Error::ttlib("AttributeError: 'Glyph' object has no attribute 'program'")
926		})?;
927		data.extend_from_slice(&u16_of(program.bytecode.len() as i64)?.to_be_bytes());
928		data.extend_from_slice(&program.bytecode);
929		if !extended && self.flags.iter().any(|f| f & FLAG_CUBIC != 0) {
930			return Err(Error::ttlib("Cubic flags require the extended GLYF table"));
931		}
932		// Deltas of the rounded coordinates.
933		let mut last = (0i64, 0i64);
934		let deltas: Vec<(i64, i64)> = self
935			.coordinates
936			.iter()
937			.map(|&(x, y)| {
938				let (x, y) = (ot_round(x), ot_round(y));
939				let d = (x - last.0, y - last.1);
940				last = (x, y);
941				d
942			})
943			.collect();
944		// For speed, every delta of an axis gets the widest representation that
945		// any of them needs: (zero, short) for x and y.
946		let widths = if optimize_size {
947			None
948		} else {
949			let width = |values: &mut dyn Iterator<Item = i64>| -> Result<(bool, bool)> {
950				let (min, max) = values.fold((None, None), |(lo, hi): (Option<i64>, _), v| {
951					(
952						Some(lo.map_or(v, |lo| lo.min(v))),
953						Some(hi.map_or(v, |hi: i64| hi.max(v))),
954					)
955				});
956				let (Some(min), Some(max)) = (min, max) else {
957					return Err(Error::value("min() arg is an empty sequence"));
958				};
959				Ok((
960					min == 0 && max == 0,
961					-255 <= min && min <= max && max <= 255,
962				))
963			};
964			Some((
965				width(&mut deltas.iter().map(|d| d.0))?,
966				width(&mut deltas.iter().map(|d| d.1))?,
967			))
968		};
969		let mut out_flags: Vec<u8> = Vec::new();
970		let mut xs: Vec<u8> = Vec::new();
971		let mut ys: Vec<u8> = Vec::new();
972		let mut last_flag: Option<u8> = None;
973		let mut repeat = 0;
974		for (&flag, &(dx, dy)) in self.flags.iter().zip(&deltas) {
975			let mut flag = flag;
976			for (d, short, same, out, width) in [
977				(dx, FLAG_X_SHORT, FLAG_X_SAME, &mut xs, widths.map(|w| w.0)),
978				(dy, FLAG_Y_SHORT, FLAG_Y_SAME, &mut ys, widths.map(|w| w.1)),
979			] {
980				let (zero, short_ok) = width.unwrap_or((d == 0, (-255..=255).contains(&d)));
981				if zero {
982					flag |= same;
983				} else if short_ok {
984					flag |= short;
985					if d > 0 {
986						flag |= same;
987					}
988					out.push(d.unsigned_abs() as u8);
989				} else {
990					out.extend_from_slice(&i16_of(d)?.to_be_bytes());
991				}
992			}
993			if Some(flag) == last_flag && repeat != 255 {
994				repeat += 1;
995				if repeat == 1 {
996					out_flags.push(flag);
997				} else {
998					let n = out_flags.len();
999					out_flags[n - 2] = flag | FLAG_REPEAT;
1000					out_flags[n - 1] = repeat as u8;
1001				}
1002			} else {
1003				repeat = 0;
1004				out_flags.push(flag);
1005			}
1006			last_flag = Some(flag);
1007		}
1008		data.extend(out_flags);
1009		data.extend(xs);
1010		data.extend(ys);
1011		Ok(data)
1012	}
1013
1014	fn compile_components(&self, num_glyphs: usize, extended: bool) -> Result<Vec<u8>> {
1015		let mut data = Vec::new();
1016		let mut have_instructions = false;
1017		let last = self.components.len().wrapping_sub(1);
1018		for (i, c) in self.components.iter().enumerate() {
1019			let more = i != last;
1020			if !more {
1021				have_instructions = self.program.is_some();
1022			}
1023			data.extend(c.compile_ext(more, have_instructions, num_glyphs, extended)?);
1024		}
1025		if have_instructions && let Some(p) = &self.program {
1026			data.extend_from_slice(&u16_of(p.bytecode.len() as i64)?.to_be_bytes());
1027			data.extend_from_slice(&p.bytecode);
1028		}
1029		Ok(data)
1030	}
1031
1032	/// `toXML`.
1033	fn to_xml(
1034		&self,
1035		writer: &mut XmlWriter,
1036		order: &GlyphOrder,
1037		extended: bool,
1038		disassemble: bool,
1039	) -> Result<()> {
1040		if !extended && self.flags.iter().any(|f| f & FLAG_CUBIC != 0) {
1041			return Err(Error::ttlib("Cubic flags require the extended GLYF table"));
1042		}
1043		if self.is_composite() {
1044			for c in &self.components {
1045				c.to_xml(writer, order);
1046			}
1047		} else {
1048			let index = || Error::ttlib("IndexError: list index out of range");
1049			let mut last = 0i64;
1050			for i in 0..self.number_of_contours.max(0) as usize {
1051				writer.begintag("contour", &[]);
1052				writer.newline();
1053				let end = *self.end_pts_of_contours.get(i).ok_or_else(index)?;
1054				for j in last..=end {
1055					let j = usize::try_from(j).map_err(|_| index())?;
1056					let (x, y) = *self.coordinates.get(j).ok_or_else(index)?;
1057					let flag = *self.flags.get(j).ok_or_else(index)?;
1058					let (x, y, on) = (
1059						coord_repr(x),
1060						coord_repr(y),
1061						(flag & FLAG_ON_CURVE).to_string(),
1062					);
1063					let mut attrs: Vec<(&str, &dyn AttrValue)> =
1064						vec![("x", &x), ("y", &y), ("on", &on)];
1065					if flag & FLAG_OVERLAP_SIMPLE != 0 {
1066						attrs.push(("overlap", &1));
1067					}
1068					if extended && flag & FLAG_CUBIC != 0 {
1069						attrs.push(("cubic", &1));
1070					}
1071					writer.simpletag_ordered("pt", &attrs);
1072					writer.newline();
1073				}
1074				last = end + 1;
1075				writer.endtag("contour");
1076				writer.newline();
1077			}
1078		}
1079		if let Some(p) = &self.program {
1080			if !p.is_empty() {
1081				writer.begintag("instructions", &[]);
1082				writer.newline();
1083				p.to_xml_with(writer, disassemble);
1084				writer.endtag("instructions");
1085			} else {
1086				writer.simpletag("instructions", &[]);
1087			}
1088			writer.newline();
1089		}
1090		Ok(())
1091	}
1092
1093	/// `fromXML` for one child element of `TTGlyph`.
1094	fn read_xml(&mut self, e: &Element, font: &mut Font, extended: bool) -> Result<()> {
1095		match e.name.as_str() {
1096			"contour" => {
1097				if self.number_of_contours < 0 {
1098					return Err(Error::ttlib("can't mix composites and contours in glyph"));
1099				}
1100				self.number_of_contours += 1;
1101				let mut coordinates = Vec::new();
1102				let mut flags = Vec::new();
1103				for pt in e.elements().filter(|p| p.name == "pt") {
1104					let attr = |name: &str| {
1105						pt.attr(name)
1106							.ok_or_else(|| Error::ttx(format!("KeyError: {name:?}")))
1107					};
1108					let num = |name: &str| -> Result<f64> {
1109						let v = attr(name)?;
1110						eval(v)?
1111							.as_float()
1112							.ok_or_else(|| Error::value(format!("invalid {name}: {v:?}")))
1113					};
1114					coordinates.push((num("x")?, num("y")?));
1115					let mut flag = u8::from(eval(attr("on")?)?.is_truthy());
1116					if let Some(v) = pt.attr("overlap")
1117						&& eval(v)?.is_truthy()
1118					{
1119						flag |= FLAG_OVERLAP_SIMPLE;
1120					}
1121					if let Some(v) = pt.attr("cubic")
1122						&& eval(v)?.is_truthy()
1123					{
1124						if !extended {
1125							return Err(Error::ttlib(
1126								"Cubic flags require the extended GLYF table",
1127							));
1128						}
1129						flag |= FLAG_CUBIC;
1130					}
1131					flags.push(flag);
1132				}
1133				let first = self.end_pts_of_contours.is_empty() && self.coordinates.is_empty();
1134				if first {
1135					self.coordinates = coordinates;
1136					self.flags = flags;
1137					self.end_pts_of_contours = vec![self.coordinates.len() as i64 - 1];
1138				} else {
1139					self.coordinates.extend(coordinates);
1140					self.flags.extend(flags);
1141					self.end_pts_of_contours
1142						.push(self.coordinates.len() as i64 - 1);
1143				}
1144			}
1145			"component" => {
1146				if self.number_of_contours > 0 {
1147					return Err(Error::ttlib("can't mix composites and contours in glyph"));
1148				}
1149				self.number_of_contours = -1;
1150				self.components.push(GlyphComponent::from_xml(e, font)?);
1151			}
1152			"instructions" => {
1153				let mut program = Program::default();
1154				for child in e.elements() {
1155					program = Program::from_xml(child)?;
1156				}
1157				self.program = Some(program);
1158			}
1159			_ => {}
1160		}
1161		Ok(())
1162	}
1163}
1164
1165/// The flattened outline of a glyph: points, contour ends and flags.
1166type Flat = (Vec<(f64, f64)>, Vec<i64>, Vec<u8>);
1167
1168/// Glyph Data table (`table__g_l_y_f`), with the glyphs by glyph ID.
1169///
1170/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/glyf>.
1171#[derive(Debug, Clone, PartialEq)]
1172pub struct Glyf {
1173	/// The glyphs (`glyphs`, which fontTools keys by glyph name). Glyphs past the
1174	/// glyph order (`ttxautoglyph…`) are kept but not written.
1175	pub glyphs: BTreeMap<u32, Glyph>,
1176	/// Glyphs are padded to multiples of this (`padding`): 0, 1, 2 or 4; 1 pads
1177	/// only when that allows short `loca` offsets.
1178	pub padding: u8,
1179	/// Whether this is `GLYF`, the beyond-64k companion of the table (`extended`).
1180	pub extended: bool,
1181}
1182
1183impl Default for Glyf {
1184	fn default() -> Self {
1185		Glyf {
1186			glyphs: BTreeMap::new(),
1187			padding: 1,
1188			extended: false,
1189		}
1190	}
1191}
1192
1193fn recursion_error(order: &GlyphOrder, gid: u32) -> Error {
1194	// LENIENT(L12): fontTools hits Python's recursion limit, and names the glyph
1195	// at that depth.
1196	Error::ttlib(format!(
1197		"glyph '{}' contains a recursive component reference",
1198		order.name(gid)
1199	))
1200}
1201
1202fn key_error(order: &GlyphOrder, gid: u32) -> Error {
1203	Error::ttlib(format!("KeyError: {:?}", order.name(gid)))
1204}
1205
1206/// The notice at the top of the TTX dump of `glyf`.
1207const BBOX_NOTICE: &str =
1208	"The xMin, yMin, xMax and yMax values\nwill be recalculated by the compiler.";
1209
1210impl Glyf {
1211	/// `toXML(writer, ttFont, splitGlyphs=True)`: dumps the table with each glyph
1212	/// that has outlines or instructions in a file of its own, which the dump
1213	/// refers to. `path` is the file name of `writer`, from which the names of
1214	/// the glyph files are derived; the glyph files are returned.
1215	pub fn to_xml_split(
1216		&self,
1217		writer: &mut XmlWriter,
1218		font: &mut Font,
1219		path: &str,
1220	) -> Result<Vec<crate::ttx::TtxFile>> {
1221		let mut files = Vec::new();
1222		self.write_xml(writer, font, Some((path, &mut files)))?;
1223		Ok(files)
1224	}
1225
1226	/// `toXML`, with the file name of `writer` and the glyph files if the glyphs
1227	/// are split.
1228	fn write_xml(
1229		&self,
1230		writer: &mut XmlWriter,
1231		font: &mut Font,
1232		mut split: Option<(&str, &mut Vec<crate::ttx::TtxFile>)>,
1233	) -> Result<()> {
1234		let order = font.glyph_order()?;
1235		if split.is_none() {
1236			writer.newline();
1237			writer.comment(BBOX_NOTICE);
1238			writer.newline();
1239			writer.newline();
1240		}
1241		let (prefix, suffix) = match &split {
1242			Some((path, _)) => {
1243				let (stem, ext) = crate::ttx::splitext(path);
1244				(format!("{stem}."), ext.to_owned())
1245			}
1246			None => Default::default(),
1247		};
1248		let mut existing_glyph_files = HashSet::new();
1249		let table_tag = Table::tag(self).to_string();
1250		let mut names: Vec<&String> = order.names().iter().collect();
1251		names.sort();
1252		for name in names {
1253			let Some(gid) = order.id(name) else {
1254				continue;
1255			};
1256			let Some(glyph) = self.glyphs.get(&gid) else {
1257				log::warn!("glyph '{name}' does not exist in glyf table");
1258				continue;
1259			};
1260			if glyph.number_of_contours != 0
1261				|| glyph.program.as_ref().is_some_and(|p| !p.is_empty())
1262			{
1263				let mut glyph_file = None;
1264				if split.is_some() {
1265					let glyph_path = crate::ttx::user_name_to_file_name(
1266						name,
1267						&existing_glyph_files,
1268						&prefix,
1269						&suffix,
1270					)?;
1271					existing_glyph_files.insert(glyph_path.to_lowercase());
1272					let mut glyph_writer = XmlWriter::with_options(
1273						fontoxide_misc::xml_writer::INDENT,
1274						writer.newline_str(),
1275					);
1276					glyph_writer
1277						.begintag("ttFont", &[("ttLibVersion", &crate::font::TTLIB_VERSION)]);
1278					glyph_writer.newline();
1279					glyph_writer.begintag(&table_tag, &[]);
1280					glyph_writer.newline();
1281					glyph_writer.comment(BBOX_NOTICE);
1282					glyph_writer.newline();
1283					writer.simpletag("TTGlyph", &[("src", &crate::ttx::basename(&glyph_path))]);
1284					glyph_file = Some((glyph_path, glyph_writer));
1285				}
1286				let glyph_writer = match &mut glyph_file {
1287					Some((_, w)) => w,
1288					None => &mut *writer,
1289				};
1290				let (x_min, y_min, x_max, y_max) =
1291					(glyph.x_min, glyph.y_min, glyph.x_max, glyph.y_max);
1292				glyph_writer.begintag_ordered(
1293					"TTGlyph",
1294					&[
1295						("name", name),
1296						("xMin", &x_min),
1297						("yMin", &y_min),
1298						("xMax", &x_max),
1299						("yMax", &y_max),
1300					],
1301				);
1302				glyph_writer.newline();
1303				glyph.to_xml(
1304					glyph_writer,
1305					&order,
1306					self.extended,
1307					font.disassemble_instructions,
1308				)?;
1309				glyph_writer.endtag("TTGlyph");
1310				glyph_writer.newline();
1311				if let (Some((glyph_path, mut glyph_writer)), Some((_, files))) =
1312					(glyph_file, &mut split)
1313				{
1314					glyph_writer.endtag(&table_tag);
1315					glyph_writer.newline();
1316					glyph_writer.endtag("ttFont");
1317					glyph_writer.newline();
1318					files.push(crate::ttx::TtxFile {
1319						path: glyph_path,
1320						contents: glyph_writer.into_string(),
1321					});
1322				}
1323			} else {
1324				writer.simpletag("TTGlyph", &[("name", name)]);
1325				writer.comment("contains no outline data");
1326				if split.is_none() {
1327					writer.newline();
1328				}
1329			}
1330			writer.newline();
1331		}
1332		Ok(())
1333	}
1334
1335	fn glyph(&self, gid: u32, order: &GlyphOrder) -> Result<&Glyph> {
1336		self.glyphs.get(&gid).ok_or_else(|| key_error(order, gid))
1337	}
1338
1339	/// `getCoordinates`: the outline, with composite glyphs flattened.
1340	///
1341	/// With `round`, `otRound` is applied to simple-glyph coordinates and XY
1342	/// component offsets before their transforms. Intermediate coordinates of
1343	/// nested components are not rounded.
1344	pub fn coordinates(&self, gid: u32, order: &GlyphOrder, round: bool) -> Result<Flat> {
1345		let mut cache = HashMap::new();
1346		let mut visiting = Vec::new();
1347		self.flatten(gid, order, round, &mut cache, &mut visiting)
1348	}
1349
1350	fn flatten(
1351		&self,
1352		gid: u32,
1353		order: &GlyphOrder,
1354		round: bool,
1355		cache: &mut HashMap<u32, Flat>,
1356		visiting: &mut Vec<u32>,
1357	) -> Result<Flat> {
1358		let g = self.glyph(gid, order)?;
1359		if g.number_of_contours > 0 {
1360			return Ok((
1361				g.coordinates.clone(),
1362				g.end_pts_of_contours.clone(),
1363				g.flags.clone(),
1364			));
1365		}
1366		if !g.is_composite() {
1367			return Ok((Vec::new(), Vec::new(), Vec::new()));
1368		}
1369		let (mut all, mut ends, mut flags): Flat = (Vec::new(), Vec::new(), Vec::new());
1370		for c in &g.components {
1371			let cg = self.glyph(c.glyph, order)?;
1372			let flat = match cache.get(&c.glyph) {
1373				Some(f) => f.clone(),
1374				None => {
1375					if visiting.contains(&c.glyph) {
1376						return Err(recursion_error(order, c.glyph));
1377					}
1378					visiting.push(c.glyph);
1379					let f = self.flatten(c.glyph, order, round, cache, visiting)?;
1380					visiting.pop();
1381					cache.insert(c.glyph, f.clone());
1382					f
1383				}
1384			};
1385			let (mut coords, end_pts, f) = flat;
1386			// Simple glyphs are rounded before being transformed; nested composites
1387			// only at the end, so that rounding errors do not compound.
1388			if round && cg.number_of_contours > 0 {
1389				for p in &mut coords {
1390					*p = (ot_round(p.0) as f64, ot_round(p.1) as f64);
1391				}
1392			}
1393			match c.placement {
1394				ComponentPlacement::Points { first, second } => {
1395					if let Some(t) = c.transform {
1396						transform(&mut coords, t);
1397					}
1398					let (x1, y1) = py_index(&all, first)?;
1399					let (x2, y2) = py_index(&coords, second)?;
1400					translate(&mut coords, (x1 - x2, y1 - y2));
1401				}
1402				ComponentPlacement::Offset { x, y } => {
1403					let mut mv = (x.value(), y.value());
1404					if round {
1405						// Match the offsets encoded by `GlyphComponent.compile`.
1406						mv = (ot_round(mv.0) as f64, ot_round(mv.1) as f64);
1407					}
1408					match c.transform {
1409						None => translate(&mut coords, mv),
1410						Some(t) => {
1411							let apple = c.flags & SCALED_COMPONENT_OFFSET != 0;
1412							let ms = c.flags & UNSCALED_COMPONENT_OFFSET != 0;
1413							if apple && ms {
1414								return Err(Error::Assertion("not (apple_way and ms_way)".into()));
1415							}
1416							// MS (scale, then move) unless the Apple flag is set.
1417							if apple {
1418								translate(&mut coords, mv);
1419								transform(&mut coords, t);
1420							} else {
1421								transform(&mut coords, t);
1422								translate(&mut coords, mv);
1423							}
1424						}
1425					}
1426				}
1427			}
1428			let offset = all.len() as i64;
1429			ends.extend(end_pts.iter().map(|e| e + offset));
1430			all.extend(coords);
1431			flags.extend(f);
1432			if all.len() > MAX_COMPOSITE_POINTS {
1433				return Err(Error::ttlib(format!(
1434					"composite glyph with component '{}' has more than {MAX_COMPOSITE_POINTS} points",
1435					order.name(c.glyph)
1436				)));
1437			}
1438		}
1439		Ok((all, ends, flags))
1440	}
1441
1442	/// `_getCoordinatesAndControls`: the coordinates of a glyph for `gvar`, rounded
1443	/// and with the four phantom points, and its contour ends (the indices of the
1444	/// components, for a composite glyph). `h_metrics` and `v_metrics` are the
1445	/// metrics of `hmtx` and `vmtx`.
1446	#[allow(clippy::type_complexity)]
1447	pub fn coordinates_and_controls(
1448		&mut self,
1449		gid: u32,
1450		order: &GlyphOrder,
1451		h_metrics: &BTreeMap<u32, (u16, i16)>,
1452		v_metrics: Option<&BTreeMap<u32, (u16, i16)>>,
1453	) -> Result<(Vec<(f64, f64)>, Vec<i64>)> {
1454		// The bounds are as they are, also those read from TTX: `_getPhantomPoints`
1455		// only calculates them for a glyph without any, which are all 0 here.
1456		let g = self.glyph(gid, order)?;
1457		let (mut coords, end_pts) = if g.is_composite() {
1458			let coords = g
1459				.components
1460				.iter()
1461				.map(|c| match c.placement {
1462					ComponentPlacement::Offset { x, y } => (x.value(), y.value()),
1463					ComponentPlacement::Points { .. } => (0.0, 0.0),
1464				})
1465				.collect();
1466			(coords, (0..g.components.len() as i64).collect())
1467		} else {
1468			let (coords, end_pts, _) = self.coordinates(gid, order, false)?;
1469			(coords, end_pts)
1470		};
1471		// `_getPhantomPoints`.
1472		let g = self.glyph(gid, order)?;
1473		let missing = || key_error(order, gid);
1474		let &(advance, lsb) = h_metrics.get(&gid).ok_or_else(missing)?;
1475		let left = (g.x_min - i64::from(lsb)) as f64;
1476		let right = left + f64::from(advance);
1477		let (top, bottom) = match v_metrics.filter(|m| !m.is_empty()) {
1478			Some(metrics) => {
1479				let &(advance, tsb) = metrics.get(&gid).ok_or_else(missing)?;
1480				let top = (i64::from(tsb) + g.y_max) as f64;
1481				(top, top - f64::from(advance))
1482			}
1483			None => (0.0, 0.0),
1484		};
1485		coords.extend([(left, 0.0), (right, 0.0), (0.0, top), (0.0, bottom)]);
1486		for c in &mut coords {
1487			*c = (ot_round(c.0) as f64, ot_round(c.1) as f64);
1488		}
1489		Ok((coords, end_pts))
1490	}
1491
1492	/// `_setCoordinates`: sets the coordinates of a glyph, which end with the four
1493	/// phantom points, and from those and its bounds the metrics.
1494	pub fn set_coordinates(
1495		&mut self,
1496		gid: u32,
1497		order: &GlyphOrder,
1498		coords: &[(f64, f64)],
1499		h_metrics: &mut BTreeMap<u32, (u16, i16)>,
1500		v_metrics: Option<&mut BTreeMap<u32, (u16, i16)>>,
1501	) -> Result<()> {
1502		let Some(split) = coords.len().checked_sub(4) else {
1503			return Err(Error::Assertion("len(coord) >= 4".into()));
1504		};
1505		let (points, phantoms) = coords.split_at(split);
1506		let (left, right, top, bottom) =
1507			(phantoms[0].0, phantoms[1].0, phantoms[2].1, phantoms[3].1);
1508		// Whole numbers are integers, as `GlyphCoordinates.__getitem__` gives them.
1509		let number = |v: f64| {
1510			if v.fract() == 0.0 {
1511				Number::Int(v as i64)
1512			} else {
1513				Number::Float(v)
1514			}
1515		};
1516		let g = self
1517			.glyphs
1518			.get_mut(&gid)
1519			.ok_or_else(|| key_error(order, gid))?;
1520		g.data = None;
1521		if g.is_composite() {
1522			if points.len() != g.components.len() {
1523				return Err(Error::Assertion(
1524					"len(coord) == len(glyph.components)".into(),
1525				));
1526			}
1527			for (p, c) in points.iter().zip(&mut g.components) {
1528				if let ComponentPlacement::Offset { x, y } = &mut c.placement {
1529					*x = number(p.0);
1530					*y = number(p.1);
1531				}
1532			}
1533		} else if g.number_of_contours == 0 {
1534			if !points.is_empty() {
1535				return Err(Error::Assertion("len(coord) == 0".into()));
1536			}
1537		} else {
1538			if points.len() != g.coordinates.len() {
1539				return Err(Error::Assertion(
1540					"len(coord) == len(glyph.coordinates)".into(),
1541				));
1542			}
1543			g.coordinates = points.to_vec();
1544		}
1545		self.recalc_bounds(gid, order, &mut HashSet::new(), &mut vec![gid])?;
1546		let g = self.glyph(gid, order)?;
1547		let advance = ot_round(right - left).max(0);
1548		let lsb = ot_round(g.x_min as f64 - left);
1549		h_metrics.insert(gid, (fit(advance, "advanceWidth")?, fit(lsb, "lsb")?));
1550		if let Some(metrics) = v_metrics {
1551			let advance = ot_round(top - bottom).max(0);
1552			let tsb = ot_round(top - g.y_max as f64);
1553			metrics.insert(gid, (fit(advance, "advanceHeight")?, fit(tsb, "tsb")?));
1554		}
1555		Ok(())
1556	}
1557
1558	/// `recalcBounds`.
1559	fn recalc_bounds(
1560		&mut self,
1561		gid: u32,
1562		order: &GlyphOrder,
1563		done: &mut HashSet<u32>,
1564		visiting: &mut Vec<u32>,
1565	) -> Result<()> {
1566		let g = self.glyph(gid, order)?;
1567		if g.is_composite()
1568			&& g.components
1569				.iter()
1570				.all(GlyphComponent::has_only_integer_translate)
1571		{
1572			let components = g.components.clone();
1573			let mut bounds: Option<[f64; 4]> = None;
1574			let mut float = false;
1575			for c in &components {
1576				if !done.contains(&c.glyph) {
1577					self.glyph(c.glyph, order)?;
1578					if visiting.contains(&c.glyph) {
1579						return Err(recursion_error(order, c.glyph));
1580					}
1581					visiting.push(c.glyph);
1582					self.recalc_bounds(c.glyph, order, done, visiting)?;
1583					visiting.pop();
1584					done.insert(c.glyph);
1585				}
1586				let cg = self.glyph(c.glyph, order)?;
1587				// Empty components do not count.
1588				if cg.y_min == cg.y_max && cg.x_min == cg.x_max {
1589					continue;
1590				}
1591				let ComponentPlacement::Offset { x, y } = c.placement else {
1592					continue;
1593				};
1594				float |= matches!(x, Number::Float(_)) || matches!(y, Number::Float(_));
1595				let (x, y) = (x.value(), y.value());
1596				for (px, py) in [
1597					(cg.x_min as f64 + x, cg.y_min as f64 + y),
1598					(cg.x_max as f64 + x, cg.y_max as f64 + y),
1599				] {
1600					bounds = Some(match bounds {
1601						None => [px, py, px, py],
1602						Some(b) => [b[0].min(px), b[1].min(py), b[2].max(px), b[3].max(py)],
1603					});
1604				}
1605			}
1606			if float && bounds.is_some() {
1607				// LENIENT(L13): fontTools stores float bounds here, and fails later
1608				// when packing the glyph header.
1609				return Err(Error::Struct("required argument is not an integer".into()));
1610			}
1611			let b = bounds.unwrap_or([0.0; 4]);
1612			let g = self
1613				.glyphs
1614				.get_mut(&gid)
1615				.ok_or_else(|| key_error(order, gid))?;
1616			g.x_min = b[0] as i64;
1617			g.y_min = b[1] as i64;
1618			g.x_max = b[2] as i64;
1619			g.y_max = b[3] as i64;
1620			return Ok(());
1621		}
1622		let (coords, _, _) = {
1623			let mut cache = HashMap::new();
1624			let mut v = visiting.clone();
1625			v.push(gid);
1626			self.flatten(gid, order, true, &mut cache, &mut v)?
1627		};
1628		let b = calc_bounds(&coords);
1629		let g = self
1630			.glyphs
1631			.get_mut(&gid)
1632			.ok_or_else(|| key_error(order, gid))?;
1633		g.x_min = ot_round(b[0]);
1634		g.y_min = ot_round(b[1]);
1635		g.x_max = ot_round(b[2]);
1636		g.y_max = ot_round(b[3]);
1637		Ok(())
1638	}
1639
1640	/// `Glyph.compile`.
1641	fn compile_glyph(
1642		&mut self,
1643		gid: u32,
1644		order: &GlyphOrder,
1645		recalc: bool,
1646		done: &mut HashSet<u32>,
1647		optimize_size: bool,
1648	) -> Result<Vec<u8>> {
1649		let g = self.glyph(gid, order)?;
1650		if let Some(data) = &g.data {
1651			if !recalc {
1652				return Ok(data.clone());
1653			}
1654			// The glyph must be expanded to recalculate its bounding box.
1655			if let Some(g) = self.glyphs.get_mut(&gid) {
1656				g.data = None;
1657			}
1658		}
1659		let g = self.glyph(gid, order)?;
1660		if g.number_of_contours == 0 && g.program.as_ref().is_none_or(Program::is_empty) {
1661			return Ok(Vec::new());
1662		}
1663		if recalc {
1664			self.recalc_bounds(gid, order, done, &mut vec![gid])?;
1665		}
1666		let g = self.glyph(gid, order)?;
1667		let mut data = Vec::new();
1668		for v in [g.number_of_contours, g.x_min, g.y_min, g.x_max, g.y_max] {
1669			data.extend_from_slice(&i16_of(v)?.to_be_bytes());
1670		}
1671		if g.is_composite() {
1672			data.extend(g.compile_components(order.len(), self.extended)?);
1673		} else if g.number_of_contours == 0 {
1674			let p = g
1675				.program
1676				.as_ref()
1677				.map(|p| p.bytecode.as_slice())
1678				.unwrap_or_default();
1679			data.extend_from_slice(&u16_of(p.len() as i64)?.to_be_bytes());
1680			data.extend_from_slice(p);
1681		} else {
1682			data.extend(g.compile_coordinates(self.extended, optimize_size)?);
1683		}
1684		Ok(data)
1685	}
1686
1687	/// `glyfTable[name].compile(glyfTable, recalcBBoxes)`: the binary data of a
1688	/// glyph, with its bounding box recalculated first if `recalc_bboxes`.
1689	pub fn glyph_data(
1690		&mut self,
1691		gid: u32,
1692		order: &GlyphOrder,
1693		recalc_bboxes: bool,
1694	) -> Result<Vec<u8>> {
1695		self.glyph_data_ext(gid, order, recalc_bboxes, true)
1696	}
1697
1698	/// [`Glyf::glyph_data`], with the coordinates packed for size if
1699	/// `optimize_size` (the default), else for speed (`compile(glyfTable,
1700	/// recalcBBoxes, optimizeSize=optimize_size)`).
1701	pub fn glyph_data_ext(
1702		&mut self,
1703		gid: u32,
1704		order: &GlyphOrder,
1705		recalc_bboxes: bool,
1706		optimize_size: bool,
1707	) -> Result<Vec<u8>> {
1708		self.compile_glyph(
1709			gid,
1710			order,
1711			recalc_bboxes,
1712			&mut HashSet::new(),
1713			optimize_size,
1714		)
1715	}
1716
1717	/// `glyfTable[name].recalcBounds(glyfTable)`.
1718	pub fn recalc_glyph_bounds(&mut self, gid: u32, order: &GlyphOrder) -> Result<()> {
1719		self.recalc_bounds(gid, order, &mut HashSet::new(), &mut vec![gid])
1720	}
1721
1722	/// `getCompositeMaxpValues`: points, contours and component depth of a
1723	/// flattened composite glyph.
1724	pub fn composite_maxp_values(
1725		&self,
1726		gid: u32,
1727		order: &GlyphOrder,
1728		depth: i64,
1729		cache: &mut HashMap<u32, (usize, usize, i64)>,
1730		visiting: &mut Vec<u32>,
1731	) -> Result<(usize, usize, i64)> {
1732		let g = self.glyph(gid, order)?;
1733		let (mut points, mut contours) = (0, 0);
1734		let mut max_depth = depth;
1735		for c in &g.components {
1736			let base = self.glyph(c.glyph, order)?;
1737			let (p, n) = if base.number_of_contours == 0 {
1738				continue;
1739			} else if base.number_of_contours > 0 {
1740				base.maxp_values()
1741			} else {
1742				let offset = depth + 1;
1743				let (p, n, d) = match cache.get(&c.glyph) {
1744					Some(&(p, n, d)) => (p, n, d + offset),
1745					None => {
1746						if visiting.contains(&c.glyph) {
1747							return Err(Error::ttlib(
1748								"RecursionError: maximum recursion depth exceeded",
1749							));
1750						}
1751						visiting.push(c.glyph);
1752						let (p, n, d) =
1753							self.composite_maxp_values(c.glyph, order, offset, cache, visiting)?;
1754						visiting.pop();
1755						cache.insert(c.glyph, (p, n, d - offset));
1756						(p, n, d)
1757					}
1758				};
1759				max_depth = max_depth.max(d);
1760				(p, n)
1761			};
1762			points += p;
1763			contours += n;
1764		}
1765		Ok((points, contours, max_depth))
1766	}
1767}
1768
1769/// Moves every point by `(x, y)` (`GlyphCoordinates.translate`, and `+=`/`-=`
1770/// with a tuple).
1771pub fn translate(coords: &mut [(f64, f64)], (x, y): (f64, f64)) {
1772	if x == 0.0 && y == 0.0 {
1773		return;
1774	}
1775	for p in coords {
1776		p.0 += x;
1777		p.1 += y;
1778	}
1779}
1780
1781/// Scales every point by `(x, y)` (`GlyphCoordinates.scale`, and `*=`/`/=`
1782/// with a tuple or a number).
1783pub fn scale(coords: &mut [(f64, f64)], (x, y): (f64, f64)) {
1784	if x == 1.0 && y == 1.0 {
1785		return;
1786	}
1787	for p in coords {
1788		p.0 *= x;
1789		p.1 *= y;
1790	}
1791}
1792
1793/// Applies the 2×2 matrix `t` to every point (`GlyphCoordinates.transform`).
1794pub fn transform(coords: &mut [(f64, f64)], t: [[f64; 2]; 2]) {
1795	for p in coords {
1796		let (x, y) = *p;
1797		*p = (x * t[0][0] + y * t[1][0], x * t[0][1] + y * t[1][1]);
1798	}
1799}
1800
1801/// Python indexing: negative indices count from the end.
1802fn py_index(coords: &[(f64, f64)], i: i64) -> Result<(f64, f64)> {
1803	let n = coords.len() as i64;
1804	let at = if i < 0 { i + n } else { i };
1805	usize::try_from(at)
1806		.ok()
1807		.and_then(|at| coords.get(at).copied())
1808		.ok_or_else(|| Error::ttlib("IndexError: array index out of range"))
1809}
1810
1811/// `calcBounds`: (0, 0, 0, 0) for no points.
1812fn calc_bounds(coords: &[(f64, f64)]) -> [f64; 4] {
1813	let Some(&(x0, y0)) = coords.first() else {
1814		return [0.0; 4];
1815	};
1816	coords.iter().fold([x0, y0, x0, y0], |b, &(x, y)| {
1817		[b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]
1818	})
1819}
1820
1821/// `remapComponentsFast`: maps the component glyphs of compact glyph data.
1822fn remap_components_fast(
1823	data: &mut [u8],
1824	extended: bool,
1825	f: &mut dyn FnMut(u32) -> Result<u32>,
1826) -> Result<()> {
1827	if data.len() < 2 || i16::from_be_bytes([data[0], data[1]]) >= 0 {
1828		// Not composite.
1829		return Ok(());
1830	}
1831	let byte = |data: &[u8], i: usize| -> Result<i64> {
1832		data.get(i)
1833			.map(|&b| i64::from(b))
1834			.ok_or_else(|| Error::ttlib("IndexError: bytearray index out of range"))
1835	};
1836	let mut i = 10;
1837	loop {
1838		let flags = (byte(data, i)? << 8) | byte(data, i + 1)?;
1839		let start = i + 2;
1840		// The size of the glyph ID stays, whatever the new glyph ID is.
1841		let size = if extended && flags & GID_IS_24_BIT != 0 {
1842			3
1843		} else {
1844			2
1845		};
1846		let mut gid = 0;
1847		for k in 0..size {
1848			gid = (gid << 8) | byte(data, start + k)?;
1849		}
1850		let new = f(gid as u32)?;
1851		if new >> (8 * size) != 0 {
1852			return Err(Error::value("OverflowError: int too big to convert"));
1853		}
1854		data[start..start + size].copy_from_slice(&new.to_be_bytes()[4 - size..]);
1855		i = start + size;
1856		i += if flags & ARG_1_AND_2_ARE_WORDS != 0 {
1857			4
1858		} else {
1859			2
1860		};
1861		if flags & WE_HAVE_A_SCALE != 0 {
1862			i += 2;
1863		} else if flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
1864			i += 4;
1865		} else if flags & WE_HAVE_A_TWO_BY_TWO != 0 {
1866			i += 8;
1867		}
1868		if flags & MORE_COMPONENTS == 0 {
1869			return Ok(());
1870		}
1871	}
1872}
1873
1874impl Glyph {
1875	/// `trim`: removes padding and, if asked, hinting, without expanding the
1876	/// glyph.
1877	pub fn trim(&mut self, remove_hinting: bool) -> Result<()> {
1878		self.trim_ext(remove_hinting, false)
1879	}
1880
1881	/// [`Glyph::trim`] for `glyf` or the `extended` `GLYF`.
1882	pub fn trim_ext(&mut self, remove_hinting: bool, extended: bool) -> Result<()> {
1883		let Some(data) = self.data.as_mut() else {
1884			if remove_hinting {
1885				if self.is_composite() {
1886					self.program = None;
1887				} else {
1888					self.program = Some(Program::from_bytecode(&[]));
1889				}
1890			}
1891			// No padding to trim.
1892			return Ok(());
1893		};
1894		if data.is_empty() {
1895			return Ok(());
1896		}
1897		let num_contours = self.trim_data(remove_hinting, extended)?;
1898		if remove_hinting {
1899			// Keep the parsed fields in step with the compact data, which is what
1900			// fontTools expands the glyph from later: without instructions, a
1901			// simple glyph has an empty program, the others none.
1902			self.program = (num_contours > 0).then(|| Program::from_bytecode(&[]));
1903		}
1904		Ok(())
1905	}
1906
1907	/// The part of [`Glyph::trim_ext`] that edits the compact data; returns the
1908	/// number of contours.
1909	fn trim_data(&mut self, remove_hinting: bool, extended: bool) -> Result<i16> {
1910		let Some(data) = self.data.as_mut() else {
1911			return Ok(0);
1912		};
1913		let err = || Error::ttlib("IndexError: bytearray index out of range");
1914		let at = |data: &[u8], i: usize| data.get(i).map(|&b| usize::from(b)).ok_or_else(err);
1915		let num_contours = i16::from_be_bytes([data[0], *data.get(1).ok_or_else(err)?]);
1916		let mut i = 10;
1917		if num_contours == 0 {
1918			// No contour end points or flags in this case.
1919			if !remove_hinting && data.len() >= i + 2 {
1920				let instruction_len = (at(data, i)? << 8) | at(data, i + 1)?;
1921				i += 2 + instruction_len;
1922			}
1923			data.truncate(i);
1924			return Ok(num_contours);
1925		}
1926		if num_contours >= 0 {
1927			i += 2 * num_contours as usize;
1928			let n_coordinates = ((at(data, i - 2)? << 8) | at(data, i - 1)?) + 1;
1929			let instruction_len = (at(data, i)? << 8) | at(data, i + 1)?;
1930			if remove_hinting {
1931				// Zero the instruction length and splice the instructions out.
1932				data[i] = 0;
1933				data[i + 1] = 0;
1934				i += 2;
1935				if instruction_len > 0 {
1936					let end = (i + instruction_len).min(data.len());
1937					data.drain(i..end);
1938				}
1939			} else {
1940				i += 2 + instruction_len;
1941			}
1942			let mut coord_bytes = 0;
1943			let mut j = 0;
1944			loop {
1945				let flag = at(data, i)? as u8;
1946				i += 1;
1947				let mut repeat = 1;
1948				if flag & FLAG_REPEAT != 0 {
1949					repeat = at(data, i)? + 1;
1950					i += 1;
1951				}
1952				let x_bytes = if flag & FLAG_X_SHORT != 0 {
1953					1
1954				} else if flag & FLAG_X_SAME == 0 {
1955					2
1956				} else {
1957					0
1958				};
1959				let y_bytes = if flag & FLAG_Y_SHORT != 0 {
1960					1
1961				} else if flag & FLAG_Y_SAME == 0 {
1962					2
1963				} else {
1964					0
1965				};
1966				coord_bytes += (x_bytes + y_bytes) * repeat;
1967				j += repeat;
1968				if j >= n_coordinates {
1969					break;
1970				}
1971			}
1972			if j != n_coordinates {
1973				return Err(Error::Assertion("bad glyph flags".into()));
1974			}
1975			i += coord_bytes;
1976			// Remove padding.
1977			data.truncate(i);
1978		} else if num_contours == -1 {
1979			let mut we_have_instructions = false;
1980			loop {
1981				let mut flags = ((at(data, i)? << 8) | at(data, i + 1)?) as i64;
1982				if remove_hinting {
1983					flags &= !WE_HAVE_INSTRUCTIONS;
1984				}
1985				if flags & WE_HAVE_INSTRUCTIONS != 0 {
1986					we_have_instructions = true;
1987				}
1988				data[i] = (flags >> 8) as u8;
1989				data[i + 1] = flags as u8;
1990				i += if extended && flags & GID_IS_24_BIT != 0 {
1991					5
1992				} else {
1993					4
1994				};
1995				i += if flags & ARG_1_AND_2_ARE_WORDS != 0 {
1996					4
1997				} else {
1998					2
1999				};
2000				if flags & WE_HAVE_A_SCALE != 0 {
2001					i += 2;
2002				} else if flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
2003					i += 4;
2004				} else if flags & WE_HAVE_A_TWO_BY_TWO != 0 {
2005					i += 8;
2006				}
2007				if flags & MORE_COMPONENTS == 0 {
2008					break;
2009				}
2010			}
2011			if we_have_instructions {
2012				let instruction_len = (at(data, i)? << 8) | at(data, i + 1)?;
2013				i += 2 + instruction_len;
2014			}
2015			// Remove padding.
2016			data.truncate(i);
2017		}
2018		Ok(num_contours)
2019	}
2020}
2021
2022/// `_is_mid_point`: whether `p1` is halfway between `p0` and `p2`, before or
2023/// after rounding.
2024fn is_mid_point(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64)) -> bool {
2025	use fontoxide_misc::py::is_close;
2026	let mid = ((p0.0 + p2.0) * 0.5, (p0.1 + p2.1) * 0.5);
2027	if is_close(mid.0, p1.0) && is_close(mid.1, p1.1) {
2028		return true;
2029	}
2030	let r = |p: (f64, f64)| (ot_round(p.0), ot_round(p.1));
2031	let (r0, r1, r2) = (r(p0), r(p1), r(p2));
2032	r0.0 + r2.0 == r1.0 * 2 && r0.1 + r2.1 == r1.1 * 2
2033}
2034
2035/// `dropImpliedOnCurvePoints`: removes the on-curve points that are halfway
2036/// between two off-curve points, in place. Several glyphs are taken as
2037/// interpolatable masters: only the points impliable in all of them are
2038/// dropped. Composite and empty glyphs are skipped. Returns the indices of
2039/// the dropped points.
2040pub fn drop_implied_on_curve_points(
2041	glyphs: &mut [&mut Glyph],
2042) -> Result<std::collections::BTreeSet<usize>> {
2043	use std::collections::BTreeSet;
2044	let mut statics: Option<(i64, Vec<u8>, Vec<i64>)> = None;
2045	let mut drop: Option<BTreeSet<usize>> = None;
2046	let mut simple = Vec::new();
2047	for (index, glyph) in glyphs.iter().enumerate() {
2048		if glyph.number_of_contours < 1 {
2049			// Composite or empty.
2050			continue;
2051		}
2052		match &statics {
2053			None => {
2054				statics = Some((
2055					glyph.number_of_contours,
2056					glyph.flags.clone(),
2057					glyph.end_pts_of_contours.clone(),
2058				))
2059			}
2060			Some((n, flags, ends)) => {
2061				let mismatch = if *n != glyph.number_of_contours {
2062					Some("numberOfContours")
2063				} else if *flags != glyph.flags {
2064					Some("flags")
2065				} else if *ends != glyph.end_pts_of_contours {
2066					Some("endPtsOfContours")
2067				} else {
2068					None
2069				};
2070				if let Some(attr) = mismatch {
2071					return Err(Error::value(format!(
2072						"Incompatible {attr} for glyph at master index {index}"
2073					)));
2074				}
2075			}
2076		}
2077		let Some((_, flags, ends)) = &statics else {
2078			continue;
2079		};
2080		let flag = |i: usize| flags.get(i).copied().unwrap_or(0);
2081		let coords = &glyph.coordinates;
2082		let mut may_drop = BTreeSet::new();
2083		let mut start = 0usize;
2084		for &last in ends {
2085			let last = usize::try_from(last).unwrap_or(0);
2086			for i in start..=last {
2087				if flag(i) & FLAG_ON_CURVE == 0 {
2088					continue;
2089				}
2090				let prv = if i > start { i - 1 } else { last };
2091				let nxt = if i < last { i + 1 } else { start };
2092				if flag(prv) & FLAG_ON_CURVE != 0 || flag(prv) != flag(nxt) {
2093					continue;
2094				}
2095				// The on-curve point may go if halfway between its neighbors.
2096				let (Some(&a), Some(&b), Some(&c)) =
2097					(coords.get(prv), coords.get(i), coords.get(nxt))
2098				else {
2099					continue;
2100				};
2101				if !is_mid_point(a, b, c) {
2102					continue;
2103				}
2104				may_drop.insert(i);
2105			}
2106			start = last + 1;
2107		}
2108		// Only the points impliable in all the glyphs are dropped.
2109		drop = Some(match drop {
2110			None => may_drop,
2111			Some(d) => d.intersection(&may_drop).copied().collect(),
2112		});
2113		simple.push(index);
2114	}
2115
2116	let drop = drop.unwrap_or_default();
2117	if drop.is_empty() {
2118		return Ok(drop);
2119	}
2120	let Some((_, flags, ends)) = statics else {
2121		return Ok(drop);
2122	};
2123	let new_flags: Vec<u8> = flags
2124		.iter()
2125		.enumerate()
2126		.filter(|(i, _)| !drop.contains(i))
2127		.map(|(_, &f)| f)
2128		.collect();
2129	let mut new_ends = Vec::with_capacity(ends.len());
2130	let mut i = 0;
2131	let mut delta = 0;
2132	for &d in &drop {
2133		while i < ends.len() && d as i64 > ends[i] {
2134			new_ends.push(ends[i] - delta);
2135			i += 1;
2136		}
2137		delta += 1;
2138	}
2139	while i < ends.len() {
2140		new_ends.push(ends[i] - delta);
2141		i += 1;
2142	}
2143	for index in simple {
2144		let glyph = &mut glyphs[index];
2145		glyph.coordinates = glyph
2146			.coordinates
2147			.iter()
2148			.enumerate()
2149			.filter(|(i, _)| !drop.contains(i))
2150			.map(|(_, &p)| p)
2151			.collect();
2152		glyph.flags = new_flags.clone();
2153		glyph.end_pts_of_contours = new_ends.clone();
2154		glyph.data = None;
2155	}
2156	Ok(drop)
2157}
2158
2159impl TableType for Glyf {
2160	const TAG: Tag = Tag::new(b"glyf");
2161	const COMPANION: Option<Tag> = Some(Tag::new(b"GLYF"));
2162
2163	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
2164		Self::decompile_as(Self::TAG, data, font)
2165	}
2166
2167	fn new_as(tag: Tag) -> Self {
2168		Glyf {
2169			extended: tag == Tag::new(b"GLYF"),
2170			..Default::default()
2171		}
2172	}
2173
2174	fn decompile_as(tag: Tag, data: &[u8], font: &mut Font) -> Result<Self> {
2175		let extended = tag == Tag::new(b"GLYF");
2176		let locations = font.require_locked::<Loca>(extended)?.locations().to_vec();
2177		let order = font.glyph_order()?;
2178		let mut pos = *locations
2179			.first()
2180			.ok_or_else(|| Error::ttlib("IndexError: array index out of range"))?
2181			as usize;
2182		let mut next = 0;
2183		let mut noname = 0;
2184		let mut glyphs = BTreeMap::new();
2185		for i in 0..locations.len() - 1 {
2186			if i >= order.len() {
2187				noname += 1;
2188			}
2189			next = locations[i + 1] as usize;
2190			let glyph_data = data.get(pos..next).filter(|d| d.len() == next - pos);
2191			let glyph_data = match glyph_data {
2192				Some(d) => d,
2193				None if next == pos => &[][..],
2194				None => return Err(Error::ttlib("not enough 'glyf' table data")),
2195			};
2196			let mut glyph = Glyph::decompile_ext(glyph_data, order.len(), extended)?;
2197			glyph.data = Some(glyph_data.to_vec());
2198			glyphs.insert(i as u32, glyph);
2199			pos = next;
2200		}
2201		if data.len() as i64 - next as i64 >= 4 {
2202			log::warn!(
2203				"too much 'glyf' table data: expected {next}, received {} bytes",
2204				data.len()
2205			);
2206		}
2207		if noname > 0 {
2208			log::warn!("{noname} glyphs have no name");
2209		}
2210		Ok(Glyf {
2211			glyphs,
2212			padding: 1,
2213			extended,
2214		})
2215	}
2216}
2217
2218impl Table for Glyf {
2219	/// Expands every glyph (`ensureDecompiled`).
2220	fn ensure_decompiled(&mut self) {
2221		for g in self.glyphs.values_mut() {
2222			g.data = None;
2223		}
2224	}
2225
2226	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
2227		let mut glyphs = BTreeMap::new();
2228		for (g, mut glyph) in std::mem::take(&mut self.glyphs) {
2229			for c in &mut glyph.components {
2230				c.glyph = f(c.glyph)?;
2231			}
2232			if let Some(data) = &mut glyph.data {
2233				remap_components_fast(data, self.extended, f)?;
2234			}
2235			glyphs.insert(f(g)?, glyph);
2236		}
2237		self.glyphs = glyphs;
2238		Ok(())
2239	}
2240
2241	fn tag(&self) -> Tag {
2242		Font::locked_tag::<Self>(self.extended)
2243	}
2244
2245	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
2246		let order = font.glyph_order()?;
2247		let padding = self.padding as usize;
2248		if ![0, 1, 2, 4].contains(&padding) {
2249			return Err(Error::Assertion("padding in (0, 1, 2, 4)".into()));
2250		}
2251		let recalc = font.recalc_bboxes;
2252		let optimize_size = !font.optimize_font_speed;
2253		let mut done = HashSet::new();
2254		let mut data_list = Vec::with_capacity(order.len());
2255		for gid in 0..order.len() as u32 {
2256			let mut d = self.compile_glyph(gid, &order, recalc, &mut done, optimize_size)?;
2257			if padding > 1 {
2258				d.resize(d.len().div_ceil(padding) * padding, 0);
2259			}
2260			data_list.push(d);
2261		}
2262		let total: usize = data_list.iter().map(Vec::len).sum();
2263		if padding == 1 && total < 0x20000 {
2264			// Pad odd-length glyphs if that allows short `loca` offsets.
2265			let odd = data_list.iter().filter(|d| d.len() % 2 == 1).count();
2266			if odd > 0 && total + odd < 0x20000 {
2267				for d in data_list.iter_mut().filter(|d| d.len() % 2 == 1) {
2268					d.push(0);
2269				}
2270			}
2271		}
2272		let mut locations = Vec::with_capacity(data_list.len() + 1);
2273		let mut at = 0u32;
2274		for d in &data_list {
2275			locations.push(at);
2276			at += d.len() as u32;
2277		}
2278		locations.push(at);
2279		let mut data = data_list.concat();
2280		let extended = self.extended;
2281		if let Some(loca) = font.get_locked::<Loca>(extended)? {
2282			loca.set(locations);
2283		}
2284		if let Some(maxp) = font.get_locked::<Maxp>(extended)?
2285			&& let Ok(n) = u32::try_from(self.glyphs.len())
2286		{
2287			maxp.num_glyphs = n;
2288		}
2289		if data.is_empty() {
2290			// An empty table would be rejected by OTS and Windows.
2291			data.push(0);
2292		}
2293		Ok(data)
2294	}
2295
2296	fn clone_table(&self) -> Box<dyn Table> {
2297		Box::new(self.clone())
2298	}
2299}
2300
2301impl TableXml for Glyf {
2302	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
2303		self.write_xml(writer, font, None)
2304	}
2305
2306	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
2307		if element.name != "TTGlyph" {
2308			return Ok(());
2309		}
2310		let name = element
2311			.attr("name")
2312			.ok_or_else(|| Error::ttx("KeyError: 'name'"))?;
2313		let gid = font.glyph_id(name)?;
2314		let mut glyph = Glyph::default();
2315		for (attr, field) in [
2316			("xMin", &mut glyph.x_min),
2317			("yMin", &mut glyph.y_min),
2318			("xMax", &mut glyph.x_max),
2319			("yMax", &mut glyph.y_max),
2320		] {
2321			let v = element.attr(attr).unwrap_or("0");
2322			// LENIENT(L13): fontTools keeps float bounds and fails when packing them.
2323			*field = eval(v)?
2324				.as_int()
2325				.ok_or_else(|| Error::value(format!("invalid {attr}: {v:?}")))
2326				.and_then(int64)?;
2327		}
2328		for e in element.elements() {
2329			glyph.read_xml(e, font, self.extended)?;
2330		}
2331		self.glyphs.insert(gid, glyph);
2332		Ok(())
2333	}
2334}