floem_renderer 0.2.0

A native Rust UI library with fine-grained reactivity
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
use std::{ops::Range, sync::LazyLock};

use crate::text::AttrsList;
use cosmic_text::{
    Affinity, Buffer, BufferLine, Cursor, FontSystem, LayoutCursor, LayoutGlyph, LineEnding,
    LineIter, Metrics, Scroll, Shaping, Wrap,
};
use parking_lot::Mutex;
use peniko::kurbo::{Point, Size};

pub static FONT_SYSTEM: LazyLock<Mutex<FontSystem>> = LazyLock::new(|| {
    let mut font_system = FontSystem::new();
    #[cfg(target_os = "macos")]
    font_system.db_mut().set_sans_serif_family("Helvetica Neue");
    #[cfg(target_os = "windows")]
    font_system.db_mut().set_sans_serif_family("Segoe UI");
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    font_system.db_mut().set_sans_serif_family("Noto Sans");
    Mutex::new(font_system)
});

/// A line of visible text for rendering
#[derive(Debug)]
pub struct LayoutRun<'a> {
    /// The index of the original text line
    pub line_i: usize,
    /// The original text line
    pub text: &'a str,
    /// True if the original paragraph direction is RTL
    pub rtl: bool,
    /// The array of layout glyphs to draw
    pub glyphs: &'a [LayoutGlyph],
    /// Maximum ascent of the glyphs in line
    pub max_ascent: f32,
    /// Maximum descent of the glyphs in line
    pub max_descent: f32,
    /// Y offset to baseline of line
    pub line_y: f32,
    /// Y offset to top of line
    pub line_top: f32,
    /// Y offset to next line
    pub line_height: f32,
    /// Width of line
    pub line_w: f32,
}

impl<'a> LayoutRun<'a> {
    /// Return the pixel span `Some((x_left, x_width))` of the highlighted area between `cursor_start`
    /// and `cursor_end` within this run, or None if the cursor range does not intersect this run.
    /// This may return widths of zero if `cursor_start == cursor_end`, if the run is empty, or if the
    /// region's left start boundary is the same as the cursor's end boundary or vice versa.
    pub fn highlight(&self, cursor_start: Cursor, cursor_end: Cursor) -> Option<(f32, f32)> {
        let mut x_start = None;
        let mut x_end = None;
        let rtl_factor = if self.rtl { 1. } else { 0. };
        let ltr_factor = 1. - rtl_factor;
        for glyph in self.glyphs.iter() {
            let cursor = self.cursor_from_glyph_left(glyph);
            if cursor >= cursor_start && cursor <= cursor_end {
                if x_start.is_none() {
                    x_start = Some(glyph.x + glyph.w * rtl_factor);
                }
                x_end = Some(glyph.x + glyph.w * rtl_factor);
            }
            let cursor = self.cursor_from_glyph_right(glyph);
            if cursor >= cursor_start && cursor <= cursor_end {
                if x_start.is_none() {
                    x_start = Some(glyph.x + glyph.w * ltr_factor);
                }
                x_end = Some(glyph.x + glyph.w * ltr_factor);
            }
        }
        if let Some(x_start) = x_start {
            let x_end = x_end.expect("end of cursor not found");
            let (x_start, x_end) = if x_start < x_end {
                (x_start, x_end)
            } else {
                (x_end, x_start)
            };
            Some((x_start, x_end - x_start))
        } else {
            None
        }
    }

    fn cursor_from_glyph_left(&self, glyph: &LayoutGlyph) -> Cursor {
        if self.rtl {
            Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
        } else {
            Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
        }
    }

    fn cursor_from_glyph_right(&self, glyph: &LayoutGlyph) -> Cursor {
        if self.rtl {
            Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
        } else {
            Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
        }
    }
}

/// An iterator of visible text lines, see [`LayoutRun`]
#[derive(Debug)]
pub struct LayoutRunIter<'b> {
    text_layout: &'b TextLayout,
    line_i: usize,
    layout_i: usize,
    total_height: f32,
    line_top: f32,
}

impl<'b> LayoutRunIter<'b> {
    pub fn new(text_layout: &'b TextLayout) -> Self {
        Self {
            text_layout,
            line_i: text_layout.buffer.scroll().line,
            layout_i: 0,
            total_height: 0.0,
            line_top: 0.0,
        }
    }
}

