fontoxide-ttlib 0.2.0

Read and write OpenType/TrueType fonts and TTX; a port of fontTools.ttLib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! `name`: Naming table (`fontTools.ttLib.tables._n_a_m_e`).

use std::cmp::Ordering;
use std::collections::HashMap;

use fontoxide_encodings::codecs;
use fontoxide_misc::Tag;
use fontoxide_misc::encoding_tools::get_encoding;
use fontoxide_misc::xml_reader::Element;
use fontoxide_misc::xml_writer::XmlWriter;

use crate::binary::{Reader, WriteBytes};
use crate::sstruct::{U16, eval};
use crate::table::{Table, TableType, TableXml};
use crate::{Error, Font, Result};

crate::sstruct! {
	/// A name record as stored (`nameRecordFormat`).
	pub struct NameRecordFormat = "nameRecordFormat" {
		/// Platform ID.
		pub platform_id: u16 = "platformID" as U16,
		/// Platform-specific encoding ID.
		pub plat_enc_id: u16 = "platEncID" as U16,
		/// Language ID.
		pub lang_id: u16 = "langID" as U16,
		/// Name ID.
		pub name_id: u16 = "nameID" as U16,
		/// String length in bytes.
		pub length: u16 = "length" as U16,
		/// String offset from the start of the string storage.
		pub offset: u16 = "offset" as U16,
	}
}

/// The string of a name record: raw bytes as read from a font, or text set by the
/// user (fontTools allows both `bytes` and `str`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NameString {
	/// Encoded bytes.
	Bytes(Vec<u8>),
	/// Text, encoded with the record's encoding when compiling.
	Text(String),
}

impl Default for NameString {
	fn default() -> Self {
		NameString::Bytes(Vec::new())
	}
}

impl From<&str> for NameString {
	fn from(s: &str) -> Self {
		NameString::Text(s.to_owned())
	}
}

impl From<String> for NameString {
	fn from(s: String) -> Self {
		NameString::Text(s)
	}
}

impl From<Vec<u8>> for NameString {
	fn from(b: Vec<u8>) -> Self {
		NameString::Bytes(b)
	}
}

/// A name record (`NameRecord`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct NameRecord {
	/// Name ID.
	pub name_id: u16,
	/// Platform ID.
	pub platform_id: u16,
	/// Platform-specific encoding ID.
	pub plat_enc_id: u16,
	/// Language ID.
	pub lang_id: u16,
	/// The string.
	pub string: NameString,
}

fn is_ascii_char(b: u32) -> bool {
	(0x20..=0x7E).contains(&b) || matches!(b, 0x09 | 0x0A | 0x0D)
}

impl NameRecord {
	/// A record with the given string and IDs (`makeName`).
	pub fn new(
		string: impl Into<NameString>,
		name_id: u16,
		platform_id: u16,
		plat_enc_id: u16,
		lang_id: u16,
	) -> Self {
		NameRecord {
			name_id,
			platform_id,
			plat_enc_id,
			lang_id,
			string: string.into(),
		}
	}

