harfrust 0.13.1

A complete HarfBuzz shaping algorithm port to Rust.
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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use core::mem::size_of;
use core::ptr;
use core::slice;

use read_fonts::types::F2Dot14;
use read_fonts::types::GlyphId;

use crate::hb::charmap::Charmap;
use crate::hb::face::FontKind;
use crate::hb::face::Scale;
use crate::hb::glyph_metrics::GlyphMetrics;

use super::buffer::{hb_buffer_t, GlyphInfo, GlyphPosition};
use super::face::{hb_font_t, GlyphExtents};

/// Raw C-style view over a batch of glyph ids and advance widths.
#[derive(Clone, Copy, Debug)]
pub struct RawAdvanceWidthBatch {
    /// Number of batch entries.
    pub len: usize,
    /// Pointer to glyph ids (read-only).
    pub gids: *const u32,
    /// Pointer to horizontal advances (writable).
    ///
    /// See "Metrics scaling" in the [FontFuncs] for details
    /// on what value this method should return.
    pub advances: *mut i32,
    /// Byte stride between successive glyph ids.
    pub gid_stride: isize,
    /// Byte stride between successive advances.
    pub advance_stride: isize,
}

/// Safe batch view for glyph id / horizontal-advance updates.
pub struct AdvanceWidthBatch<'a> {
    infos: &'a [GlyphInfo],
    positions: &'a mut [GlyphPosition],
}

impl<'a> AdvanceWidthBatch<'a> {
    pub(crate) fn new(buffer: &'a mut hb_buffer_t) -> Self {
        let len = buffer.len;
        let infos = &buffer.info[..len];
        let positions = &mut buffer.pos[..len];
        Self { infos, positions }
    }

    /// Returns the number of entries in the batch.
    pub fn len(&self) -> usize {
        self.infos.len()
    }

    /// Returns true if the batch is empty.
    pub fn is_empty(&self) -> bool {
        self.infos.is_empty()
    }

    /// Returns a raw C-style view over this batch.
    pub fn into_raw(self) -> RawAdvanceWidthBatch {
        if self.infos.is_empty() {
            return RawAdvanceWidthBatch {
                len: 0,
                gids: ptr::null(),
                advances: ptr::null_mut(),
                gid_stride: size_of::<GlyphInfo>() as isize,
                advance_stride: size_of::<GlyphPosition>() as isize,
            };
        }

        RawAdvanceWidthBatch {
            len: self.infos.len(),
            // `glyph_id` is the first field in `GlyphInfo`.
            gids: self.infos.as_ptr().cast::<u32>(),
            // `x_advance` is the first field in `GlyphPosition`.
            advances: self.positions.as_mut_ptr().cast::<i32>(),
            gid_stride: size_of::<GlyphInfo>() as isize,
            advance_stride: size_of::<GlyphPosition>() as isize,
        }
    }
}

pub struct AdvanceWidthBatchIter<'a> {
    infos: slice::Iter<'a, GlyphInfo>,
    positions: slice::IterMut<'a, GlyphPosition>,
}

impl<'a> Iterator for AdvanceWidthBatchIter<'a> {
    type Item = (GlyphId, &'a mut i32);

    fn next(&mut self) -> Option<Self::Item> {
        let info = self.infos.next()?;
        let pos = self.positions.next()?;
        Some((info.as_glyph(), &mut pos.x_advance))
    }
}

impl<'a> IntoIterator for AdvanceWidthBatch<'a> {
    type Item = (GlyphId, &'a mut i32);
    type IntoIter = AdvanceWidthBatchIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        AdvanceWidthBatchIter {
            infos: self.infos.iter(),
            positions: self.positions.iter_mut(),
        }
    }
}

/// Raw C-style view over a batch of codepoints and output glyph ids.
#[derive(Clone, Copy, Debug)]
pub struct RawNominalGlyphBatch {
    /// Number of batch entries.
    pub len: usize,
    /// Pointer to codepoints (read-only).
    pub codepoints: *const u32,
    /// Pointer to output glyph ids (writable).
    pub glyphs: *mut u32,
    /// Byte stride between successive codepoints.
    pub codepoint_stride: isize,
    /// Byte stride between successive glyphs.
    pub glyph_stride: isize,
}

/// Safe batch view for codepoint to nominal-glyph mapping.
///
/// Glyph ids must be written for consecutive codepoints starting at the
/// first entry; mapping stops at the first codepoint the font has no
/// glyph for, and the number of glyphs written is returned from
/// [FontFuncs::populate_nominal_glyphs].
pub struct NominalGlyphBatch<'a> {
    infos: &'a mut [GlyphInfo],
}

