Skip to main content

ui/input/
element.rs

1//! Shaping and painting: runs, rows, selection and caret.
2
3use super::*;
4use crate::AppExt as _;
5
6/// What gets painted, and whether it is the placeholder — which is the only
7/// reason the colour differs.
8pub(super) fn display_text(field: &TextField) -> (chip::Chipped, bool) {
9    if field.content.is_empty() {
10        (chip::Chipped::plain(field.placeholder.clone()), true)
11    } else {
12        (chip::chipped(&field.content, &field.chips), false)
13    }
14}
15
16/// `runs` with each chip in `chipped` painted: the glyph's slot empty, the
17/// title underlined, both in `color` whatever the spans said.
18fn chip_runs(mut runs: Vec<TextRun>, chipped: &chip::Chipped, color: gpui::Hsla) -> Vec<TextRun> {
19    for ((slot, _), title) in chipped.slots.iter().zip(&chipped.titles) {
20        runs = caret::recoloured(runs, &(slot.start..title.end), color);
21        runs = caret::recoloured(runs, slot, gpui::transparent_black());
22        runs = underlined(runs, title);
23    }
24    runs
25}
26
27/// One run per span, the text between them in the field's own colour.
28///
29/// The runs a field paints [`TextField::set_spans`] as, public for the same
30/// reason [`next_boundary`] is: anything shaping the same text with the same
31/// palette wants the same answer, and this is where it is decided.
32///
33/// The spans are whatever the caller last handed over, which may describe text
34/// this frame no longer holds — see [`TextField::set_spans`]. A range that runs
35/// past the end, overlaps the one before it, or cuts a character in half is
36/// dropped rather than shifting the runs after it: shaping needs the lengths to
37/// add up to the text, and a colour that is wrong for one frame is cheaper than
38/// a panic.
39///
40/// `base.len` is ignored: every run is measured off `text`.
41pub fn coloured(
42    text: &str,
43    spans: &[(Range<usize>, HighlightKind)],
44    base: &TextRun,
45    palette: &SyntaxPalette,
46) -> Vec<TextRun> {
47    if spans.is_empty() {
48        return vec![TextRun {
49            len: text.len(),
50            ..base.clone()
51        }];
52    }
53    let mut runs = Vec::with_capacity(spans.len() * 2 + 1);
54    let mut at = 0;
55    for (range, kind) in spans {
56        if range.start < at
57            || range.end <= range.start
58            || range.end > text.len()
59            || !text.is_char_boundary(range.start)
60            || !text.is_char_boundary(range.end)
61        {
62            continue;
63        }
64        if range.start > at {
65            runs.push(TextRun {
66                len: range.start - at,
67                ..base.clone()
68            });
69        }
70        runs.push(TextRun {
71            len: range.end - range.start,
72            color: palette.color(*kind),
73            ..base.clone()
74        });
75        at = range.end;
76    }
77    if at < text.len() {
78        runs.push(TextRun {
79            len: text.len() - at,
80            ..base.clone()
81        });
82    }
83    runs
84}
85
86/// The IME composition range underlined, so the user can see what is still
87/// provisional. Each run is cut at the range's edges and the pieces inside it
88/// take the line, in whatever colour they already had.
89pub fn underlined(runs: Vec<TextRun>, marked: &Range<usize>) -> Vec<TextRun> {
90    let mut out = Vec::with_capacity(runs.len() + 2);
91    let mut at = 0;
92    for run in runs {
93        let end = at + run.len;
94        for (start, stop, mark) in [
95            (at, end.min(marked.start), false),
96            (at.max(marked.start), end.min(marked.end), true),
97            (at.max(marked.end), end, false),
98        ] {
99            if stop <= start {
100                continue;
101            }
102            out.push(TextRun {
103                len: stop - start,
104                underline: mark.then(|| UnderlineStyle {
105                    color: Some(run.color),
106                    thickness: px(1.0),
107                    wavy: false,
108                }),
109                ..run.clone()
110            });
111        }
112        at = end;
113    }
114    out
115}
116
117// ---------------------------------------------------------------------------
118// Line geometry. `shape_text` returns one `WrappedLine` per hard newline, each
119// wrapping into rows of its own; gpui resolves positions *within* a line, so
120// everything here is walking that list and nothing re-implements shaping.
121// ---------------------------------------------------------------------------
122
123/// Each shaped line with the byte offset it starts at. `shape_text` splits on
124/// `\n` and drops the separator, so each line starts one byte past the last.
125pub(super) fn lines_from(lines: &[WrappedLine]) -> impl Iterator<Item = (usize, &WrappedLine)> {
126    lines.iter().scan(0usize, |start, line| {
127        let at = *start;
128        *start = at + line.len() + 1;
129        Some((at, line))
130    })
131}
132
133/// Every visual row: the byte range it covers and its top edge, relative to the
134/// text origin. A wrap boundary resolves to a byte index exactly the way
135/// `WrappedLineLayout::position_for_index` does it internally — that mapping is
136/// not exposed, and selection needs one quad per row.
137pub(super) fn rows(lines: &[WrappedLine], line_height: Pixels) -> Vec<(Range<usize>, Pixels)> {
138    let mut out = Vec::new();
139    let mut top = px(0.);
140    for (start, line) in lines_from(lines) {
141        let mut row_start = start;
142        for boundary in line.wrap_boundaries() {
143            let at = start + line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix].index;
144            out.push((row_start..at, top));
145            row_start = at;
146            top += line_height;
147        }
148        out.push((row_start..start + line.len(), top));
149        top += line_height;
150    }
151    out
152}
153
154/// Byte offset → position relative to the text origin.
155pub(super) fn position_for_offset(
156    lines: &[WrappedLine],
157    offset: usize,
158    line_height: Pixels,
159) -> Option<Point<Pixels>> {
160    let mut top = px(0.);
161    for (start, line) in lines_from(lines) {
162        if offset <= start + line.len() {
163            let local = line.position_for_index(offset.saturating_sub(start), line_height)?;
164            return Some(gpui::point(local.x, local.y + top));
165        }
166        top += line.size(line_height).height;
167    }
168    None
169}
170
171/// Position relative to the text origin → the closest byte offset.
172pub(super) fn offset_for_position(
173    lines: &[WrappedLine],
174    position: Point<Pixels>,
175    line_height: Pixels,
176) -> usize {
177    let mut top = px(0.);
178    let mut last = 0;
179    for (start, line) in lines_from(lines) {
180        let height = line.size(line_height).height;
181        last = start + line.len();
182        if position.y < top + height {
183            let local = gpui::point(position.x, position.y - top);
184            let (Ok(index) | Err(index)) = line.closest_index_for_position(local, line_height);
185            return start + index;
186        }
187        top += height;
188    }
189    last
190}
191
192/// The char boundary at or before `offset`, clamped to the end of `text`.
193pub(super) fn floor_boundary(text: &str, offset: usize) -> usize {
194    let mut offset = offset.min(text.len());
195    while !text.is_char_boundary(offset) {
196        offset -= 1;
197    }
198    offset
199}
200
201/// The selection as one rect per visual row, relative to the text origin.
202///
203/// A row's left edge is always x=0, so a continuation row is taken from there
204/// rather than by looking the offset up — at a soft wrap the two rows share a
205/// byte offset, and the lookup resolves it to the end of the earlier row.
206pub(super) fn selection_rows(
207    lines: &[WrappedLine],
208    range: &Range<usize>,
209    line_height: Pixels,
210) -> Vec<Bounds<Pixels>> {
211    rows(lines, line_height)
212        .into_iter()
213        .filter(|(row, _)| range.start <= row.end && range.end >= row.start)
214        .filter_map(|(row, top)| {
215            let left = if range.start <= row.start {
216                px(0.)
217            } else {
218                position_for_offset(lines, range.start, line_height)?.x
219            };
220            let right = position_for_offset(lines, range.end.min(row.end), line_height)?.x;
221            (right > left).then(|| {
222                Bounds::from_corners(
223                    gpui::point(left, top),
224                    gpui::point(right, top + line_height),
225                )
226            })
227        })
228        .collect()
229}
230
231impl Render for TextField {
232    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
233        // The only place the blink starts: `caret_moved` drops the task, so the
234        // next render brings it back in phase, solid beat first.
235        if self.focus_handle.is_focused(_window) && cx.caret_blink() {
236            if self.blink.is_none() {
237                self.start_blink(cx);
238            }
239        } else {
240            self.blink = None;
241            self.caret_on = true;
242        }
243        let theme = Theme::of(cx);
244        let mut key_context = gpui::KeyContext::default();
245        key_context.add(KEY_CONTEXT);
246        if self.shape.is_multiline() {
247            key_context.add(MULTILINE_KEY_CONTEXT);
248        }
249        if let Some(extra) = self.key_context.clone() {
250            key_context.add(extra);
251        }
252        div()
253            .key_context(key_context)
254            .track_focus(&self.focus_handle(cx))
255            .cursor(CursorStyle::IBeam)
256            .on_action(cx.listener(Self::backspace))
257            .on_action(cx.listener(Self::delete))
258            .on_action(cx.listener(Self::left))
259            .on_action(cx.listener(Self::right))
260            .on_action(cx.listener(Self::select_left))
261            .on_action(cx.listener(Self::select_right))
262            .on_action(cx.listener(Self::select_all))
263            .on_action(cx.listener(Self::home))
264            .on_action(cx.listener(Self::end))
265            .on_action(cx.listener(Self::select_home))
266            .on_action(cx.listener(Self::select_end))
267            .on_action(cx.listener(Self::word_left))
268            .on_action(cx.listener(Self::word_right))
269            .on_action(cx.listener(Self::select_word_left))
270            .on_action(cx.listener(Self::select_word_right))
271            .on_action(cx.listener(Self::up))
272            .on_action(cx.listener(Self::down))
273            .on_action(cx.listener(Self::select_up))
274            .on_action(cx.listener(Self::select_down))
275            .on_action(cx.listener(Self::insert_newline))
276            .on_action(cx.listener(Self::undo))
277            .on_action(cx.listener(Self::redo))
278            .on_action(cx.listener(Self::delete_word_left))
279            .on_action(cx.listener(Self::delete_word_right))
280            .on_action(cx.listener(Self::delete_to_line_start))
281            .on_action(cx.listener(Self::delete_to_line_end))
282            .on_action(cx.listener(Self::show_character_palette))
283            .on_action(cx.listener(Self::paste))
284            .on_action(cx.listener(Self::cut))
285            .on_action(cx.listener(Self::copy))
286            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
287            .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
288            .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
289            .on_scroll_wheel(cx.listener(Self::on_scroll_wheel))
290            .w_full()
291            .when(self.frame, |field| {
292                field
293                    .px(px(10.0))
294                    .py(px(7.0))
295                    .rounded(px(Theme::button_radius()))
296                    .bg(theme.input_bg)
297                    .border_1()
298                    .border_color(if self.focus_handle.is_focused(_window) {
299                        theme.ring
300                    } else {
301                        theme.border
302                    })
303            })
304            .text_size(px(self.metrics.size()))
305            .font_weight(self.metrics.weight)
306            .line_height(px(self.metrics.line_height()))
307            .text_color(theme.text)
308            .child(TextFieldElement { field: cx.entity() })
309    }
310}
311
312/// Paints the shaped lines plus selection and caret. A custom element because
313/// all three are geometry derived from the shaped text, which only exists after
314/// layout.
315pub(super) struct TextFieldElement {
316    field: Entity<TextField>,
317}
318
319pub(super) struct FieldPrepaint {
320    lines: Vec<WrappedLine>,
321    shown: Shown,
322    /// Each chip's glyph and the slot it is painted in, in `lines`' offsets.
323    glyphs: Vec<(Range<usize>, icons::Icon)>,
324    glyph_color: gpui::Hsla,
325    font_size: Pixels,
326    /// Top-left of the text, which is the box moved up by the scroll offset.
327    origin: Point<Pixels>,
328    cursor: Option<PaintQuad>,
329    /// One quad per visual row each match covers.
330    matches: Vec<PaintQuad>,
331    /// One quad per visual row the selection covers.
332    selection: Vec<PaintQuad>,
333}
334
335impl IntoElement for TextFieldElement {
336    type Element = Self;
337
338    fn into_element(self) -> Self::Element {
339        self
340    }
341}
342
343impl Element for TextFieldElement {
344    type RequestLayoutState = ();
345    type PrepaintState = FieldPrepaint;
346
347    fn id(&self) -> Option<ElementId> {
348        None
349    }
350
351    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
352        None
353    }
354
355    fn request_layout(
356        &mut self,
357        _id: Option<&GlobalElementId>,
358        _inspector_id: Option<&gpui::InspectorElementId>,
359        window: &mut Window,
360        cx: &mut App,
361    ) -> (LayoutId, ()) {
362        let mut style = Style::default();
363        style.size.width = relative(1.).into();
364        let field = self.field.read(cx);
365        // The field's own, here as everywhere: sizing the box off one height
366        // and hit-testing it at another is how a click lands on the wrong row.
367        let line_height = field.line_height();
368        let shape = field.shape;
369
370        let (min, max) = match shape {
371            Shape::Line => {
372                style.size.height = line_height.into();
373                return (window.request_layout(style, [], cx), ());
374            }
375            Shape::Rows(rows) => {
376                style.size.height = (line_height * rows.max(1) as f32).into();
377                return (window.request_layout(style, [], cx), ());
378            }
379            // Growing needs the row count, and the row count needs shaping at
380            // the width layout is still deciding — which is exactly what a
381            // measured layout is for.
382            Shape::Grow { min, max } => (min.max(1), max.max(min.max(1))),
383        };
384
385        let text = display_text(field).0.text;
386        // Measuring runs after the element's text style is popped, where the
387        // window reports gpui's default font instead.
388        let text_style = window.text_style();
389        let font_size = text_style.font_size.to_pixels(window.rem_size());
390        let id = window.request_measured_layout(style, move |known, available, window, _cx| {
391            // Prefer the width layout has already settled on. Taffy also probes
392            // with min/max-content, where there is no width to wrap against —
393            // and counting rows off unwrapped text under-reports them, which
394            // would size the box for fewer lines than it goes on to paint.
395            let wrap_width = known.width.or(match available.width {
396                gpui::AvailableSpace::Definite(width) => Some(width),
397                _ => None,
398            });
399            let run = TextRun {
400                len: text.len(),
401                font: text_style.font(),
402                color: text_style.color,
403                background_color: None,
404                underline: None,
405                strikethrough: None,
406            };
407            let count = window
408                .text_system()
409                .shape_text(text.clone(), font_size, &[run], wrap_width, None)
410                .map(|lines| {
411                    lines
412                        .iter()
413                        .map(|line| line.wrap_boundaries().len() + 1)
414                        .sum::<usize>()
415                })
416                .unwrap_or(1);
417            gpui::size(
418                wrap_width.unwrap_or(px(0.)),
419                line_height * count.clamp(min, max) as f32,
420            )
421        });
422        (id, ())
423    }
424
425    fn prepaint(
426        &mut self,
427        _id: Option<&GlobalElementId>,
428        _inspector_id: Option<&gpui::InspectorElementId>,
429        bounds: Bounds<Pixels>,
430        _request_layout: &mut Self::RequestLayoutState,
431        window: &mut Window,
432        cx: &mut App,
433    ) -> FieldPrepaint {
434        let theme = Theme::of(cx).clone();
435        let field = self.field.read(cx);
436        let (chipped, is_placeholder) = display_text(field);
437        // Everything from here on is in the offsets of the text painted.
438        let shown = chipped.shown.clone();
439        let selected_range = shown.range(&field.selected_range);
440        let cursor = shown.at(field.cursor_offset());
441        let shape = field.shape;
442        let marked_range = field.marked_range.as_ref().map(|range| shown.range(range));
443        let matches: Vec<_> = field
444            .matches
445            .iter()
446            .filter(|range| {
447                range.start <= range.end
448                    && field.content.is_char_boundary(range.start)
449                    && field.content.is_char_boundary(range.end)
450            })
451            .map(|range| shown.range(range))
452            .collect();
453        let scrolled = field.scroll;
454        let caret_shape = cx.caret_shape();
455        let caret_height = cx.caret_height();
456        let follow_caret = field.follow_caret || caret_shape != field.last_caret_shape;
457        let style = window.text_style();
458
459        let text = chipped.text.clone();
460        let text_color = if is_placeholder {
461            theme.text_faint
462        } else {
463            style.color
464        };
465
466        let run = TextRun {
467            len: text.len(),
468            font: style.font(),
469            color: text_color,
470            background_color: None,
471            underline: None,
472            strikethrough: None,
473        };
474        // Syntax first, then the IME composition range underlined over the top
475        // of it: both cut the text into runs, and the underline has to land on
476        // whatever colour is already there.
477        let runs = if is_placeholder {
478            vec![run]
479        } else {
480            let spans: Vec<_> = field
481                .spans
482                .iter()
483                .map(|(range, kind)| (shown.range(range), *kind))
484                .collect();
485            chip_runs(
486                coloured(&text, &spans, &run, &theme.syntax),
487                &chipped,
488                text_color,
489            )
490        };
491        let runs = match marked_range.as_ref() {
492            Some(marked) => underlined(runs, marked),
493            None => runs,
494        };
495
496        let font_size = style.font_size.to_pixels(window.rem_size());
497        let line_height = field.line_height();
498        // A single line never wraps: it scrolls sideways instead, so shaping it
499        // against the field's width would fold it into rows nothing can reach.
500        let wrap_width = shape.is_multiline().then_some(bounds.size.width);
501        let lines = window
502            .text_system()
503            .shape_text(text.clone(), font_size, &runs, wrap_width, None)
504            .map(|lines| lines.into_vec())
505            .unwrap_or_default();
506
507        // Clamp every frame, not just when scrolling: the content this is
508        // measured against shrinks under it — delete the last line while parked
509        // at the bottom and an unclamped offset leaves the box showing nothing.
510        //
511        // A wide caret needs trailing room even at the end of the longest row.
512        // Keep the bar's existing scroll extent unchanged.
513        let content_height: Pixels = lines.iter().map(|l| l.size(line_height).height).sum();
514        let content_width = lines.iter().map(|l| l.width()).fold(px(0.), Pixels::max);
515        // The slot a wide caret takes where no character follows it — the end
516        // of the text, a soft-wrap boundary: the font's `ch` width.
517        let slot = (caret_shape != CaretShape::Bar)
518            .then(|| caret::zero_width(style.font(), font_size, window));
519        // A placeholder is not text: over it the caret takes the empty slot.
520        let follows = (!is_placeholder)
521            .then(|| {
522                lines_from(&lines)
523                    .find_map(|(start, line)| {
524                        (cursor <= start + line.len()).then(|| {
525                            caret::character_advance(line, &line.text, cursor.saturating_sub(start))
526                        })
527                    })
528                    .flatten()
529            })
530            .flatten();
531        let advance = slot.map(|slot| follows.unwrap_or(slot));
532        let hollow = !window.is_window_active();
533        let lines = if caret_shape.cuts_out(hollow)
534            && follows.is_some()
535            && selected_range.is_empty()
536            && field.caret_on
537            && field.focus_handle.is_focused(window)
538        {
539            let glyph = cursor..next_boundary(&text, cursor);
540            window
541                .text_system()
542                .shape_text(
543                    text.clone(),
544                    font_size,
545                    &caret::recoloured(runs, &glyph, theme.bg),
546                    wrap_width,
547                    None,
548                )
549                .map(|lines| lines.into_vec())
550                .unwrap_or(lines)
551        } else {
552            lines
553        };
554        let caret_width = caret_shape
555            .quad(
556                Bounds::new(
557                    gpui::point(px(0.), px(0.)),
558                    gpui::size(CARET_WIDTH, font_size),
559                ),
560                line_height,
561                caret_height,
562                advance.unwrap_or_default(),
563                theme.caret,
564                hollow,
565            )
566            .bounds
567            .size
568            .width;
569        // A field that wraps never scrolls sideways.
570        let max = gpui::point(
571            match shape.is_multiline() {
572                true => px(0.),
573                false => (content_width + slot.unwrap_or_default() - bounds.size.width).max(px(0.)),
574            },
575            (content_height - bounds.size.height).max(px(0.)),
576        );
577        let mut scroll = gpui::point(
578            scrolled.x.clamp(px(0.), max.x),
579            scrolled.y.clamp(px(0.), max.y),
580        );
581        if follow_caret && let Some(at) = position_for_offset(&lines, cursor, line_height) {
582            if at.y < scroll.y {
583                scroll.y = at.y;
584            } else if at.y + line_height > scroll.y + bounds.size.height {
585                scroll.y = at.y + line_height - bounds.size.height;
586            }
587            // The caret is the thing being kept in view, so it is its own width
588            // that has to clear the right edge — not the character before it.
589            if at.x < scroll.x {
590                scroll.x = at.x;
591            } else if at.x + caret_width > scroll.x + bounds.size.width {
592                scroll.x = at.x + caret_width - bounds.size.width;
593            }
594            scroll.x = scroll.x.clamp(px(0.), max.x);
595            scroll.y = scroll.y.clamp(px(0.), max.y);
596        }
597        self.field.update(cx, |field, _| {
598            field.scroll = scroll;
599            field.follow_caret = false;
600            field.last_caret_shape = caret_shape;
601        });
602        let origin = bounds.origin - scroll;
603
604        let matches = if is_placeholder {
605            Vec::new()
606        } else {
607            matches
608                .iter()
609                .flat_map(|range| selection_rows(&lines, range, line_height))
610                .map(|rect| {
611                    fill(
612                        Bounds::new(origin + rect.origin, rect.size),
613                        theme.warning.opacity(0.25),
614                    )
615                })
616                .collect()
617        };
618
619        let (selection, cursor) = if selected_range.is_empty() {
620            let at = position_for_offset(&lines, cursor, line_height).unwrap_or_default();
621            (
622                Vec::new(),
623                Some(caret_shape.quad(
624                    // The font's size rather than the line's: leading is not
625                    // a bar's or an underline's to fill. A block fills it.
626                    Bounds::new(
627                        origin + at + gpui::point(px(0.), (line_height - font_size) / 2.),
628                        gpui::size(CARET_WIDTH, font_size),
629                    ),
630                    line_height,
631                    caret_height,
632                    advance.unwrap_or_default(),
633                    theme.caret,
634                    hollow,
635                )),
636            )
637        } else {
638            (
639                selection_rows(&lines, &selected_range, line_height)
640                    .into_iter()
641                    .map(|rect| {
642                        fill(
643                            Bounds::new(origin + rect.origin, rect.size),
644                            theme.selection,
645                        )
646                    })
647                    .collect(),
648                None,
649            )
650        };
651
652        FieldPrepaint {
653            lines,
654            shown,
655            glyphs: chipped.slots,
656            glyph_color: theme.text_muted,
657            font_size,
658            origin,
659            cursor,
660            matches,
661            selection,
662        }
663    }
664
665    fn paint(
666        &mut self,
667        _id: Option<&GlobalElementId>,
668        _inspector_id: Option<&gpui::InspectorElementId>,
669        bounds: Bounds<Pixels>,
670        _request_layout: &mut Self::RequestLayoutState,
671        prepaint: &mut Self::PrepaintState,
672        window: &mut Window,
673        cx: &mut App,
674    ) {
675        let focus_handle = self.field.read(cx).focus_handle.clone();
676        let caret_on = self.field.read(cx).caret_on;
677        window.handle_input(
678            &focus_handle,
679            ElementInputHandler::new(bounds, self.field.clone()),
680            cx,
681        );
682        let line_height = self.field.read(cx).line_height();
683        // A drag that leaves the box is still a drag. `on_mouse_move` on the
684        // field's own div fires only while the box is the thing under the
685        // pointer, so a run dragged past the edge froze at the last character
686        // inside it — and the last line of a full box was unreachable, since
687        // reaching it means passing the edge. This is the window's own move,
688        // which arrives wherever the pointer went.
689        //
690        // Registered every frame because that is the contract: the listener is
691        // cleared with the frame that installed it.
692        let dragged = self.field.clone();
693        window.on_mouse_event(move |event: &MouseMoveEvent, phase, _window, cx| {
694            // The button being down is what makes this a drag. `selecting`
695            // is only cleared on the release, so a press whose release went
696            // somewhere we never heard about would otherwise leave a plain
697            // hover dragging the run around.
698            if phase != DispatchPhase::Bubble || !event.dragging() {
699                return;
700            }
701            dragged.update(cx, |field, cx| {
702                field.drag_to(event.position, line_height, cx);
703            });
704        });
705        let lines = std::mem::take(&mut prepaint.lines);
706        let matches = std::mem::take(&mut prepaint.matches);
707        let selection = std::mem::take(&mut prepaint.selection);
708        let cursor = prepaint.cursor.take();
709        let origin = prepaint.origin;
710
711        // Scrolled text runs past the box in both directions, so everything the
712        // field draws is masked to it — text, selection and caret alike.
713        window.with_content_mask(Some(gpui::ContentMask::new(bounds)), |window| {
714            for quad in matches.into_iter().chain(selection) {
715                window.paint_quad(quad);
716            }
717
718            // The caret only exists while focused — an unfocused field showing
719            // one reads as two cursors on screen. Under the text, so a glyph
720            // cut out of a block lands on top of it.
721            if focus_handle.is_focused(window)
722                && caret_on
723                && let Some(cursor) = cursor
724            {
725                window.paint_quad(cursor);
726            }
727
728            let mut top = origin;
729            for line in &lines {
730                line.paint(top, line_height, gpui::TextAlign::Left, None, window, cx)
731                    .ok();
732                top.y += line.size(line_height).height;
733            }
734
735            for (slot, glyph) in &prepaint.glyphs {
736                let Some(data) = glyph.data() else { continue };
737                let (Some(start), Some(end)) = (
738                    position_for_offset(&lines, slot.start, line_height),
739                    position_for_offset(&lines, slot.end, line_height),
740                ) else {
741                    continue;
742                };
743                let side = (end.x - start.x).min(prepaint.font_size);
744                let bounds = Bounds::new(
745                    origin + start + gpui::point(px(0.), (line_height - side) / 2.),
746                    gpui::size(side, side),
747                );
748                let path = SharedString::from(format!("field-glyph-{:p}", data.as_ptr()));
749                window
750                    .paint_svg(
751                        bounds,
752                        path,
753                        Some(data),
754                        gpui::TransformationMatrix::unit(),
755                        prepaint.glyph_color,
756                        cx,
757                    )
758                    .ok();
759            }
760        });
761
762        let shown = std::mem::take(&mut prepaint.shown);
763        self.field.update(cx, |field, _| {
764            field.last_layout = lines;
765            field.last_shown = shown;
766            field.last_bounds = Some(bounds);
767        });
768    }
769}