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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Text shaping
//!
//! To quote the HarfBuzz manual:
//!
//! > Text shaping is the process of translating a string of character codes
//! > (such as Unicode codepoints) into a properly arranged sequence of glyphs
//! > that can be rendered onto a screen or into final output form for
//! > inclusion in a document.
//!
//! This module provides the [`shape`] function, which produces a sequence of
//! [`Glyph`]s based on the given text.
//!
//! This module *does not* perform line-breaking, wrapping or text reversal.

use crate::{fonts, prepared, FontId, Range, Vec2};
use ab_glyph::{GlyphId, ScaleFont};
use smallvec::SmallVec;
use unicode_bidi::Level;

/// A positioned glyph
#[derive(Clone, Copy, Debug)]
pub struct Glyph {
    /// Index of char in source text
    pub index: u32,
    /// Glyph identifier in font
    pub id: GlyphId,
    /// Position of glyph
    pub position: Vec2,
}

#[derive(Clone, Copy, Debug)]
pub struct GlyphBreak {
    /// Position in sequence of glyphs
    pub pos: u32,
    /// End position of previous "word" excluding space
    pub no_space_end: f32,
}

/// A glyph run
///
/// A glyph run is a sequence of glyphs, starting from the origin: 0.0.
/// Whether the run is left-to-right text or right-to-left, glyphs are
/// positioned between 0.0 and `run.caret` (usually with some internal
/// margin due to side bearings — though this could even be negative).
/// The first glyph in the run should not be invisible (space) except where the
/// run occurs at the start of a line with explicit initial spacing, however
/// the run may end with white-space. `no_space_end` gives the "caret" position
/// of the *logical* end of the run, excluding white-space (for right-to-left
/// text, this is the end nearer the origin than `caret`).
#[derive(Clone, Debug)]
pub struct GlyphRun {
    /// Sequence of all glyphs, with index in text
    pub glyphs: Vec<Glyph>,
    /// Sequence of all break points
    pub breaks: SmallVec<[GlyphBreak; 2]>,

    pub font_id: FontId,
    pub font_scale: f32,

    /// End position, excluding whitespace
    ///
    /// Use [`GlyphRun::start_no_space`] or [`GlyphRun::end_no_space`].
    pub no_space_end: f32,
    /// Position of next glyph, if this run is followed by another
    pub caret: f32,

    /// Range of text represented
    pub range: Range,
    /// BIDI level (odd levels are right-to-left)
    pub level: Level,
}

impl GlyphRun {
    /// Starting offset of the run, excluding space
    ///
    /// Note that runs never have space at the logical start, thus we only
    /// need to save this value for the logical end of the run.
    pub fn start_no_space(&self) -> f32 {
        if self.level.is_ltr() {
            0.0
        } else {
            self.no_space_end
        }
    }

    /// Ending offset of the run, excluding space
    ///
    /// Note that runs never have space at the logical start, thus we only
    /// need to save this value for the logical end of the run.
    pub fn end_no_space(&self) -> f32 {
        if self.level.is_ltr() {
            self.no_space_end
        } else {
            self.caret
        }
    }
}

/// Shape a `run` of text
///
/// A "run" is expected to be the maximal sequence of code points of the same
/// embedding level (as defined by Unicode TR9 aka BIDI algorithm) *and*
/// excluding all hard line breaks (e.g. `\n`).
///
/// Param `dpem` is the font size in pixels/em.
pub(crate) fn shape(font_id: FontId, dpem: f32, text: &str, run: &prepared::Run) -> GlyphRun {
    let mut glyphs = vec![];
    let mut breaks = Default::default();
    let mut no_space_end = 0.0;
    let mut caret = 0.0;

    let font = fonts().get(font_id);
    let font_scale = font.font_scale(dpem);

    if dpem >= 0.0 {
        #[cfg(feature = "harfbuzz_rs")]
        let r = shape_harfbuzz(font_id, dpem, text, run);

        #[cfg(not(feature = "harfbuzz_rs"))]
        let r = shape_simple(font, font_scale, text, run);

        glyphs = r.0;
        breaks = r.1;
        no_space_end = r.2;
        caret = r.3;
    }

    if run.level.is_rtl() {
        // With RTL text, no_space_end means start_no_space; recalculate
        let mut break_i = breaks.len().wrapping_sub(1);
        let mut start_no_space = caret;
        let mut last_id = None;
        let scale_font = font.scaled(font_scale);
        let side_bearing =
            |id: Option<GlyphId>| id.map(|id| scale_font.h_side_bearing(id)).unwrap_or(0.0);
        for (pos, glyph) in glyphs.iter().enumerate().rev() {
            if break_i < breaks.len() && breaks[break_i].pos as usize == pos {
                assert!(pos < glyphs.len());
                breaks[break_i].pos = pos as u32 + 1;
                breaks[break_i].no_space_end = start_no_space - side_bearing(last_id);
                break_i = break_i.wrapping_sub(1);
            }
            if !text[(glyph.index as usize)..]
                .chars()
                .next()
                .map(|c| c.is_whitespace())
                .unwrap_or(true)
            {
                last_id = Some(glyph.id);
                start_no_space = glyph.position.0;
            }
        }
        no_space_end = start_no_space - side_bearing(last_id);
    }

    GlyphRun {
        glyphs,
        breaks,
        font_id,
        font_scale,
        no_space_end,
        caret,
        range: run.range,
        level: run.level,
    }
}

