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 = text_style
344            .line_height
345            .to_pixels(font_size.into(), window.rem_size());
346
347        let runs = if let Some(runs) = runs {
348            runs
349        } else {
350            vec![text_style.to_run(text.len())]
351        };
352        window.request_measured_layout(Default::default(), {
353            let element_state = self.clone();
354
355            move |known_dimensions, available_space, window, cx| {
356                let wrap_width = if text_style.white_space == WhiteSpace::Normal {
357                    known_dimensions.width.or(match available_space.width {
358                        crate::AvailableSpace::Definite(x) => Some(x),
359                        _ => None,
360                    })
361                } else {
362                    None
363                };
364
365                let (truncate_width, truncation_affix, truncate_from) =
366                    if let Some(text_overflow) = text_style.text_overflow.clone() {
367                        let width = known_dimensions.width.or(match available_space.width {
368                            crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
369                                Some(max_lines) => Some(x * max_lines),
370                                None => Some(x),
371                            },
372                            _ => None,
373                        });
374
375                        match text_overflow {
376                            TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
377                            TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
378                        }
379                    } else {
380                        (None, "".into(), TruncateFrom::End)
381                    };
382
383                // Only use cached layout if:
384                // 1. We have a cached size
385                // 2. wrap_width matches (or both are None)
386                // 3. truncate_width is None (if truncate_width is Some, we need to re-layout
387                //    because the previous layout may have been computed without truncation)
388                if let Some(text_layout) = element_state.0.borrow().as_ref()
389                    && let Some(size) = text_layout.size
390                    && (wrap_width.is_none() || wrap_width == text_layout.wrap_width)
391                    && truncate_width.is_none()
392                {
393                    return size;
394                }
395
396                let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
397                let (text, runs) = if let Some(truncate_width) = truncate_width {
398                    line_wrapper.truncate_line(
399                        text.clone(),
400                        truncate_width,
401                        &truncation_affix,
402                        &runs,
403                        truncate_from,
404                    )
405                } else {
406                    (text.clone(), Cow::Borrowed(&*runs))
407                };
408                let len = text.len();
409
410                let Some(lines) = window
411                    .text_system()
412                    .shape_text(
413                        text,
414                        font_size,
415                        &runs,
416                        wrap_width,            // Wrap if we know the width.
417                        text_style.line_clamp, // Limit the number of lines if line_clamp is set.
418                    )
419                    .log_err()
420                else {
421                    element_state.0.borrow_mut().replace(TextLayoutInner {
422                        lines: Default::default(),
423                        len: 0,
424                        line_height,
425                        wrap_width,
426                        size: Some(Size::default()),
427                        bounds: None,
428                    });
429                    return Size::default();
430                };
431
432                let mut size: Size<Pixels> = Size::default();
433                for line in &lines {
434                    let line_size = line.size(line_height);
435                    size.height += line_size.height;
436                    size.width = size.width.max(line_size.width).ceil();
437                }
438
439                element_state.0.borrow_mut().replace(TextLayoutInner {
440                    lines,
441                    len,
442                    line_height,
443                    wrap_width,
444                    size: Some(size),
445                    bounds: None,
446                });
447
448                size
449            }
450        })
451    }
452
453    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
454        let mut element_state = self.0.borrow_mut();
455        let element_state = element_state
456            .as_mut()
457            .with_context(|| format!("measurement has not been performed on {text}"))
458            .unwrap();
459        element_state.bounds = Some(bounds);
460    }
461
462    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
463        let element_state = self.0.borrow();
464        let element_state = element_state
465            .as_ref()
466            .with_context(|| format!("measurement has not been performed on {text}"))
467            .unwrap();
468        let bounds = element_state
469            .bounds
470            .with_context(|| format!("prepaint has not been performed on {text}"))
471            .unwrap();
472
473        let line_height = element_state.line_height;
474        let mut line_origin = bounds.origin;
475        let text_style = window.text_style();
476        for line in &element_state.lines {
477            line.paint_background(
478                line_origin,
479                line_height,
480                text_style.text_align,
481                Some(bounds),
482                window,
483                cx,
484            )
485            .log_err();
486            line.paint(
487                line_origin,
488                line_height,
489                text_style.text_align,
490                Some(bounds),
491                window,
492                cx,
493            )
494            .log_err();
495            line_origin.y += line.size(line_height).height;
496        }
497    }
498
499    /// Get the byte index into the input of the pixel position.
500    pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
501        let element_state = self.0.borrow();
502        let element_state = element_state
503            .as_ref()
504            .expect("measurement has not been performed");
505        let bounds = element_state
506            .bounds
507            .expect("prepaint has not been performed");
508
509        if position.y < bounds.top() {
510            return Err(0);
511        }
512
513        let line_height = element_state.line_height;
514        let mut line_origin = bounds.origin;
515        let mut line_start_ix = 0;
516        for line in &element_state.lines {
517            let line_bottom = line_origin.y + line.size(line_height).height;
518            if position.y > line_bottom {
519                line_origin.y = line_bottom;
520                line_start_ix += line.len() + 1;
521            } else {
522                let position_within_line = position - line_origin;
523                match line.index_for_position(position_within_line, line_height) {
524                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
525                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
526                }
527            }
528        }
529
530        Err(line_start_ix.saturating_sub(1))
531    }
532
533    /// Get the pixel position for the given byte index.
534    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
535        let element_state = self.0.borrow();
536        let element_state = element_state
537            .as_ref()
538            .expect("measurement has not been performed");
539        let bounds = element_state
540            .bounds
541            .expect("prepaint has not been performed");
542        let line_height = element_state.line_height;
543
544        let mut line_origin = bounds.origin;
545        let mut line_start_ix = 0;
546
547        for line in &element_state.lines {
548            let line_end_ix = line_start_ix + line.len();
549            if index < line_start_ix {
550                break;
551            } else if index > line_end_ix {
552                line_origin.y += line.size(line_height).height;
553                line_start_ix = line_end_ix + 1;
554                continue;
555            } else {
556                let ix_within_line = index - line_start_ix;
557                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
558            }
559        }
560
561        None
562    }
563
564    /// Retrieve the layout for the line containing the given byte index.
565    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
566        let element_state = self.0.borrow();
567        let element_state = element_state
568            .as_ref()
569            .expect("measurement has not been performed");
570        let bounds = element_state
571            .bounds
572            .expect("prepaint has not been performed");
573        let line_height = element_state.line_height;
574
575        let mut line_origin = bounds.origin;
576        let mut line_start_ix = 0;
577
578        for line in &element_state.lines {
579            let line_end_ix = line_start_ix + line.len();
580            if index < line_start_ix {
581                break;
582            } else if index > line_end_ix {
583                line_origin.y += line.size(line_height).height;
584                line_start_ix = line_end_ix + 1;
585                continue;
586            } else {
587                return Some(line.layout.clone());
588            }
589        }
590
591        None
592    }
593
594    /// The bounds of this layout.
595    pub fn bounds(&self) -> Bounds<Pixels> {
596        self.0.borrow().as_ref().unwrap().bounds.unwrap()
597    }
598
599    /// The line height for this layout.
600    pub fn line_height(&self) -> Pixels {
601        self.0.borrow().as_ref().unwrap().line_height
602    }
603
604    /// The UTF-8 length of the underlying text.
605    pub fn len(&self) -> usize {
606        self.0.borrow().as_ref().unwrap().len
607    }
608
609    /// The text for this layout.
610    pub fn text(&self) -> String {
611        self.0
612            .borrow()
613            .as_ref()
614            .unwrap()
615            .lines
616            .iter()
617            .map(|s| &s.text)
618            .join("\n")
619    }
620
621    /// The text for this layout (with soft-wraps as newlines)
622    pub fn wrapped_text(&self) -> String {
623        let mut accumulator = String::new();
624
625        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
626            let mut seen = 0;
627            for boundary in wrapped.layout.wrap_boundaries.iter() {
628                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
629                    [boundary.glyph_ix]
630                    .index;
631
632                accumulator.push_str(&wrapped.text[seen..index]);
633                accumulator.push('\n');
634                seen = index;
635            }
636            accumulator.push_str(&wrapped.text[seen..]);
637            accumulator.push('\n');
638        }
639        // Remove trailing newline
640        accumulator.pop();
641        accumulator
642    }
643}
644
645/// A text element that can be interacted with.
646pub struct InteractiveText {
647    element_id: ElementId,
648    text: StyledText,
649    click_listener:
650        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
651    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
652    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
653    tooltip_id: Option<TooltipId>,
654    clickable_ranges: Vec<Range<usize>>,
655}
656
657struct InteractiveTextClickEvent {
658    mouse_down_index: usize,
659    mouse_up_index: usize,
660}
661
662#[doc(hidden)]
663#[derive(Default)]
664pub struct InteractiveTextState {
665    mouse_down_index: Rc<Cell<Option<usize>>>,
666    hovered_index: Rc<Cell<Option<usize>>>,
667    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
668}
669
670/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
671impl InteractiveText {
672    /// Creates a new InteractiveText from the given text.
673    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
674        Self {
675            element_id: id.into(),
676            text,
677            click_listener: None,
678            hover_listener: None,
679            tooltip_builder: None,
680            tooltip_id: None,
681            clickable_ranges: Vec::new(),
682        }
683    }
684
685    /// on_click is called when the user clicks on one of the given ranges, passing the index of
686    /// the clicked range.
687    pub fn on_click(
688        mut self,
689        ranges: Vec<Range<usize>>,
690        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
691    ) -> Self {
692        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
693            for (range_ix, range) in ranges.iter().enumerate() {
694                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
695                {
696                    listener(range_ix, window, cx);
697                }
698            }
699        }));
700        self.clickable_ranges = ranges;
701        self
702    }
703
704    /// on_hover is called when the mouse moves over a character within the text, passing the
705    /// index of the hovered character, or None if the mouse leaves the text.
706    pub fn on_hover(
707        mut self,
708        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
709    ) -> Self {
710        self.hover_listener = Some(Box::new(listener));
711        self
712    }
713
714    /// tooltip lets you specify a tooltip for a given character index in the string.
715    pub fn tooltip(
716        mut self,
717        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
718    ) -> Self {
719        self.tooltip_builder = Some(Rc::new(builder));
720        self
721    }
722}
723
724impl Element for InteractiveText {
725    type RequestLayoutState = ();
726    type PrepaintState = Hitbox;
727
728    fn id(&self) -> Option<ElementId> {
729        Some(self.element_id.clone())
730    }
731
732    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
733        None
734    }
735
736    fn request_layout(
737        &mut self,
738        _id: Option<&GlobalElementId>,
739        inspector_id: Option<&InspectorElementId>,
740        window: &mut Window,
741        cx: &mut App,
742    ) -> (LayoutId, Self::RequestLayoutState) {
743        self.text.request_layout(None, inspector_id, window, cx)
744    }
745
746    fn prepaint(
747        &mut self,
748        global_id: Option<&GlobalElementId>,
749        inspector_id: Option<&InspectorElementId>,
750        bounds: Bounds<Pixels>,
751        state: &mut Self::RequestLayoutState,
752        window: &mut Window,
753        cx: &mut App,
754    ) -> Hitbox {
755        window.with_optional_element_state::<InteractiveTextState, _>(
756            global_id,
757            |interactive_state, window| {
758                let mut interactive_state = interactive_state
759                    .map(|interactive_state| interactive_state.unwrap_or_default());
760
761                if let Some(interactive_state) = interactive_state.as_mut() {
762                    if self.tooltip_builder.is_some() {
763                        self.tooltip_id =
764                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
765                    } else {
766                        // If there is no longer a tooltip builder, remove the active tooltip.
767                        interactive_state.active_tooltip.take();
768                    }
769                }
770
771                self.text
772                    .prepaint(None, inspector_id, bounds, state, window, cx);
773                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
774                (hitbox, interactive_state)
775            },
776        )
777    }
778
779    fn paint(
780        &mut self,
781        global_id: Option<&GlobalElementId>,
782        inspector_id: Option<&InspectorElementId>,
783        bounds: Bounds<Pixels>,
784        _: &mut Self::RequestLayoutState,
785        hitbox: &mut Hitbox,
786        window: &mut Window,
787        cx: &mut App,
788    ) {
789        let current_view = window.current_view();
790        let text_layout = self.text.layout().clone();
791        window.with_element_state::<InteractiveTextState, _>(
792            global_id.unwrap(),
793            |interactive_state, window| {
794                let mut interactive_state = interactive_state.unwrap_or_default();
795                if let Some(click_listener) = self.click_listener.take() {
796                    let mouse_position = window.mouse_position();
797                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
798                        && self
799                            .clickable_ranges
800                            .iter()
801                            .any(|range| range.contains(&ix))
802                    {
803                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
804                    }
805
806                    let text_layout = text_layout.clone();
807                    let mouse_down = interactive_state.mouse_down_index.clone();
808                    if let Some(mouse_down_index) = mouse_down.get() {
809                        let hitbox = hitbox.clone();
810                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
811                        window.on_mouse_event(
812                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
813                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
814                                    if let Ok(mouse_up_index) =
815                                        text_layout.index_for_position(event.position)
816                                    {
817                                        click_listener(
818                                            &clickable_ranges,
819                                            InteractiveTextClickEvent {
820                                                mouse_down_index,
821                                                mouse_up_index,
822                                            },
823                                            window,
824                                            cx,
825                                        )
826                                    }
827
828                                    mouse_down.take();
829                                    window.refresh();
830                                }
831                            },
832                        );
833                    } else {
834                        let hitbox = hitbox.clone();
835                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
836                            if phase == DispatchPhase::Bubble
837                                && hitbox.is_hovered(window)
838                                && let Ok(mouse_down_index) =
839                                    text_layout.index_for_position(event.position)
840                            {
841                                mouse_down.set(Some(mouse_down_index));
842                                window.refresh();
843                            }
844                        });
845                    }
846                }
847
848                window.on_mouse_event({
849                    let mut hover_listener = self.hover_listener.take();
850                    let hitbox = hitbox.clone();
851                    let text_layout = text_layout.clone();
852                    let hovered_index = interactive_state.hovered_index.clone();
853                    move |event: &MouseMoveEvent, phase, window, cx| {
854                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
855                            let current = hovered_index.get();
856                            let updated = text_layout.index_for_position(event.position).ok();
857                            if current != updated {
858                                hovered_index.set(updated);
859                                if let Some(hover_listener) = hover_listener.as_ref() {
860                                    hover_listener(updated, event.clone(), window, cx);
861                                }
862                                cx.notify(current_view);
863                            }
864                        }
865                    }
866                });
867
868                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
869                    let active_tooltip = interactive_state.active_tooltip.clone();
870                    let build_tooltip = Rc::new({
871                        let tooltip_is_hoverable = false;
872                        let text_layout = text_layout.clone();
873                        move |window: &mut Window, cx: &mut App| {
874                            text_layout
875                                .index_for_position(window.mouse_position())
876                                .ok()
877                                .and_then(|position| tooltip_builder(position, window, cx))
878                                .map(|view| (view, tooltip_is_hoverable))
879                        }
880                    });
881
882                    // Use bounds instead of testing hitbox since this is called during prepaint.
883                    let check_is_hovered_during_prepaint = Rc::new({
884                        let source_bounds = hitbox.bounds;
885                        let text_layout = text_layout.clone();
886                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
887                        move |window: &Window| {
888                            text_layout
889                                .index_for_position(window.mouse_position())
890                                .is_ok()
891                                && source_bounds.contains(&window.mouse_position())
892                                && pending_mouse_down.get().is_none()
893                        }
894                    });
895
896                    let check_is_hovered = Rc::new({
897                        let hitbox = hitbox.clone();
898                        let text_layout = text_layout.clone();
899                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
900                        move |window: &Window| {
901                            text_layout
902                                .index_for_position(window.mouse_position())
903                                .is_ok()
904                                && hitbox.is_hovered(window)
905                                && pending_mouse_down.get().is_none()
906                        }
907                    });
908
909                    register_tooltip_mouse_handlers(
910                        &active_tooltip,
911                        self.tooltip_id,
912                        build_tooltip,
913                        check_is_hovered,
914                        check_is_hovered_during_prepaint,
915                        window,
916                    );
917                }
918
919                self.text
920                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
921
922                ((), interactive_state)
923            },
924        );
925    }
926}
927
928impl IntoElement for InteractiveText {
929    type Element = Self;
930
931    fn into_element(self) -> Self::Element {
932        self
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    #[test]
939    fn test_into_element_for() {
940        use crate::{ParentElement as _, SharedString, div};
941        use std::borrow::Cow;
942
943        let _ = div().child("static str");
944        let _ = div().child("String".to_string());
945        let _ = div().child(Cow::Borrowed("Cow"));
946        let _ = div().child(SharedString::from("SharedString"));
947    }
948}