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_down(MouseButton::Right, cx.listener(Self::on_right_mouse_down))
288            .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
289            .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
290            .on_scroll_wheel(cx.listener(Self::on_scroll_wheel))
291            .w_full()
292            .when(self.frame, |field| {
293                field
294                    .px(px(10.0))
295                    .py(px(7.0))
296                    .rounded(px(Theme::button_radius()))
297                    .bg(theme.input_bg)
298                    .border_1()
299                    .border_color(if self.focus_handle.contains_focused(_window, cx) {
300                        theme.ring
301                    } else {
302                        theme.border
303                    })
304            })
305            .text_size(px(self.metrics.size()))
306            .font_weight(self.metrics.weight)
307            .line_height(px(self.metrics.line_height()))
308            .text_color(theme.text)
309            .child(TextFieldElement { field: cx.entity() })
310            .children(self.edit_menu(_window, cx))
311    }
312}
313
314/// Paints the shaped lines plus selection and caret. A custom element because
315/// all three are geometry derived from the shaped text, which only exists after
316/// layout.
317pub(super) struct TextFieldElement {
318    field: Entity<TextField>,
319}
320
321pub(super) struct FieldPrepaint {
322    lines: Vec<WrappedLine>,
323    shown: Shown,
324    /// Each chip's glyph and the slot it is painted in, in `lines`' offsets.
325    glyphs: Vec<(Range<usize>, icons::Icon)>,
326    glyph_color: gpui::Hsla,
327    font_size: Pixels,
328    /// Top-left of the text, which is the box moved up by the scroll offset.
329    origin: Point<Pixels>,
330    cursor: Option<PaintQuad>,
331    /// One quad per visual row each match covers.
332    matches: Vec<PaintQuad>,
333    /// One quad per visual row the selection covers.
334    selection: Vec<PaintQuad>,
335}
336
337impl IntoElement for TextFieldElement {
338    type Element = Self;
339
340    fn into_element(self) -> Self::Element {
341        self
342    }
343}
344
345impl Element for TextFieldElement {
346    type RequestLayoutState = ();
347    type PrepaintState = FieldPrepaint;
348
349    fn id(&self) -> Option<ElementId> {
350        None
351    }
352
353    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
354        None
355    }
356
357    fn request_layout(
358        &mut self,
359        _id: Option<&GlobalElementId>,
360        _inspector_id: Option<&gpui::InspectorElementId>,
361        window: &mut Window,
362        cx: &mut App,
363    ) -> (LayoutId, ()) {
364        let mut style = Style::default();
365        style.size.width = relative(1.).into();
366        let field = self.field.read(cx);
367        // The field's own, here as everywhere: sizing the box off one height
368        // and hit-testing it at another is how a click lands on the wrong row.
369        let line_height = field.line_height();
370        let shape = field.shape;
371
372        let (min, max) = match shape {
373            Shape::Line => {
374                style.size.height = line_height.into();
375                return (window.request_layout(style, [], cx), ());
376            }
377            Shape::Rows(rows) => {
378                style.size.height = (line_height * rows.max(1) as f32).into();
379                return (window.request_layout(style, [], cx), ());
380            }
381            // Growing needs the row count, and the row count needs shaping at
382            // the width layout is still deciding — which is exactly what a
383            // measured layout is for.
384            Shape::Grow { min, max } => (min.max(1), max.max(min.max(1))),
385        };
386
387        let text = display_text(field).0.text;
388        // Measuring runs after the element's text style is popped, where the
389        // window reports gpui's default font instead.
390        let text_style = window.text_style();
391        let font_size = text_style.font_size.to_pixels(window.rem_size());
392        let id = window.request_measured_layout(style, move |known, available, window, _cx| {
393            // Prefer the width layout has already settled on. Taffy also probes
394            // with min/max-content, where there is no width to wrap against —
395            // and counting rows off unwrapped text under-reports them, which
396            // would size the box for fewer lines than it goes on to paint.
397            let wrap_width = known.width.or(match available.width {
398                gpui::AvailableSpace::Definite(width) => Some(width),
399                _ => None,
400            });
401            let run = TextRun {
402                len: text.len(),
403                font: text_style.font(),
404                color: text_style.color,
405                background_color: None,
406                underline: None,
407                strikethrough: None,
408            };
409            let count = window
410                .text_system()
411                .shape_text(text.clone(), font_size, &[run], wrap_width, None)
412                .map(|lines| {
413                    lines
414                        .iter()
415                        .map(|line| line.wrap_boundaries().len() + 1)
416                        .sum::<usize>()
417                })
418                .unwrap_or(1);
419            gpui::size(
420                wrap_width.unwrap_or(px(0.)),
421                line_height * count.clamp(min, max) as f32,
422            )
423        });
424        (id, ())
425    }
426
427    fn prepaint(
428        &mut self,
429        _id: Option<&GlobalElementId>,
430        _inspector_id: Option<&gpui::InspectorElementId>,
431        bounds: Bounds<Pixels>,
432        _request_layout: &mut Self::RequestLayoutState,
433        window: &mut Window,
434        cx: &mut App,
435    ) -> FieldPrepaint {
436        let theme = Theme::of(cx).clone();
437        let field = self.field.read(cx);
438        let (chipped, is_placeholder) = display_text(field);
439        // Everything from here on is in the offsets of the text painted.
440        let shown = chipped.shown.clone();
441        let selected_range = shown.range(&field.selected_range);
442        let cursor = shown.at(field.cursor_offset());
443        let shape = field.shape;
444        let marked_range = field.marked_range.as_ref().map(|range| shown.range(range));
445        let matches: Vec<_> = field
446            .matches
447            .iter()
448            .filter(|range| {
449                range.start <= range.end
450                    && field.content.is_char_boundary(range.start)
451                    && field.content.is_char_boundary(range.end)
452            })
453            .map(|range| shown.range(range))
454            .collect();
455        let scrolled = field.scroll;
456        let caret_shape = cx.caret_shape();
457        let caret_height = cx.caret_height();
458        let follow_caret = field.follow_caret || caret_shape != field.last_caret_shape;
459        let style = window.text_style();
460
461        let text = chipped.text.clone();
462        let text_color = if is_placeholder {
463            theme.text_faint
464        } else {
465            style.color
466        };
467
468        let run = TextRun {
469            len: text.len(),
470            font: style.font(),
471            color: text_color,
472            background_color: None,
473            underline: None,
474            strikethrough: None,
475        };
476        // Syntax first, then the IME composition range underlined over the top
477        // of it: both cut the text into runs, and the underline has to land on
478        // whatever colour is already there.
479        let runs = if is_placeholder {
480            vec![run]
481        } else {
482            let spans: Vec<_> = field
483                .spans
484                .iter()
485                .map(|(range, kind)| (shown.range(range), *kind))
486                .collect();
487            chip_runs(
488                coloured(&text, &spans, &run, &theme.syntax),
489                &chipped,
490                text_color,
491            )
492        };
493        let runs = match marked_range.as_ref() {
494            Some(marked) => underlined(runs, marked),
495            None => runs,
496        };
497
498        let font_size = style.font_size.to_pixels(window.rem_size());
499        let line_height = field.line_height();
500        // A single line never wraps: it scrolls sideways instead, so shaping it
501        // against the field's width would fold it into rows nothing can reach.
502        let wrap_width = shape.is_multiline().then_some(bounds.size.width);
503        let lines = window
504            .text_system()
505            .shape_text(text.clone(), font_size, &runs, wrap_width, None)
506            .map(|lines| lines.into_vec())
507            .unwrap_or_default();
508
509        // Clamp every frame, not just when scrolling: the content this is
510        // measured against shrinks under it — delete the last line while parked
511        // at the bottom and an unclamped offset leaves the box showing nothing.
512        //
513        // A wide caret needs trailing room even at the end of the longest row.
514        // Keep the bar's existing scroll extent unchanged.
515        let content_height: Pixels = lines.iter().map(|l| l.size(line_height).height).sum();
516        let content_width = lines.iter().map(|l| l.width()).fold(px(0.), Pixels::max);
517        // The slot a wide caret takes where no character follows it — the end
518        // of the text, a soft-wrap boundary: the font's `ch` width.
519        let slot = (caret_shape != CaretShape::Bar)
520            .then(|| caret::zero_width(style.font(), font_size, window));
521        // A placeholder is not text: over it the caret takes the empty slot.
522        let follows = (!is_placeholder)
523            .then(|| {
524                lines_from(&lines)
525                    .find_map(|(start, line)| {
526                        (cursor <= start + line.len()).then(|| {
527                            caret::character_advance(line, &line.text, cursor.saturating_sub(start))
528                        })
529                    })
530                    .flatten()
531            })
532            .flatten();
533        let advance = slot.map(|slot| follows.unwrap_or(slot));
534        let hollow = !window.is_window_active();
535        let lines = if caret_shape.cuts_out(hollow)
536            && follows.is_some()
537            && selected_range.is_empty()
538            && field.caret_on
539            && field.focus_handle.is_focused(window)
540        {
541            let glyph = cursor..next_boundary(&text, cursor);
542            window
543                .text_system()
544                .shape_text(
545                    text.clone(),
546                    font_size,
547                    &caret::recoloured(runs, &glyph, theme.bg),
548                    wrap_width,
549                    None,
550                )
551                .map(|lines| lines.into_vec())
552                .unwrap_or(lines)
553        } else {
554            lines
555        };
556        let caret_width = caret_shape
557            .quad(
558                Bounds::new(
559                    gpui::point(px(0.), px(0.)),
560                    gpui::size(CARET_WIDTH, font_size),
561                ),
562                line_height,
563                caret_height,
564                advance.unwrap_or_default(),
565                theme.caret,
566                hollow,
567            )
568            .bounds
569            .size
570            .width;
571        // A field that wraps never scrolls sideways.
572        let max = gpui::point(
573            match shape.is_multiline() {
574                true => px(0.),
575                false => (content_width + slot.unwrap_or_default() - bounds.size.width).max(px(0.)),
576            },
577            (content_height - bounds.size.height).max(px(0.)),
578        );
579        let mut scroll = gpui::point(
580            scrolled.x.clamp(px(0.), max.x),
581            scrolled.y.clamp(px(0.), max.y),
582        );
583        if follow_caret && let Some(at) = position_for_offset(&lines, cursor, line_height) {
584            if at.y < scroll.y {
585                scroll.y = at.y;
586            } else if at.y + line_height > scroll.y + bounds.size.height {
587                scroll.y = at.y + line_height - bounds.size.height;
588            }
589            // The caret is the thing being kept in view, so it is its own width
590            // that has to clear the right edge — not the character before it.
591            if at.x < scroll.x {
592                scroll.x = at.x;
593            } else if at.x + caret_width > scroll.x + bounds.size.width {
594                scroll.x = at.x + caret_width - bounds.size.width;
595            }
596            scroll.x = scroll.x.clamp(px(0.), max.x);
597            scroll.y = scroll.y.clamp(px(0.), max.y);
598        }
599        self.field.update(cx, |field, _| {
600            field.scroll = scroll;
601            field.follow_caret = false;
602            field.last_caret_shape = caret_shape;
603        });
604        let origin = bounds.origin - scroll;
605
606        let matches = if is_placeholder {
607            Vec::new()
608        } else {
609            matches
610                .iter()
611                .flat_map(|range| selection_rows(&lines, range, line_height))
612                .map(|rect| {
613                    fill(
614                        Bounds::new(origin + rect.origin, rect.size),
615                        theme.warning.opacity(0.25),
616                    )
617                })
618                .collect()
619        };
620
621        let caret_shown = caret_shape.shown(!hollow, crate::input::caret::inactive_caret(cx));
622        let (selection, cursor) = if selected_range.is_empty() {
623            let at = position_for_offset(&lines, cursor, line_height).unwrap_or_default();
624            (
625                Vec::new(),
626                caret_shown.then(|| {
627                    caret_shape.quad(
628                        // The font's size rather than the line's: leading is not
629                        // a bar's or an underline's to fill. A block fills it.
630                        Bounds::new(
631                            origin + at + gpui::point(px(0.), (line_height - font_size) / 2.),
632                            gpui::size(CARET_WIDTH, font_size),
633                        ),
634                        line_height,
635                        caret_height,
636                        advance.unwrap_or_default(),
637                        theme.caret,
638                        hollow,
639                    )
640                }),
641            )
642        } else {
643            (
644                selection_rows(&lines, &selected_range, line_height)
645                    .into_iter()
646                    .map(|rect| {
647                        fill(
648                            Bounds::new(origin + rect.origin, rect.size),
649                            theme.selection,
650                        )
651                    })
652                    .collect(),
653                None,
654            )
655        };
656
657        FieldPrepaint {
658            lines,
659            shown,
660            glyphs: chipped.slots,
661            glyph_color: theme.text_muted,
662            font_size,
663            origin,
664            cursor,
665            matches,
666            selection,
667        }
668    }
669
670    fn paint(
671        &mut self,
672        _id: Option<&GlobalElementId>,
673        _inspector_id: Option<&gpui::InspectorElementId>,
674        bounds: Bounds<Pixels>,
675        _request_layout: &mut Self::RequestLayoutState,
676        prepaint: &mut Self::PrepaintState,
677        window: &mut Window,
678        cx: &mut App,
679    ) {
680        let focus_handle = self.field.read(cx).focus_handle.clone();
681        let caret_on = self.field.read(cx).caret_on;
682        window.handle_input(
683            &focus_handle,
684            ElementInputHandler::new(bounds, self.field.clone()),
685            cx,
686        );
687        let line_height = self.field.read(cx).line_height();
688        // A drag that leaves the box is still a drag. `on_mouse_move` on the
689        // field's own div fires only while the box is the thing under the
690        // pointer, so a run dragged past the edge froze at the last character
691        // inside it — and the last line of a full box was unreachable, since
692        // reaching it means passing the edge. This is the window's own move,
693        // which arrives wherever the pointer went.
694        //
695        // Registered every frame because that is the contract: the listener is
696        // cleared with the frame that installed it.
697        let dragged = self.field.clone();
698        window.on_mouse_event(move |event: &MouseMoveEvent, phase, _window, cx| {
699            // The button being down is what makes this a drag. `selecting`
700            // is only cleared on the release, so a press whose release went
701            // somewhere we never heard about would otherwise leave a plain
702            // hover dragging the run around.
703            if phase != DispatchPhase::Bubble || !event.dragging() {
704                return;
705            }
706            dragged.update(cx, |field, cx| {
707                field.drag_to(event.position, line_height, cx);
708            });
709        });
710        let lines = std::mem::take(&mut prepaint.lines);
711        let matches = std::mem::take(&mut prepaint.matches);
712        let selection = std::mem::take(&mut prepaint.selection);
713        let cursor = prepaint.cursor.take();
714        let origin = prepaint.origin;
715
716        // Scrolled text runs past the box in both directions, so everything the
717        // field draws is masked to it — text, selection and caret alike.
718        window.with_content_mask(Some(gpui::ContentMask::new(bounds)), |window| {
719            for quad in matches.into_iter().chain(selection) {
720                window.paint_quad(quad);
721            }
722
723            // The caret only exists while focused — an unfocused field showing
724            // one reads as two cursors on screen. Under the text, so a glyph
725            // cut out of a block lands on top of it.
726            if focus_handle.is_focused(window)
727                && caret_on
728                && let Some(cursor) = cursor
729            {
730                window.paint_quad(cursor);
731            }
732
733            let mut top = origin;
734            for line in &lines {
735                line.paint(top, line_height, gpui::TextAlign::Left, None, window, cx)
736                    .ok();
737                top.y += line.size(line_height).height;
738            }
739
740            for (slot, glyph) in &prepaint.glyphs {
741                let Some(data) = glyph.data() else { continue };
742                let (Some(start), Some(end)) = (
743                    position_for_offset(&lines, slot.start, line_height),
744                    position_for_offset(&lines, slot.end, line_height),
745                ) else {
746                    continue;
747                };
748                let side = (end.x - start.x).min(prepaint.font_size);
749                let bounds = Bounds::new(
750                    origin + start + gpui::point(px(0.), (line_height - side) / 2.),
751                    gpui::size(side, side),
752                );
753                let path = SharedString::from(format!("field-glyph-{:p}", data.as_ptr()));
754                window
755                    .paint_svg(
756                        bounds,
757                        path,
758                        Some(data),
759                        gpui::TransformationMatrix::unit(),
760                        prepaint.glyph_color,
761                        cx,
762                    )
763                    .ok();
764            }
765        });
766
767        let shown = std::mem::take(&mut prepaint.shown);
768        self.field.update(cx, |field, _| {
769            field.last_layout = lines;
770            field.last_shown = shown;
771            field.last_bounds = Some(bounds);
772        });
773    }
774}