Skip to main content

gpui/elements/
text.rs

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