Debian Codegraph @

src/nametable.rs

raw
1 /// Utility functions for name table handling.
2 use std::collections::HashSet;
3
4 use fontations::skrifa::{string::StringId, FontRef, MetadataProvider};
5 use fontations::write::tables::name::NameRecord;
6
7 pub(crate) fn get_best_name(font: &FontRef, ids: &[StringId]) -> Option<String> {
8 for id in ids {
9 if let Some(name) = font.localized_strings(*id).english_or_first() {
10 return Some(name.chars().collect());
11 }
12 }
13 None
14 }
15
16 pub(crate) fn best_familyname(font: &FontRef) -> Option<String> {
17 get_best_name(
18 font,
19 &[
20 StringId::WWS_FAMILY_NAME,
21 StringId::TYPOGRAPHIC_FAMILY_NAME,
22 StringId::FAMILY_NAME,
23 ],
24 )
25 }
26
27 pub(crate) fn best_subfamilyname(font: &FontRef) -> Option<String> {
28 get_best_name(
29 font,
30 &[
31 StringId::WWS_SUBFAMILY_NAME,
32 StringId::TYPOGRAPHIC_SUBFAMILY_NAME,
33 StringId::SUBFAMILY_NAME,
34 ],
35 )
36 }
37
38 pub(crate) fn rewrite_or_insert(records: &mut Vec<NameRecord>, name_id: StringId, string: &str) {
39 if let Some(existing) = records.iter_mut().find(|r| {
40 r.name_id == name_id && r.platform_id == 3 && r.encoding_id == 1 && r.language_id == 0x409
41 }) {
42 *existing.string = string.to_string();
43 } else {
44 records.push(NameRecord {
45 platform_id: 3,
46 encoding_id: 1,
47 language_id: 0x409,
48 name_id,
49 string: string.to_string().into(),
50 });
51 }
52 }
53
54 pub(crate) fn find_or_add_name(records: &mut Vec<NameRecord>, string: &str) -> StringId {
55 if let Some(existing) = records.iter().find(|r| {
56 r.string.to_string() == string
57 && r.platform_id == 3
58 && r.encoding_id == 1
59 && r.language_id == 0x409
60 }) {
61 return existing.name_id;
62 }
63 add_name(records, string)
64 }
65
66 pub(crate) fn add_name(records: &mut Vec<NameRecord>, string: &str) -> StringId {
67 let existing_ids: HashSet<u16> = records.iter().map(|r| r.name_id.to_u16()).collect();
68 let mut id: u16 = 256;
69 while existing_ids.contains(&id) {
70 id += 1;
71 }
72 let name_id = StringId::new(id);
73 records.push(NameRecord {
74 platform_id: 3,
75 encoding_id: 1,
76 language_id: 0x409,
77 name_id,
78 string: string.to_string().into(),
79 });
80 name_id
81 }