text.rs

  1use crate::{
  2    ActiveTooltip, AnyView, App, Bounds, DispatchPhase, Element, ElementId, GlobalElementId,
  3    HighlightStyle, Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId,
  4    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, Size, TextOverflow,
  5    TextRun, TextStyle, TooltipId, TruncateFrom, WhiteSpace, Window, WrappedLine,
  6    WrappedLineLayout, register_tooltip_mouse_handlers, set_tooltip_on_window,
  7};
  8use anyhow::Context as _;
  9use gpui_util::ResultExt;
 10use itertools::Itertools;
 11use smallvec::SmallVec;
 12use std::{
 13    borrow::Cow,
 14    cell::{Cell, RefCell},
 15    mem,
 16    ops::Range,
 17    rc::Rc,
 18    sync::Arc,
 19};
 20
 21impl Element for &'static str {
 22    type RequestLayoutState = TextLayout;
 23    type PrepaintState = ();
 24
 25    fn id(&self) -> Option<ElementId> {
 26        None
 27    }
 28
 29    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 30        None
 31    }
 32
 33    fn request_layout(
 34        &mut self,
 35        _id: Option<&GlobalElementId>,
 36        _inspector_id: Option<&InspectorElementId>,
 37        window: &mut Window,
 38        cx: &mut App,
 39    ) -> (LayoutId, Self::RequestLayoutState) {
 40        let mut state = TextLayout::default();
 41        let layout_id = state.layout(SharedString::from(*self), None, window, cx);
 42        (layout_id, state)
 43    }
 44
 45    fn prepaint(
 46        &mut self,
 47        _id: Option<&GlobalElementId>,
 48        _inspector_id: Option<&InspectorElementId>,
 49        bounds: Bounds<Pixels>,
 50        text_layout: &mut Self::RequestLayoutState,
 51        _window: &mut Window,
 52        _cx: &mut App,
 53    ) {
 54        text_layout.prepaint(bounds, self)
 55    }
 56
 57    fn paint(
 58        &mut self,
 59        _id: Option<&GlobalElementId>,
 60        _inspector_id: Option<&InspectorElementId>,
 61        _bounds: Bounds<Pixels>,
 62        text_layout: &mut TextLayout,
 63        _: &mut (),
 64        window: &mut Window,
 65        cx: &mut App,
 66    ) {
 67        text_layout.paint(self, window, cx)
 68    }
 69}
 70
 71impl IntoElement for &'static str {
 72    type Element = Self;
 73
 74    fn into_element(self) -> Self::Element {
 75        self
 76    }
 77}
 78
 79impl IntoElement for String {
 80    type Element = SharedString;
 81
 82    fn into_element(self) -> Self::Element {
 83        self.into()
 84    }
 85}
 86
 87impl IntoElement for Cow<'static, str> {
 88    type Element = SharedString;
 89
 90    fn into_element(self) -> Self::Element {
 91        self.into()
 92    }
 93}
 94
 95impl Element for SharedString {
 96    type RequestLayoutState = TextLayout;
 97    type PrepaintState = ();
 98
 99    fn id(&self) -> Option<ElementId> {
100        None
101    }
102
103    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
104        None
105    }
106
107    fn request_layout(
108        &mut self,
109        _id: Option<&GlobalElementId>,
110        _inspector_id: Option<&InspectorElementId>,
111        window: &mut Window,
112        cx: &mut App,
113    ) -> (LayoutId, Self::RequestLayoutState) {
114        let mut state = TextLayout::default();
115        let layout_id = state.layout(self.clone(), None, window, cx);
116        (layout_id, state)
117    }
118
119    fn prepaint(
120        &mut self,
121        _id: Option<&GlobalElementId>,
122        _inspector_id: Option<&InspectorElementId>,
123        bounds: Bounds<Pixels>,
124        text_layout: &mut Self::RequestLayoutState,
125        _window: &mut Window,
126        _cx: &mut App,
127    ) {
128        text_layout.prepaint(bounds, self.as_ref())
129    }
130
131    fn paint(
132        &mut self,
133        _id: Option<&GlobalElementId>,
134        _inspector_id: Option<&InspectorElementId>,
135        _bounds: Bounds<Pixels>,
136        text_layout: &mut Self::RequestLayoutState,
137        _: &mut Self::PrepaintState,
138        window: &mut Window,
139        cx: &mut App,
140    ) {
141        text_layout.paint(self.as_ref(), window, cx)
142    }
143}
144
145impl IntoElement for SharedString {
146    type Element = Self;
147
148    fn into_element(self) -> Self::Element {
149        self
150    }
151}
152
153/// Renders text with runs of different styles.
154///
155/// Callers are responsible for setting the correct style for each run.
156/// For text with a uniform style, you can usually avoid calling this constructor
157/// and just pass text directly.
158pub struct StyledText {
159    text: SharedString,
160    runs: Option<Vec<TextRun>>,
161    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
162    layout: TextLayout,
163}
164
165impl StyledText {
166    /// Construct a new styled text element from the given string.
167    pub fn new(text: impl Into<SharedString>) -> Self {
168        StyledText {
169            text: text.into(),
170            runs: None,
171            delayed_highlights: None,
172            layout: TextLayout::default(),
173        }
174    }
175
176    /// Get the layout for this element. This can be used to map indices to pixels and vice versa.
177    pub fn layout(&self) -> &TextLayout {
178        &self.layout
179    }
180
181    /// Set the styling attributes for the given text, as well as
182    /// as any ranges of text that have had their style customized.
183    pub fn with_default_highlights(
184        mut self,
185        default_style: &TextStyle,
186        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
187    ) -> Self {
188        debug_assert!(
189            self.delayed_highlights.is_none(),
190            "Can't use `with_default_highlights` and `with_highlights`"
191        );
192        let runs = Self::compute_runs(&self.text, default_style, highlights);
193        self.with_runs(runs)
194    }
195
196    /// Set the styling attributes for the given text, as well as
197    /// as any ranges of text that have had their style customized.
198    pub fn with_highlights(
199        mut self,
200        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
201    ) -> Self {
202        debug_assert!(
203            self.runs.is_none(),
204            "Can't use `with_highlights` and `with_default_highlights`"
205        );
206        self.delayed_highlights = Some(
207            highlights
208                .into_iter()
209                .inspect(|(run, _)| {
210                    debug_assert!(self.text.is_char_boundary(run.start));
211                    debug_assert!(self.text.is_char_boundary(run.end));
212                })
213                .collect::<Vec<_>>(),
214        );
215        self
216    }
217
218    fn compute_runs(
219        text: &str,
220        default_style: &TextStyle,
221        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
222    ) -> Vec<TextRun> {
223        let mut runs = Vec::new();
224        let mut ix = 0;
225        for (range, highlight) in highlights {
226            if ix < range.start {
227                debug_assert!(text.is_char_boundary(range.start));
228                runs.push(default_style.clone().to_run(range.start - ix));
229            }
230            debug_assert!(text.is_char_boundary(range.end));
231            runs.push(
232                default_style
233                    .clone()
234                    .highlight(highlight)
235                    .to_run(range.len()),
236            );
237            ix = range.end;
238        }
239        if ix < text.len() {
240            runs.push(default_style.to_run(text.len() - ix));
241        }
242        runs
243    }
244
245    /// Set the text runs for this piece of text.
246    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
247        let mut text = &**self.text;
248        for run in &runs {
249            text = text.get(run.len..).expect("invalid text run");
250        }
251        assert!(text.is_empty(), "invalid text run");
252        self.runs = Some(runs);
253        self
254    }
255}
256
257impl Element for StyledText {
258    type RequestLayoutState = ();
259    type PrepaintState = ();
260
261    fn id(&self) -> Option<ElementId> {
262        None
263    }
264
265    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
266        None
267    }
268
269    fn request_layout(
270        &mut self,
271        _id: Option<&GlobalElementId>,
272        _inspector_id: Option<&InspectorElementId>,
273        window: &mut Window,
274        cx: &mut App,
275    ) -> (LayoutId, Self::RequestLayoutState) {
276        let runs = self.runs.take().or_else(|| {
277            self.delayed_highlights.take().map(|delayed_highlights| {
278                Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
279            })
280        });
281
282        let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
283        (layout_id, ())
284    }
285
286    fn prepaint(
287        &mut self,
288        _id: Option<&GlobalElementId>,
289        _inspector_id: Option<&InspectorElementId>,
290        bounds: Bounds<Pixels>,
291        _: &mut Self::RequestLayoutState,
292        _window: &mut Window,
293        _cx: &mut App,
294    ) {
295        self.layout.prepaint(bounds, &self.text)
296    }
297
298    fn paint(
299        &mut self,
300        _id: Option<&GlobalElementId>,
301        _inspector_id: Option<&InspectorElementId>,
302        _bounds: Bounds<Pixels>,
303        _: &mut Self::RequestLayoutState,
304        _: &mut Self::PrepaintState,
305        window: &mut Window,
306        cx: &mut App,
307    ) {
308        self.layout.paint(&self.text, window, cx)
309    }
310}
311
312impl IntoElement for StyledText {
313    type Element = Self;
314
315    fn into_element(self) -> Self::Element {
316        self
317    }
318}
319
320/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
321#[derive(Default, Clone)]
322pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);
323
324struct TextLayoutInner {
325    len: usize,
326    lines: SmallVec<[WrappedLine; 1]>,
327    line_height: Pixels,
328    wrap_width: Option<Pixels>,
329    size: Option<Size<Pixels>>,
330    bounds: Option<Bounds<Pixels>>,
331}
332
333impl TextLayout {
334    fn layout(
335        &self,
336        text: SharedString,
337        runs: Option<Vec<TextRun>>,
338        window: &mut Window,
339        _: &mut App,
340    ) -> LayoutId {
341        let text_style = window.text_style();
342        let font_size = text_style.font_size.to_pixels(window.rem_size());
343        let line_height = window.round_to_nearest_device_pixel(
344            text_style
345                .line_height
346                .to_pixels(font_size.into(), window.rem_size()),
347        );
348
349        let runs = if let Some(runs) = runs {
350            runs
351        } else {
352            vec![text_style.to_run(text.len())]
353        };
354        window.request_measured_layout(Default::default(), {
355            let element_state = self.clone();
356
357            move |known_dimensions, available_space, window, cx| {
358                let wrap_width = if text_style.white_space == WhiteSpace::Normal {
359                    known_dimensions.width.or(match available_space.width {
360                        crate::AvailableSpace::Definite(x) => Some(x),
361                        _ => None,
362                    })
363                } else {
364                    None
365                };
366
367                let (truncate_width, truncation_affix, truncate_from) =
368                    if let Some(text_overflow) = text_style.text_overflow.clone() {
369                        let width = known_dimensions.width.or(match available_space.width {
370                            crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
371                                Some(max_lines) => Some(x * max_lines),
372                                None => Some(x),
373                            },
374                            _ => None,
375                        });
376
377                        match text_overflow {
378                            TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
379                            TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
380                        }
381                    } else {
382                        (None, "".into(), TruncateFrom::End)
383                    };
384
385                // Only use cached layout if:
386                // 1. We have a cached size
387                // 2. wrap_width matches (or both are None)
388                // 3. truncate_width is None (if truncate_width is Some, we need to re-layout
389                //    because the previous layout may have been computed without truncation)
390                if let Some(text_layout) = element_state.0.borrow().as_ref()
391                    && let Some(size) = text_layout.size
392                    && (wrap_width.is_none() || wrap_width == text_layout.wrap_width)
393                    && truncate_width.is_none()
394                {
395                    return size;
396                }
397
398                let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
399                let (text, runs) = if let Some(truncate_width) = truncate_width {
400                    line_wrapper.truncate_line(
401                        text.clone(),
402                        truncate_width,
403                        &truncation_affix,
404                        &runs,
405                        truncate_from,
406                    )
407                } else {
408                    (text.clone(), Cow::Borrowed(&*runs))
409                };
410                let len = text.len();
411
412                let Some(lines) = window
413                    .text_system()
414                    .shape_text(
415                        text,
416                        font_size,
417                        &runs,
418                        wrap_width,            // Wrap if we know the width.
419                        text_style.line_clamp, // Limit the number of lines if line_clamp is set.
420                    )
421                    .log_err()
422                else {
423                    element_state.0.borrow_mut().replace(TextLayoutInner {
424                        lines: Default::default(),
425                        len: 0,
426                        line_height,
427                        wrap_width,
428                        size: Some(Size::default()),
429                        bounds: None,
430                    });
431                    return Size::default();
432                };
433
434                let mut size: Size<Pixels> = Size::default();
435                for line in &lines {
436                    let line_size = line.size(line_height);
437                    size.height += line_size.height;
438                    size.width = size.width.max(line_size.width).ceil();
439                }
440
441                element_state.0.borrow_mut().replace(TextLayoutInner {
442                    lines,
443                    len,
444                    line_height,
445                    wrap_width,
446                    size: Some(size),
447                    bounds: None,
448                });
449
450                size
451            }
452        })
453    }
454
455    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
456        let mut element_state = self.0.borrow_mut();
457        let element_state = element_state
458            .as_mut()
459            .with_context(|| format!("measurement has not been performed on {text}"))
460            .unwrap();
461        element_state.bounds = Some(bounds);
462    }
463
464    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
465        let element_state = self.0.borrow();
466        let element_state = element_state
467            .as_ref()
468            .with_context(|| format!("measurement has not been performed on {text}"))
469            .unwrap();
470        let bounds = element_state
471            .bounds
472            .with_context(|| format!("prepaint has not been performed on {text}"))
473            .unwrap();
474
475        let line_height = element_state.line_height;
476        let mut line_origin = bounds.origin;
477        let text_style = window.text_style();
478        for line in &element_state.lines {
479            line.paint_background(
480                line_origin,
481                line_height,
482                text_style.text_align,
483                Some(bounds),
484                window,
485                cx,
486            )
487            .log_err();
488            line.paint(
489                line_origin,
490                line_height,
491                text_style.text_align,
492                Some(bounds),
493                window,
494                cx,
495            )
496            .log_err();
497            line_origin.y += line.size(line_height).height;
498        }
499    }
500
501    /// Get the byte index into the input of the pixel position.
502    pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
503        let element_state = self.0.borrow();
504        let element_state = element_state
505            .as_ref()
506            .expect("measurement has not been performed");
507        let bounds = element_state
508            .bounds
509            .expect("prepaint has not been performed");
510
511        if position.y < bounds.top() {
512            return Err(0);
513        }
514
515        let line_height = element_state.line_height;
516        let mut line_origin = bounds.origin;
517        let mut line_start_ix = 0;
518        for line in &element_state.lines {
519            let line_bottom = line_origin.y + line.size(line_height).height;
520            if position.y > line_bottom {
521                line_origin.y = line_bottom;
522                line_start_ix += line.len() + 1;
523            } else {
524                let position_within_line = position - line_origin;
525                match line.index_for_position(position_within_line, line_height) {
526                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
527                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
528                }
529            }
530        }
531
532        Err(line_start_ix.saturating_sub(1))
533    }
534
535    /// Get the pixel position for the given byte index.
536    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
537        let element_state = self.0.borrow();
538        let element_state = element_state
539            .as_ref()
540            .expect("measurement has not been performed");
541        let bounds = element_state
542            .bounds
543            .expect("prepaint has not been performed");
544        let line_height = element_state.line_height;
545
546        let mut line_origin = bounds.origin;
547        let mut line_start_ix = 0;
548
549        for line in &element_state.lines {
550            let line_end_ix = line_start_ix + line.len();
551            if index < line_start_ix {
552                break;
553            } else if index > line_end_ix {
554                line_origin.y += line.size(line_height).height;
555                line_start_ix = line_end_ix + 1;
556                continue;
557            } else {
558                let ix_within_line = index - line_start_ix;
559                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
560            }
561        }
562
563        None
564    }
565
566    /// Retrieve the layout for the line containing the given byte index.
567    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
568        let element_state = self.0.borrow();
569        let element_state = element_state
570            .as_ref()
571            .expect("measurement has not been performed");
572        let bounds = element_state
573            .bounds
574            .expect("prepaint has not been performed");
575        let line_height = element_state.line_height;
576
577        let mut line_origin = bounds.origin;
578        let mut line_start_ix = 0;
579
580        for line in &element_state.lines {
581            let line_end_ix = line_start_ix + line.len();
582            if index < line_start_ix {
583                break;
584            } else if index > line_end_ix {
585                line_origin.y += line.size(line_height).height;
586                line_start_ix = line_end_ix + 1;
587                continue;
588            } else {
589                return Some(line.layout.clone());
590            }
591        }
592
593        None
594    }
595
596    /// The bounds of this layout.
597    pub fn bounds(&self) -> Bounds<Pixels> {
598        self.0.borrow().as_ref().unwrap().bounds.unwrap()
599    }
600
601    /// The line height for this layout.
602    pub fn line_height(&self) -> Pixels {
603        self.0.borrow().as_ref().unwrap().line_height
604    }
605
606    /// The UTF-8 length of the underlying text.
607    pub fn len(&self) -> usize {
608        self.0.borrow().as_ref().unwrap().len
609    }
610
611    /// The text for this layout.
612    pub fn text(&self) -> String {
613        self.0
614            .borrow()
615            .as_ref()
616            .unwrap()
617            .lines
618            .iter()
619            .map(|s| &s.text)
620            .join("\n")
621    }
622
623    /// The text for this layout (with soft-wraps as newlines)
624    pub fn wrapped_text(&self) -> String {
625        let mut accumulator = String::new();
626
627        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
628            let mut seen = 0;
629            for boundary in wrapped.layout.wrap_boundaries.iter() {
630                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
631                    [boundary.glyph_ix]
632                    .index;
633
634                accumulator.push_str(&wrapped.text[seen..index]);
635                accumulator.push('\n');
636                seen = index;
637            }
638            accumulator.push_str(&wrapped.text[seen..]);
639            accumulator.push('\n');
640        }
641        // Remove trailing newline
642        accumulator.pop();
643        accumulator
644    }
645}
646
647/// A text element that can be interacted with.
648pub struct InteractiveText {
649    element_id: ElementId,
650    text: StyledText,
651    click_listener:
652        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
653    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
654    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
655    tooltip_id: Option<TooltipId>,
656    clickable_ranges: Vec<Range<usize>>,
657}
658
659struct InteractiveTextClickEvent {
660    mouse_down_index: usize,
661    mouse_up_index: usize,
662}
663
664#[doc(hidden)]
665#[derive(Default)]
666pub struct InteractiveTextState {
667    mouse_down_index: Rc<Cell<Option<usize>>>,
668    hovered_index: Rc<Cell<Option<usize>>>,
669    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
670}
671
672/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
673impl InteractiveText {
674    /// Creates a new InteractiveText from the given text.
675    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
676        Self {
677            element_id: id.into(),
678            text,
679            click_listener: None,
680            hover_listener: None,
681            tooltip_builder: None,
682            tooltip_id: None,
683            clickable_ranges: Vec::new(),
684        }
685    }
686
687    /// on_click is called when the user clicks on one of the given ranges, passing the index of
688    /// the clicked range.
689    pub fn on_click(
690        mut self,
691        ranges: Vec<Range<usize>>,
692        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
693    ) -> Self {
694        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
695            for (range_ix, range) in ranges.iter().enumerate() {
696                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
697                {
698                    listener(range_ix, window, cx);
699                }
700            }
701        }));
702        self.clickable_ranges = ranges;
703        self
704    }
705
706    /// on_hover is called when the mouse moves over a character within the text, passing the
707    /// index of the hovered character, or None if the mouse leaves the text.
708    pub fn on_hover(
709        mut self,
710        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
711    ) -> Self {
712        self.hover_listener = Some(Box::new(listener));
713        self
714    }
715
716    /// tooltip lets you specify a tooltip for a given character index in the string.
717    pub fn tooltip(
718        mut self,
719        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
720    ) -> Self {
721        self.tooltip_builder = Some(Rc::new(builder));
722        self
723    }
724}
725
726impl Element for InteractiveText {
727    type RequestLayoutState = ();
728    type PrepaintState = Hitbox;
729
730    fn id(&self) -> Option<ElementId> {
731        Some(self.element_id.clone())
732    }
733
734    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
735        None
736    }
737
738    fn request_layout(
739        &mut self,
740        _id: Option<&GlobalElementId>,
741        inspector_id: Option<&InspectorElementId>,
742        window: &mut Window,
743        cx: &mut App,
744    ) -> (LayoutId, Self::RequestLayoutState) {
745        self.text.request_layout(None, inspector_id, window, cx)
746    }
747
748    fn prepaint(
749        &mut self,
750        global_id: Option<&GlobalElementId>,
751        inspector_id: Option<&InspectorElementId>,
752        bounds: Bounds<Pixels>,
753        state: &mut Self::RequestLayoutState,
754        window: &mut Window,
755        cx: &mut App,
756    ) -> Hitbox {
757        window.with_optional_element_state::<InteractiveTextState, _>(
758            global_id,
759            |interactive_state, window| {
760                let mut interactive_state = interactive_state
761                    .map(|interactive_state| interactive_state.unwrap_or_default());
762
763                if let Some(interactive_state) = interactive_state.as_mut() {
764                    if self.tooltip_builder.is_some() {
765                        self.tooltip_id =
766                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
767                    } else {
768                        // If there is no longer a tooltip builder, remove the active tooltip.
769                        interactive_state.active_tooltip.take();
770                    }
771                }
772
773                self.text
774                    .prepaint(None, inspector_id, bounds, state, window, cx);
775                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
776                (hitbox, interactive_state)
777            },
778        )
779    }
780
781    fn paint(
782        &mut self,
783        global_id: Option<&GlobalElementId>,
784        inspector_id: Option<&InspectorElementId>,
785        bounds: Bounds<Pixels>,
786        _: &mut Self::RequestLayoutState,
787        hitbox: &mut Hitbox,
788        window: &mut Window,
789        cx: &mut App,
790    ) {
791        let current_view = window.current_view();
792        let text_layout = self.text.layout().clone();
793        window.with_element_state::<InteractiveTextState, _>(
794            global_id.unwrap(),
795            |interactive_state, window| {
796                let mut interactive_state = interactive_state.unwrap_or_default();
797                if let Some(click_listener) = self.click_listener.take() {
798                    let mouse_position = window.mouse_position();
799                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
800                        && self
801                            .clickable_ranges
802                            .iter()
803                            .any(|range| range.contains(&ix))
804                    {
805                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
806                    }
807
808                    let text_layout = text_layout.clone();
809                    let mouse_down = interactive_state.mouse_down_index.clone();
810                    if let Some(mouse_down_index) = mouse_down.get() {
811                        let hitbox = hitbox.clone();
812                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
813                        window.on_mouse_event(
814                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
815                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
816                                    if let Ok(mouse_up_index) =
817                                        text_layout.index_for_position(event.position)
818                                    {
819                                        click_listener(
820                                            &clickable_ranges,
821                                            InteractiveTextClickEvent {
822                                                mouse_down_index,
823                                                mouse_up_index,
824                                            },
825                                            window,
826                                            cx,
827                                        )
828                                    }
829
830                                    mouse_down.take();
831                                    window.refresh();
832                                }
833                            },
834                        );
835                    } else {
836                        let hitbox = hitbox.clone();
837                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
838                            if phase == DispatchPhase::Bubble
839                                && hitbox.is_hovered(window)
840                                && let Ok(mouse_down_index) =
841                                    text_layout.index_for_position(event.position)
842                            {
843                                mouse_down.set(Some(mouse_down_index));
844                                window.refresh();
845                            }
846                        });
847                    }
848                }
849
850                window.on_mouse_event({
851                    let mut hover_listener = self.hover_listener.take();
852                    let hitbox = hitbox.clone();
853                    let text_layout = text_layout.clone();
854                    let hovered_index = interactive_state.hovered_index.clone();
855                    move |event: &MouseMoveEvent, phase, window, cx| {
856                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
857                            let current = hovered_index.get();
858                            let updated = text_layout.index_for_position(event.position).ok();
859                            if current != updated {
860                                hovered_index.set(updated);
861                                if let Some(hover_listener) = hover_listener.as_ref() {
862                                    hover_listener(updated, event.clone(), window, cx);
863                                }
864                                cx.notify(current_view);
865                            }
866                        }
867                    }
868                });
869
870                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
871                    let active_tooltip = interactive_state.active_tooltip.clone();
872                    let build_tooltip = Rc::new({
873                        let tooltip_is_hoverable = false;
874                        let text_layout = text_layout.clone();
875                        move |window: &mut Window, cx: &mut App| {
876                            text_layout
877                                .index_for_position(window.mouse_position())
878                                .ok()
879                                .and_then(|position| tooltip_builder(position, window, cx))
880                                .map(|view| (view, tooltip_is_hoverable))
881                        }
882                    });
883
884                    // Use bounds instead of testing hitbox since this is called during prepaint.
885                    let check_is_hovered_during_prepaint = Rc::new({
886                        let source_bounds = hitbox.bounds;
887                        let text_layout = text_layout.clone();
888                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
889                        move |window: &Window| {
890                            text_layout
891                                .index_for_position(window.mouse_position())
892                                .is_ok()
893                                && source_bounds.contains(&window.mouse_position())
894                                && pending_mouse_down.get().is_none()
895                        }
896                    });
897
898                    let check_is_hovered = Rc::new({
899                        let hitbox = hitbox.clone();
900                        let text_layout = text_layout.clone();
901                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
902                        move |window: &Window| {
903                            text_layout
904                                .index_for_position(window.mouse_position())
905                                .is_ok()
906                                && hitbox.is_hovered(window)
907                                && pending_mouse_down.get().is_none()
908                        }
909                    });
910
911                    register_tooltip_mouse_handlers(
912                        &active_tooltip,
913                        self.tooltip_id,
914                        build_tooltip,
915                        check_is_hovered,
916                        check_is_hovered_during_prepaint,
917                        window,
918                    );
919                }
920
921                self.text
922                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
923
924                ((), interactive_state)
925            },
926        );
927    }
928}
929
930impl IntoElement for InteractiveText {
931    type Element = Self;
932
933    fn into_element(self) -> Self::Element {
934        self
935    }
936}
937
938#[cfg(test)]
939mod tests {
940    #[test]
941    fn test_into_element_for() {
942        use crate::{ParentElement as _, SharedString, div};
943        use std::borrow::Cow;
944
945        let _ = div().child("static str");
946        let _ = div().child("String".to_string());
947        let _ = div().child(Cow::Borrowed("Cow"));
948        let _ = div().child(SharedString::from("SharedString"));
949    }
950}