fontcull-skrifa 0.39.2

Metadata reader and glyph scaler for OpenType fonts. (Vendored fork for fontcull)
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
//! Support for accessing glyph names.

use core::ops::Range;
use raw::{
    tables::{
        cff::Cff,
        post::Post,
        postscript::{Charset, CharsetIter, StringId as Sid},
    },
    types::GlyphId,
    FontRef, TableProvider,
};

/// "Names must be no longer than 63 characters; some older implementations
/// can assume a length limit of 31 characters."
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/post#version-20>
const MAX_GLYPH_NAME_LEN: usize = 63;

/// Mapping from glyph identifiers to names.
///
/// This sources glyph names from the `post` and `CFF` tables in that order.
/// If glyph names are not available in either, then they are synthesized
/// as `gidDDD` where `DDD` is the glyph identifier in decimal. Use the
/// [`source`](Self::source) to determine which source was chosen.
#[derive(Clone)]
pub struct GlyphNames<'a> {
    inner: Inner<'a>,
}

#[derive(Clone)]
enum Inner<'a> {
    // Second field is num_glyphs
    Post(Post<'a>, u32),
    Cff(Cff<'a>, Charset<'a>),
    Synthesized(u32),
}

impl<'a> GlyphNames<'a> {
    /// Creates a new object for accessing glyph names from the given font.
    pub fn new(font: &FontRef<'a>) -> Self {
        let num_glyphs = font
            .maxp()
            .map(|maxp| maxp.num_glyphs() as u32)
            .unwrap_or_default();
        if let Ok(post) = font.post() {
            if post.num_names() != 0 {
                return Self {
                    inner: Inner::Post(post, num_glyphs),
                };
            }
        }
        if let Some((cff, charset)) = font
            .cff()
            .ok()
            .and_then(|cff| Some((cff.clone(), cff.charset(0).ok()??)))
        {
            return Self {
                inner: Inner::Cff(cff, charset),
            };
        }
        Self {
            inner: Inner::Synthesized(num_glyphs),
        }
    }

    /// Returns the chosen source for glyph names.
    pub fn source(&self) -> GlyphNameSource {
        match &self.inner {
            Inner::Post(..) => GlyphNameSource::Post,
            Inner::Cff(..) => GlyphNameSource::Cff,
            Inner::Synthesized(..) => GlyphNameSource::Synthesized,
        }
    }

    /// Returns the number of glyphs in the font.
    pub fn num_glyphs(&self) -> u32 {
        match &self.inner {
            Inner::Post(_, n) | Inner::Synthesized(n) => *n,
            Inner::Cff(_, charset) => charset.num_glyphs(),
        }
    }

    /// Returns the name for the given glyph identifier.
    pub fn get(&self, glyph_id: GlyphId) -> Option<GlyphName> {
        if glyph_id.to_u32() >= self.num_glyphs() {
            return None;
        }
        let name = match &self.inner {
            Inner::Post(post, _) => GlyphName::from_post(post, glyph_id),
            Inner::Cff(cff, charset) => charset
                .string_id(glyph_id)
                .ok()
                .and_then(|sid| GlyphName::from_cff_sid(cff, sid)),
            _ => None,
        };
        // If name is empty string, synthesize it
        if !name.as_ref().is_some_and(|s| !s.is_empty()) {
            return Some(GlyphName::synthesize(glyph_id));
        }
        Some(name.unwrap_or_else(|| GlyphName::synthesize(glyph_id)))
    }

    /// Returns an iterator yielding the identifier and name for all glyphs in
    /// the font.
    pub fn iter(&self) -> impl Iterator<Item = (GlyphId, GlyphName)> + 'a + Clone {
        match &self.inner {
            Inner::Post(post, n) => Iter::Post(0..*n, post.clone()),
            Inner::Cff(cff, charset) => Iter::Cff(cff.clone(), charset.iter()),
            Inner::Synthesized(n) => Iter::Synthesized(0..*n),
        }
    }
}

/// Specifies the chosen source for glyph names.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum GlyphNameSource {
    /// Glyph names are sourced from the `post` table.
    Post,
    /// Glyph names are sourced from the `CFF` table.
    Cff,
    /// Glyph names are synthesized in the format `gidDDD` where `DDD` is
    /// the glyph identifier in decimal.
    Synthesized,
}

