1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Support for applying embedded hinting instructions.

use super::{
    autohint, cff,
    glyf::{self, FreeTypeScaler},
    pen::PathStyle,
    AdjustedMetrics, DrawError, GlyphStyles, Hinting, LocationRef, NormalizedCoord,
    OutlineCollectionKind, OutlineGlyph, OutlineGlyphCollection, OutlineKind, OutlinePen, Size,
};
use crate::alloc::{boxed::Box, vec::Vec};

/// Configuration settings for a hinting instance.
#[derive(Clone, Default, Debug)]
pub struct HintingOptions {
    /// Specifies the hinting engine to use.
    ///
    /// Defaults to [`Engine::AutoFallback`].
    pub engine: Engine,
    /// Defines the properties of the intended target of a hinted outline.
    ///
    /// Defaults to a target with [`SmoothMode::Normal`] which is equivalent
    /// to `FT_RENDER_MODE_NORMAL` in FreeType.
    pub target: Target,
}

impl From<Target> for HintingOptions {
    fn from(value: Target) -> Self {
        Self {
            engine: Engine::AutoFallback,
            target: value,
        }
    }
}

/// Specifies the backend to use when applying hints.
#[derive(Clone, Default, Debug)]
pub enum Engine {
    /// The TrueType or PostScript interpreter.
    Interpreter,
    /// The automatic hinter that performs just-in-time adjustment of
    /// outlines.
    ///
    /// Glyph styles can be precomputed per font and may be provided here
    /// as an optimization to avoid recomputing them for each instance.
    Auto(Option<GlyphStyles>),
    /// Selects the engine based on the same rules that FreeType uses when
    /// neither of the `FT_LOAD_NO_AUTOHINT` or `FT_LOAD_FORCE_AUTOHINT`
    /// load flags are specified.
    ///
    /// Specifically, PostScript (CFF/CFF2) fonts will always use the hinting
    /// engine in the PostScript interpreter and TrueType fonts will use the
    /// interpreter for TrueType instructions if one of the `fpgm` or `prep`
    /// tables is non-empty, falling back to the automatic hinter otherwise.
    ///
    /// This uses [`OutlineGlyphCollection::prefer_interpreter`] to make a
    /// selection.
    #[default]
    AutoFallback,
}

impl Engine {
    /// Converts the `AutoFallback` variant into either `Interpreter` or
    /// `Auto` based on the given outline set's preference for interpreter
    /// mode.
    fn resolve_auto_fallback(self, outlines: &OutlineGlyphCollection) -> Engine {
        match self {
            Self::Interpreter => Self::Interpreter,
            Self::Auto(styles) => Self::Auto(styles),
            Self::AutoFallback => {
                if outlines.prefer_interpreter() {
                    Self::Interpreter
                } else {
                    Self::Auto(None)
                }
            }
        }
    }
}

impl From<Engine> for HintingOptions {
    fn from(value: Engine) -> Self {
        Self {
            engine: value,
            target: Default::default(),
        }
    }
}

/// Defines the target settings for hinting.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Target {
    /// Strong hinting style that should only be used for aliased, monochromatic
    /// rasterization.
    ///
    /// Corresponds to `FT_LOAD_TARGET_MONO` in FreeType.
    Mono,
    /// Hinting style that is suitable for anti-aliased rasterization.
    ///
    /// Corresponds to the non-monochrome load targets in FreeType. See
    /// [`SmoothMode`] for more detail.
    Smooth {
        /// The basic mode for smooth hinting.
        ///
        /// Defaults to [`SmoothMode::Normal`].
        mode: SmoothMode,
        /// If true, TrueType bytecode may assume that the resulting outline
        /// will be rasterized with supersampling in the vertical direction.
        ///
        /// When this is enabled, ClearType fonts will often generate wider
        /// horizontal stems that may lead to blurry images when rendered with
        /// an analytical area rasterizer (such as the one in FreeType).
        ///
        /// The effect of this setting is to control the "ClearType symmetric
        /// rendering bit" of the TrueType `GETINFO` instruction. For more
        /// detail, see this [issue](https://github.com/googlefonts/fontations/issues/1080).
        ///
        /// FreeType has no corresponding setting and behaves as if this is
        /// always enabled.
        ///
        /// This only applies to the TrueType interpreter.
        ///
        /// Defaults to `true`.
        symmetric_rendering: bool,
        /// If true, prevents adjustment of the outline in the horizontal
        /// direction and preserves inter-glyph spacing.
        ///
        /// This is useful for performing layout without concern that hinting
        /// will modify the advance width of a glyph. Specifically, it means
        /// that layout will not require evaluation of glyph outlines.
        ///
        /// FreeType has no corresponding setting and behaves as if this is
        /// always disabled.
        ///
        /// This applies to the TrueType interpreter and the automatic hinter.
        ///
        /// Defaults to `false`.       
        preserve_linear_metrics: bool,
    },
}

