Skip to main content

read_fonts/ps/
type1.rs

1//! Type1 fonts.
2
3use super::{
4    charmap::UnicodeCharmap,
5    charstring::{
6        self, CharstringContext, CharstringKind, CommandSink, NopFilterSink, TransformSink,
7    },
8    encoding::PredefinedEncoding,
9    transform::{self, FontMatrix, ScaledFontMatrix, Transform},
10};
11use crate::model::Error;
12use crate::{
13    model::glyph::outline::PathSink,
14    types::{BoundingBox, Fixed, GlyphId},
15};
16use alloc::{borrow::Cow, string::String, vec::Vec};
17use core::ops::Range;
18
19/// A Type1 font.
20pub struct Type1Font {
21    name: Option<String>,
22    full_name: Option<String>,
23    family_name: Option<String>,
24    weight: Option<String>,
25    version: Option<String>,
26    notice: Option<String>,
27    bbox: BoundingBox<Fixed>,
28    italic_angle: i32,
29    is_fixed_pitch: bool,
30    underline_position: i32,
31    underline_thickness: i32,
32    matrix: ScaledFontMatrix,
33    charstrings: Charstrings,
34    subrs: Subrs,
35    encoding: Option<RawEncoding>,
36    /// The default blend of a multiple master font, empty for any other.
37    weight_vector: Vec<Fixed>,
38    multiple_master: Option<MultipleMaster>,
39    /// The number of elements in the `BuildCharArray` that othersubrs
40    /// read and write.
41    build_char_len: usize,
42    unicode_charmap: UnicodeCharmap,
43}
44
45impl Type1Font {
46    /// Creates a new Type1 font from the given data.
47    pub fn new(data: &[u8]) -> Result<Self, Error> {
48        // any failure to parse is simply malformed data
49        Self::new_impl(data).ok_or(Error::Malformed)
50    }
51
52    fn new_impl(data: &[u8]) -> Option<Self> {
53        let raw_dicts = RawDicts::new(data)?;
54        Self::from_dicts(raw_dicts.base, &raw_dicts.private)
55    }
56
57    fn empty() -> Self {
58        Self {
59            name: None,
60            full_name: None,
61            family_name: None,
62            weight: None,
63            version: None,
64            notice: None,
65            italic_angle: 0,
66            is_fixed_pitch: false,
67            underline_position: 0,
68            underline_thickness: 0,
69            matrix: ScaledFontMatrix {
70                matrix: FontMatrix::IDENTITY,
71                scale: 1000,
72            },
73            bbox: BoundingBox::default(),
74            charstrings: Charstrings::default(),
75            subrs: Subrs::default(),
76            encoding: None,
77            weight_vector: Vec::new(),
78            multiple_master: None,
79            build_char_len: 0,
80            unicode_charmap: UnicodeCharmap::default(),
81        }
82    }
83
84    fn from_dicts(base: &[u8], private: &[u8]) -> Option<Self> {
85        let mut font = Self::empty();
86        // Read base dict entries
87        let mut encoding_offset = None;
88        let mut blend = RawBlend::default();
89        let mut parser = Parser::new(base);
90        while let Some(token) = parser.next() {
91            match token {
92                Token::Name(b"FontName") => font.name = parser.read_string(),
93                Token::Name(b"FullName") => font.full_name = parser.read_string(),
94                Token::Name(b"FamilyName") => font.family_name = parser.read_string(),
95                Token::Name(b"Weight") => {
96                    // The /Weight token can appear elsewhere in MM fonts so take
97                    // the first one
98                    if font.weight.is_none() {
99                        font.weight = parser.read_string();
100                    }
101                }
102                Token::Name(b"version") => font.version = parser.read_string(),
103                Token::Name(b"Notice") => font.notice = parser.read_string(),
104                // In the /Blend dictionary of a multiple master font these
105                // hold an array with a value for each master. FreeType keeps
106                // the font's own value then, so only a number replaces it.
107                Token::Name(b"ItalicAngle") => {
108                    if let Some(angle) = parser.read_num_as_int() {
109                        font.italic_angle = angle;
110                    }
111                }
112                Token::Name(b"isFixedPitch") => match parser.next() {
113                    Some(Token::Raw(b"[") | Token::Proc(_)) => {}
114                    token => font.is_fixed_pitch = token == Some(Token::Raw(b"true")),
115                },
116                Token::Name(b"UnderlinePosition") => {
117                    if let Some(position) = parser.read_num_as_int() {
118                        font.underline_position = position;
119                    }
120                }
121                Token::Name(b"UnderlineThickness") => {
122                    if let Some(thickness) = parser.read_num_as_int() {
123                        font.underline_thickness = thickness;
124                    }
125                }
126                Token::Name(b"FontBBox") => {
127                    if let Some([x_min, y_min, x_max, y_max]) = parser.read_font_bbox() {
128                        font.bbox = BoundingBox {
129                            x_min,
130                            y_min,
131                            x_max,
132                            y_max,
133                        };
134                    }
135                }
136                Token::Name(b"FontMatrix") => font.matrix = parser.read_font_matrix()?,
137                // Simply save the encoding offset. We'll parse it after
138                // we have read charstrings so we have an accurate mapping
139                // if we've synthesized or remapped a notdef glyph
140                Token::Name(b"Encoding") => encoding_offset = Some(parser.pos),
141                Token::Name(b"WeightVector") => {
142                    // Gated on a successful read because some fonts reference
143                    // the /WeightVector name outside of a proc, leading to
144                    // spurious field reads
145                    if let Some(weights) = parser.read_weight_vector() {
146                        blend.add_weights(weights)?;
147                    }
148                }
149                // The blend dictionaries are each read only where they hold
150                // an array, as FreeType reads them.
151                Token::Name(b"BlendAxisTypes") => {
152                    if let Some(names) = parser.read_blend_axis_types() {
153                        blend.add_axis_types(names)?;
154                    }
155                }
156                Token::Name(b"BlendDesignPositions") => {
157                    if let Some(positions) = parser.read_blend_design_positions() {
158                        blend.add_design_positions(positions)?;
159                    }
160                }
161                Token::Name(b"BlendDesignMap") => {
162                    if let Some(maps) = parser.read_blend_design_map() {
163                        blend.add_design_maps(maps)?;
164                    }
165                }
166                Token::Name(b"BuildCharArray") => {
167                    if let Some(len) = parser.read_array_len() {
168                        blend.build_char_len = len;
169                    }
170                }
171                _ => {}
172            }
173        }
174        if let Some((multiple_master, weights)) = blend.finish() {
175            font.multiple_master = Some(multiple_master);
176            font.weight_vector = weights;
177            font.build_char_len = blend.build_char_len;
178        }
179        // Read private dict entries
180        let mut parser = Parser::new(private);
181        // Default value if not present
182        let mut len_iv = 4;
183        while let Some(token) = parser.next() {
184            match token {
185                Token::Name(b"lenIV") => len_iv = parser.read_int()?,
186                Token::Name(b"Subrs") => {
187                    // With synthetic fonts, it's possible to read subroutines
188                    // twice. FreeType ignores the second copy.
189                    // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1855>
190                    if font.subrs.index.is_empty() {
191                        font.subrs = parser.read_subrs(len_iv)?;
192                    }
193                }
194                Token::Name(b"CharStrings") => {
195                    // Some non-standard fonts provide multiple copies of
196                    // outlines for different resolutions and FreeType only
197                    // retains the first copy, so skip parsing if we've
198                    // already read some charstrings.
199                    // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L2058>
200                    if font.charstrings.index.is_empty() {
201                        font.charstrings = parser.read_charstrings(len_iv)?;
202                    }
203                }
204                _ => {}
205            }
206        }
207        // Reject fonts that are missing a /CharStrings array
208        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L2665>
209        if font.charstrings.index.is_empty() {
210            return None;
211        }
212        if let Some(encoding_offset) = encoding_offset {
213            let mut parser = Parser::new(base.get(encoding_offset..)?);
214            font.encoding = Some(parser.read_encoding(&font.charstrings)?);
215        }
216        // We can only generate a Unicode cmap if we have the AGL available
217        #[cfg(feature = "agl")]
218        {
219            font.unicode_charmap = UnicodeCharmap::from_glyph_names(font.glyph_names());
220        }
221        Some(font)
222    }
223
224    /// Returns the PostScript name.
225    pub fn name(&self) -> Option<&str> {
226        self.name.as_deref()
227    }
228
229    /// Returns the full font name.
230    pub fn full_name(&self) -> Option<&str> {
231        self.full_name.as_deref()
232    }
233
234    /// Returns the font family name.
235    pub fn family_name(&self) -> Option<&str> {
236        self.family_name.as_deref()
237    }
238
239    /// Returns the weight or style name.
240    pub fn weight(&self) -> Option<&str> {
241        self.weight.as_deref()
242    }
243
244    /// Returns the font version string.
245    pub fn version(&self) -> Option<&str> {
246        self.version.as_deref()
247    }
248
249    /// Returns the font's copyright or trademark notice.
250    pub fn notice(&self) -> Option<&str> {
251        self.notice.as_deref()
252    }
253
254    /// Returns the italic angle.
255    pub fn italic_angle(&self) -> i32 {
256        self.italic_angle
257    }
258
259    /// Returns true if the glyphs in this font have the same width.
260    pub fn is_fixed_pitch(&self) -> bool {
261        self.is_fixed_pitch
262    }
263
264    /// Returns the position of the center of an underline decoration.
265    pub fn underline_position(&self) -> i32 {
266        self.underline_position
267    }
268
269    /// Returns the suggested size for an underline decoration.
270    pub fn underline_thickness(&self) -> i32 {
271        self.underline_thickness
272    }
273
274    /// Returns the font bounding box.
275    pub fn bbox(&self) -> BoundingBox<Fixed> {
276        self.bbox
277    }
278
279    /// Returns the number of glyphs in the Type1 font.
280    pub fn num_glyphs(&self) -> u32 {
281        self.charstrings.num_glyphs()
282    }
283
284    /// Returns the units per em.
285    pub fn upem(&self) -> i32 {
286        self.matrix.scale
287    }
288
289    /// Returns the top level font matrix.
290    pub fn matrix(&self) -> FontMatrix {
291        self.matrix.matrix
292    }
293
294    /// Returns the appropriate transform for adjusting points and metrics.
295    pub fn transform(&self, ppem: Option<f32>) -> Transform {
296        let scale = ppem.map(|ppem| Transform::compute_scale(ppem, self.upem()));
297        Transform {
298            matrix: self.matrix(),
299            scale,
300        }
301    }
302
303    /// Returns the character encoding.
304    pub fn encoding(&self) -> Option<Encoding<'_>> {
305        self.encoding.as_ref().map(|enc| Encoding {
306            encoding: enc,
307            charstrings: &self.charstrings,
308        })
309    }
310
311    /// Returns the Unicode charmap for this font.
312    ///
313    /// Note that this is an empty mapping if the `agl` feature is not enabled.
314    pub fn unicode_charmap(&self) -> &UnicodeCharmap {
315        &self.unicode_charmap
316    }
317
318    /// Returns the glyph name for the given id.
319    pub fn glyph_name(&self, gid: GlyphId) -> Option<&str> {
320        self.charstrings.name(gid.to_u32())
321    }
322
323    /// Returns an iterator over the pairs of glyph ids and associated names in
324    /// the Type1 font.
325    pub fn glyph_names(&self) -> impl Iterator<Item = (GlyphId, &str)> {
326        (0..self.num_glyphs())
327            .filter_map(|idx| Some((GlyphId::new(idx), self.charstrings.name(idx)?)))
328    }
329
330    /// Given a glyph identifier in the original glyph order, returns the
331    /// possibly remapped identifier.
332    ///
333    /// This occurs if we remap or synthesize a `.notdef` glyph.
334    pub fn remapped_gid(&self, original_gid: GlyphId) -> GlyphId {
335        if let Some(orig_notdef) = self.charstrings.orig_notdef_index {
336            if original_gid == GlyphId::NOTDEF {
337                GlyphId::new(orig_notdef as u32)
338            } else if orig_notdef == original_gid.to_u32() as usize {
339                GlyphId::NOTDEF
340            } else {
341                original_gid
342            }
343        } else {
344            original_gid
345        }
346    }
347
348    /// Returns the design space of a multiple master font.
349    ///
350    /// `None` for a font with no masters, or with blend dictionaries that
351    /// do not agree.
352    pub fn multiple_master(&self) -> Option<&MultipleMaster> {
353        self.multiple_master.as_ref()
354    }
355
356    /// Returns the font drawn with the blend that `weights` give, one per
357    /// master.
358    ///
359    /// [`MultipleMaster::blend_to_weights`] computes the weights for a
360    /// position in the blend space.
361    pub fn instance<'a>(&'a self, weights: &'a [Fixed]) -> Type1Instance<'a> {
362        Type1Instance {
363            font: self,
364            weights,
365        }
366    }
367
368    /// Returns the font drawn with its own default blend.
369    pub fn default_instance(&self) -> Type1Instance<'_> {
370        self.instance(&self.weight_vector)
371    }
372
373    /// Evaluates the charstring for the requested glyph far enough to read
374    /// its advance width, without drawing it.
375    ///
376    /// A Type 1 charstring states its width in the `hsbw` or `sbw` that must
377    /// open it, so evaluation stops there.
378    ///
379    /// The font matrix is applied and no size is, so the width is exact and
380    /// in the units the rest of the font is measured in.
381    /// [`advance`](Self::advance) applies a size as well and reports what
382    /// [`draw`](Self::draw) does.
383    ///
384    /// Unlike [`evaluate_charstring`], the matrix is applied here rather than
385    /// left to a caller. That one withholds it so a hinter can be slotted in
386    /// ahead of it; nothing hints a width.
387    ///
388    /// [`evaluate_charstring`]: Self::evaluate_charstring
389    pub fn evaluate_width(&self, gid: GlyphId) -> Result<Option<Fixed>, Error> {
390        self.default_instance().evaluate_width(gid)
391    }
392
393    /// Evaluates the charstring for the requested glyph and sends the results
394    /// to the given sink.
395    ///
396    /// Returns the width the charstring states, in the charstring's own
397    /// space: neither the font matrix nor a size is applied, to the width or
398    /// to the commands. [`draw`](Self::draw) applies both.
399    pub fn evaluate_charstring(
400        &self,
401        gid: GlyphId,
402        sink: &mut impl CommandSink,
403    ) -> Result<Option<Fixed>, Error> {
404        self.default_instance().evaluate_charstring(gid, sink)
405    }
406
407    /// Returns the advance width of the glyph with an optional size in
408    /// ppem, without drawing it.
409    ///
410    /// This is the width [`draw`](Self::draw) reports, arrived at without
411    /// the drawing.
412    pub fn advance(&self, gid: GlyphId, ppem: Option<f32>) -> Result<Option<f32>, Error> {
413        self.default_instance().advance(gid, ppem)
414    }
415
416    /// Measures the box the glyph's drawing stays within, in design units.
417    ///
418    /// A control box: a curve counts through its control points rather than
419    /// the path they describe, so one bulging inside its hull measures larger
420    /// than it draws. HarfBuzz reports a charstring's extents the same way.
421    ///
422    /// The font matrix is applied and no size is, so the box is exact and in
423    /// the units the rest of the font is measured in.
424    /// [`extents`](Self::extents) applies a size as well and answers in what
425    /// a caller laying out text works in.
426    ///
427    /// Unlike [`evaluate_charstring`], the matrix is applied here rather than
428    /// left to a caller. That one withholds it so a hinter can be slotted in
429    /// before it; nothing hints a box, and a box cannot be brought through a
430    /// matrix afterwards anyway, because turning a box turns its corners and
431    /// a matrix that shears tilts the drawing inside a box that has to grow
432    /// to hold them.
433    ///
434    /// `None` where the glyph draws nothing.
435    ///
436    /// [`evaluate_charstring`]: Self::evaluate_charstring
437    pub fn evaluate_extents(&self, gid: GlyphId) -> Result<Option<BoundingBox<Fixed>>, Error> {
438        self.default_instance().evaluate_extents(gid)
439    }
440
441    /// Returns the box the glyph's drawing stays within, with an optional
442    /// size in ppem.
443    ///
444    /// The box [`draw`](Self::draw) would stay within, measured as
445    /// [`evaluate_extents`](Self::evaluate_extents) measures it and scaled by
446    /// the size as well.
447    ///
448    /// A size can be applied to a finished box, being one scale in both
449    /// directions; it is applied here so the answer matches `draw` at that
450    /// size without a caller doing the arithmetic. The matrix cannot, which
451    /// is why neither of these leaves it out.
452    ///
453    /// `None` where the glyph draws nothing.
454    pub fn extents(
455        &self,
456        gid: GlyphId,
457        ppem: Option<f32>,
458    ) -> Result<Option<BoundingBox<f32>>, Error> {
459        self.default_instance().extents(gid, ppem)
460    }
461
462    /// Draws the glyph with an optional size in ppem to the given pen.
463    ///
464    /// Returns the advance width of the glyph if the charstring provides
465    /// one.
466    pub fn draw(
467        &self,
468        gid: GlyphId,
469        ppem: Option<f32>,
470        sink: &mut impl PathSink,
471    ) -> Result<Option<f32>, Error> {
472        self.default_instance().draw(gid, ppem, sink)
473    }
474}
475
476impl<'a> Type1Instance<'a> {
477    /// Returns the font.
478    pub fn font(&self) -> &'a Type1Font {
479        self.font
480    }
481
482    /// Returns the weight of each master.
483    pub fn weights(&self) -> &'a [Fixed] {
484        self.weights
485    }
486
487    /// As [`Type1Font::evaluate_width`], with this instance's blend.
488    pub fn evaluate_width(&self, gid: GlyphId) -> Result<Option<Fixed>, Error> {
489        let charstring_data = self
490            .font
491            .charstrings
492            .get(gid.to_u32())
493            .ok_or(Error::Malformed)?;
494        let transform = self.font.transform(None);
495        Ok(charstring::evaluate_width(self, None, charstring_data)?
496            .map(|width| transform.transform_h_metric(width)))
497    }
498
499    /// As [`Type1Font::evaluate_charstring`], with this instance's blend.
500    pub fn evaluate_charstring(
501        &self,
502        gid: GlyphId,
503        sink: &mut impl CommandSink,
504    ) -> Result<Option<Fixed>, Error> {
505        let charstring_data = self
506            .font
507            .charstrings
508            .get(gid.to_u32())
509            .ok_or(Error::Malformed)?;
510        charstring::evaluate(self, None, charstring_data, sink)
511    }
512
513    /// As [`Type1Font::advance`], with this instance's blend.
514    pub fn advance(&self, gid: GlyphId, ppem: Option<f32>) -> Result<Option<f32>, Error> {
515        let charstring_data = self
516            .font
517            .charstrings
518            .get(gid.to_u32())
519            .ok_or(Error::Malformed)?;
520        let transform = self.font.transform(ppem);
521        Ok(charstring::evaluate_width(self, None, charstring_data)?
522            .map(|width| transform.transform_h_metric(width).to_f32().max(0.0)))
523    }
524
525    /// As [`Type1Font::evaluate_extents`], with this instance's blend.
526    pub fn evaluate_extents(&self, gid: GlyphId) -> Result<Option<BoundingBox<Fixed>>, Error> {
527        let mut bounds = charstring::ControlBoundsSink::new();
528        let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
529        let transform = self.font.transform(None);
530        let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
531        self.evaluate_charstring(gid, &mut transformer)?;
532        Ok(bounds.bounding_box())
533    }
534
535    /// As [`Type1Font::extents`], with this instance's blend.
536    pub fn extents(
537        &self,
538        gid: GlyphId,
539        ppem: Option<f32>,
540    ) -> Result<Option<BoundingBox<f32>>, Error> {
541        let mut bounds = charstring::ControlBoundsSink::new();
542        let mut nop_filter = charstring::NopFilterSink::new(&mut bounds);
543        let transform = self.font.transform(ppem);
544        let mut transformer = charstring::TransformSink::new(&mut nop_filter, transform);
545        self.evaluate_charstring(gid, &mut transformer)?;
546        Ok(bounds.bounding_box().map(|b| BoundingBox {
547            x_min: b.x_min.to_f32(),
548            y_min: b.y_min.to_f32(),
549            x_max: b.x_max.to_f32(),
550            y_max: b.y_max.to_f32(),
551        }))
552    }
553
554    /// As [`Type1Font::draw`], with this instance's blend.
555    pub fn draw(
556        &self,
557        gid: GlyphId,
558        ppem: Option<f32>,
559        sink: &mut impl PathSink,
560    ) -> Result<Option<f32>, Error> {
561        let mut nop_filter = NopFilterSink::new(sink);
562        let transform = self.font.transform(ppem);
563        let mut transformer = TransformSink::new(&mut nop_filter, transform);
564        let width = self.evaluate_charstring(gid, &mut transformer)?;
565        Ok(width.map(|w| transform.transform_h_metric(w).to_f32().max(0.0)))
566    }
567}
568
569impl CharstringContext for Type1Font {
570    fn kind(&self) -> CharstringKind {
571        CharstringKind::Type1
572    }
573
574    fn seac_components(&self, base_code: i32, accent_code: i32) -> Result<[&[u8]; 2], Error> {
575        let decode = |code: i32| {
576            let name = PredefinedEncoding::Standard
577                .name(code.try_into().map_err(|_| Error::InvalidOperation)?);
578            self.charstrings
579                .index_for_name(name)
580                .and_then(|idx| self.charstrings.get(idx))
581                .ok_or(Error::InvalidOperation)
582        };
583        let base = decode(base_code)?;
584        let accent = decode(accent_code)?;
585        Ok([base, accent])
586    }
587
588    fn subr(&self, index: i32) -> Result<&[u8], Error> {
589        self.subrs.get(index as u32).ok_or(Error::Malformed)
590    }
591
592    fn global_subr(&self, _index: i32) -> Result<&[u8], Error> {
593        // Type1 fonts don't have global subroutines
594        Err(Error::MissingResource)
595    }
596
597    fn weight_vector(&self) -> &[Fixed] {
598        &self.weight_vector
599    }
600
601    fn build_char_len(&self) -> usize {
602        self.build_char_len
603    }
604}
605
606impl CharstringContext for Type1Instance<'_> {
607    fn kind(&self) -> CharstringKind {
608        CharstringKind::Type1
609    }
610
611    fn seac_components(&self, base_code: i32, accent_code: i32) -> Result<[&[u8]; 2], Error> {
612        self.font.seac_components(base_code, accent_code)
613    }
614
615    fn subr(&self, index: i32) -> Result<&[u8], Error> {
616        self.font.subr(index)
617    }
618
619    fn global_subr(&self, index: i32) -> Result<&[u8], Error> {
620        self.font.global_subr(index)
621    }
622
623    fn weight_vector(&self) -> &[Fixed] {
624        self.weights
625    }
626
627    fn build_char_len(&self) -> usize {
628        self.font.build_char_len
629    }
630}
631
632/// The most axes a multiple master font can have.
633const MAX_MASTER_AXES: usize = 4;
634
635/// The most masters a multiple master font can have.
636const MAX_MASTERS: usize = 16;
637
638/// The most points in the design map of one axis.
639const MAX_MAP_POINTS: usize = 20;
640
641/// The blend dictionaries of a font as they are read, before they are
642/// checked against each other.
643///
644/// Each `add` fails where FreeType refuses the whole font: a count out of
645/// range, a count that disagrees with one already read, or a second design
646/// map. A later axis type or position list replaces an earlier one, as in
647/// FreeType.
648///
649/// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L764>
650#[derive(Default)]
651struct RawBlend {
652    num_axes: usize,
653    num_masters: usize,
654    axis_names: Vec<String>,
655    positions: bool,
656    maps: Vec<Vec<(i32, Fixed)>>,
657    weights: Vec<Fixed>,
658    build_char_len: usize,
659}
660
661impl RawBlend {
662    fn set_num_axes(&mut self, num_axes: usize) -> Option<()> {
663        if num_axes == 0 || num_axes > MAX_MASTER_AXES {
664            return None;
665        }
666        if self.num_axes != 0 && self.num_axes != num_axes {
667            return None;
668        }
669        self.num_axes = num_axes;
670        Some(())
671    }
672
673    fn set_num_masters(&mut self, num_masters: usize) -> Option<()> {
674        if num_masters == 0 || num_masters > MAX_MASTERS {
675            return None;
676        }
677        if self.num_masters != 0 && self.num_masters != num_masters {
678            return None;
679        }
680        self.num_masters = num_masters;
681        Some(())
682    }
683
684    fn add_axis_types(&mut self, names: Vec<String>) -> Option<()> {
685        self.set_num_axes(names.len())?;
686        self.axis_names = names;
687        Some(())
688    }
689
690    fn add_design_positions(&mut self, positions: Vec<Vec<Fixed>>) -> Option<()> {
691        self.set_num_masters(positions.len())?;
692        let num_axes = positions.first()?.len();
693        if positions.iter().any(|position| position.len() != num_axes) {
694            return None;
695        }
696        self.set_num_axes(num_axes)?;
697        // Only their presence matters: a font's masters sit at the corners
698        // of the blend space, which the weights are computed for.
699        self.positions = true;
700        Some(())
701    }
702
703    fn add_design_maps(&mut self, maps: Vec<Vec<(i32, Fixed)>>) -> Option<()> {
704        if !self.maps.is_empty() {
705            return None;
706        }
707        self.set_num_axes(maps.len())?;
708        if maps
709            .iter()
710            .any(|map| map.is_empty() || map.len() > MAX_MAP_POINTS)
711        {
712            return None;
713        }
714        self.maps = maps;
715        Some(())
716    }
717
718    fn add_weights(&mut self, weights: Vec<Fixed>) -> Option<()> {
719        self.set_num_masters(weights.len())?;
720        self.weights = weights;
721        Some(())
722    }
723
724    /// Returns the design space and the default weights, or `None` where
725    /// FreeType sets the blend aside and treats the font as an ordinary one.
726    ///
727    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L2567>
728    fn finish(&self) -> Option<(MultipleMaster, Vec<Fixed>)> {
729        // Only masters at the corners of the blend space are supported.
730        if self.num_axes == 0 || self.num_masters != 1 << self.num_axes {
731            return None;
732        }
733        if self.weights.is_empty() || !self.positions || self.maps.len() != self.num_axes {
734            return None;
735        }
736        let axes = self
737            .maps
738            .iter()
739            .enumerate()
740            .map(|(index, map)| MasterAxis {
741                name: self.axis_names.get(index).cloned(),
742                design_points: map.iter().map(|point| point.0).collect(),
743                blend_points: map.iter().map(|point| point.1).collect(),
744            })
745            .collect();
746        let multiple_master = MultipleMaster {
747            axes,
748            num_masters: self.num_masters,
749            default_weights: self.weights.clone(),
750        };
751        Some((multiple_master, self.weights.clone()))
752    }
753}
754
755/// The design space of a multiple master font.
756///
757/// A multiple master font holds two to sixteen masters at the corners of a
758/// blend space with one to four axes. An instance is a weighted blend of
759/// the masters, and its weights come from a position in that space, given
760/// as blend coordinates from 0 to 1 on each axis or as design coordinates,
761/// which each axis maps to blend coordinates.
762///
763/// The conversions follow FreeType's, including where its arithmetic
764/// departs from the specification, so that an instance draws as it does
765/// in FreeType.
766#[derive(Clone, Debug)]
767pub struct MultipleMaster {
768    axes: Vec<MasterAxis>,
769    num_masters: usize,
770    default_weights: Vec<Fixed>,
771}
772
773/// One axis of a multiple master font.
774#[derive(Clone, Debug)]
775pub struct MasterAxis {
776    name: Option<String>,
777    design_points: Vec<i32>,
778    blend_points: Vec<Fixed>,
779}
780
781impl MasterAxis {
782    /// Returns the name the font gives the axis, such as `Weight`.
783    pub fn name(&self) -> Option<&str> {
784        self.name.as_deref()
785    }
786
787    /// Returns the lowest design coordinate.
788    pub fn min_design(&self) -> i32 {
789        self.design_points.first().copied().unwrap_or_default()
790    }
791
792    /// Returns the highest design coordinate.
793    pub fn max_design(&self) -> i32 {
794        self.design_points.last().copied().unwrap_or_default()
795    }
796
797    /// Returns the map from design coordinates to blend coordinates, as
798    /// pairs in the font's order.
799    pub fn design_map(&self) -> impl Iterator<Item = (i32, Fixed)> + '_ {
800        self.design_points
801            .iter()
802            .copied()
803            .zip(self.blend_points.iter().copied())
804    }
805
806    /// Returns the blend coordinate for a design coordinate.
807    ///
808    /// This follows FreeType's `T1_Set_MM_Design`, which interpolates
809    /// between two points as though the first mapped to a blend of zero.
810    /// The result is exact for a map whose interpolated points start at
811    /// zero, as two point maps do.
812    ///
813    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L555>
814    pub fn design_to_blend(&self, design: i32) -> Fixed {
815        let designs = &self.design_points;
816        let blends = &self.blend_points;
817        let mut before = None;
818        let mut after = None;
819        for (p, &p_design) in designs.iter().enumerate() {
820            if design == p_design {
821                return blends[p];
822            }
823            if design < p_design {
824                after = Some(p);
825                break;
826            }
827            before = Some(p);
828        }
829        match (before, after) {
830            (None, _) => blends.first().copied().unwrap_or_default(),
831            (Some(_), None) => blends.last().copied().unwrap_or_default(),
832            (Some(before), Some(after)) => {
833                // FreeType leaves out `+ blends[before]`.
834                Fixed::from_bits(saturate(mul_div_wide(
835                    i64::from(design) - i64::from(designs[before]),
836                    i64::from(blends[after].to_bits()) - i64::from(blends[before].to_bits()),
837                    i64::from(designs[after]) - i64::from(designs[before]),
838                )))
839            }
840        }
841    }
842
843    /// Returns the design coordinate for a blend coordinate, a whole number.
844    ///
845    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L218>
846    pub fn blend_to_design(&self, blend: Fixed) -> i32 {
847        let designs = &self.design_points;
848        let blends = &self.blend_points;
849        if designs.is_empty() || blend <= blends[0] {
850            return self.min_design();
851        }
852        for j in 1..designs.len() {
853            if blend <= blends[j] {
854                let offset = mul_div_wide(
855                    i64::from(blend.to_bits()) - i64::from(blends[j - 1].to_bits()),
856                    i64::from(designs[j]) - i64::from(designs[j - 1]),
857                    i64::from(blends[j].to_bits()) - i64::from(blends[j - 1].to_bits()),
858                );
859                return saturate(i64::from(designs[j - 1]) + offset);
860            }
861        }
862        self.max_design()
863    }
864}
865
866/// Returns `a * b / c`, rounded as [`Fixed::mul_div`] rounds, without
867/// overflowing on the way.
868///
869/// Design maps hold any `i32`, so the differences between their points
870/// don't fit in one.
871fn mul_div_wide(a: i64, b: i64, c: i64) -> i64 {
872    let (a_abs, b_abs, c_abs) = (
873        u128::from(a.unsigned_abs()),
874        u128::from(b.unsigned_abs()),
875        u128::from(c.unsigned_abs()),
876    );
877    let result = if c_abs > 0 {
878        (a_abs * b_abs + (c_abs >> 1)) / c_abs
879    } else {
880        0x7FFFFFFF
881    };
882    let result = result.min(i64::MAX as u128) as i64;
883    if (a < 0) ^ (b < 0) ^ (c < 0) {
884        -result
885    } else {
886        result
887    }
888}
889
890/// Clamps `value` to the range of an `i32`.
891fn saturate(value: i64) -> i32 {
892    value.clamp(i32::MIN.into(), i32::MAX.into()) as i32
893}
894
895impl MultipleMaster {
896    /// Returns the axes.
897    pub fn axes(&self) -> &[MasterAxis] {
898        &self.axes
899    }
900
901    /// Returns the number of masters, which is two to the power of the
902    /// number of axes.
903    pub fn num_masters(&self) -> usize {
904        self.num_masters
905    }
906
907    /// Returns the weights of the font's default instance, one per master.
908    pub fn default_weights(&self) -> &[Fixed] {
909        &self.default_weights
910    }
911
912    /// Writes the blend coordinates of the font's default instance to
913    /// `blend`, one per axis.
914    ///
915    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L248>
916    pub fn default_blend(&self, blend: &mut [Fixed]) {
917        self.weights_to_blend(&self.default_weights, blend);
918    }
919
920    /// Writes the blend coordinates that give rise to `weights` to `blend`,
921    /// one per axis.
922    ///
923    /// The blend on an axis is the sum of the weights of the masters at its
924    /// far end.
925    pub fn weights_to_blend(&self, weights: &[Fixed], blend: &mut [Fixed]) {
926        for (axis, value) in blend.iter_mut().enumerate().take(self.axes.len()) {
927            *value = Fixed::from_bits(
928                (0..self.num_masters)
929                    .filter(|master| master & (1 << axis) != 0)
930                    .filter_map(|master| weights.get(master))
931                    .fold(0i32, |sum, weight| sum.wrapping_add(weight.to_bits())),
932            );
933        }
934    }
935
936    /// Writes the weights for the blend coordinates `blend` to `weights`, one
937    /// per master.
938    ///
939    /// An axis without a coordinate takes the middle of its range.
940    ///
941    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L383>
942    pub fn blend_to_weights(&self, blend: &[Fixed], weights: &mut [Fixed]) {
943        for (master, weight) in weights.iter_mut().enumerate().take(self.num_masters) {
944            let mut result = Fixed::ONE;
945            for axis in 0..self.axes.len() {
946                let Some(&coord) = blend.get(axis) else {
947                    result = Fixed::from_bits(result.to_bits() >> 1);
948                    continue;
949                };
950                let factor = if master & (1 << axis) == 0 {
951                    Fixed::ONE - coord
952                } else {
953                    coord
954                };
955                if factor <= Fixed::ZERO {
956                    result = Fixed::ZERO;
957                    break;
958                } else if factor >= Fixed::ONE {
959                    continue;
960                }
961                result *= factor;
962            }
963            *weight = result;
964        }
965    }
966
967    /// Writes the blend coordinates for the design coordinates `design` to
968    /// `blend`, one per axis.
969    ///
970    /// Each design coordinate is rounded to a whole number first. An axis
971    /// without a coordinate takes half its range above zero, `(max - min) /
972    /// 2`, which is the middle only of a range that starts at zero. Both
973    /// follow FreeType's `T1_Set_Var_Design`, as does
974    /// [`MasterAxis::design_to_blend`].
975    ///
976    /// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L653>
977    pub fn design_to_blend(&self, design: &[Fixed], blend: &mut [Fixed]) {
978        for (index, (axis, value)) in self.axes.iter().zip(blend.iter_mut()).enumerate() {
979            let design = match design.get(index) {
980                // FreeType's `FIXED_TO_INT`, which rounds a half away from
981                // zero.
982                Some(design) => {
983                    let bits = design.to_bits();
984                    bits.wrapping_add(0x8000 - i32::from(bits < 0)) >> 16
985                }
986                None => saturate((i64::from(axis.max_design()) - i64::from(axis.min_design())) / 2),
987            };
988            *value = axis.design_to_blend(design);
989        }
990    }
991}
992
993/// A Type 1 font drawn with a given blend of its masters.
994///
995/// For a multiple master font, the weights give the blend, one per master.
996/// [`MultipleMaster::blend_to_weights`] computes them for a position in the
997/// blend space. A font with no masters takes empty weights.
998#[derive(Clone, Copy)]
999pub struct Type1Instance<'a> {
1000    font: &'a Type1Font,
1001    weights: &'a [Fixed],
1002}
1003
1004/// Associates character codes with glyph names and ids.
1005#[derive(Clone)]
1006pub struct Encoding<'a> {
1007    encoding: &'a RawEncoding,
1008    charstrings: &'a Charstrings,
1009}
1010
1011impl<'a> Encoding<'a> {
1012    /// Returns the predefined encoding, if any.
1013    pub fn predefined(&self) -> Option<PredefinedEncoding> {
1014        if let RawEncoding::Predefined(pre) = self.encoding {
1015            Some(*pre)
1016        } else {
1017            None
1018        }
1019    }
1020
1021    /// Returns the glyph name for the given character code.
1022    pub fn glyph_name(&self, code: u8) -> Option<&'a str> {
1023        match self.encoding {
1024            RawEncoding::Predefined(pre) => Some(pre.name(code)),
1025            RawEncoding::Custom(custom) => {
1026                self.charstrings.name(custom.get(code as usize)?.to_u32())
1027            }
1028        }
1029    }
1030
1031    /// Maps a character code to a glyph identifier.
1032    pub fn map(&self, code: u8) -> Option<GlyphId> {
1033        match self.encoding {
1034            RawEncoding::Predefined(pre) => self
1035                .charstrings
1036                .index_for_name(pre.name(code))
1037                .map(GlyphId::new),
1038            RawEncoding::Custom(custom) => custom.get(code as usize).copied(),
1039        }
1040    }
1041}
1042
1043/// Raw dictionary data for a Type1 font.
1044struct RawDicts<'a> {
1045    /// Data containing the base dicitionary.
1046    base: &'a [u8],
1047    /// Data containing the decrypted private dictionary.
1048    private: Vec<u8>,
1049}
1050
1051impl<'a> RawDicts<'a> {
1052    fn new(data: &'a [u8]) -> Option<Self> {
1053        if let Some((PFB_TEXT_SEGMENT_TAG, base_size)) = decode_pfb_tag(data, 0) {
1054            // We have a PFB; skip the tag
1055            let data = data.get(6..)?;
1056            verify_header(data)?;
1057            let (base_dict, raw_private_dict) = data.split_at_checked(base_size as usize)?;
1058            // Decrypt private dict segments
1059            let private_dict = decrypt(
1060                decode_pfb_binary_segments(raw_private_dict)
1061                    .flat_map(|segment| segment.iter().copied()),
1062                EEXEC_SEED,
1063            )
1064            // First four bytes are random garbage
1065            .skip(4)
1066            .collect::<Vec<_>>();
1067            Some(Self {
1068                base: base_dict,
1069                private: private_dict,
1070            })
1071        } else {
1072            // We have a PFA
1073            verify_header(data)?;
1074            // Now find the start of the private dictionary
1075            let start = find_eexec_data(data)?;
1076            let (base_dict, raw_private_dict) = data.split_at_checked(start)?;
1077            let private_dict = if raw_private_dict.len() > 3
1078                && raw_private_dict[..4].iter().all(|b| b.is_ascii_hexdigit())
1079            {
1080                // Hex decode and then decrypt
1081                decrypt(decode_hex(raw_private_dict.iter().copied()), EEXEC_SEED)
1082                    .skip(4)
1083                    .collect::<Vec<_>>()
1084            } else {
1085                // Just decrypt
1086                decrypt(raw_private_dict.iter().copied(), EEXEC_SEED)
1087                    .skip(4)
1088                    .collect::<Vec<_>>()
1089            };
1090            Some(Self {
1091                base: base_dict,
1092                private: private_dict,
1093            })
1094        }
1095    }
1096}
1097
1098fn verify_header(data: &[u8]) -> Option<()> {
1099    (data.starts_with(b"%!PS-AdobeFont") || data.starts_with(b"%!FontType")).then_some(())
1100}
1101
1102const PFB_TEXT_SEGMENT_TAG: u16 = 0x8001;
1103const PFB_BINARY_SEGMENT_TAG: u16 = 0x8002;
1104
1105/// Returns the PFB tag and segment size.
1106///
1107/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1parse.c#L69>
1108fn decode_pfb_tag(data: &[u8], start: usize) -> Option<(u16, u32)> {
1109    let header: [u8; 6] = data.get(start..start + 6)?.try_into().ok()?;
1110    let tag = ((header[0] as u16) << 8) | header[1] as u16;
1111    if matches!(tag, PFB_BINARY_SEGMENT_TAG | PFB_TEXT_SEGMENT_TAG) {
1112        let size = u32::from_le_bytes(header[2..].try_into().unwrap());
1113        Some((tag, size))
1114    } else {
1115        None
1116    }
1117}
1118
1119/// Returns an iterator over the sequence of PFB binary segments.
1120fn decode_pfb_binary_segments(data: &[u8]) -> impl Iterator<Item = &[u8]> + '_ {
1121    let mut pos = 0usize;
1122    core::iter::from_fn(move || {
1123        let (tag, len) = decode_pfb_tag(data, pos)?;
1124        // FT only decodes the sequence of binary segments here
1125        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1parse.c#L286>
1126        if tag != PFB_BINARY_SEGMENT_TAG {
1127            return None;
1128        }
1129        // Skip tag and size bytes
1130        let start = pos + 6;
1131        let end = start + len as usize;
1132        let segment = data.get(start..end)?;
1133        pos = end;
1134        Some(segment)
1135    })
1136}
1137
1138/// Helper to find the position of the data following the 'eexec' token.
1139///
1140/// Unsurprisingly, more complicated than it should be.
1141fn find_eexec_data(data: &[u8]) -> Option<usize> {
1142    // Use a parser to avoid catching "eexec" in a comment or string
1143    // which apparently occurs in some fonts.
1144    let mut parser = Parser::new(data);
1145    while let Some(token) = parser.next() {
1146        if token != Token::Raw(b"eexec") {
1147            continue;
1148        }
1149        let mut start = parser.pos;
1150        // FreeType has some unfun logic for skipping whitespace
1151        // after the eexec token
1152        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1parse.c#L382>
1153        let mut linefeed_pos = None;
1154        while start < data.len() {
1155            match data[start] {
1156                b' ' | b'\t' => {}
1157                b'\n' => linefeed_pos = Some(start),
1158                b'\r' => {
1159                    // If we've already seen \n or there is not a \n later
1160                    // in the data, then stop at this \r
1161                    if *linefeed_pos.get_or_insert_with(|| {
1162                        data[start..]
1163                            .iter()
1164                            .position(|b| *b == b'\n')
1165                            .map(|pos| pos + start)
1166                            .unwrap_or(0)
1167                    }) < start
1168                    {
1169                        break;
1170                    }
1171                }
1172                _ => break,
1173            }
1174            start += 1;
1175        }
1176        if start == data.len() {
1177            // eexec not properly terminated
1178            return None;
1179        }
1180        return Some(start);
1181    }
1182    None
1183}
1184
1185/// Converts hex formatted data to associated bytes.
1186///
1187/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psconv.c#L464>
1188fn decode_hex(mut bytes: impl Iterator<Item = u8>) -> impl Iterator<Item = u8> {
1189    /// Converts digits (as ASCII characters) into integer values.
1190    const DIGIT_TO_NUM: [i8; 128] = [
1191        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1192        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1193        -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15,
1194        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1,
1195        -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
1196        30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
1197    ];
1198    let mut pad = 0x1_u32;
1199    core::iter::from_fn(move || {
1200        loop {
1201            let Some(c) = bytes.next() else {
1202                break;
1203            };
1204            if is_whitespace(c) {
1205                continue;
1206            }
1207            if c >= 0x80 {
1208                break;
1209            }
1210            let c = DIGIT_TO_NUM[(c & 0x7F) as usize] as u32;
1211            if c >= 16 {
1212                break;
1213            }
1214            pad = (pad << 4) | c;
1215            if pad & 0x100 != 0 {
1216                let res = pad as u8;
1217                pad = 0x1;
1218                return Some(res);
1219            } else {
1220                continue;
1221            }
1222        }
1223        if pad != 0x1 {
1224            let res = (pad << 4) as u8;
1225            pad = 0x1;
1226            return Some(res);
1227        }
1228        None
1229    })
1230}
1231
1232/// Decryption seed for eexec segment.
1233const EEXEC_SEED: u32 = 55665;
1234
1235/// Decryption seed for charstring (and subroutine) data.
1236const CHARSTRING_SEED: u32 = 4330;
1237
1238/// Returns an iterator yielding the decrypted bytes.
1239///
1240/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psconv.c#L557>
1241fn decrypt(bytes: impl Iterator<Item = u8>, mut seed: u32) -> impl Iterator<Item = u8> {
1242    bytes.map(move |b| {
1243        let b = b as u32;
1244        let plain = b ^ (seed >> 8);
1245        seed = b.wrapping_add(seed).wrapping_mul(52845).wrapping_add(22719) & 0xFFFF;
1246        plain as u8
1247    })
1248}
1249
1250fn is_whitespace(c: u8) -> bool {
1251    if c <= 32 {
1252        return matches!(c, b' ' | b'\n' | b'\r' | b'\t' | b'\0' | 0x0C);
1253    }
1254    false
1255}
1256
1257/// Characters that always delimit tokens.
1258///
1259/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/include/freetype/internal/psaux.h#L1398>
1260fn is_special(c: u8) -> bool {
1261    matches!(
1262        c,
1263        b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
1264    )
1265}
1266
1267fn is_special_or_whitespace(c: u8) -> bool {
1268    is_special(c) || is_whitespace(c)
1269}
1270
1271/// Preserve valid UTF-8 names; otherwise decode each source byte as Latin-1.
1272fn decode_name(bytes: &[u8]) -> Cow<'_, str> {
1273    match core::str::from_utf8(bytes) {
1274        Ok(value) => Cow::Borrowed(value),
1275        Err(_) => Cow::Owned(bytes.iter().copied().map(char::from).collect()),
1276    }
1277}
1278
1279#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1280enum Token<'a> {
1281    /// Integers
1282    Int(i64),
1283    /// Literal strings, delimited by ()
1284    LitString(&'a [u8]),
1285    /// Hex strings, delimited by <>
1286    HexString(&'a [u8]),
1287    /// Procedures, delimited by {}
1288    Proc(&'a [u8]),
1289    /// Binary blobs
1290    Binary(&'a [u8]),
1291    /// Names, preceded by /
1292    Name(&'a [u8]),
1293    /// All other raw tokens (identifiers and self-delimiting punctuation)
1294    Raw(&'a [u8]),
1295}
1296
1297/// Collection of subroutines.
1298#[derive(Default)]
1299struct Subrs {
1300    /// Packed data for all subroutines.
1301    data: Vec<u8>,
1302    /// Index mapping subroutine number to range in the packed data. Sorted
1303    /// by subroutine number.
1304    index: Vec<(u32, Range<usize>)>,
1305    /// If true, subroutine number == index so we don't need to
1306    /// bsearch.
1307    is_dense: bool,
1308}
1309
1310impl Subrs {
1311    fn get(&self, index: u32) -> Option<&[u8]> {
1312        let entry_idx = if self.is_dense {
1313            index as usize
1314        } else {
1315            self.index.binary_search_by_key(&index, |e| e.0).ok()?
1316        };
1317        self.data.get(self.index.get(entry_idx)?.1.clone())
1318    }
1319}
1320
1321struct CharstringEntry {
1322    name: Range<usize>,
1323    data: Range<usize>,
1324}
1325
1326/// Collection of charstrings.
1327#[derive(Default)]
1328struct Charstrings {
1329    /// Packed data for all charstrings.
1330    data: Vec<u8>,
1331    /// Packed data for all glyph names.
1332    names: Vec<u8>,
1333    /// Index containing all charstrings.
1334    index: Vec<CharstringEntry>,
1335    /// If notdef was remapped, holds the original index of the notdef
1336    /// charstring.
1337    orig_notdef_index: Option<usize>,
1338}
1339
1340impl Charstrings {
1341    fn num_glyphs(&self) -> u32 {
1342        self.index.len() as u32
1343    }
1344
1345    fn get(&self, index: u32) -> Option<&[u8]> {
1346        self.data.get(self.index.get(index as usize)?.data.clone())
1347    }
1348
1349    fn name(&self, index: u32) -> Option<&str> {
1350        core::str::from_utf8(
1351            self.names
1352                .get(self.index.get(index as usize)?.name.clone())?,
1353        )
1354        .ok()
1355    }
1356
1357    fn index_for_name(&self, name: &str) -> Option<u32> {
1358        let name = name.as_bytes();
1359        for (idx, entry) in self.index.iter().enumerate() {
1360            if self.names.get(entry.name.clone()) == Some(name) {
1361                return Some(idx as u32);
1362            }
1363        }
1364        None
1365    }
1366
1367    fn push(&mut self, name: &[u8], data: &[u8], len_iv: i64) {
1368        let start = self.data.len();
1369        if len_iv >= 0 {
1370            // use decryption; skip first len_iv bytes
1371            self.data
1372                .extend(decrypt(data.iter().copied(), CHARSTRING_SEED).skip(len_iv as usize));
1373        } else {
1374            // just add the data
1375            self.data.extend_from_slice(data);
1376        }
1377        let end = self.data.len();
1378        let name_start = self.names.len();
1379        self.names.extend_from_slice(decode_name(name).as_bytes());
1380        let name_end = self.names.len();
1381        self.index.push(CharstringEntry {
1382            name: name_start..name_end,
1383            data: start..end,
1384        });
1385    }
1386}
1387
1388/// Encoding that maps characters to glyph identifiers.
1389#[derive(PartialEq, Debug)]
1390enum RawEncoding {
1391    Predefined(PredefinedEncoding),
1392    Custom(Vec<GlyphId>),
1393}
1394
1395/// Simulated .notdef glyph, same as FreeType:
1396///
1397/// 0 333 hsbw endchar
1398///
1399/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L2192>
1400const NOTDEF_GLYPH: &[u8] = &[0x8B, 0xF7, 0xE1, 0x0D, 0x0E];
1401
1402#[derive(Clone)]
1403struct Parser<'a> {
1404    data: &'a [u8],
1405    pos: usize,
1406}
1407
1408impl<'a> Parser<'a> {
1409    fn new(data: &'a [u8]) -> Self {
1410        Self { data, pos: 0 }
1411    }
1412
1413    fn next(&mut self) -> Option<Token<'a>> {
1414        // Roughly follows the logic of ps_parser_skip_PS_token
1415        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psobjs.c#L482>
1416        loop {
1417            self.skip_whitespace()?;
1418            let start = self.pos;
1419            let c = self.next_byte()?;
1420            match c {
1421                // Line comment
1422                b'%' => self.skip_line(),
1423                // Procedures
1424                b'{' => return self.read_proc(start),
1425                // Literal strings
1426                b'(' => return self.read_lit_string(start),
1427                b'<' => {
1428                    if self.peek_byte() == Some(b'<') {
1429                        // Just ignore these
1430                        self.pos += 1;
1431                        continue;
1432                    }
1433                    // Hex string: hex digits and whitespace
1434                    return self.read_hex_string(start);
1435                }
1436                b'>' => {
1437                    // We consume single '>' when parsing hex strings so a
1438                    // double >> is expected here
1439                    if self.next_byte()? != b'>' {
1440                        return None;
1441                    }
1442                }
1443                // Name
1444                b'/' => {
1445                    if let Some(c) = self.peek_byte() {
1446                        if is_whitespace(c) || is_special(c) {
1447                            if !is_special(c) {
1448                                self.pos += 1;
1449                            }
1450                            return Some(Token::Name(&[]));
1451                        } else {
1452                            let count = self.skip_until(|c| is_whitespace(c) || is_special(c));
1453                            return self.data.get(start + 1..start + count).map(Token::Name);
1454                        }
1455                    }
1456                }
1457                // Brackets
1458                b'[' | b']' => {
1459                    let data = self.data.get(start..start + 1)?;
1460                    return Some(Token::Raw(data));
1461                }
1462                _ => {
1463                    let count = self.skip_until(is_special_or_whitespace);
1464                    let content = self.data.get(start..start + count)?;
1465                    // Look for numbers but don't try to parse fractional
1466                    // values since we want to handle those with special
1467                    // precision
1468                    if (c.is_ascii_digit() || c == b'-') && !content.contains(&b'.') {
1469                        if let Some(int) = decode_int(content) {
1470                            // HACK: if we have an int followed by RD or -|
1471                            // then is a binary blob in Type1. Hack because
1472                            // this is not actually how PostScript works
1473                            // but Type1 fonts define /RD procs and this
1474                            // pattern is used by FreeType.
1475                            // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1351>
1476                            if self.accept_blob_start() {
1477                                // skip a single space
1478                                self.pos += 1;
1479                                // read the internal data
1480                                let data = self.read_bytes(int as usize)?;
1481                                // there's often some form of terminator here
1482                                // but let the calling code handle it because
1483                                // some buggy fonts may omit it
1484                                return Some(Token::Binary(data));
1485                            }
1486                            return Some(Token::Int(int));
1487                        }
1488                    }
1489                    return Some(Token::Raw(content));
1490                }
1491            }
1492        }
1493    }
1494
1495    /// Special lookahead case for RD or -| which indicates a binary blob in
1496    /// Type1 fonts.
1497    fn accept_blob_start(&mut self) -> bool {
1498        let mut p = self.clone();
1499        p.skip_whitespace();
1500        let start = p.pos;
1501        p.skip_until(is_special_or_whitespace);
1502        let end = p.pos;
1503        if matches!(self.data.get(start..end), Some(b"RD") | Some(b"-|")) {
1504            self.pos = end;
1505            true
1506        } else {
1507            false
1508        }
1509    }
1510
1511    fn accept(&mut self, token: Token) -> bool {
1512        let mut p = self.clone();
1513        if p.next() == Some(token) {
1514            self.pos = p.pos;
1515            true
1516        } else {
1517            false
1518        }
1519    }
1520
1521    fn expect(&mut self, token: Token) -> Option<()> {
1522        (self.next()? == token).then_some(())
1523    }
1524
1525    fn next_byte(&mut self) -> Option<u8> {
1526        let byte = self.peek_byte()?;
1527        self.pos += 1;
1528        Some(byte)
1529    }
1530
1531    fn peek_byte(&self) -> Option<u8> {
1532        self.data.get(self.pos).copied()
1533    }
1534
1535    fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
1536        let end = self.pos.checked_add(len)?;
1537        let content = self.data.get(self.pos..end)?;
1538        self.pos = end;
1539        Some(content)
1540    }
1541
1542    fn skip_whitespace(&mut self) -> Option<()> {
1543        while is_whitespace(*self.data.get(self.pos)?) {
1544            self.pos += 1;
1545        }
1546        Some(())
1547    }
1548
1549    fn skip_line(&mut self) {
1550        while let Some(c) = self.next_byte() {
1551            if c == b'\n' || c == b'\r' {
1552                break;
1553            }
1554        }
1555    }
1556
1557    fn skip_until(&mut self, f: impl Fn(u8) -> bool) -> usize {
1558        let mut count = 0;
1559        while let Some(byte) = self.peek_byte() {
1560            if f(byte) {
1561                break;
1562            }
1563            self.pos += 1;
1564            count += 1;
1565        }
1566        count + 1
1567    }
1568
1569    fn read_proc(&mut self, start: usize) -> Option<Token<'a>> {
1570        let mut nest_depth = 1i32;
1571        while let Some(c) = self.next_byte() {
1572            match c {
1573                b'{' => nest_depth = nest_depth.checked_add(1)?,
1574                b'}' => {
1575                    nest_depth -= 1;
1576                    if nest_depth == 0 {
1577                        break;
1578                    }
1579                }
1580                // Skip over comments
1581                b'%' => self.skip_line(),
1582                // Skip over literal strings since they can contain braces
1583                b'(' => {
1584                    self.read_lit_string(self.pos - 1)?;
1585                }
1586                _ => {}
1587            }
1588        }
1589        if nest_depth != 0 {
1590            // unterminated procedure
1591            return None;
1592        }
1593        let end = self.pos;
1594        Some(Token::Proc(self.data.get(start + 1..end - 1)?))
1595    }
1596
1597    fn read_lit_string(&mut self, start: usize) -> Option<Token<'a>> {
1598        let mut nest_depth = 1i32;
1599        while let Some(c) = self.next_byte() {
1600            match c {
1601                b'(' => nest_depth = nest_depth.checked_add(1)?,
1602                b')' => {
1603                    nest_depth -= 1;
1604                    if nest_depth == 0 {
1605                        break;
1606                    }
1607                }
1608                // Escape sequence
1609                b'\\' => {
1610                    // Just eat the next byte. We only care
1611                    // about avoiding \( and \) anyway.
1612                    self.next_byte()?;
1613                }
1614                _ => {}
1615            }
1616        }
1617        if nest_depth != 0 {
1618            // unterminated string
1619            return None;
1620        }
1621        let end = self.pos;
1622        Some(Token::LitString(self.data.get(start + 1..end - 1)?))
1623    }
1624
1625    fn read_hex_string(&mut self, start: usize) -> Option<Token<'a>> {
1626        while let Some(c) = self.next_byte() {
1627            if !is_whitespace(c) && !c.is_ascii_hexdigit() {
1628                break;
1629            }
1630        }
1631        let end = self.pos;
1632        if self.data.get(end - 1) != Some(&b'>') {
1633            // unterminated hex string
1634            return None;
1635        }
1636        Some(Token::HexString(self.data.get(start + 1..end - 1)?))
1637    }
1638
1639    fn read_int(&mut self) -> Option<i64> {
1640        self.next().and_then(|t| match t {
1641            Token::Int(n) => Some(n),
1642            _ => None,
1643        })
1644    }
1645
1646    fn read_num_as_int(&mut self) -> Option<i32> {
1647        match self.next()? {
1648            Token::Int(n) => Some(n as i32),
1649            // Note, FT calls PS_Conv_ToInt for fields that might contain
1650            // fractional bits but just ignores everything after the
1651            // initial integer, so we do the same
1652            Token::Raw(bytes) => decode_int_prefix(bytes, 0).map(|n| n.0 as i32),
1653            _ => None,
1654        }
1655    }
1656
1657    fn read_string(&mut self) -> Option<String> {
1658        let bytes = match self.next()? {
1659            // FreeType accepts a name or a string here
1660            // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psobjs.c#L1123>
1661            Token::Name(bytes) | Token::LitString(bytes) => bytes,
1662            _ => return None,
1663        };
1664        Some(decode_name(bytes).into_owned())
1665    }
1666}
1667
1668impl Parser<'_> {
1669    /// Parse a font matrix.
1670    ///
1671    /// Like FreeType, this is designed assuming a upem of 1000 and produces
1672    /// an identity matrix in that case. This is, the result is scaled such
1673    /// that 0.001 yields a value of 1.0.
1674    ///
1675    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1403>
1676    fn read_font_matrix(&mut self) -> Option<ScaledFontMatrix> {
1677        let mut components = [Fixed::ZERO; 6];
1678        // accept [ or { to match FreeType
1679        if !self.accept(Token::Raw(b"[")) {
1680            self.expect(Token::Raw(b"{"))?;
1681        }
1682        // read all components
1683        for component in &mut components {
1684            *component = match self.next()? {
1685                Token::Int(int) => Fixed::from_i32((int as i32).checked_mul(1000)?),
1686                Token::Raw(bytes) => decode_fixed(bytes, 3)?,
1687                _ => return None,
1688            }
1689        }
1690        // FreeType doesn't validate the closing delimiter, so just skip
1691        self.next()?;
1692        let temp_scale = components[3].abs();
1693        if temp_scale == Fixed::ZERO {
1694            return None;
1695        }
1696        let mut upem = 1000;
1697        if temp_scale != Fixed::ONE {
1698            upem = (Fixed::from_bits(1000) / temp_scale).to_bits();
1699            components[0] /= temp_scale;
1700            components[1] /= temp_scale;
1701            components[2] /= temp_scale;
1702            // don't scale components[3]
1703            components[4] /= temp_scale;
1704            components[5] /= temp_scale;
1705            if components[3] < Fixed::ZERO {
1706                components[3] = -Fixed::ONE;
1707            } else {
1708                components[3] = Fixed::ONE;
1709            }
1710        }
1711        // offsets must be expressed in integer font units
1712        for offset in components.iter_mut().skip(4) {
1713            *offset = Fixed::from_bits(offset.to_bits() >> 16);
1714        }
1715        let matrix = FontMatrix::from_elements(components);
1716        if transform::is_degenerate(&matrix) {
1717            return None;
1718        }
1719        Some(ScaledFontMatrix {
1720            matrix,
1721            scale: upem,
1722        })
1723    }
1724
1725    /// Parse the set of subroutines.
1726    ///
1727    /// The `len_iv` parameter defines the number of prefix padding bytes for
1728    /// encrypted data. If < 0, then the data is not encrypted.
1729    ///
1730    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1720>
1731    fn read_subrs(&mut self, len_iv: i64) -> Option<Subrs> {
1732        let mut subrs = Subrs::default();
1733        let _: usize = match self.next()? {
1734            Token::Raw(b"[") => {
1735                // Just an empty array
1736                self.expect(Token::Raw(b"]"))?;
1737                return Some(subrs);
1738            }
1739            Token::Int(n) => n.try_into().ok()?,
1740            _ => return None,
1741        };
1742        self.expect(Token::Raw(b"array"))?;
1743        let mut is_dense = true;
1744        // The pattern for each subroutine is `dup <subr_num> <data>`
1745        while self.accept(Token::Raw(b"dup")) {
1746            let (Token::Int(n), Token::Binary(data)) = (self.next()?, self.next()?) else {
1747                return None;
1748            };
1749            // Skip the NP, | or noaccess. FreeType just skips whatever happens
1750            // to be here
1751            self.next();
1752            // There might be an additional put token following the binary data
1753            self.accept(Token::Raw(b"put"));
1754            let subr_num: u32 = n.try_into().ok()?;
1755            if subr_num as usize != subrs.index.len() {
1756                is_dense = false;
1757            }
1758            let start = subrs.data.len();
1759            if len_iv >= 0 {
1760                // use decryption; skip first len_iv bytes
1761                subrs
1762                    .data
1763                    .extend(decrypt(data.iter().copied(), CHARSTRING_SEED).skip(len_iv as usize));
1764            } else {
1765                // just add the data
1766                subrs.data.extend_from_slice(data);
1767            }
1768            let end = subrs.data.len();
1769            subrs.index.push((subr_num, start..end));
1770        }
1771        // If we don't have a dense set, sort the index by number
1772        if !is_dense {
1773            subrs.index.sort_unstable_by_key(|(n, ..)| *n);
1774        }
1775        subrs.is_dense = is_dense;
1776        subrs.data.shrink_to_fit();
1777        subrs.index.shrink_to_fit();
1778        Some(subrs)
1779    }
1780
1781    /// Parse the set of charstrings.
1782    ///
1783    /// The `len_iv` parameter defines the number of prefix padding bytes for
1784    /// encrypted data. If < 0, then the data is not encrypted.
1785    ///
1786    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1919>
1787    fn read_charstrings(&mut self, len_iv: i64) -> Option<Charstrings> {
1788        let mut charstrings = Charstrings::default();
1789        let _: usize = match self.next()? {
1790            Token::Int(n) => n.try_into().ok()?,
1791            _ => return None,
1792        };
1793        let mut notdef_idx = None;
1794        while let Some(token) = self.next() {
1795            let name = match token {
1796                // Stop when we find a `def` or `end` keyword.
1797                // The ugliness matches the FT logic to handle some malformed
1798                // fonts:
1799                // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L2006>
1800                Token::Raw(b"end") => {
1801                    if self
1802                        .peek_byte()
1803                        .map(is_special_or_whitespace)
1804                        .unwrap_or_default()
1805                    {
1806                        break;
1807                    } else {
1808                        continue;
1809                    }
1810                }
1811                Token::Raw(b"def") => {
1812                    // but ignore `def` if no charstring has been seen
1813                    if self
1814                        .peek_byte()
1815                        .map(is_special_or_whitespace)
1816                        .unwrap_or_default()
1817                        && !charstrings.index.is_empty()
1818                    {
1819                        break;
1820                    } else {
1821                        continue;
1822                    }
1823                }
1824                Token::Name(name) => name,
1825                _ => continue,
1826            };
1827            if name == b".notdef" {
1828                notdef_idx = Some(charstrings.index.len());
1829            }
1830            let Token::Binary(data) = self.next()? else {
1831                return None;
1832            };
1833            charstrings.push(name, data, len_iv);
1834        }
1835        match notdef_idx {
1836            Some(0) => {
1837                // .notdef found and at correct location
1838            }
1839            Some(idx) => {
1840                // .notdef found but at incorrect location. Swap with the
1841                // glyph at 0
1842                charstrings.index.swap(0, idx);
1843                charstrings.orig_notdef_index = Some(idx);
1844            }
1845            None => {
1846                // .notdef not found. Add it to the end and then swap with
1847                // the glyph at 0
1848                let idx = charstrings.index.len();
1849                charstrings.push(b".notdef", NOTDEF_GLYPH, -1);
1850                charstrings.index.swap(0, idx);
1851                charstrings.orig_notdef_index = Some(idx);
1852            }
1853        }
1854        charstrings.data.shrink_to_fit();
1855        charstrings.names.shrink_to_fit();
1856        charstrings.index.shrink_to_fit();
1857        Some(charstrings)
1858    }
1859
1860    /// Reads a `/FontBBox`, each component rounded to a whole unit as
1861    /// FreeType rounds it.
1862    ///
1863    /// In the `/Blend` dictionary of a multiple master font, each component
1864    /// is an array with a value for each master. FreeType stores master 0's
1865    /// box over the font's own, so this returns master 0's values.
1866    fn read_font_bbox(&mut self) -> Option<[Fixed; 4]> {
1867        let mut bbox = [Fixed::ZERO; 4];
1868        // accept [ or { to match FreeType
1869        // Note that we parse { as a procedure so this needs some special
1870        // handling
1871        let mut parser;
1872        let parser = if self.accept(Token::Raw(b"[")) {
1873            self
1874        } else if let Token::Proc(proc) = self.next()? {
1875            parser = Parser::new(proc);
1876            &mut parser
1877        } else {
1878            return None;
1879        };
1880        // read all components
1881        for component in &mut bbox {
1882            let value = match parser.next()? {
1883                Token::Proc(masters) => Parser::new(masters).read_fixed()?,
1884                Token::Raw(b"[") => {
1885                    let first = parser.read_fixed()?;
1886                    while parser.next()? != Token::Raw(b"]") {}
1887                    first
1888                }
1889                Token::Int(int) => Fixed::from_i32(int as i32),
1890                Token::Raw(bytes) => decode_fixed(bytes, 0)?,
1891                _ => return None,
1892            };
1893            *component = round_fixed(value);
1894        }
1895        Some(bbox)
1896    }
1897
1898    fn read_weight_vector(&mut self) -> Option<Vec<Fixed>> {
1899        self.accept(Token::Raw(b"["));
1900        let mut weights = Vec::new();
1901        while let Some(token) = self.next() {
1902            match token {
1903                Token::Raw(b"]") => break,
1904                Token::Int(val) => weights.push(Fixed::from_i32(val as _)),
1905                Token::Raw(raw) => weights.push(decode_fixed(raw, 0)?),
1906                _ => return None,
1907            }
1908        }
1909        Some(weights)
1910    }
1911
1912    /// Reads a number as a fixed point value.
1913    fn read_fixed(&mut self) -> Option<Fixed> {
1914        match self.next()? {
1915            Token::Int(int) => Some(Fixed::from_i32(int as i32)),
1916            Token::Raw(raw) => decode_fixed(raw, 0),
1917            _ => None,
1918        }
1919    }
1920
1921    /// Reads the names of the blend axes, as in `[/Weight /Width]`.
1922    fn read_blend_axis_types(&mut self) -> Option<Vec<String>> {
1923        self.expect(Token::Raw(b"["))?;
1924        let mut names = Vec::new();
1925        loop {
1926            match self.next()? {
1927                Token::Raw(b"]") => return Some(names),
1928                Token::Name(name) if !name.is_empty() => {
1929                    names.push(decode_name(name).into_owned());
1930                }
1931                _ => return None,
1932            }
1933        }
1934    }
1935
1936    /// Reads the position of each master in the blend space, as in
1937    /// `[[0 0] [1 0] [0 1] [1 1]]`.
1938    fn read_blend_design_positions(&mut self) -> Option<Vec<Vec<Fixed>>> {
1939        self.expect(Token::Raw(b"["))?;
1940        let mut positions = Vec::new();
1941        loop {
1942            match self.next()? {
1943                Token::Raw(b"]") => return Some(positions),
1944                Token::Raw(b"[") => {
1945                    let mut position = Vec::new();
1946                    loop {
1947                        let mut peek = self.clone();
1948                        if peek.next()? == Token::Raw(b"]") {
1949                            *self = peek;
1950                            break;
1951                        }
1952                        position.push(self.read_fixed()?);
1953                    }
1954                    positions.push(position);
1955                }
1956                _ => return None,
1957            }
1958        }
1959    }
1960
1961    /// Reads the map from design coordinates to blend coordinates for each
1962    /// axis, as in `[[[50 0] [1450 1]] [[50 0] [1450 1]]]`.
1963    fn read_blend_design_map(&mut self) -> Option<Vec<Vec<(i32, Fixed)>>> {
1964        self.expect(Token::Raw(b"["))?;
1965        let mut maps = Vec::new();
1966        loop {
1967            match self.next()? {
1968                Token::Raw(b"]") => return Some(maps),
1969                Token::Raw(b"[") => {
1970                    let mut map = Vec::new();
1971                    loop {
1972                        match self.next()? {
1973                            Token::Raw(b"]") => break,
1974                            Token::Raw(b"[") => {
1975                                // The design point is read as an integer,
1976                                // ignoring any fraction, as FreeType reads
1977                                // it.
1978                                let design = self.read_num_as_int()?;
1979                                let blend = self.read_fixed()?;
1980                                self.expect(Token::Raw(b"]"))?;
1981                                map.push((design, blend));
1982                            }
1983                            _ => return None,
1984                        }
1985                    }
1986                    maps.push(map);
1987                }
1988                _ => return None,
1989            }
1990        }
1991    }
1992
1993    /// Reads an array and returns the number of elements in it.
1994    fn read_array_len(&mut self) -> Option<usize> {
1995        self.expect(Token::Raw(b"["))?;
1996        let mut len = 0;
1997        loop {
1998            match self.next()? {
1999                Token::Raw(b"]") => return Some(len),
2000                _ => len += 1,
2001            }
2002        }
2003    }
2004
2005    /// Parse the encoding.
2006    ///
2007    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1474>
2008    fn read_encoding(&mut self, charstrings: &Charstrings) -> Option<RawEncoding> {
2009        match self.next()? {
2010            // Array of names where index == character code
2011            Token::Raw(b"[") => {
2012                let mut map = Vec::new();
2013                // Should always be 256 entries but preset values to notdef
2014                map.resize(256, GlyphId::NOTDEF);
2015                self.read_dense_encoding(|idx, name| {
2016                    if let Some((slot, gid)) = map
2017                        .get_mut(idx as usize)
2018                        .zip(charstrings.index_for_name(name))
2019                    {
2020                        *slot = gid.into();
2021                    }
2022                });
2023                Some(RawEncoding::Custom(map))
2024            }
2025            // Map of index to glyph name
2026            Token::Int(count) => {
2027                // We're limited to 256 character codes
2028                // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1518>
2029                let count: usize = count.clamp(0, 256) as usize;
2030                let mut map = Vec::new();
2031                // Start with all glyphs mapped to notdef
2032                map.resize(count, GlyphId::NOTDEF);
2033                self.read_sparse_encoding(|idx, name| {
2034                    if let Some((slot, gid)) = map
2035                        .get_mut(idx as usize)
2036                        .zip(charstrings.index_for_name(name))
2037                    {
2038                        *slot = gid.into();
2039                    }
2040                });
2041                Some(RawEncoding::Custom(map))
2042            }
2043            Token::Raw(b"StandardEncoding") => {
2044                Some(RawEncoding::Predefined(PredefinedEncoding::Standard))
2045            }
2046            Token::Raw(b"ExpertEncoding") => {
2047                Some(RawEncoding::Predefined(PredefinedEncoding::Expert))
2048            }
2049            Token::Raw(b"ISOLatin1Encoding") => {
2050                Some(RawEncoding::Predefined(PredefinedEncoding::IsoLatin1))
2051            }
2052            _ => None,
2053        }
2054    }
2055
2056    /// Returns a custom encoding defined by an array of `/<name>`, where
2057    /// the index represents the character code, and invokes the given
2058    /// callback for each.
2059    fn read_dense_encoding(&mut self, mut f: impl FnMut(i64, &str)) -> Option<()> {
2060        // Eat the opening brace if present
2061        self.accept(Token::Raw(b"["));
2062        // Always expect 256 entries
2063        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/type1/t1load.c#L1510>
2064        let mut idx = 0;
2065        while let Some(token) = self.next() {
2066            match token {
2067                Token::Raw(b"]") => break,
2068                Token::Name(name) => {
2069                    let code = idx;
2070                    idx += 1;
2071                    f(code, &decode_name(name));
2072                }
2073                _ => {
2074                    // FreeType fails if missing a literal name here
2075                    return None;
2076                }
2077            }
2078        }
2079        Some(())
2080    }
2081
2082    /// Reads a custom encoding defined by a map of `<charcode> /<name>`
2083    /// and invokes the given callback for each.
2084    fn read_sparse_encoding(&mut self, mut f: impl FnMut(i64, &str)) -> Option<()> {
2085        while let Some(token) = self.next() {
2086            match token {
2087                // The 'def' keyword ends the mapping
2088                Token::Raw(b"def") => break,
2089                Token::Int(code) => {
2090                    // read the name
2091                    let Some(Token::Name(name)) = self.next() else {
2092                        continue;
2093                    };
2094                    f(code, &decode_name(name));
2095                }
2096                _ => {}
2097            }
2098        }
2099        Some(())
2100    }
2101}
2102
2103/// Decode an integer, optionally with a base.
2104///
2105/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psconv.c#L161>
2106fn decode_int(bytes: &[u8]) -> Option<i64> {
2107    let s = std::str::from_utf8(bytes).ok()?;
2108    if let Some(hash_idx) = s.find('#') {
2109        if hash_idx == 1 || hash_idx == 2 {
2110            // It's a radix number, like 8#40.
2111            let radix_str = s.get(0..hash_idx)?;
2112            let number_str = s.get(hash_idx + 1..)?;
2113            let radix = radix_str
2114                .parse::<u32>()
2115                .ok()
2116                .filter(|n| (2..=36).contains(n))?;
2117            i64::from_str_radix(number_str, radix).ok()
2118        } else {
2119            s.parse::<i64>().ok()
2120        }
2121    } else {
2122        s.parse::<i64>().ok()
2123    }
2124}
2125
2126/// Decode an integer at the given position, returning the value and the
2127/// index of the position following the decoded integer.
2128fn decode_int_prefix(bytes: &[u8], start: usize) -> Option<(i64, usize)> {
2129    let tail = bytes.get(start..)?;
2130    let end = tail
2131        .iter()
2132        .position(|c| *c != b'-' && !c.is_ascii_digit())
2133        .unwrap_or(tail.len());
2134    let int = decode_int(tail.get(..end)?)?;
2135    Some((int, start + end))
2136}
2137
2138/// Rounds to a whole unit, halves away from zero, as FreeType's
2139/// `FT_RoundFix` does.
2140///
2141/// A value from 32767.5 up rounds to 32768, which `Fixed` can't hold, so
2142/// it saturates to `Fixed::MAX`. FreeType keeps 32768 in a 64-bit value;
2143/// both give 32768 once rounded up to whole units.
2144fn round_fixed(value: Fixed) -> Fixed {
2145    let bits = value.to_bits() as i64;
2146    let rounded = (bits + 0x8000 - (bits < 0) as i64) & !0xFFFF;
2147    Fixed::from_bits(rounded.min(i32::MAX as i64) as i32)
2148}
2149
2150/// Decode a fixed point value, scaling to a specific power of
2151/// ten.
2152///
2153/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/80a507a6b8e3d2906ad2c8ba69329bd2fb2a85ef/src/psaux/psconv.c#L195>
2154fn decode_fixed(bytes: &[u8], mut power_ten: i32) -> Option<Fixed> {
2155    const LIMIT: i32 = 0xCCCCCCC;
2156    let mut idx = 0;
2157    let &first = bytes.get(idx)?;
2158    let sign = if first == b'-' || first == b'+' {
2159        idx += 1;
2160        if first == b'-' {
2161            -1
2162        } else {
2163            1
2164        }
2165    } else {
2166        1
2167    };
2168    let overflow = || Some(Fixed::from_bits(0x7FFFFFFF * sign));
2169    let mut integral = 0;
2170    if *bytes.get(idx)? != b'.' {
2171        let (int, end_idx) = decode_int_prefix(bytes, idx)?;
2172        if int > 0x7FFF {
2173            return overflow();
2174        }
2175        integral = (int << 16) as i32;
2176        idx = end_idx;
2177    }
2178    let mut decimal = 0;
2179    let mut divider = 1;
2180    if bytes.get(idx) == Some(&b'.') {
2181        idx += 1;
2182        while let Some(byte) = bytes.get(idx).copied() {
2183            if !byte.is_ascii_digit() {
2184                break;
2185            }
2186            let digit = (byte - b'0') as i32;
2187            if divider < LIMIT && decimal < LIMIT {
2188                decimal = decimal * 10 + digit;
2189                if integral == 0 && power_ten > 0 {
2190                    power_ten -= 1;
2191                } else {
2192                    divider *= 10;
2193                }
2194            }
2195            idx += 1;
2196        }
2197    }
2198    if bytes.get(idx).map(|b| b.to_ascii_lowercase()) == Some(b'e') {
2199        idx += 1;
2200        let (exponent, _) = decode_int_prefix(bytes, idx)?;
2201        if exponent > 1000 {
2202            return overflow();
2203        } else if exponent < -1000 {
2204            // underflow
2205            return Some(Fixed::ZERO);
2206        } else {
2207            power_ten = power_ten.checked_add(exponent as i32)?;
2208        }
2209    }
2210    if integral == 0 && decimal == 0 {
2211        return Some(Fixed::ZERO);
2212    }
2213    while power_ten > 0 {
2214        if integral >= LIMIT {
2215            return overflow();
2216        }
2217        integral *= 10;
2218        if decimal >= LIMIT {
2219            if divider == 1 {
2220                return overflow();
2221            }
2222            divider /= 10;
2223        } else {
2224            decimal *= 10;
2225        }
2226        power_ten -= 1;
2227    }
2228    while power_ten < 0 {
2229        integral /= 10;
2230        if divider < LIMIT {
2231            divider *= 10;
2232        } else {
2233            decimal /= 10;
2234        }
2235        if integral == 0 && decimal == 0 {
2236            return Some(Fixed::ZERO);
2237        }
2238        power_ten += 1;
2239    }
2240    if decimal != 0 {
2241        decimal = (Fixed::from_bits(decimal) / Fixed::from_bits(divider)).to_bits();
2242        integral += decimal;
2243    }
2244    Some(Fixed::from_bits(integral * sign))
2245}
2246
2247#[cfg(test)]
2248mod tests {
2249    use super::*;
2250    use charstring::test_helpers::*;
2251
2252    #[test]
2253    fn pfb_tags() {
2254        // Text segment tag
2255        let data = [0x80, 0x01, 0x01, 0x02, 0x00, 0x00];
2256        let (tag, len) = decode_pfb_tag(&data, 0).unwrap();
2257        assert_eq!(tag, PFB_TEXT_SEGMENT_TAG);
2258        assert_eq!(len, 513);
2259        // Binary segment tag
2260        let data = [0x80, 0x02, 0x01, 0x03, 0x00, 0x00];
2261        let (tag, len) = decode_pfb_tag(&data, 0).unwrap();
2262        assert_eq!(tag, PFB_BINARY_SEGMENT_TAG);
2263        assert_eq!(len, 769);
2264        // Invalid tag
2265        let data = [0x00; 6];
2266        assert!(decode_pfb_tag(&data, 0).is_none());
2267        // Not enough data
2268        let data = [0x00; 5];
2269        assert!(decode_pfb_tag(&data, 0).is_none());
2270    }
2271
2272    #[test]
2273    fn pfb_segments() {
2274        let segments = [
2275            vec![0x01; 8],
2276            vec![0x02; 10],
2277            vec![0x03; 4],
2278            vec![0x04; 255],
2279        ];
2280        // Write each segment to a buffer
2281        let mut buf = vec![];
2282        for segment in &segments {
2283            buf.push(0x80);
2284            buf.push(0x02);
2285            buf.push(segment.len() as u8);
2286            buf.extend_from_slice(&[0; 3]);
2287            for byte in segment {
2288                buf.push(*byte);
2289            }
2290        }
2291        // Now parse and compare
2292        let mut parsed_count = 0;
2293        for (parsed, expected) in decode_pfb_binary_segments(&buf).zip(&segments) {
2294            assert_eq!(parsed, expected);
2295            parsed_count += 1;
2296        }
2297        assert_eq!(parsed_count, segments.len());
2298    }
2299
2300    #[test]
2301    fn hex_decode() {
2302        check_hex_decode(
2303            b"743F8413F3636CA85A9FFEFB50B4BB27",
2304            &[
2305                116, 63, 132, 19, 243, 99, 108, 168, 90, 159, 254, 251, 80, 180, 187, 39,
2306            ],
2307        );
2308    }
2309
2310    #[test]
2311    fn hex_decode_ignores_whitespace() {
2312        check_hex_decode(
2313            b"743F 8413F3636C\nA85A9FFEF\tB50B     4BB27",
2314            &[
2315                116, 63, 132, 19, 243, 99, 108, 168, 90, 159, 254, 251, 80, 180, 187, 39,
2316            ],
2317        );
2318    }
2319
2320    #[test]
2321    fn hex_decode_truncate() {
2322        check_hex_decode(b"743F.8413F3636CA85A9FFEFB50B4BB27", &[116, 63]);
2323    }
2324
2325    #[test]
2326    fn hex_decode_odd_chars() {
2327        check_hex_decode(b"743", &[116, 48]);
2328    }
2329
2330    #[track_caller]
2331    fn check_hex_decode(hex: &[u8], expected: &[u8]) {
2332        let decoded = decode_hex(hex.iter().copied()).collect::<Vec<_>>();
2333        assert_eq!(decoded, expected);
2334    }
2335
2336    #[test]
2337    fn decrypt_bytes() {
2338        let cipher = [
2339            0x74, 0x3f, 0x84, 0x13, 0xf3, 0x63, 0x6c, 0xa8, 0x5a, 0x9f, 0xfe, 0xfb, 0x50, 0xb4,
2340            0xbb, 0x27,
2341        ];
2342        let plain = decrypt(cipher.iter().copied(), EEXEC_SEED).collect::<Vec<_>>();
2343        // First 4 bytes are random garbage
2344        assert_eq!(&plain[4..], b"dup\n/Private");
2345    }
2346
2347    #[test]
2348    fn find_eexec() {
2349        // Just a space
2350        assert_eq!(
2351            find_eexec_data(b"dup\n/Private\ncurrentfile eexec *&&FW"),
2352            Some(31)
2353        );
2354        // Multiple spaces
2355        assert_eq!(
2356            find_eexec_data(b"dup\n/Private\ncurrentfile eexec     *&&FW"),
2357            Some(35)
2358        );
2359        // New lines
2360        assert_eq!(
2361            find_eexec_data(b"dup\n/Private\ncurrentfile eexec\n\n*&&FW"),
2362            Some(32)
2363        );
2364        // Only skip \r when it precedes \n
2365        assert_eq!(
2366            find_eexec_data(b"dup\n/Private\ncurrentfile eexec\r\n\r*&&FW"),
2367            Some(32)
2368        );
2369        // Skip eexec in comments and strings
2370        assert_eq!(
2371            find_eexec_data(b"% eexec in comment\n(eexec in string) currentfile eexec $$$$"),
2372            Some(55)
2373        );
2374        // No eexec
2375        assert!(find_eexec_data(b"% eexec in comment\n(eexec in string) currentfile").is_none());
2376    }
2377
2378    #[test]
2379    fn read_pfb_raw_dicts() {
2380        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB).unwrap();
2381        check_noto_serif_base(dicts.base);
2382        check_noto_serif_private(&dicts.private);
2383    }
2384
2385    #[test]
2386    fn read_pfa_raw_dicts() {
2387        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
2388        check_noto_serif_base(dicts.base);
2389        check_noto_serif_private(&dicts.private);
2390    }
2391
2392    fn check_noto_serif_base(base: &[u8]) {
2393        const EXPECTED_PREFIX: &str = r#"%!PS-AdobeFont-1.0: NotoSerif-Regular 2.007; ttfautohint (v1.8) -l 8 -r 50 -G 200 -x 14 -D latn -f none -a qsq -X ""
2394%%Title: NotoSerif-Regular
2395%Version: 2.007; ttfautohint (v1.8) -l 8 -r 50 -G 200 -x 14 -D latn -f none -a qsq -X ""
2396%%CreationDate: Tue Feb 10 16:07:25 2026
2397%%Creator: www-data
2398%Copyright: Copyright 2015-2021 Google LLC. All Rights Reserved.
2399% Generated by FontForge 20190801 (http://fontforge.sf.net/)
2400%%EndComments
2401
240210 dict begin
2403/FontType 1 def
2404/FontMatrix [0.001 0 0 0.001 0 0 ]readonly def
2405/FontName /NotoSerif-Regular def
2406/FontBBox {5 0 989 775 }readonly def
2407"#;
2408        // git will replace \r\n with \n in pfa files on windows so strip
2409        // \r out to ensure a robust comparison
2410        let mut base = base.to_vec();
2411        base.retain(|&b| b != b'\r');
2412        assert!(base.starts_with(EXPECTED_PREFIX.as_bytes()));
2413    }
2414
2415    fn check_noto_serif_private(private: &[u8]) {
2416        const EXPECTED_PREFIX: &str = r#"dup
2417/Private 8 dict dup begin
2418/RD{string currentfile exch readstring pop}executeonly def
2419/ND{noaccess def}executeonly def
2420/NP{noaccess put}executeonly def
2421/MinFeature{16 16}ND
2422/password 5839 def
2423/BlueValues [0 0 536 536 714 714 770 770 ]ND
2424/OtherSubrs"#;
2425        assert!(private.starts_with(EXPECTED_PREFIX.as_bytes()))
2426    }
2427
2428    #[test]
2429    fn parse_ints() {
2430        check_tokens(
2431            "% a comment\n20 -30 2#1011 10#-5 %another!\r 16#fC",
2432            &[
2433                Token::Int(20),
2434                Token::Int(-30),
2435                Token::Int(11),
2436                Token::Int(-5),
2437                Token::Int(252),
2438            ],
2439        );
2440    }
2441
2442    #[test]
2443    fn parse_num_to_int() {
2444        let mut parser =
2445            Parser::new(b"102 102.1 102.4 102.5 102.9 -102.1 -102.5 -102.9 8#146 16#66");
2446        for _ in 0..10 {
2447            assert_eq!(parser.read_num_as_int().unwrap().abs(), 102);
2448        }
2449        assert!(parser.next().is_none());
2450    }
2451
2452    #[test]
2453    fn parse_strings() {
2454        check_tokens(
2455            "(string (nested) 1) % and a hex string:\n <DEAD BEEF>",
2456            &[
2457                Token::LitString(b"string (nested) 1"),
2458                Token::HexString(b"DEAD BEEF"),
2459            ],
2460        );
2461    }
2462
2463    #[test]
2464    fn font_info_strings_use_utf8_then_latin1() {
2465        let mut parser = Parser::new(b"(Caf\xc3\xa9) (Caf\xe9) /Caf\xe9");
2466        assert_eq!(parser.read_string().as_deref(), Some("Café"));
2467        assert_eq!(parser.read_string().as_deref(), Some("Café"));
2468        assert_eq!(parser.read_string().as_deref(), Some("Café"));
2469    }
2470
2471    #[test]
2472    fn latin1_glyph_and_encoding_names_match() {
2473        let mut charstrings = Charstrings::default();
2474        charstrings.push(b"Caf\xe9", b"", -1);
2475        assert_eq!(charstrings.name(0), Some("Café"));
2476        assert_eq!(charstrings.index_for_name("Café"), Some(0));
2477
2478        let mut dense = Parser::new(b"[/Caf\xe9]");
2479        let mut dense_names = Vec::new();
2480        dense
2481            .read_dense_encoding(|code, name| dense_names.push((code, name.to_owned())))
2482            .unwrap();
2483        assert_eq!(dense_names, [(0, "Café".into())]);
2484
2485        let mut sparse = Parser::new(b"65 /Caf\xe9 def");
2486        let mut sparse_names = Vec::new();
2487        sparse
2488            .read_sparse_encoding(|code, name| sparse_names.push((code, name.to_owned())))
2489            .unwrap();
2490        assert_eq!(sparse_names, [(65, "Café".into())]);
2491    }
2492
2493    #[test]
2494    fn parse_unterminated_strings() {
2495        check_tokens("(string (nested) 1", &[]);
2496        check_tokens("<DEAD BEEF", &[]);
2497    }
2498
2499    #[test]
2500    fn parse_procs() {
2501        check_tokens(
2502            "{a {nested 20 % comment\n} proc } % and a\n {simple proc}",
2503            &[
2504                Token::Proc(b"a {nested 20 % comment\n} proc "),
2505                Token::Proc(b"simple proc"),
2506            ],
2507        );
2508    }
2509
2510    #[test]
2511    fn parse_procs_with_string_containing_unbalanced_braces() {
2512        check_tokens(
2513            "{a proc with (string {with braces}} {) }",
2514            &[Token::Proc(b"a proc with (string {with braces}} {) ")],
2515        );
2516    }
2517
2518    #[test]
2519    fn parse_proc_with_single_int() {
2520        check_tokens(
2521            "dup 3 {3} executeonly put",
2522            &[
2523                Token::Raw(b"dup"),
2524                Token::Int(3),
2525                Token::Proc(b"3"),
2526                Token::Raw(b"executeonly"),
2527                Token::Raw(b"put"),
2528            ],
2529        );
2530    }
2531
2532    #[test]
2533    fn parse_unterminated_procs() {
2534        check_tokens("{a {nested 20} proc", &[]);
2535    }
2536
2537    #[test]
2538    fn parse_aggregate_tokens_without_whitespace() {
2539        check_tokens(
2540            "{(string)}3(string1)(string2)",
2541            &[
2542                Token::Proc(b"(string)"),
2543                Token::Int(3),
2544                Token::LitString(b"string1"),
2545                Token::LitString(b"string2"),
2546            ],
2547        );
2548    }
2549
2550    #[test]
2551    fn parse_names() {
2552        check_tokens(
2553            "/FontMatrix\r %comment\n /CharStrings",
2554            &[Token::Name(b"FontMatrix"), Token::Name(b"CharStrings")],
2555        );
2556    }
2557
2558    #[test]
2559    fn parse_binary_blobs() {
2560        check_tokens(
2561            "/.notdef 4 RD abcd \n5 11\n \t-| a83jnshf7 3 ",
2562            &[
2563                // simulates a charstring: name followed by data
2564                Token::Name(b".notdef"),
2565                Token::Binary(b"abcd"),
2566                // simulates a subr: index followed by data
2567                Token::Int(5),
2568                Token::Binary(b"a83jnshf7 3"),
2569            ],
2570        )
2571    }
2572
2573    #[test]
2574    fn parse_base_dict_prefix() {
2575        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
2576        let ts = parse_to_tokens(dicts.base);
2577        assert_eq!(
2578            &ts[..19],
2579            &[
2580                Token::Int(10),
2581                Token::Raw(b"dict"),
2582                Token::Raw(b"begin"),
2583                Token::Name(b"FontType"),
2584                Token::Int(1),
2585                Token::Raw(b"def"),
2586                Token::Name(b"FontMatrix"),
2587                Token::Raw(b"["),
2588                Token::Raw(b"0.001"),
2589                Token::Int(0),
2590                Token::Int(0),
2591                Token::Raw(b"0.001"),
2592                Token::Int(0),
2593                Token::Int(0),
2594                Token::Raw(b"]"),
2595                Token::Raw(b"readonly"),
2596                Token::Raw(b"def"),
2597                Token::Name(b"FontName"),
2598                Token::Name(b"NotoSerif-Regular"),
2599            ]
2600        );
2601    }
2602
2603    #[track_caller]
2604    fn check_tokens(source: &str, expected: &[Token]) {
2605        let ts = parse_to_tokens(source.as_bytes());
2606        assert_eq!(ts, expected);
2607    }
2608
2609    fn parse_to_tokens(data: &'_ [u8]) -> Vec<Token<'_>> {
2610        let mut tokens = vec![];
2611        let mut parser = Parser::new(data);
2612        while let Some(token) = parser.next() {
2613            tokens.push(token);
2614        }
2615        tokens
2616    }
2617
2618    #[test]
2619    fn parse_fixed() {
2620        // Direct conversions (power_ten = 0)
2621        assert_eq!(decode_fixed(b"42.5", 0).unwrap(), Fixed::from_f64(42.5));
2622        assert_eq!(
2623            decode_fixed(b"0.0015", 0).unwrap(),
2624            Fixed::from_f64(0.001495361328125)
2625        );
2626        assert_eq!(
2627            decode_fixed(b"425.000e-1", 0).unwrap(),
2628            Fixed::from_f64(42.5)
2629        );
2630        assert_eq!(
2631            decode_fixed(b"1.5e-3", 0).unwrap(),
2632            Fixed::from_f64(0.001495361328125)
2633        );
2634        // Scaled by 1000 (power_ten = 3)
2635        assert_eq!(decode_fixed(b"1.5", 3).unwrap(), Fixed::from_f64(1500.0));
2636        assert_eq!(decode_fixed(b"0.001", 3).unwrap(), Fixed::from_f64(1.0));
2637        assert_eq!(
2638            decode_fixed(b"15000e-4", 3).unwrap(),
2639            Fixed::from_f64(1500.0)
2640        );
2641        assert_eq!(decode_fixed(b"1.000e-3", 3).unwrap(), Fixed::from_f64(1.0));
2642    }
2643
2644    #[test]
2645    fn parse_font_matrix() {
2646        // Standard matrix for 1000 upem
2647        assert_eq!(
2648            Parser::new(b"[0.001 0 0 0.001 0 0]")
2649                .read_font_matrix()
2650                .unwrap()
2651                .matrix,
2652            FontMatrix::IDENTITY,
2653        );
2654        // Matrix with a stretch along the x axis and a small
2655        // offset
2656        assert_eq!(
2657            Parser::new(b"[0.002 0 0 0.001 1 2e1]")
2658                .read_font_matrix()
2659                .unwrap()
2660                .matrix,
2661            FontMatrix::from_elements([
2662                Fixed::from_i32(2),
2663                Fixed::ZERO,
2664                Fixed::ZERO,
2665                Fixed::ONE,
2666                Fixed::from_bits(1000),
2667                Fixed::from_bits(20000)
2668            ])
2669        );
2670        // Matrix with modified upem
2671        assert_eq!(
2672            Parser::new(b"[0.001 0 0 0.0005 0.0 0.0]")
2673                .read_font_matrix()
2674                .unwrap(),
2675            ScaledFontMatrix {
2676                matrix: FontMatrix::from_elements([
2677                    Fixed::from_i32(2),
2678                    Fixed::ZERO,
2679                    Fixed::ZERO,
2680                    Fixed::ONE,
2681                    Fixed::from_i32(0),
2682                    Fixed::from_i32(0)
2683                ]),
2684                scale: 2000,
2685            }
2686        );
2687    }
2688
2689    #[test]
2690    fn parse_subrs() {
2691        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
2692        let mut parser = Parser::new(&dicts.private);
2693        let mut subrs = None;
2694        while let Some(token) = parser.next() {
2695            if let Token::Name(b"Subrs") = token {
2696                subrs = parser.read_subrs(4);
2697                break;
2698            }
2699        }
2700        let mut subrs = subrs.unwrap();
2701        // The decrypted subroutines extracted from FreeType
2702        let expected_subrs: [&[u8]; 5] = [
2703            &[142, 139, 12, 16, 12, 17, 12, 17, 12, 33, 11],
2704            &[139, 140, 12, 16, 11],
2705            &[139, 141, 12, 16, 11],
2706            &[11],
2707            &[140, 142, 12, 16, 12, 17, 10, 11],
2708        ];
2709        assert_eq!(subrs.index.len(), expected_subrs.len());
2710        assert!(subrs.is_dense);
2711        // These subrs are densely allocated but check binary search mode
2712        // as well
2713        for is_dense in [true, false] {
2714            subrs.is_dense = is_dense;
2715            for (idx, &expected) in expected_subrs.iter().enumerate() {
2716                let subr = subrs.get(idx as u32).unwrap();
2717                assert_eq!(subr, expected);
2718            }
2719        }
2720    }
2721
2722    #[test]
2723    fn parse_empty_array_subrs() {
2724        let subrs = Parser::new(b"[ ]").read_subrs(4).unwrap();
2725        assert!(subrs.data.is_empty());
2726        assert!(subrs.index.is_empty());
2727    }
2728
2729    #[test]
2730    fn parse_empty_subrs() {
2731        let subrs = Parser::new(b" 0 array\nND\n").read_subrs(4).unwrap();
2732        assert!(subrs.data.is_empty());
2733        assert!(subrs.index.is_empty());
2734    }
2735
2736    #[test]
2737    fn parse_malformed_subrs() {
2738        assert!(Parser::new(b" 20 \nND\n").read_subrs(4).is_none());
2739    }
2740
2741    #[test]
2742    fn parse_subrs_duplicate_def() {
2743        // Two definitions of subrs.. we want to keep the first
2744        // one which has two entries at 5 and 42
2745        let private = b"/Subrs 2 array dup 5 2 RD nd NP dup 42 2 RD ab NP ND\n/Subrs 1 array dup 0 2 RD xy NP ND /CharStrings 0";
2746        let font = Type1Font::from_dicts(b"", private).unwrap();
2747        assert_eq!(font.subrs.index.len(), 2);
2748        assert_eq!(font.subrs.index[0].0, 5);
2749        assert_eq!(font.subrs.index[1].0, 42);
2750    }
2751
2752    #[test]
2753    fn parse_charstrings() {
2754        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
2755        let mut parser = Parser::new(&dicts.private);
2756        let mut charstrings = None;
2757        while let Some(token) = parser.next() {
2758            if let Token::Name(b"CharStrings") = token {
2759                charstrings = parser.read_charstrings(4);
2760                break;
2761            }
2762        }
2763        let charstrings = charstrings.unwrap();
2764        assert_eq!(charstrings.num_glyphs(), 9);
2765        assert!(charstrings.orig_notdef_index.is_none());
2766        let expected_names = [
2767            ".notdef",
2768            "H",
2769            "f",
2770            "i",
2771            "x",
2772            "f_f.liga",
2773            "f_f_i.liga",
2774            "f_i.liga",
2775            "H.c2sc",
2776        ];
2777        let names = (0..charstrings.num_glyphs())
2778            .map(|idx| charstrings.name(idx).unwrap())
2779            .collect::<Vec<_>>();
2780        assert_eq!(names, expected_names);
2781        // Prefix (up to 8 bytes), extracted from FreeType
2782        let expected_charstrings_prefix: [&[u8]; 9] = [
2783            &[139, 248, 236, 13, 14],
2784            &[177, 249, 173, 13, 139, 4, 247, 183],
2785            &[166, 248, 5, 13, 139, 4, 247, 201],
2786            &[162, 247, 212, 13, 247, 30, 249, 16],
2787            &[144, 248, 214, 13, 139, 4, 247, 130],
2788            &[166, 249, 88, 13, 139, 4, 247, 181],
2789            &[166, 250, 126, 13, 139, 4, 247, 181],
2790            &[166, 249, 43, 13, 139, 4, 247, 181],
2791            &[180, 249, 60, 13, 139, 4, 247, 141],
2792        ];
2793        for (idx, &expected) in expected_charstrings_prefix.iter().enumerate() {
2794            let charstring = charstrings.get(idx as u32).unwrap();
2795            assert_eq!(&charstring[..expected.len()], expected);
2796        }
2797    }
2798
2799    #[test]
2800    fn parse_charstrings_duplicate_def() {
2801        // Two definitions of charstrings.. we want to keep the first
2802        // one which has three glyphs: .notdef, H and I
2803        let private = b"/CharStrings 2 /.notdef 2 RD nd ND /H 2 RD ab ND /I 2 RD cd ND def\n/CharStrings 1 /B 2 RD xy ND def";
2804        let font = Type1Font::from_dicts(b"", private).unwrap();
2805        assert_eq!(font.num_glyphs(), 3);
2806        assert_eq!(font.charstrings.name(0).unwrap(), ".notdef");
2807        assert_eq!(font.charstrings.name(1).unwrap(), "H");
2808        assert_eq!(font.charstrings.name(2).unwrap(), "I");
2809    }
2810
2811    #[test]
2812    fn parse_charstrings_missing_notdef() {
2813        let mut parser = Parser::new(b"1 /H 2 RD ab ND /B 2 RD xy ND");
2814        let charstrings = parser.read_charstrings(-1).unwrap();
2815        assert_eq!(charstrings.num_glyphs(), 3);
2816        assert_eq!(charstrings.orig_notdef_index, Some(2));
2817        let expected_glyphs: &[(&str, &[u8])] =
2818            &[(".notdef", NOTDEF_GLYPH), ("B", b"xy"), ("H", b"ab")];
2819        check_charstrings(&charstrings, expected_glyphs);
2820        let mut font = Type1Font::empty();
2821        font.charstrings = charstrings;
2822        assert_eq!(font.remapped_gid(GlyphId::new(0)), GlyphId::new(2));
2823        assert_eq!(font.remapped_gid(GlyphId::new(1)), GlyphId::new(1));
2824        assert_eq!(font.remapped_gid(GlyphId::new(2)), GlyphId::new(0));
2825    }
2826
2827    #[test]
2828    fn parse_charstrings_notdef_moved() {
2829        let mut parser = Parser::new(b"1 /H 2 RD ab ND /.notdef 2 RD nd ND /B 2 RD xy ND");
2830        let charstrings = parser.read_charstrings(-1).unwrap();
2831        assert_eq!(charstrings.num_glyphs(), 3);
2832        assert_eq!(charstrings.orig_notdef_index, Some(1));
2833        let expected_glyphs: &[(&str, &[u8])] = &[(".notdef", b"nd"), ("H", b"ab"), ("B", b"xy")];
2834        check_charstrings(&charstrings, expected_glyphs);
2835        let mut font = Type1Font::empty();
2836        font.charstrings = charstrings;
2837        assert_eq!(font.remapped_gid(GlyphId::new(0)), GlyphId::new(1));
2838        assert_eq!(font.remapped_gid(GlyphId::new(1)), GlyphId::new(0));
2839        assert_eq!(font.remapped_gid(GlyphId::new(2)), GlyphId::new(2));
2840    }
2841
2842    #[track_caller]
2843    fn check_charstrings(charstrings: &Charstrings, expected_glyphs: &[(&str, &[u8])]) {
2844        for (idx, expected) in expected_glyphs.iter().enumerate() {
2845            let idx = idx as u32;
2846            let name = charstrings.name(idx).unwrap();
2847            let data = charstrings.get(idx).unwrap();
2848            assert_eq!((name, data), *expected);
2849        }
2850    }
2851
2852    #[test]
2853    fn parse_weight_vector() {
2854        let mut parser = Parser::new(b"[0 0.125, 1.25 -0.87]");
2855        let weights = parser
2856            .read_weight_vector()
2857            .unwrap()
2858            .drain(..)
2859            .map(|w| w.to_f32())
2860            .collect::<Vec<_>>();
2861        assert_eq!(weights, &[0.0, 0.125, 1.25, -0.8699951]);
2862    }
2863
2864    #[test]
2865    fn parse_type1_font_pfb() {
2866        check_type1_font(
2867            &Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB).unwrap(),
2868        );
2869    }
2870
2871    #[test]
2872    fn parse_type1_font_pfa() {
2873        check_type1_font(
2874            &Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap(),
2875        );
2876    }
2877
2878    #[track_caller]
2879    fn check_type1_font(font: &Type1Font) {
2880        assert_eq!(font.name(), Some("NotoSerif-Regular"));
2881        assert_eq!(
2882            font.version(),
2883            Some(
2884                "2.007; ttfautohint (v1.8) -l 8 -r 50 -G 200 -x 14 -D latn -f none -a qsq -X \"\""
2885            )
2886        );
2887        assert_eq!(
2888            font.notice(),
2889            Some("Copyright 2015-2021 Google LLC. All Rights Reserved.")
2890        );
2891        assert_eq!(font.full_name(), Some("Noto Serif Regular"));
2892        assert_eq!(font.family_name(), Some("Noto Serif"));
2893        assert_eq!(font.weight(), Some("Book"));
2894        assert_eq!(font.italic_angle(), 0);
2895        assert!(!font.is_fixed_pitch());
2896        assert_eq!(font.underline_position(), -125);
2897        assert_eq!(font.underline_thickness(), 50);
2898        assert_eq!(
2899            font.bbox(),
2900            BoundingBox {
2901                x_min: Fixed::from_i32(5),
2902                y_min: Fixed::ZERO,
2903                x_max: Fixed::from_i32(989),
2904                y_max: Fixed::from_i32(775)
2905            }
2906        );
2907        assert_eq!(font.num_glyphs(), 9);
2908        assert_eq!(font.subrs.index.len(), 5);
2909        assert_eq!(
2910            font.matrix,
2911            ScaledFontMatrix {
2912                matrix: FontMatrix::IDENTITY,
2913                scale: 1000
2914            }
2915        );
2916        assert!(font
2917            .glyph_names()
2918            .map(|(_, name)| name)
2919            .take(4)
2920            .eq([".notdef", "H", "f", "i"].into_iter()))
2921    }
2922
2923    #[test]
2924    fn parses_lowercase_is_fixed_pitch() {
2925        let dicts = RawDicts::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
2926        let mut base = dicts.base.to_vec();
2927        base.extend_from_slice(b"\n/isFixedPitch true def\n");
2928        let font = Type1Font::from_dicts(&base, &dicts.private).unwrap();
2929        assert!(font.is_fixed_pitch());
2930    }
2931
2932    #[test]
2933    fn parse_encoding() {
2934        assert!(matches!(
2935            Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA)
2936                .unwrap()
2937                .encoding,
2938            Some(RawEncoding::Predefined(PredefinedEncoding::Standard)),
2939        ));
2940    }
2941
2942    #[test]
2943    fn parse_known_encodings() {
2944        for (blob, encoding) in [
2945            (
2946                "StandardEncoding",
2947                RawEncoding::Predefined(PredefinedEncoding::Standard),
2948            ),
2949            (
2950                "ExpertEncoding",
2951                RawEncoding::Predefined(PredefinedEncoding::Expert),
2952            ),
2953            (
2954                "ISOLatin1Encoding",
2955                RawEncoding::Predefined(PredefinedEncoding::IsoLatin1),
2956            ),
2957        ] {
2958            assert_eq!(
2959                Parser::new(blob.as_bytes())
2960                    .read_encoding(&Charstrings::default())
2961                    .unwrap(),
2962                encoding
2963            );
2964        }
2965    }
2966
2967    #[test]
2968    fn parse_custom_dense_encoding() {
2969        let mut map = Vec::new();
2970        map.resize(256, ".notdef".to_string());
2971        let mut parser = Parser::new(b"[/.notdef /A /b /.notdef /comma /at]");
2972        parser.read_dense_encoding(|idx, name| {
2973            map[idx as usize] = name.to_string();
2974        });
2975        for (ch, entry) in map.iter().enumerate() {
2976            let expected = match ch {
2977                1 => "A",
2978                2 => "b",
2979                4 => "comma",
2980                5 => "at",
2981                _ => ".notdef",
2982            };
2983            assert_eq!(entry, expected);
2984        }
2985    }
2986
2987    #[test]
2988    fn parse_custom_sparse_encoding() {
2989        let mut map = Vec::new();
2990        map.resize(256, ".notdef".to_string());
2991        let mut parser = Parser::new(CUSTOM_SPARSE_ENCODING.as_bytes());
2992        parser.read_sparse_encoding(|idx, name| {
2993            map[idx as usize] = name.to_string();
2994        });
2995        for (ch, entry) in map.iter().enumerate() {
2996            let expected = match ch {
2997                66 => "B",
2998                97 => "a",
2999                64 => "at",
3000                44 => "comma",
3001                56 => "eight",
3002                _ => ".notdef",
3003            };
3004            assert_eq!(entry, expected);
3005        }
3006    }
3007
3008    const CUSTOM_SPARSE_ENCODING: &str = r#"
3009        array
3010        0 1 255 {1 index exch /.notdef put} for
3011        dup 66 /B put
3012        dup 97 /a put
3013        dup 64 /at put
3014        dup 44 /comma put
3015        dup 56 /eight put
3016        readonly def    
3017    "#;
3018
3019    #[test]
3020    fn eval_charstrings() {
3021        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3022        let expected_eval_prefix = [
3023            "M38,0 L329,0 L329,42 L316,42 C293,42 274,46 258,54 C242,63 234,83 234,114",
3024            "M27,0 L336,0 L336,42 L298,42 C275,42 256,46 240,54 C224,63 216,83 216,114",
3025            "M161,636 C176,636 190,641 201,650 C212,659 218,675 218,698 C218,721 212,738 201,746",
3026            "M5,0 L243,0 L243,42 L240,42 C218,42 202,44 192,50 C183,54 178,62 178,73",
3027            "M27,0 L316,0 L316,42 L298,42 C275,42 256,46 240,54 C224,63 216,83 216,114",
3028            "M27,0 L316,0 L316,42 L298,42 C275,42 256,46 240,54 C224,63 216,83 216,114",
3029            "M27,0 L316,0 L316,42 L298,42 C275,42 256,46 240,54 C224,63 216,83 216,114",
3030            "M41,0 L290,0 L290,42 L269,42 C254,42 240,45 229,52 C218,58 212,73 212,98",
3031        ];
3032        // -1 to ignore the .notdef glyph
3033        assert_eq!(font.num_glyphs() as usize - 1, expected_eval_prefix.len());
3034        let mut commands = CaptureCommandSink::default();
3035        for (gid, expected_prefix) in (1..font.num_glyphs()).zip(&expected_eval_prefix) {
3036            commands.0.clear();
3037            font.evaluate_charstring(gid.into(), &mut commands).unwrap();
3038            assert!(commands.to_svg().starts_with(expected_prefix));
3039        }
3040    }
3041
3042    #[test]
3043    fn eval_charstring_widths() {
3044        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3045        let expected_widths = [
3046            600.0, 793.0, 369.0, 320.0, 578.0, 708.0, 1002.0, 663.0, 680.0,
3047        ];
3048        let mut commands = CaptureCommandSink::default();
3049        let widths = (0..font.num_glyphs())
3050            .map(|gid| {
3051                commands.0.clear();
3052                font.evaluate_charstring(gid.into(), &mut commands)
3053                    .unwrap()
3054                    .unwrap()
3055                    .to_f32()
3056            })
3057            .collect::<Vec<_>>();
3058        assert_eq!(widths, expected_widths);
3059    }
3060
3061    #[test]
3062    fn csctx_seac_components() {
3063        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3064        // Standard encoding for 'x' and 'i'
3065        let x_code = 120;
3066        let i_code = 105;
3067        let [x_data, i_data] = font.seac_components(x_code, i_code).unwrap();
3068        let name_to_gid = |name| {
3069            font.glyph_names()
3070                .find_map(|(gid, gname)| (name == gname).then_some(gid.to_u32()))
3071                .unwrap()
3072        };
3073        assert_eq!(x_data, font.charstrings.get(name_to_gid("x")).unwrap());
3074        assert_eq!(i_data, font.charstrings.get(name_to_gid("i")).unwrap());
3075    }
3076
3077    #[test]
3078    fn csctx_subrs() {
3079        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3080        assert!(!font.subrs.index.is_empty());
3081        for subr_idx in 0..font.subrs.index.len() {
3082            assert_eq!(
3083                font.subrs.get(subr_idx as u32).unwrap(),
3084                font.subr(subr_idx as _).unwrap()
3085            )
3086        }
3087    }
3088
3089    #[test]
3090    fn encoding_mapping() {
3091        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3092        let encoding = font.encoding().unwrap();
3093        let expected = [
3094            // code, gid, name
3095            (0, 0, ".notdef"),
3096            (72, 1, "H"),
3097            (102, 2, "f"),
3098            (105, 3, "i"),
3099            (120, 4, "x"),
3100        ];
3101        for (code, gid, name) in expected {
3102            assert_eq!(encoding.glyph_name(code).unwrap(), name);
3103            assert_eq!(encoding.map(code).unwrap().to_u32(), gid);
3104        }
3105    }
3106}
3107
3108#[cfg(test)]
3109mod width_only_tests {
3110    use super::*;
3111    use crate::model::glyph::outline::NullSink;
3112
3113    const FONTS: [&[u8]; 2] = [
3114        font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA,
3115        font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB,
3116    ];
3117
3118    #[test]
3119    fn the_quick_width_is_what_a_full_run_reports() {
3120        for data in FONTS {
3121            let font = Type1Font::new(data).unwrap();
3122            assert!(font.num_glyphs() > 1);
3123            // `evaluate_charstring` answers in the charstring's own space and
3124            // `evaluate_width` in design units, so the matrix goes on the
3125            // full run before the two can be compared. It maps one onto the
3126            // other unchanged in these fonts, so what this pins is the width
3127            // rather than the mapping; the CFF side has a font where the two
3128            // spaces differ.
3129            let transform = font.transform(None);
3130            for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3131                let full = font
3132                    .evaluate_charstring(gid, &mut charstring::NullSink)
3133                    .unwrap()
3134                    .map(|width| transform.transform_h_metric(width));
3135                let quick = font.evaluate_width(gid).unwrap();
3136                assert_eq!(full, quick, "glyph {gid}");
3137            }
3138        }
3139    }
3140
3141    #[test]
3142    fn the_quick_advance_is_what_drawing_reports() {
3143        // Drawing scales the width by the font matrix, and by ppem where one
3144        // is given, so this is what catches an advance that skipped either.
3145        for data in FONTS {
3146            let font = Type1Font::new(data).unwrap();
3147            for ppem in [None, Some(16.0), Some(72.0)] {
3148                for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3149                    let drawn = font.draw(gid, ppem, &mut NullSink).unwrap();
3150                    let quick = font.advance(gid, ppem).unwrap();
3151                    assert_eq!(drawn, quick, "glyph {gid} at {ppem:?}");
3152                }
3153            }
3154        }
3155    }
3156
3157    #[test]
3158    fn every_glyph_states_a_width() {
3159        // A Type 1 charstring must open with hsbw or sbw, so one that
3160        // reports nothing is malformed rather than merely silent.
3161        let font = Type1Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA).unwrap();
3162        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3163            assert!(font.evaluate_width(gid).unwrap().is_some(), "glyph {gid}");
3164        }
3165    }
3166}
3167
3168#[cfg(test)]
3169mod extents_tests {
3170    use super::*;
3171    use crate::model::glyph::outline::PathSink;
3172
3173    const FONTS: [&[u8]; 2] = [
3174        font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA,
3175        font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB,
3176    ];
3177
3178    /// Collects the same box from the other side, through a pen.
3179    #[derive(Default)]
3180    struct BoundsPen(Option<[f32; 4]>);
3181
3182    impl BoundsPen {
3183        fn add(&mut self, x: f32, y: f32) {
3184            self.0 = Some(match self.0 {
3185                Some([a, b, c, d]) => [a.min(x), b.min(y), c.max(x), d.max(y)],
3186                None => [x, y, x, y],
3187            });
3188        }
3189    }
3190
3191    impl PathSink for BoundsPen {
3192        fn move_to(&mut self, x: f32, y: f32) {
3193            self.add(x, y);
3194        }
3195        fn line_to(&mut self, x: f32, y: f32) {
3196            self.add(x, y);
3197        }
3198        fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
3199            self.add(cx, cy);
3200            self.add(x, y);
3201        }
3202        fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
3203            self.add(cx0, cy0);
3204            self.add(cx1, cy1);
3205            self.add(x, y);
3206        }
3207        fn close(&mut self) {}
3208    }
3209
3210    fn corners(b: BoundingBox<f32>) -> [f32; 4] {
3211        [b.x_min, b.y_min, b.x_max, b.y_max]
3212    }
3213
3214    #[test]
3215    fn the_extents_are_the_box_drawing_stays_within() {
3216        // The same pipeline either way, so the two agree exactly. A
3217        // difference would mean the box was measured somewhere the drawing
3218        // was not, which is what transforming a finished box would do.
3219        for data in FONTS {
3220            let font = Type1Font::new(data).unwrap();
3221            for ppem in [None, Some(16.0), Some(72.0)] {
3222                let mut drew = 0;
3223                for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3224                    let mut pen = BoundsPen::default();
3225                    font.draw(gid, ppem, &mut pen).unwrap();
3226                    let measured = font.extents(gid, ppem).unwrap();
3227                    assert_eq!(measured.map(corners), pen.0, "glyph {gid} at {ppem:?}");
3228                    drew += pen.0.is_some() as u32;
3229                }
3230                assert!(drew > 1, "almost nothing drew, so this proves little");
3231            }
3232        }
3233    }
3234
3235    #[test]
3236    fn the_exact_box_and_the_sized_one_agree_at_no_size() {
3237        // Both apply the matrix; only the size and the number type differ.
3238        let font = Type1Font::new(FONTS[0]).unwrap();
3239        let mut checked = 0;
3240        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3241            let exact = font.evaluate_extents(gid).unwrap();
3242            let sized = font.extents(gid, None).unwrap();
3243            assert_eq!(
3244                exact.map(|b| [
3245                    b.x_min.to_f32(),
3246                    b.y_min.to_f32(),
3247                    b.x_max.to_f32(),
3248                    b.y_max.to_f32()
3249                ]),
3250                sized.map(corners),
3251                "glyph {gid}"
3252            );
3253            checked += exact.is_some() as u32;
3254        }
3255        assert!(checked > 1, "almost nothing drew, so this proves little");
3256    }
3257
3258    #[test]
3259    fn a_size_scales_the_box() {
3260        // `evaluate_extents` measures before the matrix and any size;
3261        // `extents` measures after both. This font's matrix maps its
3262        // charstring space onto design units unchanged, so what separates
3263        // the two here is the size. A matrix that does more than that is
3264        // covered where one exists, on the CFF side.
3265        let font = Type1Font::new(FONTS[0]).unwrap();
3266        let mut checked = 0;
3267        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
3268            let Some(unscaled) = font.extents(gid, None).unwrap() else {
3269                continue;
3270            };
3271            let scaled = font.extents(gid, Some(16.0)).unwrap().unwrap();
3272            let factor = 16.0 / font.upem() as f32;
3273            for (a, b) in corners(scaled).iter().zip(corners(unscaled)) {
3274                assert!(
3275                    (a - b * factor).abs() < 0.05,
3276                    "glyph {gid}: {a} against {}",
3277                    b * factor
3278                );
3279            }
3280            checked += 1;
3281        }
3282        assert!(checked > 1, "almost nothing drew, so this proves little");
3283    }
3284
3285    #[test]
3286    fn a_glyph_that_draws_nothing_has_no_extents() {
3287        // A box of no size at the origin would say something different from
3288        // drawing nothing at all.
3289        let font = Type1Font::new(FONTS[0]).unwrap();
3290        let empty = (0..font.num_glyphs())
3291            .map(GlyphId::new)
3292            .find(|gid| font.extents(*gid, None).unwrap().is_none());
3293        let gid = empty.expect("this font has no empty glyph to check");
3294        assert!(font.evaluate_extents(gid).unwrap().is_none());
3295    }
3296}
3297
3298#[cfg(test)]
3299pub(crate) mod multiple_master_tests {
3300    use super::*;
3301    use crate::model::glyph::outline::PathElement;
3302    use alloc::{format, vec};
3303
3304    /// Encodes `value` as a Type 1 charstring number.
3305    fn num(value: i32) -> Vec<u8> {
3306        match value {
3307            -107..=107 => vec![(value + 139) as u8],
3308            108..=1131 => {
3309                let v = value - 108;
3310                vec![(v / 256 + 247) as u8, (v % 256) as u8]
3311            }
3312            -1131..=-108 => {
3313                let v = -value - 108;
3314                vec![(v / 256 + 251) as u8, (v % 256) as u8]
3315            }
3316            _ => {
3317                let mut bytes = vec![255];
3318                bytes.extend_from_slice(&value.to_be_bytes());
3319                bytes
3320            }
3321        }
3322    }
3323
3324    /// Builds a charstring from numbers and operators, where an operator is
3325    /// given as its bytes.
3326    fn charstring(parts: &[&[i32]]) -> Vec<u8> {
3327        let mut bytes = Vec::new();
3328        for part in parts {
3329            match part {
3330                [op] if *op < 0 => bytes.push((-op) as u8),
3331                [12, op] if *op < 0 => bytes.extend_from_slice(&[12, (-op) as u8]),
3332                values => values.iter().for_each(|&v| bytes.extend(num(v))),
3333            }
3334        }
3335        bytes
3336    }
3337
3338    const HSBW: &[i32] = &[-13];
3339    const RMOVETO: &[i32] = &[-21];
3340    const RLINETO: &[i32] = &[-5];
3341    const CLOSEPATH: &[i32] = &[-9];
3342    const ENDCHAR: &[i32] = &[-14];
3343    const CALLOTHERSUBR: &[i32] = &[12, -16];
3344    const POP: &[i32] = &[12, -17];
3345
3346    /// Reads the font that [`pfa_with_blend`] makes.
3347    fn font_with_blend(blend: &str) -> Option<Type1Font> {
3348        Type1Font::new(&pfa_with_blend(blend)).ok()
3349    }
3350
3351    /// Returns a PFA font with `blend` in place of the blend entries of its
3352    /// font dictionary.
3353    ///
3354    /// Glyph 1 moves to x = 100 + 200 * w1, where w1 is the weight of the
3355    /// second master, then draws a triangle.
3356    pub(crate) fn pfa_with_blend(blend: &str) -> Vec<u8> {
3357        let base = format!(
3358            "%!PS-AdobeFont-1.0: Test\n/FontName /Test def \
3359             /FontMatrix [0.001 0 0 0.001 0 0] readonly def {blend}\n\
3360             currentfile eexec\n"
3361        );
3362        let notdef = charstring(&[&[0, 500], HSBW, ENDCHAR]);
3363        let glyph = charstring(&[
3364            &[0, 500],
3365            HSBW,
3366            &[100, 50, 200, 0, 4, 15],
3367            CALLOTHERSUBR,
3368            POP,
3369            POP,
3370            RMOVETO,
3371            &[300, 0],
3372            RLINETO,
3373            &[0, 300],
3374            RLINETO,
3375            CLOSEPATH,
3376            ENDCHAR,
3377        ]);
3378        let mut private = b"/lenIV -1 def /CharStrings 2 dict dup begin\n".to_vec();
3379        for (name, bytes) in [("/.notdef", notdef), ("/a", glyph)] {
3380            private.extend_from_slice(format!("{name} {} RD ", bytes.len()).as_bytes());
3381            private.extend_from_slice(&bytes);
3382            private.extend_from_slice(b" ND\n");
3383        }
3384        private.extend_from_slice(b"end");
3385        // Encrypted as eexec data, after four bytes of padding, and written
3386        // as hex.
3387        let mut seed = EEXEC_SEED;
3388        let mut pfa = base.into_bytes();
3389        for plain in [0u8; 4].iter().chain(&private) {
3390            let cipher = (*plain as u32 ^ (seed >> 8)) as u8;
3391            seed = (cipher as u32)
3392                .wrapping_add(seed)
3393                .wrapping_mul(52845)
3394                .wrapping_add(22719)
3395                & 0xFFFF;
3396            pfa.extend_from_slice(format!("{cipher:02x}").as_bytes());
3397        }
3398        pfa
3399    }
3400
3401    pub(crate) const ONE_AXIS: &str = "/BlendAxisTypes [/Weight] def \
3402        /BlendDesignPositions [[0] [1]] def \
3403        /BlendDesignMap [[[100 0] [900 1]]] def \
3404        /WeightVector [0.75 0.25] def";
3405
3406    fn bbox(font: &Type1Font) -> [f32; 4] {
3407        let b = font.bbox();
3408        [b.x_min, b.y_min, b.x_max, b.y_max].map(|v| v.to_f32())
3409    }
3410
3411    // Every box is rounded to whole units, halves away from zero.
3412    #[test]
3413    fn boxes_are_rounded() {
3414        let font = font_with_blend("/FontBBox {-10.4 -20.5 1000.5 900.25} readonly def").unwrap();
3415        assert_eq!(bbox(&font), [-10.0, -21.0, 1001.0, 900.0]);
3416    }
3417
3418    // A bound that rounds past the largest fixed value saturates instead of
3419    // overflowing.
3420    #[test]
3421    fn box_rounding_saturates() {
3422        let font = font_with_blend("/FontBBox [-32768 0 32767.5 900] def").unwrap();
3423        assert_eq!(font.bbox().x_max, Fixed::MAX);
3424        assert_eq!(font.bbox().x_min, Fixed::from_i32(-32768));
3425    }
3426
3427    // The /Blend dictionary holds a box for each master, and master 0's
3428    // replaces the font's own.
3429    #[test]
3430    fn box_is_master_zeros() {
3431        let font = font_with_blend(&format!(
3432            "{ONE_AXIS} /FontBBox {{-157 -257 1194 872}} readonly def \
3433             /Blend 3 dict dup begin \
3434             /FontBBox {{{{-55 -112}} {{-261 -262}} {{424.4 1156}} {{811 970}}}} def \
3435             end def"
3436        ))
3437        .unwrap();
3438        assert_eq!(bbox(&font), [-55.0, -261.0, 424.0, 811.0]);
3439        let bracketed = font_with_blend(&format!(
3440            "{ONE_AXIS} /Blend 3 dict dup begin \
3441             /FontBBox [[-55 -112] [-261 -262] [424 1156] [811 970]] def end def"
3442        ))
3443        .unwrap();
3444        assert_eq!(bbox(&bracketed), [-55.0, -261.0, 424.0, 811.0]);
3445    }
3446
3447    // The /Blend dictionary's font info holds a value for each master, and
3448    // the font keeps its own.
3449    #[test]
3450    fn font_info_keeps_its_own_values() {
3451        let font = font_with_blend(&format!(
3452            "{ONE_AXIS} /ItalicAngle -12 def /isFixedPitch true def \
3453             /UnderlinePosition -100 def /UnderlineThickness 50 def \
3454             /Blend 3 dict dup begin /FontInfo 4 dict dup begin \
3455             /ItalicAngle [-12 0] def /isFixedPitch [false false] def \
3456             /UnderlinePosition [-80 -120] def /UnderlineThickness [40 60] def \
3457             end def end def"
3458        ))
3459        .unwrap();
3460        assert_eq!(font.italic_angle(), -12);
3461        assert!(font.is_fixed_pitch());
3462        assert_eq!(font.underline_position(), -100);
3463        assert_eq!(font.underline_thickness(), 50);
3464    }
3465
3466    fn first_move(instance: Type1Instance) -> f32 {
3467        let mut path = Vec::<PathElement>::new();
3468        instance.draw(GlyphId::new(1), None, &mut path).unwrap();
3469        match path[0] {
3470            PathElement::MoveTo { x, .. } => x,
3471            _ => panic!("expected a move"),
3472        }
3473    }
3474
3475    #[test]
3476    fn reads_the_design_space() {
3477        let font = font_with_blend(ONE_AXIS).unwrap();
3478        let mm = font.multiple_master().unwrap();
3479        assert_eq!(mm.num_masters(), 2);
3480        let [axis] = mm.axes() else {
3481            panic!("expected one axis")
3482        };
3483        assert_eq!(axis.name(), Some("Weight"));
3484        assert_eq!((axis.min_design(), axis.max_design()), (100, 900));
3485        let mut blend = [Fixed::ZERO];
3486        mm.default_blend(&mut blend);
3487        assert_eq!(blend, [Fixed::from_f64(0.25)]);
3488        assert_eq!(axis.blend_to_design(blend[0]), 300);
3489    }
3490
3491    #[test]
3492    fn draws_with_a_blend_of_the_masters() {
3493        let font = font_with_blend(ONE_AXIS).unwrap();
3494        let mm = font.multiple_master().unwrap();
3495        // The font's own weights.
3496        assert_eq!(first_move(font.default_instance()), 150.0);
3497        let mut blend = [Fixed::ZERO];
3498        let mut weights = [Fixed::ZERO; 2];
3499        for (design, x) in [(100.0, 100.0), (500.0, 200.0), (900.0, 300.0)] {
3500            mm.design_to_blend(&[Fixed::from_f64(design)], &mut blend);
3501            mm.blend_to_weights(&blend, &mut weights);
3502            assert_eq!(first_move(font.instance(&weights)), x, "{design}");
3503        }
3504    }
3505
3506    // Blends that FreeType sets aside leave an ordinary font, whose glyphs
3507    // fail where they blend.
3508    #[test]
3509    fn inconsistent_blends_are_set_aside() {
3510        for blend in [
3511            // Three masters cannot sit at the corners of one axis.
3512            "/BlendDesignPositions [[0] [1] [0.5]] def \
3513             /BlendDesignMap [[[100 0] [900 1]]] def \
3514             /WeightVector [0.5 0.25 0.25] def",
3515            // No design map.
3516            "/BlendDesignPositions [[0] [1]] def /WeightVector [0.75 0.25] def",
3517            // Only weights, as in a font made from one instance.
3518            "/WeightVector [0.75 0.25] def",
3519        ] {
3520            let font = font_with_blend(blend).unwrap();
3521            assert!(font.multiple_master().is_none(), "{blend}");
3522            let mut path = Vec::<PathElement>::new();
3523            assert!(font.draw(GlyphId::new(1), None, &mut path).is_err());
3524        }
3525    }
3526
3527    // Counts that disagree make FreeType refuse the font.
3528    #[test]
3529    fn conflicting_counts_refuse_the_font() {
3530        for blend in [
3531            "/BlendDesignPositions [[0] [1]] def /WeightVector [0.5 0.25 0.25] def",
3532            "/BlendAxisTypes [/Weight /Width] def /BlendDesignPositions [[0] [1]] def",
3533            "/BlendDesignMap [[[100 0] [900 1]]] def /BlendDesignMap [[[100 0] [900 1]]] def",
3534            "/BlendAxisTypes [/A /B /C /D /E] def",
3535        ] {
3536            assert!(font_with_blend(blend).is_none(), "{blend}");
3537        }
3538    }
3539
3540    /// The design space of a font with two axes, each mapping 50 to 1450,
3541    /// whose default is the last master.
3542    fn two_axes() -> MultipleMaster {
3543        let axis = |name: &str| MasterAxis {
3544            name: Some(name.into()),
3545            design_points: vec![50, 1450],
3546            blend_points: vec![Fixed::ZERO, Fixed::ONE],
3547        };
3548        MultipleMaster {
3549            axes: vec![axis("Weight"), axis("Width")],
3550            num_masters: 4,
3551            default_weights: vec![Fixed::ZERO, Fixed::ZERO, Fixed::ZERO, Fixed::ONE],
3552        }
3553    }
3554
3555    // The blends and weights FreeType computes for these design coordinates
3556    // in a font with this design space.
3557    #[test]
3558    fn design_coordinates_convert_as_in_freetype() {
3559        let mm = two_axes();
3560        for (design, blend, weights) in [
3561            (
3562                &[471.5, 819.4][..],
3563                [19754, 35998],
3564                [20635, 8903, 25147, 10851],
3565            ),
3566            (
3567                &[470.49, 820.51],
3568                [19661, 36092],
3569                [20611, 8833, 25264, 10828],
3570            ),
3571            (&[1000.0, 333.0], [44471, 13248], [16807, 35481, 4258, 8990]),
3572            (&[-100.0, 2000.0], [0, 65536], [0, 0, 65536, 0]),
3573            // The missing axis takes (1450 - 50) / 2 = 700.
3574            (&[300.0], [11703, 30427], [28839, 6270, 24994, 5433]),
3575        ] {
3576            let design: Vec<_> = design
3577                .iter()
3578                .map(|v| Fixed::from_bits((v * 65536.0) as i32))
3579                .collect();
3580            let mut actual_blend = [Fixed::ZERO; 2];
3581            mm.design_to_blend(&design, &mut actual_blend);
3582            assert_eq!(actual_blend.map(Fixed::to_bits), blend, "{design:?}");
3583            let mut actual_weights = [Fixed::ZERO; 4];
3584            mm.blend_to_weights(&actual_blend, &mut actual_weights);
3585            assert_eq!(actual_weights.map(Fixed::to_bits), weights, "{design:?}");
3586        }
3587        let mut default = [Fixed::ZERO; 2];
3588        mm.default_blend(&mut default);
3589        assert_eq!(default, [Fixed::ONE; 2]);
3590        assert!(mm
3591            .axes()
3592            .iter()
3593            .all(|axis| axis.blend_to_design(Fixed::ONE) == 1450));
3594    }
3595
3596    // Between two points that are not the first, FreeType's interpolation
3597    // leaves out the blend at the lower point.
3598    #[test]
3599    fn three_point_maps_interpolate_as_in_freetype() {
3600        let axis = MasterAxis {
3601            name: None,
3602            design_points: vec![0, 500, 1000],
3603            blend_points: vec![Fixed::ZERO, Fixed::from_f64(0.6), Fixed::ONE],
3604        };
3605        assert_eq!(axis.design_to_blend(250), Fixed::from_f64(0.3));
3606        assert_eq!(axis.design_to_blend(500), Fixed::from_f64(0.6));
3607        // The specification gives 0.8.
3608        assert_eq!(axis.design_to_blend(750), Fixed::from_f64(0.2));
3609        assert_eq!(axis.design_to_blend(2000), Fixed::ONE);
3610    }
3611
3612    // Design coordinates round to whole numbers, a half away from zero.
3613    #[test]
3614    fn design_coordinates_round_away_from_zero() {
3615        let axis = MasterAxis {
3616            name: None,
3617            design_points: vec![-10, 10],
3618            blend_points: vec![Fixed::ZERO, Fixed::ONE],
3619        };
3620        let mm = MultipleMaster {
3621            axes: vec![axis],
3622            num_masters: 2,
3623            default_weights: vec![Fixed::ONE, Fixed::ZERO],
3624        };
3625        let mut blend = [Fixed::ZERO];
3626        for (design, rounded) in [(0.5, 1), (-0.5, -1), (0.49, 0), (-1.5, -2)] {
3627            mm.design_to_blend(&[Fixed::from_f64(design)], &mut blend);
3628            assert_eq!(blend[0], mm.axes()[0].design_to_blend(rounded), "{design}");
3629        }
3630    }
3631
3632    // A map can span every design coordinate without overflowing.
3633    #[test]
3634    fn widest_design_maps_convert() {
3635        let axis = MasterAxis {
3636            name: None,
3637            design_points: vec![i32::MIN, i32::MAX],
3638            blend_points: vec![Fixed::ZERO, Fixed::ONE],
3639        };
3640        assert_eq!(axis.design_to_blend(0), Fixed::from_f64(0.5));
3641        assert_eq!(axis.blend_to_design(Fixed::from_f64(0.5)), 0);
3642        assert_eq!(axis.blend_to_design(Fixed::ONE), i32::MAX);
3643        assert_eq!(axis.blend_to_design(Fixed::ZERO), i32::MIN);
3644        let mm = MultipleMaster {
3645            axes: vec![axis],
3646            num_masters: 2,
3647            default_weights: vec![Fixed::from_f64(0.5), Fixed::from_f64(0.5)],
3648        };
3649        // A missing coordinate is half the range, which is beyond the map.
3650        let mut blend = [Fixed::ZERO];
3651        mm.design_to_blend(&[], &mut blend);
3652        assert_eq!(blend[0], Fixed::ONE);
3653        let font = font_with_blend(
3654            "/BlendAxisTypes [/Weight] def /BlendDesignPositions [[0] [1]] def              /BlendDesignMap [[[-2147483648 0] [2147483647 1]]] def              /WeightVector [0.5 0.5] def",
3655        )
3656        .unwrap();
3657        assert!(font.multiple_master().is_some());
3658    }
3659}