Skip to main content

gpui/text_system/
line.rs

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