impl Default for Target {
    fn default() -> Self {
        SmoothMode::Normal.into()
    }
}

/// Mode selector for a smooth hinting target.
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
pub enum SmoothMode {
    /// The standard smooth hinting mode.
    ///
    /// Corresponds to `FT_LOAD_TARGET_NORMAL` in FreeType.
    #[default]
    Normal,
    /// Hinting with a lighter touch, typically meaning less aggressive
    /// adjustment in the horizontal direction.
    ///
    /// Corresponds to `FT_LOAD_TARGET_LIGHT` in FreeType.
    Light,
    /// Hinting that is optimized for subpixel rendering with horizontal LCD
    /// layouts.
    ///
    /// Corresponds to `FT_LOAD_TARGET_LCD` in FreeType.
    Lcd,
    /// Hinting that is optimized for subpixel rendering with vertical LCD
    /// layouts.
    ///
    /// Corresponds to `FT_LOAD_TARGET_LCD_V` in FreeType.
    VerticalLcd,
}

impl From<SmoothMode> for Target {
    fn from(value: SmoothMode) -> Self {
        Self::Smooth {
            mode: value,
            symmetric_rendering: true,
            preserve_linear_metrics: false,
        }
    }
}

/// Modes that control hinting when using embedded instructions.
///
/// Only the TrueType interpreter supports all hinting modes.
///
/// # FreeType compatibility
///
/// The following table describes how to map FreeType hinting modes:
///
/// | FreeType mode         | Variant                                                                              |
/// |-----------------------|--------------------------------------------------------------------------------------|
/// | FT_LOAD_TARGET_MONO   | Strong                                                                               |
/// | FT_LOAD_TARGET_NORMAL | Smooth { lcd_subpixel: None, preserve_linear_metrics: false }                        |
/// | FT_LOAD_TARGET_LCD    | Smooth { lcd_subpixel: Some(LcdLayout::Horizontal), preserve_linear_metrics: false } |
/// | FT_LOAD_TARGET_LCD_V  | Smooth { lcd_subpixel: Some(LcdLayout::Vertical), preserve_linear_metrics: false }   |
///
/// Note: `FT_LOAD_TARGET_LIGHT` is equivalent to `FT_LOAD_TARGET_NORMAL` since
/// FreeType 2.7.
///
/// The default value of this type is equivalent to `FT_LOAD_TARGET_NORMAL`.
#[doc(hidden)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum HintingMode {
    /// Strong hinting mode that should only be used for aliased, monochromatic
    /// rasterization.
    ///
    /// Corresponds to `FT_LOAD_TARGET_MONO` in FreeType.
    Strong,
    /// Lighter hinting mode that is intended for anti-aliased rasterization.
    Smooth {
        /// If set, enables support for optimized hinting that takes advantage
        /// of subpixel layouts in LCD displays and corresponds to
        /// `FT_LOAD_TARGET_LCD` or `FT_LOAD_TARGET_LCD_V` in FreeType.
        ///
        /// If unset, corresponds to `FT_LOAD_TARGET_NORMAL` in FreeType.
        lcd_subpixel: Option<LcdLayout>,
        /// If true, prevents adjustment of the outline in the horizontal
        /// direction and preserves inter-glyph spacing.
        ///
        /// This is useful for performing layout without concern that hinting
        /// will modify the advance width of a glyph. Specifically, it means
        /// that layout will not require evaluation of glyph outlines.
        ///
        /// FreeType has no corresponding setting.
        preserve_linear_metrics: bool,
    },
}

impl Default for HintingMode {
    fn default() -> Self {
        Self::Smooth {
            lcd_subpixel: None,
            preserve_linear_metrics: false,
        }
    }
}

