Skip to main content

read_fonts/ps/cff/
font.rs

1//! Unified access to CFF/CFF2 fonts.
2
3use crate::model::Error;
4use crate::{
5    model::glyph::outline::PathSink,
6    ps::{
7        cff::{
8            blend::BlendState, charset::Charset, dict, encoding::Encoding as RawEncoding,
9            fd_select::FdSelect, index::Index,
10        },
11        charstring::{self, CommandSink, NopFilterSink, TransformSink},
12        encoding::PredefinedEncoding,
13        hinting::HintingParams,
14        string::Sid,
15        transform::{ScaledFontMatrix, Transform},
16    },
17    tables::{cff, cff2, variations::ItemVariationStore},
18    FontData, FontRead,
19};
20use core::ops::Range;
21use types::{BoundingBox, F2Dot14, Fixed, GlyphId};
22use yoke::Yokeable;
23
24/// A CFF or CFF2 font.
25///
26/// The source data may be a raw CFF blob as embedded in a PDF or the content
27/// of a CFF or CFF2 table in an OpenType font.
28#[derive(Clone, Yokeable)]
29pub struct CffFontRef<'a> {
30    data: &'a [u8],
31    is_cff2: bool,
32    upem: i32,
33    global_subrs: Index<'a>,
34    top_dict: TopDict<'a>,
35    top_dict_index: u16,
36}
37
38impl<'a> CffFontRef<'a> {
39    /// The byte range of an SID font's private dict, for tests that damage
40    /// it.
41    #[cfg(test)]
42    pub(crate) fn sid_private_dict_range(&self) -> Option<Range<usize>> {
43        match &self.top_dict.kind {
44            CffFontKind::Sid { private_dict, .. } => {
45                Some(private_dict.start as usize..private_dict.end as usize)
46            }
47            _ => None,
48        }
49    }
50
51    /// Creates a new font for the given CFF or CFF2 data.
52    ///
53    /// Tries to determine the CFF version by reading the first word of the
54    /// header.
55    ///
56    /// For CFF blobs embedded in an OpenType font, the upem should be taken
57    /// from the `head` table. Otherwise, 1000 will be assumed.
58    pub fn new(data: &'a [u8], top_dict_index: u32, upem: Option<i32>) -> Result<Self, Error> {
59        let version: u8 = FontData::new(data).read_at(0)?;
60        match version {
61            1 => Self::new_cff(data, top_dict_index, upem),
62            2 => Self::new_cff2(data, upem),
63            // the first byte says neither 1 nor 2
64            _ => Err(Error::Malformed),
65        }
66    }
67
68    /// Creates a new font for the given CFF data.
69    ///
70    /// For CFF blobs embedded in an OpenType font, the upem should be taken
71    /// from the `head` table. Otherwise, 1000 will be assumed.
72    pub fn new_cff(data: &'a [u8], top_dict_index: u32, upem: Option<i32>) -> Result<Self, Error> {
73        let cff = cff::Cff::read(data.into())?;
74        let top_dict_data = cff
75            .top_dicts()
76            .get(top_dict_index as usize)
77            .ok_or(Error::Malformed)?;
78        let top_dict_index: u16 = top_dict_index.try_into().map_err(|_| Error::Malformed)?;
79        Self::new_impl(
80            data,
81            false,
82            upem,
83            top_dict_data,
84            top_dict_index,
85            cff.strings().into(),
86            cff.global_subrs().into(),
87        )
88    }
89
90    /// Creates a new font for the given CFF2 data.
91    ///
92    /// For CFF blobs embedded in an OpenType font, the upem should be taken
93    /// from the `head` table. Otherwise, 1000 will be assumed.
94    pub fn new_cff2(data: &'a [u8], upem: Option<i32>) -> Result<Self, Error> {
95        let cff = cff2::Cff2::read(data.into())?;
96        Self::new_impl(
97            data,
98            true,
99            upem,
100            cff.top_dict_data(),
101            0,
102            Index::Empty,
103            cff.global_subrs().into(),
104        )
105    }
106
107    fn new_impl(
108        data: &'a [u8],
109        is_cff2: bool,
110        upem: Option<i32>,
111        top_dict_data: &'a [u8],
112        top_dict_index: u16,
113        strings: Index<'a>,
114        global_subrs: Index<'a>,
115    ) -> Result<Self, Error> {
116        let top_dict = TopDict::new(data, top_dict_data, strings, is_cff2)?;
117        let top_upem = top_dict.matrix.map(|mat| mat.scale).unwrap_or(1000);
118        Ok(Self {
119            data,
120            is_cff2,
121            upem: upem.unwrap_or(top_upem),
122            global_subrs,
123            top_dict,
124            top_dict_index,
125        })
126    }
127
128    /// Returns the raw CFF blob.
129    pub fn data(&self) -> &'a [u8] {
130        self.data
131    }
132
133    /// Returns the CFF version (either 1 or 2).
134    pub fn version(&self) -> u16 {
135        if self.is_cff2 {
136            2
137        } else {
138            1
139        }
140    }
141
142    /// Returns additional metadata such as font names and metrics.
143    pub fn metadata(&self) -> Option<Metadata<'a>> {
144        Metadata::new(self.data, self.top_dict_index)
145    }
146
147    /// Returns true if this is a CID-keyed font.
148    pub fn is_cid(&self) -> bool {
149        matches!(&self.top_dict.kind, CffFontKind::Cid { .. })
150    }
151
152    /// Returns the global subroutine index.
153    pub fn global_subrs(&self) -> &Index<'a> {
154        &self.global_subrs
155    }
156
157    /// Returns the number of glyphs in the CFF font.
158    pub fn num_glyphs(&self) -> u32 {
159        self.top_dict.charstrings.count()
160    }
161
162    /// Returns the charstring index.
163    pub fn charstrings(&self) -> &Index<'a> {
164        &self.top_dict.charstrings
165    }
166
167    /// Returns the string index.
168    pub fn strings(&self) -> Option<&Index<'a>> {
169        match &self.top_dict.kind {
170            CffFontKind::Sid { strings, .. } => Some(strings),
171            _ => None,
172        }
173    }
174
175    /// Returns the string for the given identifier.
176    pub fn string(&self, sid: Sid) -> Option<&'a [u8]> {
177        match sid.resolve_standard() {
178            Ok(s) => Some(s),
179            Err(idx) => self.strings()?.get(idx),
180        }
181    }
182
183    /// Returns the mapping for glyph identifiers.
184    ///
185    /// For a CID font, this maps between CIDs and glyph identifiers.
186    /// Otherwise maps between SIDs and glyph identifiers.
187    pub fn charset(&self) -> Option<Charset<'a>> {
188        Charset::new(
189            self.data.into(),
190            self.top_dict.charset_offset.get()?,
191            self.top_dict.charstrings.count(),
192        )
193    }
194
195    /// Returns the mapping from character codes to glyph identifiers.
196    pub fn encoding(&self) -> Option<Encoding<'a>> {
197        let charset = self.charset()?;
198        let encoding = RawEncoding::new(self.data, self.top_dict.encoding_offset.get()?)?;
199        Some(Encoding { encoding, charset })
200    }
201
202    /// Returns the top level font matrix.
203    pub fn matrix(&self) -> Option<&ScaledFontMatrix> {
204        self.top_dict.matrix.as_ref()
205    }
206
207    /// Returns the units per em.
208    pub fn upem(&self) -> i32 {
209        self.upem
210    }
211
212    /// Returns the item variation store.
213    ///
214    /// Only present for CFF2 variable fonts.
215    pub fn var_store(&self) -> Option<&ItemVariationStore<'a>> {
216        self.top_dict.var_store.as_ref()
217    }
218
219    /// Returns the number of available subfonts.
220    pub fn num_subfonts(&self) -> u16 {
221        match &self.top_dict.kind {
222            CffFontKind::Sid { .. } => 1,
223            CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
224                fd_array.count() as u16
225            }
226        }
227    }
228
229    /// Returns the subfont index for the given glyph.
230    pub fn subfont_index(&self, gid: GlyphId) -> Option<u16> {
231        match &self.top_dict.kind {
232            CffFontKind::Sid { .. } => Some(0),
233            CffFontKind::Cid { fd_select, .. } | CffFontKind::Cff2 { fd_select, .. } => fd_select
234                .as_ref()
235                .map_or(Some(0), |fds| fds.font_index(gid)),
236        }
237    }
238
239    /// Returns the subfont with the given index and normalized variation
240    /// coordinates.
241    pub fn subfont(&self, index: u16, coords: &[F2Dot14]) -> Result<Subfont, Error> {
242        let blend = self.blend_state(0, coords);
243        match &self.top_dict.kind {
244            CffFontKind::Sid { private_dict, .. } => Subfont::new(
245                self.data,
246                private_dict.start as usize..private_dict.end as usize,
247                blend,
248                None,
249            ),
250            CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
251                let font_dict =
252                    FontDict::new(fd_array.get(index as usize).ok_or(Error::Malformed)?)?;
253                Subfont::new(
254                    self.data,
255                    font_dict.private_dict_range,
256                    blend,
257                    font_dict.matrix,
258                )
259            }
260        }
261    }
262
263    /// Returns the subfont and hinting parameters for the given index and
264    /// normalized variation coordinates.
265    pub fn subfont_hinted(
266        &self,
267        index: u16,
268        coords: &[F2Dot14],
269    ) -> Result<(Subfont, HintingParams), Error> {
270        let blend = self.blend_state(0, coords);
271        match &self.top_dict.kind {
272            CffFontKind::Sid { private_dict, .. } => Subfont::new_hinted(
273                self.data,
274                private_dict.start as usize..private_dict.end as usize,
275                blend,
276                None,
277            ),
278            CffFontKind::Cid { fd_array, .. } | CffFontKind::Cff2 { fd_array, .. } => {
279                let font_dict =
280                    FontDict::new(fd_array.get(index as usize).ok_or(Error::Malformed)?)?;
281                Subfont::new_hinted(
282                    self.data,
283                    font_dict.private_dict_range,
284                    blend,
285                    font_dict.matrix,
286                )
287            }
288        }
289    }
290
291    /// Returns the effective transform for the given subfont and optional size
292    /// in pixels per em.
293    pub fn transform(&self, subfont: &Subfont, ppem: Option<f32>) -> Transform {
294        let mut scale = ppem.map(|ppem| Transform::compute_scale(ppem, self.upem));
295        // Compute our font matrix and adjusted UPEM
296        // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/f1cd6dbfa0c98f352b698448f40ac27e8fb3832e/src/cff/cffobjs.c#L746>
297        let scaled_matrix = if let Some(top_matrix) = self.top_dict.matrix {
298            // We have a top dict matrix. Now check for a font dict matrix.
299            if let Some(sub_matrix) = subfont.matrix {
300                Some(top_matrix.combine(&sub_matrix))
301            } else {
302                // Top matrix was already normalized on load
303                Some(top_matrix)
304            }
305        } else {
306            // Just normalize if we have a subfont matrix
307            subfont.matrix.map(|matrix| matrix.normalize())
308        };
309        // Now adjust our scale factor if necessary
310        // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/f1cd6dbfa0c98f352b698448f40ac27e8fb3832e/src/cff/cffgload.c#L450>
311        if let Some(matrix) = scaled_matrix.as_ref() {
312            // If the scaling factor from our matrix does not equal the nominal
313            // UPEM of the font then adjust the scale.
314            if matrix.scale != self.upem {
315                // In this case, we need to force a scale for "unscaled"
316                // requests in order to apply the adjusted UPEM from the
317                // font matrix.
318                let original_scale = scale.unwrap_or(Fixed::from_i32(64));
319                scale = Some(
320                    original_scale
321                        .mul_div(Fixed::from_bits(self.upem), Fixed::from_bits(matrix.scale)),
322                );
323            }
324        }
325        Transform {
326            matrix: scaled_matrix
327                .map(|scaled_mat| scaled_mat.matrix)
328                .unwrap_or_default(),
329            scale,
330        }
331    }
332
333    /// Evaluates the charstring for the requested glyph far enough to read
334    /// its advance width, without drawing it.
335    ///
336    /// A Type 2 charstring states its width, where it states one at all, as
337    /// an optional extra argument on the first operator that clears the
338    /// stack, so evaluation stops there. Where the charstring states none,
339    /// the subfont's default width applies.
340    ///
341    /// The font matrix is applied and no size is, so the width is exact and
342    /// in the units the rest of the font is measured in.
343    /// [`advance`](Self::advance) applies a size as well and reports what
344    /// [`draw`](Self::draw) does.
345    ///
346    /// Unlike [`evaluate_charstring`], the matrix is applied here rather than
347    /// left to a caller. That one withholds it so a hinter can be slotted in
348    /// ahead of it; nothing hints a width.
349    ///
350    /// [`evaluate_charstring`]: Self::evaluate_charstring
351    pub fn evaluate_width(
352        &self,
353        subfont: &Subfont,
354        gid: GlyphId,
355        coords: &[F2Dot14],
356    ) -> Result<Option<Fixed>, Error> {
357        let transform = self.transform(subfont, None);
358        Ok(self
359            .charstring_width(subfont, gid, coords)?
360            .map(|width| transform.transform_h_metric(width)))
361    }
362
363    /// The width the charstring itself gives, before any transform.
364    ///
365    /// Where it gives none the subfont's default applies, as it does when the
366    /// glyph is drawn.
367    fn charstring_width(
368        &self,
369        subfont: &Subfont,
370        gid: GlyphId,
371        coords: &[F2Dot14],
372    ) -> Result<Option<Fixed>, Error> {
373        let charstrings = self.top_dict.charstrings.clone();
374        let blend = self.blend_state(subfont.vs_index, coords);
375        let subrs = if subfont.subrs_offset != 0 {
376            let data = self
377                .data
378                .get(subfont.subrs_offset as usize..)
379                .ok_or(Error::Malformed)?;
380            Index::new(data, self.is_cff2)?
381        } else {
382            Index::Empty
383        };
384        let charstring_data = charstrings
385            .get(gid.to_u32() as usize)
386            .ok_or(Error::Malformed)?;
387        let ctx = (self.data, &charstrings, &self.global_subrs, &subrs);
388        Ok(
389            match charstring::evaluate_width(&ctx, blend, charstring_data)? {
390                Some(width) => Some(width + subfont.nominal_width),
391                None => subfont.default_width,
392            },
393        )
394    }
395
396    /// Evaluates the charstring for the requested glyph and sends the results
397    /// to the given sink.
398    ///
399    /// Returns the width the charstring states, in the charstring's own
400    /// space: neither the font matrix nor a size is applied, to the width or
401    /// to the commands. [`draw`](Self::draw) applies both.
402    pub fn evaluate_charstring(
403        &self,
404        subfont: &Subfont,
405        gid: GlyphId,
406        coords: &[F2Dot14],
407        sink: &mut impl CommandSink,
408    ) -> Result<Option<Fixed>, Error> {
409        let charstrings = self.top_dict.charstrings.clone();
410        let blend = self.blend_state(subfont.vs_index, coords);
411        let subrs = if subfont.subrs_offset != 0 {
412            let data = self
413                .data
414                .get(subfont.subrs_offset as usize..)
415                .ok_or(Error::Malformed)?;
416            Index::new(data, self.is_cff2)?
417        } else {
418            Index::Empty
419        };
420        let charstring_data = charstrings
421            .get(gid.to_u32() as usize)
422            .ok_or(Error::Malformed)?;
423        let ctx = (self.data, &charstrings, &self.global_subrs, &subrs);
424        if let Some(width) = charstring::evaluate(&ctx, blend, charstring_data, sink)? {
425            Ok(Some(width + subfont.nominal_width))
426        } else {
427            Ok(subfont.default_width)
428        }
429    }
430
431    /// Returns the advance width of the glyph with an optional size in
432    /// ppem, without drawing it.
433    ///
434    /// This is the width [`draw`](Self::draw) reports, arrived at without
435    /// the drawing.
436    pub fn advance(
437        &self,
438        subfont: &Subfont,
439        gid: GlyphId,
440        coords: &[F2Dot14],
441        ppem: Option<f32>,
442    ) -> Result<Option<f32>, Error> {
443        let transform = self.transform(subfont, ppem);
444        Ok(self
445            .charstring_width(subfont, gid, coords)?
446            .map(|width| transform.transform_h_metric(width).to_f32().max(0.0)))
447    }
448
449    /// Measures the box the glyph's drawing stays within, in design units.
450    ///
451    /// A control box: a curve counts through its control points rather than
452    /// the path they describe, so one bulging inside its hull measures larger
453    /// than it draws. HarfBuzz reports a charstring's extents the same way.
454    ///
455    /// The font matrix is applied and no size is, so the box is exact and in
456    /// the units the rest of the font is measured in.
457    /// [`extents`](Self::extents) applies a size as well and answers in what
458    /// a caller laying out text works in.
459    ///
460    /// Unlike [`evaluate_charstring`], the matrix is applied here rather than
461    /// left to a caller. That one withholds it so a hinter can be slotted in
462    /// before it; nothing hints a box, and a box cannot be brought through a
463    /// matrix afterwards anyway, because turning a box turns its corners and
464    /// a matrix that shears tilts the drawing inside a box that has to grow
465    /// to hold them.
466    ///
467    /// `None` where the glyph draws nothing.
468    ///
469    /// [`evaluate_charstring`]: Self::evaluate_charstring
470    pub fn evaluate_extents(
471        &self,
472        subfont: &Subfont,
473        gid: GlyphId,
474        coords: &[F2Dot14],
475    ) -> Result<Option<BoundingBox<Fixed>>, Error> {
476        let mut bounds = charstring::ControlBoundsSink::new();
477        let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
478        let transform = self.transform(subfont, None);
479        let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
480        self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
481        Ok(bounds.bounding_box())
482    }
483
484    /// Returns the box the glyph's drawing stays within, with an optional
485    /// size in ppem.
486    ///
487    /// The box [`draw`](Self::draw) would stay within, measured as
488    /// [`evaluate_extents`](Self::evaluate_extents) measures it and scaled by
489    /// the size as well.
490    ///
491    /// A size can be applied to a finished box, being one scale in both
492    /// directions; it is applied here so the answer matches `draw` at that
493    /// size without a caller doing the arithmetic. The matrix cannot, which
494    /// is why neither of these leaves it out.
495    ///
496    /// `None` where the glyph draws nothing.
497    pub fn extents(
498        &self,
499        subfont: &Subfont,
500        gid: GlyphId,
501        coords: &[F2Dot14],
502        ppem: Option<f32>,
503    ) -> Result<Option<BoundingBox<f32>>, Error> {
504        let mut bounds = charstring::ControlBoundsSink::new();
505        let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
506        let transform = self.transform(subfont, ppem);
507        let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
508        self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
509        Ok(bounds.bounding_box().map(|b| BoundingBox {
510            x_min: b.x_min.to_f32(),
511            y_min: b.y_min.to_f32(),
512            x_max: b.x_max.to_f32(),
513            y_max: b.y_max.to_f32(),
514        }))
515    }
516
517    /// Draws the glyph with an optional size in ppem to the given pen.
518    ///
519    /// Returns the advance width of the glyph if the charstring provides
520    /// one.
521    pub fn draw(
522        &self,
523        subfont: &Subfont,
524        gid: GlyphId,
525        coords: &[F2Dot14],
526        ppem: Option<f32>,
527        sink: &mut impl PathSink,
528    ) -> Result<Option<f32>, Error> {
529        let mut nop_filter = NopFilterSink::new(sink);
530        let transform = self.transform(subfont, ppem);
531        let mut transformer = TransformSink::new(&mut nop_filter, transform);
532        let width = self.evaluate_charstring(subfont, gid, coords, &mut transformer)?;
533        Ok(width.map(|w| transform.transform_h_metric(w).to_f32().max(0.0)))
534    }
535
536    /// Returns a blend state for the given variation store index and
537    /// normalized coordinates.
538    fn blend_state(&self, vs_index: u16, coords: &'a [F2Dot14]) -> Option<BlendState<'a>> {
539        self.top_dict
540            .var_store
541            .as_ref()
542            .and_then(|store| BlendState::new(store.clone(), coords, vs_index).ok())
543    }
544}
545
546/// Mapping from character codes to glyph identifiers.
547#[derive(Clone)]
548pub struct Encoding<'a> {
549    encoding: RawEncoding<'a>,
550    charset: Charset<'a>,
551}
552
553impl<'a> Encoding<'a> {
554    /// Returns the predefined encoding, if any. Otherwise this is a custom
555    /// encoding.
556    pub fn predefined(&self) -> Option<PredefinedEncoding> {
557        if let RawEncoding::Predefined(pre) = &self.encoding {
558            Some(*pre)
559        } else {
560            None
561        }
562    }
563
564    /// Returns the associated character set.
565    pub fn charset(&self) -> &Charset<'a> {
566        &self.charset
567    }
568
569    /// Maps a character code to a glyph identifier.
570    pub fn map(&self, code: u8) -> Option<GlyphId> {
571        self.encoding.map(&self.charset, code)
572    }
573}
574
575/// An SID or CID font.
576#[derive(Clone)]
577enum CffFontKind<'a> {
578    /// A CFF font.
579    Sid {
580        /// Index for resolving glyph names.
581        strings: Index<'a>,
582        /// Byte range of the private dict from the base of the font data.
583        private_dict: Range<u32>,
584    },
585    /// A CFF font with an externally defined encoding.
586    Cid {
587        /// Maps from glyph identifiers to font dict indices.
588        fd_select: Option<FdSelect<'a>>,
589        /// Index containing font dicts.
590        fd_array: Index<'a>,
591    },
592    /// A CFF2 font.
593    Cff2 {
594        /// Maps from glyph identifiers to font dict indices.
595        fd_select: Option<FdSelect<'a>>,
596        /// Index containing font dicts.
597        fd_array: Index<'a>,
598    },
599}
600
601/// Metadata for a CFF subfont.
602///
603/// A subfont is the collection of data read from both the
604/// [Font DICT](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=28)
605/// and [Private Dict](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf#page=24)
606/// structures. These determine the set of subroutines, metrics and hinting
607/// parameters for some group of glyphs.
608///
609/// Use [CffFontRef::subfont_index] to determine the subfont index for a
610/// particular glyph and then [CffFontRef::subfont] (or
611/// [CffFontRef::subfont_hinted]) to retrieve the associated subfont.
612#[derive(Copy, Clone, Default, Debug)]
613pub struct Subfont {
614    subrs_offset: u32,
615    default_width: Option<Fixed>,
616    nominal_width: Fixed,
617    matrix: Option<ScaledFontMatrix>,
618    vs_index: u16,
619}
620
621impl Subfont {
622    fn new(
623        data: &[u8],
624        range: Range<usize>,
625        blend: Option<BlendState>,
626        matrix: Option<ScaledFontMatrix>,
627    ) -> Result<Self, Error> {
628        let mut subfont = Self {
629            matrix,
630            ..Default::default()
631        };
632        let data = data.get(range.clone()).ok_or(Error::Malformed)?;
633        for entry in dict::unhinted_private_entries(data, blend).filter_map(|e| e.ok()) {
634            match entry {
635                dict::Entry::SubrsOffset(offset) => {
636                    subfont.subrs_offset =
637                        range.start.checked_add(offset).ok_or(Error::Malformed)? as u32;
638                }
639                dict::Entry::VariationStoreIndex(index) => subfont.vs_index = index,
640                // FreeType truncates the width values to int on read
641                dict::Entry::DefaultWidthX(width) => subfont.default_width = Some(width.floor()),
642                dict::Entry::NominalWidthX(width) => subfont.nominal_width = width.floor(),
643                _ => {}
644            }
645        }
646        Ok(subfont)
647    }
648
649    fn new_hinted(
650        data: &[u8],
651        range: Range<usize>,
652        blend: Option<BlendState>,
653        matrix: Option<ScaledFontMatrix>,
654    ) -> Result<(Self, HintingParams), Error> {
655        let mut subfont = Self {
656            matrix,
657            ..Default::default()
658        };
659        let mut params = HintingParams::default();
660        let data = data.get(range.clone()).ok_or(Error::Malformed)?;
661        for entry in dict::entries(data, blend).filter_map(|e| e.ok()) {
662            match entry {
663                dict::Entry::SubrsOffset(offset) => {
664                    subfont.subrs_offset =
665                        range.start.checked_add(offset).ok_or(Error::Malformed)? as u32;
666                }
667                dict::Entry::VariationStoreIndex(index) => subfont.vs_index = index,
668                // FreeType truncates the width values to int on read
669                dict::Entry::DefaultWidthX(width) => subfont.default_width = Some(width.floor()),
670                dict::Entry::NominalWidthX(width) => subfont.nominal_width = width.floor(),
671                dict::Entry::BlueValues(values) => params.blues = values,
672                dict::Entry::FamilyBlues(values) => params.family_blues = values,
673                dict::Entry::OtherBlues(values) => params.other_blues = values,
674                dict::Entry::FamilyOtherBlues(values) => params.family_other_blues = values,
675                dict::Entry::BlueScale(value) => params.blue_scale = value,
676                dict::Entry::BlueShift(value) => params.blue_shift = value,
677                dict::Entry::BlueFuzz(value) => params.blue_fuzz = value,
678                dict::Entry::LanguageGroup(group) => params.language_group = group,
679                _ => {}
680            }
681        }
682        Ok((subfont, params))
683    }
684
685    /// Returns the offset to the local subroutine index from the start of the
686    /// CFF blob.
687    pub fn subrs_offset(&self) -> u32 {
688        self.subrs_offset
689    }
690
691    /// Returns the default advance width.
692    ///
693    /// The advance value for charstrings that do not contain a width.
694    pub fn default_width(&self) -> Option<Fixed> {
695        self.default_width
696    }
697
698    /// Returns the nominal advance width.
699    ///
700    /// The base advance value for charstrings that do contain a width. This
701    /// should be added to the width in the charstring.
702    pub fn nominal_width(&self) -> Fixed {
703        self.nominal_width
704    }
705
706    /// Returns the font matrix.
707    pub fn matrix(&self) -> Option<&ScaledFontMatrix> {
708        self.matrix.as_ref()
709    }
710
711    /// Returns the default variation store index.
712    pub fn vs_index(&self) -> u16 {
713        self.vs_index
714    }
715}
716
717/// Use in-band signaling for missing offsets to keep the struct size small.
718#[derive(Copy, Clone)]
719struct MaybeOffset(u32);
720
721impl MaybeOffset {
722    fn get(self) -> Option<usize> {
723        (self.0 != u32::MAX).then_some(self.0 as usize)
724    }
725}
726
727impl Default for MaybeOffset {
728    fn default() -> Self {
729        Self(u32::MAX)
730    }
731}
732
733#[derive(Clone)]
734struct TopDict<'a> {
735    charstrings: Index<'a>,
736    charset_offset: MaybeOffset,
737    encoding_offset: MaybeOffset,
738    matrix: Option<ScaledFontMatrix>,
739    var_store: Option<ItemVariationStore<'a>>,
740    kind: CffFontKind<'a>,
741}
742
743impl<'a> TopDict<'a> {
744    fn new(
745        cff_data: &'a [u8],
746        top_dict_data: &[u8],
747        strings: Index<'a>,
748        is_cff2: bool,
749    ) -> Result<Self, Error> {
750        let mut has_ros = false;
751        let mut charstrings = None;
752        let [mut charset_offset, mut encoding_offset] = if is_cff2 {
753            // CFF2 fonts use the cmap table but grab the encoding and
754            // charset if one is provided
755            [MaybeOffset::default(); 2]
756        } else {
757            // CFF fonts have a default charset and encoding offset of 0
758            // which selects the standard Adobe encoding
759            [MaybeOffset(0); 2]
760        };
761        let mut fd_array = None;
762        let mut fd_select = None;
763        let mut private_dict_range = 0..0;
764        let mut matrix = None;
765        let mut var_store = None;
766        for entry in dict::entries(top_dict_data, None).filter_map(|e| e.ok()) {
767            match entry {
768                dict::Entry::Ros { .. } => has_ros = true,
769                dict::Entry::CharstringsOffset(offset) => {
770                    charstrings = cff_data
771                        .get(offset..)
772                        .and_then(|data| Index::new(data, is_cff2).ok());
773                }
774                dict::Entry::Charset(offset) => charset_offset = MaybeOffset(offset as u32),
775                dict::Entry::Encoding(offset) => encoding_offset = MaybeOffset(offset as u32),
776                dict::Entry::FdArrayOffset(offset) => {
777                    fd_array = cff_data
778                        .get(offset..)
779                        .and_then(|data| Index::new(data, is_cff2).ok());
780                }
781                dict::Entry::FdSelectOffset(offset) => {
782                    fd_select = cff_data
783                        .get(offset..)
784                        .and_then(|data| FdSelect::read(data.into()).ok());
785                }
786                dict::Entry::PrivateDictRange(range) => {
787                    // Fail early if our private dictionary is out of bounds
788                    let _ = cff_data.get(range.clone()).ok_or(Error::Malformed)?;
789                    private_dict_range = range;
790                }
791                dict::Entry::FontMatrix(font_matrix) => {
792                    // FreeType always normalizes this and the scaling factor
793                    // is dynamic so it won't make a difference to our users
794                    matrix = Some(font_matrix.normalize());
795                }
796                dict::Entry::VariationStoreOffset(offset) if is_cff2 => {
797                    // IVS is preceded by a 2 byte length, but ensure that
798                    // we don't overflow
799                    // See <https://github.com/googlefonts/fontations/issues/1223>
800                    let offset = offset.checked_add(2).ok_or(Error::Malformed)?;
801                    var_store = Some(ItemVariationStore::read(
802                        cff_data.get(offset..).unwrap_or_default().into(),
803                    )?);
804                }
805                _ => {}
806            }
807        }
808        let charstrings = charstrings.ok_or(Error::MissingResource)?;
809        let kind = if let Some(fd_array) = fd_array {
810            if is_cff2 {
811                CffFontKind::Cff2 {
812                    fd_array,
813                    fd_select,
814                }
815            } else {
816                CffFontKind::Cid {
817                    fd_array,
818                    fd_select,
819                }
820            }
821        } else {
822            if has_ros || is_cff2 {
823                // The font dict array is required for CID-keyed and CFF2 fonts
824                return Err(Error::MissingResource);
825            }
826            CffFontKind::Sid {
827                strings,
828                private_dict: private_dict_range.start as u32..private_dict_range.end as u32,
829            }
830        };
831        Ok(Self {
832            charset_offset,
833            encoding_offset,
834            charstrings,
835            matrix,
836            kind,
837            var_store,
838        })
839    }
840}
841
842#[derive(Default)]
843struct FontDict {
844    private_dict_range: Range<usize>,
845    matrix: Option<ScaledFontMatrix>,
846}
847
848impl FontDict {
849    fn new(dict_data: &[u8]) -> Result<Self, Error> {
850        let mut range = None;
851        let mut matrix = None;
852        for entry in dict::entries(dict_data, None) {
853            match entry? {
854                dict::Entry::PrivateDictRange(dict_range) => {
855                    range = Some(dict_range);
856                }
857                dict::Entry::FontMatrix(font_matrix) => {
858                    matrix = Some(font_matrix);
859                }
860                _ => {}
861            }
862        }
863        Ok(Self {
864            private_dict_range: range.ok_or(Error::MissingResource)?,
865            matrix,
866        })
867    }
868}
869
870/// Extra metadata for a CFF font.
871///
872/// This is accessed separately because this information is redundant when a
873/// CFF blob is used in an OpenType font.
874#[derive(Copy, Clone, Debug)]
875pub struct Metadata<'a> {
876    name: Option<&'a str>,
877    version: Option<&'a str>,
878    notice: Option<&'a str>,
879    copyright: Option<&'a str>,
880    full_name: Option<&'a str>,
881    family_name: Option<&'a str>,
882    weight: Option<&'a str>,
883    bbox: BoundingBox<Fixed>,
884    italic_angle: Fixed,
885    is_fixed_pitch: bool,
886    underline_position: Fixed,
887    underline_thickness: Fixed,
888}
889
890impl<'a> Metadata<'a> {
891    fn new(data: &'a [u8], top_dict_index: u16) -> Option<Self> {
892        let cff = cff::Cff::read(FontData::new(data)).ok()?;
893        let strings = cff.strings();
894        let get_str = |sid: Sid| {
895            let bytes = match sid.resolve_standard() {
896                Ok(bytes) => bytes,
897                Err(idx) => strings.get(idx)?,
898            };
899            core::str::from_utf8(bytes).ok()
900        };
901        let top_dict_data = cff.top_dicts().get(top_dict_index as usize)?;
902        let name = cff
903            .name(top_dict_index as usize)
904            .and_then(|bytes| core::str::from_utf8(bytes).ok());
905        let mut meta = Metadata {
906            name,
907            ..Default::default()
908        };
909        for entry in dict::entries(top_dict_data, None).filter_map(|e| e.ok()) {
910            match entry {
911                dict::Entry::Version(sid) => meta.version = get_str(sid),
912                dict::Entry::Notice(sid) => meta.notice = get_str(sid),
913                dict::Entry::Copyright(sid) => meta.copyright = get_str(sid),
914                dict::Entry::FullName(sid) => meta.full_name = get_str(sid),
915                dict::Entry::FamilyName(sid) => meta.family_name = get_str(sid),
916                dict::Entry::Weight(sid) => meta.weight = get_str(sid),
917                dict::Entry::FontBbox([x_min, y_min, x_max, y_max]) => {
918                    meta.bbox = BoundingBox {
919                        x_min,
920                        x_max,
921                        y_min,
922                        y_max,
923                    }
924                }
925                dict::Entry::ItalicAngle(angle) => meta.italic_angle = angle,
926                dict::Entry::IsFixedPitch(fixed_pitch) => meta.is_fixed_pitch = fixed_pitch,
927                dict::Entry::UnderlinePosition(pos) => meta.underline_position = pos,
928                dict::Entry::UnderlineThickness(size) => meta.underline_thickness = size,
929                _ => {}
930            }
931        }
932        Some(meta)
933    }
934
935    /// Returns the PostScript name.
936    pub fn name(&self) -> Option<&'a str> {
937        self.name
938    }
939
940    /// Returns the version string.
941    pub fn version(&self) -> Option<&'a str> {
942        self.version
943    }
944
945    /// Returns the notice, commonly a trademark statement.
946    pub fn notice(&self) -> Option<&'a str> {
947        self.notice
948    }
949
950    /// Returns the copyright statement.
951    pub fn copyright(&self) -> Option<&'a str> {
952        self.copyright
953    }
954
955    /// Returns the full font name.
956    pub fn full_name(&self) -> Option<&'a str> {
957        self.full_name
958    }
959
960    /// Returns the font family name.
961    pub fn family_name(&self) -> Option<&'a str> {
962        self.family_name
963    }
964
965    /// Returns the weight or style name.
966    pub fn weight(&self) -> Option<&'a str> {
967        self.weight
968    }
969
970    /// Returns the italic angle.
971    pub fn italic_angle(&self) -> Fixed {
972        self.italic_angle
973    }
974
975    /// Returns true if the glyphs in this font have the same width.
976    pub fn is_fixed_pitch(&self) -> bool {
977        self.is_fixed_pitch
978    }
979
980    /// Returns the position of the top of an underline decoration.
981    pub fn underline_position(&self) -> Fixed {
982        self.underline_position
983    }
984
985    /// Returns the suggested size for an underline decoration.
986    pub fn underline_thickness(&self) -> Fixed {
987        self.underline_thickness
988    }
989
990    /// Returns the font bounding box.
991    pub fn bbox(&self) -> BoundingBox<Fixed> {
992        self.bbox
993    }
994}
995
996impl Default for Metadata<'_> {
997    fn default() -> Self {
998        Self {
999            name: None,
1000            version: None,
1001            notice: None,
1002            copyright: None,
1003            full_name: None,
1004            family_name: None,
1005            weight: None,
1006            bbox: BoundingBox::default(),
1007            italic_angle: Fixed::ZERO,
1008            is_fixed_pitch: false,
1009            underline_position: Fixed::from_i32(-100),
1010            underline_thickness: Fixed::from_i32(50),
1011        }
1012    }
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018    use crate::{
1019        ps::{hinting::Blues, transform::FontMatrix},
1020        FontData, FontRef, TableProvider,
1021    };
1022    use charstring::test_helpers::*;
1023    use font_test_data::bebuffer::BeBuffer;
1024
1025    #[test]
1026    fn read_cff_static() {
1027        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1028        let cff =
1029            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1030        assert_eq!(cff.version(), 1);
1031        assert!(cff.var_store().is_none());
1032        let CffFontKind::Sid { private_dict, .. } = &cff.top_dict.kind else {
1033            panic!("this is an SID font");
1034        };
1035        assert!(!private_dict.is_empty());
1036        assert_eq!(cff.num_glyphs(), 5);
1037        assert_eq!(cff.num_subfonts(), 1);
1038        assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1039        assert_eq!(cff.global_subrs.count(), 17);
1040    }
1041
1042    #[test]
1043    fn read_cff_metadata() {
1044        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1045        let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1046        let meta = cff.metadata().unwrap();
1047        assert_eq!(meta.name(), Some("NotoSerifDisplay-Regular"));
1048        assert_eq!(meta.full_name(), Some("Noto Serif Display Regular"));
1049        assert_eq!(meta.family_name(), Some("Noto Serif Display"));
1050        assert_eq!(meta.weight(), None);
1051        assert_eq!(
1052            meta.bbox(),
1053            BoundingBox {
1054                x_min: Fixed::from_i32(-693),
1055                y_min: Fixed::from_i32(-470),
1056                x_max: Fixed::from_i32(2797),
1057                y_max: Fixed::from_i32(1048)
1058            }
1059        );
1060        assert_eq!(meta.italic_angle(), Fixed::ZERO);
1061        assert!(!meta.is_fixed_pitch());
1062        assert_eq!(meta.underline_position(), Fixed::from_i32(-100));
1063        assert_eq!(meta.underline_thickness(), Fixed::from_i32(50));
1064        let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET).unwrap();
1065        let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1066        let meta = cff.metadata().unwrap();
1067        assert_eq!(meta.name(), Some("GoogleMaterialIcons-Regular"));
1068        assert_eq!(meta.full_name(), Some("GoogleMaterialIcons-Regular"));
1069        assert_eq!(meta.family_name(), None);
1070        assert_eq!(meta.weight(), None);
1071        assert_eq!(
1072            meta.bbox(),
1073            BoundingBox {
1074                x_min: Fixed::from_i32(-1),
1075                y_min: Fixed::ZERO,
1076                x_max: Fixed::from_i32(513),
1077                y_max: Fixed::from_i32(512)
1078            }
1079        );
1080        assert_eq!(meta.italic_angle(), Fixed::ZERO);
1081        assert!(!meta.is_fixed_pitch());
1082        assert_eq!(meta.underline_position(), Fixed::from_i32(-100));
1083        assert_eq!(meta.underline_thickness(), Fixed::from_i32(50));
1084    }
1085
1086    #[test]
1087    fn read_cff2_static() {
1088        let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1089        let cff =
1090            CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1091        assert_eq!(cff.version(), 2);
1092        assert!(cff.var_store().is_some());
1093        let CffFontKind::Cff2 { fd_array, .. } = &cff.top_dict.kind else {
1094            panic!("this is a CFF2 font");
1095        };
1096        assert_eq!(fd_array.count(), 1);
1097        assert_eq!(cff.num_glyphs(), 6);
1098        assert_eq!(cff.num_subfonts(), 1);
1099        assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1100        assert_eq!(cff.global_subrs.count(), 0);
1101    }
1102
1103    #[test]
1104    fn read_example_cff2_table() {
1105        let cff = CffFontRef::new_cff2(font_test_data::cff2::EXAMPLE, None).unwrap();
1106        assert_eq!(cff.version(), 2);
1107        assert!(cff.var_store().is_some());
1108        let CffFontKind::Cff2 { fd_array, .. } = &cff.top_dict.kind else {
1109            panic!("this is a CFF2 font");
1110        };
1111        assert_eq!(fd_array.count(), 1);
1112        assert_eq!(cff.num_glyphs(), 2);
1113        assert_eq!(cff.num_subfonts(), 1);
1114        assert_eq!(cff.subfont_index(GlyphId::new(1)), Some(0));
1115        assert_eq!(cff.global_subrs.count(), 0);
1116    }
1117
1118    #[test]
1119    fn charset() {
1120        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1121        let cff =
1122            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1123        let charset = cff.charset().unwrap();
1124        let glyph_names = charset
1125            .iter()
1126            .map(|(gid, sid)| {
1127                (
1128                    gid.to_u32(),
1129                    std::str::from_utf8(sid.resolve_standard().unwrap()).unwrap(),
1130                )
1131            })
1132            .collect::<Vec<_>>();
1133        let expected = [(0, ".notdef"), (1, "i"), (2, "j"), (3, "k"), (4, "l")];
1134        assert_eq!(glyph_names, expected)
1135    }
1136
1137    // Fuzzer caught add with overflow when computing offset to
1138    // var store.
1139    // See <https://issues.oss-fuzz.com/issues/377574377>
1140    #[test]
1141    fn top_dict_ivs_offset_overflow() {
1142        // A top DICT with a var store offset of -1 which will cause an
1143        // overflow
1144        let top_dict = BeBuffer::new()
1145            .push(29u8) // integer operator
1146            .push(-1i32) // integer value
1147            .push(24u8) // var store offset operator
1148            .to_vec();
1149        // Just don't panic with overflow
1150        assert!(TopDict::new(&[], &top_dict, Index::Empty, true).is_err());
1151    }
1152
1153    /// Fuzzer caught add with overflow when computing subrs offset.
1154    /// See <https://issues.oss-fuzz.com/issues/377965575>
1155    #[test]
1156    fn subrs_offset_overflow() {
1157        // A private DICT with an overflowing subrs offset
1158        let private_dict = BeBuffer::new()
1159            .push(0u32) // pad so that range doesn't start with 0 and we overflow
1160            .push(29u8) // integer operator
1161            .push(-1i32) // integer value
1162            .push(19u8) // subrs offset operator
1163            .to_vec();
1164        // Just don't panic with overflow
1165        assert!(Subfont::new(&private_dict, 4..private_dict.len(), None, None).is_err());
1166    }
1167
1168    /// Ensure we don't reject an empty Private DICT
1169    #[test]
1170    fn empty_private_dict() {
1171        let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET).unwrap();
1172        let cff =
1173            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1174        let CffFontKind::Sid { private_dict, .. } = &cff.top_dict.kind else {
1175            panic!("this is an SID font");
1176        };
1177        assert!(private_dict.is_empty());
1178    }
1179
1180    // We were overwriting family_other_blues with family_blues.
1181    #[test]
1182    fn capture_family_other_blues() {
1183        let private_dict_data = &font_test_data::cff2::EXAMPLE[0x4f..=0xc0];
1184        let store =
1185            ItemVariationStore::read(FontData::new(&font_test_data::cff2::EXAMPLE[18..])).unwrap();
1186        let coords = &[F2Dot14::from_f32(0.0)];
1187        let blend_state = BlendState::new(store, coords, 0).unwrap();
1188        let (_subfont, hint_params) = Subfont::new_hinted(
1189            private_dict_data,
1190            0..private_dict_data.len(),
1191            Some(blend_state),
1192            None,
1193        )
1194        .unwrap();
1195        assert_eq!(
1196            hint_params.family_other_blues,
1197            Blues::new([-249.0, -239.0].map(Fixed::from_f64).into_iter())
1198        )
1199    }
1200
1201    #[test]
1202    fn subfont_cff() {
1203        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1204        let cff =
1205            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1206        let subfont = cff.subfont(0, &[]).unwrap();
1207        assert_eq!(subfont.default_width, None);
1208        assert_eq!(subfont.nominal_width, Fixed::from_i32(598));
1209        assert_eq!(subfont.vs_index, 0);
1210        assert_eq!(subfont.matrix, None);
1211    }
1212
1213    fn make_blues<const N: usize>(values: [i32; N]) -> Blues {
1214        Blues::new(values.map(Fixed::from_i32).into_iter())
1215    }
1216
1217    #[test]
1218    fn hinted_subfont_cff() {
1219        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1220        let cff =
1221            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1222        let (subfont, hinting) = cff.subfont_hinted(0, &[]).unwrap();
1223        assert_eq!(subfont.default_width, None);
1224        assert_eq!(subfont.nominal_width, Fixed::from_i32(598));
1225        assert_eq!(subfont.vs_index, 0);
1226        assert_eq!(subfont.matrix, None);
1227        let expected_hinting = HintingParams {
1228            blues: make_blues([-15, 0, 536, 547, 571, 582, 714, 726, 760, 772]),
1229            family_blues: Blues::default(),
1230            other_blues: make_blues([-255, -240]),
1231            family_other_blues: Blues::default(),
1232            blue_scale: Fixed::from_f64(0.0500030517578125),
1233            blue_shift: Fixed::from_f64(7.0),
1234            blue_fuzz: Fixed::ZERO,
1235            language_group: 0,
1236        };
1237        assert_eq!(hinting, expected_hinting);
1238    }
1239
1240    #[test]
1241    fn subfont_cff2() {
1242        let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1243        let cff =
1244            CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1245        let subfont = cff.subfont(0, &[]).unwrap();
1246        assert_eq!(subfont.default_width, None);
1247        assert_eq!(subfont.nominal_width, Fixed::ZERO);
1248        assert_eq!(subfont.vs_index, 0);
1249        assert_eq!(subfont.matrix, None);
1250    }
1251
1252    #[test]
1253    fn hinted_subfont_cff2() {
1254        let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1255        let cff =
1256            CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1257        let (subfont, hinting) = cff.subfont_hinted(0, &[]).unwrap();
1258        assert_eq!(subfont.default_width, None);
1259        assert_eq!(subfont.nominal_width, Fixed::ZERO);
1260        assert_eq!(subfont.vs_index, 0);
1261        assert_eq!(subfont.matrix, None);
1262        let expected_hinting = HintingParams {
1263            blues: make_blues([-10, 0, 482, 492, 694, 704, 739, 749]),
1264            family_blues: Blues::default(),
1265            other_blues: make_blues([-227, -217]),
1266            family_other_blues: Blues::default(),
1267            blue_scale: Fixed::from_f64(0.0625),
1268            blue_shift: Fixed::from_f64(7.0),
1269            blue_fuzz: Fixed::ONE,
1270            language_group: 0,
1271        };
1272        assert_eq!(hinting, expected_hinting);
1273    }
1274
1275    #[test]
1276    fn subfont_matrix() {
1277        let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX).unwrap();
1278        let cff =
1279            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1280        let subfont = cff.subfont(0, &[]).unwrap();
1281        assert_eq!(subfont.default_width, None);
1282        assert_eq!(subfont.nominal_width, Fixed::ZERO);
1283        assert_eq!(subfont.vs_index, 0);
1284        let expected_matrix = FontMatrix::from_elements([
1285            Fixed::from_i32(5),
1286            Fixed::ZERO,
1287            Fixed::ZERO,
1288            Fixed::from_i32(5),
1289            Fixed::ZERO,
1290            Fixed::ZERO,
1291        ]);
1292        let expected_scale = 10;
1293        assert_eq!(
1294            subfont.matrix,
1295            Some(ScaledFontMatrix {
1296                matrix: expected_matrix,
1297                scale: expected_scale
1298            })
1299        );
1300    }
1301
1302    #[test]
1303    fn eval_charstring_cff() {
1304        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1305        let cff =
1306            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1307        let mut sink = CharstringCommandCounter::default();
1308        let subfont = cff.subfont(0, &[]).unwrap();
1309        cff.evaluate_charstring(&subfont, GlyphId::new(2), &[], &mut sink)
1310            .unwrap();
1311        // Charstring eval is tested elsewhere so just make sure we're processing the
1312        // *correct* charstring.
1313        assert_eq!(sink.0, 18);
1314    }
1315
1316    #[test]
1317    fn eval_charstring_cff2() {
1318        let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1319        let cff =
1320            CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1321        let mut sink = CharstringCommandCounter::default();
1322        let subfont = cff.subfont(0, &[]).unwrap();
1323        cff.evaluate_charstring(&subfont, GlyphId::new(2), &[], &mut sink)
1324            .unwrap();
1325        // Charstring eval is tested elsewhere so just make sure we're processing the
1326        // *correct* charstring.
1327        assert_eq!(sink.0, 11);
1328    }
1329
1330    #[test]
1331    fn select_version() {
1332        // CFF2 font
1333        assert_eq!(
1334            CffFontRef::new(
1335                FontRef::new(font_test_data::CANTARELL_VF_TRIMMED)
1336                    .unwrap()
1337                    .cff2()
1338                    .unwrap()
1339                    .offset_data()
1340                    .as_bytes(),
1341                0,
1342                None
1343            )
1344            .unwrap()
1345            .version(),
1346            2
1347        );
1348        // CFF font
1349        assert_eq!(
1350            CffFontRef::new(
1351                FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX)
1352                    .unwrap()
1353                    .cff()
1354                    .unwrap()
1355                    .offset_data()
1356                    .as_bytes(),
1357                0,
1358                None
1359            )
1360            .unwrap()
1361            .version(),
1362            1
1363        );
1364        // Not a CFF font
1365        assert!(CffFontRef::new(&[0, 1, 4, 5], 0, None).is_err());
1366        // Spoof version 1
1367        assert!(CffFontRef::new(&[1, 1, 4, 5], 0, None).is_err());
1368        // Spoof version 2
1369        assert!(CffFontRef::new(&[2, 1, 4, 5], 0, None).is_err());
1370    }
1371
1372    #[test]
1373    fn transform() {
1374        // font with gnarly nested matrices
1375        let font = FontRef::new(font_test_data::MATERIAL_ICONS_SUBSET_MATRIX).unwrap();
1376        // this font has a fun upem of 512
1377        let cff =
1378            CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, Some(512)).unwrap();
1379        let subfont = cff.subfont(0, &[]).unwrap();
1380        // Extracted from FreeType
1381        let expected_matrix = [65536, 0, 5604, 65536, 0, 0].map(Fixed::from_bits);
1382        // Unscaled
1383        let transform = cff.transform(&subfont, None);
1384        assert_eq!(transform.matrix.elements(), expected_matrix);
1385        assert_eq!(transform.scale, Some(Fixed::from_bits(32 << 16)));
1386        // Scaled at 16px
1387        let transform = cff.transform(&subfont, Some(16.0));
1388        assert_eq!(transform.matrix.elements(), expected_matrix);
1389        assert_eq!(transform.scale, Some(Fixed::from_bits(1 << 16)));
1390    }
1391
1392    #[test]
1393    fn cff_encoding() {
1394        let font = FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
1395        let cff = CffFontRef::new(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1396        let encoding = cff.encoding().unwrap();
1397        assert_eq!(encoding.predefined(), Some(PredefinedEncoding::Standard));
1398    }
1399
1400    #[test]
1401    fn cff2_lacks_encoding() {
1402        let font = FontRef::new(font_test_data::CANTARELL_VF_TRIMMED).unwrap();
1403        let cff = CffFontRef::new(font.cff2().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1404        assert!(cff.encoding().is_none());
1405    }
1406}
1407
1408#[cfg(test)]
1409mod width_only_tests {
1410    use super::*;
1411    use crate::{model::glyph::outline::NullSink, FontRef, TableProvider};
1412
1413    const FONTS: [&[u8]; 3] = [
1414        font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
1415        font_test_data::ift::CFF_FONT,
1416        // A nested matrix, so the charstring's space and the font's differ
1417        // and the two widths are not the same number.
1418        font_test_data::MATERIAL_ICONS_SUBSET_MATRIX,
1419    ];
1420
1421    /// Calls `check` for every glyph, with the subfont that glyph belongs to.
1422    fn for_each_glyph(data: &[u8], mut check: impl FnMut(&CffFontRef, &Subfont, GlyphId)) {
1423        let font = FontRef::new(data).unwrap();
1424        let cff =
1425            CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap();
1426        let num_glyphs = font.maxp().unwrap().num_glyphs() as u32;
1427        assert!(num_glyphs > 1);
1428        for gid in (0..num_glyphs).map(GlyphId::new) {
1429            let index = cff.subfont_index(gid).unwrap_or(0);
1430            let subfont = cff.subfont(index, &[]).unwrap();
1431            check(&cff, &subfont, gid);
1432        }
1433    }
1434
1435    #[test]
1436    fn the_quick_width_is_what_a_full_run_reports() {
1437        let mut mapped = 0;
1438        for data in FONTS {
1439            let mut stated = 0;
1440            for_each_glyph(data, |cff, subfont, gid| {
1441                // `evaluate_charstring` answers in the charstring's own space
1442                // and `evaluate_width` in design units, so the matrix goes on
1443                // the full run before the two can be compared.
1444                let transform = cff.transform(subfont, None);
1445                let full = cff
1446                    .evaluate_charstring(subfont, gid, &[], &mut charstring::NullSink)
1447                    .unwrap();
1448                let quick = cff.evaluate_width(subfont, gid, &[]).unwrap();
1449                assert_eq!(
1450                    full.map(|width| transform.transform_h_metric(width)),
1451                    quick,
1452                    "glyph {gid}"
1453                );
1454                stated += full.is_some() as u32;
1455                if let (Some(full), Some(quick)) = (full, quick) {
1456                    mapped += (full != quick) as u32;
1457                }
1458            });
1459            // The comparison is worthless if nothing reported a width at all.
1460            assert!(stated > 0, "no glyph reported a width");
1461        }
1462        // And worthless again if the matrix never moved one, since then the
1463        // two spaces coincide and the comparison spans nothing.
1464        assert!(mapped > 0, "no width was moved by a matrix");
1465    }
1466
1467    #[test]
1468    fn the_quick_advance_is_what_drawing_reports() {
1469        // Drawing scales the width by the font matrix, and by ppem where one
1470        // is given, so this is what catches an advance that skipped either.
1471        for data in FONTS {
1472            for ppem in [None, Some(16.0), Some(72.0)] {
1473                for_each_glyph(data, |cff, subfont, gid| {
1474                    let drawn = cff.draw(subfont, gid, &[], ppem, &mut NullSink).unwrap();
1475                    let quick = cff.advance(subfont, gid, &[], ppem).unwrap();
1476                    assert_eq!(drawn, quick, "glyph {gid} at {ppem:?}");
1477                });
1478            }
1479        }
1480    }
1481}
1482
1483#[cfg(test)]
1484mod extents_tests {
1485    use super::*;
1486    use crate::{model::glyph::outline::PathSink, FontRef, TableProvider};
1487
1488    /// Has a sheared top level matrix over a scaled one, so where the box is
1489    /// measured is observable.
1490    const SHEARED: &[u8] = font_test_data::MATERIAL_ICONS_SUBSET_MATRIX;
1491
1492    #[derive(Default)]
1493    struct BoundsPen(Option<[f32; 4]>);
1494
1495    impl BoundsPen {
1496        fn add(&mut self, x: f32, y: f32) {
1497            self.0 = Some(match self.0 {
1498                Some([a, b, c, d]) => [a.min(x), b.min(y), c.max(x), d.max(y)],
1499                None => [x, y, x, y],
1500            });
1501        }
1502    }
1503
1504    impl PathSink for BoundsPen {
1505        fn move_to(&mut self, x: f32, y: f32) {
1506            self.add(x, y);
1507        }
1508        fn line_to(&mut self, x: f32, y: f32) {
1509            self.add(x, y);
1510        }
1511        fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
1512            self.add(cx, cy);
1513            self.add(x, y);
1514        }
1515        fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
1516            self.add(cx0, cy0);
1517            self.add(cx1, cy1);
1518            self.add(x, y);
1519        }
1520        fn close(&mut self) {}
1521    }
1522
1523    fn corners(b: BoundingBox<f32>) -> [f32; 4] {
1524        [b.x_min, b.y_min, b.x_max, b.y_max]
1525    }
1526
1527    fn cff_of(data: &[u8]) -> CffFontRef<'_> {
1528        let font = FontRef::new(data).unwrap();
1529        CffFontRef::new_cff(font.cff().unwrap().offset_data().as_bytes(), 0, None).unwrap()
1530    }
1531
1532    fn each_glyph(data: &[u8], mut f: impl FnMut(&CffFontRef, &Subfont, GlyphId)) {
1533        let cff = cff_of(data);
1534        for gid in (0..cff.num_glyphs()).map(GlyphId::new) {
1535            let index = cff.subfont_index(gid).unwrap_or(0);
1536            let subfont = cff.subfont(index, &[]).unwrap();
1537            f(&cff, &subfont, gid);
1538        }
1539    }
1540
1541    #[test]
1542    fn the_extents_are_the_box_drawing_stays_within() {
1543        for data in [
1544            font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
1545            font_test_data::ift::CFF_FONT,
1546            SHEARED,
1547        ] {
1548            for ppem in [None, Some(16.0)] {
1549                let mut drew = 0;
1550                each_glyph(data, |cff, subfont, gid| {
1551                    let mut pen = BoundsPen::default();
1552                    cff.draw(subfont, gid, &[], ppem, &mut pen).unwrap();
1553                    let measured = cff.extents(subfont, gid, &[], ppem).unwrap();
1554                    assert_eq!(measured.map(corners), pen.0, "glyph {gid} at {ppem:?}");
1555                    drew += pen.0.is_some() as u32;
1556                });
1557                assert!(drew > 0, "nothing drew, so this proves nothing");
1558            }
1559        }
1560    }
1561
1562    #[test]
1563    fn a_sheared_matrix_measures_smaller_than_a_box_turned_afterwards() {
1564        // Why the matrix is applied while measuring rather than to the
1565        // finished box: a shear tilts the drawing inside a box that has to
1566        // grow to hold the corners of a turned box.
1567        let mut tighter = 0;
1568        each_glyph(SHEARED, |cff, subfont, gid| {
1569            // The box before the matrix. No method answers with one, since
1570            // it cannot be brought through the matrix afterwards, which is
1571            // what this test is about; the sink gives it.
1572            let mut before = charstring::ControlBoundsSink::new();
1573            let mut filter = charstring::NopFilterSink::new(&mut before);
1574            cff.evaluate_charstring(subfont, gid, &[], &mut filter)
1575                .unwrap();
1576            let Some(plain) = before.bounding_box() else {
1577                return;
1578            };
1579            let mut turned = charstring::ControlBoundsSink::new();
1580            let transform = cff.transform(subfont, None);
1581            let mut sink = charstring::TransformSink::new(&mut turned, transform);
1582            for (x, y) in [
1583                (plain.x_min, plain.y_min),
1584                (plain.x_min, plain.y_max),
1585                (plain.x_max, plain.y_min),
1586                (plain.x_max, plain.y_max),
1587            ] {
1588                sink.move_to(x, y);
1589            }
1590            let turned = turned.bounding_box().unwrap();
1591            let measured = cff.extents(subfont, gid, &[], None).unwrap().unwrap();
1592            // Measuring during never reaches outside measuring after.
1593            assert!(measured.x_min >= turned.x_min.to_f32());
1594            assert!(measured.x_max <= turned.x_max.to_f32());
1595            if measured.x_min > turned.x_min.to_f32() || measured.x_max < turned.x_max.to_f32() {
1596                tighter += 1;
1597            }
1598        });
1599        assert!(
1600            tighter > 0,
1601            "no glyph measured tighter, so the shear went unnoticed"
1602        );
1603    }
1604
1605    #[test]
1606    fn a_location_moves_a_cff2_box_as_it_moves_the_drawing() {
1607        // Coordinates reach the box the way they reach the drawing, through
1608        // the blend the charstring runs with. Most glyphs here have no ink;
1609        // the count guards against a subset leaving none that move.
1610        let data = font_test_data::ift::CFF2_FONT;
1611        let font = FontRef::new(data).unwrap();
1612        let cff =
1613            CffFontRef::new_cff2(font.cff2().unwrap().offset_data().as_bytes(), None).unwrap();
1614        let axes = font.fvar().unwrap().axis_count() as usize;
1615        let mut at_default: Vec<Option<[f32; 4]>> = Vec::new();
1616        let mut moved = 0;
1617        for coord in [0.0f32, -1.0, 1.0] {
1618            let coords: Vec<_> = (0..axes).map(|_| F2Dot14::from_f32(coord)).collect();
1619            for (i, gid) in (0..cff.num_glyphs()).map(GlyphId::new).enumerate() {
1620                let index = cff.subfont_index(gid).unwrap_or(0);
1621                let subfont = cff.subfont(index, &coords).unwrap();
1622                let measured = cff
1623                    .extents(&subfont, gid, &coords, None)
1624                    .unwrap()
1625                    .map(corners);
1626                let mut pen = BoundsPen::default();
1627                cff.draw(&subfont, gid, &coords, None, &mut pen).unwrap();
1628                assert_eq!(measured, pen.0, "glyph {gid} at {coord}");
1629                if coord == 0.0 {
1630                    at_default.push(measured);
1631                } else if at_default[i] != measured {
1632                    moved += 1;
1633                }
1634            }
1635        }
1636        assert!(moved > 0, "no box moved, so the location went unread");
1637    }
1638}