parley 0.14.0

Parley provides an API for implementing rich text layout.
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
// Copyright 2021 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use crate::FontData;
use crate::layout::cluster::Cluster;
use crate::layout::data::{LineItemData, RunData};
use crate::layout::layout::Layout;
use crate::layout::spacing::{Gaps, RunGaps};
use crate::style::Brush;

use core::ops::Range;
use fontique::Synthesis;
use parlance::BidiLevel;
use parley_engine::{
    Atom, Atoms, FontMetrics, Glyph, Graphemes, NormalizedCoord, ShapedClusterGlyphs, ShapedRun,
    ShapedSlice,
};

/// Sequence of clusters with a single font and style.
pub struct Run<'a, B: Brush> {
    pub(crate) layout: &'a Layout<B>,
    /// The index of the line this run is part of.
    pub(crate) line_index: u32,
    /// The index of the run within the line it is part of.
    pub(crate) index: u32,
    /// The index of the shaped run within [`parley_engine::ShapedText`].
    pub(crate) shaped_text_run_index: u32,
    pub(crate) shaped: &'a ShapedRun,
    pub(crate) data: &'a RunData,
    pub(crate) line_data: Option<&'a LineItemData>,
}

// `Run` is `Copy` and `Clone` regardless of `B`.
impl<B: Brush> Copy for Run<'_, B> {}
impl<B: Brush> Clone for Run<'_, B> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, B: Brush> Run<'a, B> {
    pub(crate) fn new(
        layout: &'a Layout<B>,
        line_index: u32,
        index: u32,
        run_index: usize,
        line_data: Option<&'a LineItemData>,
    ) -> Self {
        Self {
            layout,
            line_index,
            index,
            shaped_text_run_index: run_index as u32,
            shaped: &layout.data.shaped_text.runs()[run_index],
            data: &layout.data.runs[run_index],
            line_data,
        }
    }