/// The name of a glyph.
#[derive(Clone)]
pub struct GlyphName {
    name: [u8; MAX_GLYPH_NAME_LEN],
    len: u8,
    is_synthesized: bool,
}

impl GlyphName {
    /// Returns the underlying name as a string.
    pub fn as_str(&self) -> &str {
        let bytes = &self.name[..self.len as usize];
        core::str::from_utf8(bytes).unwrap_or_default()
    }

    /// Returns true if the glyph name was synthesized, i.e. not found in any
    /// source.
    pub fn is_synthesized(&self) -> bool {
        self.is_synthesized
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        let mut name = Self::default();
        name.append(bytes);
        name
    }

    fn from_post(post: &Post, glyph_id: GlyphId) -> Option<Self> {
        glyph_id
            .try_into()
            .ok()
            .and_then(|id| post.glyph_name(id))
            .map(|s| s.as_bytes())
            .map(Self::from_bytes)
    }

    fn from_cff_sid(cff: &Cff, sid: Sid) -> Option<Self> {
        cff.string(sid)
            .and_then(|s| core::str::from_utf8(s.bytes()).ok())
            .map(|s| s.as_bytes())
            .map(Self::from_bytes)
    }

    fn synthesize(glyph_id: GlyphId) -> Self {
        use core::fmt::Write;
        let mut name = Self {
            is_synthesized: true,
            ..Self::default()
        };
        let _ = write!(GlyphNameWrite(&mut name), "gid{}", glyph_id.to_u32());
        name
    }

    /// Appends the given bytes to `self` while keeping the maximum length
    /// at 63 bytes.
    ///
    /// This exists primarily to support the [`core::fmt::Write`] impl
    /// (which is used for generating synthesized glyph names) because
    /// we have no guarantee of how many times `write_str` might be called
    /// for a given format.
    fn append(&mut self, bytes: &[u8]) {
        // We simply truncate when length exceeds the max since glyph names
        // are expected to be <= 63 chars
        let start = self.len as usize;
        let available = MAX_GLYPH_NAME_LEN - start;
        let copy_len = available.min(bytes.len());
        self.name[start..start + copy_len].copy_from_slice(&bytes[..copy_len]);
        self.len = (start + copy_len) as u8;
    }
}

impl Default for GlyphName {
    fn default() -> Self {
        Self {
            name: [0; MAX_GLYPH_NAME_LEN],
            len: 0,
            is_synthesized: false,
        }
    }
}

impl core::fmt::Debug for GlyphName {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GlyphName")
            .field("name", &self.as_str())
            .field("is_synthesized", &self.is_synthesized)
            .finish()
    }
}

impl core::fmt::Display for GlyphName {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl core::ops::Deref for GlyphName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl PartialEq<&str> for GlyphName {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

struct GlyphNameWrite<'a>(&'a mut GlyphName);

impl core::fmt::Write for GlyphNameWrite<'_> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        self.0.append(s.as_bytes());
        Ok(())
    }
}

#[derive(Clone)]
enum Iter<'a> {
    Post(Range<u32>, Post<'a>),
    Cff(Cff<'a>, CharsetIter<'a>),
    Synthesized(Range<u32>),
}

impl Iter<'_> {
    fn next_name(&mut self) -> Option<Result<(GlyphId, GlyphName), GlyphId>> {
        match self {
            Self::Post(range, post) => {
                let gid = GlyphId::new(range.next()?);
                Some(
                    GlyphName::from_post(post, gid)
                        .map(|name| (gid, name))
                        .ok_or(gid),
                )
            }
            Self::Cff(cff, iter) => {
                let (gid, sid) = iter.next()?;
                Some(
                    GlyphName::from_cff_sid(cff, sid)
                        .map(|name| (gid, name))
                        .ok_or(gid),
                )
            }
            Self::Synthesized(range) => {
                let gid = GlyphId::new(range.next()?);
                Some(Ok((gid, GlyphName::synthesize(gid))))
            }
        }
    }
}

