1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use super::{
    cff, glyf, Context, Error, NormalizedCoord, Pen, Result, Size, UniqueId, VariationSetting,
};

#[cfg(feature = "hinting")]
use super::Hinting;

use core::borrow::Borrow;
use read_fonts::{
    types::{Fixed, GlyphId},
    TableProvider,
};

/// Information and adjusted metrics generated while scaling a glyph.
#[derive(Copy, Clone, Default, Debug)]
pub struct ScalerMetrics {
    /// True if the underlying glyph contains flags indicating the
    /// presence of overlapping contours or components.
    pub has_overlaps: bool,
    /// If present, an adjusted left side bearing value generated by the
    /// scaler.
    pub adjusted_lsb: Option<f32>,
    /// If present, an adjusted advance width value generated by the
    /// scaler.
    pub adjusted_advance_width: Option<f32>,
}

/// Builder for configuring a glyph scaler.
///
/// See the [module level documentation](crate::scale#building-a-scaler)
/// for more detail.
pub struct ScalerBuilder<'a> {
    context: &'a mut Context,
    cache_key: Option<UniqueId>,
    size: Size,
    #[cfg(feature = "hinting")]
    hint: Option<Hinting>,
}

impl<'a> ScalerBuilder<'a> {
    /// Creates a new builder for configuring a scaler with the given context.
    pub fn new(context: &'a mut Context) -> Self {
        context.coords.clear();
        context.variations.clear();
        Self {
            context,
            cache_key: None,
            size: Size::unscaled(),
            #[cfg(feature = "hinting")]
            hint: None,
        }
    }

    /// Sets a unique font identifier for hint state caching. Specifying `None` will
    /// disable caching.
    pub fn cache_key(mut self, key: Option<UniqueId>) -> Self {
        self.cache_key = key;
        self
    }

    /// Sets the requested font size.
    ///
    /// The default value is `Size::unscaled()` and outlines will be generated
    /// in font units.
    pub fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }

    /// Sets the hinting mode.
    ///
    /// Passing `None` will disable hinting.
    #[cfg(feature = "hinting")]
    pub fn hint(mut self, hint: Option<Hinting>) -> Self {
        self.hint = hint;
        self
    }

    /// Specifies a variation with a set of normalized coordinates.
    ///
    /// This will clear any variations specified with the variations method.
    pub fn normalized_coords<I>(self, coords: I) -> Self
    where
        I: IntoIterator,
        I::Item: Borrow<NormalizedCoord>,
    {
        self.context.variations.clear();
        self.context.coords.clear();
        self.context
            .coords
            .extend(coords.into_iter().map(|v| *v.borrow()));
        self
    }

    /// Appends the given sequence of variation settings. This will clear any
    /// variations specified as normalized coordinates.
    ///
    /// This methods accepts any type which can be converted into an iterator
    /// that yields a sequence of values that are convertible to
    /// [`VariationSetting`]. Various conversions from tuples are provided.
    ///
    /// The following are all equivalent:
    ///
    /// ```
    /// # use skrifa::{scale::*, setting::VariationSetting, Tag};
    /// # let mut context = Context::new();
    /// # let builder = context.new_scaler();
    /// // slice of VariationSetting
    /// builder.variation_settings(&[
    ///     VariationSetting::new(Tag::new(b"wgth"), 720.0),
    ///     VariationSetting::new(Tag::new(b"wdth"), 50.0),
    /// ])
    /// # ; let builder = context.new_scaler();
    /// // slice of (Tag, f32)
    /// builder.variation_settings(&[(Tag::new(b"wght"), 720.0), (Tag::new(b"wdth"), 50.0)])
    /// # ; let builder = context.new_scaler();
    /// // slice of (&str, f32)
    /// builder.variation_settings(&[("wght", 720.0), ("wdth", 50.0)])
    /// # ;
    ///
    /// ```
    ///
    /// Iterators that yield the above types are also accepted.
    pub fn variation_settings<I>(self, settings: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<VariationSetting>,
    {
        self.context.coords.clear();
        self.context
            .variations
            .extend(settings.into_iter().map(|v| v.into()));
        self
    }

    /// Builds a scaler using the currently configured settings
    /// and the specified font.
    pub fn build(mut self, font: &impl TableProvider<'a>) -> Scaler<'a> {
        self.resolve_variations(font);
        let coords = &self.context.coords[..];
        let size = self.size.ppem().unwrap_or_default();
        let outlines = if let Some(glyf) = glyf::Scaler::new(font) {
            Some(Outlines::TrueType(glyf, &mut self.context.outline_memory))
        } else {
            cff::Scaler::new(font)
                .ok()
                .and_then(|scaler| {
                    let first_subfont = scaler.subfont(0, size, coords).ok()?;
                    Some((scaler, first_subfont))
                })
                .map(|(scaler, subfont)| Outlines::PostScript(scaler, subfont))
        };
        Scaler {
            size,
            coords,
            outlines,
        }
    }

    fn resolve_variations(&mut self, font: &impl TableProvider<'a>) {
        if self.context.variations.is_empty() {
            return; // nop
        }
        let Ok(fvar) = font.fvar() else {
            return; // nop
        };
        let Ok(axes) = fvar.axes() else {
            return; // nop
        };
        let avar_mappings = font.avar().ok().map(|avar| avar.axis_segment_maps());
        let axis_count = fvar.axis_count() as usize;
        self.context.coords.clear();
        self.context
            .coords
            .resize(axis_count, NormalizedCoord::default());
        for variation in &self.context.variations {
            // To permit non-linear interpolation, iterate over all axes to ensure we match
            // multiple axes with the same tag:
            // https://github.com/PeterConstable/OT_Drafts/blob/master/NLI/UnderstandingNLI.md
            // We accept quadratic behavior here to avoid dynamic allocation and with the assumption
            // that fonts contain a relatively small number of axes.
            for (i, axis) in axes
                .iter()
                .enumerate()
                .filter(|(_, axis)| axis.axis_tag() == variation.selector)
            {
                let coord = axis.normalize(Fixed::from_f64(variation.value as f64));
                let coord = avar_mappings
                    .as_ref()
                    .and_then(|mappings| mappings.get(i).transpose().ok())
                    .flatten()
                    .map(|mapping| mapping.apply(coord))
                    .unwrap_or(coord);
                self.context.coords[i] = coord.to_f2dot14();
            }
        }
    }
}

/// Glyph scaler for a specific font and configuration.
///
/// See the [module level documentation](crate::scale#getting-an-outline)
/// for more detail.
pub struct Scaler<'a> {
    size: f32,
    coords: &'a [NormalizedCoord],
    outlines: Option<Outlines<'a>>,
}