impl<'b> Iterator for LayoutRunIter<'b> {
    type Item = LayoutRun<'b>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(line) = self.text_layout.buffer.lines.get(self.line_i) {
            let shape = line.shape_opt().as_ref()?;
            let layout = line.layout_opt().as_ref()?;
            while let Some(layout_line) = layout.get(self.layout_i) {
                self.layout_i += 1;

                let line_height = layout_line
                    .line_height_opt
                    .unwrap_or(self.text_layout.buffer.metrics().line_height);
                self.total_height += line_height;

                let line_top = self.line_top - self.text_layout.buffer.scroll().vertical;
                let glyph_height = layout_line.max_ascent + layout_line.max_descent;
                let centering_offset = (line_height - glyph_height) / 2.0;
                let line_y = line_top + centering_offset + layout_line.max_ascent;
                if let Some(height) = self.text_layout.height_opt {
                    if line_y > height {
                        return None;
                    }
                }
                self.line_top += line_height;
                if line_y < 0.0 {
                    continue;
                }

                return Some(LayoutRun {
                    line_i: self.line_i,
                    text: line.text(),
                    rtl: shape.rtl,
                    glyphs: &layout_line.glyphs,
                    max_ascent: layout_line.max_ascent,
                    max_descent: layout_line.max_descent,
                    line_y,
                    line_top,
                    line_height,
                    line_w: layout_line.w,
                });
            }
            self.line_i += 1;
            self.layout_i = 0;
        }

        None
    }
}

pub struct HitPosition {
    /// Text line the cursor is on
    pub line: usize,
    /// Point of the cursor
    pub point: Point,
    /// ascent of glyph
    pub glyph_ascent: f64,
    /// descent of glyph
    pub glyph_descent: f64,
}

pub struct HitPoint {
    /// Text line the cursor is on
    pub line: usize,
    /// First-byte-index of glyph at cursor (will insert behind this glyph)
    pub index: usize,
    /// Whether or not the point was inside the bounds of the layout object.
    ///
    /// A click outside the layout object will still resolve to a position in the
    /// text; for instance a click to the right edge of a line will resolve to the
    /// end of that line, and a click below the last line will resolve to a
    /// position in that line.
    pub is_inside: bool,
}

#[derive(Clone, Debug)]
pub struct TextLayout {
    buffer: Buffer,
    lines_range: Vec<Range<usize>>,
    width_opt: Option<f32>,
    height_opt: Option<f32>,
}

impl Default for TextLayout {
    fn default() -> Self {
        Self::new()
    }
}

impl TextLayout {
    pub fn new() -> Self {
        TextLayout {
            buffer: Buffer::new_empty(Metrics::new(16.0, 16.0)),
            lines_range: Vec::new(),
            width_opt: None,
            height_opt: None,
        }
    }

    pub fn set_text(&mut self, text: &str, attrs_list: AttrsList) {
        self.buffer.lines.clear();
        self.lines_range.clear();
        let mut attrs_list = attrs_list.0;
        for (range, ending) in LineIter::new(text) {
            self.lines_range.push(range.clone());
            let line_text = &text[range];
            let new_attrs = attrs_list
                .clone()
                .split_off(line_text.len() + ending.as_str().len());
            self.buffer.lines.push(BufferLine::new(
                line_text,
                ending,
                attrs_list.clone(),
                Shaping::Advanced,
            ));
            attrs_list = new_attrs;
        }
        if self.buffer.lines.is_empty() {
            self.buffer.lines.push(BufferLine::new(
                "",
                LineEnding::default(),
                attrs_list,
                Shaping::Advanced,
            ));
            self.lines_range.push(0..0)
        }
        self.buffer.set_scroll(Scroll::default());
        let mut font_system = FONT_SYSTEM.lock();
        self.buffer.shape_until_scroll(&mut font_system, false);
    }

    pub fn set_wrap(&mut self, wrap: Wrap) {
        let mut font_system = FONT_SYSTEM.lock();
        self.buffer.set_wrap(&mut font_system, wrap);
    }

    pub fn set_tab_width(&mut self, tab_width: usize) {
        let mut font_system = FONT_SYSTEM.lock();
        self.buffer
            .set_tab_width(&mut font_system, tab_width as u16);
    }

    pub fn set_size(&mut self, width: f32, height: f32) {
        let mut font_system = FONT_SYSTEM.lock();
        self.width_opt = Some(width);
        self.height_opt = Some(height);
        self.buffer
            .set_size(&mut font_system, Some(width), Some(height));
    }

    pub fn lines(&self) -> &[BufferLine] {
        &self.buffer.lines
    }

    pub fn lines_range(&self) -> &[Range<usize>] {
        &self.lines_range
    }

    pub fn layout_runs(&self) -> LayoutRunIter {
        LayoutRunIter::new(self)
    }

    pub fn layout_cursor(&mut self, cursor: Cursor) -> LayoutCursor {
        let line = cursor.line;
        let mut font_system = FONT_SYSTEM.lock();
        self.buffer
            .layout_cursor(&mut font_system, cursor)
            .unwrap_or_else(|| LayoutCursor::new(line, 0, 0))
    }