	/// The codec for this record, or `"ascii"` if unknown (`getEncoding()`).
	pub fn encoding(&self) -> &'static str {
		get_encoding(self.platform_id, self.plat_enc_id, self.lang_id).unwrap_or("ascii")
	}

	/// Whether the encoding can represent any text (`encodingIsUnicodeCompatible`).
	pub fn encoding_is_unicode_compatible(&self) -> bool {
		matches!(
			get_encoding(self.platform_id, self.plat_enc_id, self.lang_id),
			Some("utf_16_be" | "ucs2be" | "ascii" | "latin1")
		)
	}

	/// Whether the string is Unicode (`isUnicode`).
	pub fn is_unicode(&self) -> bool {
		self.platform_id == 0 || (self.platform_id == 3 && matches!(self.plat_enc_id, 0 | 1 | 10))
	}

	/// The string as text (`toUnicode()`), with fontTools' heuristics to recover
	/// misencoded UTF-16.
	pub fn to_unicode(&self) -> std::result::Result<String, codecs::CodecError> {
		self.to_unicode_with(codecs::Errors::Strict)
	}

	/// [`NameRecord::to_unicode`], with bytes that cannot be decoded handled by
	/// `errors` (`toUnicode(errors)`, `toStr(errors)`).
	pub fn to_unicode_with(
		&self,
		errors: codecs::Errors,
	) -> std::result::Result<String, codecs::CodecError> {
		let encoding = self.encoding();
		let mut string = match &self.string {
			NameString::Text(s) => s.clone(),
			NameString::Bytes(bytes) => {
				let mut bytes = bytes.clone();
				if encoding == "utf_16_be" && bytes.len() % 2 == 1 {
					// Recover badly encoded UTF-16 strings that have an odd number
					// of bytes:
					// - If the last byte is zero, drop it. Otherwise,
					// - If all the odd bytes are zero and all the even bytes are
					//   ASCII, prepend one zero byte. Otherwise,
					// - If the first byte is zero and all other bytes are ASCII,
					//   insert zero bytes between consecutive ASCII bytes.
					if bytes.last() == Some(&0) {
						bytes.pop();
					} else if bytes.iter().enumerate().all(|(i, &b)| {
						if i % 2 == 1 {
							b == 0
						} else {
							is_ascii_char(b as u32)
						}
					}) {
						bytes.insert(0, 0);
					} else if bytes[0] == 0 && bytes[1..].iter().all(|&b| is_ascii_char(b as u32)) {
						bytes = bytes[1..].iter().flat_map(|&b| [0, b]).collect();
					}
				}
				codecs::decode_with(encoding, &bytes, errors)?
			}
		};
		// If the decoded string still looks like UTF-16BE, it suggests a double
		// encoding; narrow it down.
		if string.chars().enumerate().all(|(i, c)| {
			if i % 2 == 0 {
				c == '\0'
			} else {
				is_ascii_char(c as u32)
			}
		}) {
			string = string.chars().skip(1).step_by(2).collect();
		}
		Ok(string)
	}

	/// The encoded string (`toBytes()`).
	pub fn to_bytes(&self) -> std::result::Result<Vec<u8>, codecs::CodecError> {
		self.to_bytes_with(codecs::Errors::Strict)
	}

	/// [`NameRecord::to_bytes`], with characters that cannot be encoded handled
	/// by `errors` (`toBytes(errors)`).
	pub fn to_bytes_with(
		&self,
		errors: codecs::Errors,
	) -> std::result::Result<Vec<u8>, codecs::CodecError> {
		match &self.string {
			NameString::Bytes(b) => Ok(b.clone()),
			NameString::Text(s) => codecs::encode_with(self.encoding(), s, errors),
		}
	}

	/// The string with undecodable bytes escaped (`str(record)`, which is
	/// `toStr(errors="backslashreplace")`).
	pub fn to_str_lossy(&self) -> String {
		match self.to_unicode_with(codecs::Errors::BackslashReplace) {
			Ok(s) => s,
			// Only for codecs that fontoxide does not have.
			Err(_) => match &self.string {
				NameString::Bytes(b) => b
					.iter()
					.map(|&c| {
						if c < 0x80 {
							(c as char).to_string()
						} else {
							format!("\\x{c:02x}")
						}
					})
					.collect(),
				NameString::Text(s) => s.clone(),
			},
		}
	}

	fn ids(&self) -> (u16, u16, u16, u16) {
		(
			self.platform_id,
			self.plat_enc_id,
			self.lang_id,
			self.name_id,
		)
	}

	fn to_xml(&self, writer: &mut XmlWriter) {
		let unistr = self.to_unicode().ok();
		let lang_id = format!("{:#x}", self.lang_id);
		let unicode = unistr.is_some();
		let mut attrs: Vec<(&str, &dyn fontoxide_misc::xml_writer::AttrValue)> = vec![
			("nameID", &self.name_id),
			("platformID", &self.platform_id),
			("platEncID", &self.plat_enc_id),
			("langID", &lang_id),
		];
		if unistr.is_none() || !self.encoding_is_unicode_compatible() {
			attrs.push(("unicode", &unicode));
		}
		writer.begintag_ordered("namerecord", &attrs);
		writer.newline();
		match (&unistr, &self.string) {
			(Some(s), _) => writer.write(s),
			(None, NameString::Bytes(b)) => writer.write8bit(b, false),
			(None, NameString::Text(s)) => writer.write(s),
		}
		writer.newline();
		writer.endtag("namerecord");
		writer.newline();
	}

	fn from_xml(element: &Element) -> Result<Self> {
		let attr = |name: &str| {
			element
				.attr(name)
				.ok_or_else(|| Error::ttx(format!("missing '{name}' on <namerecord>")))
		};
		let int = |name: &str| -> Result<u16> {
			let v = eval(attr(name)?)?
				.as_int()
				.ok_or_else(|| Error::value(format!("invalid {name}")))?;
			crate::binary::fit(v, name)
		};
		let mut record = NameRecord {
			name_id: int("nameID")?,
			platform_id: int("platformID")?,
			plat_enc_id: int("platEncID")?,
			lang_id: int("langID")?,
			string: NameString::default(),
		};
		let text = element.text();
		let s = fontoxide_misc::py::strip(&text);
		let unicode = element
			.attr("unicode")
			.map(eval)
			.transpose()?
			.is_some_and(|v| v.is_truthy());
		let bytes = if record.encoding_is_unicode_compatible() || unicode {
			codecs::encode(record.encoding(), s).map_err(|e| Error::value(e.to_string()))?
		} else {
			// The inverse of write8bit.
			fontoxide_misc::py::latin1_encode(s)
				.ok_or_else(|| Error::value("'latin-1' codec can't encode the name record"))?
		};
		record.string = NameString::Bytes(bytes);
		Ok(record)
	}
}

