Skip to main content

gpui/text_system/
line.rs

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