impl From<HintingMode> for HintingOptions {
    fn from(value: HintingMode) -> Self {
        let target = match value {
            HintingMode::Strong => Target::Mono,
            HintingMode::Smooth {
                lcd_subpixel,
                preserve_linear_metrics,
            } => {
                let mode = match lcd_subpixel {
                    Some(LcdLayout::Horizontal) => SmoothMode::Lcd,
                    Some(LcdLayout::Vertical) => SmoothMode::VerticalLcd,
                    None => SmoothMode::Normal,
                };
                Target::Smooth {
                    mode,
                    preserve_linear_metrics,
                    symmetric_rendering: true,
                }
            }
        };
        target.into()
    }
}

/// Specifies direction of pixel layout for LCD based subpixel hinting.
#[doc(hidden)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum LcdLayout {
    /// Subpixels are ordered horizontally.
    ///
    /// Corresponds to `FT_LOAD_TARGET_LCD` in FreeType.
    Horizontal,
    /// Subpixels are ordered vertically.
    ///
    /// Corresponds to `FT_LOAD_TARGET_LCD_V` in FreeType.
    Vertical,
}

/// Hinting instance that uses information embedded in the font to perform
/// grid-fitting.
#[derive(Clone)]
pub struct HintingInstance {
    size: Size,
    coords: Vec<NormalizedCoord>,
    target: Target,
    kind: HinterKind,
}

impl HintingInstance {
    /// Creates a new embedded hinting instance for the given outline
    /// collection, size, location in variation space and hinting mode.
    pub fn new<'a>(
        outline_glyphs: &OutlineGlyphCollection,
        size: Size,
        location: impl Into<LocationRef<'a>>,
        options: impl Into<HintingOptions>,
    ) -> Result<Self, DrawError> {
        let options = options.into();
        let mut hinter = Self {
            size: Size::unscaled(),
            coords: vec![],
            target: options.target,
            kind: HinterKind::None,
        };
        hinter.reconfigure(outline_glyphs, size, location, options)?;
        Ok(hinter)
    }

    /// Returns the currently configured size.
    pub fn size(&self) -> Size {
        self.size
    }

    /// Returns the currently configured normalized location in variation space.
    pub fn location(&self) -> LocationRef {
        LocationRef::new(&self.coords)
    }

    /// Returns the currently configured hinting target.
    pub fn target(&self) -> Target {
        self.target
    }

    /// Resets the hinter state for a new font instance with the given
    /// outline collection and settings.
    pub fn reconfigure<'a>(
        &mut self,
        outlines: &OutlineGlyphCollection,
        size: Size,
        location: impl Into<LocationRef<'a>>,
        options: impl Into<HintingOptions>,
    ) -> Result<(), DrawError> {
        self.size = size;
        self.coords.clear();
        self.coords.extend_from_slice(location.into().coords());
        let options = options.into();
        self.target = options.target;
        let engine = options.engine.resolve_auto_fallback(outlines);
        // Reuse memory if the font contains the same outline format
        let current_kind = core::mem::replace(&mut self.kind, HinterKind::None);
        match engine {
            Engine::Interpreter => match &outlines.kind {
                OutlineCollectionKind::Glyf(glyf) => {
                    let mut hint_instance = match current_kind {
                        HinterKind::Glyf(instance) => instance,
                        _ => Box::<glyf::HintInstance>::default(),
                    };
                    let ppem = size.ppem();
                    let scale = glyf.compute_scale(ppem).1.to_bits();
                    hint_instance.reconfigure(
                        glyf,
                        scale,
                        ppem.unwrap_or_default() as i32,
                        self.target,
                        &self.coords,
                    )?;
                    self.kind = HinterKind::Glyf(hint_instance);
                }
                OutlineCollectionKind::Cff(cff) => {
                    let mut subfonts = match current_kind {
                        HinterKind::Cff(subfonts) => subfonts,
                        _ => vec![],
                    };
                    subfonts.clear();
                    let ppem = size.ppem();
                    for i in 0..cff.subfont_count() {
                        subfonts.push(cff.subfont(i, ppem, &self.coords)?);
                    }
                    self.kind = HinterKind::Cff(subfonts);
                }
                OutlineCollectionKind::None => {}
            },
            Engine::Auto(styles) => {
                let Some(font) = outlines.common().map(|scaler| &scaler.font) else {
                    return Ok(());
                };
                let instance = autohint::Instance::new(
                    font,
                    outlines,
                    &self.coords,
                    self.target,
                    styles,
                    true,
                );
                self.kind = HinterKind::Auto(instance);
            }
            _ => {}
        }
        Ok(())
    }

    /// Returns true if hinting should actually be applied for this instance.
    ///
    /// Some TrueType fonts disable hinting dynamically based on the instance
    /// configuration.
    pub fn is_enabled(&self) -> bool {
        match &self.kind {
            HinterKind::Glyf(instance) => instance.is_enabled(),
            HinterKind::Cff(_) | HinterKind::Auto(_) => true,
            _ => false,
        }
    }

    pub(super) fn draw(
        &self,
        glyph: &OutlineGlyph,
        memory: Option<&mut [u8]>,
        path_style: PathStyle,
        pen: &mut impl OutlinePen,
        is_pedantic: bool,
    ) -> Result<AdjustedMetrics, DrawError> {
        let ppem = self.size.ppem();
        let coords = self.coords.as_slice();
        match (&self.kind, &glyph.kind) {
            (HinterKind::Auto(instance), _) => {
                instance.draw(self.size, coords, glyph, path_style, pen)
            }
            (HinterKind::Glyf(instance), OutlineKind::Glyf(glyf, outline)) => {
                if matches!(path_style, PathStyle::HarfBuzz) {
                    return Err(DrawError::HarfBuzzHintingUnsupported);
                }
                super::with_glyf_memory(outline, Hinting::Embedded, memory, |buf| {
                    let scaled_outline = FreeTypeScaler::hinted(
                        glyf,
                        outline,
                        buf,
                        ppem,
                        coords,
                        instance,
                        is_pedantic,
                    )?
                    .scale(&outline.glyph, outline.glyph_id)?;
                    scaled_outline.to_path(path_style, pen)?;
                    Ok(AdjustedMetrics {
                        has_overlaps: outline.has_overlaps,
                        lsb: Some(scaled_outline.adjusted_lsb().to_f32()),
                        // When hinting is requested, we round the advance
                        // <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/base/ftobjs.c#L889>
                        advance_width: Some(
                            scaled_outline.adjusted_advance_width().round().to_f32(),
                        ),
                    })
                })
            }
            (HinterKind::Cff(subfonts), OutlineKind::Cff(cff, glyph_id, subfont_ix)) => {
                let Some(subfont) = subfonts.get(*subfont_ix as usize) else {
                    return Err(DrawError::NoSources);
                };
                cff.draw(subfont, *glyph_id, &self.coords, true, pen)?;
                Ok(AdjustedMetrics::default())
            }
            _ => Err(DrawError::NoSources),
        }
    }
}