/// `NameRecord.__lt__`, which compares the IDs and, if both strings can be
/// encoded, the encoded strings.
fn record_cmp(a: &(NameRecord, Option<Vec<u8>>), b: &(NameRecord, Option<Vec<u8>>)) -> Ordering {
	let ids = a.0.ids().cmp(&b.0.ids());
	match (&a.1, &b.1) {
		(Some(x), Some(y)) => ids.then_with(|| x.cmp(y)),
		_ => ids,
	}
}

/// A stable merge sort that, unlike `slice::sort_by`, tolerates the inconsistent
/// comparisons `record_cmp` can produce when some strings fail to encode.
fn merge_sort<T: Clone>(items: &mut [T], cmp: &impl Fn(&T, &T) -> Ordering) {
	if items.len() <= 1 {
		return;
	}
	let mid = items.len() / 2;
	merge_sort(&mut items[..mid], cmp);
	merge_sort(&mut items[mid..], cmp);
	let mut merged = Vec::with_capacity(items.len());
	let (mut i, mut j) = (0, mid);
	while i < mid && j < items.len() {
		if cmp(&items[j], &items[i]) == Ordering::Less {
			merged.push(items[j].clone());
			j += 1;
		} else {
			merged.push(items[i].clone());
			i += 1;
		}
	}
	merged.extend_from_slice(&items[i..mid]);
	merged.extend_from_slice(&items[j..]);
	items.clone_from_slice(&merged);
}

/// Naming table (`table__n_a_m_e`).
///
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/name>.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Name {
	/// The name records (`names`).
	pub names: Vec<NameRecord>,
}

impl Name {
	/// The first record with the given IDs; any language if `lang_id` is `None`
	/// (`getName`).
	pub fn get_name(
		&self,
		name_id: u16,
		platform_id: u16,
		plat_enc_id: u16,
		lang_id: Option<u16>,
	) -> Option<&NameRecord> {
		self.names.iter().find(|r| {
			r.name_id == name_id
				&& r.platform_id == platform_id
				&& r.plat_enc_id == plat_enc_id
				&& lang_id.is_none_or(|l| r.lang_id == l)
		})
	}

	/// A name for debugging or display, preferring Windows English, then Mac
	/// English, then any decodable record (`getDebugName`).
	pub fn get_debug_name(&self, name_id: u16) -> Option<String> {
		let mut mac_english = None;
		let mut some = None;
		for record in self.names.iter().filter(|r| r.name_id == name_id) {
			let Ok(s) = record.to_unicode() else {
				continue;
			};
			if (record.platform_id, record.lang_id) == (3, 0x409) {
				if !s.is_empty() {
					return Some(s);
				}
				some = Some(s);
				break;
			}
			if (record.platform_id, record.lang_id) == (1, 0) && mac_english.is_none() {
				mac_english = Some(s.clone());
			}
			some = Some(s);
		}
		// fontTools tests the candidates for truthiness, so empty strings are
		// skipped except as the last resort.
		mac_english
			.filter(|s| !s.is_empty())
			.or_else(|| some.filter(|s| !s.is_empty()))
	}