impl<'a> Scaler<'a> {
    /// Returns the current set of normalized coordinates in use by the scaler.
    pub fn normalized_coords(&self) -> &'a [NormalizedCoord] {
        self.coords
    }

    /// Returns true if the scaler has a source for simple outlines.
    pub fn has_outlines(&self) -> bool {
        self.outlines.is_some()
    }

    /// Loads a simple outline for the specified glyph identifier and invokes the functions
    /// in the given pen for the sequence of path commands that define the outline.
    pub fn outline(&mut self, glyph_id: GlyphId, pen: &mut impl Pen) -> Result<ScalerMetrics> {
        if let Some(outlines) = &mut self.outlines {
            outlines.outline(glyph_id, self.size, self.coords, pen)
        } else {
            Err(Error::NoSources)
        }
    }
}

// Clippy doesn't like the size discrepancy between the two variants. Ignore
// for now: we'll replace this with a real cache.
#[allow(clippy::large_enum_variant)]
enum Outlines<'a> {
    TrueType(glyf::Scaler<'a>, &'a mut Vec<u8>),
    PostScript(cff::Scaler<'a>, cff::Subfont),
}

impl<'a> Outlines<'a> {
    fn outline(
        &mut self,
        glyph_id: GlyphId,
        size: f32,
        coords: &'a [NormalizedCoord],
        pen: &mut impl Pen,
    ) -> Result<ScalerMetrics> {
        match self {
            Self::TrueType(scaler, buf) => {
                let glyph = scaler.glyph(glyph_id, false)?;
                let buf_size = glyph.required_buffer_size();
                if buf.len() < buf_size {
                    buf.resize(buf_size, 0);
                }
                let memory = glyph
                    .memory_from_buffer(&mut buf[..])
                    .ok_or(Error::InsufficientMemory)?;
                let outline = scaler.outline(memory, &glyph, size, coords)?;
                outline.to_path(pen)?;
                Ok(ScalerMetrics {
                    has_overlaps: glyph.has_overlaps,
                    ..Default::default()
                })
            }
            Self::PostScript(scaler, subfont) => {
                let subfont_index = scaler.subfont_index(glyph_id);
                if subfont_index != subfont.index() {
                    *subfont = scaler.subfont(subfont_index, size, coords)?;
                }
                scaler.outline(subfont, glyph_id, coords, false, pen)?;
                // CFF does not have overlap flags and hinting never adjusts
                // horizontal metrics
                Ok(ScalerMetrics::default())
            }
        }
    }
}