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