Skip to main content

gpui/text_system/
line.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{
3    App, Bounds, DevicePixels, Half, Hsla, LineLayout, Pixels, Point, RenderGlyphParams, Result,
4    SharedString, StrikethroughStyle, TextAlign, UnderlineStyle, Window, WrapBoundary,
5    WrappedLineLayout, black, fill, point, px, size, underline_y_offset,
6};
7use derive_more::{Deref, DerefMut};
8use smallvec::SmallVec;
9use std::{ops::Range, sync::Arc};
10
11/// Pre-computed glyph data for efficient painting without per-glyph cache lookups.
12///
13/// This is produced by `ShapedLine::compute_glyph_raster_data` during prepaint
14/// and consumed by `ShapedLine::paint_with_raster_data` during paint.
15#[derive(Clone, Debug)]
16pub struct GlyphRasterData {
17    /// The raster bounds for each glyph, in paint order.
18    pub bounds: Vec<Bounds<DevicePixels>>,
19    /// The render params for each glyph (needed for sprite atlas lookup).
20    pub params: Vec<RenderGlyphParams>,
21}
22
23/// Set the text decoration for a run of text.
24#[derive(Debug, Clone)]
25pub struct DecorationRun {
26    /// The length of the run in utf-8 bytes.
27    pub len: u32,
28
29    /// The color for this run
30    pub color: Hsla,
31
32    /// The background color for this run
33    pub background_color: Option<Hsla>,
34
35    /// The underline style for this run
36    pub underline: Option<UnderlineStyle>,
37
38    /// The strikethrough style for this run
39    pub strikethrough: Option<StrikethroughStyle>,
40}
41
42/// A line of text that has been shaped and decorated.
43#[derive(Clone, Default, Debug, Deref, DerefMut)]
44pub struct ShapedLine {
45    #[deref]
46    #[deref_mut]
47    pub(crate) layout: Arc<LineLayout>,
48    /// The text that was shaped for this line.
49    pub text: SharedString,
50    pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
51}
52
53impl ShapedLine {
54    /// Returns a forward-only cursor for this shaped line.
55    pub fn cursor(&self) -> ShapedLineCursor<'_> {
56        assert_eq!(
57            self.len(),
58            self.text.len(),
59            "cannot split a shaped line with an adjusted length"
60        );
61        let byte_ordered = self
62            .layout
63            .runs
64            .iter()
65            .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.index))
66            .is_sorted();
67        ShapedLineCursor {
68            line: self,
69            unordered_remainder: (!byte_ordered).then(|| self.clone()),
70            byte_index: 0,
71            run_index: 0,
72            glyph_index: 0,
73            decoration_index: 0,
74            decoration_offset: 0,
75            x_offset: px(0.),
76        }
77    }
78
79    /// The length of the line in utf-8 bytes.
80    #[allow(clippy::len_without_is_empty)]
81    pub fn len(&self) -> usize {
82        self.layout.len
83    }
84
85    /// The width of the shaped line in pixels.
86    ///
87    /// This is the glyph advance width computed by the text shaping system and is useful for
88    /// incrementally advancing a "pen" when painting multiple fragments on the same row.
89    pub fn width(&self) -> Pixels {
90        self.layout.width
91    }
92
93    /// Override the len, useful if you're rendering text a
94    /// as text b (e.g. rendering invisibles).
95    pub fn with_len(mut self, len: usize) -> Self {
96        let layout = self.layout.as_ref();
97        self.layout = Arc::new(LineLayout {
98            font_size: layout.font_size,
99            width: layout.width,
100            ascent: layout.ascent,
101            descent: layout.descent,
102            runs: layout.runs.clone(),
103            len,
104        });
105        self
106    }
107
108    /// Paint the line of text to the window.
109    pub fn paint(
110        &self,
111        origin: Point<Pixels>,
112        line_height: Pixels,
113        align: TextAlign,
114        align_width: Option<Pixels>,
115        window: &mut Window,
116        cx: &mut App,
117    ) -> Result<()> {
118        self.paint_with_underline_handler(
119            origin,
120            line_height,
121            align,
122            align_width,
123            window,
124            cx,
125            |_, origin, width, style, window| window.paint_underline(origin, width, style),
126        )
127    }
128
129    /// Paint the line with a handler for each underline.
130    pub fn paint_with_underline_handler(
131        &self,
132        origin: Point<Pixels>,
133        line_height: Pixels,
134        align: TextAlign,
135        align_width: Option<Pixels>,
136        window: &mut Window,
137        cx: &mut App,
138        mut paint_underline: impl FnMut(
139            Range<usize>,
140            Point<Pixels>,
141            Pixels,
142            &UnderlineStyle,
143            &mut Window,
144        ),
145    ) -> Result<()> {
146        paint_line(
147            origin,
148            &self.layout,
149            line_height,
150            align,
151            align_width,
152            &self.decoration_runs,
153            &[],
154            window,
155            cx,
156            &mut paint_underline,
157        )
158    }
159
160    /// Paint the background of the line to the window.
161    pub fn paint_background(
162        &self,
163        origin: Point<Pixels>,
164        line_height: Pixels,
165        align: TextAlign,
166        align_width: Option<Pixels>,
167        window: &mut Window,
168        cx: &mut App,
169    ) -> Result<()> {
170        if !has_background(&self.decoration_runs) {
171            return Ok(());
172        }
173        paint_line_background(
174            origin,
175            &self.layout,
176            line_height,
177            align,
178            align_width,
179            &self.decoration_runs,
180            &[],
181            window,
182            cx,
183        )?;
184
185        Ok(())
186    }
187
188    /// Split this shaped line at a byte index, returning `(prefix, suffix)`.
189    ///
190    /// - `prefix` contains glyphs for bytes `[0, byte_index)` with original positions.
191    ///   Its width equals the x-advance up to the split point.
192    /// - `suffix` contains glyphs for bytes `[byte_index, len)` with positions
193    ///   shifted left so the first glyph starts at x=0, and byte indices rebased to 0.
194    /// - Decoration runs are partitioned at the boundary; a run that straddles it is
195    ///   split into two with adjusted lengths.
196    /// - `font_size`, `ascent`, and `descent` are copied to both halves.
197    pub fn split_at(&self, byte_index: usize) -> (ShapedLine, ShapedLine) {
198        let (left_layout, right_layout) = self.layout.split_at(byte_index);
199
200        // Partition decoration runs. A run straddling the boundary is split into two.
201        let mut left_decorations = SmallVec::new();
202        let mut right_decorations = SmallVec::new();
203        let mut decoration_offset = 0u32;
204        let split_point = byte_index as u32;
205
206        for decoration in &self.decoration_runs {
207            let run_end = decoration_offset + decoration.len;
208
209            if run_end <= split_point {
210                left_decorations.push(decoration.clone());
211            } else if decoration_offset >= split_point {
212                right_decorations.push(decoration.clone());
213            } else {
214                let left_len = split_point - decoration_offset;
215                let right_len = run_end - split_point;
216                left_decorations.push(DecorationRun {
217                    len: left_len,
218                    color: decoration.color,
219                    background_color: decoration.background_color,
220                    underline: decoration.underline,
221                    strikethrough: decoration.strikethrough,
222                });
223                right_decorations.push(DecorationRun {
224                    len: right_len,
225                    color: decoration.color,
226                    background_color: decoration.background_color,
227                    underline: decoration.underline,
228                    strikethrough: decoration.strikethrough,
229                });
230            }
231
232            decoration_offset = run_end;
233        }
234
235        // Split text
236        let left_text = if byte_index == self.text.len() {
237            self.text.clone()
238        } else {
239            SharedString::new(&self.text[..byte_index])
240        };
241        let right_text = if byte_index == 0 {
242            self.text.clone()
243        } else {
244            SharedString::new(&self.text[byte_index..])
245        };
246
247        let left = ShapedLine {
248            layout: Arc::new(left_layout),
249            text: left_text,
250            decoration_runs: left_decorations,
251        };
252
253        let right = ShapedLine {
254            layout: Arc::new(right_layout),
255            text: right_text,
256            decoration_runs: right_decorations,
257        };
258
259        (left, right)
260    }
261}
262
263/// Incrementally splits a [`ShapedLine`] at increasing UTF-8 byte boundaries.
264///
265/// Each piece preserves the original glyphs and decorations, rebased as in
266/// [`ShapedLine::split_at`]. Byte-ordered glyphs are advanced in linear time,
267/// copying each glyph and byte at most once; visually reordered glyphs fall
268/// back to the existing split operation.
269pub struct ShapedLineCursor<'a> {
270    line: &'a ShapedLine,
271    /// Bidirectional shaping can put glyphs out of byte order.
272    unordered_remainder: Option<ShapedLine>,
273    byte_index: usize,
274    run_index: usize,
275    glyph_index: usize,
276    decoration_index: usize,
277    decoration_offset: u32,
278    x_offset: Pixels,
279}
280
281impl<'a> ShapedLineCursor<'a> {
282    /// Takes the bytes since the previous boundary.
283    ///
284    /// Panics if the boundary precedes the previous one, exceeds the line's
285    /// length, or falls inside a UTF-8 character.
286    pub fn take_until(&mut self, byte_index: usize) -> ShapedLine {
287        assert!(
288            byte_index >= self.byte_index,
289            "split boundary moved backwards"
290        );
291        assert!(
292            byte_index <= self.line.len(),
293            "split boundary exceeds line length"
294        );
295        assert!(
296            self.line.text.is_char_boundary(byte_index),
297            "split boundary is not a UTF-8 character boundary"
298        );
299        let previous_index = self.byte_index;
300        let previous_x = self.x_offset;
301        if let Some(remainder) = &mut self.unordered_remainder {
302            let (piece, rest) = remainder.split_at(byte_index - previous_index);
303            *remainder = rest;
304            self.byte_index = byte_index;
305            self.x_offset = self.line.layout.x_for_index(byte_index);
306            return piece;
307        }
308        let mut runs = Vec::new();
309        let mut next_x = self.line.layout.width;
310        while let Some(run) = self.line.layout.runs.get(self.run_index) {
311            let start = self.glyph_index;
312            while let Some(glyph) = run.glyphs.get(self.glyph_index) {
313                if glyph.index >= byte_index {
314                    break;
315                }
316                self.glyph_index += 1;
317            }
318            let end = self.glyph_index;
319            if start < end {
320                runs.push(crate::ShapedRun {
321                    font_id: run.font_id,
322                    glyphs: run.glyphs[start..end]
323                        .iter()
324                        .map(|glyph| crate::ShapedGlyph {
325                            id: glyph.id,
326                            position: point(glyph.position.x - previous_x, glyph.position.y),
327                            index: glyph.index - previous_index,
328                            is_emoji: glyph.is_emoji,
329                        })
330                        .collect(),
331                });
332            }
333            if let Some(glyph) = run.glyphs.get(self.glyph_index) {
334                next_x = glyph.position.x;
335                break;
336            }
337            self.run_index += 1;
338            self.glyph_index = 0;
339        }
340        let mut decorations = SmallVec::new();
341        while let Some(decoration) = self.line.decoration_runs.get(self.decoration_index)
342            && (self.decoration_offset < byte_index as u32
343                || (decoration.len == 0 && self.decoration_offset == byte_index as u32))
344        {
345            let end = self.decoration_offset + decoration.len;
346            let start = self.decoration_offset.max(previous_index as u32);
347            let len = end.min(byte_index as u32) - start;
348            if len > 0 || decoration.len == 0 {
349                decorations.push(DecorationRun {
350                    len,
351                    color: decoration.color,
352                    background_color: decoration.background_color,
353                    underline: decoration.underline,
354                    strikethrough: decoration.strikethrough,
355                });
356            }
357            if end <= byte_index as u32 {
358                self.decoration_index += 1;
359                self.decoration_offset = end;
360            } else {
361                break;
362            }
363        }
364        self.byte_index = byte_index;
365        self.x_offset = next_x;
366        ShapedLine {
367            layout: Arc::new(LineLayout {
368                font_size: self.line.layout.font_size,
369                width: next_x - previous_x,
370                ascent: self.line.layout.ascent,
371                descent: self.line.layout.descent,
372                runs,
373                len: byte_index - previous_index,
374            }),
375            text: SharedString::new(&self.line.text[previous_index..byte_index]),
376            decoration_runs: decorations,
377        }
378    }
379
380    /// Returns the original line's x position at the current boundary.
381    pub fn x_offset(&self) -> Pixels {
382        self.x_offset
383    }
384}
385
386impl LineLayout {
387    /// Paint this layout to the window, using the given decoration runs to color
388    /// glyphs and draw underlines and strikethroughs.
389    ///
390    /// This is a lower-level alternative to [`ShapedLine::paint`] for callers that
391    /// hold a bare layout and track decorations themselves.
392    pub fn paint(
393        &self,
394        origin: Point<Pixels>,
395        line_height: Pixels,
396        align: TextAlign,
397        align_width: Option<Pixels>,
398        decoration_runs: &[DecorationRun],
399        window: &mut Window,
400        cx: &mut App,
401    ) -> Result<()> {
402        paint_line(
403            origin,
404            self,
405            line_height,
406            align,
407            align_width,
408            decoration_runs,
409            &[],
410            window,
411            cx,
412            &mut |_, origin, width, style, window| window.paint_underline(origin, width, style),
413        )
414    }
415
416    /// Paint the background of this layout to the window, using the given
417    /// decoration runs to determine background colors.
418    ///
419    /// This is a lower-level alternative to [`ShapedLine::paint_background`] for
420    /// callers that hold a bare layout and track decorations themselves.
421    pub fn paint_background(
422        &self,
423        origin: Point<Pixels>,
424        line_height: Pixels,
425        align: TextAlign,
426        align_width: Option<Pixels>,
427        decoration_runs: &[DecorationRun],
428        window: &mut Window,
429        cx: &mut App,
430    ) -> Result<()> {
431        if !has_background(decoration_runs) {
432            return Ok(());
433        }
434        paint_line_background(
435            origin,
436            self,
437            line_height,
438            align,
439            align_width,
440            decoration_runs,
441            &[],
442            window,
443            cx,
444        )
445    }
446}
447
448/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
449#[derive(Default, Debug, Deref, DerefMut)]
450pub struct WrappedLine {
451    #[deref]
452    #[deref_mut]
453    pub(crate) layout: Arc<WrappedLineLayout>,
454    /// The text that was shaped for this line.
455    pub text: SharedString,
456    pub(crate) decoration_runs: Vec<DecorationRun>,
457}
458
459impl WrappedLine {
460    /// The length of the underlying, unwrapped layout, in utf-8 bytes.
461    #[allow(clippy::len_without_is_empty)]
462    pub fn len(&self) -> usize {
463        self.layout.len()
464    }
465
466    /// Paint this line of text to the window.
467    pub fn paint(
468        &self,
469        origin: Point<Pixels>,
470        line_height: Pixels,
471        align: TextAlign,
472        bounds: Option<Bounds<Pixels>>,
473        window: &mut Window,
474        cx: &mut App,
475    ) -> Result<()> {
476        let align_width = match bounds {
477            Some(bounds) => Some(bounds.size.width),
478            None => self.layout.wrap_width,
479        };
480
481        paint_line(
482            origin,
483            &self.layout.unwrapped_layout,
484            line_height,
485            align,
486            align_width,
487            &self.decoration_runs,
488            &self.wrap_boundaries,
489            window,
490            cx,
491            &mut |_, origin, width, style, window| window.paint_underline(origin, width, style),
492        )?;
493
494        Ok(())
495    }
496
497    /// Paint the background of line of text to the window.
498    pub fn paint_background(
499        &self,
500        origin: Point<Pixels>,
501        line_height: Pixels,
502        align: TextAlign,
503        bounds: Option<Bounds<Pixels>>,
504        window: &mut Window,
505        cx: &mut App,
506    ) -> Result<()> {
507        let align_width = match bounds {
508            Some(bounds) => Some(bounds.size.width),
509            None => self.layout.wrap_width,
510        };
511
512        if !has_background(&self.decoration_runs) {
513            return Ok(());
514        }
515        paint_line_background(
516            origin,
517            &self.layout.unwrapped_layout,
518            line_height,
519            align,
520            align_width,
521            &self.decoration_runs,
522            &self.wrap_boundaries,
523            window,
524            cx,
525        )?;
526
527        Ok(())
528    }
529}
530
531fn paint_line(
532    origin: Point<Pixels>,
533    layout: &LineLayout,
534    line_height: Pixels,
535    align: TextAlign,
536    align_width: Option<Pixels>,
537    decoration_runs: &[DecorationRun],
538    wrap_boundaries: &[WrapBoundary],
539    window: &mut Window,
540    cx: &mut App,
541    paint_underline: &mut dyn FnMut(
542        Range<usize>,
543        Point<Pixels>,
544        Pixels,
545        &UnderlineStyle,
546        &mut Window,
547    ),
548) -> Result<()> {
549    let line_bounds = line_paint_bounds(
550        origin,
551        layout,
552        line_height,
553        align,
554        align_width,
555        wrap_boundaries,
556    );
557    window.paint_layer(line_bounds, |window| {
558        let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
559        let baseline_offset = point(px(0.), padding_top + layout.ascent);
560        let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent);
561        let mut decoration_runs = decoration_runs.iter();
562        let mut wraps = wrap_boundaries.iter().peekable();
563        let mut run_end = 0;
564        let mut color = black();
565        let mut current_underline: Option<(Point<Pixels>, UnderlineStyle, Range<usize>)> = None;
566        let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
567        let mut glyph_painter = crate::fast::glyphs::LineGlyphPainter::new(window);
568        let mut glyph_origin = point(
569            aligned_origin_x(
570                origin,
571                align_width.unwrap_or(layout.width),
572                px(0.0),
573                &align,
574                layout,
575                wraps.peek(),
576            ),
577            origin.y,
578        );
579        let mut prev_glyph_position = Point::default();
580        let mut max_glyph_size = size(px(0.), px(0.));
581        let mut first_glyph_x = origin.x;
582        for (run_ix, run) in layout.runs.iter().enumerate() {
583            max_glyph_size =
584                crate::fast::glyphs::bounding_box(window, cx, run.font_id, layout.font_size).size;
585
586            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
587                glyph_origin.x += glyph.position.x - prev_glyph_position.x;
588                if glyph_ix == 0 && run_ix == 0 {
589                    first_glyph_x = glyph_origin.x;
590                }
591
592                if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
593                    wraps.next();
594                    if let Some((underline_origin, underline_style, underline_range)) =
595                        current_underline.as_mut()
596                    {
597                        if glyph_origin.x == underline_origin.x {
598                            underline_origin.x -= max_glyph_size.width.half();
599                        };
600                        paint_underline(
601                            underline_range.clone(),
602                            *underline_origin,
603                            glyph_origin.x - underline_origin.x,
604                            underline_style,
605                            window,
606                        );
607                        if glyph.index < run_end {
608                            underline_origin.x = origin.x;
609                            underline_origin.y += line_height;
610                        } else {
611                            current_underline = None;
612                        }
613                    }
614                    if let Some((strikethrough_origin, strikethrough_style)) =
615                        current_strikethrough.as_mut()
616                    {
617                        if glyph_origin.x == strikethrough_origin.x {
618                            strikethrough_origin.x -= max_glyph_size.width.half();
619                        };
620                        window.paint_strikethrough(
621                            *strikethrough_origin,
622                            glyph_origin.x - strikethrough_origin.x,
623                            strikethrough_style,
624                        );
625                        if glyph.index < run_end {
626                            strikethrough_origin.x = origin.x;
627                            strikethrough_origin.y += line_height;
628                        } else {
629                            current_strikethrough = None;
630                        }
631                    }
632
633                    glyph_origin.x = aligned_origin_x(
634                        origin,
635                        align_width.unwrap_or(layout.width),
636                        glyph.position.x,
637                        &align,
638                        layout,
639                        wraps.peek(),
640                    );
641                    glyph_origin.y += line_height;
642                }
643                prev_glyph_position = glyph.position;
644
645                let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle, Range<usize>)> =
646                    None;
647                let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
648                if glyph.index >= run_end {
649                    let mut style_run = decoration_runs.next();
650
651                    // ignore style runs that apply to a partial glyph
652                    while let Some(run) = style_run {
653                        if glyph.index < run_end + (run.len as usize) {
654                            break;
655                        }
656                        run_end += run.len as usize;
657                        style_run = decoration_runs.next();
658                    }
659
660                    if let Some(style_run) = style_run {
661                        let style_run_start = run_end;
662                        if let Some((_, underline_style, underline_range)) = &mut current_underline
663                        {
664                            if style_run.underline.as_ref() != Some(underline_style) {
665                                finished_underline = current_underline.take();
666                            } else {
667                                underline_range.end = style_run_start + style_run.len as usize;
668                            }
669                        }
670                        if let Some(run_underline) = style_run.underline.as_ref() {
671                            current_underline.get_or_insert((
672                                point(glyph_origin.x, glyph_origin.y + underline_y_offset),
673                                UnderlineStyle {
674                                    color: Some(run_underline.color.unwrap_or(style_run.color)),
675                                    thickness: run_underline.thickness,
676                                    wavy: run_underline.wavy,
677                                },
678                                style_run_start..style_run_start + style_run.len as usize,
679                            ));
680                        }
681                        if let Some((_, strikethrough_style)) = &mut current_strikethrough
682                            && style_run.strikethrough.as_ref() != Some(strikethrough_style)
683                        {
684                            finished_strikethrough = current_strikethrough.take();
685                        }
686                        if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
687                            current_strikethrough.get_or_insert((
688                                point(
689                                    glyph_origin.x,
690                                    glyph_origin.y
691                                        + (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
692                                ),
693                                StrikethroughStyle {
694                                    color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
695                                    thickness: run_strikethrough.thickness,
696                                },
697                            ));
698                        }
699
700                        run_end += style_run.len as usize;
701                        color = style_run.color;
702                    } else {
703                        run_end = layout.len;
704                        finished_underline = current_underline.take();
705                        finished_strikethrough = current_strikethrough.take();
706                    }
707                }
708
709                if let Some((mut underline_origin, underline_style, underline_range)) =
710                    finished_underline
711                {
712                    if underline_origin.x == glyph_origin.x {
713                        underline_origin.x -= max_glyph_size.width.half();
714                    };
715                    paint_underline(
716                        underline_range,
717                        underline_origin,
718                        glyph_origin.x - underline_origin.x,
719                        &underline_style,
720                        window,
721                    );
722                }
723
724                if let Some((mut strikethrough_origin, strikethrough_style)) =
725                    finished_strikethrough
726                {
727                    if strikethrough_origin.x == glyph_origin.x {
728                        strikethrough_origin.x -= max_glyph_size.width.half();
729                    };
730                    window.paint_strikethrough(
731                        strikethrough_origin,
732                        glyph_origin.x - strikethrough_origin.x,
733                        &strikethrough_style,
734                    );
735                }
736
737                let max_glyph_bounds = Bounds {
738                    origin: glyph_origin,
739                    size: max_glyph_size,
740                };
741
742                let content_mask = window.content_mask();
743                if crate::fast::glyphs::LineGlyphPainter::may_reach(
744                    &mut glyph_painter,
745                    max_glyph_bounds,
746                    baseline_offset.y + glyph.position.y,
747                    &content_mask.bounds,
748                ) {
749                    let vertical_offset = point(px(0.0), glyph.position.y);
750                    if glyph.is_emoji {
751                        window.paint_emoji(
752                            glyph_origin + baseline_offset + vertical_offset,
753                            run.font_id,
754                            glyph.id,
755                            layout.font_size,
756                        )?;
757                    } else {
758                        crate::fast::glyphs::LineGlyphPainter::paint_glyph(
759                            &mut glyph_painter,
760                            window,
761                            glyph_origin + baseline_offset + vertical_offset,
762                            run.font_id,
763                            glyph.id,
764                            layout.font_size,
765                            color,
766                        )?;
767                    }
768                }
769            }
770        }
771
772        let mut last_line_end_x = first_glyph_x + layout.width;
773        if let Some(boundary) = wrap_boundaries.last() {
774            let run = &layout.runs[boundary.run_ix];
775            let glyph = &run.glyphs[boundary.glyph_ix];
776            last_line_end_x -= glyph.position.x;
777        }
778
779        if let Some((mut underline_start, underline_style, underline_range)) =
780            current_underline.take()
781        {
782            if last_line_end_x == underline_start.x {
783                underline_start.x -= max_glyph_size.width.half()
784            };
785            paint_underline(
786                underline_range,
787                underline_start,
788                last_line_end_x - underline_start.x,
789                &underline_style,
790                window,
791            );
792        }
793
794        if let Some((mut strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
795            if last_line_end_x == strikethrough_start.x {
796                strikethrough_start.x -= max_glyph_size.width.half()
797            };
798            window.paint_strikethrough(
799                strikethrough_start,
800                last_line_end_x - strikethrough_start.x,
801                &strikethrough_style,
802            );
803        }
804
805        Ok(())
806    })
807}
808
809/// Painting backgrounds walks every glyph and opens a layer, so callers skip it when there's
810/// nothing to paint.
811fn has_background(decoration_runs: &[DecorationRun]) -> bool {
812    decoration_runs
813        .iter()
814        .any(|run| run.background_color.is_some())
815}
816
817fn paint_line_background(
818    origin: Point<Pixels>,
819    layout: &LineLayout,
820    line_height: Pixels,
821    align: TextAlign,
822    align_width: Option<Pixels>,
823    decoration_runs: &[DecorationRun],
824    wrap_boundaries: &[WrapBoundary],
825    window: &mut Window,
826    cx: &mut App,
827) -> Result<()> {
828    if crate::fast::glyphs::has_no_background(decoration_runs) {
829        return Ok(());
830    }
831    let line_bounds = line_paint_bounds(
832        origin,
833        layout,
834        line_height,
835        align,
836        align_width,
837        wrap_boundaries,
838    );
839    window.paint_layer(line_bounds, |window| {
840        let mut decoration_runs = decoration_runs.iter();
841        let mut wraps = wrap_boundaries.iter().peekable();
842        let mut run_end = 0;
843        let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
844        let text_system = cx.text_system().clone();
845        let mut glyph_origin = point(
846            aligned_origin_x(
847                origin,
848                align_width.unwrap_or(layout.width),
849                px(0.0),
850                &align,
851                layout,
852                wraps.peek(),
853            ),
854            origin.y,
855        );
856        let mut prev_glyph_position = Point::default();
857        let mut max_glyph_size = size(px(0.), px(0.));
858        for (run_ix, run) in layout.runs.iter().enumerate() {
859            max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
860
861            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
862                glyph_origin.x += glyph.position.x - prev_glyph_position.x;
863
864                if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
865                    wraps.next();
866                    if let Some((background_origin, background_color)) = current_background.as_mut()
867                    {
868                        if glyph_origin.x == background_origin.x {
869                            background_origin.x -= max_glyph_size.width.half()
870                        }
871                        window.paint_quad(fill(
872                            Bounds {
873                                origin: *background_origin,
874                                size: size(glyph_origin.x - background_origin.x, line_height),
875                            },
876                            *background_color,
877                        ));
878                        if glyph.index < run_end {
879                            background_origin.x = origin.x;
880                            background_origin.y += line_height;
881                        } else {
882                            current_background = None;
883                        }
884                    }
885
886                    glyph_origin.x = aligned_origin_x(
887                        origin,
888                        align_width.unwrap_or(layout.width),
889                        glyph.position.x,
890                        &align,
891                        layout,
892                        wraps.peek(),
893                    );
894                    glyph_origin.y += line_height;
895                }
896                prev_glyph_position = glyph.position;
897
898                let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
899                if glyph.index >= run_end {
900                    let mut style_run = decoration_runs.next();
901
902                    // ignore style runs that apply to a partial glyph
903                    while let Some(run) = style_run {
904                        if glyph.index < run_end + (run.len as usize) {
905                            break;
906                        }
907                        run_end += run.len as usize;
908                        style_run = decoration_runs.next();
909                    }
910
911                    if let Some(style_run) = style_run {
912                        if let Some((_, background_color)) = &mut current_background
913                            && style_run.background_color.as_ref() != Some(background_color)
914                        {
915                            finished_background = current_background.take();
916                        }
917                        if let Some(run_background) = style_run.background_color {
918                            current_background.get_or_insert((
919                                point(glyph_origin.x, glyph_origin.y),
920                                run_background,
921                            ));
922                        }
923                        run_end += style_run.len as usize;
924                    } else {
925                        run_end = layout.len;
926                        finished_background = current_background.take();
927                    }
928                }
929
930                if let Some((mut background_origin, background_color)) = finished_background {
931                    let width = glyph_origin.x - background_origin.x;
932                    if background_origin.x == glyph_origin.x {
933                        background_origin.x -= max_glyph_size.width.half();
934                    };
935                    window.paint_quad(fill(
936                        Bounds {
937                            origin: background_origin,
938                            size: size(width, line_height),
939                        },
940                        background_color,
941                    ));
942                }
943            }
944        }
945
946        let mut last_line_end_x = origin.x + layout.width;
947        if let Some(boundary) = wrap_boundaries.last() {
948            let run = &layout.runs[boundary.run_ix];
949            let glyph = &run.glyphs[boundary.glyph_ix];
950            last_line_end_x -= glyph.position.x;
951        }
952
953        if let Some((mut background_origin, background_color)) = current_background.take() {
954            if last_line_end_x == background_origin.x {
955                background_origin.x -= max_glyph_size.width.half()
956            };
957            window.paint_quad(fill(
958                Bounds {
959                    origin: background_origin,
960                    size: size(last_line_end_x - background_origin.x, line_height),
961                },
962                background_color,
963            ));
964        }
965
966        Ok(())
967    })
968}
969
970fn line_paint_bounds(
971    origin: Point<Pixels>,
972    layout: &LineLayout,
973    line_height: Pixels,
974    align: TextAlign,
975    align_width: Option<Pixels>,
976    wrap_boundaries: &[WrapBoundary],
977) -> Bounds<Pixels> {
978    let mut bounds = Bounds::new(
979        origin,
980        size(
981            layout.width,
982            line_height * (wrap_boundaries.len() as f32 + 1.),
983        ),
984    );
985    if align == TextAlign::Left || layout.len == 0 {
986        return bounds;
987    }
988
989    let align_width = align_width.unwrap_or(layout.width);
990    let mut row_start = Pixels::ZERO;
991    let row_ends = wrap_boundaries
992        .iter()
993        .map(|boundary| {
994            layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix]
995                .position
996                .x
997        })
998        .chain([layout.width]);
999    for (row, row_end) in row_ends.enumerate() {
1000        let width = row_end - row_start;
1001        let offset = match align {
1002            TextAlign::Left => Pixels::ZERO,
1003            TextAlign::Center => (align_width - width) / 2.,
1004            TextAlign::Right => align_width - width,
1005        };
1006        bounds = bounds.union(&Bounds::new(
1007            point(origin.x + offset, origin.y + line_height * row as f32),
1008            size(width, line_height),
1009        ));
1010        row_start = row_end;
1011    }
1012    bounds
1013}
1014
1015fn aligned_origin_x(
1016    origin: Point<Pixels>,
1017    align_width: Pixels,
1018    last_glyph_x: Pixels,
1019    align: &TextAlign,
1020    layout: &LineLayout,
1021    wrap_boundary: Option<&&WrapBoundary>,
1022) -> Pixels {
1023    let end_of_line = if let Some(WrapBoundary { run_ix, glyph_ix }) = wrap_boundary {
1024        layout.runs[*run_ix].glyphs[*glyph_ix].position.x
1025    } else {
1026        layout.width
1027    };
1028
1029    let line_width = end_of_line - last_glyph_x;
1030
1031    match align {
1032        TextAlign::Left => origin.x,
1033        TextAlign::Center => (origin.x * 2.0 + align_width - line_width) / 2.0,
1034        TextAlign::Right => origin.x + align_width - line_width,
1035    }
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041    use crate::{
1042        AppContext as _, Context, FontId, GlyphId, IntoElement, Render, ShapedGlyph, ShapedRun,
1043        Styled, TestAppContext, TextRun, Underline, canvas, font, hsla,
1044    };
1045    use std::rc::Rc;
1046
1047    /// Helper: build a ShapedLine from glyph descriptors without the platform text system.
1048    /// Each glyph is described as (byte_index, x_position).
1049    fn make_shaped_line(
1050        text: &str,
1051        glyphs: &[(usize, f32)],
1052        width: f32,
1053        decorations: &[DecorationRun],
1054    ) -> ShapedLine {
1055        let shaped_glyphs: Vec<ShapedGlyph> = glyphs
1056            .iter()
1057            .map(|&(index, x)| ShapedGlyph {
1058                id: GlyphId(0),
1059                position: point(px(x), px(0.0)),
1060                index,
1061                is_emoji: false,
1062            })
1063            .collect();
1064
1065        ShapedLine {
1066            layout: Arc::new(LineLayout {
1067                font_size: px(16.0),
1068                width: px(width),
1069                ascent: px(12.0),
1070                descent: px(4.0),
1071                runs: vec![ShapedRun {
1072                    font_id: FontId(0),
1073                    glyphs: shaped_glyphs,
1074                }],
1075                len: text.len(),
1076            }),
1077            text: SharedString::new(text),
1078            decoration_runs: SmallVec::from(decorations.to_vec()),
1079        }
1080    }
1081
1082    #[test]
1083    fn test_aligned_line_paint_bounds() {
1084        let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]);
1085        let origin = point(px(10.), px(20.));
1086        let line_height = px(16.);
1087        for (wrapped, align_width, expected_edges) in [
1088            (false, None, [(10., 50.), (10., 50.), (10., 50.)]),
1089            (true, None, [(10., 50.), (10., 50.), (10., 50.)]),
1090            (false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
1091            (true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
1092            (false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]),
1093            (true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]),
1094            (false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]),
1095            (true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]),
1096            (false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]),
1097            (true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]),
1098        ] {
1099            let boundaries = if wrapped {
1100                vec![WrapBoundary {
1101                    run_ix: 0,
1102                    glyph_ix: 2,
1103                }]
1104            } else {
1105                Vec::new()
1106            };
1107            for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right]
1108                .into_iter()
1109                .zip(expected_edges)
1110            {
1111                assert_eq!(
1112                    line_paint_bounds(
1113                        origin,
1114                        &line.layout,
1115                        line_height,
1116                        align,
1117                        align_width.map(px),
1118                        &boundaries,
1119                    ),
1120                    Bounds::new(
1121                        point(px(left), origin.y),
1122                        size(px(right - left), px(if wrapped { 32. } else { 16. })),
1123                    ),
1124                    "wrapped={wrapped}, align={align:?}, align_width={align_width:?}",
1125                );
1126            }
1127        }
1128        let empty = make_shaped_line("", &[], 0., &[]);
1129        for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
1130            assert_eq!(
1131                line_paint_bounds(
1132                    origin,
1133                    &empty.layout,
1134                    line_height,
1135                    align,
1136                    Some(px(100.)),
1137                    &[]
1138                ),
1139                Bounds::new(origin, size(Pixels::ZERO, line_height)),
1140            );
1141        }
1142    }
1143
1144    #[gpui::test]
1145    fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) {
1146        test_underline_handler_at_scales(cx, |window, cx| {
1147            let first_style = UnderlineStyle {
1148                thickness: px(1.),
1149                color: Some(hsla(0., 1., 0.5, 1.)),
1150                wavy: true,
1151            };
1152            let last_style = UnderlineStyle {
1153                color: Some(hsla(0.5, 1., 0.5, 1.)),
1154                wavy: false,
1155                ..first_style
1156            };
1157            let fallback_style = UnderlineStyle {
1158                color: Some(black()),
1159                ..first_style
1160            };
1161            let decoration = DecorationRun {
1162                len: 1,
1163                color: black(),
1164                background_color: None,
1165                underline: Some(first_style),
1166                strikethrough: None,
1167            };
1168            let line = underline_test_line(
1169                "aébcde",
1170                &[
1171                    decoration.clone(),
1172                    DecorationRun {
1173                        len: 2,
1174                        ..decoration.clone()
1175                    },
1176                    DecorationRun {
1177                        underline: None,
1178                        ..decoration.clone()
1179                    },
1180                    DecorationRun {
1181                        underline: Some(UnderlineStyle {
1182                            color: None,
1183                            ..first_style
1184                        }),
1185                        ..decoration.clone()
1186                    },
1187                    DecorationRun {
1188                        underline: Some(last_style),
1189                        ..decoration.clone()
1190                    },
1191                    DecorationRun {
1192                        underline: Some(last_style),
1193                        ..decoration
1194                    },
1195                ],
1196                false,
1197                window,
1198            );
1199            assert_eq!(line.width(), px(48.));
1200            for origin_x in [-3.25, 0., 4.25] {
1201                for (align, align_width, offset) in [
1202                    (TextAlign::Left, None, 0.),
1203                    (TextAlign::Center, None, 0.),
1204                    (TextAlign::Right, None, 0.),
1205                    (TextAlign::Left, Some(px(96.)), 0.),
1206                    (TextAlign::Center, Some(px(96.)), 24.),
1207                    (TextAlign::Right, Some(px(96.)), 48.),
1208                ] {
1209                    let origin = point(px(origin_x), px(12.25));
1210                    let line_height = px(20.);
1211                    window.next_frame.scene.clear();
1212                    line.paint(origin, line_height, align, align_width, window, cx)
1213                        .unwrap();
1214                    let original = window.next_frame.scene.underlines.clone();
1215                    window.next_frame.scene.clear();
1216                    line.layout
1217                        .paint(
1218                            origin,
1219                            line_height,
1220                            align,
1221                            align_width,
1222                            &line.decoration_runs,
1223                            window,
1224                            cx,
1225                        )
1226                        .unwrap();
1227                    assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1228
1229                    window.next_frame.scene.clear();
1230                    let mut strokes = Vec::new();
1231                    line.paint_with_underline_handler(
1232                        origin,
1233                        line_height,
1234                        align,
1235                        align_width,
1236                        window,
1237                        cx,
1238                        |range, origin, width, style, window| {
1239                            strokes.push((range, origin, width, *style));
1240                            window.paint_underline(origin, width, style);
1241                        },
1242                    )
1243                    .unwrap();
1244                    let start = px(origin_x + offset);
1245                    let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1246                    assert_eq!(
1247                        strokes,
1248                        [
1249                            (0..3, point(start, y), px(16.), first_style),
1250                            (4..5, point(start + px(24.), y), px(8.), fallback_style),
1251                            (5..7, point(start + px(32.), y), px(16.), last_style),
1252                        ]
1253                    );
1254                    assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1255
1256                    window.next_frame.scene.clear();
1257                    let mut captured = Vec::new();
1258                    line.paint_with_underline_handler(
1259                        origin,
1260                        line_height,
1261                        align,
1262                        align_width,
1263                        window,
1264                        cx,
1265                        |range, origin, width, style, _| {
1266                            captured.push((range, origin, width, *style))
1267                        },
1268                    )
1269                    .unwrap();
1270                    assert_eq!(captured, strokes);
1271                    assert_eq!(window.next_frame.scene.underlines.len(), 0);
1272                }
1273            }
1274            for text in ["", "abc"] {
1275                let line = underline_test_line(text, &[], false, window);
1276                let mut calls = 0;
1277                line.paint_with_underline_handler(
1278                    point(px(4.), px(10.)),
1279                    px(20.),
1280                    TextAlign::Left,
1281                    None,
1282                    window,
1283                    cx,
1284                    |_, _, _, _, _| calls += 1,
1285                )
1286                .unwrap();
1287                assert_eq!(calls, 0);
1288            }
1289        });
1290    }
1291
1292    #[gpui::test]
1293    fn test_underline_handler_reports_zero_advance_geometry(cx: &mut TestAppContext) {
1294        test_underline_handler_at_scales(cx, |window, cx| {
1295            let first_style = UnderlineStyle {
1296                thickness: px(1.),
1297                color: Some(black()),
1298                wavy: true,
1299            };
1300            let last_style = UnderlineStyle {
1301                wavy: false,
1302                ..first_style
1303            };
1304            let decoration = DecorationRun {
1305                len: 1,
1306                color: black(),
1307                background_color: None,
1308                underline: Some(first_style),
1309                strikethrough: None,
1310            };
1311            let line = underline_test_line(
1312                "ab",
1313                &[
1314                    decoration.clone(),
1315                    DecorationRun {
1316                        underline: Some(last_style),
1317                        ..decoration
1318                    },
1319                ],
1320                true,
1321                window,
1322            );
1323            let half_width = cx
1324                .text_system()
1325                .bounding_box(line.runs[0].font_id, line.font_size)
1326                .size
1327                .width
1328                / 2.;
1329            let origin = point(px(40.25), px(10.25));
1330            let line_height = px(20.);
1331            let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1332            for (align, offset) in [
1333                (TextAlign::Left, 0.),
1334                (TextAlign::Center, 16.),
1335                (TextAlign::Right, 32.),
1336            ] {
1337                window.next_frame.scene.clear();
1338                line.paint(origin, line_height, align, Some(px(32.)), window, cx)
1339                    .unwrap();
1340                let original = window.next_frame.scene.underlines.clone();
1341                window.next_frame.scene.clear();
1342                let mut strokes = Vec::new();
1343                line.paint_with_underline_handler(
1344                    origin,
1345                    line_height,
1346                    align,
1347                    Some(px(32.)),
1348                    window,
1349                    cx,
1350                    |range, origin, width, style, window| {
1351                        strokes.push((range, origin, width, *style));
1352                        window.paint_underline(origin, width, style);
1353                    },
1354                )
1355                .unwrap();
1356                let end = origin.x + px(offset);
1357                let start = point(end - half_width, y);
1358                let width = end - start.x;
1359                assert_eq!(
1360                    strokes,
1361                    [
1362                        (0..1, start, width, first_style),
1363                        (1..2, start, width, last_style),
1364                    ]
1365                );
1366                assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1367            }
1368        });
1369    }
1370
1371    #[gpui::test]
1372    fn test_underline_handler_matches_wrapped_paint(cx: &mut TestAppContext) {
1373        test_underline_handler_at_scales(cx, |window, cx| {
1374            let style = UnderlineStyle {
1375                thickness: px(1.),
1376                color: Some(black()),
1377                wavy: true,
1378            };
1379            for zero_advance in [false, true] {
1380                let line = underline_test_line(
1381                    "abcd",
1382                    &[DecorationRun {
1383                        len: 4,
1384                        color: black(),
1385                        background_color: None,
1386                        underline: Some(style),
1387                        strikethrough: None,
1388                    }],
1389                    zero_advance,
1390                    window,
1391                );
1392                let half_width = cx
1393                    .text_system()
1394                    .bounding_box(line.runs[0].font_id, line.font_size)
1395                    .size
1396                    .width
1397                    / 2.;
1398                let origin = point(px(40.25), px(10.25));
1399                let line_height = px(20.);
1400                let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1401                let wrapped = WrappedLine {
1402                    layout: Arc::new(WrappedLineLayout {
1403                        unwrapped_layout: line.layout,
1404                        wrap_boundaries: SmallVec::from_buf([WrapBoundary {
1405                            run_ix: 0,
1406                            glyph_ix: 2,
1407                        }]),
1408                        wrap_width: Some(px(16.)),
1409                    }),
1410                    text: line.text,
1411                    decoration_runs: line.decoration_runs.into_vec(),
1412                };
1413                window.next_frame.scene.clear();
1414                wrapped
1415                    .paint(origin, line_height, TextAlign::Left, None, window, cx)
1416                    .unwrap();
1417                let original = window.next_frame.scene.underlines.clone();
1418                window.next_frame.scene.clear();
1419                let mut strokes = Vec::new();
1420                paint_line(
1421                    origin,
1422                    &wrapped.unwrapped_layout,
1423                    line_height,
1424                    TextAlign::Left,
1425                    Some(px(16.)),
1426                    &wrapped.decoration_runs,
1427                    &wrapped.wrap_boundaries,
1428                    window,
1429                    cx,
1430                    &mut |range, origin, width, style, window| {
1431                        strokes.push((range, origin, width, *style));
1432                        window.paint_underline(origin, width, style);
1433                    },
1434                )
1435                .unwrap();
1436                let (start, width) = if zero_advance {
1437                    let start = origin.x - half_width;
1438                    (start, origin.x - start)
1439                } else {
1440                    (origin.x, px(16.))
1441                };
1442                assert_eq!(
1443                    strokes,
1444                    [
1445                        (0..4, point(start, y), width, style),
1446                        (0..4, point(start, y + line_height), width, style),
1447                    ]
1448                );
1449                assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1450            }
1451        });
1452    }
1453
1454    #[test]
1455    fn test_split_at_invariants() {
1456        // Split "abcdef" at every possible byte index and verify structural invariants.
1457        let line = make_shaped_line(
1458            "abcdef",
1459            &[
1460                (0, 0.0),
1461                (1, 10.0),
1462                (2, 20.0),
1463                (3, 30.0),
1464                (4, 40.0),
1465                (5, 50.0),
1466            ],
1467            60.0,
1468            &[],
1469        );
1470
1471        for i in 0..=6 {
1472            let (left, right) = line.split_at(i);
1473
1474            assert_eq!(
1475                left.width() + right.width(),
1476                line.width(),
1477                "widths must sum at split={i}"
1478            );
1479            assert_eq!(
1480                left.len() + right.len(),
1481                line.len(),
1482                "lengths must sum at split={i}"
1483            );
1484            assert_eq!(
1485                format!("{}{}", left.text.as_ref(), right.text.as_ref()),
1486                "abcdef",
1487                "text must concatenate at split={i}"
1488            );
1489            assert_eq!(left.font_size, line.font_size, "font_size at split={i}");
1490            assert_eq!(right.ascent, line.ascent, "ascent at split={i}");
1491            assert_eq!(right.descent, line.descent, "descent at split={i}");
1492        }
1493
1494        // Edge: split at 0 produces no left runs, full content on right
1495        let (left, right) = line.split_at(0);
1496        assert_eq!(left.runs.len(), 0);
1497        assert_eq!(right.runs[0].glyphs.len(), 6);
1498
1499        // Edge: split at end produces full content on left, no right runs
1500        let (left, right) = line.split_at(6);
1501        assert_eq!(left.runs[0].glyphs.len(), 6);
1502        assert_eq!(right.runs.len(), 0);
1503    }
1504
1505    #[test]
1506    fn test_split_at_glyph_rebasing() {
1507        // Two font runs (simulating a font fallback boundary at byte 3):
1508        //   run A (FontId 0): glyphs at bytes 0,1,2  positions 0,10,20
1509        //   run B (FontId 1): glyphs at bytes 3,4,5  positions 30,40,50
1510        // Successive splits simulate the incremental splitting done during wrap.
1511        let line = ShapedLine {
1512            layout: Arc::new(LineLayout {
1513                font_size: px(16.0),
1514                width: px(60.0),
1515                ascent: px(12.0),
1516                descent: px(4.0),
1517                runs: vec![
1518                    ShapedRun {
1519                        font_id: FontId(0),
1520                        glyphs: vec![
1521                            ShapedGlyph {
1522                                id: GlyphId(0),
1523                                position: point(px(0.0), px(0.0)),
1524                                index: 0,
1525                                is_emoji: false,
1526                            },
1527                            ShapedGlyph {
1528                                id: GlyphId(0),
1529                                position: point(px(10.0), px(0.0)),
1530                                index: 1,
1531                                is_emoji: false,
1532                            },
1533                            ShapedGlyph {
1534                                id: GlyphId(0),
1535                                position: point(px(20.0), px(0.0)),
1536                                index: 2,
1537                                is_emoji: false,
1538                            },
1539                        ],
1540                    },
1541                    ShapedRun {
1542                        font_id: FontId(1),
1543                        glyphs: vec![
1544                            ShapedGlyph {
1545                                id: GlyphId(0),
1546                                position: point(px(30.0), px(0.0)),
1547                                index: 3,
1548                                is_emoji: false,
1549                            },
1550                            ShapedGlyph {
1551                                id: GlyphId(0),
1552                                position: point(px(40.0), px(0.0)),
1553                                index: 4,
1554                                is_emoji: false,
1555                            },
1556                            ShapedGlyph {
1557                                id: GlyphId(0),
1558                                position: point(px(50.0), px(0.0)),
1559                                index: 5,
1560                                is_emoji: false,
1561                            },
1562                        ],
1563                    },
1564                ],
1565                len: 6,
1566            }),
1567            text: "abcdef".into(),
1568            decoration_runs: SmallVec::new(),
1569        };
1570
1571        // First split at byte 2 — mid-run in run A
1572        let (first, remainder) = line.split_at(2);
1573        assert_eq!(first.text.as_ref(), "ab");
1574        assert_eq!(first.runs.len(), 1);
1575        assert_eq!(first.runs[0].font_id, FontId(0));
1576
1577        // Remainder "cdef" should have two runs: tail of A (1 glyph) + all of B (3 glyphs)
1578        assert_eq!(remainder.text.as_ref(), "cdef");
1579        assert_eq!(remainder.runs.len(), 2);
1580        assert_eq!(remainder.runs[0].font_id, FontId(0));
1581        assert_eq!(remainder.runs[0].glyphs.len(), 1);
1582        assert_eq!(remainder.runs[0].glyphs[0].index, 0);
1583        assert_eq!(remainder.runs[0].glyphs[0].position.x, px(0.0));
1584        assert_eq!(remainder.runs[1].font_id, FontId(1));
1585        assert_eq!(remainder.runs[1].glyphs[0].index, 1);
1586        assert_eq!(remainder.runs[1].glyphs[0].position.x, px(10.0));
1587
1588        // Second split at byte 2 within remainder — crosses the run boundary
1589        let (second, final_part) = remainder.split_at(2);
1590        assert_eq!(second.text.as_ref(), "cd");
1591        assert_eq!(final_part.text.as_ref(), "ef");
1592        assert_eq!(final_part.runs[0].glyphs[0].index, 0);
1593        assert_eq!(final_part.runs[0].glyphs[0].position.x, px(0.0));
1594
1595        // Widths must sum across all three pieces
1596        assert_eq!(
1597            first.width() + second.width() + final_part.width(),
1598            line.width()
1599        );
1600    }
1601
1602    #[test]
1603    fn test_split_at_decorations() {
1604        // Three decoration runs: red [0..2), green [2..5), blue [5..6).
1605        // Split at byte 3 — red goes entirely left, green straddles, blue goes entirely right.
1606        let red = Hsla {
1607            h: 0.0,
1608            s: 1.0,
1609            l: 0.5,
1610            a: 1.0,
1611        };
1612        let green = Hsla {
1613            h: 0.3,
1614            s: 1.0,
1615            l: 0.5,
1616            a: 1.0,
1617        };
1618        let blue = Hsla {
1619            h: 0.6,
1620            s: 1.0,
1621            l: 0.5,
1622            a: 1.0,
1623        };
1624
1625        let line = make_shaped_line(
1626            "abcdef",
1627            &[
1628                (0, 0.0),
1629                (1, 10.0),
1630                (2, 20.0),
1631                (3, 30.0),
1632                (4, 40.0),
1633                (5, 50.0),
1634            ],
1635            60.0,
1636            &[
1637                DecorationRun {
1638                    len: 2,
1639                    color: red,
1640                    background_color: None,
1641                    underline: None,
1642                    strikethrough: None,
1643                },
1644                DecorationRun {
1645                    len: 3,
1646                    color: green,
1647                    background_color: None,
1648                    underline: None,
1649                    strikethrough: None,
1650                },
1651                DecorationRun {
1652                    len: 1,
1653                    color: blue,
1654                    background_color: None,
1655                    underline: None,
1656                    strikethrough: None,
1657                },
1658            ],
1659        );
1660
1661        let (left, right) = line.split_at(3);
1662
1663        // Left: red(2) + green(1) — green straddled, left portion has len 1
1664        assert_eq!(left.decoration_runs.len(), 2);
1665        assert_eq!(left.decoration_runs[0].len, 2);
1666        assert_eq!(left.decoration_runs[0].color, red);
1667        assert_eq!(left.decoration_runs[1].len, 1);
1668        assert_eq!(left.decoration_runs[1].color, green);
1669
1670        // Right: green(2) + blue(1) — green straddled, right portion has len 2
1671        assert_eq!(right.decoration_runs.len(), 2);
1672        assert_eq!(right.decoration_runs[0].len, 2);
1673        assert_eq!(right.decoration_runs[0].color, green);
1674        assert_eq!(right.decoration_runs[1].len, 1);
1675        assert_eq!(right.decoration_runs[1].color, blue);
1676    }
1677
1678    struct UnderlineHandlerTestView(Rc<dyn Fn(&mut Window, &mut App)>);
1679
1680    impl Render for UnderlineHandlerTestView {
1681        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1682            let paint = self.0.clone();
1683            canvas(
1684                |_, _, _| {},
1685                move |_, _, window, cx| {
1686                    window.with_element_opacity(Some(0.5), |window| paint(window, cx));
1687                },
1688            )
1689            .size_full()
1690        }
1691    }
1692
1693    fn test_underline_handler_at_scales(
1694        cx: &mut TestAppContext,
1695        paint: impl Fn(&mut Window, &mut App) + 'static,
1696    ) {
1697        let window = cx.add_window(move |_, _| UnderlineHandlerTestView(Rc::new(paint)));
1698        for scale in [1., 1.25, 1.5, 2., 3.] {
1699            cx.simulate_window_scale_factor_change(window.into(), scale);
1700            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
1701                .unwrap();
1702        }
1703    }
1704
1705    fn underline_test_line(
1706        text: &str,
1707        decorations: &[DecorationRun],
1708        zero_advance: bool,
1709        window: &Window,
1710    ) -> ShapedLine {
1711        let mut line = window.text_system().shape_line(
1712            SharedString::new(text),
1713            px(16.),
1714            &[TextRun {
1715                len: text.len(),
1716                font: font(".ZedMono"),
1717                color: black(),
1718                ..TextRun::default()
1719            }],
1720            None,
1721        );
1722        line.decoration_runs = SmallVec::from(decorations.to_vec());
1723        let layout = &line.layout;
1724        let mut runs = layout.runs.clone();
1725        let advance = if zero_advance { px(0.) } else { px(8.) };
1726        let mut width = px(0.);
1727        for glyph in runs.iter_mut().flat_map(|run| &mut run.glyphs) {
1728            glyph.position.x = width;
1729            width += advance;
1730        }
1731        line.layout = Arc::new(LineLayout {
1732            font_size: layout.font_size,
1733            width,
1734            ascent: layout.ascent,
1735            descent: layout.descent,
1736            runs,
1737            len: layout.len,
1738        });
1739        line
1740    }
1741
1742    fn assert_underline_primitives_eq(actual: &[Underline], expected: &[Underline]) {
1743        assert_eq!(actual.len(), expected.len());
1744        for (actual, expected) in actual.iter().zip(expected) {
1745            assert_eq!(actual.bounds, expected.bounds);
1746            assert_eq!(actual.content_mask, expected.content_mask);
1747            assert_eq!(actual.color, expected.color);
1748            assert_eq!(actual.thickness, expected.thickness);
1749            assert_eq!(actual.wavy, expected.wavy);
1750            assert_eq!(actual.order, expected.order);
1751            assert_eq!(actual.pad, expected.pad);
1752        }
1753    }
1754
1755    #[test]
1756    fn test_cursor_preserves_shaping_metadata_across_runs() {
1757        let line = ShapedLine {
1758            layout: Arc::new(LineLayout {
1759                font_size: px(16.0),
1760                width: px(50.0),
1761                ascent: px(12.0),
1762                descent: px(4.0),
1763                runs: vec![
1764                    ShapedRun {
1765                        font_id: FontId(3),
1766                        glyphs: vec![
1767                            ShapedGlyph {
1768                                id: GlyphId(11),
1769                                position: point(px(0.0), px(1.0)),
1770                                index: 0,
1771                                is_emoji: true,
1772                            },
1773                            ShapedGlyph {
1774                                id: GlyphId(12),
1775                                position: point(px(17.0), px(1.0)),
1776                                index: 1,
1777                                is_emoji: false,
1778                            },
1779                            ShapedGlyph {
1780                                id: GlyphId(13),
1781                                position: point(px(19.0), px(-1.0)),
1782                                index: 1,
1783                                is_emoji: false,
1784                            },
1785                        ],
1786                    },
1787                    ShapedRun {
1788                        font_id: FontId(8),
1789                        glyphs: vec![
1790                            ShapedGlyph {
1791                                id: GlyphId(21),
1792                                position: point(px(25.0), px(1.0)),
1793                                index: 5,
1794                                is_emoji: true,
1795                            },
1796                            ShapedGlyph {
1797                                id: GlyphId(22),
1798                                position: point(px(41.0), px(1.0)),
1799                                index: 7,
1800                                is_emoji: false,
1801                            },
1802                        ],
1803                    },
1804                ],
1805                len: 10,
1806            }),
1807            text: "a😀bcdef".into(),
1808            decoration_runs: SmallVec::new(),
1809        };
1810        let mut cursor = line.cursor();
1811        let first = cursor.take_until(5);
1812        assert_eq!(first.text.as_ref(), "a😀");
1813        assert_eq!(first.runs[0].font_id, FontId(3));
1814        assert_eq!(first.runs[0].glyphs[0].id, GlyphId(11));
1815        assert!(first.runs[0].glyphs[0].is_emoji);
1816        assert_eq!(first.runs[0].glyphs[1].index, 1);
1817        assert_eq!(first.runs[0].glyphs[1].position, point(px(17.0), px(1.0)));
1818        assert_eq!(first.runs[0].glyphs.len(), 3);
1819        assert_eq!(first.runs[0].glyphs[2].index, 1);
1820        assert_eq!(first.runs[0].glyphs[2].position, point(px(19.0), px(-1.0)));
1821        assert_eq!(cursor.x_offset(), px(25.0));
1822
1823        let second = cursor.take_until(7);
1824        assert_eq!(second.text.as_ref(), "bc");
1825        assert_eq!(second.runs[0].font_id, FontId(8));
1826        assert_eq!(second.runs[0].glyphs[0].id, GlyphId(21));
1827        assert_eq!(second.runs[0].glyphs[0].index, 0);
1828        assert_eq!(second.runs[0].glyphs[0].position, point(px(0.0), px(1.0)));
1829        assert_eq!(cursor.x_offset(), px(41.0));
1830
1831        let final_part = cursor.take_until(10);
1832        assert_eq!(final_part.text.as_ref(), "def");
1833        assert_eq!(final_part.runs[0].font_id, FontId(8));
1834        assert_eq!(final_part.runs[0].glyphs[0].id, GlyphId(22));
1835        assert_eq!(final_part.runs[0].glyphs[0].index, 0);
1836        assert_eq!(
1837            final_part.runs[0].glyphs[0].position,
1838            point(px(0.0), px(1.0))
1839        );
1840    }
1841
1842    #[test]
1843    fn test_cursor_preserves_existing_visual_order_splitting() {
1844        let line = make_shaped_line("abc", &[(0, 0.0), (2, 10.0), (1, 20.0)], 30.0, &[]);
1845        let mut cursor = line.cursor();
1846        let mut remainder = line.clone();
1847        let mut previous_boundary = 0;
1848        for boundary in [0, 1, 2, 3] {
1849            let (expected, rest) = remainder.split_at(boundary - previous_boundary);
1850            let actual = cursor.take_until(boundary);
1851            assert_eq!(actual.text, expected.text);
1852            assert_eq!(actual.width(), expected.width());
1853            assert_eq!(actual.runs.len(), expected.runs.len());
1854            for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
1855                assert_eq!(actual.font_id, expected.font_id);
1856                assert_eq!(actual.glyphs.len(), expected.glyphs.len());
1857                for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
1858                    assert_eq!(actual.id, expected.id);
1859                    assert_eq!(actual.index, expected.index);
1860                    assert_eq!(actual.position, expected.position);
1861                }
1862            }
1863            assert_eq!(cursor.x_offset(), line.x_for_index(boundary));
1864            remainder = rest;
1865            previous_boundary = boundary;
1866        }
1867    }
1868
1869    #[test]
1870    fn test_cursor_partitions_one_decoration_across_three_chunks() {
1871        let line = make_shaped_line(
1872            "abcdef",
1873            &[
1874                (0, 0.0),
1875                (1, 10.0),
1876                (2, 20.0),
1877                (3, 30.0),
1878                (4, 40.0),
1879                (5, 50.0),
1880            ],
1881            60.0,
1882            &[DecorationRun {
1883                len: 6,
1884                color: Hsla {
1885                    h: 0.2,
1886                    s: 0.4,
1887                    l: 0.6,
1888                    a: 1.0,
1889                },
1890                background_color: None,
1891                underline: None,
1892                strikethrough: None,
1893            }],
1894        );
1895        let mut cursor = line.cursor();
1896        assert_eq!(cursor.take_until(2).decoration_runs[0].len, 2);
1897        assert_eq!(cursor.take_until(4).decoration_runs[0].len, 2);
1898        assert_eq!(cursor.take_until(6).decoration_runs[0].len, 2);
1899    }
1900
1901    #[test]
1902    fn test_cursor_matches_successive_splits_at_ordered_boundaries() {
1903        let decorations: Vec<_> = [2, 0, 3, 1]
1904            .into_iter()
1905            .map(|len| DecorationRun {
1906                len,
1907                color: Hsla {
1908                    h: len as f32 / 10.0,
1909                    s: 0.5,
1910                    l: 0.5,
1911                    a: 1.0,
1912                },
1913                background_color: Some(black()),
1914                underline: None,
1915                strikethrough: None,
1916            })
1917            .collect();
1918        let line = make_shaped_line(
1919            "abcdef",
1920            &[(0, 5.0), (0, 5.0), (2, 15.0), (4, 25.0), (5, 35.0)],
1921            45.0,
1922            &decorations,
1923        );
1924        for first in 0..=line.len() {
1925            for second in first..=line.len() {
1926                let mut cursor = line.cursor();
1927                let mut remainder = line.clone();
1928                let mut previous_boundary = 0;
1929                let mut total_width = px(0.0);
1930                let mut text = String::new();
1931                for boundary in [first, second, line.len(), line.len()] {
1932                    let (expected, rest) = remainder.split_at(boundary - previous_boundary);
1933                    let actual = cursor.take_until(boundary);
1934                    assert_eq!(actual.text, expected.text);
1935                    assert_eq!(actual.len(), expected.len());
1936                    assert_eq!(actual.width(), expected.width());
1937                    assert_eq!(actual.runs.len(), expected.runs.len());
1938                    for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
1939                        assert_eq!(actual.font_id, expected.font_id);
1940                        assert_eq!(actual.glyphs.len(), expected.glyphs.len());
1941                        for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
1942                            assert_eq!(actual.id, expected.id);
1943                            assert_eq!(actual.index, expected.index);
1944                            assert_eq!(actual.position, expected.position);
1945                        }
1946                    }
1947                    assert_eq!(actual.decoration_runs.len(), expected.decoration_runs.len());
1948                    for (actual, expected) in
1949                        actual.decoration_runs.iter().zip(&expected.decoration_runs)
1950                    {
1951                        assert_eq!(actual.len, expected.len);
1952                        assert_eq!(actual.color, expected.color);
1953                        assert_eq!(actual.background_color, expected.background_color);
1954                    }
1955                    total_width += actual.width();
1956                    text.push_str(&actual.text);
1957                    remainder = rest;
1958                    previous_boundary = boundary;
1959                }
1960                assert_eq!(total_width, line.width());
1961                assert_eq!(text, line.text.as_ref());
1962            }
1963        }
1964    }
1965
1966    #[test]
1967    fn test_cursor_empty_chunks_and_repeated_boundaries() {
1968        let line = make_shaped_line("ab", &[(0, 5.0), (1, 15.0)], 20.0, &[]);
1969        let mut cursor = line.cursor();
1970        assert_eq!(cursor.take_until(0).text.as_ref(), "");
1971        assert_eq!(cursor.take_until(0).text.as_ref(), "");
1972        assert_eq!(cursor.take_until(1).text.as_ref(), "a");
1973        assert_eq!(cursor.take_until(2).text.as_ref(), "b");
1974        assert_eq!(cursor.take_until(2).text.as_ref(), "");
1975        let empty = make_shaped_line("", &[], 0.0, &[]);
1976        let piece = empty.cursor().take_until(0);
1977        assert!(piece.text.is_empty());
1978        assert!(piece.runs.is_empty());
1979        assert_eq!(piece.width(), px(0.0));
1980    }
1981
1982    #[test]
1983    fn test_cursor_rejects_invalid_boundaries() {
1984        let line = make_shaped_line("é", &[(0, 0.0)], 10.0, &[]);
1985        let mut cursor = line.cursor();
1986        assert!(
1987            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1988                cursor.take_until(1);
1989            }))
1990            .is_err()
1991        );
1992        let mut cursor = line.cursor();
1993        cursor.take_until(2);
1994        assert!(
1995            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1996                cursor.take_until(0);
1997            }))
1998            .is_err()
1999        );
2000        let mut cursor = line.cursor();
2001        assert!(
2002            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2003                cursor.take_until(3);
2004            }))
2005            .is_err()
2006        );
2007    }
2008}