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
//! `ttf-parser` utils.

/// A bounding box.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct BBox {
    /// Minimum X coordinate.
    pub x_min: f32,
    /// Minimum Y coordinate.
    pub y_min: f32,
    /// Maximum X coordinate.
    pub x_max: f32,
    /// Maximum Y coordinate.
    pub y_max: f32,
}

impl BBox {
    /// Returns the bbox width.
    #[inline]
    pub fn width(&self) -> f32 {
        self.x_max - self.x_min
    }

    /// Returns the bbox height.
    #[inline]
    pub fn height(&self) -> f32 {
        self.y_max - self.y_min
    }

    /// Extend the bbox.
    #[inline]
    pub fn extend_by(&mut self, x: f32, y: f32) {
        self.x_min = self.x_min.min(x);
        self.y_min = self.y_min.min(y);
        self.x_max = self.x_max.max(x);
        self.y_max = self.y_max.max(y);
    }
}

/// A glyph outline.
#[derive(Debug, Clone)]
pub struct Outline {
    bbox: std::cell::Cell<Option<BBox>>,
    cff: bool,
    contours: Vec<Contour>,
}

impl Outline {
    /// Returns a new outline or `None` when the glyph has no outline or on error.
    pub fn new(face: &ttf_parser::Face, glyph_id: ttf_parser::GlyphId) -> Option<Self> {
        let mut outline = Outline {
            bbox: std::cell::Cell::new(None),
            cff: face.has_table(ttf_parser::TableName::CompactFontFormat)
                || face.has_table(ttf_parser::TableName::CompactFontFormat2),
            contours: Vec::new(),
        };
        let mut outline_builder = OutlineBuilder::new(&mut outline);
        let _ = face.outline_glyph(glyph_id, &mut outline_builder)?;
        Some(outline)
    }

    /// Returns the outline bounding box.
    pub fn bbox(&self) -> BBox {
        if let Some(bbox) = self.bbox.get() {
            bbox
        } else {
            let mut bbox = BBox::default();
            for (i, p) in self.contours.iter().flat_map(|c| &c.points).enumerate() {
                if i == 0 {
                    bbox.x_min = p.x;
                    bbox.y_min = p.y;
                    bbox.x_max = p.x;
                    bbox.y_max = p.y;
                } else {
                    bbox.extend_by(p.x, p.y);
                }
            }

            self.bbox.set(Some(bbox));
            bbox
        }
    }

    /// Embolden the outline.
    pub fn embolden(&mut self, strength: f32) {
        self.bbox.set(None);
        for c in &mut self.contours {
            let num_points = c.points.len();
            if num_points == 0 {
                continue;
            }

            let closed = num_points > 1 && c.points.last() == c.points.first();
            let last = if closed {
                num_points - 2
            } else {
                num_points - 1
            };

            let mut in_pt = Point::default();
            let mut in_len = 0f32;

            let mut anchor_pt = Point::default();
            let mut anchor_len = 0f32;

            let mut i = last;
            let mut j = 0;
            let mut k: Option<usize> = None;
            while i != j && Some(i) != k {
                let (out_pt, out_len) = if Some(j) != k {
                    let x = c.points[j].x - c.points[i].x;
                    let y = c.points[j].y - c.points[i].y;
                    let len = (x * x + y * y).sqrt();
                    if len != 0.0 {
                        (Point::new(x / len, y / len), len)
                    } else {
                        j = if j < last { j + 1 } else { 0 };
                        continue;
                    }
                } else {
                    (anchor_pt, anchor_len)
                };

                if in_len != 0.0 {
                    if k.is_none() {
                        k = Some(i);
                        anchor_pt = in_pt;
                        anchor_len = in_len;
                    }

                    let d = (in_pt.x * out_pt.x) + (in_pt.y * out_pt.y);
                    let shift_pt = if d > -0.9375 {
                        let d = d + 1.0;
                        let mut q = out_pt.x * in_pt.y - out_pt.y * in_pt.x;
                        if !self.cff {
                            q = -q;
                        }

                        let len = in_len.min(out_len);
                        let (x, y) = if self.cff {
                            (in_pt.y + out_pt.y, -(in_pt.x + out_pt.x))
                        } else {
                            (-(in_pt.y + out_pt.y), in_pt.x + out_pt.x)
                        };
                        if (strength * q) <= (len * d) {
                            Point::new(x * strength / d, y * strength / d)
                        } else {
                            Point::new(x * len / q, y * len / q)
                        }
                    } else {
                        Point::default()
                    };

                    while i != j {
                        let pt = &mut c.points[i];
                        pt.x += strength + shift_pt.x;
                        pt.y += strength + shift_pt.y;
                        i = if i < last { i + 1 } else { 0 };
                    }
                } else {
                    i = j;
                }

                in_pt = out_pt;
                in_len = out_len;
                j = if j < last { j + 1 } else { 0 };
            }

            if closed {
                let first = &c.points[0];
                c.points[num_points - 1] = *first;
            }
        }
    }