	/// The first name found for the given IDs (`getFirstDebugName`).
	pub fn get_first_debug_name(&self, name_ids: &[u16]) -> Option<String> {
		name_ids.iter().find_map(|&id| self.get_debug_name(id))
	}

	/// WWS, typographic or legacy family name (`getBestFamilyName`).
	pub fn best_family_name(&self) -> Option<String> {
		self.get_first_debug_name(&[21, 16, 1])
	}

	/// WWS, typographic or legacy subfamily name (`getBestSubFamilyName`).
	pub fn best_sub_family_name(&self) -> Option<String> {
		self.get_first_debug_name(&[22, 17, 2])
	}

	/// The full name, from the family and subfamily names or name IDs 4 or 6
	/// (`getBestFullName`).
	pub fn best_full_name(&self) -> Option<String> {
		for (family, sub) in [(21, 22), (16, 17), (1, 2)] {
			let (Some(fam), Some(subfam)) = (self.get_debug_name(family), self.get_debug_name(sub))
			else {
				continue;
			};
			return Some(if subfam.to_lowercase() == "regular" {
				fam
			} else {
				format!("{fam} {subfam}")
			});
		}
		self.get_debug_name(4).or_else(|| self.get_debug_name(6))
	}

	/// Sets the string of a record, adding the record if needed (`setName`).
	pub fn set_name(
		&mut self,
		string: impl Into<NameString>,
		name_id: u16,
		platform_id: u16,
		plat_enc_id: u16,
		lang_id: u16,
	) {
		let string = string.into();
		if let NameString::Bytes(b) = &string {
			log::warn!(
				"name string is bytes, ensure it's correctly encoded: {}",
				fontoxide_misc::py::bytes_repr(b)
			);
		}
		match self.names.iter_mut().find(|r| {
			r.name_id == name_id
				&& r.platform_id == platform_id
				&& r.plat_enc_id == plat_enc_id
				&& r.lang_id == lang_id
		}) {
			Some(r) => r.string = string,
			None => self.names.push(NameRecord::new(
				string,
				name_id,
				platform_id,
				plat_enc_id,
				lang_id,
			)),
		}
	}

	/// Removes the records matching all the given IDs (`removeNames`). Without any
	/// ID, nothing is removed.
	pub fn remove_names(
		&mut self,
		name_id: Option<u16>,
		platform_id: Option<u16>,
		plat_enc_id: Option<u16>,
		lang_id: Option<u16>,
	) {
		if name_id.is_none() && platform_id.is_none() && plat_enc_id.is_none() && lang_id.is_none()
		{
			return;
		}
		self.names.retain(|r| {
			name_id.is_some_and(|v| v != r.name_id)
				|| platform_id.is_some_and(|v| v != r.platform_id)
				|| plat_enc_id.is_some_and(|v| v != r.plat_enc_id)
				|| lang_id.is_some_and(|v| v != r.lang_id)
		});
	}

	/// An unused name ID after the highest one in the table, at least
	/// `min_name_id` (`_findUnusedNameID`).
	pub fn find_unused_name_id(&self, min_name_id: u16) -> Result<u16> {
		let name_id = 1 + self
			.names
			.iter()
			.map(|n| n.name_id as i64)
			.chain([min_name_id as i64 - 1])
			.max()
			.unwrap_or(-1);
		if name_id > 32767 {
			return Err(Error::value("nameID must be less than 32768"));
		}
		Ok(name_id as u16)
	}

	/// Adds records for `string` on each `(platformID, platEncID, langID)` and
	/// returns the new name ID, which is above `min_name_id` (`addName`).
	pub fn add_name(
		&mut self,
		string: &str,
		platforms: &[(u16, u16, u16)],
		min_name_id: u16,
	) -> Result<u16> {
		if platforms.is_empty() {
			return Err(Error::Assertion(
				"'platforms' must contain at least one (platformID, platEncID, langID) tuple"
					.into(),
			));
		}
		let name_id = self.find_unused_name_id(min_name_id.saturating_add(1))?;
		for &(p, e, l) in platforms {
			self.names.push(NameRecord::new(string, name_id, p, e, l));
		}
		Ok(name_id)
	}

