Skip to main content

gpui/elements/
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::{Deref, DerefMut, Range},
17    rc::Rc,
18    sync::Arc,
19};
20
21/// An [`Element`] that renders text.
22///
23/// In general, [`Text`] objects should be created via the [`text`] macro:
24/// ```rust
25/// # use gpui::*;
26/// # fn render() -> impl IntoElement {
27/// div().child(text!("hello"))
28/// # }
29/// ```
30/// ## IDs and Accessibility
31///
32/// [`Text`] elements have an ID. This ID is primarily used to produce nodes in
33/// the accessibility tree, which allows the text to be visible to screen
34/// readers and other assistive technologies.
35///
36/// This ID is stable across frames. If the same text, with the same ID, is
37/// present in two consecutive frames, no updates are reported to the screen
38/// reader. If the text changes, but the ID stays the same, then the screen
39/// reader will be notified that a text node's content has changed. **However**,
40/// if the ID changes, then the screen reader will be notified that a node has
41/// been removed, and a new node has been added.
42///
43/// When using the [`text`] macro, each invocation of the macro will get a
44/// unique ID, derived from its position in the source code (filename, line, and
45/// column). For example:
46/// ```rust
47/// # use gpui::*;
48/// let x = text!("hello");
49/// let y = text!("hello");
50/// // not equal, because different `text!` invocations produced them
51/// assert_ne!(x.id(), y.id());
52///
53/// fn make_text(s: &str) -> Text { text!(s) }
54/// let x = make_text("hello");
55/// let y = make_text("hello");
56/// // equal, because the same `text!` invocation produced them
57/// assert_eq!(x.id(), y.id());
58/// ```
59/// When the contents of an invocation of [`text`] do not change, this
60/// distinction is less relevant (with the caveat that you still need to take
61/// care to ensure that duplicate IDs do not appear).
62///
63/// However, when a [`text`] invocation's argument *does* change, you should
64/// consider whether this change should be reported as a node "updating its
65/// contents", or an old node being destroyed and a new node being created.
66#[derive(Debug, Clone)]
67pub struct Text {
68    id: Option<ElementId>,
69    text: SharedString,
70}
71
72impl Text {
73    /// Create a new [`Text`] element with a specific ID.
74    ///
75    /// If you want a unique ID to be assigned automatically, use the [`text`]
76    /// macro. The docs for [`Text`] have more detail about choosing IDs.
77    #[inline]
78    pub const fn new(id: ElementId, text: SharedString) -> Self {
79        Self { id: Some(id), text }
80    }
81
82    /// Create a new [`Text`] element that is inaccessible to screen readers.
83    ///
84    /// In order for text to be accessible to screen readers, it must have an ID
85    /// provided. If you want text to be accessible, either use [`text`] to have
86    /// an ID automatically assigned, or use [`Text::new`] to manually assign an
87    /// ID.
88    ///
89    /// This function is intended for use inside custom UI components, where
90    /// accessible properties may be set on parent containers.
91    #[inline]
92    pub const fn new_inaccessible(text: SharedString) -> Self {
93        Self { id: None, text }
94    }
95
96    /// The ID of this [`Text`] element.
97    #[inline]
98    pub const fn id(&self) -> Option<&ElementId> {
99        self.id.as_ref()
100    }
101
102    /// Produce a new [`Text`] with the given `id`.
103    pub fn with_id(mut self, id: impl Into<ElementId>) -> Self {
104        self.id = Some(id.into());
105        self
106    }
107
108    /// The text that this [`Text`] element will display.
109    #[inline]
110    pub const fn text(&self) -> &SharedString {
111        &self.text
112    }
113}
114
115impl Deref for Text {
116    type Target = SharedString;
117    fn deref(&self) -> &Self::Target {
118        &self.text
119    }
120}
121
122impl DerefMut for Text {
123    fn deref_mut(&mut self) -> &mut Self::Target {
124        &mut self.text
125    }
126}
127
128/// Trivial hash function for the location information produced by the [`text`]
129/// macro. Not covered by semver guarantees. Performance is not particularly
130/// significant because it's only used on small strings in const contexts.
131#[doc(hidden)]
132pub const fn __hash_text_macro_location_unstable_do_not_use(s: &'static str) -> u64 {
133    const BASIS: u64 = 0xcbf29ce484222325;
134    const PRIME: u64 = 0x100000001b3;
135
136    let bytes = s.as_bytes();
137    let mut hash = BASIS;
138    let mut i = 0;
139    while i < bytes.len() {
140        hash ^= bytes[i] as u64;
141        hash = hash.wrapping_mul(PRIME);
142        i += 1;
143    }
144    hash
145}
146
147/// Create a new [`Text`] element.
148///
149/// ```rust
150/// # use gpui::*;
151/// let a = text!("hello");
152/// let b = text!(id = "farewell-message", "hello");
153///
154/// ```
155///
156/// Text created with this macro is *accessible*. The macro generates an ID
157/// based on the source location. See the docs for [`Text`] for a more in-depth
158/// explanation of the significance of the ID of a [`Text`] element.
159#[macro_export]
160macro_rules! text {
161    (id = $id:expr, $text:expr) => {{ $crate::Text::new($id.into(), $text.into()) }};
162    ($text:expr) => {{
163        const ID: &'static str = concat!(file!(), "/", line!(), ":", column!());
164        const HASH: u64 = $crate::__hash_text_macro_location_unstable_do_not_use(ID);
165        $crate::Text::new($crate::ElementId::Integer(HASH), $text.into())
166    }};
167}
168
169impl Element for Text {
170    type RequestLayoutState = TextLayout;
171    type PrepaintState = ();
172
173    fn id(&self) -> Option<ElementId> {
174        self.id.clone()
175    }
176
177    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
178        None
179    }
180
181    fn a11y_role(&self) -> Option<accesskit::Role> {
182        if self.id.is_some() {
183            Some(accesskit::Role::Label)
184        } else {
185            None
186        }
187    }
188
189    fn write_a11y_info(&self, node: &mut accesskit::Node) {
190        node.set_value(self.text.to_string());
191    }
192
193    fn request_layout(
194        &mut self,
195        id: Option<&GlobalElementId>,
196        inspector_id: Option<&InspectorElementId>,
197        window: &mut Window,
198        cx: &mut App,
199    ) -> (LayoutId, Self::RequestLayoutState) {
200        <SharedString as Element>::request_layout(&mut self.text, id, inspector_id, window, cx)
201    }
202
203    fn prepaint(
204        &mut self,
205        id: Option<&GlobalElementId>,
206        inspector_id: Option<&InspectorElementId>,
207        bounds: Bounds<Pixels>,
208        request_layout: &mut Self::RequestLayoutState,
209        window: &mut Window,
210        cx: &mut App,
211    ) -> Self::PrepaintState {
212        <SharedString as Element>::prepaint(
213            &mut self.text,
214            id,
215            inspector_id,
216            bounds,
217            request_layout,
218            window,
219            cx,
220        )
221    }
222
223    fn paint(
224        &mut self,
225        id: Option<&GlobalElementId>,
226        inspector_id: Option<&InspectorElementId>,
227        bounds: Bounds<Pixels>,
228        request_layout: &mut Self::RequestLayoutState,
229        prepaint: &mut Self::PrepaintState,
230        window: &mut Window,
231        cx: &mut App,
232    ) {
233        <SharedString as Element>::paint(
234            &mut self.text,
235            id,
236            inspector_id,
237            bounds,
238            request_layout,
239            prepaint,
240            window,
241            cx,
242        );
243    }
244}
245
246impl Element for &'static str {
247    type RequestLayoutState = TextLayout;
248    type PrepaintState = ();
249
250    fn id(&self) -> Option<ElementId> {
251        None
252    }
253
254    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
255        None
256    }
257
258    fn request_layout(
259        &mut self,
260        _id: Option<&GlobalElementId>,
261        _inspector_id: Option<&InspectorElementId>,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> (LayoutId, Self::RequestLayoutState) {
265        let state = TextLayout::default();
266        let layout_id = state.layout(SharedString::new_static(self), None, window, cx);
267        (layout_id, state)
268    }
269
270    fn prepaint(
271        &mut self,
272        _id: Option<&GlobalElementId>,
273        _inspector_id: Option<&InspectorElementId>,
274        bounds: Bounds<Pixels>,
275        text_layout: &mut Self::RequestLayoutState,
276        _window: &mut Window,
277        _cx: &mut App,
278    ) {
279        text_layout.prepaint(bounds, self)
280    }
281
282    fn paint(
283        &mut self,
284        _id: Option<&GlobalElementId>,
285        _inspector_id: Option<&InspectorElementId>,
286        _bounds: Bounds<Pixels>,
287        text_layout: &mut TextLayout,
288        _: &mut (),
289        window: &mut Window,
290        cx: &mut App,
291    ) {
292        text_layout.paint(self, window, cx)
293    }
294}
295
296impl IntoElement for String {
297    type Element = SharedString;
298
299    fn into_element(self) -> Self::Element {
300        self.into()
301    }
302}
303
304impl IntoElement for Cow<'static, str> {
305    type Element = SharedString;
306
307    fn into_element(self) -> Self::Element {
308        self.into()
309    }
310}
311
312impl Element for SharedString {
313    type RequestLayoutState = TextLayout;
314    type PrepaintState = ();
315
316    fn id(&self) -> Option<ElementId> {
317        None
318    }
319
320    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
321        None
322    }
323
324    fn request_layout(
325        &mut self,
326        _id: Option<&GlobalElementId>,
327        _inspector_id: Option<&InspectorElementId>,
328        window: &mut Window,
329        cx: &mut App,
330    ) -> (LayoutId, Self::RequestLayoutState) {
331        let state = TextLayout::default();
332        let layout_id = state.layout(self.clone(), None, window, cx);
333        (layout_id, state)
334    }
335
336    fn prepaint(
337        &mut self,
338        _id: Option<&GlobalElementId>,
339        _inspector_id: Option<&InspectorElementId>,
340        bounds: Bounds<Pixels>,
341        text_layout: &mut Self::RequestLayoutState,
342        _window: &mut Window,
343        _cx: &mut App,
344    ) {
345        text_layout.prepaint(bounds, self.as_ref())
346    }
347
348    fn paint(
349        &mut self,
350        _id: Option<&GlobalElementId>,
351        _inspector_id: Option<&InspectorElementId>,
352        _bounds: Bounds<Pixels>,
353        text_layout: &mut Self::RequestLayoutState,
354        _: &mut Self::PrepaintState,
355        window: &mut Window,
356        cx: &mut App,
357    ) {
358        text_layout.paint(self.as_ref(), window, cx)
359    }
360}
361
362/// Renders text with runs of different styles.
363///
364/// Callers are responsible for setting the correct style for each run.
365/// For text with a uniform style, you can usually avoid calling this constructor
366/// and just pass text directly.
367pub struct StyledText {
368    text: SharedString,
369    runs: Option<Vec<TextRun>>,
370    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
371    delayed_font_family_overrides: Option<Vec<(Range<usize>, SharedString)>>,
372    layout: TextLayout,
373}
374
375impl StyledText {
376    /// Construct a new styled text element from the given string.
377    pub fn new(text: impl Into<SharedString>) -> Self {
378        StyledText {
379            text: text.into(),
380            runs: None,
381            delayed_highlights: None,
382            delayed_font_family_overrides: None,
383            layout: TextLayout::default(),
384        }
385    }
386
387    /// Get the layout for this element. This can be used to map indices to pixels and vice versa.
388    pub fn layout(&self) -> &TextLayout {
389        &self.layout
390    }
391
392    /// Set the styling attributes for the given text, as well as
393    /// as any ranges of text that have had their style customized.
394    pub fn with_default_highlights(
395        self,
396        default_style: &TextStyle,
397        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
398    ) -> Self {
399        debug_assert!(
400            self.delayed_highlights.is_none(),
401            "Can't use `with_default_highlights` and `with_highlights`"
402        );
403        let runs = Self::compute_runs(&self.text, default_style, highlights);
404        self.with_runs(runs)
405    }
406
407    /// Set the styling attributes for the given text, as well as
408    /// as any ranges of text that have had their style customized.
409    pub fn with_highlights(
410        mut self,
411        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
412    ) -> Self {
413        debug_assert!(
414            self.runs.is_none(),
415            "Can't use `with_highlights` and `with_default_highlights`"
416        );
417        self.delayed_highlights = Some(
418            highlights
419                .into_iter()
420                .inspect(|(run, _)| {
421                    debug_assert!(self.text.is_char_boundary(run.start));
422                    debug_assert!(self.text.is_char_boundary(run.end));
423                })
424                .collect::<Vec<_>>(),
425        );
426        self
427    }
428
429    fn compute_runs(
430        text: &str,
431        default_style: &TextStyle,
432        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
433    ) -> Vec<TextRun> {
434        let mut runs = Vec::new();
435        let mut ix = 0;
436        for (range, highlight) in highlights {
437            if ix < range.start {
438                debug_assert!(text.is_char_boundary(range.start));
439                runs.push(default_style.clone().to_run(range.start - ix));
440            }
441            debug_assert!(text.is_char_boundary(range.end));
442            runs.push(
443                default_style
444                    .clone()
445                    .highlight(highlight)
446                    .to_run(range.len()),
447            );
448            ix = range.end;
449        }
450        if ix < text.len() {
451            runs.push(default_style.to_run(text.len() - ix));
452        }
453        runs
454    }
455
456    /// Override the font family for specific byte ranges of the text.
457    ///
458    /// This is resolved lazily at layout time, so the overrides are applied
459    /// on top of the inherited text style from the parent element.
460    /// Can be combined with [`with_highlights`](Self::with_highlights).
461    ///
462    /// The overrides must be sorted by range start and non-overlapping.
463    /// Each override range must fall on character boundaries.
464    pub fn with_font_family_overrides(
465        mut self,
466        overrides: impl IntoIterator<Item = (Range<usize>, SharedString)>,
467    ) -> Self {
468        self.delayed_font_family_overrides = Some(
469            overrides
470                .into_iter()
471                .inspect(|(range, _)| {
472                    debug_assert!(self.text.is_char_boundary(range.start));
473                    debug_assert!(self.text.is_char_boundary(range.end));
474                })
475                .collect(),
476        );
477        self
478    }
479
480    fn apply_font_family_overrides(
481        runs: &mut [TextRun],
482        overrides: &[(Range<usize>, SharedString)],
483    ) {
484        let mut byte_offset = 0;
485        let mut override_idx = 0;
486        for run in runs.iter_mut() {
487            let run_end = byte_offset + run.len;
488            while override_idx < overrides.len() && overrides[override_idx].0.end <= byte_offset {
489                override_idx += 1;
490            }
491            if override_idx < overrides.len() {
492                let (ref range, ref family) = overrides[override_idx];
493                if byte_offset >= range.start && run_end <= range.end {
494                    run.font.family = family.clone();
495                }
496            }
497            byte_offset = run_end;
498        }
499    }
500
501    /// Set the text runs for this piece of text.
502    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
503        let mut text = &*self.text;
504        for run in &runs {
505            text = text.get(run.len..).unwrap_or_else(|| {
506                #[cfg(debug_assertions)]
507                panic!("invalid text run. Text: '{text}', run: {run:?}");
508                #[cfg(not(debug_assertions))]
509                panic!("invalid text run");
510            });
511        }
512        assert!(text.is_empty(), "invalid text run");
513        self.runs = Some(runs);
514        self
515    }
516}
517
518impl Element for StyledText {
519    type RequestLayoutState = ();
520    type PrepaintState = ();
521
522    fn id(&self) -> Option<ElementId> {
523        None
524    }
525
526    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
527        None
528    }
529
530    fn request_layout(
531        &mut self,
532        _id: Option<&GlobalElementId>,
533        _inspector_id: Option<&InspectorElementId>,
534        window: &mut Window,
535        cx: &mut App,
536    ) -> (LayoutId, Self::RequestLayoutState) {
537        let font_family_overrides = self.delayed_font_family_overrides.take();
538        let mut runs = self.runs.take().or_else(|| {
539            self.delayed_highlights.take().map(|delayed_highlights| {
540                Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
541            })
542        });
543
544        if let Some(ref overrides) = font_family_overrides {
545            let runs =
546                runs.get_or_insert_with(|| vec![window.text_style().to_run(self.text.len())]);
547            Self::apply_font_family_overrides(runs, overrides);
548        }
549
550        let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
551        (layout_id, ())
552    }
553
554    fn prepaint(
555        &mut self,
556        _id: Option<&GlobalElementId>,
557        _inspector_id: Option<&InspectorElementId>,
558        bounds: Bounds<Pixels>,
559        _: &mut Self::RequestLayoutState,
560        _window: &mut Window,
561        _cx: &mut App,
562    ) {
563        self.layout.prepaint(bounds, &self.text)
564    }
565
566    fn paint(
567        &mut self,
568        _id: Option<&GlobalElementId>,
569        _inspector_id: Option<&InspectorElementId>,
570        _bounds: Bounds<Pixels>,
571        _: &mut Self::RequestLayoutState,
572        _: &mut Self::PrepaintState,
573        window: &mut Window,
574        cx: &mut App,
575    ) {
576        self.layout.paint(&self.text, window, cx)
577    }
578}
579
580/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
581#[derive(Default, Clone)]
582pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);
583
584#[derive(Clone, Copy)]
585enum TextPaintPass {
586    All,
587    Background,
588    Foreground,
589}
590
591struct TextLayoutInner {
592    len: usize,
593    lines: SmallVec<[WrappedLine; 1]>,
594    line_height: Pixels,
595    wrap_width: Option<Pixels>,
596    truncate_width: Option<Pixels>,
597    size: Option<Size<Pixels>>,
598    bounds: Option<Bounds<Pixels>>,
599}
600
601impl TextLayout {
602    fn layout(
603        &self,
604        text: SharedString,
605        runs: Option<Vec<TextRun>>,
606        window: &mut Window,
607        _: &mut App,
608    ) -> LayoutId {
609        let text_style = window.text_style();
610        let font_size = text_style.font_size.to_pixels(window.rem_size());
611        let line_height = window.pixel_snap(
612            text_style
613                .line_height
614                .to_pixels(font_size.into(), window.rem_size()),
615        );
616
617        let runs = if let Some(runs) = runs {
618            runs
619        } else {
620            vec![text_style.to_run(text.len())]
621        };
622        window.request_measured_layout(Default::default(), {
623            let element_state = self.clone();
624
625            move |known_dimensions, available_space, window, cx| {
626                let wrap_width = if text_style.white_space == WhiteSpace::Normal {
627                    known_dimensions.width.or(match available_space.width {
628                        crate::AvailableSpace::Definite(x) => Some(x),
629                        _ => None,
630                    })
631                } else {
632                    None
633                };
634
635                let (truncate_width, truncation_affix, truncate_from) =
636                    if let Some(text_overflow) = text_style.text_overflow.clone() {
637                        let width = known_dimensions.width.or(match available_space.width {
638                            crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
639                                Some(max_lines) => Some(x * max_lines),
640                                None => Some(x),
641                            },
642                            _ => None,
643                        });
644
645                        match text_overflow {
646                            TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
647                            TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
648                            TextOverflow::TruncateMiddle(s) => (width, s, TruncateFrom::Middle),
649                        }
650                    } else {
651                        (None, "".into(), TruncateFrom::End)
652                    };
653
654                // Only use cached layout if:
655                // 1. We have a cached size
656                // 2. wrap_width matches (or both are None)
657                // 3. truncate_width is None (if truncate_width is Some, we need to re-layout
658                //    because the previous layout may have been computed without truncation)
659                // 4. the cached layout was not truncated (a truncated layout answers an
660                //    unconstrained probe with the truncated size, which poisons intrinsic
661                //    sizing with whatever width some earlier measure pass happened to use)
662                if let Some(text_layout) = element_state.0.borrow().as_ref()
663                    && let Some(size) = text_layout.size
664                    && (wrap_width.is_none() || wrap_width == text_layout.wrap_width)
665                    && truncate_width.is_none()
666                    && text_layout.truncate_width.is_none()
667                {
668                    return size;
669                }
670
671                let (text, runs) = if let Some(truncate_width) = truncate_width {
672                    // Taking a wrapper from the pool locks it twice and moves its
673                    // character width cache around, so only do it when truncating.
674                    let mut line_wrapper =
675                        cx.text_system().line_wrapper(text_style.font(), font_size);
676                    if let Some(max_lines) = text_style.line_clamp
677                        && let Some(wrap_width) = wrap_width
678                    {
679                        line_wrapper.truncate_wrapped_line(
680                            text.clone(),
681                            wrap_width,
682                            max_lines,
683                            &truncation_affix,
684                            &runs,
685                            truncate_from,
686                        )
687                    } else if let Some(unclipped) = window
688                        .text_system()
689                        .shape_text(text.clone(), font_size, &runs, None, None)
690                        .log_err()
691                        && unclipped
692                            .iter()
693                            .all(|line| line.size(line_height).width <= truncate_width)
694                    {
695                        // The truncation decision below sums per-character advances,
696                        // which overestimates the shaped width (no kerning), truncating
697                        // text that fits exactly in its measured width. Skip truncation
698                        // whenever the honestly-shaped text fits; the shaping result
699                        // comes from the line layout cache when the same text was
700                        // already measured untruncated this frame.
701                        (text.clone(), Cow::Borrowed(&*runs))
702                    } else {
703                        line_wrapper.truncate_line(
704                            text.clone(),
705                            truncate_width,
706                            &truncation_affix,
707                            &runs,
708                            truncate_from,
709                        )
710                    }
711                } else {
712                    (text.clone(), Cow::Borrowed(&*runs))
713                };
714                let len = text.len();
715
716                let Some(lines) = window
717                    .text_system()
718                    .shape_text(
719                        text,
720                        font_size,
721                        &runs,
722                        wrap_width,            // Wrap if we know the width.
723                        text_style.line_clamp, // Limit the number of lines if line_clamp is set.
724                    )
725                    .log_err()
726                else {
727                    element_state.0.borrow_mut().replace(TextLayoutInner {
728                        lines: Default::default(),
729                        len: 0,
730                        line_height,
731                        wrap_width,
732                        truncate_width,
733                        size: Some(Size::default()),
734                        bounds: None,
735                    });
736                    return Size::default();
737                };
738
739                let mut size: Size<Pixels> = Size::default();
740                for line in &lines {
741                    let line_size = line.size(line_height);
742                    size.height += line_size.height;
743                    size.width = size.width.max(line_size.width).ceil();
744                }
745
746                element_state.0.borrow_mut().replace(TextLayoutInner {
747                    lines,
748                    len,
749                    line_height,
750                    wrap_width,
751                    truncate_width,
752                    size: Some(size),
753                    bounds: None,
754                });
755
756                size
757            }
758        })
759    }
760
761    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
762        let mut element_state = self.0.borrow_mut();
763        let element_state = element_state
764            .as_mut()
765            .with_context(|| format!("measurement has not been performed on {text}"))
766            .unwrap();
767        element_state.bounds = Some(bounds);
768    }
769
770    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
771        self.paint_lines(TextPaintPass::All, window, cx)
772            .with_context(|| format!("failed to paint {text}"))
773            .unwrap();
774    }
775
776    /// Paints the backgrounds of the text runs without the glyphs, so that callers can paint
777    /// content, such as highlights, between the backgrounds and the text. Follow it with
778    /// [`Self::paint_foreground`] to paint the glyphs.
779    pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
780        self.paint_lines(TextPaintPass::Background, window, cx)
781    }
782
783    /// Paints the glyphs and decorations of the text without the run backgrounds.
784    pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
785        self.paint_lines(TextPaintPass::Foreground, window, cx)
786    }
787
788    fn paint_lines(
789        &self,
790        pass: TextPaintPass,
791        window: &mut Window,
792        cx: &mut App,
793    ) -> anyhow::Result<()> {
794        let element_state = self.0.borrow();
795        let element_state = element_state
796            .as_ref()
797            .context("measurement has not been performed")?;
798        let bounds = element_state
799            .bounds
800            .context("prepaint has not been performed")?;
801
802        let line_height = element_state.line_height;
803        let mut line_origin = bounds.origin;
804        let text_style = window.text_style();
805        for line in &element_state.lines {
806            if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {
807                line.paint_background(
808                    line_origin,
809                    line_height,
810                    text_style.text_align,
811                    Some(bounds),
812                    window,
813                    cx,
814                )
815                .log_err();
816            }
817            if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {
818                line.paint(
819                    line_origin,
820                    line_height,
821                    text_style.text_align,
822                    Some(bounds),
823                    window,
824                    cx,
825                )
826                .log_err();
827            }
828            line_origin.y += line.size(line_height).height;
829        }
830        Ok(())
831    }
832
833    /// Get the byte index into the input of the pixel position.
834    pub fn index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
835        let element_state = self.0.borrow();
836        let element_state = element_state
837            .as_ref()
838            .expect("measurement has not been performed");
839        let bounds = element_state
840            .bounds
841            .expect("prepaint has not been performed");
842
843        if position.y < bounds.top() {
844            return Err(0);
845        }
846
847        let line_height = element_state.line_height;
848        let mut line_origin = bounds.origin;
849        let mut line_start_ix = 0;
850        for line in &element_state.lines {
851            let line_bottom = line_origin.y + line.size(line_height).height;
852            if position.y > line_bottom {
853                line_origin.y = line_bottom;
854                line_start_ix += line.len() + 1;
855            } else {
856                let position_within_line = position - line_origin;
857                match line.index_for_position(position_within_line, line_height) {
858                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
859                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
860                }
861            }
862        }
863
864        Err(line_start_ix.saturating_sub(1))
865    }
866
867    /// Get the pixel position for the given byte index.
868    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
869        let element_state = self.0.borrow();
870        let element_state = element_state
871            .as_ref()
872            .expect("measurement has not been performed");
873        let bounds = element_state
874            .bounds
875            .expect("prepaint has not been performed");
876        let line_height = element_state.line_height;
877
878        let mut line_origin = bounds.origin;
879        let mut line_start_ix = 0;
880
881        for line in &element_state.lines {
882            let line_end_ix = line_start_ix + line.len();
883            if index < line_start_ix {
884                break;
885            } else if index > line_end_ix {
886                line_origin.y += line.size(line_height).height;
887                line_start_ix = line_end_ix + 1;
888                continue;
889            } else {
890                let ix_within_line = index - line_start_ix;
891                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
892            }
893        }
894
895        None
896    }
897
898    /// Retrieve the layout for the line containing the given byte index.
899    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
900        let element_state = self.0.borrow();
901        let element_state = element_state
902            .as_ref()
903            .expect("measurement has not been performed");
904        let mut line_start_ix = 0;
905
906        for line in &element_state.lines {
907            let line_end_ix = line_start_ix + line.len();
908            if index < line_start_ix {
909                break;
910            } else if index > line_end_ix {
911                line_start_ix = line_end_ix + 1;
912                continue;
913            } else {
914                return Some(line.layout.clone());
915            }
916        }
917
918        None
919    }
920
921    /// Retrieve all line layouts in source order.
922    pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {
923        self.0
924            .borrow()
925            .as_ref()
926            .expect("measurement has not been performed")
927            .lines
928            .iter()
929            .map(|line| line.layout.clone())
930            .collect()
931    }
932
933    /// The bounds of this layout.
934    pub fn bounds(&self) -> Bounds<Pixels> {
935        self.0.borrow().as_ref().unwrap().bounds.unwrap()
936    }
937
938    /// The line height for this layout.
939    pub fn line_height(&self) -> Pixels {
940        self.0.borrow().as_ref().unwrap().line_height
941    }
942
943    /// The UTF-8 length of the underlying text.
944    pub fn len(&self) -> usize {
945        self.0.borrow().as_ref().unwrap().len
946    }
947
948    /// The text for this layout.
949    pub fn text(&self) -> String {
950        self.0
951            .borrow()
952            .as_ref()
953            .unwrap()
954            .lines
955            .iter()
956            .map(|s| &s.text)
957            .join("\n")
958    }
959
960    /// The text for this layout (with soft-wraps as newlines)
961    pub fn wrapped_text(&self) -> String {
962        let mut accumulator = String::new();
963
964        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
965            let mut seen = 0;
966            for boundary in wrapped.layout.wrap_boundaries.iter() {
967                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
968                    [boundary.glyph_ix]
969                    .index;
970
971                accumulator.push_str(&wrapped.text[seen..index]);
972                accumulator.push('\n');
973                seen = index;
974            }
975            accumulator.push_str(&wrapped.text[seen..]);
976            accumulator.push('\n');
977        }
978        // Remove trailing newline
979        accumulator.pop();
980        accumulator
981    }
982}
983
984/// A text element that can be interacted with.
985pub struct InteractiveText {
986    element_id: ElementId,
987    text: StyledText,
988    click_listener:
989        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
990    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
991    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
992    tooltip_id: Option<TooltipId>,
993    clickable_ranges: Vec<Range<usize>>,
994}
995
996struct InteractiveTextClickEvent {
997    mouse_down_index: usize,
998    mouse_up_index: usize,
999}
1000
1001#[doc(hidden)]
1002#[derive(Default)]
1003pub struct InteractiveTextState {
1004    mouse_down_index: Rc<Cell<Option<usize>>>,
1005    hovered_index: Rc<Cell<Option<usize>>>,
1006    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
1007    long_press_tooltip_active: Rc<Cell<bool>>,
1008}
1009
1010/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
1011impl InteractiveText {
1012    /// Creates a new InteractiveText from the given text.
1013    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
1014        Self {
1015            element_id: id.into(),
1016            text,
1017            click_listener: None,
1018            hover_listener: None,
1019            tooltip_builder: None,
1020            tooltip_id: None,
1021            clickable_ranges: Vec::new(),
1022        }
1023    }
1024
1025    /// on_click is called when the user clicks on one of the given ranges, passing the index of
1026    /// the clicked range.
1027    pub fn on_click(
1028        mut self,
1029        ranges: Vec<Range<usize>>,
1030        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
1031    ) -> Self {
1032        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
1033            for (range_ix, range) in ranges.iter().enumerate() {
1034                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
1035                {
1036                    listener(range_ix, window, cx);
1037                }
1038            }
1039        }));
1040        self.clickable_ranges = ranges;
1041        self
1042    }
1043
1044    /// on_hover is called when the mouse moves over a character within the text, passing the
1045    /// index of the hovered character, or None if the mouse leaves the text.
1046    pub fn on_hover(
1047        mut self,
1048        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
1049    ) -> Self {
1050        self.hover_listener = Some(Box::new(listener));
1051        self
1052    }
1053
1054    /// tooltip lets you specify a tooltip for a given character index in the string.
1055    pub fn tooltip(
1056        mut self,
1057        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
1058    ) -> Self {
1059        self.tooltip_builder = Some(Rc::new(builder));
1060        self
1061    }
1062}
1063
1064impl Element for InteractiveText {
1065    type RequestLayoutState = ();
1066    type PrepaintState = Hitbox;
1067
1068    fn id(&self) -> Option<ElementId> {
1069        Some(self.element_id.clone())
1070    }
1071
1072    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1073        None
1074    }
1075
1076    fn a11y_role(&self) -> Option<accesskit::Role> {
1077        Some(accesskit::Role::Label)
1078    }
1079
1080    fn write_a11y_info(&self, node: &mut accesskit::Node) {
1081        node.set_value(self.text.text.to_string());
1082    }
1083
1084    fn request_layout(
1085        &mut self,
1086        _id: Option<&GlobalElementId>,
1087        inspector_id: Option<&InspectorElementId>,
1088        window: &mut Window,
1089        cx: &mut App,
1090    ) -> (LayoutId, Self::RequestLayoutState) {
1091        self.text.request_layout(None, inspector_id, window, cx)
1092    }
1093
1094    fn prepaint(
1095        &mut self,
1096        global_id: Option<&GlobalElementId>,
1097        inspector_id: Option<&InspectorElementId>,
1098        bounds: Bounds<Pixels>,
1099        state: &mut Self::RequestLayoutState,
1100        window: &mut Window,
1101        cx: &mut App,
1102    ) -> Hitbox {
1103        window.with_optional_element_state::<InteractiveTextState, _>(
1104            global_id,
1105            |interactive_state, window| {
1106                let mut interactive_state = interactive_state
1107                    .map(|interactive_state| interactive_state.unwrap_or_default());
1108
1109                if let Some(interactive_state) = interactive_state.as_mut() {
1110                    if self.tooltip_builder.is_some() {
1111                        self.tooltip_id =
1112                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
1113                    } else {
1114                        // If there is no longer a tooltip builder, remove the active tooltip.
1115                        interactive_state.long_press_tooltip_active.set(false);
1116                        interactive_state.active_tooltip.take();
1117                    }
1118                }
1119
1120                self.text
1121                    .prepaint(None, inspector_id, bounds, state, window, cx);
1122                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1123                (hitbox, interactive_state)
1124            },
1125        )
1126    }
1127
1128    fn paint(
1129        &mut self,
1130        global_id: Option<&GlobalElementId>,
1131        inspector_id: Option<&InspectorElementId>,
1132        bounds: Bounds<Pixels>,
1133        _: &mut Self::RequestLayoutState,
1134        hitbox: &mut Hitbox,
1135        window: &mut Window,
1136        cx: &mut App,
1137    ) {
1138        let current_view = window.current_view();
1139        let text_layout = self.text.layout().clone();
1140        window.with_element_state::<InteractiveTextState, _>(
1141            global_id.unwrap(),
1142            |interactive_state, window| {
1143                let interactive_state = interactive_state.unwrap_or_default();
1144                if let Some(click_listener) = self.click_listener.take() {
1145                    let mouse_position = window.mouse_position();
1146                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
1147                        && self
1148                            .clickable_ranges
1149                            .iter()
1150                            .any(|range| range.contains(&ix))
1151                    {
1152                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
1153                    }
1154
1155                    let text_layout = text_layout.clone();
1156                    let mouse_down = interactive_state.mouse_down_index.clone();
1157                    if let Some(mouse_down_index) = mouse_down.get() {
1158                        let hitbox = hitbox.clone();
1159                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
1160                        window.on_mouse_event(
1161                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
1162                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1163                                    if let Ok(mouse_up_index) =
1164                                        text_layout.index_for_position(event.position)
1165                                    {
1166                                        click_listener(
1167                                            &clickable_ranges,
1168                                            InteractiveTextClickEvent {
1169                                                mouse_down_index,
1170                                                mouse_up_index,
1171                                            },
1172                                            window,
1173                                            cx,
1174                                        )
1175                                    }
1176
1177                                    mouse_down.take();
1178                                    window.refresh();
1179                                }
1180                            },
1181                        );
1182                    } else {
1183                        let hitbox = hitbox.clone();
1184                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
1185                            if phase == DispatchPhase::Bubble
1186                                && hitbox.is_hovered(window)
1187                                && let Ok(mouse_down_index) =
1188                                    text_layout.index_for_position(event.position)
1189                            {
1190                                mouse_down.set(Some(mouse_down_index));
1191                                window.refresh();
1192                            }
1193                        });
1194                    }
1195                }
1196
1197                window.on_mouse_event({
1198                    let hover_listener = self.hover_listener.take();
1199                    let hitbox = hitbox.clone();
1200                    let text_layout = text_layout.clone();
1201                    let hovered_index = interactive_state.hovered_index.clone();
1202                    move |event: &MouseMoveEvent, phase, window, cx| {
1203                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1204                            let current = hovered_index.get();
1205                            let updated = text_layout.index_for_position(event.position).ok();
1206                            if current != updated {
1207                                hovered_index.set(updated);
1208                                if let Some(hover_listener) = hover_listener.as_ref() {
1209                                    hover_listener(updated, event.clone(), window, cx);
1210                                }
1211                                cx.notify(current_view);
1212                            }
1213                        }
1214                    }
1215                });
1216
1217                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
1218                    let active_tooltip = interactive_state.active_tooltip.clone();
1219                    let build_tooltip = Rc::new({
1220                        let tooltip_is_hoverable = false;
1221                        let text_layout = text_layout.clone();
1222                        move |window: &mut Window, cx: &mut App| {
1223                            text_layout
1224                                .index_for_position(window.mouse_position())
1225                                .ok()
1226                                .and_then(|position| tooltip_builder(position, window, cx))
1227                                .map(|view| (view, tooltip_is_hoverable))
1228                        }
1229                    });
1230
1231                    // Use bounds instead of testing hitbox since this is called during prepaint.
1232                    let check_is_hovered_during_prepaint = Rc::new({
1233                        let source_bounds = hitbox.bounds;
1234                        let text_layout = text_layout.clone();
1235                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1236                        move |window: &Window| {
1237                            text_layout
1238                                .index_for_position(window.mouse_position())
1239                                .is_ok()
1240                                && source_bounds.contains(&window.mouse_position())
1241                                && pending_mouse_down.get().is_none()
1242                        }
1243                    });
1244
1245                    let check_is_hovered = Rc::new({
1246                        let hitbox = hitbox.clone();
1247                        let text_layout = text_layout.clone();
1248                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1249                        move |window: &Window| {
1250                            text_layout
1251                                .index_for_position(window.mouse_position())
1252                                .is_ok()
1253                                && hitbox.is_hovered(window)
1254                                && pending_mouse_down.get().is_none()
1255                        }
1256                    });
1257
1258                    register_tooltip_mouse_handlers(
1259                        &active_tooltip,
1260                        self.tooltip_id,
1261                        build_tooltip,
1262                        check_is_hovered,
1263                        check_is_hovered_during_prepaint,
1264                        interactive_state.long_press_tooltip_active.clone(),
1265                        None,
1266                        window,
1267                    );
1268                }
1269
1270                self.text
1271                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
1272
1273                ((), interactive_state)
1274            },
1275        );
1276    }
1277}
1278
1279#[cfg(test)]
1280mod tests {
1281    use super::*;
1282
1283    #[test]
1284    fn test_into_element_for() {
1285        use crate::{ParentElement as _, SharedString, div};
1286        use std::borrow::Cow;
1287
1288        let _ = div().child("static str");
1289        let _ = div().child("String".to_string());
1290        let _ = div().child(Cow::Borrowed("Cow"));
1291        let _ = div().child(SharedString::from("SharedString"));
1292    }
1293
1294    #[test]
1295    fn text_macro_id() {
1296        // one call to `text!` = one id
1297        fn make_text_stable_id(happy: bool) -> Text {
1298            text!(if happy { "happy" } else { "sad" })
1299        }
1300
1301        // two calls to `text!` = two ids
1302        fn make_text_unstable_id(happy: bool) -> Text {
1303            if happy { text!("happy") } else { text!("sad") }
1304        }
1305
1306        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
1307        assert_ne!(
1308            make_text_unstable_id(false).id,
1309            make_text_unstable_id(true).id
1310        );
1311    }
1312}