    /// Slant the outline.
    pub fn oblique(&mut self, x_skew: f32) {
        self.bbox.set(None);
        for c in &mut self.contours {
            for p in &mut c.points {
                if p.y != 0.0 {
                    p.x += p.y * x_skew;
                }
            }
        }
    }

    /// Emit the outline segments.
    pub fn emit(&self, builder: &mut dyn ttf_parser::OutlineBuilder) {
        let mut points = self.contours.iter().flat_map(|c| &c.points);
        for v in self.contours.iter().flat_map(|c| &c.verbs) {
            match v {
                PathVerb::MoveTo => {
                    let p = points.next().unwrap();
                    builder.move_to(p.x, p.y);
                }
                PathVerb::LineTo => {
                    let p = points.next().unwrap();
                    builder.line_to(p.x, p.y);
                }
                PathVerb::QuadTo => {
                    let p1 = points.next().unwrap();
                    let p = points.next().unwrap();
                    builder.quad_to(p1.x, p1.y, p.x, p.y);
                }
                PathVerb::CurveTo => {
                    let p1 = points.next().unwrap();
                    let p2 = points.next().unwrap();
                    let p = points.next().unwrap();
                    builder.curve_to(p1.x, p1.y, p2.x, p2.y, p.x, p.y);
                }
                PathVerb::Close => {
                    builder.close();
                }
            }
        }
    }
}

#[derive(Debug, Default, Clone)]
struct Contour {
    verbs: Vec<PathVerb>,
    points: Vec<Point>,
}

#[derive(Debug, Clone, Copy)]
enum PathVerb {
    MoveTo,
    LineTo,
    QuadTo,
    CurveTo,
    Close,
}

#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct Point {
    x: f32,
    y: f32,
}

impl Point {
    #[inline]
    fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

struct OutlineBuilder<'a> {
    outline: &'a mut Outline,
    current_contour: usize,
}

impl<'a> OutlineBuilder<'a> {
    #[inline]
    fn new(outline: &'a mut Outline) -> Self {
        Self {
            outline,
            current_contour: 1,
        }
    }

    #[inline]
    fn current_contour(&mut self) -> &mut Contour {
        if self.current_contour > self.outline.contours.len() {
            self.outline.contours.push(Contour::default());
        }

        &mut self.outline.contours[self.current_contour - 1]
    }
}

impl<'a> ttf_parser::OutlineBuilder for OutlineBuilder<'a> {
    fn move_to(&mut self, x: f32, y: f32) {
        let c = self.current_contour();
        c.verbs.push(PathVerb::MoveTo);
        c.points.push(Point::new(x, y));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        let c = self.current_contour();
        c.verbs.push(PathVerb::LineTo);
        c.points.push(Point::new(x, y));
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let c = self.current_contour();
        c.verbs.push(PathVerb::QuadTo);
        c.points.push(Point::new(x1, y1));
        c.points.push(Point::new(x, y));
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        let c = self.current_contour();
        c.verbs.push(PathVerb::CurveTo);
        c.points.push(Point::new(x1, y1));
        c.points.push(Point::new(x2, y2));
        c.points.push(Point::new(x, y));
    }

    fn close(&mut self) {
        self.current_contour().verbs.push(PathVerb::Close);
        self.current_contour += 1;
    }
}