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