skrifa 0.21.0

Metadata reader and glyph scaler for OpenType fonts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Apply edge hints to an outline.
//!
//! This happens in three passes:
//! 1. Align points that are directly attached to edges.
//! 2. Interpolate non-weak points that were not touched by the previous pass.
//! 3. Interpolate remaining (weak) points.
//!
//! The final result is a fully hinted outline.

use super::{
    axis::{Axis, Dimension},
    metrics::{fixed_div, fixed_mul, Scale},
    outline::{Outline, Point},
};
use core::cmp::Ordering;

/// Align all points of an edge to the same coordinate value.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1324>
pub(crate) fn align_edge_points(outline: &mut Outline, axis: &Axis) -> Option<()> {
    let edges = axis.edges.as_slice();
    let segments = axis.segments.as_slice();
    let points = outline.points.as_mut_slice();
    for segment in segments {
        let Some(edge) = segment.edge(edges) else {
            continue;
        };
        let mut point_ix = segment.first();
        let last_ix = segment.last();
        loop {
            let point = points.get_mut(point_ix)?;
            if axis.dim == Axis::HORIZONTAL {
                point.x = edge.pos;
                point.flags |= Point::TOUCH_X;
            } else {
                point.y = edge.pos;
                point.flags |= Point::TOUCH_Y;
            }
            if point_ix == last_ix {
                break;
            }
            point_ix = point.next();
        }
    }
    Some(())
}

/// Align the strong points; equivalent to the TrueType `IP` instruction.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1399>
pub(crate) fn align_strong_points(outline: &mut Outline, axis: &mut Axis) -> Option<()> {
    if axis.edges.is_empty() {
        return Some(());
    }
    let dim = axis.dim;
    let touch_flag = if dim == Axis::HORIZONTAL {
        Point::TOUCH_X
    } else {
        Point::TOUCH_Y
    };
    'points: for point in &mut outline.points {
        // Skip points that are already touched; do weak interpolation in the
        // next pass
        if point.flags & (touch_flag | Point::WEAK_INTERPOLATION) != 0 {
            continue;
        }
        let (u, ou) = if dim == Axis::VERTICAL {
            (point.fy, point.oy)
        } else {
            (point.fx, point.ox)
        };
        let edges = axis.edges.as_mut_slice();
        // Is the point before the first edge?
        let edge = edges.first()?;
        let delta = edge.fpos as i32 - u;
        if delta >= 0 {
            store_point(point, dim, edge.pos - (edge.opos - ou));
            continue;
        }
        // Is the point after the last edge?
        let edge = edges.last()?;
        let delta = u - edge.fpos as i32;
        if delta >= 0 {
            store_point(point, dim, edge.pos + (ou - edge.opos));
            continue;
        }
        // Find enclosing edges
        let mut min_ix = 0;
        let mut max_ix = edges.len();
        while min_ix < max_ix {
            let mid_ix = (min_ix + max_ix) >> 1;
            let edge = &edges[mid_ix];
            let fpos = edge.fpos as i32;
            match u.cmp(&fpos) {
                Ordering::Less => max_ix = mid_ix,
                Ordering::Greater => min_ix = mid_ix + 1,
                Ordering::Equal => {
                    // We are on an edge
                    store_point(point, dim, edge.pos);
                    continue 'points;
                }
            }
        }
        // Point is not on an edge
        if let Some(before_ix) = min_ix.checked_sub(1) {
            let edge_before = edges.get(before_ix)?;
            let before_pos = edge_before.pos;
            let before_fpos = edge_before.fpos as i32;
            let scale = if edge_before.scale == 0 {
                let edge_after = edges.get(min_ix)?;
                let scale = fixed_div(
                    edge_after.pos - edge_before.pos,
                    edge_after.fpos as i32 - before_fpos,
                );
                edges[before_ix].scale = scale;
                scale
            } else {
                edge_before.scale
            };
            store_point(point, dim, before_pos + fixed_mul(u - before_fpos, scale));
        }
    }
    Some(())
}