// Use HarfBuzz lib
#[cfg(feature = "harfbuzz_rs")]
fn shape_harfbuzz(
    font_id: FontId,
    dpem: f32,
    text: &str,
    run: &prepared::Run,
) -> (Vec<Glyph>, SmallVec<[GlyphBreak; 2]>, f32, f32) {
    let mut font = fonts().get_harfbuzz(font_id);

    // ppem affects hinting but does not scale layout, so this has little effect:
    font.set_ppem(dpem as u32, dpem as u32);

    // Note: we could alternatively set scale to dpem*x and let unit_factor=1/x,
    // resulting in sub-pixel precision of x.
    let upem = font.face().upem() as i32;
    // This is the default: font.set_scale(upem, upem);
    let unit_factor = dpem / (upem as f32);

    let slice = &text[run.range];
    let idx_offset = run.range.start;
    let rtl = run.level.is_rtl();

    // TODO: cache the buffer for reuse later?
    let buffer = harfbuzz_rs::UnicodeBuffer::new()
        .set_direction(match rtl {
            false => harfbuzz_rs::Direction::Ltr,
            true => harfbuzz_rs::Direction::Rtl,
        })
        .add_str(slice);
    let features = [];

    let output = harfbuzz_rs::shape(&font, buffer, &features);

    let unit = |x: harfbuzz_rs::Position| x as f32 * unit_factor;

    let mut caret = 0.0;
    let mut no_space_end = caret;

    let mut breaks_iter = run.breaks.iter();
    let mut get_next_break = || match rtl {
        false => breaks_iter.next().cloned().unwrap_or(u32::MAX),
        true => breaks_iter.next_back().cloned().unwrap_or(u32::MAX),
    };
    let mut next_break = get_next_break();
    assert!(next_break >= idx_offset);
    let mut breaks = SmallVec::<[GlyphBreak; 2]>::with_capacity(run.breaks.len());

    let mut glyphs = Vec::with_capacity(output.len());

    for (info, pos) in output
        .get_glyph_infos()
        .iter()
        .zip(output.get_glyph_positions().iter())
    {
        let index = idx_offset + info.cluster;
        assert!(info.codepoint <= u16::MAX as u32, "failed to map glyph id");
        let id = GlyphId(info.codepoint as u16);

        if index == next_break {
            let pos = glyphs.len() as u32;
            breaks.push(GlyphBreak { pos, no_space_end });
            next_break = get_next_break();
        }

        let position = Vec2(caret + unit(pos.x_offset), unit(pos.y_offset));
        glyphs.push(Glyph {
            index,
            id,
            position,
        });

        // IIRC this is only applicable to vertical text, which we don't
        // currently support:
        debug_assert_eq!(pos.y_advance, 0);
        caret += unit(pos.x_advance);
        if text[(index as usize)..]
            .chars()
            .next()
            .map(|c| !c.is_whitespace())
            .unwrap()
        {
            no_space_end = caret;
        }
    }

    (glyphs, breaks, no_space_end, caret)
}

// Simple implementation (kerning but no shaping)
#[cfg(not(feature = "harfbuzz_rs"))]
fn shape_simple(
    font: crate::Font,
    font_scale: f32,
    text: &str,
    run: &prepared::Run,
) -> (Vec<Glyph>, SmallVec<[GlyphBreak; 2]>, f32, f32) {
    use ab_glyph::Font;
    use unicode_bidi_mirroring::get_mirrored;

    let scale_font = font.scaled(font_scale);

    let slice = &text[run.range];
    let idx_offset = run.range.start;
    let rtl = run.level.is_rtl();

    let mut caret = 0.0;
    let mut no_space_end = caret;
    let mut prev_glyph_id = None;

    let mut breaks_iter = run.breaks.iter();
    let mut get_next_break = || match rtl {
        false => breaks_iter.next().cloned().unwrap_or(u32::MAX),
        true => breaks_iter.next_back().cloned().unwrap_or(u32::MAX),
    };
    let mut next_break = get_next_break();
    assert!(next_break >= idx_offset);
    let mut breaks = SmallVec::<[GlyphBreak; 2]>::with_capacity(run.breaks.len());

    // Allocate with an over-estimate and shrink later:
    let mut glyphs = Vec::with_capacity(slice.len());
    let mut iter = slice.char_indices();
    let mut next_char_index = || match rtl {
        false => iter.next(),
        true => iter.next_back(),
    };
    while let Some((index, mut c)) = next_char_index() {
        let index = idx_offset + index as u32;
        if rtl {
            if let Some(m) = get_mirrored(c) {
                c = m;
            }
        }
        let id = scale_font.font().glyph_id(c);

        if index == next_break {
            let pos = glyphs.len() as u32;
            breaks.push(GlyphBreak { pos, no_space_end });
            next_break = get_next_break();
            no_space_end = caret;
        }

        if let Some(prev) = prev_glyph_id {
            caret += scale_font.kern(prev, id);
        }
        prev_glyph_id = Some(id);

        let position = Vec2(caret, 0.0);
        let glyph = Glyph {
            index,
            id,
            position,
        };
        glyphs.push(glyph);

        caret += scale_font.h_advance(id);
        if !c.is_whitespace() {
            no_space_end = caret;
        }
    }

    glyphs.shrink_to_fit();

    (glyphs, breaks, no_space_end, caret)
}