Skip to main content

fontoxide_ttlib/tables/
colr.rs

1//! `COLR`: Color table (`fontTools.ttLib.tables.C_O_L_R_`).
2
3use std::collections::BTreeMap;
4
5use fontoxide_misc::Tag;
6use fontoxide_misc::xml_reader::Element;
7use fontoxide_misc::xml_writer::XmlWriter;
8
9use crate::binary::fit;
10use crate::generated::ot;
11use crate::ot::table::{OtTable, XmlCtx};
12use crate::ot::{OtReader, WriterGraph};
13use fontoxide_misc::array_tools::quantize_rect;
14use fontoxide_misc::transform::{IDENTITY, Transform};
15use fontoxide_pens::{BoundsPen, Pen, TransformPen};
16
17use crate::glyph_set::GlyphSet;
18use crate::ot::colr::ClipList;
19use crate::ot::types::Paint;
20use crate::sstruct::eval;
21use crate::table::{Table, TableType, TableXml};
22use crate::{Error, Font, Result};
23
24/// A layer of a version 0 color glyph (`LayerRecord`): a glyph drawn in a
25/// palette color.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct LayerRecord {
28	/// The layer glyph (`name`).
29	pub glyph: u32,
30	/// The palette entry index (`colorID`).
31	pub color_id: u16,
32}
33
34/// Color table (`table_C_O_L_R_`).
35///
36/// Version 0 tables are read as [`Colr::color_layers`]; newer ones are kept as
37/// the otData table in [`Colr::table`]. When both are set, as can happen from
38/// TTX, the table wins. See
39/// <https://learn.microsoft.com/en-us/typography/opentype/spec/colr>.
40#[derive(Debug, Clone, Default, PartialEq)]
41pub struct Colr {
42	/// The table version.
43	pub version: u16,
44	/// The layers of each color glyph, for version 0 (`ColorLayers`).
45	pub color_layers: Option<BTreeMap<u32, Vec<LayerRecord>>>,
46	/// The otData table, for version 1 and later (`table`).
47	pub table: Option<ot::COLR>,
48}
49
50fn color_layers_v0(table: &ot::COLR) -> Result<BTreeMap<u32, Vec<LayerRecord>>> {
51	let Some(layer_array) = table.layer_record_array.as_deref() else {
52		return Ok(BTreeMap::new());
53	};
54	let layers = &layer_array.layer_record;
55	let base_array = table.base_glyph_record_array.as_deref().ok_or_else(|| {
56		Error::ttlib("AttributeError: 'NoneType' object has no attribute 'BaseGlyphRecord'")
57	})?;
58	let mut color_layers = BTreeMap::new();
59	for rec in &base_array.base_glyph_record {
60		let first = rec.first_layer_index as usize;
61		let end = first + rec.num_layers as usize;
62		if end > layers.len() {
63			return Err(Error::Assertion(
64				"firstLayerIndex + numLayers <= numLayerRecords".into(),
65			));
66		}
67		let list = layers[first..end]
68			.iter()
69			.map(|l| LayerRecord {
70				glyph: l.layer_glyph,
71				color_id: l.palette_index,
72			})
73			.collect();
74		color_layers.insert(rec.base_glyph, list);
75	}
76	Ok(color_layers)
77}
78
79fn no_paint() -> Error {
80	Error::ttlib("AttributeError: 'NoneType' object has no attribute 'Format'")
81}
82
83/// How deep [`compute_clip_box`] follows paints.
84///
85/// LENIENT(L38): fontTools does not end if `PaintColrGlyph`s or `PaintColrLayers`
86/// form a cycle; fontoxide fails instead.
87const MAX_PAINT_DEPTH: usize = 1000;
88
89/// `Paint.getTransform`.
90fn paint_transform(paint: &Paint) -> Result<Transform> {
91	let around = |cx: i16, cy: i16, t: &dyn Fn(Transform) -> Transform| {
92		let (cx, cy) = (f64::from(cx), f64::from(cy));
93		t(IDENTITY.translate(cx, cy)).translate(-cx, -cy)
94	};
95	Ok(match paint {
96		Paint::Format12(p) => {
97			let t = p.transform.as_deref().ok_or_else(|| {
98				Error::ttlib("AttributeError: 'NoneType' object has no attribute 'xx'")
99			})?;
100			Transform::new(t.xx, t.yx, t.xy, t.yy, t.dx, t.dy)
101		}
102		Paint::Format14(p) => IDENTITY.translate(f64::from(p.dx), f64::from(p.dy)),
103		Paint::Format16(p) => IDENTITY.scale(p.scale_x, Some(p.scale_y)),
104		Paint::Format18(p) => around(p.center_x, p.center_y, &|t| {
105			t.scale(p.scale_x, Some(p.scale_y))
106		}),
107		Paint::Format20(p) => IDENTITY.scale(p.scale, None),
108		Paint::Format22(p) => around(p.center_x, p.center_y, &|t| t.scale(p.scale, None)),
109		Paint::Format24(p) => IDENTITY.rotate(p.angle.to_radians()),
110		Paint::Format26(p) => around(p.center_x, p.center_y, &|t| t.rotate(p.angle.to_radians())),
111		Paint::Format28(p) => {
112			IDENTITY.skew((-p.x_skew_angle).to_radians(), p.y_skew_angle.to_radians())
113		}
114		Paint::Format30(p) => around(p.center_x, p.center_y, &|t| {
115			t.skew((-p.x_skew_angle).to_radians(), p.y_skew_angle.to_radians())
116		}),
117		Paint::Format3(_)
118		| Paint::Format5(_)
119		| Paint::Format7(_)
120		| Paint::Format9(_)
121		| Paint::Format13(_)
122		| Paint::Format15(_)
123		| Paint::Format17(_)
124		| Paint::Format19(_)
125		| Paint::Format21(_)
126		| Paint::Format23(_)
127		| Paint::Format25(_)
128		| Paint::Format27(_)
129		| Paint::Format29(_)
130		| Paint::Format31(_) => {
131			return Err(Error::ttlib(format!(
132				"NotImplementedError: Variable Paints not supported: {}",
133				paint.format().unwrap_or_default()
134			)));
135		}
136		_ => IDENTITY,
137	})
138}
139
140/// `Paint.iterPaintSubTables`: the child paints, the layers of a
141/// `PaintColrLayers` and the paint of the base glyph of a `PaintColrGlyph`.
142fn paint_sub_tables<'a>(colr: &'a ot::COLR, paint: &'a Paint) -> Result<Vec<&'a Paint>> {
143	let children: Vec<&Option<Box<Paint>>> = match paint {
144		Paint::Format1(p) => {
145			let layers = colr.layer_list.as_deref().map_or(&[][..], |l| &l.paint[..]);
146			let start = (p.first_layer_index as usize).min(layers.len());
147			let end = (start + p.num_layers as usize).min(layers.len());
148			layers[start..end].iter().collect()
149		}
150		Paint::Format11(p) => {
151			let records = colr
152				.base_glyph_list
153				.as_deref()
154				.map_or(&[][..], |l| &l.base_glyph_paint_record[..]);
155			let record = records
156				.iter()
157				.find(|r| r.base_glyph == p.glyph)
158				.ok_or_else(|| Error::ttlib("KeyError: glyph not in colr.BaseGlyphList"))?;
159			vec![&record.paint]
160		}
161		Paint::Format10(p) => vec![&p.paint],
162		Paint::Format12(p) => vec![&p.paint],
163		Paint::Format13(p) => vec![&p.paint],
164		Paint::Format14(p) => vec![&p.paint],
165		Paint::Format15(p) => vec![&p.paint],
166		Paint::Format16(p) => vec![&p.paint],
167		Paint::Format17(p) => vec![&p.paint],
168		Paint::Format18(p) => vec![&p.paint],
169		Paint::Format19(p) => vec![&p.paint],
170		Paint::Format20(p) => vec![&p.paint],
171		Paint::Format21(p) => vec![&p.paint],
172		Paint::Format22(p) => vec![&p.paint],
173		Paint::Format23(p) => vec![&p.paint],
174		Paint::Format24(p) => vec![&p.paint],
175		Paint::Format25(p) => vec![&p.paint],
176		Paint::Format26(p) => vec![&p.paint],
177		Paint::Format27(p) => vec![&p.paint],
178		Paint::Format28(p) => vec![&p.paint],
179		Paint::Format29(p) => vec![&p.paint],
180		Paint::Format30(p) => vec![&p.paint],
181		Paint::Format31(p) => vec![&p.paint],
182		Paint::Format32(p) => vec![&p.source_paint, &p.backdrop_paint],
183		Paint::Format33(p) => vec![&p.paint],
184		_ => Vec::new(),
185	};
186	children
187		.into_iter()
188		.map(|c| c.as_deref().ok_or_else(no_paint))
189		.collect()
190}
191
192/// `Paint.computeClipBox`: the control bounds of the glyphs that a paint
193/// draws, transformed as the paints above them say, quantized.
194fn compute_clip_box(
195	colr: &ot::COLR,
196	paint: &Paint,
197	glyph_set: &GlyphSet<'_>,
198	quantization: i64,
199) -> Result<Option<ot::ClipBox>> {
200	/// The paints from the root to `paint`, with their transforms: fontTools only
201	/// computes these (`getTransform`) when it reaches a glyph paint, so the
202	/// errors are kept until then.
203	fn walk<'a>(
204		colr: &'a ot::COLR,
205		paint: &'a Paint,
206		path: &mut Vec<&'a Paint>,
207		glyph_set: &GlyphSet<'_>,
208		pen: &mut dyn Pen,
209	) -> Result<()> {
210		if path.len() > MAX_PAINT_DEPTH {
211			return Err(Error::ttlib("RecursionError: COLR paint graph is too deep"));
212		}
213		path.push(paint);
214		let children = paint_sub_tables(colr, paint)?;
215		if let Paint::Format10(ot::PaintFormat10 { glyph, .. })
216		| Paint::Format33(ot::PaintFormat33 { glyph, .. }) = paint
217		{
218			let mut transformation = IDENTITY;
219			for p in path.iter() {
220				transformation = transformation.transform(&paint_transform(p)?);
221			}
222			let mut transform_pen = TransformPen::new(&mut *pen, transformation);
223			glyph_set.draw(&glyph_set.glyph_order().name(*glyph), &mut transform_pen)?;
224		}
225		for child in children {
226			walk(colr, child, path, glyph_set, pen)?;
227		}
228		path.pop();
229		Ok(())
230	}
231
232	let mut pen = BoundsPen::new_control_bounds(Some(glyph_set), false);
233	walk(colr, paint, &mut Vec::new(), glyph_set, &mut pen)?;
234	let Some(bounds) = pen.bounds() else {
235		return Ok(None);
236	};
237	let [x_min, y_min, x_max, y_max] = quantize_rect(bounds, quantization as f64)
238		.ok_or_else(|| Error::value("factor must be >= 1"))?;
239	Ok(Some(ot::ClipBox::Format1(ot::ClipBoxFormat1 {
240		x_min: fit(x_min, "xMin")?,
241		y_min: fit(y_min, "yMin")?,
242		x_max: fit(x_max, "xMax")?,
243		y_max: fit(y_max, "yMax")?,
244	})))
245}
246
247fn no_color_layers() -> Error {
248	Error::ttlib("AttributeError: 'table_C_O_L_R_' object has no attribute 'ColorLayers'")
249}
250
251impl Colr {
252	/// `_decompileColorLayersV0`.
253	pub fn decompile_color_layers_v0(table: &ot::COLR) -> Result<BTreeMap<u32, Vec<LayerRecord>>> {
254		color_layers_v0(table)
255	}
256
257	/// `populateCOLRv0`, with the base glyphs in glyph order.
258	pub fn populate_color_layers_v0(
259		table: &mut ot::COLR,
260		color_layers: &BTreeMap<u32, Vec<LayerRecord>>,
261	) -> Result<()> {
262		let mut base_records = Vec::new();
263		let mut layer_records = Vec::new();
264		for (&base_glyph, layers) in color_layers {
265			base_records.push(ot::BaseGlyphRecord {
266				base_glyph,
267				first_layer_index: fit(layer_records.len(), "FirstLayerIndex")?,
268				num_layers: fit(layers.len(), "NumLayers")?,
269			});
270			for l in layers {
271				layer_records.push(ot::LayerRecord {
272					layer_glyph: l.glyph,
273					palette_index: l.color_id,
274				});
275			}
276		}
277		table.base_glyph_record_count = Some(fit(base_records.len(), "BaseGlyphRecordCount")?);
278		table.layer_record_count = Some(fit(layer_records.len(), "LayerRecordCount")?);
279		table.base_glyph_record_array = (!base_records.is_empty()).then(|| {
280			Box::new(ot::BaseGlyphRecordArray {
281				base_glyph_record: base_records,
282			})
283		});
284		table.layer_record_array = (!layer_records.is_empty()).then(|| {
285			Box::new(ot::LayerRecordArray {
286				layer_record: layer_records,
287			})
288		});
289		Ok(())
290	}
291
292	/// Sets the clip box of each base glyph of a version 1 table to the
293	/// control bounds of its paint, quantized (`COLR.computeClipBoxes`). A glyph
294	/// set from [`GlyphSet::new`] draws the glyphs; version 0 tables are left
295	/// alone.
296	pub fn compute_clip_boxes(
297		&mut self,
298		glyph_set: &GlyphSet<'_>,
299		quantization: i64,
300	) -> Result<()> {
301		let Some(table) = &mut self.table else {
302			return Ok(());
303		};
304		if table.version == 0 {
305			return Ok(());
306		}
307		let records = &table
308			.base_glyph_list
309			.as_deref()
310			.ok_or_else(|| {
311				Error::ttlib(
312					"AttributeError: 'NoneType' object has no attribute 'BaseGlyphPaintRecord'",
313				)
314			})?
315			.base_glyph_paint_record;
316		let mut clips = BTreeMap::new();
317		for rec in records {
318			let clip_box = rec
319				.paint
320				.as_deref()
321				.ok_or_else(no_paint)
322				.and_then(|paint| compute_clip_box(table, paint, glyph_set, quantization))
323				.map_err(|e| {
324					Error::ttlib(format!(
325						"Failed to compute COLR ClipBox for '{}': {e}",
326						glyph_set.glyph_order().name(rec.base_glyph)
327					))
328				})?;
329			if let Some(clip_box) = clip_box {
330				clips.insert(rec.base_glyph, clip_box);
331			}
332		}
333		if clips.is_empty() {
334			table.clip_list = None;
335		} else {
336			let clip_list = table.clip_list.get_or_insert_with(|| {
337				Box::new(ClipList {
338					format: Some(1),
339					..Default::default()
340				})
341			});
342			clip_list.clips = clips;
343		}
344		Ok(())
345	}
346
347	/// `_toOTTable`.
348	fn to_ot_table(&self) -> Result<ot::COLR> {
349		let color_layers = self.color_layers.as_ref().ok_or_else(no_color_layers)?;
350		let mut table = ot::COLR {
351			version: self.version,
352			..Default::default()
353		};
354		Self::populate_color_layers_v0(&mut table, color_layers)?;
355		Ok(table)
356	}
357}
358
359impl TableType for Colr {
360	const TAG: Tag = Tag::new(b"COLR");
361
362	fn decompile(data: &[u8], font: &mut Font) -> Result<Self> {
363		let mut reader = OtReader::new(data, Self::TAG);
364		let table = ot::COLR::decompile(&mut reader, font)?;
365		Ok(if table.version == 0 {
366			Colr {
367				version: 0,
368				color_layers: Some(color_layers_v0(&table)?),
369				table: None,
370			}
371		} else {
372			Colr {
373				version: table.version,
374				color_layers: None,
375				table: Some(table),
376			}
377		})
378	}
379}
380
381impl Table for Colr {
382	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
383		if let Some(layers) = &mut self.color_layers {
384			let mut out = BTreeMap::new();
385			for (g, mut records) in std::mem::take(layers) {
386				for r in &mut records {
387					r.glyph = f(r.glyph)?;
388				}
389				out.insert(f(g)?, records);
390			}
391			*layers = out;
392		}
393		if let Some(table) = &mut self.table {
394			table.remap_glyphs(f)?;
395		}
396		Ok(())
397	}
398
399	fn tag(&self) -> Tag {
400		Self::TAG
401	}
402
403	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
404		let built;
405		let table = match &self.table {
406			Some(t) => t,
407			None => {
408				built = self.to_ot_table()?;
409				&built
410			}
411		};
412		let mut graph = WriterGraph::new(Self::TAG);
413		table.compile(&mut graph.root(), font)?;
414		graph.get_all_data()
415	}
416
417	fn clone_table(&self) -> Box<dyn Table> {
418		Box::new(self.clone())
419	}
420}
421
422impl TableXml for Colr {
423	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
424		if let Some(table) = &self.table {
425			return table.to_xml2(writer, font);
426		}
427		writer.simpletag("version", &[("value", &self.version)]);
428		writer.newline();
429		let color_layers = self.color_layers.as_ref().ok_or_else(no_color_layers)?;
430		let order = font.glyph_order()?.clone();
431		for (&base_glyph, layers) in color_layers {
432			writer.begintag("ColorGlyph", &[("name", &order.name(base_glyph))]);
433			writer.newline();
434			for layer in layers {
435				writer.simpletag(
436					"layer",
437					&[
438						("name", &order.name(layer.glyph)),
439						("colorID", &layer.color_id),
440					],
441				);
442				writer.newline();
443			}
444			writer.endtag("ColorGlyph");
445			writer.newline();
446		}
447		Ok(())
448	}
449
450	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
451		let attr = |e: &Element, name: &str| -> Result<String> {
452			e.attr(name)
453				.map(str::to_owned)
454				.ok_or_else(|| Error::ttx(format!("KeyError: {name:?}")))
455		};
456		// LENIENT(L7): fontTools keeps any value and fails when writing one that
457		// does not fit; values are range-checked here.
458		let int = |s: &str, name: &str| -> Result<u16> {
459			let v = eval(s)?
460				.as_int()
461				.ok_or_else(|| Error::value(format!("invalid {name}: {s:?}")))?;
462			fit(v, name)
463		};
464		match element.name.as_str() {
465			"version" => self.version = int(&attr(element, "value")?, "version")?,
466			"ColorGlyph" => {
467				let base_glyph = font.glyph_id(&attr(element, "name")?)?;
468				let mut layers = Vec::new();
469				for e in element.elements() {
470					layers.push(LayerRecord {
471						glyph: font.glyph_id(&attr(e, "name")?)?,
472						color_id: int(&attr(e, "colorID")?, "colorID")?,
473					});
474				}
475				self.color_layers
476					.get_or_insert_with(BTreeMap::new)
477					.insert(base_glyph, layers);
478			}
479			_ => {
480				let table = self.table.get_or_insert_with(ot::COLR::default);
481				let mut ctx = XmlCtx::default();
482				table.from_xml(element, font, &mut ctx)?;
483				table.populate_defaults(&mut ctx)?;
484				self.version = table.version;
485			}
486		}
487		Ok(())
488	}
489}