Skip to main content

fontoxide_ttlib/
reorder_glyphs.rs

1//! Reorder the glyphs of a font (`fontTools.ttLib.reorderGlyphs`).
2//!
3//! fontTools refers to glyphs by name, so most tables follow a new glyph order by
4//! themselves; here every table's glyph IDs are remapped instead
5//! ([`Font::remap_glyphs`]). What does not follow by itself is the same as in
6//! fontTools: the coverage tables of `GDEF`, `GPOS`, `GSUB` and `MATH`, which keep
7//! their order, are sorted again with the arrays parallel to them, and the
8//! charstrings of `CFF ` and `CFF2` are put in the new order.
9
10use std::collections::{BTreeSet, HashMap};
11
12use crate::generated::ot;
13use crate::ot::table::OtTable;
14use crate::ot::types::Coverage;
15use crate::tables::{Cff, Cff2, Gdef, Gpos, Gsub, Math};
16use crate::{Error, Font, Result, Tag};
17
18/// `repr(set)` of glyph names, sorted (the order of a Python set of strings
19/// depends on the hash seed).
20fn set_repr(names: &BTreeSet<&str>) -> String {
21	if names.is_empty() {
22		return "set()".into();
23	}
24	let items: Vec<String> = names
25		.iter()
26		.map(|n| fontoxide_misc::py::str_repr(n))
27		.collect();
28	format!("{{{}}}", items.join(", "))
29}
30
31/// Sorts a coverage by glyph ID, and the list parallel to it the same way
32/// (`ReorderCoverage` with a `parallel_list_attr`).
33fn sort_coverage<T>(coverage: &mut Option<Box<Coverage>>, parallel: &mut Vec<T>) -> Result<()> {
34	// A null offset, such as the `ExtendedShapeCoverage` or the
35	// `HorizGlyphCoverage` of a MATH table without extended shapes or horizontal
36	// variants: nothing to reorder.
37	let Some(coverage) = coverage else {
38		return Ok(());
39	};
40	if parallel.len() != coverage.glyphs.len() {
41		return Err(Error::Assertion("Nothing makes sense".into()));
42	}
43	let mut pairs: Vec<(u32, T)> = coverage.glyphs.drain(..).zip(parallel.drain(..)).collect();
44	pairs.sort_by_key(|p| p.0);
45	for (g, item) in pairs {
46		coverage.glyphs.push(g);
47		parallel.push(item);
48	}
49	Ok(())
50}
51
52/// Sorts a coverage by glyph ID (`ReorderCoverage` without a parallel list).
53fn sort_glyphs(coverage: &mut Option<Box<Coverage>>) -> Result<()> {
54	// A null offset: nothing to reorder (see `sort_coverage`).
55	if let Some(coverage) = coverage {
56		coverage.glyphs.sort_unstable();
57	}
58	Ok(())
59}
60
61/// Sorts each coverage of a list (`ReorderCoverage` of an attribute that is a list).
62fn sort_coverages(coverages: &mut [Option<Box<Coverage>>]) -> Result<()> {
63	for coverage in coverages {
64		sort_glyphs(coverage)?;
65	}
66	Ok(())
67}
68
69/// Sorts a list by the glyph of its items (`ReorderList`).
70fn sort_pairs<T>(list: &mut [T], key: impl Fn(&T) -> u32) -> Result<()> {
71	list.sort_by_key(key);
72	Ok(())
73}
74
75/// Applies `_REORDER_RULES` to one table of the layout tables.
76fn reorder(any: &mut dyn std::any::Any) -> Result<()> {
77	macro_rules! rules {
78		($($ty:ty => |$t:ident| $body:expr;)*) => {
79			$(if let Some($t) = any.downcast_mut::<$ty>() {
80				return $body;
81			})*
82		};
83	}
84	rules! {
85		// GPOS
86		ot::SinglePosFormat1 => |t| sort_glyphs(&mut t.coverage);
87		ot::SinglePosFormat3 => |t| sort_glyphs(&mut t.coverage);
88		ot::SinglePosFormat2 => |t| sort_coverage(&mut t.coverage, &mut t.value);
89		ot::SinglePosFormat4 => |t| sort_coverage(&mut t.coverage, &mut t.value);
90		ot::PairPosFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.pair_set);
91		ot::PairPosFormat3 => |t| sort_coverage(&mut t.coverage, &mut t.pair_set);
92		ot::PairSet => |t| sort_pairs(&mut t.pair_value_record, |r| r.second_glyph);
93		ot::PairSet2 => |t| sort_pairs(&mut t.pair_value_record, |r| r.second_glyph);
94		ot::PairPosFormat2 => |t| sort_glyphs(&mut t.coverage);
95		ot::PairPosFormat4 => |t| sort_glyphs(&mut t.coverage);
96		ot::CursivePosFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.entry_exit_record);
97		ot::CursivePosFormat2 => |t| sort_coverage(&mut t.coverage, &mut t.entry_exit_record);
98		ot::MarkBasePosFormat1 => |t| {
99			sort_coverage(&mut t.mark_coverage, mark_records(&mut t.mark_array)?)?;
100			sort_coverage(&mut t.base_coverage, &mut required(&mut t.base_array)?.base_record)
101		};
102		ot::MarkBasePosFormat2 => |t| {
103			sort_coverage(&mut t.mark_coverage, mark_records2(&mut t.mark_array)?)?;
104			sort_coverage(&mut t.base_coverage, &mut required(&mut t.base_array)?.base_record)
105		};
106		ot::MarkLigPosFormat1 => |t| {
107			sort_coverage(&mut t.mark_coverage, mark_records(&mut t.mark_array)?)?;
108			sort_coverage(
109				&mut t.ligature_coverage,
110				&mut required(&mut t.ligature_array)?.ligature_attach,
111			)
112		};
113		ot::MarkLigPosFormat2 => |t| {
114			sort_coverage(&mut t.mark_coverage, mark_records2(&mut t.mark_array)?)?;
115			sort_coverage(
116				&mut t.ligature_coverage,
117				&mut required(&mut t.ligature_array)?.ligature_attach,
118			)
119		};
120		ot::MarkMarkPosFormat1 => |t| {
121			sort_coverage(&mut t.mark1_coverage, mark_records(&mut t.mark1_array)?)?;
122			sort_coverage(&mut t.mark2_coverage, &mut required(&mut t.mark2_array)?.mark2_record)
123		};
124		ot::MarkMarkPosFormat2 => |t| {
125			sort_coverage(&mut t.mark1_coverage, mark_records2(&mut t.mark1_array)?)?;
126			sort_coverage(&mut t.mark2_coverage, &mut required(&mut t.mark2_array)?.mark2_record)
127		};
128		ot::ContextPosFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.pos_rule_set);
129		ot::ContextPosFormat2 => |t| sort_glyphs(&mut t.coverage);
130		ot::ContextPosFormat5 => |t| sort_glyphs(&mut t.coverage);
131		ot::ContextPosFormat3 => |t| sort_coverages(&mut t.coverage);
132		ot::ContextPosFormat6 => |t| sort_coverages(&mut t.coverage);
133		ot::ContextPosFormat4 => |t| sort_coverage(&mut t.coverage, &mut t.seq_rule_set);
134		ot::ChainContextPosFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.chain_pos_rule_set);
135		ot::ChainContextPosFormat2 => |t| sort_glyphs(&mut t.coverage);
136		ot::ChainContextPosFormat5 => |t| sort_glyphs(&mut t.coverage);
137		ot::ChainContextPosFormat3 => |t| {
138			sort_coverages(&mut t.backtrack_coverage)?;
139			sort_coverages(&mut t.input_coverage)?;
140			sort_coverages(&mut t.look_ahead_coverage)
141		};
142		ot::ChainContextPosFormat4 => |t| sort_coverage(&mut t.coverage, &mut t.chained_seq_rule_set);
143		// GSUB
144		ot::ContextSubstFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.sub_rule_set);
145		ot::ContextSubstFormat2 => |t| sort_glyphs(&mut t.coverage);
146		ot::ContextSubstFormat5 => |t| sort_glyphs(&mut t.coverage);
147		ot::ContextSubstFormat3 => |t| sort_coverages(&mut t.coverage);
148		ot::ContextSubstFormat6 => |t| sort_coverages(&mut t.coverage);
149		ot::ContextSubstFormat4 => |t| sort_coverage(&mut t.coverage, &mut t.seq_rule_set);
150		ot::ChainContextSubstFormat1 => |t| sort_coverage(&mut t.coverage, &mut t.chain_sub_rule_set);
151		ot::ChainContextSubstFormat2 => |t| sort_glyphs(&mut t.coverage);
152		ot::ChainContextSubstFormat5 => |t| sort_glyphs(&mut t.coverage);
153		ot::ChainContextSubstFormat3 => |t| {
154			sort_coverages(&mut t.backtrack_coverage)?;
155			sort_coverages(&mut t.input_coverage)?;
156			sort_coverages(&mut t.look_ahead_coverage)
157		};
158		ot::ChainContextSubstFormat4 => |t| sort_coverage(&mut t.coverage, &mut t.chained_seq_rule_set);
159		ot::ReverseChainSingleSubstFormat1 => |t| {
160			sort_coverage(&mut t.coverage, &mut t.substitute)?;
161			sort_coverages(&mut t.backtrack_coverage)?;
162			sort_coverages(&mut t.look_ahead_coverage)
163		};
164		ot::ReverseChainSingleSubstFormat2 => |t| {
165			sort_coverage(&mut t.coverage, &mut t.substitute)?;
166			sort_coverages(&mut t.backtrack_coverage)?;
167			sort_coverages(&mut t.look_ahead_coverage)
168		};
169		// GDEF
170		ot::AttachList => |t| sort_coverage(&mut t.coverage, &mut t.attach_point);
171		ot::LigCaretList => |t| sort_coverage(&mut t.coverage, &mut t.lig_glyph);
172		ot::LigCaretList2 => |t| sort_coverage(&mut t.coverage, &mut t.lig_glyph);
173		ot::MarkGlyphSetsDef => |t| sort_coverages(&mut t.coverage);
174		// MATH
175		ot::MathGlyphInfo => |t| sort_glyphs(&mut t.extended_shape_coverage);
176		ot::MathItalicsCorrectionInfo => |t| sort_coverage(&mut t.coverage, &mut t.italics_correction);
177		ot::MathTopAccentAttachment => |t| {
178			sort_coverage(&mut t.top_accent_coverage, &mut t.top_accent_attachment)
179		};
180		ot::MathKernInfo => |t| sort_coverage(&mut t.math_kern_coverage, &mut t.math_kern_info_records);
181		ot::MathVariants => |t| {
182			sort_coverage(&mut t.vert_glyph_coverage, &mut t.vert_glyph_construction)?;
183			sort_coverage(&mut t.horiz_glyph_coverage, &mut t.horiz_glyph_construction)
184		};
185	}
186	Ok(())
187}
188
189/// An array that the rule follows: fontTools fails without it.
190fn required<T>(table: &mut Option<Box<T>>) -> Result<&mut T> {
191	table
192		.as_deref_mut()
193		.ok_or_else(|| Error::ttlib("AttributeError: 'NoneType' object has no attribute"))
194}
195
196fn mark_records(array: &mut Option<Box<ot::MarkArray>>) -> Result<&mut Vec<ot::MarkRecord>> {
197	Ok(&mut required(array)?.mark_record)
198}
199
200fn mark_records2(array: &mut Option<Box<ot::MarkArray2>>) -> Result<&mut Vec<ot::MarkRecord2>> {
201	Ok(&mut required(array)?.mark_record)
202}
203
204fn reorder_table<T: OtTable>(table: &mut T) -> Result<()> {
205	table.visit_mut(&mut reorder)
206}
207
208/// Puts the charstrings of a CFF or CFF2 font set in the new glyph order, with the
209/// Top DICT's FDSelect, and sets its charset to it.
210///
211/// The charstrings keep the names they were read with (fontTools reads them
212/// before changing the glyph order: CFF2 has no charset, and takes the names
213/// from the font's glyph order).
214fn reorder_cff(
215	cff: &mut crate::cff::font::CffFontSet,
216	old_order: &[String],
217	new_order: &[String],
218) -> Result<()> {
219	let Some(top) = cff.top_dicts.first_mut() else {
220		return Ok(());
221	};
222	if let Some(fd_select) = &mut top.fd_select
223		&& !fd_select.gid_array.is_empty()
224	{
225		// `dict(zip(old_glyph_order, fd_select.gidArray))`
226		let mut glyph_to_fd: HashMap<&str, Option<i64>> = HashMap::new();
227		for (name, &fd) in old_order.iter().zip(&fd_select.gid_array) {
228			glyph_to_fd.insert(name.as_str(), fd);
229		}
230		fd_select.gid_array = new_order
231			.iter()
232			.filter_map(|g| glyph_to_fd.get(g.as_str()).copied())
233			.collect();
234	}
235	if let Some(cs) = &mut top.char_strings {
236		let index: HashMap<&str, usize> = cs
237			.names
238			.iter()
239			.enumerate()
240			.map(|(i, n)| (n.as_str(), i))
241			.collect();
242		let mut positions = Vec::with_capacity(new_order.len());
243		for name in new_order {
244			// fontTools stores `None` for a glyph without a charstring, which
245			// cannot be compiled.
246			let i = *index
247				.get(name.as_str())
248				.ok_or_else(|| Error::ttlib(format!("KeyError: {name:?}")))?;
249			positions.push(i);
250		}
251
252		cs.privates = positions.iter().map(|&i| cs.privates[i]).collect();
253		// The FDSelect read with the CharStrings INDEX goes with the charstrings
254		// (fontTools loads the private DICTs with the original FDSelect, then puts
255		// the INDEX in the new order with the Top DICT's FDSelect).
256		if let Some(fd) = &cs.fd_select {
257			let fd: Vec<Option<i64>> = positions
258				.iter()
259				.map(|&i| fd.get(i).copied().flatten())
260				.collect();
261			cs.fd_select = Some(fd);
262		}
263		cs.names = positions.iter().map(|&i| cs.names[i].clone()).collect();
264		cs.items = positions.iter().map(|&i| cs.items[i].clone()).collect();
265	}
266	top.charset = Some(new_order.to_vec());
267	Ok(())
268}
269
270/// Reorders the glyphs of a font (`reorderGlyphs`): sets the glyph order to
271/// `new_glyph_order`, which must have the same glyphs, and updates the tables
272/// that do not follow by themselves.
273///
274/// All tables are decompiled first.
275pub fn reorder_glyphs(font: &mut Font, new_glyph_order: Vec<String>) -> Result<()> {
276	let old_order = font.glyph_order()?;
277	if new_glyph_order.len() != old_order.len() {
278		return Err(Error::value(format!(
279			"New glyph order contains {} glyphs, but font has {} glyphs",
280			new_glyph_order.len(),
281			old_order.len()
282		)));
283	}
284	let old: BTreeSet<&str> = old_order.names().iter().map(String::as_str).collect();
285	let new: BTreeSet<&str> = new_glyph_order.iter().map(String::as_str).collect();
286	if old != new {
287		return Err(Error::value(format!(
288			"New glyph order does not contain the same set of glyphs as the font:\n\
289			 * only in new: {}\n\
290			 * only in old: {}",
291			set_repr(&new.difference(&old).copied().collect()),
292			set_repr(&old.difference(&new).copied().collect()),
293		)));
294	}
295
296	// Changing the order of glyphs requires that all tables that use glyph
297	// indexes have been fully decompiled.
298	font.ensure_decompiled()?;
299
300	let new_ids: HashMap<&str, u32> = new_glyph_order
301		.iter()
302		.enumerate()
303		.map(|(i, n)| (n.as_str(), i as u32))
304		.collect();
305	let map: Vec<u32> = old_order
306		.names()
307		.iter()
308		.map(|n| new_ids.get(n.as_str()).copied().unwrap_or(0))
309		.collect();
310	// A glyph past the glyph order is named `glyph<ID>` in fontTools, which stays
311	// the same glyph ID.
312	let mut f = |gid: u32| -> Result<u32> { Ok(map.get(gid as usize).copied().unwrap_or(gid)) };
313	font.remap_glyphs(&mut f, new_glyph_order.clone())?;
314
315	for tag in [b"GDEF", b"GPOS", b"GSUB", b"MATH"] {
316		let tag = Tag::new(tag);
317		if !font.contains(tag) {
318			continue;
319		}
320		let Some(table) = font.get_dyn(tag)? else {
321			continue;
322		};
323		let any = table.as_any_mut();
324		if let Some(t) = any.downcast_mut::<Gdef>() {
325			reorder_table(&mut t.table)?;
326		} else if let Some(t) = any.downcast_mut::<Gpos>() {
327			reorder_table(&mut t.table)?;
328		} else if let Some(t) = any.downcast_mut::<Gsub>() {
329			reorder_table(&mut t.table)?;
330		} else if let Some(t) = any.downcast_mut::<Math>() {
331			reorder_table(&mut t.table)?;
332		}
333	}
334
335	let old_names = old_order.names();
336	if let Some(t) = font.get::<Cff>()? {
337		reorder_cff(&mut t.cff, old_names, &new_glyph_order)?;
338	}
339	if let Some(t) = font.get::<Cff2>()? {
340		reorder_cff(&mut t.cff, old_names, &new_glyph_order)?;
341	}
342	Ok(())
343}
344
345impl Font {
346	/// Reorders the glyphs of the font (`TTFont.reorderGlyphs`); see
347	/// [`reorder_glyphs`].
348	pub fn reorder_glyphs(&mut self, new_glyph_order: Vec<String>) -> Result<()> {
349		reorder_glyphs(self, new_glyph_order)
350	}
351}