	/// [`Name::add_name`] with fontTools' default platforms: Macintosh English
	/// and Windows English (US), and a minimum name ID of 255.
	pub fn add_name_default(&mut self, string: &str) -> Result<u16> {
		self.add_name(string, &[(1, 0, 0), (3, 1, 0x409)], 255)
	}

	/// The name ID of existing records that hold all of `names` (BCP 47
	/// language tag to string), at least `min_name_id`; `None` if there are none
	/// (`findMultilingualName` without a font: names that would need an `ltag`
	/// table are left out). See [`find_multilingual_name`] for the version with a
	/// font.
	pub fn find_multilingual_name(
		&self,
		names: &[(&str, &str)],
		windows: bool,
		mac: bool,
		min_name_id: u16,
	) -> Result<Option<u16>> {
		self.find_multilingual_name_with(names, windows, mac, min_name_id, &mut no_ltag)
	}

	/// `findMultilingualName`, with `ltag` adding a language tag to the font's
	/// `ltag` table (`None` without a font).
	fn find_multilingual_name_with(
		&self,
		names: &[(&str, &str)],
		windows: bool,
		mac: bool,
		min_name_id: u16,
		ltag: &mut LtagFn<'_>,
	) -> Result<Option<u16>> {
		let mut sorted = names.to_vec();
		sorted.sort();
		let mut requested: Vec<(String, u16, u16, u16)> = Vec::new();
		let mut add = |r: NameRecord| {
			let key = (r.text(), r.platform_id, r.plat_enc_id, r.lang_id);
			if !requested.contains(&key) {
				requested.push(key);
			}
		};
		for &(lang, name) in &sorted {
			if windows && let Some(r) = make_windows_name(name, 0, lang) {
				add(r);
			}
			if mac && let Some(r) = make_mac_name(name, 0, lang, ltag)? {
				add(r);
			}
		}
		let mut matching: std::collections::BTreeMap<u16, Vec<(String, u16, u16, u16)>> =
			std::collections::BTreeMap::new();
		for record in &self.names {
			let Ok(s) = record.to_unicode() else {
				continue;
			};
			let key = (s, record.platform_id, record.plat_enc_id, record.lang_id);
			if requested.contains(&key) && record.name_id >= min_name_id {
				let set = matching.entry(record.name_id).or_default();
				if !set.contains(&key) {
					set.push(key);
				}
			}
		}
		Ok(matching
			.into_iter()
			.find(|(_, set)| set.len() == requested.len())
			.map(|(id, _)| id))
	}

	/// Adds records for a name in several languages (BCP 47 language tag to
	/// string) and returns its name ID (`addMultilingualName` without a font).
	///
	/// Without `name_id`, the ID of existing matching records is reused if there
	/// are any, otherwise an unused ID is picked. Names that would need an `ltag`
	/// table are left out; see [`add_multilingual_name`] for the version with a
	/// font.
	pub fn add_multilingual_name(
		&mut self,
		names: &[(&str, &str)],
		name_id: Option<u16>,
		windows: bool,
		mac: bool,
		min_name_id: u16,
	) -> Result<u16> {
		self.add_multilingual_name_with(names, name_id, windows, mac, min_name_id, &mut no_ltag)
	}

	fn add_multilingual_name_with(
		&mut self,
		names: &[(&str, &str)],
		name_id: Option<u16>,
		windows: bool,
		mut mac: bool,
		min_name_id: u16,
		ltag: &mut LtagFn<'_>,
	) -> Result<u16> {
		let name_id = match name_id {
			Some(id) => id,
			None => {
				if let Some(id) =
					self.find_multilingual_name_with(names, windows, mac, min_name_id, ltag)?
				{
					return Ok(id);
				}
				// fontTools does not pass minNameID here.
				self.find_unused_name_id(256)?
			}
		};
		let mut sorted = names.to_vec();
		sorted.sort();
		for (lang, name) in sorted {
			if windows {
				match make_windows_name(name, name_id, lang) {
					Some(r) => self.names.push(r),
					// Without a Windows name, make sure there is a Mac name.
					None => mac = true,
				}
			}
			if mac && let Some(r) = make_mac_name(name, name_id, lang, ltag)? {
				self.names.push(r);
			}
		}
		Ok(name_id)
	}
}

/// Adds a language tag to the font's `ltag` table and returns its index.
type LtagFn<'a> = dyn FnMut(&str) -> Result<Option<u16>> + 'a;