/// Align the weak points; equivalent to the TrueType `IUP` instruction.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1673>
pub(crate) fn align_weak_points(outline: &mut Outline, dim: Dimension) -> Option<()> {
    let touch_flag = if dim == Axis::HORIZONTAL {
        for point in &mut outline.points {
            point.u = point.x;
            point.v = point.ox;
        }
        Point::TOUCH_X
    } else {
        for point in &mut outline.points {
            point.u = point.y;
            point.v = point.oy;
        }
        Point::TOUCH_Y
    };
    for contour in &outline.contours {
        let points = outline.points.get_mut(contour.range())?;
        // Find first touched point
        let Some(first_touched_ix) = points
            .iter()
            .position(|point| point.flags & touch_flag != 0)
        else {
            continue;
        };
        let last_ix = points.len() - 1;
        let mut point_ix = first_touched_ix;
        let mut last_touched_ix;
        'outer: loop {
            // Skip any touched neighbors
            while point_ix < last_ix && points.get(point_ix + 1)?.flags & touch_flag != 0 {
                point_ix += 1;
            }
            last_touched_ix = point_ix;
            // Find the next touched point
            point_ix += 1;
            loop {
                if point_ix > last_ix {
                    break 'outer;
                }
                if points[point_ix].flags & touch_flag != 0 {
                    break;
                }
                point_ix += 1;
            }
            iup_interpolate(
                points,
                last_touched_ix + 1,
                point_ix - 1,
                last_touched_ix,
                point_ix,
            );
        }
        if last_touched_ix == first_touched_ix {
            // Special case: only one point was touched
            iup_shift(points, 0, last_ix, first_touched_ix);
        } else {
            // Interpolate the remainder
            if last_touched_ix < last_ix {
                iup_interpolate(
                    points,
                    last_touched_ix + 1,
                    last_ix,
                    last_touched_ix,
                    first_touched_ix,
                );
            }
            if first_touched_ix > 0 {
                iup_interpolate(
                    points,
                    0,
                    first_touched_ix - 1,
                    last_touched_ix,
                    first_touched_ix,
                );
            }
        }
    }
    // Save interpolated values
    if dim == Axis::HORIZONTAL {
        for point in &mut outline.points {
            point.x = point.u;
        }
    } else {
        for point in &mut outline.points {
            point.y = point.u;
        }
    }
    Some(())
}

#[inline(always)]
fn store_point(point: &mut Point, dim: Dimension, u: i32) {
    if dim == Axis::HORIZONTAL {
        point.x = u;
        point.flags |= Point::TOUCH_X;
    } else {
        point.y = u;
        point.flags |= Point::TOUCH_Y;
    }
}

/// Shift original coordinates of all points between `p1_ix` and `p2_ix`
/// (inclusive) to get hinted coordinates using the same difference as
/// given by the point at `ref_ix`.
///
/// The `u` and `v` members are the current and original coordinate values,
/// respectively.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1578>
fn iup_shift(points: &mut [Point], p1_ix: usize, p2_ix: usize, ref_ix: usize) -> Option<()> {
    let ref_point = points.get(ref_ix)?;
    let delta = ref_point.u - ref_point.v;
    if delta == 0 {
        return Some(());
    }
    for point in points.get_mut(p1_ix..ref_ix)? {
        point.u = point.v + delta;
    }
    for point in points.get_mut(ref_ix + 1..=p2_ix)? {
        point.u = point.v + delta;
    }
    Some(())
}

/// Interpolate the original coordinates all of points between `p1_ix` and
/// `p2_ix` (inclusive) to get hinted coordinates, using the points at
/// `ref1_ix` and `ref2_ix` as the reference points.
///
/// The `u` and `v` members are the current and original coordinate values,
/// respectively.
///
/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/57617782464411201ce7bbc93b086c1b4d7d84a5/src/autofit/afhints.c#L1605>
fn iup_interpolate(
    points: &mut [Point],
    p1_ix: usize,
    p2_ix: usize,
    ref1_ix: usize,
    ref2_ix: usize,
) -> Option<()> {
    if p1_ix > p2_ix {
        return Some(());
    }
    let mut ref_point1 = points.get(ref1_ix)?;
    let mut ref_point2 = points.get(ref2_ix)?;
    if ref_point1.v > ref_point2.v {
        core::mem::swap(&mut ref_point1, &mut ref_point2);
    }
    let (u1, v1) = (ref_point1.u, ref_point1.v);
    let (u2, v2) = (ref_point2.u, ref_point2.v);
    let d1 = u1 - v1;
    let d2 = u2 - v2;
    if u1 == u2 || v1 == v2 {
        for point in points.get_mut(p1_ix..=p2_ix)? {
            point.u = if point.v <= v1 {
                point.v + d1
            } else if point.v >= v2 {
                point.v + d2
            } else {
                u1
            };
        }
    } else {
        let scale = fixed_div(u2 - u1, v2 - v1);
        for point in points.get_mut(p1_ix..=p2_ix)? {
            point.u = if point.v <= v1 {
                point.v + d1
            } else if point.v >= v2 {
                point.v + d2
            } else {
                u1 + fixed_mul(point.v - v1, scale)
            };
        }
    }
    Some(())
}