impl<'a> NominalGlyphBatch<'a> {
    /// Byte offset of the output glyph id within a batch entry.
    const GLYPH_OFFSET: usize = core::mem::offset_of!(GlyphInfo, vars)
        + (GlyphInfo::NORMALIZER_GLYPH_INDEX_VAR.var_index as usize - 1) * size_of::<u32>();

    pub(crate) fn new(infos: &'a mut [GlyphInfo]) -> Self {
        Self { infos }
    }

    /// Returns the number of entries in the batch.
    pub fn len(&self) -> usize {
        self.infos.len()
    }

    /// Returns true if the batch is empty.
    pub fn is_empty(&self) -> bool {
        self.infos.is_empty()
    }

    /// Returns a raw C-style view over this batch.
    pub fn into_raw(self) -> RawNominalGlyphBatch {
        if self.infos.is_empty() {
            return RawNominalGlyphBatch {
                len: 0,
                codepoints: ptr::null(),
                glyphs: ptr::null_mut(),
                codepoint_stride: size_of::<GlyphInfo>() as isize,
                glyph_stride: size_of::<GlyphInfo>() as isize,
            };
        }

        let base = self.infos.as_mut_ptr();
        RawNominalGlyphBatch {
            len: self.infos.len(),
            // `glyph_id` is the first field in `GlyphInfo` and holds the
            // codepoint before mapping.
            codepoints: base.cast::<u32>().cast_const(),
            // The normalizer glyph-index var.
            glyphs: base.wrapping_byte_add(Self::GLYPH_OFFSET).cast::<u32>(),
            codepoint_stride: size_of::<GlyphInfo>() as isize,
            glyph_stride: size_of::<GlyphInfo>() as isize,
        }
    }
}

pub struct NominalGlyphBatchIter<'a> {
    infos: slice::IterMut<'a, GlyphInfo>,
}

impl<'a> Iterator for NominalGlyphBatchIter<'a> {
    type Item = (u32, &'a mut GlyphId);

    fn next(&mut self) -> Option<Self::Item> {
        let info = self.infos.next()?;
        let codepoint = info.glyph_id;
        let var_index = GlyphInfo::NORMALIZER_GLYPH_INDEX_VAR.var_index as usize - 1;
        Some((codepoint, bytemuck::cast_mut(&mut info.vars[var_index])))
    }
}

impl<'a> IntoIterator for NominalGlyphBatch<'a> {
    type Item = (u32, &'a mut GlyphId);
    type IntoIter = NominalGlyphBatchIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        NominalGlyphBatchIter {
            infos: self.infos.iter_mut(),
        }
    }
}

/// Default implementations backed by font tables.
pub struct BuiltinFontFuncs<'a> {
    face: &'a hb_font_t<'a>,
    glyph_metrics: core::cell::OnceCell<GlyphMetrics<'a>>,
    charmap: core::cell::OnceCell<Charmap<'a>>,
}

impl<'a> BuiltinFontFuncs<'a> {
    pub(crate) fn new(face: &'a hb_font_t<'a>) -> Self {
        Self {
            face,
            glyph_metrics: core::cell::OnceCell::new(),
            charmap: core::cell::OnceCell::new(),
        }
    }

    fn coords(&self) -> &[F2Dot14] {
        self.face.ot_tables.coords
    }

    fn charmap(&self) -> &Charmap<'a> {
        self.charmap.get_or_init(|| match &self.face.font {
            FontKind::FontRef(font) => font.charmap.clone(),
            FontKind::FontInstance(instance, _) => Charmap::from_tables(&instance.tables()),
        })
    }

    fn glyph_metrics(&self) -> &GlyphMetrics<'a> {
        self.glyph_metrics.get_or_init(|| match &self.face.font {
            FontKind::FontRef(font) => font.glyph_metrics.clone(),
            FontKind::FontInstance(instance, metrics) => {
                GlyphMetrics::from_tables(&instance.tables(), metrics)
            }
        })
    }

    /// Maps a Unicode scalar value to a nominal glyph.
    pub fn nominal_glyph(&self, c: u32) -> Option<GlyphId> {
        self.charmap().map(c)
    }

    /// Maps a Unicode scalar value and variation selector to a glyph.
    pub fn variant_glyph(&self, c: u32, vs: u32) -> Option<GlyphId> {
        self.charmap().map_variant(c, vs)
    }

    /// Returns the horizontal advance for a glyph.
    pub fn advance_width(&self, glyph: GlyphId) -> i32 {
        self.glyph_metrics()
            .advance_width(glyph, self.coords())
            .unwrap_or_default()
    }

    /// Returns the vertical advance for a glyph.
    pub fn advance_height(&self, glyph: GlyphId) -> i32 {
        self.glyph_metrics()
            .advance_height(glyph, self.coords())
            .unwrap_or(self.face.units_per_em as i32)
            .saturating_neg()
    }

    /// Returns the vertical origin for a glyph.
    pub fn vertical_origin(&self, glyph: GlyphId) -> (i32, i32) {
        let v_origin_y = self
            .glyph_metrics()
            .v_origin(glyph, self.coords())
            .unwrap_or_default();
        (self.advance_width(glyph) / 2, v_origin_y)
    }

    /// Returns extents for a glyph if available.
    pub fn extents(&self, glyph: GlyphId) -> Option<GlyphExtents> {
        self.glyph_metrics().extents(glyph, self.coords())
    }

    /// Populates horizontal advances for all entries in the batch.
    pub fn populate_advance_widths(&self, batch: AdvanceWidthBatch<'_>) {
        for (glyph, advance) in batch {
            *advance = self.advance_width(glyph);
        }
    }

    /// Maps a run of codepoints to nominal glyphs, stopping at the first
    /// codepoint the font has no glyph for. Returns the number of
    /// consecutive codepoints mapped.
    pub fn populate_nominal_glyphs(&self, batch: NominalGlyphBatch<'_>) -> usize {
        let mut done = 0;
        for (codepoint, glyph) in batch {
            match self.nominal_glyph(codepoint) {
                Some(gid) => *glyph = gid,
                None => break,
            }
            done += 1;
        }
        done
    }
}