#[derive(Clone)]
enum HinterKind {
    /// Represents a hinting instance that is associated with an empty outline
    /// collection.
    None,
    Glyf(Box<glyf::HintInstance>),
    Cff(Vec<cff::Subfont>),
    Auto(autohint::Instance),
}

// Internal helpers for deriving various flags from the mode which
// change the behavior of certain instructions.
// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/truetype/ttgload.c#L2222>
impl Target {
    pub(crate) fn is_smooth(&self) -> bool {
        matches!(self, Self::Smooth { .. })
    }

    pub(crate) fn is_grayscale_cleartype(&self) -> bool {
        match self {
            Self::Smooth { mode, .. } => matches!(mode, SmoothMode::Normal | SmoothMode::Light),
            _ => false,
        }
    }

    pub(crate) fn is_light(&self) -> bool {
        matches!(
            self,
            Self::Smooth {
                mode: SmoothMode::Light,
                ..
            }
        )
    }

    pub(crate) fn is_lcd(&self) -> bool {
        matches!(
            self,
            Self::Smooth {
                mode: SmoothMode::Lcd,
                ..
            }
        )
    }

    pub(crate) fn is_vertical_lcd(&self) -> bool {
        matches!(
            self,
            Self::Smooth {
                mode: SmoothMode::VerticalLcd,
                ..
            }
        )
    }

    pub(crate) fn symmetric_rendering(&self) -> bool {
        matches!(
            self,
            Self::Smooth {
                symmetric_rendering: true,
                ..
            }
        )
    }

    pub(crate) fn preserve_linear_metrics(&self) -> bool {
        matches!(
            self,
            Self::Smooth {
                preserve_linear_metrics: true,
                ..
            }
        )
    }
}