Skip to main content

markdown/render/
text.rs

1//! Inline text: flattening to runs, painting, carets and selection rects.
2
3use super::*;
4
5/// Inline content flattened for shaping: one string, its runs, and the ranges
6/// that need painting underneath (link clicks, inline-code washes, mentions).
7///
8/// [`Self::text`] is the [`Text`] with every mention replaced by what it shows,
9/// so every range here is in its offsets; [`Self::shown`] maps the two.
10pub struct Flat {
11    pub text: SharedString,
12    pub runs: Vec<TextRun>,
13    pub links: Vec<(Range<usize>, String)>,
14    pub code: Vec<Range<usize>>,
15    /// Each run of a [`crate::MarkPaint::background`], painted over the
16    /// selection.
17    pub washes: Vec<(Range<usize>, Hsla)>,
18    pub mentions: Vec<Mention>,
19    pub shown: Shown,
20}
21
22/// A mention as it is shown: a favicon slot, then its label and title.
23#[derive(Clone, Debug)]
24pub struct Mention {
25    pub url: String,
26    /// Everything it shows, the favicon slot included.
27    pub range: Range<usize>,
28    /// The favicon slot: one em space.
29    pub icon: Range<usize>,
30    pub favicon: Option<SharedString>,
31    /// The app's mark, painted in the slot instead of a favicon.
32    pub glyph: Option<ui::icons::Icon>,
33    /// What stands in the slot while no favicon has loaded.
34    pub initial: SharedString,
35}
36
37pub use ui::input::Shown;
38
39/// What stands in a mention's favicon slot. An em space is as wide as the
40/// type is tall.
41const ICON_SLOT: &str = "\u{2003}";
42
43/// Marks are ranges, gpui wants consecutive runs — so cut the text at every
44/// mark boundary and ask which marks cover each piece.
45pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
46    flatten_with(text, base_weight, theme, |_| None, |_| None)
47}
48
49/// [`flatten`] with the app's own marks painted — see [`crate::MarkPaint`] —
50/// and each mention described by `preview`. A name the app does not paint
51/// reads as the text it wraps.
52pub fn flatten_with(
53    text: &Text,
54    base_weight: FontWeight,
55    theme: &Theme,
56    paint: impl Fn(&str) -> Option<crate::MarkPaint>,
57    preview: impl Fn(&str) -> Option<preview::Preview>,
58) -> Flat {
59    let mut cuts: Vec<usize> = text
60        .marks
61        .iter()
62        .flat_map(|span| [span.range.start, span.range.end])
63        .chain([0, text.text.len()])
64        .filter(|cut| *cut <= text.text.len())
65        .collect();
66    cuts.sort_unstable();
67    cuts.dedup();
68
69    // Mentions in order; one overlapping an earlier one is text.
70    let mut atoms: Vec<(Range<usize>, &str)> = text
71        .marks
72        .iter()
73        .filter_map(|span| match &span.mark {
74            Mark::Mention { url, .. } if !span.range.is_empty() => {
75                Some((span.range.clone(), url.as_str()))
76            }
77            _ => None,
78        })
79        .collect();
80    atoms.sort_by_key(|(range, _)| range.start);
81    atoms.dedup_by(|later, earlier| later.0.start < earlier.0.end);
82
83    let mut shown = String::with_capacity(text.text.len());
84    let mut runs = Vec::new();
85    let mut links: Vec<(Range<usize>, String)> = Vec::new();
86    let mut code: Vec<Range<usize>> = Vec::new();
87    let mut washes: Vec<(Range<usize>, Hsla)> = Vec::new();
88    let mut mentions: Vec<Mention> = Vec::new();
89    let mut map: Vec<(Range<usize>, Range<usize>)> = Vec::new();
90
91    for pair in cuts.windows(2) {
92        let (start, end) = (pair[0], pair[1]);
93        let atom = atoms
94            .iter()
95            .find(|(range, _)| range.start <= start && end <= range.end);
96        if atom.is_some_and(|(range, _)| range.start != start) {
97            continue;
98        }
99        let covering = text
100            .marks
101            .iter()
102            .filter(|span| span.range.start <= start && span.range.end >= end);
103
104        let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
105        let mut link = None;
106        // The app's own marks, merged in the order they cover this run: the
107        // last one to say something about a field is the one that says it.
108        let mut custom = crate::MarkPaint::default();
109        for span in covering {
110            match &span.mark {
111                Mark::Bold => bold = true,
112                Mark::Italic => italic = true,
113                Mark::Strike => strike = true,
114                Mark::Code => mono = true,
115                Mark::Mention { .. } => {}
116                Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
117                Mark::Custom(name) => {
118                    let Some(painted) = paint(name) else { continue };
119                    custom.color = painted.color.or(custom.color);
120                    custom.background = painted.background.or(custom.background);
121                    custom.weight = painted.weight.or(custom.weight);
122                    custom.italic |= painted.italic;
123                    custom.underline |= painted.underline;
124                    custom.strikethrough |= painted.strikethrough;
125                }
126            }
127        }
128        let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);
129
130        let mut face = font(if mono && atom.is_none() {
131            theme.font_mono.clone()
132        } else {
133            theme.font_body.clone()
134        });
135        face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
136            FontWeight::SEMIBOLD
137        } else {
138            custom.weight.unwrap_or(base_weight)
139        };
140        face.style = if italic {
141            FontStyle::Italic
142        } else {
143            FontStyle::Normal
144        };
145        let underline = UnderlineStyle {
146            color: Some(theme.text_muted),
147            thickness: px(1.0),
148            wavy: false,
149        };
150
151        if let Some((range, url)) = atom {
152            let described = preview(url).unwrap_or_default();
153            let host = preview::host(url);
154            let own = &text.text[range.clone()];
155            let title: SharedString = match &described.title {
156                Some(title) => title.clone(),
157                None if own != *url => own.to_string().into(),
158                None => host.to_string().into(),
159            };
160            let from = shown.len();
161            let mut run = |shown: &mut String,
162                           piece: &str,
163                           color: Hsla,
164                           underline: Option<UnderlineStyle>| {
165                shown.push_str(piece);
166                runs.push(TextRun {
167                    len: piece.len(),
168                    font: face.clone(),
169                    color,
170                    background_color: None,
171                    underline,
172                    strikethrough: None,
173                });
174            };
175            run(&mut shown, ICON_SLOT, gpui::transparent_black(), None);
176            run(&mut shown, " ", theme.text, None);
177            run(&mut shown, &title, theme.text, Some(underline));
178            let to = shown.len();
179            links.push((from..to, url.to_string()));
180            mentions.push(Mention {
181                url: url.to_string(),
182                range: from..to,
183                icon: from..from + ICON_SLOT.len(),
184                favicon: described.icon,
185                glyph: described.glyph,
186                initial: host
187                    .chars()
188                    .next()
189                    .unwrap_or('?')
190                    .to_uppercase()
191                    .to_string()
192                    .into(),
193            });
194            map.push((range.clone(), from..to));
195            continue;
196        }
197
198        let (from, to) = (shown.len(), shown.len() + end - start);
199        shown.push_str(&text.text[start..end]);
200        if mono {
201            match code.last_mut() {
202                Some(range) if range.end == from => range.end = to,
203                _ => code.push(from..to),
204            }
205        }
206        if let Some(background) = custom.background {
207            match washes.last_mut() {
208                Some((range, last)) if range.end == from && *last == background => range.end = to,
209                _ => washes.push((from..to, background)),
210            }
211        }
212        if let Some(url) = &link {
213            match links.last_mut() {
214                Some((range, last)) if range.end == from && last == url => range.end = to,
215                _ => links.push((from..to, url.clone())),
216            }
217        }
218
219        runs.push(TextRun {
220            len: end - start,
221            font: face,
222            // Links stay monochrome and underlined; the accent is reserved for
223            // primary actions.
224            color: match (mono, custom.color) {
225                (_, Some(color)) => color,
226                (true, None) => theme.code_text,
227                (false, None) => theme.text,
228            },
229            background_color: None,
230            underline: (link.is_some() || custom.underline).then_some(underline),
231            strikethrough: strike.then_some(StrikethroughStyle {
232                thickness: px(1.0),
233                color: Some(theme.text_muted),
234            }),
235        });
236    }
237
238    Flat {
239        text: shown.into(),
240        runs,
241        links,
242        code,
243        washes,
244        mentions,
245        shown: Shown::new(map),
246    }
247}
248
249pub(super) fn text_element(
250    text: &Text,
251    size: f32,
252    line_height: f32,
253    weight: FontWeight,
254    overlay: Overlay,
255    theme: &Theme,
256    cx: &App,
257) -> AnyElement {
258    let flat = flatten_with(
259        text,
260        weight,
261        theme,
262        |name| crate::marks::paint_of(cx, name, theme),
263        |url| crate::link::preview(crate::Link::new(url, overlay.base), cx),
264    );
265    painted_text(flat, text.text.len(), size, line_height, overlay, theme)
266}
267
268/// Shaped inline content with the editing overlay under it: the selection, the
269/// caret, the inline-code wash, and the layout a click resolves against.
270///
271/// Takes a [`Flat`] rather than a [`Text`] because a table has to shape every
272/// cell to measure the columns before it can paint one.
273pub(super) fn painted_text(
274    flat: Flat,
275    len: usize,
276    size: f32,
277    line_height: f32,
278    overlay: Overlay,
279    theme: &Theme,
280) -> AnyElement {
281    let (ix, part) = (overlay.block, overlay.part);
282    let shown = flat.shown.clone();
283    let caret = overlay.caret_painted().map(|offset| shown.at(offset));
284    let affinity = overlay.affinity();
285    let selected = overlay.selected(len).map(|range| shown.range(&range));
286    let span = 0..len;
287    // Only where the caret already is, and only while there is nothing to
288    // read: a hint on every empty block would be a page of grey.
289    let hint = overlay
290        .placeholder
291        // The caret's own presence, not the blink's phase — a hint that came
292        // and went twice a second would be unreadable.
293        .filter(|_| len == 0 && overlay.caret().is_some())
294        .map(|hint| {
295            div()
296                .absolute()
297                .text_color(theme.text_faint)
298                .child(hint.clone())
299        });
300    let (shape, height, hollow) = (
301        overlay.caret_shape,
302        overlay.caret_height,
303        overlay.caret_hollow(),
304    );
305    let glyph = caret
306        .filter(|_| shape.cuts_out(hollow))
307        .and_then(|offset| overlay.covered(&flat.text, offset));
308    let runs = flat.runs.clone();
309    let styled = StyledText::new(flat.text).with_runs(flat.runs);
310    let layout = styled.layout().clone();
311
312    let mentions = flat.mentions;
313    let link_ranges: Vec<Range<usize>> =
314        flat.links.iter().map(|(range, _)| range.clone()).collect();
315    let press_layout = layout.clone();
316    let painted: AnyElement = if flat.links.is_empty() {
317        styled.into_any_element()
318    } else {
319        let hovered = flat.links.clone();
320        let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
321        let jump = overlay.jump.cloned();
322        let base = overlay.base.map(Path::to_path_buf);
323        let hover_base = base.clone();
324        InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
325            .on_click(ranges, move |clicked, window, cx| {
326                if let Some(url) = urls.get(clicked) {
327                    let link = crate::Link::new(url, base.as_deref());
328                    crate::link::follow(link, jump.as_ref(), window, cx);
329                }
330            })
331            .tooltip(move |at, _window, cx| {
332                let (_, url) = hovered.iter().find(|(range, _)| range.contains(&at))?;
333                Some(HoverCard::view(url, hover_base.clone(), cx))
334            })
335            .into_any_element()
336    };
337
338    // The wash is painted before the text — an earlier sibling is underneath —
339    // reading glyph geometry from the text's own layout handle. Pure paint,
340    // never part of layout.
341    let wash = theme.code_wash;
342    let code_ranges = flat.code;
343    let washes = flat.washes;
344    let (icon_color, icon_wash) = (theme.text_muted, theme.element_hover);
345    let caret_color = theme.caret;
346    let selection_color = theme.selection;
347    let annotated: Vec<_> = overlay
348        .annotated(len, theme)
349        .into_iter()
350        .map(|(range, wash)| (shown.range(&range), wash))
351        .collect();
352    let layouts = overlay.layouts.cloned();
353    // In the order the underlay paints them.
354    let layers: Vec<_> = selected
355        .iter()
356        .map(|range| (range.clone(), selection_color))
357        .chain(washes.iter().cloned())
358        .chain(annotated.iter().cloned())
359        .chain(code_ranges.iter().map(|range| (range.clone(), wash)))
360        .collect();
361    let overdraws = ui::input::overdraw::overdraws(&runs, theme.bg, &layers);
362    // Over the text, which a solid block hides: the glyph it covers is painted
363    // again on top of it.
364    let caret_layout = layout.clone();
365    let cover = theme::legible(theme.bg, caret_color, theme::LEGIBLE);
366    let over = canvas(
367        |_, _, _| (),
368        move |_, _, window, cx| {
369            ui::input::overdraw::paint(
370                caret_layout.line_layouts().iter().map(|line| &**line),
371                caret_layout.bounds().origin,
372                caret_layout.line_height(),
373                px(2.0),
374                &overdraws,
375                window,
376            );
377            let Some(offset) = caret else {
378                return;
379            };
380            let face = font(Theme::of(cx).font_body.clone());
381            paint_caret(
382                &caret_layout,
383                offset,
384                affinity,
385                glyph.as_ref(),
386                CaretPaint {
387                    shape,
388                    height,
389                    hollow,
390                    color: caret_color,
391                    cover,
392                    size,
393                    face,
394                },
395                window,
396            );
397        },
398    )
399    .absolute()
400    .size_full();
401    let underlay = canvas(
402        {
403            let mentions = mentions.clone();
404            move |_, window, cx| {
405                mentions
406                    .iter()
407                    .map(|mention| {
408                        let favicon = mention.favicon.clone()?;
409                        let source = gpui::Resource::Uri(favicon.to_string().into());
410                        window
411                            .use_asset::<gpui::ImgResourceLoader>(&source, cx)?
412                            .ok()
413                    })
414                    .collect::<Vec<_>>()
415            }
416        },
417        move |_, favicons, window, cx| {
418            if let Some(layouts) = &layouts {
419                layouts.record(ix, part, span.clone(), layout.clone(), shown.clone());
420            }
421            // Under the glyphs, like the inline-code wash — one quad per visual
422            // row, so a wrapped selection is a stack of rows rather than a box
423            // around all of them. Under the marks and the annotations, which
424            // are translucent: a highlight shows through over a selection.
425            if let Some(range) = &selected {
426                for rect in range_rects(&layout, range, 0.0, 0.0) {
427                    window.paint_quad(quad(
428                        rect,
429                        px(2.0),
430                        selection_color,
431                        px(0.0),
432                        gpui::transparent_black(),
433                        BorderStyle::default(),
434                    ));
435                }
436            }
437            for (range, wash) in &washes {
438                for rect in range_rects(&layout, range, 0.0, 0.0) {
439                    window.paint_quad(quad(
440                        rect,
441                        px(0.0),
442                        *wash,
443                        px(0.0),
444                        gpui::transparent_black(),
445                        BorderStyle::default(),
446                    ));
447                }
448            }
449            for (range, wash) in &annotated {
450                for rect in range_rects(&layout, range, 0.0, 0.0) {
451                    window.paint_quad(quad(
452                        rect,
453                        px(2.0),
454                        *wash,
455                        px(0.0),
456                        gpui::transparent_black(),
457                        BorderStyle::default(),
458                    ));
459                }
460            }
461            for range in &code_ranges {
462                for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
463                    window.paint_quad(quad(
464                        rect,
465                        px(INLINE_CODE_RADIUS),
466                        wash,
467                        px(0.0),
468                        gpui::transparent_black(),
469                        BorderStyle::default(),
470                    ));
471                }
472            }
473            for (mention, favicon) in mentions.iter().zip(favicons) {
474                let Some(slot) = range_rects(&layout, &mention.icon, 0.0, 0.0).pop() else {
475                    continue;
476                };
477                let side = slot.size.width.min(px(size));
478                let icon = Bounds::new(
479                    slot.origin + point(px(0.0), (slot.size.height - side) / 2.0),
480                    gpui::size(side, side),
481                );
482                let radius = gpui::Corners::all(side / 4.0);
483                if let Some(data) = mention.glyph.as_ref().and_then(|glyph| glyph.data()) {
484                    let path = SharedString::from(format!("markdown-glyph-{:p}", data.as_ptr()));
485                    window
486                        .paint_svg(
487                            icon,
488                            path,
489                            Some(data),
490                            gpui::TransformationMatrix::unit(),
491                            icon_color,
492                            cx,
493                        )
494                        .ok();
495                    continue;
496                }
497                if let Some(favicon) = favicon {
498                    window
499                        .paint_image(icon, icon, radius, favicon, 0, false)
500                        .ok();
501                    continue;
502                }
503                window.paint_quad(quad(
504                    icon,
505                    side / 4.0,
506                    icon_wash,
507                    px(0.0),
508                    gpui::transparent_black(),
509                    BorderStyle::default(),
510                ));
511                let font = font(Theme::of(cx).font_body.clone());
512                let letter = window.text_system().shape_line(
513                    mention.initial.clone(),
514                    side * 0.55,
515                    &[TextRun {
516                        len: mention.initial.len(),
517                        font,
518                        color: icon_color,
519                        background_color: None,
520                        underline: None,
521                        strikethrough: None,
522                    }],
523                    None,
524                );
525                let at = point(icon.center().x - letter.width / 2.0, icon.origin.y);
526                letter
527                    .paint(at, side, gpui::TextAlign::Left, None, window, cx)
528                    .ok();
529            }
530        },
531    )
532    .absolute()
533    .size_full();
534
535    div()
536        .text_size(px(size))
537        .line_height(px(line_height))
538        .relative()
539        .child(underlay)
540        .children(hint)
541        .child(painted)
542        .child(over)
543        // A shift-press on a link is the link's: the host follows it on the
544        // release, and the editor around would take the press as extending
545        // the selection.
546        .on_mouse_down(MouseButton::Left, move |event, _, cx| {
547            let on_link = press_layout
548                .index_for_position(event.position)
549                .is_ok_and(|at| link_ranges.iter().any(|range| range.contains(&at)));
550            if event.modifiers.shift && on_link {
551                cx.stop_propagation();
552            }
553        })
554        .into_any_element()
555}
556
557/// The caret's quad: the text's own size, centred in the line box.
558///
559/// The leading is not the caret's to take. A document is set with air around
560/// its lines, and a caret filling all of it reads as a second, larger font
561/// standing where the text should be.
562pub(super) fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
563    let inset = (line_height - px(size)) / 2.0;
564    Bounds::new(
565        head + point(px(0.0), inset),
566        gpui::size(px(CARET_WIDTH), px(size)),
567    )
568}
569
570/// The grapheme after `offset` on its line, if there is one.
571pub(super) fn glyph_at(text: &str, offset: usize) -> Option<Range<usize>> {
572    (offset < text.len() && text.is_char_boundary(offset) && !text[offset..].starts_with('\n'))
573        .then(|| offset..ui::input::next_boundary(text, offset))
574}
575
576/// How a caret is drawn, apart from where.
577pub(super) struct CaretPaint {
578    pub shape: ui::input::CaretShape,
579    pub height: ui::input::CaretHeight,
580    pub hollow: bool,
581    pub color: Hsla,
582    /// The colour of the glyph a solid block covers.
583    pub cover: Hsla,
584    /// The text's font size, in pixels.
585    pub size: f32,
586    /// The font a wide caret measures its empty slot in.
587    pub face: gpui::Font,
588}
589
590/// Where a caret at `offset` paints in `layout`, on the row `affinity` names
591/// at a soft wrap.
592pub(super) fn caret_position(
593    layout: &TextLayout,
594    offset: usize,
595    affinity: Affinity,
596) -> Option<Point<Pixels>> {
597    if affinity == Affinity::Downstream
598        && let Some(start) = wrapped_row_start(layout, offset)
599    {
600        return Some(start);
601    }
602    layout.position_for_index(offset)
603}
604
605/// The origin of the row a soft wrap at `offset` starts, or `None` when no
606/// wrap falls there.
607fn wrapped_row_start(layout: &TextLayout, offset: usize) -> Option<Point<Pixels>> {
608    let line_height = layout.line_height();
609    let mut origin = layout.bounds().origin;
610    let mut line_start = 0;
611    for line in layout.line_layouts() {
612        if offset > line_start + line.len() {
613            origin.y += line.size(line_height).height;
614            line_start += line.len() + 1;
615            continue;
616        }
617        let shaped = &line.unwrapped_layout;
618        let row = line.wrap_boundaries().iter().position(|wrap| {
619            line_start + shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index == offset
620        })?;
621        return Some(origin + point(px(0.0), line_height * (row + 1) as f32));
622    }
623    None
624}
625
626/// Paints the caret at `offset` in `layout`, over the text. A `glyph` is what
627/// a solid block covers, on whichever row it shaped, painted again over it.
628pub(super) fn paint_caret(
629    layout: &TextLayout,
630    offset: usize,
631    affinity: Affinity,
632    glyph: Option<&Range<usize>>,
633    paint: CaretPaint,
634    window: &mut Window,
635) {
636    let line_height = layout.line_height();
637    let covered = glyph.and_then(|glyph| range_rects(layout, glyph, 0.0, 0.0).into_iter().next());
638    let (head, width) = match covered {
639        Some(rect) => (rect.origin, rect.size.width),
640        None => {
641            let Some(head) = caret_position(layout, offset, affinity) else {
642                return;
643            };
644            let width = match paint.shape {
645                ui::input::CaretShape::Bar => px(0.0),
646                _ => caret_advance(layout, offset).unwrap_or_else(|| {
647                    ui::input::caret::zero_width(paint.face, px(paint.size), window)
648                }),
649            };
650            (head, width)
651        }
652    };
653    window.paint_quad(paint.shape.quad(
654        caret_quad(head, paint.size, line_height),
655        line_height,
656        paint.height,
657        width,
658        paint.color,
659        paint.hollow,
660    ));
661    if let Some(glyph) = glyph
662        && covered.is_some()
663        && let Some((line, range)) = line_of(layout, glyph)
664    {
665        ui::input::caret::paint_covered(
666            &line.unwrapped_layout,
667            &range,
668            head,
669            line_height,
670            paint.cover,
671            window,
672        );
673    }
674}
675
676/// The shaped line `range` falls in, and `range` within that line.
677fn line_of(
678    layout: &TextLayout,
679    range: &Range<usize>,
680) -> Option<(Arc<gpui::WrappedLineLayout>, Range<usize>)> {
681    let mut start = 0;
682    for line in layout.line_layouts() {
683        let end = start + line.len();
684        if range.start <= end {
685            return (range.end <= end).then(|| (line, range.start - start..range.end - start));
686        }
687        start = end + 1;
688    }
689    None
690}
691
692/// The rectangles a byte range occupies, one per visual row.
693pub(super) fn range_rects(
694    layout: &gpui::TextLayout,
695    range: &Range<usize>,
696    pad_x: f32,
697    inset_y: f32,
698) -> Vec<Bounds<Pixels>> {
699    let mut rects = Vec::new();
700    let line_height = layout.line_height();
701    let mut origin = layout.bounds().origin;
702    let mut line_start = 0;
703    for line in layout.line_layouts() {
704        let shaped = &line.unwrapped_layout;
705        // A wrap boundary index is both the end of one row and the start of
706        // the next.
707        let row_ends = line
708            .wrap_boundaries()
709            .iter()
710            .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
711            .chain([line.len()]);
712        let mut row_start = 0;
713        for (row, row_end) in row_ends.enumerate() {
714            let from = range
715                .start
716                .saturating_sub(line_start)
717                .clamp(row_start, row_end);
718            let to = range.end.saturating_sub(line_start).min(row_end);
719            let row_x = shaped.x_for_index(row_start);
720            let (left, right) = (shaped.x_for_index(from), shaped.x_for_index(to));
721            if from < to && right > left {
722                rects.push(Bounds::new(
723                    origin
724                        + point(
725                            left - row_x - px(pad_x),
726                            line_height * row as f32 + px(inset_y),
727                        ),
728                    size(
729                        right - left + px(2.0 * pad_x),
730                        line_height - px(2.0 * inset_y),
731                    ),
732                ));
733            }
734            row_start = row_end;
735        }
736        origin.y += line.size(line_height).height;
737        // The newline between two lines is a byte of the text and of neither.
738        line_start += line.len() + 1;
739    }
740    rects
741}
742
743/// Resolve the advance in the same shaped line that owns the caret position.
744pub(super) fn caret_advance(layout: &TextLayout, offset: usize) -> Option<Pixels> {
745    let text = layout.text();
746    let mut start = 0;
747    for line in layout.line_layouts() {
748        let end = start + line.len();
749        if offset <= end {
750            return ui::input::caret::character_advance(&line, &text[start..end], offset - start);
751        }
752        start = end + 1;
753    }
754    None
755}