cosmic_text/
buffer.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3#[cfg(not(feature = "std"))]
4use alloc::{string::String, vec::Vec};
5
6use core::{cmp, fmt};
7
8#[cfg(not(feature = "std"))]
9use core_maths::CoreFloat;
10use unicode_segmentation::UnicodeSegmentation;
11
12#[cfg(feature = "swash")]
13use crate::Color;
14
15use crate::{
16    Affinity, Align, Attrs, AttrsList, BidiParagraphs, BorrowedWithFontSystem, BufferLine, Cursor,
17    FontSystem, LayoutCursor, LayoutGlyph, LayoutLine, LineEnding, LineIter, Motion, Scroll,
18    ShapeLine, Shaping, Wrap,
19};
20
21/// A line of visible text for rendering
22#[derive(Debug)]
23pub struct LayoutRun<'a> {
24    /// The index of the original text line
25    pub line_i: usize,
26    /// The original text line
27    pub text: &'a str,
28    /// True if the original paragraph direction is RTL
29    pub rtl: bool,
30    /// The array of layout glyphs to draw
31    pub glyphs: &'a [LayoutGlyph],
32    /// Y offset to baseline of line
33    pub line_y: f32,
34    /// Y offset to top of line
35    pub line_top: f32,
36    /// Y offset to next line
37    pub line_height: f32,
38    /// Width of line
39    pub line_w: f32,
40}
41
42impl LayoutRun<'_> {
43    /// Return the pixel span `Some((x_left, x_width))` of the highlighted area between `cursor_start`
44    /// and `cursor_end` within this run, or None if the cursor range does not intersect this run.
45    /// This may return widths of zero if `cursor_start == cursor_end`, if the run is empty, or if the
46    /// region's left start boundary is the same as the cursor's end boundary or vice versa.
47    #[allow(clippy::missing_panics_doc)]
48    pub fn highlight(&self, cursor_start: Cursor, cursor_end: Cursor) -> Option<(f32, f32)> {
49        let mut x_start = None;
50        let mut x_end = None;
51        let rtl_factor = if self.rtl { 1. } else { 0. };
52        let ltr_factor = 1. - rtl_factor;
53        for glyph in self.glyphs {
54            let cursor = self.cursor_from_glyph_left(glyph);
55            if cursor >= cursor_start && cursor <= cursor_end {
56                if x_start.is_none() {
57                    x_start = Some(glyph.x + glyph.w.mul_add(rtl_factor, 0.0));
58                }
59                x_end = Some(glyph.x + glyph.w.mul_add(rtl_factor, 0.0));
60            }
61            let cursor = self.cursor_from_glyph_right(glyph);
62            if cursor >= cursor_start && cursor <= cursor_end {
63                if x_start.is_none() {
64                    x_start = Some(glyph.x + glyph.w.mul_add(ltr_factor, 0.0));
65                }
66                x_end = Some(glyph.x + glyph.w.mul_add(ltr_factor, 0.0));
67            }
68        }
69        x_start.map(|x_start| {
70            let x_end = x_end.expect("end of cursor not found");
71            let (x_start, x_end) = if x_start < x_end {
72                (x_start, x_end)
73            } else {
74                (x_end, x_start)
75            };
76            (x_start, x_end - x_start)
77        })
78    }
79
80    const fn cursor_from_glyph_left(&self, glyph: &LayoutGlyph) -> Cursor {
81        if self.rtl {
82            Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
83        } else {
84            Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
85        }
86    }
87
88    const fn cursor_from_glyph_right(&self, glyph: &LayoutGlyph) -> Cursor {
89        if self.rtl {
90            Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
91        } else {
92            Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
93        }
94    }
95}
96
97/// An iterator of visible text lines, see [`LayoutRun`]
98#[derive(Debug)]
99pub struct LayoutRunIter<'b> {
100    buffer: &'b Buffer,
101    line_i: usize,
102    layout_i: usize,
103    total_height: f32,
104    line_top: f32,
105}
106
107impl<'b> LayoutRunIter<'b> {
108    pub const fn new(buffer: &'b Buffer) -> Self {
109        Self {
110            buffer,
111            line_i: buffer.scroll.line,
112            layout_i: 0,
113            total_height: 0.0,
114            line_top: 0.0,
115        }
116    }
117}
118
119impl<'b> Iterator for LayoutRunIter<'b> {
120    type Item = LayoutRun<'b>;
121
122    fn next(&mut self) -> Option<Self::Item> {
123        while let Some(line) = self.buffer.lines.get(self.line_i) {
124            let shape = line.shape_opt()?;
125            let layout = line.layout_opt()?;
126            while let Some(layout_line) = layout.get(self.layout_i) {
127                self.layout_i += 1;
128
129                let line_height = layout_line
130                    .line_height_opt
131                    .unwrap_or(self.buffer.metrics.line_height);
132                self.total_height += line_height;
133
134                let line_top = self.line_top - self.buffer.scroll.vertical;
135                let glyph_height = layout_line.max_ascent + layout_line.max_descent;
136                let centering_offset = (line_height - glyph_height) / 2.0;
137                let line_y = line_top + centering_offset + layout_line.max_ascent;
138                if let Some(height) = self.buffer.height_opt {
139                    if line_y - layout_line.max_ascent > height {
140                        return None;
141                    }
142                }
143                self.line_top += line_height;
144                if line_y + layout_line.max_descent < 0.0 {
145                    continue;
146                }
147
148                return Some(LayoutRun {
149                    line_i: self.line_i,
150                    text: line.text(),
151                    rtl: shape.rtl,
152                    glyphs: &layout_line.glyphs,
153                    line_y,
154                    line_top,
155                    line_height,
156                    line_w: layout_line.w,
157                });
158            }
159            self.line_i += 1;
160            self.layout_i = 0;
161        }
162
163        None
164    }
165}
166
167/// Metrics of text
168#[derive(Clone, Copy, Debug, Default, PartialEq)]
169pub struct Metrics {
170    /// Font size in pixels
171    pub font_size: f32,
172    /// Line height in pixels
173    pub line_height: f32,
174}
175
176impl Metrics {
177    /// Create metrics with given font size and line height
178    pub const fn new(font_size: f32, line_height: f32) -> Self {
179        Self {
180            font_size,
181            line_height,
182        }
183    }
184
185    /// Create metrics with given font size and calculate line height using relative scale
186    pub fn relative(font_size: f32, line_height_scale: f32) -> Self {
187        Self {
188            font_size,
189            line_height: font_size * line_height_scale,
190        }
191    }
192
193    /// Scale font size and line height
194    pub fn scale(self, scale: f32) -> Self {
195        Self {
196            font_size: self.font_size * scale,
197            line_height: self.line_height * scale,
198        }
199    }
200}
201
202impl fmt::Display for Metrics {
203    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204        write!(f, "{}px / {}px", self.font_size, self.line_height)
205    }
206}
207
208/// A buffer of text that is shaped and laid out
209#[derive(Debug)]
210pub struct Buffer {
211    /// [`BufferLine`]s (or paragraphs) of text in the buffer
212    pub lines: Vec<BufferLine>,
213    metrics: Metrics,
214    width_opt: Option<f32>,
215    height_opt: Option<f32>,
216    scroll: Scroll,
217    /// True if a redraw is requires. Set to false after processing
218    redraw: bool,
219    wrap: Wrap,
220    monospace_width: Option<f32>,
221    tab_width: u16,
222}
223
224impl Clone for Buffer {
225    fn clone(&self) -> Self {
226        Self {
227            lines: self.lines.clone(),
228            metrics: self.metrics,
229            width_opt: self.width_opt,
230            height_opt: self.height_opt,
231            scroll: self.scroll,
232            redraw: self.redraw,
233            wrap: self.wrap,
234            monospace_width: self.monospace_width,
235            tab_width: self.tab_width,
236        }
237    }
238}
239
240impl Buffer {
241    /// Create an empty [`Buffer`] with the provided [`Metrics`].
242    /// This is useful for initializing a [`Buffer`] without a [`FontSystem`].
243    ///
244    /// You must populate the [`Buffer`] with at least one [`BufferLine`] before shaping and layout,
245    /// for example by calling [`Buffer::set_text`].
246    ///
247    /// If you have a [`FontSystem`] in scope, you should use [`Buffer::new`] instead.
248    ///
249    /// # Panics
250    ///
251    /// Will panic if `metrics.line_height` is zero.
252    pub fn new_empty(metrics: Metrics) -> Self {
253        assert_ne!(metrics.line_height, 0.0, "line height cannot be 0");
254        Self {
255            lines: Vec::new(),
256            metrics,
257            width_opt: None,
258            height_opt: None,
259            scroll: Scroll::default(),
260            redraw: false,
261            wrap: Wrap::WordOrGlyph,
262            monospace_width: None,
263            tab_width: 8,
264        }
265    }
266
267    /// Create a new [`Buffer`] with the provided [`FontSystem`] and [`Metrics`]
268    ///
269    /// # Panics
270    ///
271    /// Will panic if `metrics.line_height` is zero.
272    pub fn new(font_system: &mut FontSystem, metrics: Metrics) -> Self {
273        let mut buffer = Self::new_empty(metrics);
274        buffer.set_text(font_system, "", &Attrs::new(), Shaping::Advanced, None);
275        buffer
276    }
277
278    /// Mutably borrows the buffer together with an [`FontSystem`] for more convenient methods
279    pub fn borrow_with<'a>(
280        &'a mut self,
281        font_system: &'a mut FontSystem,
282    ) -> BorrowedWithFontSystem<'a, Self> {
283        BorrowedWithFontSystem {
284            inner: self,
285            font_system,
286        }
287    }
288
289    fn relayout(&mut self, font_system: &mut FontSystem) {
290        #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
291        let instant = std::time::Instant::now();
292
293        for line in &mut self.lines {
294            if line.shape_opt().is_some() {
295                line.reset_layout();
296                line.layout(
297                    font_system,
298                    self.metrics.font_size,
299                    self.width_opt,
300                    self.wrap,
301                    self.monospace_width,
302                    self.tab_width,
303                );
304            }
305        }
306
307        self.redraw = true;
308
309        #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
310        log::debug!("relayout: {:?}", instant.elapsed());
311    }
312
313    /// Shape lines until cursor, also scrolling to include cursor in view
314    #[allow(clippy::missing_panics_doc)]
315    pub fn shape_until_cursor(
316        &mut self,
317        font_system: &mut FontSystem,
318        cursor: Cursor,
319        prune: bool,
320    ) {
321        let metrics = self.metrics;
322        let old_scroll = self.scroll;
323
324        let layout_cursor = self
325            .layout_cursor(font_system, cursor)
326            .expect("shape_until_cursor invalid cursor");
327
328        let mut layout_y = 0.0;
329        let mut total_height = {
330            let layout = self
331                .line_layout(font_system, layout_cursor.line)
332                .expect("shape_until_cursor failed to scroll forwards");
333            (0..layout_cursor.layout).for_each(|layout_i| {
334                layout_y += layout[layout_i]
335                    .line_height_opt
336                    .unwrap_or(metrics.line_height);
337            });
338            layout_y
339                + layout[layout_cursor.layout]
340                    .line_height_opt
341                    .unwrap_or(metrics.line_height)
342        };
343
344        if self.scroll.line > layout_cursor.line
345            || (self.scroll.line == layout_cursor.line && self.scroll.vertical > layout_y)
346        {
347            // Adjust scroll backwards if cursor is before it
348            self.scroll.line = layout_cursor.line;
349            self.scroll.vertical = layout_y;
350        } else if let Some(height) = self.height_opt {
351            // Adjust scroll forwards if cursor is after it
352            let mut line_i = layout_cursor.line;
353            if line_i <= self.scroll.line {
354                // This is a single line that may wrap
355                if total_height > height + self.scroll.vertical {
356                    self.scroll.vertical = total_height - height;
357                }
358            } else {
359                while line_i > self.scroll.line {
360                    line_i -= 1;
361                    let layout = self
362                        .line_layout(font_system, line_i)
363                        .expect("shape_until_cursor failed to scroll forwards");
364                    for layout_line in layout {
365                        total_height += layout_line.line_height_opt.unwrap_or(metrics.line_height);
366                    }
367                    if total_height > height + self.scroll.vertical {
368                        self.scroll.line = line_i;
369                        self.scroll.vertical = total_height - height;
370                    }
371                }
372            }
373        }
374
375        if old_scroll != self.scroll {
376            self.redraw = true;
377        }
378
379        self.shape_until_scroll(font_system, prune);
380
381        // Adjust horizontal scroll to include cursor
382        if let Some(layout_cursor) = self.layout_cursor(font_system, cursor) {
383            if let Some(layout_lines) = self.line_layout(font_system, layout_cursor.line) {
384                if let Some(layout_line) = layout_lines.get(layout_cursor.layout) {
385                    let (x_min, x_max) = layout_line
386                        .glyphs
387                        .get(layout_cursor.glyph)
388                        .or_else(|| layout_line.glyphs.last())
389                        .map_or((0.0, 0.0), |glyph| {
390                            //TODO: use code from cursor_glyph_opt?
391                            let x_a = glyph.x;
392                            let x_b = glyph.x + glyph.w;
393                            (x_a.min(x_b), x_a.max(x_b))
394                        });
395                    if x_min < self.scroll.horizontal {
396                        self.scroll.horizontal = x_min;
397                        self.redraw = true;
398                    }
399                    if let Some(width) = self.width_opt {
400                        if x_max > self.scroll.horizontal + width {
401                            self.scroll.horizontal = x_max - width;
402                            self.redraw = true;
403                        }
404                    }
405                }
406            }
407        }
408    }
409
410    /// Shape lines until scroll
411    #[allow(clippy::missing_panics_doc)]
412    pub fn shape_until_scroll(&mut self, font_system: &mut FontSystem, prune: bool) {
413        let metrics = self.metrics;
414        let old_scroll = self.scroll;
415
416        loop {
417            // Adjust scroll.layout to be positive by moving scroll.line backwards
418            while self.scroll.vertical < 0.0 {
419                if self.scroll.line > 0 {
420                    let line_i = self.scroll.line - 1;
421                    if let Some(layout) = self.line_layout(font_system, line_i) {
422                        let mut layout_height = 0.0;
423                        for layout_line in layout {
424                            layout_height +=
425                                layout_line.line_height_opt.unwrap_or(metrics.line_height);
426                        }
427                        self.scroll.line = line_i;
428                        self.scroll.vertical += layout_height;
429                    } else {
430                        // If layout is missing, just assume line height
431                        self.scroll.line = line_i;
432                        self.scroll.vertical += metrics.line_height;
433                    }
434                } else {
435                    self.scroll.vertical = 0.0;
436                    break;
437                }
438            }
439
440            let scroll_start = self.scroll.vertical;
441            let scroll_end = scroll_start + self.height_opt.unwrap_or(f32::INFINITY);
442
443            let mut total_height = 0.0;
444            for line_i in 0..self.lines.len() {
445                if line_i < self.scroll.line {
446                    if prune {
447                        self.lines[line_i].reset_shaping();
448                    }
449                    continue;
450                }
451                if total_height > scroll_end {
452                    if prune {
453                        self.lines[line_i].reset_shaping();
454                        continue;
455                    }
456                    break;
457                }
458
459                let mut layout_height = 0.0;
460                let layout = self
461                    .line_layout(font_system, line_i)
462                    .expect("shape_until_scroll invalid line");
463                for layout_line in layout {
464                    let line_height = layout_line.line_height_opt.unwrap_or(metrics.line_height);
465                    layout_height += line_height;
466                    total_height += line_height;
467                }
468
469                // Adjust scroll.vertical to be smaller by moving scroll.line forwards
470                if line_i == self.scroll.line && layout_height <= self.scroll.vertical {
471                    self.scroll.line += 1;
472                    self.scroll.vertical -= layout_height;
473                }
474            }
475
476            if total_height < scroll_end && self.scroll.line > 0 {
477                // Need to scroll up to stay inside of buffer
478                self.scroll.vertical -= scroll_end - total_height;
479            } else {
480                // Done adjusting scroll
481                break;
482            }
483        }
484
485        if old_scroll != self.scroll {
486            self.redraw = true;
487        }
488    }
489
490    /// Convert a [`Cursor`] to a [`LayoutCursor`]
491    pub fn layout_cursor(
492        &mut self,
493        font_system: &mut FontSystem,
494        cursor: Cursor,
495    ) -> Option<LayoutCursor> {
496        let layout = self.line_layout(font_system, cursor.line)?;
497        for (layout_i, layout_line) in layout.iter().enumerate() {
498            for (glyph_i, glyph) in layout_line.glyphs.iter().enumerate() {
499                let cursor_end =
500                    Cursor::new_with_affinity(cursor.line, glyph.end, Affinity::Before);
501                let cursor_start =
502                    Cursor::new_with_affinity(cursor.line, glyph.start, Affinity::After);
503                let (cursor_left, cursor_right) = if glyph.level.is_ltr() {
504                    (cursor_start, cursor_end)
505                } else {
506                    (cursor_end, cursor_start)
507                };
508                if cursor == cursor_left {
509                    return Some(LayoutCursor::new(cursor.line, layout_i, glyph_i));
510                }
511                if cursor == cursor_right {
512                    return Some(LayoutCursor::new(cursor.line, layout_i, glyph_i + 1));
513                }
514            }
515        }
516
517        // Fall back to start of line
518        //TODO: should this be the end of the line?
519        Some(LayoutCursor::new(cursor.line, 0, 0))
520    }
521
522    /// Shape the provided line index and return the result
523    pub fn line_shape(
524        &mut self,
525        font_system: &mut FontSystem,
526        line_i: usize,
527    ) -> Option<&ShapeLine> {
528        let line = self.lines.get_mut(line_i)?;
529        Some(line.shape(font_system, self.tab_width))
530    }
531
532    /// Lay out the provided line index and return the result
533    pub fn line_layout(
534        &mut self,
535        font_system: &mut FontSystem,
536        line_i: usize,
537    ) -> Option<&[LayoutLine]> {
538        let line = self.lines.get_mut(line_i)?;
539        Some(line.layout(
540            font_system,
541            self.metrics.font_size,
542            self.width_opt,
543            self.wrap,
544            self.monospace_width,
545            self.tab_width,
546        ))
547    }
548
549    /// Get the current [`Metrics`]
550    pub const fn metrics(&self) -> Metrics {
551        self.metrics
552    }
553
554    /// Set the current [`Metrics`]
555    ///
556    /// # Panics
557    ///
558    /// Will panic if `metrics.font_size` is zero.
559    pub fn set_metrics(&mut self, font_system: &mut FontSystem, metrics: Metrics) {
560        self.set_metrics_and_size(font_system, metrics, self.width_opt, self.height_opt);
561    }
562
563    /// Get the current [`Wrap`]
564    pub const fn wrap(&self) -> Wrap {
565        self.wrap
566    }
567
568    /// Set the current [`Wrap`]
569    pub fn set_wrap(&mut self, font_system: &mut FontSystem, wrap: Wrap) {
570        if wrap != self.wrap {
571            self.wrap = wrap;
572            self.relayout(font_system);
573            self.shape_until_scroll(font_system, false);
574        }
575    }
576
577    /// Get the current `monospace_width`
578    pub const fn monospace_width(&self) -> Option<f32> {
579        self.monospace_width
580    }
581
582    /// Set monospace width monospace glyphs should be resized to match. `None` means don't resize
583    pub fn set_monospace_width(
584        &mut self,
585        font_system: &mut FontSystem,
586        monospace_width: Option<f32>,
587    ) {
588        if monospace_width != self.monospace_width {
589            self.monospace_width = monospace_width;
590            self.relayout(font_system);
591            self.shape_until_scroll(font_system, false);
592        }
593    }
594
595    /// Get the current `tab_width`
596    pub const fn tab_width(&self) -> u16 {
597        self.tab_width
598    }
599
600    /// Set tab width (number of spaces between tab stops)
601    pub fn set_tab_width(&mut self, font_system: &mut FontSystem, tab_width: u16) {
602        // A tab width of 0 is not allowed
603        if tab_width == 0 {
604            return;
605        }
606        if tab_width != self.tab_width {
607            self.tab_width = tab_width;
608            // Shaping must be reset when tab width is changed
609            for line in &mut self.lines {
610                if line.shape_opt().is_some() && line.text().contains('\t') {
611                    line.reset_shaping();
612                }
613            }
614            self.redraw = true;
615            self.shape_until_scroll(font_system, false);
616        }
617    }
618
619    /// Get the current buffer dimensions (width, height)
620    pub const fn size(&self) -> (Option<f32>, Option<f32>) {
621        (self.width_opt, self.height_opt)
622    }
623
624    /// Set the current buffer dimensions
625    pub fn set_size(
626        &mut self,
627        font_system: &mut FontSystem,
628        width_opt: Option<f32>,
629        height_opt: Option<f32>,
630    ) {
631        self.set_metrics_and_size(font_system, self.metrics, width_opt, height_opt);
632    }
633
634    /// Set the current [`Metrics`] and buffer dimensions at the same time
635    ///
636    /// # Panics
637    ///
638    /// Will panic if `metrics.font_size` is zero.
639    pub fn set_metrics_and_size(
640        &mut self,
641        font_system: &mut FontSystem,
642        metrics: Metrics,
643        width_opt: Option<f32>,
644        height_opt: Option<f32>,
645    ) {
646        let clamped_width_opt = width_opt.map(|width| width.max(0.0));
647        let clamped_height_opt = height_opt.map(|height| height.max(0.0));
648
649        if metrics != self.metrics
650            || clamped_width_opt != self.width_opt
651            || clamped_height_opt != self.height_opt
652        {
653            assert_ne!(metrics.font_size, 0.0, "font size cannot be 0");
654            self.metrics = metrics;
655            self.width_opt = clamped_width_opt;
656            self.height_opt = clamped_height_opt;
657            self.relayout(font_system);
658            self.shape_until_scroll(font_system, false);
659        }
660    }
661
662    /// Get the current scroll location
663    pub const fn scroll(&self) -> Scroll {
664        self.scroll
665    }
666
667    /// Set the current scroll location
668    pub fn set_scroll(&mut self, scroll: Scroll) {
669        if scroll != self.scroll {
670            self.scroll = scroll;
671            self.redraw = true;
672        }
673    }
674
675    /// Set text of buffer, using provided attributes for each line by default
676    pub fn set_text(
677        &mut self,
678        font_system: &mut FontSystem,
679        text: &str,
680        attrs: &Attrs,
681        shaping: Shaping,
682        alignment: Option<Align>,
683    ) {
684        self.lines.clear();
685        for (range, ending) in LineIter::new(text) {
686            self.lines.push(BufferLine::new(
687                &text[range],
688                ending,
689                AttrsList::new(attrs),
690                shaping,
691            ));
692        }
693        if self.lines.is_empty() {
694            self.lines.push(BufferLine::new(
695                "",
696                LineEnding::default(),
697                AttrsList::new(attrs),
698                shaping,
699            ));
700        }
701
702        if alignment.is_some() {
703            self.lines.iter_mut().for_each(|line| {
704                line.set_align(alignment);
705            });
706        }
707
708        self.scroll = Scroll::default();
709        self.shape_until_scroll(font_system, false);
710    }
711
712    /// Set text of buffer, using an iterator of styled spans (pairs of text and attributes)
713    ///
714    /// ```
715    /// # use cosmic_text::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping};
716    /// # let mut font_system = FontSystem::new();
717    /// let mut buffer = Buffer::new_empty(Metrics::new(32.0, 44.0));
718    /// let attrs = Attrs::new().family(Family::Serif);
719    /// buffer.set_rich_text(
720    ///     &mut font_system,
721    ///     [
722    ///         ("hello, ", attrs.clone()),
723    ///         ("cosmic\ntext", attrs.clone().family(Family::Monospace)),
724    ///     ],
725    ///     &attrs,
726    ///     Shaping::Advanced,
727    ///     None,
728    /// );
729    /// ```
730    pub fn set_rich_text<'r, 's, I>(
731        &mut self,
732        font_system: &mut FontSystem,
733        spans: I,
734        default_attrs: &Attrs,
735        shaping: Shaping,
736        alignment: Option<Align>,
737    ) where
738        I: IntoIterator<Item = (&'s str, Attrs<'r>)>,
739    {
740        let mut end = 0;
741        // TODO: find a way to cache this string and vec for reuse
742        let (string, spans_data): (String, Vec<_>) = spans
743            .into_iter()
744            .map(|(s, attrs)| {
745                let start = end;
746                end += s.len();
747                (s, (attrs, start..end))
748            })
749            .unzip();
750
751        let mut spans_iter = spans_data.into_iter();
752        let mut maybe_span = spans_iter.next();
753
754        // split the string into lines, as ranges
755        let string_start = string.as_ptr() as usize;
756        let mut lines_iter = BidiParagraphs::new(&string).map(|line: &str| {
757            let start = line.as_ptr() as usize - string_start;
758            let end = start + line.len();
759            start..end
760        });
761        let mut maybe_line = lines_iter.next();
762        //TODO: set this based on information from spans
763        let line_ending = LineEnding::default();
764
765        let mut line_count = 0;
766        let mut attrs_list = self
767            .lines
768            .get_mut(line_count)
769            .map_or_else(|| AttrsList::new(&Attrs::new()), BufferLine::reclaim_attrs)
770            .reset(default_attrs);
771        let mut line_string = self
772            .lines
773            .get_mut(line_count)
774            .map(BufferLine::reclaim_text)
775            .unwrap_or_default();
776
777        loop {
778            let (Some(line_range), Some((attrs, span_range))) = (&maybe_line, &maybe_span) else {
779                // this is reached only if this text is empty
780                if self.lines.len() == line_count {
781                    self.lines.push(BufferLine::empty());
782                }
783                self.lines[line_count].reset_new(
784                    String::new(),
785                    line_ending,
786                    AttrsList::new(default_attrs),
787                    shaping,
788                );
789                line_count += 1;
790                break;
791            };
792
793            // start..end is the intersection of this line and this span
794            let start = line_range.start.max(span_range.start);
795            let end = line_range.end.min(span_range.end);
796            if start < end {
797                let text = &string[start..end];
798                let text_start = line_string.len();
799                line_string.push_str(text);
800                let text_end = line_string.len();
801                // Only add attrs if they don't match the defaults
802                if *attrs != attrs_list.defaults() {
803                    attrs_list.add_span(text_start..text_end, attrs);
804                }
805            }
806
807            // we know that at the end of a line,
808            // span text's end index is always >= line text's end index
809            // so if this span ends before this line ends,
810            // there is another span in this line.
811            // otherwise, we move on to the next line.
812            if span_range.end < line_range.end {
813                maybe_span = spans_iter.next();
814            } else {
815                maybe_line = lines_iter.next();
816                if maybe_line.is_some() {
817                    // finalize this line and start a new line
818                    let next_attrs_list = self
819                        .lines
820                        .get_mut(line_count + 1)
821                        .map_or_else(|| AttrsList::new(&Attrs::new()), BufferLine::reclaim_attrs)
822                        .reset(default_attrs);
823                    let next_line_string = self
824                        .lines
825                        .get_mut(line_count + 1)
826                        .map(BufferLine::reclaim_text)
827                        .unwrap_or_default();
828                    let prev_attrs_list = core::mem::replace(&mut attrs_list, next_attrs_list);
829                    let prev_line_string = core::mem::replace(&mut line_string, next_line_string);
830                    if self.lines.len() == line_count {
831                        self.lines.push(BufferLine::empty());
832                    }
833                    self.lines[line_count].reset_new(
834                        prev_line_string,
835                        line_ending,
836                        prev_attrs_list,
837                        shaping,
838                    );
839                    line_count += 1;
840                } else {
841                    // finalize the final line
842                    if self.lines.len() == line_count {
843                        self.lines.push(BufferLine::empty());
844                    }
845                    self.lines[line_count].reset_new(line_string, line_ending, attrs_list, shaping);
846                    line_count += 1;
847                    break;
848                }
849            }
850        }
851
852        // Discard excess lines now that we have reused as much of the existing allocations as possible.
853        self.lines.truncate(line_count);
854
855        self.lines.iter_mut().for_each(|line| {
856            line.set_align(alignment);
857        });
858
859        self.scroll = Scroll::default();
860
861        self.shape_until_scroll(font_system, false);
862    }
863
864    /// True if a redraw is needed
865    pub const fn redraw(&self) -> bool {
866        self.redraw
867    }
868
869    /// Set redraw needed flag
870    pub fn set_redraw(&mut self, redraw: bool) {
871        self.redraw = redraw;
872    }
873
874    /// Get the visible layout runs for rendering and other tasks
875    pub fn layout_runs(&self) -> LayoutRunIter<'_> {
876        LayoutRunIter::new(self)
877    }
878
879    /// Convert x, y position to Cursor (hit detection)
880    pub fn hit(&self, x: f32, y: f32) -> Option<Cursor> {
881        #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
882        let instant = std::time::Instant::now();
883
884        let mut new_cursor_opt = None;
885
886        let mut runs = self.layout_runs().peekable();
887        let mut first_run = true;
888        while let Some(run) = runs.next() {
889            let line_top = run.line_top;
890            let line_height = run.line_height;
891
892            if first_run && y < line_top {
893                first_run = false;
894                let new_cursor = Cursor::new(run.line_i, 0);
895                new_cursor_opt = Some(new_cursor);
896            } else if y >= line_top && y < line_top + line_height {
897                let mut new_cursor_glyph = run.glyphs.len();
898                let mut new_cursor_char = 0;
899                let mut new_cursor_affinity = Affinity::After;
900
901                let mut first_glyph = true;
902
903                'hit: for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
904                    if first_glyph {
905                        first_glyph = false;
906                        if (run.rtl && x > glyph.x) || (!run.rtl && x < 0.0) {
907                            new_cursor_glyph = 0;
908                            new_cursor_char = 0;
909                        }
910                    }
911                    if x >= glyph.x && x <= glyph.x + glyph.w {
912                        new_cursor_glyph = glyph_i;
913
914                        let cluster = &run.text[glyph.start..glyph.end];
915                        let total = cluster.grapheme_indices(true).count();
916                        let mut egc_x = glyph.x;
917                        let egc_w = glyph.w / (total as f32);
918                        for (egc_i, egc) in cluster.grapheme_indices(true) {
919                            if x >= egc_x && x <= egc_x + egc_w {
920                                new_cursor_char = egc_i;
921
922                                let right_half = x >= egc_x + egc_w / 2.0;
923                                if right_half != glyph.level.is_rtl() {
924                                    // If clicking on last half of glyph, move cursor past glyph
925                                    new_cursor_char += egc.len();
926                                    new_cursor_affinity = Affinity::Before;
927                                }
928                                break 'hit;
929                            }
930                            egc_x += egc_w;
931                        }
932
933                        let right_half = x >= glyph.x + glyph.w / 2.0;
934                        if right_half != glyph.level.is_rtl() {
935                            // If clicking on last half of glyph, move cursor past glyph
936                            new_cursor_char = cluster.len();
937                            new_cursor_affinity = Affinity::Before;
938                        }
939                        break 'hit;
940                    }
941                }
942
943                let mut new_cursor = Cursor::new(run.line_i, 0);
944
945                match run.glyphs.get(new_cursor_glyph) {
946                    Some(glyph) => {
947                        // Position at glyph
948                        new_cursor.index = glyph.start + new_cursor_char;
949                        new_cursor.affinity = new_cursor_affinity;
950                    }
951                    None => {
952                        if let Some(glyph) = run.glyphs.last() {
953                            // Position at end of line
954                            new_cursor.index = glyph.end;
955                            new_cursor.affinity = Affinity::Before;
956                        }
957                    }
958                }
959
960                new_cursor_opt = Some(new_cursor);
961
962                break;
963            } else if runs.peek().is_none() && y > run.line_y {
964                let mut new_cursor = Cursor::new(run.line_i, 0);
965                if let Some(glyph) = run.glyphs.last() {
966                    new_cursor = run.cursor_from_glyph_right(glyph);
967                }
968                new_cursor_opt = Some(new_cursor);
969            }
970        }
971
972        #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
973        log::trace!("click({}, {}): {:?}", x, y, instant.elapsed());
974
975        new_cursor_opt
976    }
977
978    /// Apply a [`Motion`] to a [`Cursor`]
979    pub fn cursor_motion(
980        &mut self,
981        font_system: &mut FontSystem,
982        mut cursor: Cursor,
983        mut cursor_x_opt: Option<i32>,
984        motion: Motion,
985    ) -> Option<(Cursor, Option<i32>)> {
986        match motion {
987            Motion::LayoutCursor(layout_cursor) => {
988                let layout = self.line_layout(font_system, layout_cursor.line)?;
989
990                let layout_line = match layout.get(layout_cursor.layout) {
991                    Some(some) => some,
992                    None => match layout.last() {
993                        Some(some) => some,
994                        None => {
995                            return None;
996                        }
997                    },
998                };
999
1000                let (new_index, new_affinity) =
1001                    layout_line.glyphs.get(layout_cursor.glyph).map_or_else(
1002                        || {
1003                            layout_line
1004                                .glyphs
1005                                .last()
1006                                .map_or((0, Affinity::After), |glyph| (glyph.end, Affinity::Before))
1007                        },
1008                        |glyph| (glyph.start, Affinity::After),
1009                    );
1010
1011                if cursor.line != layout_cursor.line
1012                    || cursor.index != new_index
1013                    || cursor.affinity != new_affinity
1014                {
1015                    cursor.line = layout_cursor.line;
1016                    cursor.index = new_index;
1017                    cursor.affinity = new_affinity;
1018                }
1019            }
1020            Motion::Previous => {
1021                let line = self.lines.get(cursor.line)?;
1022                if cursor.index > 0 {
1023                    // Find previous character index
1024                    let mut prev_index = 0;
1025                    for (i, _) in line.text().grapheme_indices(true) {
1026                        if i < cursor.index {
1027                            prev_index = i;
1028                        } else {
1029                            break;
1030                        }
1031                    }
1032
1033                    cursor.index = prev_index;
1034                    cursor.affinity = Affinity::After;
1035                } else if cursor.line > 0 {
1036                    cursor.line -= 1;
1037                    cursor.index = self.lines.get(cursor.line)?.text().len();
1038                    cursor.affinity = Affinity::After;
1039                }
1040                cursor_x_opt = None;
1041            }
1042            Motion::Next => {
1043                let line = self.lines.get(cursor.line)?;
1044                if cursor.index < line.text().len() {
1045                    for (i, c) in line.text().grapheme_indices(true) {
1046                        if i == cursor.index {
1047                            cursor.index += c.len();
1048                            cursor.affinity = Affinity::Before;
1049                            break;
1050                        }
1051                    }
1052                } else if cursor.line + 1 < self.lines.len() {
1053                    cursor.line += 1;
1054                    cursor.index = 0;
1055                    cursor.affinity = Affinity::Before;
1056                }
1057                cursor_x_opt = None;
1058            }
1059            Motion::Left => {
1060                let rtl_opt = self
1061                    .line_shape(font_system, cursor.line)
1062                    .map(|shape| shape.rtl);
1063                if let Some(rtl) = rtl_opt {
1064                    if rtl {
1065                        (cursor, cursor_x_opt) =
1066                            self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Next)?;
1067                    } else {
1068                        (cursor, cursor_x_opt) = self.cursor_motion(
1069                            font_system,
1070                            cursor,
1071                            cursor_x_opt,
1072                            Motion::Previous,
1073                        )?;
1074                    }
1075                }
1076            }
1077            Motion::Right => {
1078                let rtl_opt = self
1079                    .line_shape(font_system, cursor.line)
1080                    .map(|shape| shape.rtl);
1081                if let Some(rtl) = rtl_opt {
1082                    if rtl {
1083                        (cursor, cursor_x_opt) = self.cursor_motion(
1084                            font_system,
1085                            cursor,
1086                            cursor_x_opt,
1087                            Motion::Previous,
1088                        )?;
1089                    } else {
1090                        (cursor, cursor_x_opt) =
1091                            self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Next)?;
1092                    }
1093                }
1094            }
1095            Motion::Up => {
1096                let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1097
1098                if cursor_x_opt.is_none() {
1099                    cursor_x_opt = Some(
1100                        layout_cursor.glyph as i32, //TODO: glyph x position
1101                    );
1102                }
1103
1104                if layout_cursor.layout > 0 {
1105                    layout_cursor.layout -= 1;
1106                } else if layout_cursor.line > 0 {
1107                    layout_cursor.line -= 1;
1108                    layout_cursor.layout = usize::MAX;
1109                }
1110
1111                if let Some(cursor_x) = cursor_x_opt {
1112                    layout_cursor.glyph = cursor_x as usize; //TODO: glyph x position
1113                }
1114
1115                (cursor, cursor_x_opt) = self.cursor_motion(
1116                    font_system,
1117                    cursor,
1118                    cursor_x_opt,
1119                    Motion::LayoutCursor(layout_cursor),
1120                )?;
1121            }
1122            Motion::Down => {
1123                let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1124
1125                let layout_len = self.line_layout(font_system, layout_cursor.line)?.len();
1126
1127                if cursor_x_opt.is_none() {
1128                    cursor_x_opt = Some(
1129                        layout_cursor.glyph as i32, //TODO: glyph x position
1130                    );
1131                }
1132
1133                if layout_cursor.layout + 1 < layout_len {
1134                    layout_cursor.layout += 1;
1135                } else if layout_cursor.line + 1 < self.lines.len() {
1136                    layout_cursor.line += 1;
1137                    layout_cursor.layout = 0;
1138                }
1139
1140                if let Some(cursor_x) = cursor_x_opt {
1141                    layout_cursor.glyph = cursor_x as usize; //TODO: glyph x position
1142                }
1143
1144                (cursor, cursor_x_opt) = self.cursor_motion(
1145                    font_system,
1146                    cursor,
1147                    cursor_x_opt,
1148                    Motion::LayoutCursor(layout_cursor),
1149                )?;
1150            }
1151            Motion::Home => {
1152                let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1153                layout_cursor.glyph = 0;
1154                #[allow(unused_assignments)]
1155                {
1156                    (cursor, cursor_x_opt) = self.cursor_motion(
1157                        font_system,
1158                        cursor,
1159                        cursor_x_opt,
1160                        Motion::LayoutCursor(layout_cursor),
1161                    )?;
1162                }
1163                cursor_x_opt = None;
1164            }
1165            Motion::SoftHome => {
1166                let line = self.lines.get(cursor.line)?;
1167                cursor.index = line
1168                    .text()
1169                    .char_indices()
1170                    .find_map(|(i, c)| if c.is_whitespace() { None } else { Some(i) })
1171                    .unwrap_or(0);
1172                cursor_x_opt = None;
1173            }
1174            Motion::End => {
1175                let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1176                layout_cursor.glyph = usize::MAX;
1177                #[allow(unused_assignments)]
1178                {
1179                    (cursor, cursor_x_opt) = self.cursor_motion(
1180                        font_system,
1181                        cursor,
1182                        cursor_x_opt,
1183                        Motion::LayoutCursor(layout_cursor),
1184                    )?;
1185                }
1186                cursor_x_opt = None;
1187            }
1188            Motion::ParagraphStart => {
1189                cursor.index = 0;
1190                cursor_x_opt = None;
1191            }
1192            Motion::ParagraphEnd => {
1193                cursor.index = self.lines.get(cursor.line)?.text().len();
1194                cursor_x_opt = None;
1195            }
1196            Motion::PageUp => {
1197                if let Some(height) = self.height_opt {
1198                    (cursor, cursor_x_opt) = self.cursor_motion(
1199                        font_system,
1200                        cursor,
1201                        cursor_x_opt,
1202                        Motion::Vertical(-height as i32),
1203                    )?;
1204                }
1205            }
1206            Motion::PageDown => {
1207                if let Some(height) = self.height_opt {
1208                    (cursor, cursor_x_opt) = self.cursor_motion(
1209                        font_system,
1210                        cursor,
1211                        cursor_x_opt,
1212                        Motion::Vertical(height as i32),
1213                    )?;
1214                }
1215            }
1216            Motion::Vertical(px) => {
1217                // TODO more efficient, use layout run line height
1218                let lines = px / self.metrics().line_height as i32;
1219                match lines.cmp(&0) {
1220                    cmp::Ordering::Less => {
1221                        for _ in 0..-lines {
1222                            (cursor, cursor_x_opt) =
1223                                self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Up)?;
1224                        }
1225                    }
1226                    cmp::Ordering::Greater => {
1227                        for _ in 0..lines {
1228                            (cursor, cursor_x_opt) = self.cursor_motion(
1229                                font_system,
1230                                cursor,
1231                                cursor_x_opt,
1232                                Motion::Down,
1233                            )?;
1234                        }
1235                    }
1236                    cmp::Ordering::Equal => {}
1237                }
1238            }
1239            Motion::PreviousWord => {
1240                let line = self.lines.get(cursor.line)?;
1241                if cursor.index > 0 {
1242                    cursor.index = line
1243                        .text()
1244                        .unicode_word_indices()
1245                        .rev()
1246                        .map(|(i, _)| i)
1247                        .find(|&i| i < cursor.index)
1248                        .unwrap_or(0);
1249                } else if cursor.line > 0 {
1250                    cursor.line -= 1;
1251                    cursor.index = self.lines.get(cursor.line)?.text().len();
1252                }
1253                cursor_x_opt = None;
1254            }
1255            Motion::NextWord => {
1256                let line = self.lines.get(cursor.line)?;
1257                if cursor.index < line.text().len() {
1258                    cursor.index = line
1259                        .text()
1260                        .unicode_word_indices()
1261                        .map(|(i, word)| i + word.len())
1262                        .find(|&i| i > cursor.index)
1263                        .unwrap_or_else(|| line.text().len());
1264                } else if cursor.line + 1 < self.lines.len() {
1265                    cursor.line += 1;
1266                    cursor.index = 0;
1267                }
1268                cursor_x_opt = None;
1269            }
1270            Motion::LeftWord => {
1271                let rtl_opt = self
1272                    .line_shape(font_system, cursor.line)
1273                    .map(|shape| shape.rtl);
1274                if let Some(rtl) = rtl_opt {
1275                    if rtl {
1276                        (cursor, cursor_x_opt) = self.cursor_motion(
1277                            font_system,
1278                            cursor,
1279                            cursor_x_opt,
1280                            Motion::NextWord,
1281                        )?;
1282                    } else {
1283                        (cursor, cursor_x_opt) = self.cursor_motion(
1284                            font_system,
1285                            cursor,
1286                            cursor_x_opt,
1287                            Motion::PreviousWord,
1288                        )?;
1289                    }
1290                }
1291            }
1292            Motion::RightWord => {
1293                let rtl_opt = self
1294                    .line_shape(font_system, cursor.line)
1295                    .map(|shape| shape.rtl);
1296                if let Some(rtl) = rtl_opt {
1297                    if rtl {
1298                        (cursor, cursor_x_opt) = self.cursor_motion(
1299                            font_system,
1300                            cursor,
1301                            cursor_x_opt,
1302                            Motion::PreviousWord,
1303                        )?;
1304                    } else {
1305                        (cursor, cursor_x_opt) = self.cursor_motion(
1306                            font_system,
1307                            cursor,
1308                            cursor_x_opt,
1309                            Motion::NextWord,
1310                        )?;
1311                    }
1312                }
1313            }
1314            Motion::BufferStart => {
1315                cursor.line = 0;
1316                cursor.index = 0;
1317                cursor_x_opt = None;
1318            }
1319            Motion::BufferEnd => {
1320                cursor.line = self.lines.len().saturating_sub(1);
1321                cursor.index = self.lines.get(cursor.line)?.text().len();
1322                cursor_x_opt = None;
1323            }
1324            Motion::GotoLine(line) => {
1325                let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1326                layout_cursor.line = line;
1327                (cursor, cursor_x_opt) = self.cursor_motion(
1328                    font_system,
1329                    cursor,
1330                    cursor_x_opt,
1331                    Motion::LayoutCursor(layout_cursor),
1332                )?;
1333            }
1334        }
1335        Some((cursor, cursor_x_opt))
1336    }
1337
1338    /// Draw the buffer
1339    #[cfg(feature = "swash")]
1340    pub fn draw<F>(
1341        &self,
1342        font_system: &mut FontSystem,
1343        cache: &mut crate::SwashCache,
1344        color: Color,
1345        mut f: F,
1346    ) where
1347        F: FnMut(i32, i32, u32, u32, Color),
1348    {
1349        for run in self.layout_runs() {
1350            for glyph in run.glyphs {
1351                let physical_glyph = glyph.physical((0., 0.), 1.0);
1352                let glyph_color = glyph.color_opt.map_or(color, |some| some);
1353
1354                cache.with_pixels(
1355                    font_system,
1356                    physical_glyph.cache_key,
1357                    glyph_color,
1358                    |x, y, color| {
1359                        f(
1360                            physical_glyph.x + x,
1361                            run.line_y as i32 + physical_glyph.y + y,
1362                            1,
1363                            1,
1364                            color,
1365                        );
1366                    },
1367                );
1368            }
1369        }
1370    }
1371}
1372
1373impl BorrowedWithFontSystem<'_, Buffer> {
1374    /// Shape lines until cursor, also scrolling to include cursor in view
1375    pub fn shape_until_cursor(&mut self, cursor: Cursor, prune: bool) {
1376        self.inner
1377            .shape_until_cursor(self.font_system, cursor, prune);
1378    }
1379
1380    /// Shape lines until scroll
1381    pub fn shape_until_scroll(&mut self, prune: bool) {
1382        self.inner.shape_until_scroll(self.font_system, prune);
1383    }
1384
1385    /// Shape the provided line index and return the result
1386    pub fn line_shape(&mut self, line_i: usize) -> Option<&ShapeLine> {
1387        self.inner.line_shape(self.font_system, line_i)
1388    }
1389
1390    /// Lay out the provided line index and return the result
1391    pub fn line_layout(&mut self, line_i: usize) -> Option<&[LayoutLine]> {
1392        self.inner.line_layout(self.font_system, line_i)
1393    }
1394
1395    /// Set the current [`Metrics`]
1396    ///
1397    /// # Panics
1398    ///
1399    /// Will panic if `metrics.font_size` is zero.
1400    pub fn set_metrics(&mut self, metrics: Metrics) {
1401        self.inner.set_metrics(self.font_system, metrics);
1402    }
1403
1404    /// Set the current [`Wrap`]
1405    pub fn set_wrap(&mut self, wrap: Wrap) {
1406        self.inner.set_wrap(self.font_system, wrap);
1407    }
1408
1409    /// Set the current buffer dimensions
1410    pub fn set_size(&mut self, width_opt: Option<f32>, height_opt: Option<f32>) {
1411        self.inner.set_size(self.font_system, width_opt, height_opt);
1412    }
1413
1414    /// Set the current [`Metrics`] and buffer dimensions at the same time
1415    ///
1416    /// # Panics
1417    ///
1418    /// Will panic if `metrics.font_size` is zero.
1419    pub fn set_metrics_and_size(
1420        &mut self,
1421        metrics: Metrics,
1422        width_opt: Option<f32>,
1423        height_opt: Option<f32>,
1424    ) {
1425        self.inner
1426            .set_metrics_and_size(self.font_system, metrics, width_opt, height_opt);
1427    }
1428
1429    /// Set tab width (number of spaces between tab stops)
1430    pub fn set_tab_width(&mut self, tab_width: u16) {
1431        self.inner.set_tab_width(self.font_system, tab_width);
1432    }
1433
1434    /// Set text of buffer, using provided attributes for each line by default
1435    pub fn set_text(
1436        &mut self,
1437        text: &str,
1438        attrs: &Attrs,
1439        shaping: Shaping,
1440        alignment: Option<Align>,
1441    ) {
1442        self.inner
1443            .set_text(self.font_system, text, attrs, shaping, alignment);
1444    }
1445
1446    /// Set text of buffer, using an iterator of styled spans (pairs of text and attributes)
1447    ///
1448    /// ```
1449    /// # use cosmic_text::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping};
1450    /// # let mut font_system = FontSystem::new();
1451    /// let mut buffer = Buffer::new_empty(Metrics::new(32.0, 44.0));
1452    /// let attrs = Attrs::new().family(Family::Serif);
1453    /// buffer.set_rich_text(
1454    ///     &mut font_system,
1455    ///     [
1456    ///         ("hello, ", attrs.clone()),
1457    ///         ("cosmic\ntext", attrs.clone().family(Family::Monospace)),
1458    ///     ],
1459    ///     &attrs,
1460    ///     Shaping::Advanced,
1461    ///     None,
1462    /// );
1463    /// ```
1464    pub fn set_rich_text<'r, 's, I>(
1465        &mut self,
1466        spans: I,
1467        default_attrs: &Attrs,
1468        shaping: Shaping,
1469        alignment: Option<Align>,
1470    ) where
1471        I: IntoIterator<Item = (&'s str, Attrs<'r>)>,
1472    {
1473        self.inner
1474            .set_rich_text(self.font_system, spans, default_attrs, shaping, alignment);
1475    }
1476
1477    /// Apply a [`Motion`] to a [`Cursor`]
1478    pub fn cursor_motion(
1479        &mut self,
1480        cursor: Cursor,
1481        cursor_x_opt: Option<i32>,
1482        motion: Motion,
1483    ) -> Option<(Cursor, Option<i32>)> {
1484        self.inner
1485            .cursor_motion(self.font_system, cursor, cursor_x_opt, motion)
1486    }
1487
1488    /// Draw the buffer
1489    #[cfg(feature = "swash")]
1490    pub fn draw<F>(&mut self, cache: &mut crate::SwashCache, color: Color, f: F)
1491    where
1492        F: FnMut(i32, i32, u32, u32, Color),
1493    {
1494        self.inner.draw(self.font_system, cache, color, f);
1495    }
1496}