/// Customizable font callback surface.
///
/// # Metrics scaling
///
/// All font metrics returned by these callbacks must be consistent with the
/// scale factor configured via
/// [`ShapeOptions::scale`](crate::ShapeOptions::scale).
///
/// If no scale is set, values must be in unscaled font units (i.e. the same
/// coordinate space as the font's `units_per_em`). If a scale is set —
/// for example `font_size * 64` for FreeType-style 26.6 — then all returned
/// values must already be in that scaled coordinate space.
pub trait FontFuncs {
    /// Nominal character-to-glyph mapping callback.
    fn nominal_glyph(&mut self, builtin: &BuiltinFontFuncs, c: u32) -> Option<GlyphId> {
        builtin.nominal_glyph(c)
    }

    /// Variation-selector mapping callback.
    fn variant_glyph(&mut self, builtin: &BuiltinFontFuncs, c: u32, vs: u32) -> Option<GlyphId> {
        builtin.variant_glyph(c, vs)
    }

    /// Horizontal advance callback.
    ///
    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
    /// on what value this method should return.
    fn advance_width(&mut self, builtin: &BuiltinFontFuncs, glyph: GlyphId) -> i32 {
        builtin.advance_width(glyph)
    }

    /// Batch horizontal-advance callback.
    ///
    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
    /// on what value this method should return.
    fn populate_advance_widths(
        &mut self,
        builtin: &BuiltinFontFuncs,
        batch: AdvanceWidthBatch<'_>,
    ) {
        for (glyph, advance) in batch {
            *advance = self.advance_width(builtin, glyph);
        }
    }

    /// Batch nominal character-to-glyph mapping callback.
    ///
    /// Maps a run of codepoints to glyphs, stopping at the first
    /// codepoint the font has no glyph for. Returns the number of
    /// consecutive codepoints mapped.
    fn populate_nominal_glyphs(
        &mut self,
        builtin: &BuiltinFontFuncs,
        batch: NominalGlyphBatch<'_>,
    ) -> usize {
        let mut done = 0;
        for (codepoint, glyph) in batch {
            match self.nominal_glyph(builtin, codepoint) {
                Some(gid) => *glyph = gid,
                None => break,
            }
            done += 1;
        }
        done
    }

    /// Vertical advance callback.
    ///
    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
    /// on what value this method should return.
    fn advance_height(&mut self, builtin: &BuiltinFontFuncs, glyph: GlyphId) -> i32 {
        builtin.advance_height(glyph)
    }

    /// Vertical origin callback.
    ///
    /// Returns the (x, y) coordinates of the vertical origin for the given glyph.
    ///
    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
    /// on what values this method should return.
    fn vertical_origin(&mut self, builtin: &BuiltinFontFuncs, glyph: GlyphId) -> (i32, i32) {
        builtin.vertical_origin(glyph)
    }

    /// Glyph extents callback.
    ///
    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
    /// on what values this method should return.
    fn extents(&mut self, builtin: &BuiltinFontFuncs, glyph: GlyphId) -> Option<GlyphExtents> {
        builtin.extents(glyph)
    }
}

pub(crate) struct FontFuncsDispatch<'a, 'u> {
    builtin: BuiltinFontFuncs<'a>,
    scale: Scale,
    funcs: Option<&'u mut (dyn FontFuncs + 'u)>,
}