fn no_ltag(_: &str) -> Result<Option<u16>> {
	Ok(None)
}

/// The `ltag` table function for a font: like fontTools, it adds a new `ltag` table
/// unless the font has one decompiled already.
fn font_ltag(font: &mut Font) -> impl FnMut(&str) -> Result<Option<u16>> + '_ {
	move |lang| {
		let tag = <crate::tables::misc_tables::Ltag as TableType>::TAG;
		if !font.is_loaded(tag) {
			font.insert(Box::new(crate::tables::misc_tables::Ltag::default()));
		}
		let ltag = font.require::<crate::tables::misc_tables::Ltag>()?;
		crate::binary::fit(ltag.add_tag(lang) as u64, "langID").map(Some)
	}
}

/// `font["name"].findMultilingualName(names, ..., ttFont=font)`: see
/// [`Name::find_multilingual_name`]. Names in languages that need it may add
/// tags to the font's `ltag` table, as in fontTools.
pub fn find_multilingual_name(
	font: &mut Font,
	names: &[(&str, &str)],
	windows: bool,
	mac: bool,
	min_name_id: u16,
) -> Result<Option<u16>> {
	font.with_table(<Name as TableType>::TAG, |t, font| {
		let name = name_table(t)?;
		name.find_multilingual_name_with(names, windows, mac, min_name_id, &mut font_ltag(font))
	})
}

/// `font["name"].addMultilingualName(names, ttFont=font, ...)`: see
/// [`Name::add_multilingual_name`]. Names that a Macintosh encoding cannot
/// represent are added as Unicode records whose language is a tag of the
/// font's `ltag` table.
pub fn add_multilingual_name(
	font: &mut Font,
	names: &[(&str, &str)],
	name_id: Option<u16>,
	windows: bool,
	mac: bool,
	min_name_id: u16,
) -> Result<u16> {
	font.with_table(<Name as TableType>::TAG, |t, font| {
		let name = name_table(t)?;
		name.add_multilingual_name_with(
			names,
			name_id,
			windows,
			mac,
			min_name_id,
			&mut font_ltag(font),
		)
	})
}

fn name_table(t: &mut dyn Table) -> Result<&mut Name> {
	t.as_any_mut()
		.downcast_mut::<Name>()
		.ok_or(Error::WrongTableType(<Name as TableType>::TAG))
}

fn lookup(table: &[(&str, u16)], key: &str) -> Option<u16> {
	table
		.binary_search_by(|(k, _)| (*k).cmp(key))
		.ok()
		.map(|i| table[i].1)
}

/// A Windows name record for a BCP 47 language, if Windows has a language ID for
/// it (`_makeWindowsName`).
fn make_windows_name(name: &str, name_id: u16, language: &str) -> Option<NameRecord> {
	let lang = language.to_lowercase();
	match lookup(super::name_languages::WINDOWS_LANGUAGE_CODES, &lang) {
		Some(lang_id) => Some(NameRecord::new(name, name_id, 3, 1, lang_id)),
		None => {
			log::warn!(
				"cannot add Windows name in language {language} because fonttools does not yet support name table format 1"
			);
			None
		}
	}
}

/// A Macintosh name record for a BCP 47 language (`_makeMacName`): with a legacy
/// language and encoding if possible, otherwise Unicode with an `ltag` language.
fn make_mac_name(
	name: &str,
	name_id: u16,
	language: &str,
	ltag: &mut LtagFn<'_>,
) -> Result<Option<NameRecord>> {
	let lang = language.to_lowercase();
	let mac_lang = lookup(super::name_languages::MAC_LANGUAGE_CODES, &lang);
	let mac_script = mac_lang.and_then(|l| {
		let table = super::name_languages::MAC_LANGUAGE_TO_SCRIPT;
		table
			.binary_search_by_key(&l, |&(k, _)| k)
			.ok()
			.map(|i| table[i].1)
	});
	if let (Some(mac_lang), Some(mac_script)) = (mac_lang, mac_script) {
		let encoding = get_encoding(1, mac_script, mac_lang).unwrap_or("ascii");
		if codecs::encode(encoding, name).is_ok() {
			return Ok(Some(NameRecord::new(
				name, name_id, 1, mac_script, mac_lang,
			)));
		}
	}
	match ltag(language)? {
		// 0 = Unicode; 4 = Unicode 2.0 or later semantics.
		Some(index) => Ok(Some(NameRecord::new(name, name_id, 0, 4, index))),
		None => {
			log::warn!(
				"cannot store language {language} into 'ltag' table without having access to the TTFont object"
			);
			Ok(None)
		}
	}
}

