Skip to main content

fontoxide_ttlib/tables/
cmap.rs

1//! `cmap`: Character to Glyph Index Mapping table
2//! (`fontTools.ttLib.tables._c_m_a_p`).
3//!
4//! fontTools maps character codes to glyph *names*; fontoxide maps them to glyph
5//! IDs, and converts to and from names only for TTX. Compiling goes through the
6//! names all the same (glyph ID → name → glyph ID), so that fonts whose glyph order
7//! has duplicate names compile exactly as in fontTools.
8//!
9//! fontTools decompiles subtables lazily; fontoxide always decompiles them eagerly,
10//! which is what fontTools does with `TTFont(lazy=False)`.
11
12use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
13use std::sync::Arc;
14
15use fontoxide_misc::Tag;
16use fontoxide_misc::text_tools::Literal;
17use fontoxide_misc::xml_reader::Element;
18use fontoxide_misc::xml_writer::XmlWriter;
19
20use crate::binary::{WriteBytes, fit, get_search_range};
21use crate::glyph_order::GlyphOrder;
22use crate::sstruct::eval;
23use crate::table::{Table, TableType, TableXml, read_hex};
24use crate::{Error, Font, Result};
25
26/// Character code to glyph ID (`subtable.cmap`, which fontTools keys to glyph
27/// names).
28pub type CharMap = BTreeMap<u32, u32>;
29
30/// Unicode Variation Sequences of a format 14 or 15 subtable (`uvsDict`): variation
31/// selector to `(base character, glyph ID)` pairs, where `None` means the default
32/// glyph of the base character.
33pub type UvsDict = BTreeMap<u32, Vec<(u32, Option<u32>)>>;
34
35/// The (platform ID, encoding ID) pairs `get_best_cmap` searches by default, in
36/// order of preference.
37pub const DEFAULT_CMAP_PREFERENCES: [(u16, u16); 8] = [
38	(3, 10),
39	(0, 6),
40	(0, 4),
41	(3, 1),
42	(0, 3),
43	(0, 2),
44	(0, 1),
45	(0, 0),
46];
47
48/// The mapping of one Unicode subtable, as used to derive glyph names.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct UnicodeMapping {
51	/// Code point to glyph ID.
52	pub cmap: BTreeMap<u32, u32>,
53}
54
55/// The mappings of the Unicode subtables (`isUnicode()`) of a `cmap` or `DMAP`
56/// table, in subtable order. (`DMAP` has the same structure as `cmap`.)
57pub fn unicode_mappings(_tag: Tag, data: &[u8]) -> Result<Vec<UnicodeMapping>> {
58	let table = Cmap::parse(data)?;
59	Ok(table
60		.tables
61		.iter()
62		.filter(|t| t.is_unicode())
63		.map(|t| UnicodeMapping {
64			cmap: (*t.cmap).clone(),
65		})
66		.collect())
67}
68
69/// The lowest and highest code points of the font's Unicode `cmap` subtables,
70/// loading `cmap` as `ttFont["cmap"]` does (used by
71/// `OS/2.updateFirstAndLastCharIndex`). `None` without a `cmap` or code points.
72pub fn unicode_code_range(font: &mut Font) -> Result<Option<(u32, u32)>> {
73	let Some(cmap) = font.get::<Cmap>()? else {
74		return Ok(None);
75	};
76	let mut range: Option<(u32, u32)> = None;
77	for t in cmap.tables.iter().filter(|t| t.is_unicode()) {
78		if let (Some((&lo, _)), Some((&hi, _))) =
79			(t.cmap.first_key_value(), t.cmap.last_key_value())
80		{
81			range = Some(match range {
82				Some((a, b)) => (a.min(lo), b.max(hi)),
83				None => (lo, hi),
84			});
85		}
86	}
87	Ok(range)
88}
89
90/// Character to Glyph Index Mapping table (`table__c_m_a_p`).
91///
92/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/cmap>.
93#[derive(Debug, Clone, PartialEq, Default)]
94pub struct Cmap {
95	/// The table version (`tableVersion`), 0.
96	pub table_version: u16,
97	/// The subtables (`tables`).
98	pub tables: Vec<CmapSubtable>,
99}
100
101/// The subtable class, which decides how a subtable is read and written
102/// (`cmap_format_0`, `cmap_format_2`, …, `cmap_format_unknown`).
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub enum SubtableKind {
105	/// Byte encoding table.
106	Format0,
107	/// High-byte mapping through table.
108	Format2,
109	/// Segment mapping to delta values.
110	Format4,
111	/// Trimmed table mapping.
112	Format6,
113	/// Segmented coverage.
114	Format12,
115	/// Many-to-one range mappings.
116	Format13,
117	/// Unicode Variation Sequences.
118	Format14,
119	/// Unicode Variation Sequences with 24-bit glyph IDs.
120	Format15,
121	/// Any other format (including 8 and 10), kept as raw data.
122	Unknown,
123}
124
125impl SubtableKind {
126	/// The class for a format (`getSubtableClass`).
127	pub fn from_format(format: u16) -> Self {
128		match format {
129			0 => SubtableKind::Format0,
130			2 => SubtableKind::Format2,
131			4 => SubtableKind::Format4,
132			6 => SubtableKind::Format6,
133			12 => SubtableKind::Format12,
134			13 => SubtableKind::Format13,
135			14 => SubtableKind::Format14,
136			15 => SubtableKind::Format15,
137			_ => SubtableKind::Unknown,
138		}
139	}
140
141	/// The size of the fixed header (`struct.calcsize(headerFormat)`).
142	fn header_size(self) -> usize {
143		match self {
144			SubtableKind::Format12 | SubtableKind::Format13 => 16,
145			SubtableKind::Format14 | SubtableKind::Format15 => 10,
146			SubtableKind::Unknown => 0,
147			_ => 6,
148		}
149	}
150
151	/// Whether glyph names of the form `gidNNN` are accepted (formats 2, 4, 12 and
152	/// 13 allow such "virtual" glyph IDs).
153	fn allows_virtual_gids(self) -> bool {
154		matches!(
155			self,
156			SubtableKind::Format2
157				| SubtableKind::Format4
158				| SubtableKind::Format12
159				| SubtableKind::Format13
160		)
161	}
162}
163
164/// A `cmap` subtable (`CmapSubtable` and its subclasses).
165#[derive(Debug, Clone, PartialEq)]
166pub struct CmapSubtable {
167	/// The subtable class.
168	pub kind: SubtableKind,
169	/// The format number (`format`).
170	pub format: u16,
171	/// The platform ID (`platformID`).
172	pub platform_id: u16,
173	/// The encoding ID (`platEncID`).
174	pub plat_enc_id: u16,
175	/// The language (`language`); `None` where fontTools has none (a subtable not
176	/// read from anywhere yet, or an unknown format read from TTX).
177	pub language: Option<u32>,
178	/// The mapping (`cmap`). Subtables at the same offset in a decompiled table
179	/// share it, as in fontTools, and are compiled only once; use
180	/// [`Arc::make_mut`] to modify it.
181	pub cmap: Arc<CharMap>,
182	/// The reserved field of formats 12 and 13 (`reserved`).
183	pub reserved: u16,
184	/// The subtable length, as read (`length`; written to TTX for formats 12 and
185	/// 13).
186	pub length: u32,
187	/// The number of groups, as read (`nGroups`; formats 12 and 13).
188	pub n_groups: u32,
189	/// The number of variation selector records, as read (`numVarSelectorRecords`;
190	/// formats 14 and 15).
191	pub num_var_selector_records: u32,
192	/// The variation sequences of formats 14 and 15 (`uvsDict`). `None` if not set,
193	/// as for a subtable sharing its data with an earlier one.
194	pub uvs_dict: Option<UvsDict>,
195	/// The raw subtable of an unknown format, header included (`data`).
196	pub data: Option<Vec<u8>>,
197}
198
199impl CmapSubtable {
200	/// A new, empty subtable of the given format (`CmapSubtable.newSubtable`).
201	pub fn new(format: u16) -> Self {
202		CmapSubtable {
203			kind: SubtableKind::from_format(format),
204			format,
205			platform_id: 0,
206			plat_enc_id: 0,
207			language: None,
208			cmap: Arc::new(CharMap::new()),
209			reserved: 0,
210			length: 0,
211			n_groups: 0,
212			num_var_selector_records: 0,
213			uvs_dict: None,
214			data: None,
215		}
216	}
217
218	/// Whether the characters are Unicode code points (`isUnicode`).
219	pub fn is_unicode(&self) -> bool {
220		self.platform_id == 0 || (self.platform_id == 3 && matches!(self.plat_enc_id, 0 | 1 | 10))
221	}
222
223	/// The codec of the subtable's encoding, `None` if unknown (`getEncoding()`).
224	pub fn encoding(&self) -> Option<&'static str> {
225		// Only a few small language IDs select a specific codec.
226		let language = self.language.unwrap_or(0).min(0xFFFF) as u16;
227		fontoxide_misc::encoding_tools::get_encoding(self.platform_id, self.plat_enc_id, language)
228	}
229
230	/// Whether the subtable is for the Symbol encoding (3, 0) (`isSymbol`).
231	pub fn is_symbol(&self) -> bool {
232		self.platform_id == 3 && self.plat_enc_id == 0
233	}
234
235	/// The mapping, for modification ([`Arc::make_mut`] on [`CmapSubtable::cmap`]).
236	pub fn cmap_mut(&mut self) -> &mut CharMap {
237		Arc::make_mut(&mut self.cmap)
238	}
239
240	/// The TTX element name (the class name).
241	fn element_name(&self) -> String {
242		match self.kind {
243			SubtableKind::Format0 => "cmap_format_0".into(),
244			SubtableKind::Format2 => "cmap_format_2".into(),
245			SubtableKind::Format4 => "cmap_format_4".into(),
246			SubtableKind::Format6 => "cmap_format_6".into(),
247			SubtableKind::Format12 => "cmap_format_12".into(),
248			SubtableKind::Format13 => "cmap_format_13".into(),
249			SubtableKind::Format14 => "cmap_format_14".into(),
250			SubtableKind::Format15 => "cmap_format_15".into(),
251			SubtableKind::Unknown => format!("cmap_format_{}", self.format),
252		}
253	}
254
255	/// Decompiles a subtable from its data, header included (`decompile(data,
256	/// ttFont)`).
257	pub fn decompile(&mut self, data: &[u8]) -> Result<()> {
258		self.decompile_header(data)?;
259		self.decompile_body(data)
260	}
261
262	/// Reads the header (`decompileHeader`).
263	fn decompile_header(&mut self, data: &[u8]) -> Result<()> {
264		let size = self.kind.header_size();
265		if data.len() < size {
266			return Err(unpack_error(size));
267		}
268		match self.kind {
269			SubtableKind::Format12 | SubtableKind::Format13 => {
270				let format = be16(data, 0);
271				let reserved = be16(data, 2);
272				let length = be32(data, 4);
273				let language = be32(data, 8);
274				let n_groups = be32(data, 12);
275				if data.len() as u64 != length as u64 {
276					return Err(Error::ttlib(format!(
277						"cmap subtable format {} is truncated: length {length}, got {} bytes",
278						self.format,
279						data.len()
280					)));
281				}
282				let expected = 16 + n_groups as u64 * 12;
283				if length as u64 != expected {
284					return Err(Error::ttlib(format!(
285						"cmap subtable format {} has an inconsistent group count: length {length}, but {n_groups} groups need {expected} bytes",
286						self.format
287					)));
288				}
289				self.format = format;
290				self.reserved = reserved;
291				self.length = length;
292				self.language = Some(language);
293				self.n_groups = n_groups;
294			}
295			SubtableKind::Format14 | SubtableKind::Format15 => {
296				self.length = be32(data, 2);
297				self.num_var_selector_records = be32(data, 6);
298				self.language = Some(0xFF);
299			}
300			SubtableKind::Unknown => {
301				self.language = Some(0);
302				self.data = Some(data.to_vec());
303			}
304			_ => {
305				let format = be16(data, 0);
306				let length = be16(data, 2);
307				let language = be16(data, 4);
308				if data.len() != length as usize {
309					return Err(Error::Assertion(format!(
310						"corrupt cmap table format {format} (data length: {}, header length: {length})",
311						data.len()
312					)));
313				}
314				self.format = format;
315				self.length = length as u32;
316				self.language = Some(language as u32);
317			}
318		}
319		Ok(())
320	}
321
322	/// Reads the rest of the subtable (`decompile`).
323	fn decompile_body(&mut self, data: &[u8]) -> Result<()> {
324		let body = &data[self.kind.header_size().min(data.len())..];
325		let pairs = match self.kind {
326			SubtableKind::Format0 => {
327				if self.length != 262 {
328					return Err(Error::Assertion(
329						"Format 0 cmap subtable not 262 bytes".into(),
330					));
331				}
332				body.iter()
333					.enumerate()
334					.map(|(i, &g)| (i as u32, g as u32))
335					.collect()
336			}
337			SubtableKind::Format2 => decompile_format_2(body)?,
338			SubtableKind::Format4 => decompile_format_4(body)?,
339			SubtableKind::Format6 => decompile_format_6(body)?,
340			SubtableKind::Format12 | SubtableKind::Format13 => {
341				decompile_format_12_or_13(body, self.kind, self.format, self.n_groups)?
342			}
343			SubtableKind::Format14 | SubtableKind::Format15 => {
344				self.uvs_dict = Some(decompile_format_14(
345					body,
346					self.kind,
347					self.num_var_selector_records,
348				)?);
349				Vec::new()
350			}
351			SubtableKind::Unknown => Vec::new(),
352		};
353		self.cmap = Arc::new(make_map(pairs));
354		Ok(())
355	}
356
357	/// Compiles the subtable (`compile`).
358	pub fn compile(&self, font: &mut Font) -> Result<Vec<u8>> {
359		match self.kind {
360			SubtableKind::Unknown => match &self.data {
361				Some(data) if !data.is_empty() => Ok(data.clone()),
362				_ => Err(Error::value(
363					"can only concatenate bytes (not \"NoneType\") to bytes: unknown cmap subtable has no data",
364				)),
365			},
366			SubtableKind::Format14 | SubtableKind::Format15 => self.compile_format_14(font),
367			_ => {
368				let order = font.glyph_order()?;
369				let items: Vec<(u32, u32)> = self
370					.cmap
371					.iter()
372					.map(|(&code, &gid)| (code, canonical_gid(&order, gid)))
373					.collect();
374				let language = self.language;
375				match self.kind {
376					SubtableKind::Format0 => compile_format_0(&items, language),
377					SubtableKind::Format2 => compile_format_2(&items, language),
378					SubtableKind::Format4 => compile_format_4(&items, self.format, language),
379					SubtableKind::Format6 => compile_format_6(&items, language),
380					_ => self.compile_format_12_or_13(&items),
381				}
382			}
383		}
384	}
385
386	fn compile_format_12_or_13(&self, items: &[(u32, u32)]) -> Result<Vec<u8>> {
387		let language = language_u32(self.language)?;
388		let mut data = Vec::new();
389		data.put_u16(self.format);
390		data.put_u16(self.reserved);
391		if items.is_empty() {
392			data.put_u32(16);
393			data.put_u32(language);
394			data.put_u32(0);
395			return Ok(data);
396		}
397		let step: i64 = if self.kind == SubtableKind::Format12 {
398			1
399		} else {
400			0
401		};
402		let in_same_run = |gid: i64, last_gid: i64, code: i64, last_code: i64| {
403			if step == 1 {
404				gid == 1 + last_gid && code == 1 + last_code
405			} else {
406				gid == last_gid && code == 1 + last_code
407			}
408		};
409		let mut groups = Vec::new();
410		let (mut start_code, mut start_gid) = (items[0].0 as i64, items[0].1 as i64);
411		let mut last_gid = start_gid - step;
412		let mut last_code = start_code - 1;
413		for &(code, gid) in items {
414			let (code, gid) = (code as i64, gid as i64);
415			if !in_same_run(gid, last_gid, code, last_code) {
416				groups.push((start_code, last_code, start_gid));
417				start_code = code;
418				start_gid = gid;
419			}
420			last_gid = gid;
421			last_code = code;
422		}
423		groups.push((start_code, last_code, start_gid));
424		let length = 16 + groups.len() * 12;
425		data.put_u32(fit(length, "length")?);
426		data.put_u32(language);
427		data.put_u32(fit(groups.len(), "nGroups")?);
428		for (start, end, gid) in groups {
429			data.put_u32(fit(start, "startCharCode")?);
430			data.put_u32(fit(end, "endCharCode")?);
431			data.put_u32(fit(gid, "startGlyphID")?);
432		}
433		Ok(data)
434	}
435
436	fn compile_format_14(&self, font: &mut Font) -> Result<Vec<u8>> {
437		let uvs_dict = self
438			.uvs_dict
439			.as_ref()
440			.ok_or_else(|| no_attribute(self, "uvsDict"))?;
441		let order = font.glyph_order()?;
442		let record_size = if self.kind == SubtableKind::Format15 {
443			6
444		} else {
445			5
446		};
447		let num_records = uvs_dict.len();
448		let mut offset = 10 + num_records * 11;
449		let mut data = Vec::new();
450		let mut var_selector_records = Vec::new();
451		for (&uvs, entries) in uvs_dict {
452			let mut def_list: Vec<u32> = entries
453				.iter()
454				.filter(|e| e.1.is_none())
455				.map(|e| e.0)
456				.collect();
457			let def_offset = if def_list.is_empty() {
458				0
459			} else {
460				def_list.sort_unstable();
461				let mut last_uv = def_list[0] as i64;
462				let mut cnt: i64 = -1;
463				let mut def_recs = Vec::new();
464				for &entry in &def_list {
465					cnt += 1;
466					if last_uv + cnt != entry as i64 || cnt > 255 {
467						def_recs.push((last_uv, cnt - 1));
468						last_uv = entry as i64;
469						cnt = 0;
470					}
471				}
472				def_recs.push((last_uv, cnt));
473				data.put_u32(fit(def_recs.len(), "numUnicodeValueRanges")?);
474				for &(uv, count) in &def_recs {
475					data.put_u24(cvt_from_uvs(uv)?);
476					data.put_u8(fit(count, "additionalCount")?);
477				}
478				let o = offset;
479				offset += 4 + def_recs.len() * 4;
480				o
481			};
482			let mut ndef_list: Vec<(u32, u32, String)> = entries
483				.iter()
484				.filter_map(|&(uv, gid)| gid.map(|g| (uv, g, order.name(g).into_owned())))
485				.collect();
486			let non_def_offset = if ndef_list.is_empty() {
487				0
488			} else {
489				ndef_list.sort_by(|a, b| (a.0, &a.2).cmp(&(b.0, &b.2)));
490				let o = offset;
491				data.put_u32(fit(ndef_list.len(), "numUVSMappings")?);
492				offset += 4 + ndef_list.len() * record_size;
493				for (uv, gid, _) in &ndef_list {
494					let gid = canonical_gid(&order, *gid);
495					data.put_u24(cvt_from_uvs(*uv as i64)?);
496					if self.kind == SubtableKind::Format15 {
497						data.put_u24(cvt_from_uvs(gid as i64)?);
498					} else {
499						data.put_u16(fit(gid, "glyphID")?);
500					}
501				}
502				o
503			};
504			var_selector_records.put_u24(cvt_from_uvs(uvs as i64)?);
505			var_selector_records.put_u32(fit(def_offset, "defaultUVSOffset")?);
506			var_selector_records.put_u32(fit(non_def_offset, "nonDefaultUVSOffset")?);
507		}
508		let length = 10 + var_selector_records.len() + data.len();
509		let mut out = Vec::with_capacity(length);
510		out.put_u16(self.format);
511		out.put_u32(fit(length, "length")?);
512		out.put_u32(fit(num_records, "numVarSelectorRecords")?);
513		out.extend(var_selector_records);
514		out.extend(data);
515		Ok(out)
516	}
517
518	/// Writes the subtable's TTX element (`toXML`).
519	pub fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
520		let name = self.element_name();
521		match self.kind {
522			SubtableKind::Unknown => {
523				let data = self.data.as_ref().ok_or_else(|| {
524					Error::value(
525						"object of type 'NoneType' has no len(): unknown cmap subtable has no data",
526					)
527				})?;
528				writer.begintag_ordered(
529					&name,
530					&[
531						("platformID", &self.platform_id),
532						("platEncID", &self.plat_enc_id),
533					],
534				);
535				writer.newline();
536				writer.dumphex(data);
537			}
538			SubtableKind::Format14 | SubtableKind::Format15 => {
539				let uvs_dict = self
540					.uvs_dict
541					.as_ref()
542					.ok_or_else(|| no_attribute(self, "uvsDict"))?;
543				let order = font.glyph_order()?;
544				writer.begintag_ordered(
545					&name,
546					&[
547						("platformID", &self.platform_id),
548						("platEncID", &self.plat_enc_id),
549					],
550				);
551				writer.newline();
552				for (&uvs, entries) in uvs_dict {
553					let mut entries: Vec<(u32, Option<String>)> = entries
554						.iter()
555						.map(|&(uv, gid)| (uv, gid.map(|g| order.name(g).into_owned())))
556						.collect();
557					entries.sort_by(|a, b| {
558						(a.1.is_some(), a.0, &a.1).cmp(&(b.1.is_some(), b.0, &b.1))
559					});
560					for (uv, glyph_name) in &entries {
561						let uv = format!("{uv:#x}");
562						let uvs = format!("{uvs:#x}");
563						match glyph_name {
564							Some(n) => writer.simpletag_ordered(
565								"map",
566								&[("uv", &uv), ("uvs", &uvs), ("name", n)],
567							),
568							None => writer.simpletag_ordered("map", &[("uv", &uv), ("uvs", &uvs)]),
569						}
570						writer.newline();
571					}
572				}
573			}
574			SubtableKind::Format12 | SubtableKind::Format13 => {
575				let language = LanguageAttr(self.language);
576				writer.begintag_ordered(
577					&name,
578					&[
579						("platformID", &self.platform_id),
580						("platEncID", &self.plat_enc_id),
581						("format", &self.format),
582						("reserved", &self.reserved),
583						("length", &self.length),
584						("language", &language),
585						("nGroups", &self.n_groups),
586					],
587				);
588				writer.newline();
589				self.write_codes(writer, font)?;
590			}
591			_ => {
592				let language = LanguageAttr(self.language);
593				writer.begintag_ordered(
594					&name,
595					&[
596						("platformID", &self.platform_id),
597						("platEncID", &self.plat_enc_id),
598						("language", &language),
599					],
600				);
601				writer.newline();
602				self.write_codes(writer, font)?;
603			}
604		}
605		writer.endtag(&name);
606		writer.newline();
607		Ok(())
608	}
609
610	/// `_writeCodes`.
611	fn write_codes(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
612		let order = font.glyph_order()?;
613		let is_unicode = self.is_unicode();
614		for (&code, &gid) in self.cmap.iter() {
615			let code_str = format!("{code:#x}");
616			let name = order.name(gid);
617			writer.simpletag("map", &[("code", &code_str), ("name", &name.as_ref())]);
618			if is_unicode {
619				writer.comment(&fontoxide_unicodedata::unicode_name(code));
620			}
621			writer.newline();
622		}
623		Ok(())
624	}
625
626	/// Reads the subtable's TTX element (`fromXML`); the platform and encoding IDs
627	/// are read by the caller.
628	pub fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
629		match self.kind {
630			SubtableKind::Unknown => {
631				self.data = Some(read_hex(element)?);
632				self.cmap = Arc::new(CharMap::new());
633				return Ok(());
634			}
635			SubtableKind::Format14 | SubtableKind::Format15 => {
636				return self.read_xml_format_14(element, font);
637			}
638			SubtableKind::Format12 | SubtableKind::Format13 => {
639				self.format = fit(int_attr(element, "format")?, "format")?;
640				self.reserved = fit(int_attr(element, "reserved")?, "reserved")?;
641				self.length = fit(int_attr(element, "length")?, "length")?;
642				self.language = language_attr(element)?;
643				self.n_groups = fit(int_attr(element, "nGroups")?, "nGroups")?;
644			}
645			_ => self.language = language_attr(element)?,
646		}
647		let order = font.glyph_order()?;
648		let cmap = Arc::make_mut(&mut self.cmap);
649		for child in element.elements() {
650			if child.name != "map" {
651				if self.kind == SubtableKind::Format4 {
652					return Err(Error::Assertion(
653						"Unrecognized keyword in cmap subtable".into(),
654					));
655				}
656				continue;
657			}
658			let code: u32 = fit(int_attr(child, "code")?, "code")?;
659			let name = str_attr(child, "name")?;
660			cmap.insert(
661				code,
662				glyph_id_for(&order, name, self.kind.allows_virtual_gids())?,
663			);
664		}
665		Ok(())
666	}
667
668	fn read_xml_format_14(&mut self, element: &Element, font: &mut Font) -> Result<()> {
669		self.language = Some(0xFF);
670		let order = font.glyph_order()?;
671		// For backwards compatibility, "None" means the default mapping, unless the
672		// font actually has a glyph named "None".
673		let mut has_glyph_named_none = None;
674		let uvs_dict = self.uvs_dict.get_or_insert_with(UvsDict::new);
675		for child in element.elements() {
676			if child.name != "map" {
677				continue;
678			}
679			let uvs: u32 = fit(int_attr(child, "uvs")?, "uvs")?;
680			let uv: u32 = fit(int_attr(child, "uv")?, "uv")?;
681			let mut name = child.attr("name");
682			if name == Some("None") {
683				let has = *has_glyph_named_none
684					.get_or_insert_with(|| order.names().iter().any(|n| n == "None"));
685				if !has {
686					name = None;
687				}
688			}
689			let gid = match name {
690				Some(n) => Some(glyph_id_for(&order, n, false)?),
691				None => None,
692			};
693			uvs_dict.entry(uvs).or_default().push((uv, gid));
694		}
695		Ok(())
696	}
697
698	/// The sort key (`__lt__`).
699	fn sort_key(&self) -> (u16, u16, Option<u32>) {
700		(self.platform_id, self.plat_enc_id, self.language)
701	}
702}
703
704/// `language` as Python formats it: `None` when unset.
705struct LanguageAttr(Option<u32>);
706
707impl fontoxide_misc::xml_writer::AttrValue for LanguageAttr {
708	fn attr_string(&self) -> std::borrow::Cow<'_, str> {
709		match self.0 {
710			Some(l) => l.to_string().into(),
711			None => "None".into(),
712		}
713	}
714}
715
716impl Cmap {
717	/// Parses a `cmap` (or `DMAP`) table; this needs no font, since glyphs are
718	/// stored by ID.
719	pub fn parse(data: &[u8]) -> Result<Self> {
720		if data.len() < 4 {
721			return Err(Error::ttlib("cmap table is too short"));
722		}
723		let table_version = be16(data, 0);
724		let num_sub_tables = be16(data, 2) as usize;
725		let mut tables: Vec<CmapSubtable> = Vec::new();
726		let mut seen_offsets: HashMap<usize, usize> = HashMap::new();
727		let len = data.len();
728		for i in 0..num_sub_tables {
729			let start = 4 + i * 8;
730			if start + 8 > len {
731				return Err(Error::ttlib("cmap subtable directory is truncated"));
732			}
733			let platform_id = be16(data, start);
734			let plat_enc_id = be16(data, start + 2);
735			let offset = be32(data, start + 4) as usize;
736			if offset as u64 + 4 > len as u64 {
737				return Err(Error::ttlib(format!(
738					"cmap subtable offset {offset} is out of bounds (data length {len})"
739				)));
740			}
741			let format = be16(data, offset);
742			let mut length = be16(data, offset + 2) as u64;
743			if matches!(format, 8 | 10 | 12 | 13) {
744				if offset + 8 > len {
745					return Err(Error::ttlib("cmap subtable header is truncated"));
746				}
747				length = be32(data, offset + 4) as u64;
748			} else if matches!(format, 14 | 15) {
749				if offset + 6 > len {
750					return Err(Error::ttlib("cmap subtable header is truncated"));
751				}
752				length = be32(data, offset + 2) as u64;
753			}
754			if length == 0 {
755				log::error!(
756					"cmap subtable is reported as having zero length: platformID {platform_id}, platEncID {plat_enc_id}, format {format} offset {offset}. Skipping table."
757				);
758				continue;
759			}
760			let mut table = CmapSubtable::new(format);
761			table.platform_id = platform_id;
762			table.plat_enc_id = plat_enc_id;
763			let min_header_size = table.kind.header_size() as u64;
764			if length < min_header_size {
765				return Err(Error::ttlib(format!(
766					"cmap subtable header is truncated: length {length} < {min_header_size}"
767				)));
768			}
769			if offset as u64 + length > len as u64 {
770				return Err(Error::ttlib(format!(
771					"cmap subtable is truncated: needs {length} bytes, only {} available",
772					len - offset
773				)));
774			}
775			let sub_data = &data[offset..offset + length as usize];
776			table.decompile_header(sub_data)?;
777			if let Some(&first) = seen_offsets.get(&offset) {
778				// Mark as decompiled, sharing the mapping. As in fontTools, the index
779				// is that of the directory entry, which differs from the index in
780				// `tables` after a skipped zero-length subtable.
781				table.data = None;
782				table.cmap = tables
783					.get(first)
784					.ok_or_else(|| Error::value("list index out of range"))?
785					.cmap
786					.clone();
787			} else {
788				seen_offsets.insert(offset, i);
789				table.decompile_body(sub_data)?;
790			}
791			tables.push(table);
792		}
793		Ok(Cmap {
794			table_version,
795			tables,
796		})
797	}
798
799	/// The first subtable with the given platform and encoding IDs (`getcmap`).
800	pub fn getcmap(&self, platform_id: u16, plat_enc_id: u16) -> Option<&CmapSubtable> {
801		self.tables
802			.iter()
803			.find(|t| t.platform_id == platform_id && t.plat_enc_id == plat_enc_id)
804	}
805
806	/// The mapping of the first subtable found in order of preference
807	/// (`getBestCmap`); [`DEFAULT_CMAP_PREFERENCES`] is the default order.
808	pub fn get_best_cmap(&self, preferences: &[(u16, u16)]) -> Option<&CharMap> {
809		preferences
810			.iter()
811			.find_map(|&(p, e)| self.getcmap(p, e))
812			.map(|t| &*t.cmap)
813	}
814
815	/// Glyph ID to the code points mapped to it in the Unicode subtables
816	/// (`buildReversed`).
817	pub fn build_reversed(&self) -> BTreeMap<u32, BTreeSet<u32>> {
818		let mut result: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::new();
819		for t in self.tables.iter().filter(|t| t.is_unicode()) {
820			for (&code, &gid) in t.cmap.iter() {
821				result.entry(gid).or_default().insert(code);
822			}
823		}
824		result
825	}
826
827	/// Glyph ID to the lowest code point mapped to it in the Unicode subtables
828	/// (`buildReversedMin`).
829	pub fn build_reversed_min(&self) -> BTreeMap<u32, u32> {
830		let mut result: BTreeMap<u32, u32> = BTreeMap::new();
831		for t in self.tables.iter().filter(|t| t.is_unicode()) {
832			for (&code, &gid) in t.cmap.iter() {
833				result
834					.entry(gid)
835					.and_modify(|c| *c = (*c).min(code))
836					.or_insert(code);
837			}
838		}
839		result
840	}
841
842	/// Sorts the subtables by (platform ID, encoding ID, language), as the
843	/// specification requires (`tables.sort()`).
844	pub fn sort_tables(&mut self) -> Result<()> {
845		// Python fails to compare a missing language (None) with a number.
846		let mut languages: HashMap<(u16, u16), (bool, bool)> = HashMap::new();
847		for t in &self.tables {
848			let e = languages.entry((t.platform_id, t.plat_enc_id)).or_default();
849			if t.language.is_some() {
850				e.0 = true;
851			} else {
852				e.1 = true;
853			}
854		}
855		if languages.values().any(|&(some, none)| some && none) {
856			return Err(Error::value(
857				"'<' not supported between instances of 'int' and 'NoneType'",
858			));
859		}
860		self.tables.sort_by_key(|t| t.sort_key());
861		Ok(())
862	}
863}
864
865impl TableType for Cmap {
866	const TAG: Tag = Tag::new(b"cmap");
867
868	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
869		Cmap::parse(data)
870	}
871}
872
873impl Table for Cmap {
874	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
875		for t in &mut self.tables {
876			let mut cmap = (*t.cmap).clone();
877			for g in cmap.values_mut() {
878				*g = f(*g)?;
879			}
880			t.cmap = std::sync::Arc::new(cmap);
881			if let Some(uvs) = &mut t.uvs_dict {
882				for records in uvs.values_mut() {
883					for (_, g) in records.iter_mut() {
884						if let Some(g) = g {
885							*g = f(*g)?;
886						}
887					}
888				}
889			}
890		}
891		Ok(())
892	}
893
894	fn tag(&self) -> Tag {
895		Self::TAG
896	}
897
898	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
899		self.sort_tables()?;
900		let mut seen = HashSet::new();
901		let mut duplicates = BTreeSet::new();
902		for t in &self.tables {
903			if !seen.insert(t.sort_key()) {
904				duplicates.insert(t.sort_key());
905			}
906		}
907		if !duplicates.is_empty() {
908			let items: Vec<String> = duplicates
909				.iter()
910				.map(|(p, e, l)| match l {
911					Some(l) => format!("({p}, {e}, {l})"),
912					None => format!("({p}, {e}, None)"),
913				})
914				.collect();
915			return Err(Error::value(format!(
916				"cmap subtables have duplicate (platformID, platEncID, language) entries, which the OpenType spec does not allow: {{{}}}",
917				items.join(", ")
918			)));
919		}
920		let num_sub_tables = self.tables.len();
921		let total_offset = 4 + 8 * num_sub_tables;
922		let mut data = Vec::new();
923		data.put_u16(self.table_version);
924		data.put_u16(fit(num_sub_tables, "numSubTables")?);
925		let mut table_data = Vec::new();
926		// Some subtables share their mapping: compile them once.
927		let mut seen: HashMap<usize, usize> = HashMap::new();
928		// Some subtables are different, but compile to the same data.
929		let mut done: HashMap<Vec<u8>, usize> = HashMap::new();
930		for table in &self.tables {
931			let id = Arc::as_ptr(&table.cmap) as usize;
932			let offset = match seen.get(&id) {
933				Some(&offset) => offset,
934				None => {
935					let chunk = table.compile(font)?;
936					match done.get(&chunk) {
937						Some(&offset) => offset,
938						None => {
939							let offset = total_offset + table_data.len();
940							seen.insert(id, offset);
941							table_data.extend_from_slice(&chunk);
942							done.insert(chunk, offset);
943							offset
944						}
945					}
946				}
947			};
948			data.put_u16(table.platform_id);
949			data.put_u16(table.plat_enc_id);
950			data.put_u32(fit(offset, "offset")?);
951		}
952		data.extend(table_data);
953		Ok(data)
954	}
955
956	fn clone_table(&self) -> Box<dyn Table> {
957		Box::new(self.clone())
958	}
959}
960
961impl TableXml for Cmap {
962	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
963		writer.simpletag("tableVersion", &[("version", &self.table_version)]);
964		writer.newline();
965		for table in &self.tables {
966			table.to_xml(writer, font)?;
967		}
968		Ok(())
969	}
970
971	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
972		if element.name == "tableVersion" {
973			self.table_version = fit(int_attr(element, "version")?, "tableVersion")?;
974			return Ok(());
975		}
976		let Some(format) = element.name.strip_prefix("cmap_format_") else {
977			return Ok(());
978		};
979		let format = eval(format)?
980			.as_int()
981			.ok_or_else(|| Error::value(format!("invalid cmap subtable format: {format:?}")))?;
982		let mut table = CmapSubtable::new(fit(format, "format")?);
983		table.platform_id = fit(int_attr(element, "platformID")?, "platformID")?;
984		table.plat_enc_id = fit(int_attr(element, "platEncID")?, "platEncID")?;
985		table.from_xml(element, font)?;
986		self.tables.push(table);
987		Ok(())
988	}
989}
990
991/// Delta map table (`table_D_M_A_P_`): the same structure as `cmap`, whose
992/// mappings it takes precedence over.
993#[derive(Debug, Clone, PartialEq, Default)]
994pub struct Dmap(pub Cmap);
995
996impl TableType for Dmap {
997	const TAG: Tag = Tag::new(b"DMAP");
998
999	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
1000		Cmap::parse(data).map(Dmap)
1001	}
1002}
1003
1004impl Table for Dmap {
1005	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
1006		self.0.remap_glyphs(f)
1007	}
1008
1009	fn tag(&self) -> Tag {
1010		Self::TAG
1011	}
1012
1013	fn compile(&mut self, font: &mut Font) -> Result<Vec<u8>> {
1014		self.0.compile(font)
1015	}
1016
1017	fn clone_table(&self) -> Box<dyn Table> {
1018		Box::new(self.clone())
1019	}
1020}
1021
1022impl TableXml for Dmap {
1023	fn to_xml(&self, writer: &mut XmlWriter, font: &mut Font) -> Result<()> {
1024		self.0.to_xml(writer, font)
1025	}
1026
1027	fn from_xml(&mut self, element: &Element, font: &mut Font) -> Result<()> {
1028		self.0.from_xml(element, font)
1029	}
1030}
1031
1032// ---------------------------------------------------------------------------
1033// Helpers
1034
1035fn be16(data: &[u8], pos: usize) -> u16 {
1036	u16::from_be_bytes([data[pos], data[pos + 1]])
1037}
1038
1039fn be24(data: &[u8], pos: usize) -> u32 {
1040	u32::from_be_bytes([0, data[pos], data[pos + 1], data[pos + 2]])
1041}
1042
1043fn be32(data: &[u8], pos: usize) -> u32 {
1044	u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]])
1045}
1046
1047fn unpack_error(size: usize) -> Error {
1048	Error::Struct(format!("unpack requires a buffer of {size} bytes"))
1049}
1050
1051fn index_error() -> Error {
1052	Error::value("array index out of range")
1053}
1054
1055fn no_attribute(table: &CmapSubtable, attr: &str) -> Error {
1056	Error::value(format!(
1057		"'{}' object has no attribute '{attr}'",
1058		table.element_name()
1059	))
1060}
1061
1062/// `data[start:end]` with Python's clamping (non-negative bounds).
1063fn clamp<T>(data: &[T], start: usize, end: usize) -> &[T] {
1064	let start = start.min(data.len());
1065	let end = end.clamp(start, data.len());
1066	&data[start..end]
1067}
1068
1069/// `data[start:end]` with Python's handling of negative and out-of-range bounds.
1070fn py_slice(data: &[u8], start: i64, end: i64) -> &[u8] {
1071	let len = data.len() as i64;
1072	let norm = |i: i64| {
1073		if i < 0 { (i + len).max(0) } else { i.min(len) }
1074	};
1075	let (s, e) = (norm(start), norm(end));
1076	if s >= e {
1077		&[]
1078	} else {
1079		&data[s as usize..e as usize]
1080	}
1081}
1082
1083/// `array.array("H").frombytes(data)`, big-endian.
1084fn u16_array(data: &[u8]) -> Result<Vec<u16>> {
1085	if data.len() % 2 == 1 {
1086		return Err(Error::value("bytes length not a multiple of item size"));
1087	}
1088	Ok(data
1089		.as_chunks::<2>()
1090		.0
1091		.iter()
1092		.map(|c| u16::from_be_bytes(*c))
1093		.collect())
1094}
1095
1096/// `_make_map`: drops the code points mapped to glyph 0. Later pairs override
1097/// earlier ones, as in a Python dict.
1098fn make_map(pairs: Vec<(u32, u32)>) -> CharMap {
1099	let mut map: CharMap = pairs.into_iter().collect();
1100	map.retain(|_, gid| *gid != 0);
1101	map
1102}
1103
1104/// The glyph ID fontTools would compile for a glyph ID it read: the ID of the
1105/// glyph's name (`getGlyphID(getGlyphName(gid))`), which differs only when the glyph
1106/// order has duplicate names.
1107fn canonical_gid(order: &GlyphOrder, gid: u32) -> u32 {
1108	order.id(&order.name(gid)).unwrap_or(gid)
1109}
1110
1111/// The glyph ID for a glyph name read from TTX. Formats 2, 4, 12 and 13 also accept
1112/// `gidNNN` names for glyphs not in the glyph order.
1113fn glyph_id_for(order: &GlyphOrder, name: &str, allow_virtual: bool) -> Result<u32> {
1114	if let Some(&gid) = order.reverse_map().get(name) {
1115		return Ok(gid);
1116	}
1117	if allow_virtual && let Some(digits) = name.strip_prefix("gid") {
1118		let gid = fontoxide_misc::py::parse_int(digits)
1119			.ok_or_else(|| Error::GlyphNotFound(name.to_owned()))?;
1120		return u32::try_from(gid)
1121			.map_err(|_| Error::Struct(format!("cmap cannot represent glyph ID {gid}")));
1122	}
1123	order
1124		.id(name)
1125		.ok_or_else(|| Error::GlyphNotFound(name.to_owned()))
1126}
1127
1128fn str_attr<'a>(element: &'a Element, name: &str) -> Result<&'a str> {
1129	element
1130		.attr(name)
1131		.ok_or_else(|| Error::ttx(format!("missing '{name}' attribute on <{}>", element.name)))
1132}
1133
1134fn int_attr(element: &Element, name: &str) -> Result<i128> {
1135	let value = str_attr(element, name)?;
1136	eval(value)?
1137		.as_int()
1138		.ok_or_else(|| Error::value(format!("invalid '{name}' value: {value:?}")))
1139}
1140
1141fn language_attr(element: &Element) -> Result<Option<u32>> {
1142	let value = str_attr(element, "language")?;
1143	match eval(value)? {
1144		Literal::None => Ok(None),
1145		v => {
1146			let l = v
1147				.as_int()
1148				.ok_or_else(|| Error::value(format!("invalid 'language' value: {value:?}")))?;
1149			Ok(Some(fit(l, "language")?))
1150		}
1151	}
1152}
1153
1154/// The language of a 16-bit subtable header.
1155fn language_u16(language: Option<u32>) -> Result<u16> {
1156	match language {
1157		Some(l) => fit(l, "language"),
1158		None => Err(Error::Struct("required argument is not an integer".into())),
1159	}
1160}
1161
1162/// The language of a 32-bit subtable header.
1163fn language_u32(language: Option<u32>) -> Result<u32> {
1164	language.ok_or_else(|| Error::Struct("required argument is not an integer".into()))
1165}
1166
1167/// `cvtFromUVS`.
1168fn cvt_from_uvs(value: i64) -> Result<u32> {
1169	if !(0..0x1000000).contains(&value) {
1170		return Err(Error::Assertion("0 <= val < 0x1000000".into()));
1171	}
1172	Ok(value as u32)
1173}
1174
1175// ---------------------------------------------------------------------------
1176// Decompiling
1177
1178struct SubHeader {
1179	first_code: i64,
1180	entry_count: i64,
1181	id_delta: i64,
1182	id_range_offset: i64,
1183	glyph_index_array: Vec<i64>,
1184}
1185
1186fn decompile_format_2(data: &[u8]) -> Result<Vec<(u32, u32)>> {
1187	let all_keys = u16_array(clamp(data, 0, 512))?;
1188	let data = clamp(data, 512, data.len());
1189	let sub_header_keys: Vec<usize> = all_keys.iter().map(|&k| (k / 8) as usize).collect();
1190	let max_index = *sub_header_keys
1191		.iter()
1192		.max()
1193		.ok_or_else(|| Error::value("max() arg is an empty sequence"))?;
1194	let mut sub_headers = Vec::with_capacity(max_index + 1);
1195	let mut pos = 0usize;
1196	for _ in 0..=max_index {
1197		let rec = clamp(data, pos, pos + 8);
1198		if rec.len() < 8 {
1199			return Err(unpack_error(8));
1200		}
1201		let first_code = be16(rec, 0) as i64;
1202		let entry_count = be16(rec, 2) as i64;
1203		let id_delta = i16::from_be_bytes([rec[4], rec[5]]) as i64;
1204		let id_range_offset = be16(rec, 6) as i64;
1205		pos += 8;
1206		let gi_pos = pos + id_range_offset as usize - 2;
1207		let gi = u16_array(clamp(data, gi_pos, gi_pos + entry_count as usize * 2))?;
1208		sub_headers.push(SubHeader {
1209			first_code,
1210			entry_count,
1211			id_delta,
1212			id_range_offset,
1213			glyph_index_array: gi.into_iter().map(i64::from).collect(),
1214		});
1215	}
1216	let mut pairs = Vec::new();
1217	for first_byte in 0..256i64 {
1218		let index = *sub_header_keys
1219			.get(first_byte as usize)
1220			.ok_or_else(index_error)?;
1221		let sh = &sub_headers[index];
1222		if index == 0 {
1223			if first_byte < sh.first_code || first_byte >= sh.first_code + sh.entry_count {
1224				continue; // gi is notdef.
1225			}
1226			let gi = *sh
1227				.glyph_index_array
1228				.get((first_byte - sh.first_code) as usize)
1229				.ok_or_else(index_error)?;
1230			if gi == 0 {
1231				continue; // gi is notdef.
1232			}
1233			pairs.push((
1234				first_byte as u32,
1235				(gi + sh.id_delta).rem_euclid(0x10000) as u32,
1236			));
1237		} else if sh.entry_count != 0 {
1238			let char_code_offset = first_byte * 256 + sh.first_code;
1239			for offset_index in 0..sh.entry_count {
1240				let gi = *sh
1241					.glyph_index_array
1242					.get(offset_index as usize)
1243					.ok_or_else(index_error)?;
1244				if gi == 0 {
1245					continue;
1246				}
1247				pairs.push((
1248					(char_code_offset + offset_index) as u32,
1249					(gi + sh.id_delta).rem_euclid(0x10000) as u32,
1250				));
1251			}
1252		}
1253		// If not entryCount, all char codes with this first byte map to .notdef.
1254	}
1255	Ok(pairs)
1256}
1257
1258fn decompile_format_4(data: &[u8]) -> Result<Vec<(u32, u32)>> {
1259	if data.len() < 8 {
1260		return Err(unpack_error(8));
1261	}
1262	let seg_count = (be16(data, 0) / 2) as usize;
1263	let all_codes = u16_array(&data[8..])?;
1264	let end_code = clamp(&all_codes, 0, seg_count);
1265	let rest = clamp(&all_codes, seg_count + 1, all_codes.len()); // skip reservedPad
1266	let start_code = clamp(rest, 0, seg_count);
1267	let rest = clamp(rest, seg_count, rest.len());
1268	let id_delta = clamp(rest, 0, seg_count);
1269	let rest = clamp(rest, seg_count, rest.len());
1270	let id_range_offset = clamp(rest, 0, seg_count);
1271	let glyph_index_array = clamp(rest, seg_count, rest.len());
1272	let len_gi_array = glyph_index_array.len() as i64;
1273
1274	// Later segments override earlier ones, but a missing glyph does not erase an
1275	// earlier mapping.
1276	let mut code_to_gid: CharMap = CharMap::new();
1277	let num_segments = start_code.len().saturating_sub(1); // don't do 0xffff!
1278	for (i, &start) in start_code.iter().enumerate().take(num_segments) {
1279		let start = start as i64;
1280		let delta = *id_delta.get(i).ok_or_else(index_error)? as i64;
1281		let range_offset = *id_range_offset.get(i).ok_or_else(index_error)? as i64;
1282		let partial = range_offset / 2 - start + i as i64 - id_range_offset.len() as i64;
1283		let end = *end_code.get(i).ok_or_else(index_error)? as i64;
1284		if range_offset == 0 {
1285			for code in start..=end {
1286				let gid = (code + delta) & 0xFFFF;
1287				if gid != 0 {
1288					code_to_gid.insert(code as u32, gid as u32);
1289				}
1290			}
1291		} else {
1292			let mut gids = Vec::new();
1293			for code in start..=end {
1294				let index = code + partial;
1295				// A negative index would wrap around to the end of the array.
1296				if !(0..len_gi_array).contains(&index) {
1297					return Err(Error::ttlib(format!(
1298						"cmap format 4 subtable: glyph index array offset {index} out of range [0, {len_gi_array}) in segment {i}"
1299					)));
1300				}
1301				let g = glyph_index_array[index as usize] as i64;
1302				let gid = if g != 0 { (g + delta) & 0xFFFF } else { 0 };
1303				gids.push((code as u32, gid as u32));
1304			}
1305			code_to_gid.extend(gids.into_iter().filter(|&(_, g)| g != 0));
1306		}
1307	}
1308	Ok(code_to_gid.into_iter().collect())
1309}
1310
1311fn decompile_format_6(data: &[u8]) -> Result<Vec<(u32, u32)>> {
1312	if data.len() < 4 {
1313		return Err(unpack_error(4));
1314	}
1315	let first_code = be16(data, 0) as u32;
1316	let entry_count = be16(data, 2) as usize;
1317	let gids = u16_array(clamp(data, 4, 4 + 2 * entry_count))?;
1318	Ok(gids
1319		.into_iter()
1320		.enumerate()
1321		.map(|(i, g)| (first_code + i as u32, g as u32))
1322		.collect())
1323}
1324
1325fn decompile_format_12_or_13(
1326	data: &[u8],
1327	kind: SubtableKind,
1328	format: u16,
1329	n_groups: u32,
1330) -> Result<Vec<(u32, u32)>> {
1331	let groups = clamp(data, 0, n_groups as usize * 12);
1332	if !groups.len().is_multiple_of(4) {
1333		return Err(Error::value("bytes length not a multiple of item size"));
1334	}
1335	let is_12 = kind == SubtableKind::Format12;
1336	// Group ranges come straight from the font, so follow HarfBuzz: clamp each
1337	// group to U+10FFFF and skip any group that is inverted or starts before the
1338	// previous one ends.
1339	let mut code_to_gid = CharMap::new();
1340	let (mut clamped, mut skipped) = (false, false);
1341	let mut last_end = 0u32;
1342	let mut dropped = false;
1343	for g in groups.as_chunks::<12>().0 {
1344		let mut start = be32(g, 0);
1345		let mut end = be32(g, 4);
1346		let mut glyph_id = be32(g, 8) as u64;
1347		if end > 0x10FFFF {
1348			end = 0x10FFFF;
1349			clamped = true;
1350		}
1351		if start > end || start < last_end {
1352			skipped = true;
1353			continue;
1354		}
1355		last_end = end;
1356		if glyph_id == 0 {
1357			// The missing glyph maps nothing: all of a format 13 group, only the
1358			// first code point of a format 12 one.
1359			if !is_12 {
1360				continue;
1361			}
1362			start += 1;
1363			glyph_id += 1;
1364		}
1365		for (k, code) in (start..=end).enumerate() {
1366			let gid = if is_12 { glyph_id + k as u64 } else { glyph_id };
1367			match u32::try_from(gid) {
1368				Ok(gid) => {
1369					code_to_gid.insert(code, gid);
1370				}
1371				Err(_) => dropped = true,
1372			}
1373		}
1374	}
1375	if clamped {
1376		log::warn!("cmap subtable format {format}: group ranges beyond U+10FFFF were truncated");
1377	}
1378	if skipped {
1379		log::warn!("cmap subtable format {format}: skipped unsorted or overlapping groups");
1380	}
1381	if dropped {
1382		// fontTools keeps these as "glyphNNNNN" names; glyph IDs are 32-bit here.
1383		log::warn!("cmap subtable format {format}: dropped glyph IDs beyond 0xFFFFFFFF");
1384	}
1385	Ok(code_to_gid.into_iter().collect())
1386}
1387
1388fn decompile_format_14(data: &[u8], kind: SubtableKind, num_records: u32) -> Result<UvsDict> {
1389	let record_size: i64 = if kind == SubtableKind::Format15 { 6 } else { 5 };
1390	let mut uvs_dict = UvsDict::new();
1391	let mut rec_offset = 0usize;
1392	// The offsets count from the start of the subtable, whose 10-byte header has
1393	// been stripped; fontTools slices with possibly negative indices.
1394	let read_u32 = |start: i64| -> Result<u32> {
1395		let s = py_slice(data, start, start + 4);
1396		if s.len() != 4 {
1397			return Err(unpack_error(4));
1398		}
1399		Ok(be32(s, 0))
1400	};
1401	for _ in 0..num_records {
1402		let rec = clamp(data, rec_offset, rec_offset + 11);
1403		if rec.len() != 11 {
1404			return Err(unpack_error(11));
1405		}
1406		rec_offset += 11;
1407		let var_uvs = be24(rec, 0);
1408		let def_offset = be32(rec, 3);
1409		let non_def_offset = be32(rec, 7);
1410		if def_offset != 0 {
1411			let mut start = def_offset as i64 - 10;
1412			let num_values = read_u32(start)?;
1413			start += 4;
1414			for _ in 0..num_values {
1415				let r = py_slice(data, start, start + 4);
1416				if r.len() != 4 {
1417					return Err(unpack_error(4));
1418				}
1419				start += 4;
1420				let first = be24(r, 0);
1421				let count = r[3] as u32 + 1;
1422				let list = uvs_dict.entry(var_uvs).or_default();
1423				list.extend((first..first + count).map(|uv| (uv, None)));
1424			}
1425		}
1426		if non_def_offset != 0 {
1427			let mut start = non_def_offset as i64 - 10;
1428			let num_recs = read_u32(start)?;
1429			start += 4;
1430			let mut local = Vec::new();
1431			for _ in 0..num_recs {
1432				let r = py_slice(data, start, start + record_size);
1433				if r.len() != record_size as usize {
1434					return Err(unpack_error(record_size as usize));
1435				}
1436				start += record_size;
1437				let uv = be24(r, 0);
1438				let gid = if kind == SubtableKind::Format15 {
1439					be24(r, 3)
1440				} else {
1441					be16(r, 3) as u32
1442				};
1443				local.push((uv, Some(gid)));
1444			}
1445			uvs_dict.entry(var_uvs).or_default().extend(local);
1446		}
1447	}
1448	Ok(uvs_dict)
1449}
1450
1451// ---------------------------------------------------------------------------
1452// Compiling
1453
1454fn compile_format_0(items: &[(u32, u32)], language: Option<u32>) -> Result<Vec<u8>> {
1455	if items.iter().any(|&(code, _)| code > 255) {
1456		return Err(Error::Assertion(
1457			"set(cmap.keys()).issubset(range(256))".into(),
1458		));
1459	}
1460	let mut gids = [0u32; 256];
1461	for &(code, gid) in items {
1462		gids[code as usize] = gid;
1463	}
1464	let mut data = Vec::with_capacity(262);
1465	data.put_u16(0);
1466	data.put_u16(262);
1467	data.put_u16(language_u16(language)?);
1468	for gid in gids {
1469		data.put_u8(
1470			u8::try_from(gid)
1471				.map_err(|_| Error::value("unsigned byte integer is greater than maximum"))?,
1472		);
1473	}
1474	Ok(data)
1475}
1476
1477fn check_16_bit_gids(items: &[(u32, u32)], format: u16) -> Result<()> {
1478	for &(_, gid) in items {
1479		if gid > 0xFFFF {
1480			return Err(Error::Struct(format!(
1481				"cmap format {format} cannot represent glyph ID {gid}"
1482			)));
1483		}
1484	}
1485	Ok(())
1486}
1487
1488/// `cmap_format_2.setIDDelta`.
1489fn set_id_delta(sub_header: &mut SubHeader) {
1490	sub_header.id_delta = 0;
1491	// An empty subheader (an all-notdef two-byte range) has no glyphs to adjust.
1492	let Some(&first) = sub_header.glyph_index_array.first() else {
1493		return;
1494	};
1495	// Find the minimum glyph index which is not zero.
1496	let mut min_gi = first;
1497	for &gid in &sub_header.glyph_index_array {
1498		if gid != 0 && gid < min_gi {
1499			min_gi = gid;
1500		}
1501	}
1502	// Pick an idDelta such that the first glyph index is 1, so that subranges are
1503	// more likely to be shared; idDelta is a short, so wrap around past 0x8000.
1504	if min_gi > 1 {
1505		let id_delta = if min_gi > 0x8000 {
1506			-(0x10000 - min_gi) - 1
1507		} else {
1508			min_gi - 1
1509		};
1510		sub_header.id_delta = id_delta;
1511		for i in 0..sub_header.entry_count as usize {
1512			let gid = sub_header.glyph_index_array[i];
1513			if gid > 0 {
1514				sub_header.glyph_index_array[i] = (gid - id_delta) & 0xFFFF;
1515			}
1516		}
1517	}
1518}
1519
1520fn compile_format_2(items: &[(u32, u32)], language: Option<u32>) -> Result<Vec<u8>> {
1521	check_16_bit_gids(items, 2)?;
1522	const EMPTY_TWO_CHAR_CODE_RANGE: i64 = -1;
1523	let new_sub_header = |first_code, entry_count, id_range_offset| SubHeader {
1524		first_code,
1525		entry_count,
1526		id_delta: 0,
1527		id_range_offset,
1528		glyph_index_array: Vec::new(),
1529	};
1530	// One-byte char codes all map to subheader 0; two-byte ranges are assumed to
1531	// map to the empty subheader unless proven otherwise.
1532	let mut sub_header_keys = [EMPTY_TWO_CHAR_CODE_RANGE; 256];
1533	let mut list: Vec<SubHeader> = Vec::new();
1534	// Char codes mapped to .notdef are left unencoded.
1535	let items: Vec<(i64, i64)> = items
1536		.iter()
1537		.filter(|&&(_, gid)| gid != 0)
1538		.map(|&(c, g)| (c as i64, g as i64))
1539		.collect();
1540	// A byte cannot be both a single-byte code and the first byte of a two-byte
1541	// code: report the lowest.
1542	let single_bytes: BTreeSet<i64> = items
1543		.iter()
1544		.map(|&(code, _)| code)
1545		.filter(|&code| code <= 0xFF)
1546		.collect();
1547	if let Some(conflict) = items
1548		.iter()
1549		.filter(|&&(code, _)| code > 0xFF)
1550		.map(|&(code, _)| code >> 8)
1551		.filter(|lead| single_bytes.contains(lead))
1552		.min()
1553	{
1554		return Err(Error::Struct(format!(
1555			"cmap format 2 cannot use byte 0x{conflict:02X} both as a single-byte code \
1556			 and as the first byte of a two-byte code"
1557		)));
1558	}
1559	// Force subheader 0 to exist when no one-byte char code is mapped.
1560	if items.first().is_none_or(|&(code, _)| code > 255) {
1561		list.push(new_sub_header(0, 0, 0));
1562	}
1563	let set_one_byte_keys = |keys: &mut [i64; 256], sh: &SubHeader| -> Result<()> {
1564		for index in 0..sh.entry_count {
1565			let code = (sh.first_code + index) as usize;
1566			*keys.get_mut(code).ok_or_else(index_error)? = 0;
1567		}
1568		Ok(())
1569	};
1570	let mut last_first_byte: i64 = -1;
1571	for &(char_code, gid) in &items {
1572		let first_byte = char_code >> 8;
1573		let second_byte = char_code & 0xFF;
1574		if first_byte != last_first_byte {
1575			if last_first_byte > -1
1576				&& let Some(sh) = list.last_mut()
1577			{
1578				set_id_delta(sh);
1579				if last_first_byte == 0 {
1580					set_one_byte_keys(&mut sub_header_keys, sh)?;
1581				}
1582			}
1583			let mut sh = new_sub_header(second_byte, 1, 0);
1584			sh.glyph_index_array.push(gid);
1585			list.push(sh);
1586			*sub_header_keys
1587				.get_mut(first_byte as usize)
1588				.ok_or_else(index_error)? = list.len() as i64 - 1;
1589			last_first_byte = first_byte;
1590		} else if let Some(sh) = list.last_mut() {
1591			// Fill in .notdef for the code points between the last and this one.
1592			let code_diff = second_byte - (sh.first_code + sh.entry_count);
1593			for _ in 0..code_diff {
1594				sh.glyph_index_array.push(0);
1595			}
1596			sh.glyph_index_array.push(gid);
1597			sh.entry_count += code_diff + 1;
1598		}
1599	}
1600	if let Some(sh) = list.last_mut() {
1601		set_id_delta(sh);
1602		if last_first_byte == 0 {
1603			set_one_byte_keys(&mut sub_header_keys, sh)?;
1604		}
1605	}
1606	// A final subheader for the first bytes that map to empty two-byte ranges.
1607	list.push(new_sub_header(0, 0, 2));
1608	let empty_index = list.len() as i64 - 1;
1609	for key in sub_header_keys.iter_mut() {
1610		if *key == EMPTY_TWO_CHAR_CODE_RANGE {
1611			*key = empty_index;
1612		}
1613	}
1614	// Offset to the start of the glyph index array from the first subheader's
1615	// idRangeOffset; subheaders with the same subrange share it.
1616	let mut id_range_offset = (list.len() as i64 - 1) * 8 + 2;
1617	for index in 0..list.len() - 1 {
1618		list[index].id_range_offset = 0;
1619		for j in 0..index {
1620			if list[j].glyph_index_array == list[index].glyph_index_array {
1621				list[index].id_range_offset = list[j].id_range_offset - (index - j) as i64 * 8;
1622				list[index].glyph_index_array = Vec::new();
1623				break;
1624			}
1625		}
1626		if list[index].id_range_offset == 0 {
1627			list[index].id_range_offset = id_range_offset;
1628			id_range_offset = (id_range_offset - 8) + list[index].entry_count * 2;
1629		} else {
1630			id_range_offset -= 8;
1631		}
1632	}
1633	let mut length = 6 + 512 + 8 * list.len();
1634	for sh in &list[..list.len() - 1] {
1635		length += sh.glyph_index_array.len() * 2;
1636	}
1637	let mut data = Vec::with_capacity(length);
1638	data.put_u16(2);
1639	data.put_u16(fit(length, "length")?);
1640	data.put_u16(language_u16(language)?);
1641	for key in sub_header_keys {
1642		data.put_u16(fit(key * 8, "subHeaderKeys")?);
1643	}
1644	for sh in &list {
1645		data.put_u16(fit(sh.first_code, "firstCode")?);
1646		data.put_u16(fit(sh.entry_count, "entryCount")?);
1647		data.put_i16(fit(sh.id_delta, "idDelta")?);
1648		data.put_u16(fit(sh.id_range_offset, "idRangeOffset")?);
1649	}
1650	for sh in &list[..list.len() - 1] {
1651		for &gi in &sh.glyph_index_array {
1652			data.put_u16(fit(gi, "glyphIndexArray")?);
1653		}
1654	}
1655	Ok(data)
1656}
1657
1658/// Splits a range of consecutive character codes into subranges with
1659/// consecutive glyph IDs, where that makes the format 4 subtable smaller
1660/// (`splitRange`). Returns the additional start codes and the end codes.
1661fn split_range(start_code: i64, end_code: i64, cmap: &HashMap<i64, i64>) -> (Vec<i64>, Vec<i64>) {
1662	if start_code == end_code {
1663		return (Vec::new(), vec![end_code]);
1664	}
1665	let gid = |code: i64| cmap.get(&code).copied().unwrap_or_default();
1666	let mut last_id = gid(start_code);
1667	let mut last_code = start_code;
1668	let mut in_order: Option<bool> = None;
1669	let mut ordered_begin = start_code;
1670	let mut sub_ranges: Vec<(i64, i64)> = Vec::new();
1671	// Gather subranges in which the glyph IDs are consecutive.
1672	for code in start_code + 1..=end_code {
1673		let glyph_id = gid(code);
1674		if glyph_id - 1 == last_id {
1675			if in_order != Some(true) {
1676				in_order = Some(true);
1677				ordered_begin = last_code;
1678			}
1679		} else if in_order == Some(true) {
1680			in_order = Some(false);
1681			sub_ranges.push((ordered_begin, last_code));
1682		}
1683		last_id = glyph_id;
1684		last_code = code;
1685	}
1686	if in_order == Some(true) {
1687		sub_ranges.push((ordered_begin, last_code));
1688	}
1689	// Filter out the subranges that would only make the data bigger: a new segment
1690	// costs 8 bytes, not using one costs 2 bytes per character.
1691	let mut new_ranges = Vec::new();
1692	for &(b, e) in &sub_ranges {
1693		if b == start_code && e == end_code {
1694			break; // the whole range, we're fine
1695		}
1696		let threshold = if b == start_code || e == end_code {
1697			4
1698		} else {
1699			8
1700		};
1701		if e - b + 1 > threshold {
1702			new_ranges.push((b, e));
1703		}
1704	}
1705	let mut sub_ranges = new_ranges;
1706	let (Some(&(first, _)), Some(&(_, last))) = (sub_ranges.first(), sub_ranges.last()) else {
1707		return (Vec::new(), vec![end_code]);
1708	};
1709	if first != start_code {
1710		sub_ranges.insert(0, (start_code, first - 1));
1711	}
1712	if last != end_code {
1713		sub_ranges.push((last + 1, end_code));
1714	}
1715	// Fill the holes: the segments in which the glyph IDs are not consecutive.
1716	let mut i = 1;
1717	while i < sub_ranges.len() {
1718		if sub_ranges[i - 1].1 + 1 != sub_ranges[i].0 {
1719			sub_ranges.insert(i, (sub_ranges[i - 1].1 + 1, sub_ranges[i].0 - 1));
1720			i += 1;
1721		}
1722		i += 1;
1723	}
1724	let mut start: Vec<i64> = sub_ranges.iter().map(|r| r.0).collect();
1725	let end: Vec<i64> = sub_ranges.iter().map(|r| r.1).collect();
1726	start.remove(0);
1727	(start, end)
1728}
1729
1730/// A value for `array.array("H", …)`.
1731fn u16_item(value: i64) -> Result<u16> {
1732	u16::try_from(value).map_err(|_| {
1733		Error::value(if value < 0 {
1734			"unsigned short is less than minimum"
1735		} else {
1736			"unsigned short is greater than maximum"
1737		})
1738	})
1739}
1740
1741fn compile_format_4(items: &[(u32, u32)], format: u16, language: Option<u32>) -> Result<Vec<u8>> {
1742	let mut cmap: HashMap<i64, i64> = HashMap::new();
1743	let (start_code, end_code) = if items.is_empty() {
1744		(vec![0xFFFF], vec![0xFFFF])
1745	} else {
1746		check_16_bit_gids(items, 4)?;
1747		for &(code, gid) in items {
1748			cmap.insert(code as i64, gid as i64);
1749		}
1750		// Split the char codes in ranges of consecutive char codes, then split each
1751		// range in more ranges of consecutive/not consecutive glyph IDs.
1752		let codes: Vec<i64> = items.iter().map(|&(c, _)| c as i64).collect();
1753		let mut last_code = codes[0];
1754		let mut end_code = Vec::new();
1755		let mut start_code = vec![last_code];
1756		for &code in &codes[1..] {
1757			if code == last_code + 1 {
1758				last_code = code;
1759				continue;
1760			}
1761			let (start, end) = split_range(start_code[start_code.len() - 1], last_code, &cmap);
1762			start_code.extend(start);
1763			end_code.extend(end);
1764			start_code.push(code);
1765			last_code = code;
1766		}
1767		let (start, end) = split_range(start_code[start_code.len() - 1], last_code, &cmap);
1768		start_code.extend(start);
1769		end_code.extend(end);
1770		start_code.push(0xFFFF);
1771		end_code.push(0xFFFF);
1772		(start_code, end_code)
1773	};
1774
1775	let mut id_delta = Vec::new();
1776	let mut id_range_offset = Vec::new();
1777	let mut glyph_index_array: Vec<i64> = Vec::new();
1778	for i in 0..end_code.len() - 1 {
1779		// skip the closing codes (0xffff)
1780		let indices: Vec<i64> = (start_code[i]..=end_code[i])
1781			.map(|c| cmap.get(&c).copied().unwrap_or_default())
1782			.collect();
1783		let consecutive = indices
1784			.iter()
1785			.enumerate()
1786			.all(|(k, &g)| g == indices[0] + k as i64);
1787		if consecutive {
1788			id_delta.push((indices[0] - start_code[i]).rem_euclid(0x10000));
1789			id_range_offset.push(0);
1790		} else {
1791			id_delta.push(0);
1792			id_range_offset.push(2 * (end_code.len() + glyph_index_array.len() - i) as i64);
1793			glyph_index_array.extend(indices);
1794		}
1795	}
1796	id_delta.push(1); // 0xffff + 1 == 0, so this end code maps to .notdef
1797	id_range_offset.push(0);
1798
1799	let seg_count = end_code.len();
1800	let (search_range, entry_selector, range_shift) =
1801		get_search_range(fit(seg_count, "segCount")?, 2);
1802	let mut data = Vec::new();
1803	for &v in end_code.iter().chain(&[0]).chain(&start_code) {
1804		data.put_u16(u16_item(v)?);
1805	}
1806	for &v in id_delta
1807		.iter()
1808		.chain(&id_range_offset)
1809		.chain(&glyph_index_array)
1810	{
1811		data.put_u16(u16_item(v)?);
1812	}
1813	let length = 14 + data.len();
1814	let mut out = Vec::with_capacity(length);
1815	out.put_u16(format);
1816	out.put_u16(fit(length, "length")?);
1817	out.put_u16(language_u16(language)?);
1818	out.put_u16(fit(seg_count * 2, "segCountX2")?);
1819	out.put_u16(fit(search_range, "searchRange")?);
1820	out.put_u16(fit(entry_selector, "entrySelector")?);
1821	out.put_u16(fit(range_shift, "rangeShift")?);
1822	out.extend(data);
1823	Ok(out)
1824}
1825
1826fn compile_format_6(items: &[(u32, u32)], language: Option<u32>) -> Result<Vec<u8>> {
1827	let mut gids = Vec::new();
1828	let (first_code, count) = match (items.first(), items.last()) {
1829		(Some(&(first, _)), Some(&(last, _))) => {
1830			let map: HashMap<u32, u32> = items.iter().copied().collect();
1831			for code in first..=last {
1832				let gid = map.get(&code).copied().unwrap_or(0);
1833				gids.put_u16(u16_item(gid as i64)?);
1834			}
1835			(first, (last - first) as usize + 1)
1836		}
1837		_ => (0, 0),
1838	};
1839	let mut data = Vec::with_capacity(10 + gids.len());
1840	data.put_u16(6);
1841	data.put_u16(fit(gids.len() + 10, "length")?);
1842	data.put_u16(language_u16(language)?);
1843	data.put_u16(fit(first_code, "firstCode")?);
1844	data.put_u16(fit(count, "entryCount")?);
1845	data.extend(gids);
1846	Ok(data)
1847}
1848
1849#[cfg(test)]
1850mod tests;