impl<'a, 'u> FontFuncsDispatch<'a, 'u> {
    pub(crate) fn new(
        face: &'a hb_font_t<'a>,
        scale: Scale,
        funcs: Option<&'u mut (dyn FontFuncs + 'u)>,
    ) -> Self {
        Self {
            builtin: BuiltinFontFuncs::new(face),
            scale,
            funcs,
        }
    }

    #[inline(always)]
    pub(crate) fn font(&self) -> &'a hb_font_t<'a> {
        self.builtin.face
    }

    #[inline(always)]
    pub(crate) fn scale(&self) -> &Scale {
        &self.scale
    }

    #[inline(always)]
    fn scale_x(&self, value: i32) -> i32 {
        self.scale.scale_x(value)
    }

    #[inline(always)]
    fn scale_y(&self, value: i32) -> i32 {
        self.scale.scale_y(value)
    }

    #[inline(always)]
    fn scale_point(&self, point: (i32, i32)) -> (i32, i32) {
        (self.scale_x(point.0), self.scale_y(point.1))
    }

    #[inline(always)]
    fn scale_extents(&self, extents: GlyphExtents) -> GlyphExtents {
        self.scale.scale_extents(extents)
    }

    #[inline(always)]
    pub(crate) fn nominal_glyph(&mut self, c: u32) -> Option<GlyphId> {
        if let Some(funcs) = &mut self.funcs {
            funcs.nominal_glyph(&self.builtin, c)
        } else if let Some(gid) = self.builtin.face.cmap_cache.get(c) {
            Some(gid.into())
        } else if let Some(gid) = self.builtin.nominal_glyph(c) {
            let cache = self.builtin.face.cmap_cache;
            cache.set(c, gid.to_u32());
            Some(gid)
        } else {
            None
        }
    }

    #[inline(always)]
    pub(crate) fn populate_nominal_glyphs(&mut self, batch: NominalGlyphBatch<'_>) -> usize {
        if let Some(funcs) = &mut self.funcs {
            funcs.populate_nominal_glyphs(&self.builtin, batch)
        } else {
            let mut done = 0;
            for (codepoint, glyph) in batch {
                let gid = if let Some(gid) = self.builtin.face.cmap_cache.get(codepoint) {
                    GlyphId::new(gid)
                } else if let Some(gid) = self.builtin.nominal_glyph(codepoint) {
                    self.builtin.face.cmap_cache.set(codepoint, gid.to_u32());
                    gid
                } else {
                    break;
                };
                *glyph = gid;
                done += 1;
            }
            done
        }
    }

    #[inline(always)]
    pub(crate) fn has_glyph(&mut self, c: u32) -> bool {
        self.nominal_glyph(c).is_some()
    }

    #[inline(always)]
    pub(crate) fn variant_glyph(&mut self, c: u32, vs: u32) -> Option<GlyphId> {
        if let Some(funcs) = &mut self.funcs {
            funcs.variant_glyph(&self.builtin, c, vs)
        } else {
            self.builtin.variant_glyph(c, vs)
        }
    }

    #[inline(always)]
    pub(crate) fn advance_width(&mut self, glyph: GlyphId) -> i32 {
        if let Some(funcs) = &mut self.funcs {
            funcs.advance_width(&self.builtin, glyph)
        } else {
            self.scale_x(self.builtin.advance_width(glyph))
        }
    }

    #[inline(always)]
    pub(crate) fn advance_height(&mut self, glyph: GlyphId) -> i32 {
        if let Some(funcs) = &mut self.funcs {
            funcs.advance_height(&self.builtin, glyph)
        } else {
            self.scale_y(self.builtin.advance_height(glyph))
        }
    }

    #[inline(always)]
    pub(crate) fn vertical_origin(&mut self, glyph: GlyphId) -> (i32, i32) {
        if let Some(funcs) = &mut self.funcs {
            funcs.vertical_origin(&self.builtin, glyph)
        } else {
            self.scale_point(self.builtin.vertical_origin(glyph))
        }
    }

    #[inline(always)]
    pub(crate) fn extents(&mut self, glyph: GlyphId) -> Option<GlyphExtents> {
        if let Some(funcs) = &mut self.funcs {
            funcs.extents(&self.builtin, glyph)
        } else {
            Some(self.scale_extents(self.builtin.extents(glyph)?))
        }
    }

    pub(crate) fn populate_advance_widths(&mut self, batch: AdvanceWidthBatch<'_>) {
        if let Some(funcs) = &mut self.funcs {
            funcs.populate_advance_widths(&self.builtin, batch);
        } else {
            self.builtin.glyph_metrics().populate_advance_widths(
                batch.infos,
                batch.positions,
                self.builtin.coords(),
                self.scale,
            );
        }
    }
}