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