Skip to main content

fontoxide_ttlib/tables/
name.rs

1//! `name`: Naming table (`fontTools.ttLib.tables._n_a_m_e`).
2
3use std::cmp::Ordering;
4use std::collections::HashMap;
5
6use fontoxide_encodings::codecs;
7use fontoxide_misc::Tag;
8use fontoxide_misc::encoding_tools::get_encoding;
9use fontoxide_misc::xml_reader::Element;
10use fontoxide_misc::xml_writer::XmlWriter;
11
12use crate::binary::{Reader, WriteBytes};
13use crate::sstruct::{U16, eval};
14use crate::table::{Table, TableType, TableXml};
15use crate::{Error, Font, Result};
16
17crate::sstruct! {
18	/// A name record as stored (`nameRecordFormat`).
19	pub struct NameRecordFormat = "nameRecordFormat" {
20		/// Platform ID.
21		pub platform_id: u16 = "platformID" as U16,
22		/// Platform-specific encoding ID.
23		pub plat_enc_id: u16 = "platEncID" as U16,
24		/// Language ID.
25		pub lang_id: u16 = "langID" as U16,
26		/// Name ID.
27		pub name_id: u16 = "nameID" as U16,
28		/// String length in bytes.
29		pub length: u16 = "length" as U16,
30		/// String offset from the start of the string storage.
31		pub offset: u16 = "offset" as U16,
32	}
33}
34
35/// The string of a name record: raw bytes as read from a font, or text set by the
36/// user (fontTools allows both `bytes` and `str`).
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum NameString {
39	/// Encoded bytes.
40	Bytes(Vec<u8>),
41	/// Text, encoded with the record's encoding when compiling.
42	Text(String),
43}
44
45impl Default for NameString {
46	fn default() -> Self {
47		NameString::Bytes(Vec::new())
48	}
49}
50
51impl From<&str> for NameString {
52	fn from(s: &str) -> Self {
53		NameString::Text(s.to_owned())
54	}
55}
56
57impl From<String> for NameString {
58	fn from(s: String) -> Self {
59		NameString::Text(s)
60	}
61}
62
63impl From<Vec<u8>> for NameString {
64	fn from(b: Vec<u8>) -> Self {
65		NameString::Bytes(b)
66	}
67}
68
69/// A name record (`NameRecord`).
70#[derive(Debug, Clone, PartialEq, Eq, Default)]
71pub struct NameRecord {
72	/// Name ID.
73	pub name_id: u16,
74	/// Platform ID.
75	pub platform_id: u16,
76	/// Platform-specific encoding ID.
77	pub plat_enc_id: u16,
78	/// Language ID.
79	pub lang_id: u16,
80	/// The string.
81	pub string: NameString,
82}
83
84fn is_ascii_char(b: u32) -> bool {
85	(0x20..=0x7E).contains(&b) || matches!(b, 0x09 | 0x0A | 0x0D)
86}
87
88impl NameRecord {
89	/// A record with the given string and IDs (`makeName`).
90	pub fn new(
91		string: impl Into<NameString>,
92		name_id: u16,
93		platform_id: u16,
94		plat_enc_id: u16,
95		lang_id: u16,
96	) -> Self {
97		NameRecord {
98			name_id,
99			platform_id,
100			plat_enc_id,
101			lang_id,
102			string: string.into(),
103		}
104	}
105
106	/// The codec for this record, or `"ascii"` if unknown (`getEncoding()`).
107	pub fn encoding(&self) -> &'static str {
108		get_encoding(self.platform_id, self.plat_enc_id, self.lang_id).unwrap_or("ascii")
109	}
110
111	/// Whether the encoding can represent any text (`encodingIsUnicodeCompatible`).
112	pub fn encoding_is_unicode_compatible(&self) -> bool {
113		matches!(
114			get_encoding(self.platform_id, self.plat_enc_id, self.lang_id),
115			Some("utf_16_be" | "ucs2be" | "ascii" | "latin1")
116		)
117	}
118
119	/// Whether the string is Unicode (`isUnicode`).
120	pub fn is_unicode(&self) -> bool {
121		self.platform_id == 0 || (self.platform_id == 3 && matches!(self.plat_enc_id, 0 | 1 | 10))
122	}
123
124	/// The string as text (`toUnicode()`), with fontTools' heuristics to recover
125	/// misencoded UTF-16.
126	pub fn to_unicode(&self) -> std::result::Result<String, codecs::CodecError> {
127		self.to_unicode_with(codecs::Errors::Strict)
128	}
129
130	/// [`NameRecord::to_unicode`], with bytes that cannot be decoded handled by
131	/// `errors` (`toUnicode(errors)`, `toStr(errors)`).
132	pub fn to_unicode_with(
133		&self,
134		errors: codecs::Errors,
135	) -> std::result::Result<String, codecs::CodecError> {
136		let encoding = self.encoding();
137		let mut string = match &self.string {
138			NameString::Text(s) => s.clone(),
139			NameString::Bytes(bytes) => {
140				let mut bytes = bytes.clone();
141				if encoding == "utf_16_be" && bytes.len() % 2 == 1 {
142					// Recover badly encoded UTF-16 strings that have an odd number
143					// of bytes:
144					// - If the last byte is zero, drop it. Otherwise,
145					// - If all the odd bytes are zero and all the even bytes are
146					//   ASCII, prepend one zero byte. Otherwise,
147					// - If the first byte is zero and all other bytes are ASCII,
148					//   insert zero bytes between consecutive ASCII bytes.
149					if bytes.last() == Some(&0) {
150						bytes.pop();
151					} else if bytes.iter().enumerate().all(|(i, &b)| {
152						if i % 2 == 1 {
153							b == 0
154						} else {
155							is_ascii_char(b as u32)
156						}
157					}) {
158						bytes.insert(0, 0);
159					} else if bytes[0] == 0 && bytes[1..].iter().all(|&b| is_ascii_char(b as u32)) {
160						bytes = bytes[1..].iter().flat_map(|&b| [0, b]).collect();
161					}
162				}
163				codecs::decode_with(encoding, &bytes, errors)?
164			}
165		};
166		// If the decoded string still looks like UTF-16BE, it suggests a double
167		// encoding; narrow it down.
168		if string.chars().enumerate().all(|(i, c)| {
169			if i % 2 == 0 {
170				c == '\0'
171			} else {
172				is_ascii_char(c as u32)
173			}
174		}) {
175			string = string.chars().skip(1).step_by(2).collect();
176		}
177		Ok(string)
178	}
179
180	/// The encoded string (`toBytes()`).
181	pub fn to_bytes(&self) -> std::result::Result<Vec<u8>, codecs::CodecError> {
182		self.to_bytes_with(codecs::Errors::Strict)
183	}
184
185	/// [`NameRecord::to_bytes`], with characters that cannot be encoded handled
186	/// by `errors` (`toBytes(errors)`).
187	pub fn to_bytes_with(
188		&self,
189		errors: codecs::Errors,
190	) -> std::result::Result<Vec<u8>, codecs::CodecError> {
191		match &self.string {
192			NameString::Bytes(b) => Ok(b.clone()),
193			NameString::Text(s) => codecs::encode_with(self.encoding(), s, errors),
194		}
195	}
196
197	/// The string with undecodable bytes escaped (`str(record)`, which is
198	/// `toStr(errors="backslashreplace")`).
199	pub fn to_str_lossy(&self) -> String {
200		match self.to_unicode_with(codecs::Errors::BackslashReplace) {
201			Ok(s) => s,
202			// Only for codecs that fontoxide does not have.
203			Err(_) => match &self.string {
204				NameString::Bytes(b) => b
205					.iter()
206					.map(|&c| {
207						if c < 0x80 {
208							(c as char).to_string()
209						} else {
210							format!("\\x{c:02x}")
211						}
212					})
213					.collect(),
214				NameString::Text(s) => s.clone(),
215			},
216		}
217	}
218
219	fn ids(&self) -> (u16, u16, u16, u16) {
220		(
221			self.platform_id,
222			self.plat_enc_id,
223			self.lang_id,
224			self.name_id,
225		)
226	}
227
228	fn to_xml(&self, writer: &mut XmlWriter) {
229		let unistr = self.to_unicode().ok();
230		let lang_id = format!("{:#x}", self.lang_id);
231		let unicode = unistr.is_some();
232		let mut attrs: Vec<(&str, &dyn fontoxide_misc::xml_writer::AttrValue)> = vec![
233			("nameID", &self.name_id),
234			("platformID", &self.platform_id),
235			("platEncID", &self.plat_enc_id),
236			("langID", &lang_id),
237		];
238		if unistr.is_none() || !self.encoding_is_unicode_compatible() {
239			attrs.push(("unicode", &unicode));
240		}
241		writer.begintag_ordered("namerecord", &attrs);
242		writer.newline();
243		match (&unistr, &self.string) {
244			(Some(s), _) => writer.write(s),
245			(None, NameString::Bytes(b)) => writer.write8bit(b, false),
246			(None, NameString::Text(s)) => writer.write(s),
247		}
248		writer.newline();
249		writer.endtag("namerecord");
250		writer.newline();
251	}
252
253	fn from_xml(element: &Element) -> Result<Self> {
254		let attr = |name: &str| {
255			element
256				.attr(name)
257				.ok_or_else(|| Error::ttx(format!("missing '{name}' on <namerecord>")))
258		};
259		let int = |name: &str| -> Result<u16> {
260			let v = eval(attr(name)?)?
261				.as_int()
262				.ok_or_else(|| Error::value(format!("invalid {name}")))?;
263			crate::binary::fit(v, name)
264		};
265		let mut record = NameRecord {
266			name_id: int("nameID")?,
267			platform_id: int("platformID")?,
268			plat_enc_id: int("platEncID")?,
269			lang_id: int("langID")?,
270			string: NameString::default(),
271		};
272		let text = element.text();
273		let s = fontoxide_misc::py::strip(&text);
274		let unicode = element
275			.attr("unicode")
276			.map(eval)
277			.transpose()?
278			.is_some_and(|v| v.is_truthy());
279		let bytes = if record.encoding_is_unicode_compatible() || unicode {
280			codecs::encode(record.encoding(), s).map_err(|e| Error::value(e.to_string()))?
281		} else {
282			// The inverse of write8bit.
283			fontoxide_misc::py::latin1_encode(s)
284				.ok_or_else(|| Error::value("'latin-1' codec can't encode the name record"))?
285		};
286		record.string = NameString::Bytes(bytes);
287		Ok(record)
288	}
289}
290
291/// `NameRecord.__lt__`, which compares the IDs and, if both strings can be
292/// encoded, the encoded strings.
293fn record_cmp(a: &(NameRecord, Option<Vec<u8>>), b: &(NameRecord, Option<Vec<u8>>)) -> Ordering {
294	let ids = a.0.ids().cmp(&b.0.ids());
295	match (&a.1, &b.1) {
296		(Some(x), Some(y)) => ids.then_with(|| x.cmp(y)),
297		_ => ids,
298	}
299}
300
301/// A stable merge sort that, unlike `slice::sort_by`, tolerates the inconsistent
302/// comparisons `record_cmp` can produce when some strings fail to encode.
303fn merge_sort<T: Clone>(items: &mut [T], cmp: &impl Fn(&T, &T) -> Ordering) {
304	if items.len() <= 1 {
305		return;
306	}
307	let mid = items.len() / 2;
308	merge_sort(&mut items[..mid], cmp);
309	merge_sort(&mut items[mid..], cmp);
310	let mut merged = Vec::with_capacity(items.len());
311	let (mut i, mut j) = (0, mid);
312	while i < mid && j < items.len() {
313		if cmp(&items[j], &items[i]) == Ordering::Less {
314			merged.push(items[j].clone());
315			j += 1;
316		} else {
317			merged.push(items[i].clone());
318			i += 1;
319		}
320	}
321	merged.extend_from_slice(&items[i..mid]);
322	merged.extend_from_slice(&items[j..]);
323	items.clone_from_slice(&merged);
324}
325
326/// Naming table (`table__n_a_m_e`).
327///
328/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/name>.
329#[derive(Debug, Clone, PartialEq, Default)]
330pub struct Name {
331	/// The name records (`names`).
332	pub names: Vec<NameRecord>,
333}
334
335impl Name {
336	/// The first record with the given IDs; any language if `lang_id` is `None`
337	/// (`getName`).
338	pub fn get_name(
339		&self,
340		name_id: u16,
341		platform_id: u16,
342		plat_enc_id: u16,
343		lang_id: Option<u16>,
344	) -> Option<&NameRecord> {
345		self.names.iter().find(|r| {
346			r.name_id == name_id
347				&& r.platform_id == platform_id
348				&& r.plat_enc_id == plat_enc_id
349				&& lang_id.is_none_or(|l| r.lang_id == l)
350		})
351	}
352
353	/// A name for debugging or display, preferring Windows English, then Mac
354	/// English, then any decodable record (`getDebugName`).
355	pub fn get_debug_name(&self, name_id: u16) -> Option<String> {
356		let mut mac_english = None;
357		let mut some = None;
358		for record in self.names.iter().filter(|r| r.name_id == name_id) {
359			let Ok(s) = record.to_unicode() else {
360				continue;
361			};
362			if (record.platform_id, record.lang_id) == (3, 0x409) {
363				if !s.is_empty() {
364					return Some(s);
365				}
366				some = Some(s);
367				break;
368			}
369			if (record.platform_id, record.lang_id) == (1, 0) && mac_english.is_none() {
370				mac_english = Some(s.clone());
371			}
372			some = Some(s);
373		}
374		// fontTools tests the candidates for truthiness, so empty strings are
375		// skipped except as the last resort.
376		mac_english
377			.filter(|s| !s.is_empty())
378			.or_else(|| some.filter(|s| !s.is_empty()))
379	}
380
381	/// The first name found for the given IDs (`getFirstDebugName`).
382	pub fn get_first_debug_name(&self, name_ids: &[u16]) -> Option<String> {
383		name_ids.iter().find_map(|&id| self.get_debug_name(id))
384	}
385
386	/// WWS, typographic or legacy family name (`getBestFamilyName`).
387	pub fn best_family_name(&self) -> Option<String> {
388		self.get_first_debug_name(&[21, 16, 1])
389	}
390
391	/// WWS, typographic or legacy subfamily name (`getBestSubFamilyName`).
392	pub fn best_sub_family_name(&self) -> Option<String> {
393		self.get_first_debug_name(&[22, 17, 2])
394	}
395
396	/// The full name, from the family and subfamily names or name IDs 4 or 6
397	/// (`getBestFullName`).
398	pub fn best_full_name(&self) -> Option<String> {
399		for (family, sub) in [(21, 22), (16, 17), (1, 2)] {
400			let (Some(fam), Some(subfam)) = (self.get_debug_name(family), self.get_debug_name(sub))
401			else {
402				continue;
403			};
404			return Some(if subfam.to_lowercase() == "regular" {
405				fam
406			} else {
407				format!("{fam} {subfam}")
408			});
409		}
410		self.get_debug_name(4).or_else(|| self.get_debug_name(6))
411	}
412
413	/// Sets the string of a record, adding the record if needed (`setName`).
414	pub fn set_name(
415		&mut self,
416		string: impl Into<NameString>,
417		name_id: u16,
418		platform_id: u16,
419		plat_enc_id: u16,
420		lang_id: u16,
421	) {
422		let string = string.into();
423		if let NameString::Bytes(b) = &string {
424			log::warn!(
425				"name string is bytes, ensure it's correctly encoded: {}",
426				fontoxide_misc::py::bytes_repr(b)
427			);
428		}
429		match self.names.iter_mut().find(|r| {
430			r.name_id == name_id
431				&& r.platform_id == platform_id
432				&& r.plat_enc_id == plat_enc_id
433				&& r.lang_id == lang_id
434		}) {
435			Some(r) => r.string = string,
436			None => self.names.push(NameRecord::new(
437				string,
438				name_id,
439				platform_id,
440				plat_enc_id,
441				lang_id,
442			)),
443		}
444	}
445
446	/// Removes the records matching all the given IDs (`removeNames`). Without any
447	/// ID, nothing is removed.
448	pub fn remove_names(
449		&mut self,
450		name_id: Option<u16>,
451		platform_id: Option<u16>,
452		plat_enc_id: Option<u16>,
453		lang_id: Option<u16>,
454	) {
455		if name_id.is_none() && platform_id.is_none() && plat_enc_id.is_none() && lang_id.is_none()
456		{
457			return;
458		}
459		self.names.retain(|r| {
460			name_id.is_some_and(|v| v != r.name_id)
461				|| platform_id.is_some_and(|v| v != r.platform_id)
462				|| plat_enc_id.is_some_and(|v| v != r.plat_enc_id)
463				|| lang_id.is_some_and(|v| v != r.lang_id)
464		});
465	}
466
467	/// An unused name ID after the highest one in the table, at least
468	/// `min_name_id` (`_findUnusedNameID`).
469	pub fn find_unused_name_id(&self, min_name_id: u16) -> Result<u16> {
470		let name_id = 1 + self
471			.names
472			.iter()
473			.map(|n| n.name_id as i64)
474			.chain([min_name_id as i64 - 1])
475			.max()
476			.unwrap_or(-1);
477		if name_id > 32767 {
478			return Err(Error::value("nameID must be less than 32768"));
479		}
480		Ok(name_id as u16)
481	}
482
483	/// Adds records for `string` on each `(platformID, platEncID, langID)` and
484	/// returns the new name ID, which is above `min_name_id` (`addName`).
485	pub fn add_name(
486		&mut self,
487		string: &str,
488		platforms: &[(u16, u16, u16)],
489		min_name_id: u16,
490	) -> Result<u16> {
491		if platforms.is_empty() {
492			return Err(Error::Assertion(
493				"'platforms' must contain at least one (platformID, platEncID, langID) tuple"
494					.into(),
495			));
496		}
497		let name_id = self.find_unused_name_id(min_name_id.saturating_add(1))?;
498		for &(p, e, l) in platforms {
499			self.names.push(NameRecord::new(string, name_id, p, e, l));
500		}
501		Ok(name_id)
502	}
503
504	/// [`Name::add_name`] with fontTools' default platforms: Macintosh English
505	/// and Windows English (US), and a minimum name ID of 255.
506	pub fn add_name_default(&mut self, string: &str) -> Result<u16> {
507		self.add_name(string, &[(1, 0, 0), (3, 1, 0x409)], 255)
508	}
509
510	/// The name ID of existing records that hold all of `names` (BCP 47
511	/// language tag to string), at least `min_name_id`; `None` if there are none
512	/// (`findMultilingualName` without a font: names that would need an `ltag`
513	/// table are left out). See [`find_multilingual_name`] for the version with a
514	/// font.
515	pub fn find_multilingual_name(
516		&self,
517		names: &[(&str, &str)],
518		windows: bool,
519		mac: bool,
520		min_name_id: u16,
521	) -> Result<Option<u16>> {
522		self.find_multilingual_name_with(names, windows, mac, min_name_id, &mut no_ltag)
523	}
524
525	/// `findMultilingualName`, with `ltag` adding a language tag to the font's
526	/// `ltag` table (`None` without a font).
527	fn find_multilingual_name_with(
528		&self,
529		names: &[(&str, &str)],
530		windows: bool,
531		mac: bool,
532		min_name_id: u16,
533		ltag: &mut LtagFn<'_>,
534	) -> Result<Option<u16>> {
535		let mut sorted = names.to_vec();
536		sorted.sort();
537		let mut requested: Vec<(String, u16, u16, u16)> = Vec::new();
538		let mut add = |r: NameRecord| {
539			let key = (r.text(), r.platform_id, r.plat_enc_id, r.lang_id);
540			if !requested.contains(&key) {
541				requested.push(key);
542			}
543		};
544		for &(lang, name) in &sorted {
545			if windows && let Some(r) = make_windows_name(name, 0, lang) {
546				add(r);
547			}
548			if mac && let Some(r) = make_mac_name(name, 0, lang, ltag)? {
549				add(r);
550			}
551		}
552		let mut matching: std::collections::BTreeMap<u16, Vec<(String, u16, u16, u16)>> =
553			std::collections::BTreeMap::new();
554		for record in &self.names {
555			let Ok(s) = record.to_unicode() else {
556				continue;
557			};
558			let key = (s, record.platform_id, record.plat_enc_id, record.lang_id);
559			if requested.contains(&key) && record.name_id >= min_name_id {
560				let set = matching.entry(record.name_id).or_default();
561				if !set.contains(&key) {
562					set.push(key);
563				}
564			}
565		}
566		Ok(matching
567			.into_iter()
568			.find(|(_, set)| set.len() == requested.len())
569			.map(|(id, _)| id))
570	}
571
572	/// Adds records for a name in several languages (BCP 47 language tag to
573	/// string) and returns its name ID (`addMultilingualName` without a font).
574	///
575	/// Without `name_id`, the ID of existing matching records is reused if there
576	/// are any, otherwise an unused ID is picked. Names that would need an `ltag`
577	/// table are left out; see [`add_multilingual_name`] for the version with a
578	/// font.
579	pub fn add_multilingual_name(
580		&mut self,
581		names: &[(&str, &str)],
582		name_id: Option<u16>,
583		windows: bool,
584		mac: bool,
585		min_name_id: u16,
586	) -> Result<u16> {
587		self.add_multilingual_name_with(names, name_id, windows, mac, min_name_id, &mut no_ltag)
588	}
589
590	fn add_multilingual_name_with(
591		&mut self,
592		names: &[(&str, &str)],
593		name_id: Option<u16>,
594		windows: bool,
595		mut mac: bool,
596		min_name_id: u16,
597		ltag: &mut LtagFn<'_>,
598	) -> Result<u16> {
599		let name_id = match name_id {
600			Some(id) => id,
601			None => {
602				if let Some(id) =
603					self.find_multilingual_name_with(names, windows, mac, min_name_id, ltag)?
604				{
605					return Ok(id);
606				}
607				// fontTools does not pass minNameID here.
608				self.find_unused_name_id(256)?
609			}
610		};
611		let mut sorted = names.to_vec();
612		sorted.sort();
613		for (lang, name) in sorted {
614			if windows {
615				match make_windows_name(name, name_id, lang) {
616					Some(r) => self.names.push(r),
617					// Without a Windows name, make sure there is a Mac name.
618					None => mac = true,
619				}
620			}
621			if mac && let Some(r) = make_mac_name(name, name_id, lang, ltag)? {
622				self.names.push(r);
623			}
624		}
625		Ok(name_id)
626	}
627}
628
629/// Adds a language tag to the font's `ltag` table and returns its index.
630type LtagFn<'a> = dyn FnMut(&str) -> Result<Option<u16>> + 'a;
631
632fn no_ltag(_: &str) -> Result<Option<u16>> {
633	Ok(None)
634}
635
636/// The `ltag` table function for a font: like fontTools, it adds a new `ltag` table
637/// unless the font has one decompiled already.
638fn font_ltag(font: &mut Font) -> impl FnMut(&str) -> Result<Option<u16>> + '_ {
639	move |lang| {
640		let tag = <crate::tables::misc_tables::Ltag as TableType>::TAG;
641		if !font.is_loaded(tag) {
642			font.insert(Box::new(crate::tables::misc_tables::Ltag::default()));
643		}
644		let ltag = font.require::<crate::tables::misc_tables::Ltag>()?;
645		crate::binary::fit(ltag.add_tag(lang) as u64, "langID").map(Some)
646	}
647}
648
649/// `font["name"].findMultilingualName(names, ..., ttFont=font)`: see
650/// [`Name::find_multilingual_name`]. Names in languages that need it may add
651/// tags to the font's `ltag` table, as in fontTools.
652pub fn find_multilingual_name(
653	font: &mut Font,
654	names: &[(&str, &str)],
655	windows: bool,
656	mac: bool,
657	min_name_id: u16,
658) -> Result<Option<u16>> {
659	font.with_table(<Name as TableType>::TAG, |t, font| {
660		let name = name_table(t)?;
661		name.find_multilingual_name_with(names, windows, mac, min_name_id, &mut font_ltag(font))
662	})
663}
664
665/// `font["name"].addMultilingualName(names, ttFont=font, ...)`: see
666/// [`Name::add_multilingual_name`]. Names that a Macintosh encoding cannot
667/// represent are added as Unicode records whose language is a tag of the
668/// font's `ltag` table.
669pub fn add_multilingual_name(
670	font: &mut Font,
671	names: &[(&str, &str)],
672	name_id: Option<u16>,
673	windows: bool,
674	mac: bool,
675	min_name_id: u16,
676) -> Result<u16> {
677	font.with_table(<Name as TableType>::TAG, |t, font| {
678		let name = name_table(t)?;
679		name.add_multilingual_name_with(
680			names,
681			name_id,
682			windows,
683			mac,
684			min_name_id,
685			&mut font_ltag(font),
686		)
687	})
688}
689
690fn name_table(t: &mut dyn Table) -> Result<&mut Name> {
691	t.as_any_mut()
692		.downcast_mut::<Name>()
693		.ok_or(Error::WrongTableType(<Name as TableType>::TAG))
694}
695
696fn lookup(table: &[(&str, u16)], key: &str) -> Option<u16> {
697	table
698		.binary_search_by(|(k, _)| (*k).cmp(key))
699		.ok()
700		.map(|i| table[i].1)
701}
702
703/// A Windows name record for a BCP 47 language, if Windows has a language ID for
704/// it (`_makeWindowsName`).
705fn make_windows_name(name: &str, name_id: u16, language: &str) -> Option<NameRecord> {
706	let lang = language.to_lowercase();
707	match lookup(super::name_languages::WINDOWS_LANGUAGE_CODES, &lang) {
708		Some(lang_id) => Some(NameRecord::new(name, name_id, 3, 1, lang_id)),
709		None => {
710			log::warn!(
711				"cannot add Windows name in language {language} because fonttools does not yet support name table format 1"
712			);
713			None
714		}
715	}
716}
717
718/// A Macintosh name record for a BCP 47 language (`_makeMacName`): with a legacy
719/// language and encoding if possible, otherwise Unicode with an `ltag` language.
720fn make_mac_name(
721	name: &str,
722	name_id: u16,
723	language: &str,
724	ltag: &mut LtagFn<'_>,
725) -> Result<Option<NameRecord>> {
726	let lang = language.to_lowercase();
727	let mac_lang = lookup(super::name_languages::MAC_LANGUAGE_CODES, &lang);
728	let mac_script = mac_lang.and_then(|l| {
729		let table = super::name_languages::MAC_LANGUAGE_TO_SCRIPT;
730		table
731			.binary_search_by_key(&l, |&(k, _)| k)
732			.ok()
733			.map(|i| table[i].1)
734	});
735	if let (Some(mac_lang), Some(mac_script)) = (mac_lang, mac_script) {
736		let encoding = get_encoding(1, mac_script, mac_lang).unwrap_or("ascii");
737		if codecs::encode(encoding, name).is_ok() {
738			return Ok(Some(NameRecord::new(
739				name, name_id, 1, mac_script, mac_lang,
740			)));
741		}
742	}
743	match ltag(language)? {
744		// 0 = Unicode; 4 = Unicode 2.0 or later semantics.
745		Some(index) => Ok(Some(NameRecord::new(name, name_id, 0, 4, index))),
746		None => {
747			log::warn!(
748				"cannot store language {language} into 'ltag' table without having access to the TTFont object"
749			);
750			Ok(None)
751		}
752	}
753}
754
755impl NameRecord {
756	/// The string as text, for records made from text.
757	fn text(&self) -> String {
758		match &self.string {
759			NameString::Text(s) => s.clone(),
760			NameString::Bytes(_) => self.to_str_lossy(),
761		}
762	}
763}
764
765impl Name {
766	/// Sorts the records as the specification requires (`names.sort()`).
767	pub fn sort(&mut self) {
768		let mut keyed: Vec<(NameRecord, Option<Vec<u8>>)> = self
769			.names
770			.drain(..)
771			.map(|r| {
772				let b = r.to_bytes();
773				if let Err(e) = &b {
774					log::error!("NameRecord sorting failed to encode: {e}");
775				}
776				let b = b.ok();
777				(r, b)
778			})
779			.collect();
780		merge_sort(&mut keyed, &record_cmp);
781		self.names = keyed.into_iter().map(|(r, _)| r).collect();
782	}
783}
784
785impl TableType for Name {
786	const TAG: Tag = Tag::new(b"name");
787
788	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
789		let mut r = Reader::new(data);
790		let _format = r.u16()?;
791		let n = r.u16()? as usize;
792		let string_offset = r.u16()? as usize;
793		let expected = 6 + n * NameRecordFormat::SIZE;
794		if string_offset != expected {
795			log::error!(
796				"'name' table stringOffset incorrect. Expected: {expected}; Actual: {string_offset}"
797			);
798		}
799		let string_data = data.get(string_offset..).unwrap_or_default();
800		let mut records = &data[6..];
801		let mut names = Vec::with_capacity(n);
802		for i in 0..n {
803			if records.len() < 12 {
804				log::error!("skipping malformed name record #{i}");
805				continue;
806			}
807			let (rec, rest) = NameRecordFormat::unpack2(records)?;
808			records = rest;
809			let start = rec.offset as usize;
810			let end = start + rec.length as usize;
811			if end > string_data.len() {
812				log::error!("skipping malformed name record #{i}");
813				continue;
814			}
815			names.push(NameRecord {
816				name_id: rec.name_id,
817				platform_id: rec.platform_id,
818				plat_enc_id: rec.plat_enc_id,
819				lang_id: rec.lang_id,
820				string: NameString::Bytes(string_data[start..end].to_vec()),
821			});
822		}
823		Ok(Name { names })
824	}
825}
826
827impl Table for Name {
828	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
829		let _ = f;
830		Ok(())
831	}
832
833	fn tag(&self) -> Tag {
834		Self::TAG
835	}
836
837	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
838		self.sort();
839		let n = self.names.len();
840		let string_offset = 6 + n * NameRecordFormat::SIZE;
841		let mut data = Vec::with_capacity(string_offset);
842		data.put_u16(0);
843		data.put_u16(crate::binary::fit(n, "count")?);
844		data.put_u16(crate::binary::fit(string_offset, "stringOffset")?);
845		let mut string_data: Vec<u8> = Vec::new();
846		let mut done: HashMap<Vec<u8>, (usize, usize)> = HashMap::new();
847		for name in &self.names {
848			let string = name.to_bytes().map_err(|e| Error::value(e.to_string()))?;
849			let (offset, length) = match done.get(&string) {
850				Some(&v) => v,
851				None => {
852					let v = (string_data.len(), string.len());
853					string_data.extend_from_slice(&string);
854					done.insert(string, v);
855					v
856				}
857			};
858			NameRecordFormat {
859				platform_id: name.platform_id,
860				plat_enc_id: name.plat_enc_id,
861				lang_id: name.lang_id,
862				name_id: name.name_id,
863				length: crate::binary::fit(length, "length")?,
864				offset: crate::binary::fit(offset, "offset")?,
865			}
866			.pack(&mut data)?;
867		}
868		data.extend(string_data);
869		Ok(data)
870	}
871
872	fn clone_table(&self) -> Box<dyn Table> {
873		Box::new(self.clone())
874	}
875}
876
877impl TableXml for Name {
878	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
879		for name in &self.names {
880			name.to_xml(writer);
881		}
882		Ok(())
883	}
884
885	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
886		if element.name != "namerecord" {
887			return Ok(());
888		}
889		self.names.push(NameRecord::from_xml(element)?);
890		Ok(())
891	}
892}
893
894#[cfg(test)]
895mod tests {
896	use super::*;
897
898	#[test]
899	fn format_matches_upstream() {
900		crate::sstruct::tests::check(NameRecordFormat::FORMAT_NAME, NameRecordFormat::FIELDS);
901	}
902}