#[cfg(test)]
mod tests {
    use super::{
        super::{latin, metrics::Scale, style},
        *,
    };
    use crate::MetadataProvider;
    use raw::{
        types::{F2Dot14, GlyphId},
        FontRef, TableProvider,
    };

    #[test]
    fn hinted_coords() {
        let font = FontRef::new(font_test_data::NOTOSERIFHEBREW_AUTOHINT_METRICS).unwrap();
        let outline = hint_latin_outline(
            &font,
            16.0,
            Default::default(),
            GlyphId::new(9),
            &style::STYLE_CLASSES[style::StyleClass::HEBR],
        );
        #[rustfmt::skip]
        let expected_coords = [
            (133, -256),
            (133, 282),
            (133, 343),
            (146, 431),
            (158, 463),
            (158, 463),
            (57, 463),
            (30, 463),
            (0, 495),
            (0, 534),
            (0, 548),
            (2, 570),
            (11, 604),
            (17, 633),
            (50, 633),
            (50, 629),
            (50, 604),
            (77, 576),
            (101, 576),
            (163, 576),
            (180, 576),
            (192, 562),
            (192, 542),
            (192, 475),
            (190, 457),
            (187, 423),
            (187, 366),
            (187, 315),
            (187, -220),
            (178, -231),
            (159, -248),
            (146, -256),
        ];
        let coords = outline
            .points
            .iter()
            .map(|point| (point.x, point.y))
            .collect::<Vec<_>>();
        assert_eq!(coords, expected_coords);
    }

    // Specific test case for <https://issues.skia.org/issues/344529168> which
    // uses the Ahem <https://web-platform-tests.org/writing-tests/ahem.html>
    // font
    #[test]
    fn skia_ahem_test_case() {
        let font = FontRef::new(font_test_data::AHEM).unwrap();
        let outline = hint_latin_outline(
            &font,
            24.0,
            Default::default(),
            // This glyph is the typical Ahem block square; the link to the
            // font description above more detail.
            GlyphId::new(5),
            &style::STYLE_CLASSES[style::StyleClass::LATN],
        );
        let expected_coords = [(0, 1216), (1536, 1216), (1536, -320), (0, -320)];
        // See <https://issues.skia.org/issues/344529168#comment3>
        // Note that Skia inverts y coords
        let expected_float_coords = [(0.0, 19.0), (24.0, 19.0), (24.0, -5.0), (0.0, -5.0)];
        let coords = outline
            .points
            .iter()
            .map(|point| (point.x, point.y))
            .collect::<Vec<_>>();
        let float_coords = coords
            .iter()
            .map(|(x, y)| (*x as f32 / 64.0, *y as f32 / 64.0))
            .collect::<Vec<_>>();
        assert_eq!(coords, expected_coords);
        assert_eq!(float_coords, expected_float_coords);
    }

    fn hint_latin_outline(
        font: &FontRef,
        size: f32,
        coords: &[F2Dot14],
        gid: GlyphId,
        style: &style::StyleClass,
    ) -> Outline {
        let glyphs = font.outline_glyphs();
        let glyph = glyphs.get(gid).unwrap();
        let mut outline = Outline::default();
        outline.fill(&glyph, coords).unwrap();
        let metrics = latin::compute_unscaled_style_metrics(font, coords, style);
        let scale = Scale::new(
            size,
            font.head().unwrap().units_per_em() as i32,
            Default::default(),
        );
        latin::hint_outline(&mut outline, &metrics, &scale);
        outline
    }
}