    /// Borrow the shaped content of this run as a slice, narrowed to this [`Run`]'s line.
    pub(crate) fn line_slice(&self) -> ShapedSlice<'a> {
        match self.line_data {
            Some(line_data) => line_data.slice(&self.layout.data),
            None => self
                .layout
                .data
                .shaped_text
                .run_slice(self.shaped_text_run_index),
        }
    }

    /// Returns the index of the run within the line.
    pub fn index(&self) -> usize {
        self.index as usize
    }

    /// Returns the font for the run.
    pub fn font(&self) -> &'a FontData {
        &self
            .layout
            .data
            .shaped_text
            .fonts()
            .get(self.shaped.font_index)
            .unwrap()
            .font
    }

    /// Returns the font size for the run.
    pub fn font_size(&self) -> f32 {
        self.shaped.font_size
    }

    /// Returns the font attributes for the run.
    pub fn font_attrs(&self) -> &'a fontique::Attributes {
        &self.data.font_attrs
    }

    /// Returns the synthesis suggestions for the font associated with the run.
    pub fn synthesis(&self) -> Synthesis {
        self.data.synthesis
    }

    /// Returns the normalized variation coordinates for the font associated
    /// with the run.
    pub fn normalized_coords(&self) -> &'a [NormalizedCoord] {
        self.layout
            .data
            .shaped_text
            .normalized_coords()
            .get(self.shaped.normalized_coords_range)
            .unwrap_or(&[])
    }

    /// Returns metrics for the run.
    pub fn font_metrics(&self) -> &'a FontMetrics {
        &self.shaped.font_metrics
    }

    /// Spacing for this run's shaped clusters on its line, or `None` for unspaced text.
    pub(crate) fn gaps(&self) -> Option<RunGaps<'a>> {
        // A Run with no line_data only happens during line breaking, which doesn't call this method.
        // TODO: Maybe use a different data type than run in that case?
        let item = self.line_data.unwrap();
        let start = item.gaps_start? as usize;
        let clusters = item.shaped_cluster_range;
        Some(RunGaps::new(
            &self.layout.data.cluster_gaps[start..start + (clusters.end - clusters.start) as usize],
            clusters.start,
        ))
    }

    /// Returns the advance for the run.
    ///
    /// This includes the additional advances inserted for word spacing, letter spacing, and, if the
    /// layout has been [aligned](Layout::set_alignment) with [`Justify`](crate::Alignment::Justify), the
    /// justification.
    pub fn advance(&self) -> f32 {
        let slice = self.line_slice();
        match self.gaps() {
            Some(gaps) => gaps
                .for_cluster_range(slice.shaped_clusters_range())
                .iter()
                .zip(slice.shaped_clusters())
                .map(|(entry, cluster)| cluster.advance + entry.total())
                .sum(),
            None => slice
                .shaped_clusters()
                .iter()
                .map(|cluster| cluster.advance)
                .sum(),
        }
    }

    /// Returns the original text range for the run.
    pub fn text_range(&self) -> Range<usize> {
        self.line_data
            .map_or(self.shaped.range.byte_range, |d| d.text_range)
            .into()
    }

    /// The run's bidi level.
    ///
    /// Note that due to [UAX #9 rule L1], this can differ from the level the run was shaped at.
    ///
    /// [UAX #9 rule L1]: https://www.unicode.org/reports/tr9/#L1
    pub(crate) fn bidi_level(&self) -> BidiLevel {
        self.line_data
            .map_or(self.shaped.bidi_level, |data| data.bidi_level)
    }

    /// Returns `true` if the run has right-to-left directionality.
    pub fn is_rtl(&self) -> bool {
        self.bidi_level().is_rtl()
    }

    /// Returns the number of clusters in the run.
    ///
    /// Note this counts the run's clusters, so the cost is linear in the run's length. To check
    /// whether the run has any clusters, use [`Self::is_empty`].
    pub fn len(&self) -> usize {
        let slice = self.line_slice();
        slice
            .characters()
            .iter()
            .filter(|character| character.grapheme_start)
            .count()
            // If the run starts inside a grapheme, we also count it, as it is its own `Cluster`.
            + usize::from(slice.grapheme_continues_before())
    }

    /// Returns `true` if the run is empty.
    pub fn is_empty(&self) -> bool {
        self.line_slice().shaped_clusters_range().is_empty()
    }

    /// Returns the cluster at the specified logical index.
    ///
    /// Note this walks the run's clusters, so the cost is `O(index)`.
    pub fn get(&self, index: usize) -> Option<Cluster<'a, B>> {
        Clusters::new(*self, false).nth(index)
    }

    /// Returns an iterator over the clusters in logical order.
    pub fn clusters(&self) -> impl Iterator<Item = Cluster<'a, B>> + Clone + use<'a, B> {
        Clusters::new(*self, false)
    }

    /// Returns an iterator over the clusters in visual order.
    pub fn visual_clusters(&self) -> impl Iterator<Item = Cluster<'a, B>> + Clone + use<'a, B> {
        Clusters::new(*self, self.is_rtl())
    }

    /// Returns an iterator over the clusters in reverse visual order.
    pub(crate) fn visual_clusters_rev(
        &self,
    ) -> impl Iterator<Item = Cluster<'a, B>> + Clone + use<'a, B> {
        Clusters::new(*self, !self.is_rtl())
    }

    /// The cluster containing the character at `char_index`.
    ///
    /// Returns `None` if `char_index` is not within this run.
    pub(crate) fn cluster_containing_char(&self, char_index: u32) -> Option<Cluster<'a, B>> {
        let atom = self.line_slice().atom_at_char(char_index)?;
        let grapheme = atom
            .graphemes_start()
            .find(|grapheme| grapheme.char_range().contains(&char_index))?;
        Some(Cluster {
            run: *self,
            atom,
            grapheme,
        })
    }

    /// The cluster containing the source text byte at `text_byte`.
    ///
    /// Returns `None` if `text_byte` is not within this run.
    pub(crate) fn cluster_at_text_byte(&self, text_byte: usize) -> Option<Cluster<'a, B>> {
        let slice = self.line_slice();
        let atom = slice.atom_at_text_byte(u32::try_from(text_byte).ok()?)?;
        let grapheme = atom
            .graphemes_start()
            .find(|grapheme| slice.text_byte_range(grapheme.char_range()).end > text_byte)?;
        Some(Cluster {
            run: *self,
            atom,
            grapheme,
        })
    }

    /// An iterator over the glyphs in `shaped_clusters` in visual left-to-right order.
    ///
    /// This includes additional spacing from the stored [`Gaps`].
    ///
    /// `shaped_clusters` must be a subrange of this [`Run`]'s shaped clusters on its line.
    pub(crate) fn glyphs_in(self, shaped_clusters: Range<u32>) -> Glyphs<'a> {
        let gaps = self
            .gaps()
            .map(|run_gaps| run_gaps.for_cluster_range(shaped_clusters.clone()));
        Glyphs::new(
            self.line_slice().narrow(shaped_clusters),
            self.is_rtl(),
            gaps,
        )
    }
}