    pub fn hit_position(&self, idx: usize) -> HitPosition {
        let mut last_line = 0;
        let mut last_end: usize = 0;
        let mut offset = 0;
        let mut last_glyph_width = 0.0;
        let mut last_position = HitPosition {
            line: 0,
            point: Point::ZERO,
            glyph_ascent: 0.0,
            glyph_descent: 0.0,
        };
        for (line, run) in self.layout_runs().enumerate() {
            if run.line_i > last_line {
                last_line = run.line_i;
                offset += last_end + 1;
            }
            for glyph in run.glyphs {
                if glyph.start + offset > idx {
                    last_position.point.x += last_glyph_width as f64;
                    return last_position;
                }
                last_end = glyph.end;
                last_glyph_width = glyph.w;
                last_position = HitPosition {
                    line,
                    point: Point::new(glyph.x as f64, run.line_y as f64),
                    glyph_ascent: run.max_ascent as f64,
                    glyph_descent: run.max_descent as f64,
                };
                if (glyph.start + offset..glyph.end + offset).contains(&idx) {
                    return last_position;
                }
            }
        }

        if idx > 0 {
            last_position.point.x += last_glyph_width as f64;
            return last_position;
        }

        HitPosition {
            line: 0,
            point: Point::ZERO,
            glyph_ascent: 0.0,
            glyph_descent: 0.0,
        }
    }

    pub fn hit_point(&self, point: Point) -> HitPoint {
        if let Some(cursor) = self.hit(point.x as f32, point.y as f32) {
            let size = self.size();
            let is_inside = point.x <= size.width && point.y <= size.height;
            HitPoint {
                line: cursor.line,
                index: cursor.index,
                is_inside,
            }
        } else {
            HitPoint {
                line: 0,
                index: 0,
                is_inside: false,
            }
        }
    }

    /// Convert x, y position to Cursor (hit detection)
    pub fn hit(&self, x: f32, y: f32) -> Option<Cursor> {
        self.buffer.hit(x, y)
    }

    pub fn line_col_position(&self, line: usize, col: usize) -> HitPosition {
        let mut last_glyph: Option<&LayoutGlyph> = None;
        let mut last_line = 0;
        let mut last_line_y = 0.0;
        let mut last_glyph_ascent = 0.0;
        let mut last_glyph_descent = 0.0;
        for (current_line, run) in self.layout_runs().enumerate() {
            for glyph in run.glyphs {
                match run.line_i.cmp(&line) {
                    std::cmp::Ordering::Equal => {
                        if glyph.start > col {
                            return HitPosition {
                                line: last_line,
                                point: Point::new(
                                    last_glyph.map(|g| (g.x + g.w) as f64).unwrap_or(0.0),
                                    last_line_y as f64,
                                ),
                                glyph_ascent: last_glyph_ascent as f64,
                                glyph_descent: last_glyph_descent as f64,
                            };
                        }
                        if (glyph.start..glyph.end).contains(&col) {
                            return HitPosition {
                                line: current_line,
                                point: Point::new(glyph.x as f64, run.line_y as f64),
                                glyph_ascent: run.max_ascent as f64,
                                glyph_descent: run.max_descent as f64,
                            };
                        }
                    }
                    std::cmp::Ordering::Greater => {
                        return HitPosition {
                            line: last_line,
                            point: Point::new(
                                last_glyph.map(|g| (g.x + g.w) as f64).unwrap_or(0.0),
                                last_line_y as f64,
                            ),
                            glyph_ascent: last_glyph_ascent as f64,
                            glyph_descent: last_glyph_descent as f64,
                        };
                    }
                    std::cmp::Ordering::Less => {}
                };
                last_glyph = Some(glyph);
            }
            last_line = current_line;
            last_line_y = run.line_y;
            last_glyph_ascent = run.max_ascent;
            last_glyph_descent = run.max_descent;
        }

        HitPosition {
            line: last_line,
            point: Point::new(
                last_glyph.map(|g| (g.x + g.w) as f64).unwrap_or(0.0),
                last_line_y as f64,
            ),
            glyph_ascent: last_glyph_ascent as f64,
            glyph_descent: last_glyph_descent as f64,
        }
    }

    pub fn size(&self) -> Size {
        self.buffer
            .layout_runs()
            .fold(Size::new(0.0, 0.0), |mut size, run| {
                let new_width = run.line_w as f64;
                if new_width > size.width {
                    size.width = new_width;
                }

                size.height += run.line_height as f64;

                size
            })
    }
}