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