impl Iterator for Iter<'_> {
    type Item = (GlyphId, GlyphName);

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_name()? {
            Ok((gid, name)) if name.is_empty() => Some((gid, GlyphName::synthesize(gid))),
            Ok(gid_name) => Some(gid_name),
            Err(gid) => Some((gid, GlyphName::synthesize(gid))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use raw::{FontData, FontRead};

    #[test]
    fn synthesized_glyph_names() {
        let count = 58;
        let names = GlyphNames {
            inner: Inner::Synthesized(58),
        };
        let names_buf = (0..count).map(|i| format!("gid{i}")).collect::<Vec<_>>();
        let expected_names = names_buf.iter().map(|s| s.as_str()).collect::<Vec<_>>();
        for (_, name) in names.iter() {
            assert!(name.is_synthesized())
        }
        check_names(&names, &expected_names, GlyphNameSource::Synthesized);
    }

    #[test]
    fn synthesize_for_empty_names() {
        let mut post_data = fontcull_font_test_data::post::SIMPLE.to_vec();
        // last name in this post data is "hola" so pop 5 bytes and then
        // push a 0 to simulate an empty name
        post_data.truncate(post_data.len() - 5);
        post_data.push(0);
        let post = Post::read(FontData::new(&post_data)).unwrap();
        let gid = GlyphId::new(9);
        assert!(post.glyph_name(gid.try_into().unwrap()).unwrap().is_empty());
        let names = GlyphNames {
            inner: Inner::Post(post, 10),
        };
        assert_eq!(names.get(gid).unwrap(), "gid9");
        assert_eq!(names.iter().last().unwrap().1, "gid9");
    }

    #[test]
    fn cff_glyph_names() {
        let font = FontRef::new(fontcull_font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
        let names = GlyphNames::new(&font);
        assert_eq!(names.source(), GlyphNameSource::Cff);
        let expected_names = [".notdef", "i", "j", "k", "l"];
        check_names(&names, &expected_names, GlyphNameSource::Cff);
    }

    #[test]
    fn post_glyph_names() {
        let font =
            FontRef::new(fontcull_font_test_data::HVAR_WITH_TRUNCATED_ADVANCE_INDEX_MAP).unwrap();
        let names = GlyphNames::new(&font);
        let expected_names = [
            ".notdef",
            "space",
            "A",
            "I",
            "T",
            "Aacute",
            "Agrave",
            "Iacute",
            "Igrave",
            "Amacron",
            "Imacron",
            "acutecomb",
            "gravecomb",
            "macroncomb",
            "A.001",
            "A.002",
            "A.003",
            "A.004",
            "A.005",
            "A.006",
            "A.007",
            "A.008",
            "A.009",
            "A.010",
        ];
        check_names(&names, &expected_names, GlyphNameSource::Post);
    }

    #[test]
    fn post_glyph_names_partial() {
        let font =
            FontRef::new(fontcull_font_test_data::HVAR_WITH_TRUNCATED_ADVANCE_INDEX_MAP).unwrap();
        let mut names = GlyphNames::new(&font);
        let Inner::Post(_, len) = &mut names.inner else {
            panic!("it's a post table!");
        };
        // Increase count by 4 so we synthesize the remaining names
        *len += 4;
        let expected_names = [
            ".notdef",
            "space",
            "A",
            "I",
            "T",
            "Aacute",
            "Agrave",
            "Iacute",
            "Igrave",
            "Amacron",
            "Imacron",
            "acutecomb",
            "gravecomb",
            "macroncomb",
            "A.001",
            "A.002",
            "A.003",
            "A.004",
            "A.005",
            "A.006",
            "A.007",
            "A.008",
            "A.009",
            "A.010",
            // synthesized names...
            "gid24",
            "gid25",
            "gid26",
            "gid27",
        ];
        check_names(&names, &expected_names, GlyphNameSource::Post);
    }

    fn check_names(names: &GlyphNames, expected_names: &[&str], expected_source: GlyphNameSource) {
        assert_eq!(names.source(), expected_source);
        let iter_names = names.iter().collect::<Vec<_>>();
        assert_eq!(iter_names.len(), expected_names.len());
        for (i, expected) in expected_names.iter().enumerate() {
            let gid = GlyphId::new(i as u32);
            let name = names.get(gid).unwrap();
            assert_eq!(name, expected);
            assert_eq!(iter_names[i].0, gid);
            assert_eq!(iter_names[i].1, expected);
        }
    }
}