impl NameRecord {
	/// The string as text, for records made from text.
	fn text(&self) -> String {
		match &self.string {
			NameString::Text(s) => s.clone(),
			NameString::Bytes(_) => self.to_str_lossy(),
		}
	}
}

impl Name {
	/// Sorts the records as the specification requires (`names.sort()`).
	pub fn sort(&mut self) {
		let mut keyed: Vec<(NameRecord, Option<Vec<u8>>)> = self
			.names
			.drain(..)
			.map(|r| {
				let b = r.to_bytes();
				if let Err(e) = &b {
					log::error!("NameRecord sorting failed to encode: {e}");
				}
				let b = b.ok();
				(r, b)
			})
			.collect();
		merge_sort(&mut keyed, &record_cmp);
		self.names = keyed.into_iter().map(|(r, _)| r).collect();
	}
}

impl TableType for Name {
	const TAG: Tag = Tag::new(b"name");

	fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
		let mut r = Reader::new(data);
		let _format = r.u16()?;
		let n = r.u16()? as usize;
		let string_offset = r.u16()? as usize;
		let expected = 6 + n * NameRecordFormat::SIZE;
		if string_offset != expected {
			log::error!(
				"'name' table stringOffset incorrect. Expected: {expected}; Actual: {string_offset}"
			);
		}
		let string_data = data.get(string_offset..).unwrap_or_default();
		let mut records = &data[6..];
		let mut names = Vec::with_capacity(n);
		for i in 0..n {
			if records.len() < 12 {
				log::error!("skipping malformed name record #{i}");
				continue;
			}
			let (rec, rest) = NameRecordFormat::unpack2(records)?;
			records = rest;
			let start = rec.offset as usize;
			let end = start + rec.length as usize;
			if end > string_data.len() {
				log::error!("skipping malformed name record #{i}");
				continue;
			}
			names.push(NameRecord {
				name_id: rec.name_id,
				platform_id: rec.platform_id,
				plat_enc_id: rec.plat_enc_id,
				lang_id: rec.lang_id,
				string: NameString::Bytes(string_data[start..end].to_vec()),
			});
		}
		Ok(Name { names })
	}
}

impl Table for Name {
	fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
		let _ = f;
		Ok(())
	}

	fn tag(&self) -> Tag {
		Self::TAG
	}

	fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
		self.sort();
		let n = self.names.len();
		let string_offset = 6 + n * NameRecordFormat::SIZE;
		let mut data = Vec::with_capacity(string_offset);
		data.put_u16(0);
		data.put_u16(crate::binary::fit(n, "count")?);
		data.put_u16(crate::binary::fit(string_offset, "stringOffset")?);
		let mut string_data: Vec<u8> = Vec::new();
		let mut done: HashMap<Vec<u8>, (usize, usize)> = HashMap::new();
		for name in &self.names {
			let string = name.to_bytes().map_err(|e| Error::value(e.to_string()))?;
			let (offset, length) = match done.get(&string) {
				Some(&v) => v,
				None => {
					let v = (string_data.len(), string.len());
					string_data.extend_from_slice(&string);
					done.insert(string, v);
					v
				}
			};
			NameRecordFormat {
				platform_id: name.platform_id,
				plat_enc_id: name.plat_enc_id,
				lang_id: name.lang_id,
				name_id: name.name_id,
				length: crate::binary::fit(length, "length")?,
				offset: crate::binary::fit(offset, "offset")?,
			}
			.pack(&mut data)?;
		}
		data.extend(string_data);
		Ok(data)
	}

	fn clone_table(&self) -> Box<dyn Table> {
		Box::new(self.clone())
	}
}

impl TableXml for Name {
	fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
		for name in &self.names {
			name.to_xml(writer);
		}
		Ok(())
	}

	fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
		if element.name != "namerecord" {
			return Ok(());
		}
		self.names.push(NameRecord::from_xml(element)?);
		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn format_matches_upstream() {
		crate::sstruct::tests::check(NameRecordFormat::FORMAT_NAME, NameRecordFormat::FIELDS);
	}
}