/// An iterator over the glyphs of a range of shaped clusters, in visual left-to-right order.
///
/// See [`Run::glyphs_in`].
#[derive(Clone)]
pub(crate) struct Glyphs<'a> {
    /// The slice of shaped text narrowed to the shaped clusters being iterated.
    slice: ShapedSlice<'a>,
    is_rtl: bool,
    /// The gaps of the shaped clusters being iterated, indexed relative to the start of
    /// [`Self::slice`]'s shaped cluster range.
    /// (Semantically, this is the same index space conversion as a [`RunGaps`] constructed
    /// with that index, but using that abstraction would grow this iterator)
    ///
    /// If `None`, the shaped clusters have no additional spacing.
    gaps: Option<&'a [Gaps]>,
    /// The shaped clusters not yet visited. Visited in logical order for LTR text and in reverse
    /// for RTL.
    remaining: Range<u32>,
    /// The not-yet-yielded glyphs of the current shaped cluster.
    glyphs: ShapedClusterGlyphs<'a>,
    /// The current shaped cluster's [`Gaps::before`], if its first glyph hasn't been yielded yet,
    /// otherwise zero.
    shift: f32,
    /// The current shaped cluster's [`Gaps::after`].
    after: f32,
}

impl<'a> Glyphs<'a> {
    fn new(slice: ShapedSlice<'a>, is_rtl: bool, gaps: Option<&'a [Gaps]>) -> Self {
        Self {
            remaining: slice.shaped_clusters_range(),
            slice,
            is_rtl,
            gaps,
            glyphs: ShapedClusterGlyphs::empty(),
            shift: 0.,
            after: 0.,
        }
    }
}

impl Iterator for Glyphs<'_> {
    type Item = Glyph;

    #[inline]
    fn next(&mut self) -> Option<Glyph> {
        loop {
            if let Some(mut glyph) = self.glyphs.next() {
                if self.gaps.is_some() {
                    glyph.x += self.shift;
                    // Also shift subsequent glyphs.
                    glyph.advance += self.shift;
                    self.shift = 0.;
                    if self.glyphs.len() == 0 {
                        glyph.advance += self.after;
                    }
                }
                return Some(glyph);
            }

            let cluster = if self.is_rtl {
                self.remaining.next_back()
            } else {
                self.remaining.next()
            }?;
            self.glyphs = self.slice.shaped_cluster_glyphs(cluster);
            if let Some(cluster_gaps) = self.gaps {
                // TODO: if `self.shift` is non-zero at this point, then there was a shaped cluster without glyphs,
                // and glyph rendering would fall out of sync with layout.
                let index = (cluster - self.slice.shaped_clusters_range().start) as usize;
                // TODO: These gaps are never made visible to the caller if
                // this shaped cluster didn't contain any glyphs.
                // This can make accumulated glyph advances (as in `GlyphRun::positioned_glyphs` disagree
                // with layout, mispositioning subsequent glyphs in the run).
                let gaps = cluster_gaps[index];
                self.shift = gaps.before;
                self.after = gaps.after;
            }
        }
    }
}

/// An iterator over a [`Run`]'s clusters.
///
/// This walks the run's graphemes. Each grapheme is one [`Cluster`].
struct Clusters<'a, B: Brush> {
    run: Run<'a, B>,
    /// Cursor over the run's (line-scoped) atoms.
    atoms: Atoms<'a>,
    /// Grapheme cursor over the run's (line-scoped) slice.
    graphemes: Graphemes<'a>,
    /// The atom containing the most recently yielded grapheme; `None` before the first grapheme.
    atom: Option<Atom<'a>>,
    /// Whether iteration is in reverse logical order.
    rev: bool,
}

impl<'a, B: Brush> Clusters<'a, B> {
    fn new(run: Run<'a, B>, rev: bool) -> Self {
        let slice = run.line_slice();
        Self {
            run,
            atoms: if rev {
                slice.atoms_end()
            } else {
                slice.atoms_start()
            },
            graphemes: if rev {
                slice.graphemes_end()
            } else {
                slice.graphemes_start()
            },
            atom: None,
            rev,
        }
    }
}

impl<B: Brush> Clone for Clusters<'_, B> {
    fn clone(&self) -> Self {
        Self {
            run: self.run,
            atoms: self.atoms,
            graphemes: self.graphemes,
            atom: self.atom,
            rev: self.rev,
        }
    }
}

impl<'a, B: Brush> Iterator for Clusters<'a, B> {
    type Item = Cluster<'a, B>;

    fn next(&mut self) -> Option<Self::Item> {
        let grapheme = if self.rev {
            self.graphemes.prev()?
        } else {
            self.graphemes.next()?
        };
        let entered_new_atom = if self.rev {
            grapheme.is_atom_end()
        } else {
            grapheme.is_atom_start()
        };
        if entered_new_atom {
            self.atom = if self.rev {
                self.atoms.prev()
            } else {
                self.atoms.next()
            };
        }
        let atom = self.atom.expect(
            "The first call to `next` should always be an atom edge, so this should always be set at this point.",
        );
        Some(Cluster {
            run: self.run,
            atom,
            grapheme,
        })
    }
}