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        text_layout.prepaint(bounds, self)
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        text_layout.prepaint(bounds, self.as_ref())
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        self.layout.prepaint(bounds, &self.text)
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 prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
646        let mut element_state = self.0.borrow_mut();
647        let element_state = element_state
648            .as_mut()
649            .with_context(|| format!("measurement has not been performed on {text}"))
650            .unwrap();
651        element_state.bounds = Some(bounds);
652    }
653
654    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
655        self.paint_lines(TextPaintPass::All, window, cx)
656            .with_context(|| format!("failed to paint {text}"))
657            .unwrap();
658    }
659
660    /// Paints the backgrounds of the text runs without the glyphs, so that callers can paint
661    /// content, such as highlights, between the backgrounds and the text. Follow it with
662    /// [`Self::paint_foreground`] to paint the glyphs.
663    pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
664        self.paint_lines(TextPaintPass::Background, window, cx)
665    }
666
667    /// Paints the glyphs and decorations of the text without the run backgrounds.
668    pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
669        self.paint_lines(TextPaintPass::Foreground, window, cx)
670    }
671
672    fn paint_lines(
673        &self,
674        pass: TextPaintPass,
675        window: &mut Window,
676        cx: &mut App,
677    ) -> anyhow::Result<()> {
678        let element_state = self.0.borrow();
679        let element_state = element_state
680            .as_ref()
681            .context("measurement has not been performed")?;
682        let bounds = element_state
683            .bounds
684            .context("prepaint has not been performed")?;
685
686        let line_height = element_state.line_height;
687        let mut line_origin = bounds.origin;
688        let text_style = crate::fast::text_style::text_paint_style(window);
689        for line in &element_state.lines {
690            if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {
691                line.paint_background(
692                    line_origin,
693                    line_height,
694                    text_style.text_align,
695                    Some(bounds),
696                    window,
697                    cx,
698                )
699                .log_err();
700            }
701            if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {
702                line.paint(
703                    line_origin,
704                    line_height,
705                    text_style.text_align,
706                    Some(bounds),
707                    window,
708                    cx,
709                )
710                .log_err();
711            }
712            line_origin.y += line.size(line_height).height;
713        }
714        Ok(())
715    }
716
717    /// Get the byte index into the input of the pixel position.
718    pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
719        let element_state = self.0.borrow();
720        let element_state = element_state
721            .as_ref()
722            .expect("measurement has not been performed");
723        let bounds = element_state
724            .bounds
725            .expect("prepaint has not been performed");
726
727        if position.y < bounds.top() {
728            return Err(0);
729        }
730
731        let line_height = element_state.line_height;
732        let mut line_origin = bounds.origin;
733        let mut line_start_ix = 0;
734        for line in &element_state.lines {
735            let line_bottom = line_origin.y + line.size(line_height).height;
736            if position.y > line_bottom {
737                line_origin.y = line_bottom;
738                line_start_ix += line.len() + 1;
739            } else {
740                let position_within_line = position - line_origin;
741                match line.index_for_position(position_within_line, line_height) {
742                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
743                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
744                }
745            }
746        }
747
748        Err(line_start_ix.saturating_sub(1))
749    }
750
751    /// Get the pixel position for the given byte index.
752    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
753        let element_state = self.0.borrow();
754        let element_state = element_state
755            .as_ref()
756            .expect("measurement has not been performed");
757        let bounds = element_state
758            .bounds
759            .expect("prepaint has not been performed");
760        let line_height = element_state.line_height;
761
762        let mut line_origin = bounds.origin;
763        let mut line_start_ix = 0;
764
765        for line in &element_state.lines {
766            let line_end_ix = line_start_ix + line.len();
767            if index < line_start_ix {
768                break;
769            } else if index > line_end_ix {
770                line_origin.y += line.size(line_height).height;
771                line_start_ix = line_end_ix + 1;
772                continue;
773            } else {
774                let ix_within_line = index - line_start_ix;
775                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
776            }
777        }
778
779        None
780    }
781
782    /// Retrieve the layout for the line containing the given byte index.
783    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
784        let element_state = self.0.borrow();
785        let element_state = element_state
786            .as_ref()
787            .expect("measurement has not been performed");
788        let mut line_start_ix = 0;
789
790        for line in &element_state.lines {
791            let line_end_ix = line_start_ix + line.len();
792            if index < line_start_ix {
793                break;
794            } else if index > line_end_ix {
795                line_start_ix = line_end_ix + 1;
796                continue;
797            } else {
798                return Some(line.layout.clone());
799            }
800        }
801
802        None
803    }
804
805    /// Retrieve all line layouts in source order.
806    pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {
807        self.0
808            .borrow()
809            .as_ref()
810            .expect("measurement has not been performed")
811            .lines
812            .iter()
813            .map(|line| line.layout.clone())
814            .collect()
815    }
816
817    /// The bounds of this layout.
818    pub fn bounds(&self) -> Bounds<Pixels> {
819        self.0.borrow().as_ref().unwrap().bounds.unwrap()
820    }
821
822    /// The line height for this layout.
823    pub fn line_height(&self) -> Pixels {
824        self.0.borrow().as_ref().unwrap().line_height
825    }
826
827    /// The UTF-8 length of the underlying text.
828    pub fn len(&self) -> usize {
829        self.0.borrow().as_ref().unwrap().len
830    }
831
832    /// The text for this layout.
833    pub fn text(&self) -> String {
834        self.0
835            .borrow()
836            .as_ref()
837            .unwrap()
838            .lines
839            .iter()
840            .map(|s| &s.text)
841            .join("\n")
842    }
843
844    /// The text for this layout (with soft-wraps as newlines)
845    pub fn wrapped_text(&self) -> String {
846        let mut accumulator = String::new();
847
848        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
849            let mut seen = 0;
850            for boundary in wrapped.layout.wrap_boundaries.iter() {
851                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
852                    [boundary.glyph_ix]
853                    .index;
854
855                accumulator.push_str(&wrapped.text[seen..index]);
856                accumulator.push('\n');
857                seen = index;
858            }
859            accumulator.push_str(&wrapped.text[seen..]);
860            accumulator.push('\n');
861        }
862        // Remove trailing newline
863        accumulator.pop();
864        accumulator
865    }
866}
867
868/// A text element that can be interacted with.
869pub struct InteractiveText {
870    element_id: ElementId,
871    text: StyledText,
872    click_listener:
873        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
874    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
875    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
876    tooltip_id: Option<TooltipId>,
877    clickable_ranges: Vec<Range<usize>>,
878}
879
880struct InteractiveTextClickEvent {
881    mouse_down_index: usize,
882    mouse_up_index: usize,
883}
884
885#[doc(hidden)]
886#[derive(Default)]
887pub struct InteractiveTextState {
888    mouse_down_index: Rc<Cell<Option<usize>>>,
889    hovered_index: Rc<Cell<Option<usize>>>,
890    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
891    long_press_tooltip_active: Rc<Cell<bool>>,
892}
893
894/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
895impl InteractiveText {
896    /// Creates a new InteractiveText from the given text.
897    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
898        Self {
899            element_id: id.into(),
900            text,
901            click_listener: None,
902            hover_listener: None,
903            tooltip_builder: None,
904            tooltip_id: None,
905            clickable_ranges: Vec::new(),
906        }
907    }
908
909    /// on_click is called when the user clicks on one of the given ranges, passing the index of
910    /// the clicked range.
911    pub fn on_click(
912        mut self,
913        ranges: Vec<Range<usize>>,
914        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
915    ) -> Self {
916        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
917            for (range_ix, range) in ranges.iter().enumerate() {
918                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
919                {
920                    listener(range_ix, window, cx);
921                }
922            }
923        }));
924        self.clickable_ranges = ranges;
925        self
926    }
927
928    /// on_hover is called when the mouse moves over a character within the text, passing the
929    /// index of the hovered character, or None if the mouse leaves the text.
930    pub fn on_hover(
931        mut self,
932        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
933    ) -> Self {
934        self.hover_listener = Some(Box::new(listener));
935        self
936    }
937
938    /// tooltip lets you specify a tooltip for a given character index in the string.
939    pub fn tooltip(
940        mut self,
941        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
942    ) -> Self {
943        self.tooltip_builder = Some(Rc::new(builder));
944        self
945    }
946}
947
948impl Element for InteractiveText {
949    type RequestLayoutState = ();
950    type PrepaintState = Hitbox;
951
952    fn id(&self) -> Option<ElementId> {
953        Some(self.element_id.clone())
954    }
955
956    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
957        None
958    }
959
960    fn a11y_role(&self) -> Option<accesskit::Role> {
961        Some(accesskit::Role::Label)
962    }
963
964    fn write_a11y_info(&self, node: &mut accesskit::Node) {
965        node.set_value(self.text.text.to_string());
966    }
967
968    fn request_layout(
969        &mut self,
970        _id: Option<&GlobalElementId>,
971        inspector_id: Option<&InspectorElementId>,
972        window: &mut Window,
973        cx: &mut App,
974    ) -> (LayoutId, Self::RequestLayoutState) {
975        self.text.request_layout(None, inspector_id, window, cx)
976    }
977
978    fn prepaint(
979        &mut self,
980        global_id: Option<&GlobalElementId>,
981        inspector_id: Option<&InspectorElementId>,
982        bounds: Bounds<Pixels>,
983        state: &mut Self::RequestLayoutState,
984        window: &mut Window,
985        cx: &mut App,
986    ) -> Hitbox {
987        window.with_optional_element_state::<InteractiveTextState, _>(
988            global_id,
989            |interactive_state, window| {
990                let mut interactive_state = interactive_state
991                    .map(|interactive_state| interactive_state.unwrap_or_default());
992
993                if let Some(interactive_state) = interactive_state.as_mut() {
994                    if self.tooltip_builder.is_some() {
995                        self.tooltip_id =
996                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
997                    } else {
998                        // If there is no longer a tooltip builder, remove the active tooltip.
999                        interactive_state.long_press_tooltip_active.set(false);
1000                        interactive_state.active_tooltip.take();
1001                    }
1002                }
1003
1004                self.text
1005                    .prepaint(None, inspector_id, bounds, state, window, cx);
1006                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1007                (hitbox, interactive_state)
1008            },
1009        )
1010    }
1011
1012    fn paint(
1013        &mut self,
1014        global_id: Option<&GlobalElementId>,
1015        inspector_id: Option<&InspectorElementId>,
1016        bounds: Bounds<Pixels>,
1017        _: &mut Self::RequestLayoutState,
1018        hitbox: &mut Hitbox,
1019        window: &mut Window,
1020        cx: &mut App,
1021    ) {
1022        let current_view = window.current_view();
1023        let text_layout = self.text.layout().clone();
1024        window.with_element_state::<InteractiveTextState, _>(
1025            global_id.unwrap(),
1026            |interactive_state, window| {
1027                let mut interactive_state = interactive_state.unwrap_or_default();
1028                if let Some(click_listener) = self.click_listener.take() {
1029                    let mouse_position = window.mouse_position();
1030                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
1031                        && self
1032                            .clickable_ranges
1033                            .iter()
1034                            .any(|range| range.contains(&ix))
1035                    {
1036                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
1037                    }
1038
1039                    let text_layout = text_layout.clone();
1040                    let mouse_down = interactive_state.mouse_down_index.clone();
1041                    if let Some(mouse_down_index) = mouse_down.get() {
1042                        let hitbox = hitbox.clone();
1043                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
1044                        window.on_mouse_event(
1045                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
1046                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1047                                    if let Ok(mouse_up_index) =
1048                                        text_layout.index_for_position(event.position)
1049                                    {
1050                                        click_listener(
1051                                            &clickable_ranges,
1052                                            InteractiveTextClickEvent {
1053                                                mouse_down_index,
1054                                                mouse_up_index,
1055                                            },
1056                                            window,
1057                                            cx,
1058                                        )
1059                                    }
1060
1061                                    mouse_down.take();
1062                                    window.refresh();
1063                                }
1064                            },
1065                        );
1066                    } else {
1067                        let hitbox = hitbox.clone();
1068                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
1069                            if phase == DispatchPhase::Bubble
1070                                && hitbox.is_hovered(window)
1071                                && let Ok(mouse_down_index) =
1072                                    text_layout.index_for_position(event.position)
1073                            {
1074                                mouse_down.set(Some(mouse_down_index));
1075                                window.refresh();
1076                            }
1077                        });
1078                    }
1079                }
1080
1081                window.on_mouse_event({
1082                    let mut hover_listener = self.hover_listener.take();
1083                    let hitbox = hitbox.clone();
1084                    let text_layout = text_layout.clone();
1085                    let hovered_index = interactive_state.hovered_index.clone();
1086                    move |event: &MouseMoveEvent, phase, window, cx| {
1087                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1088                            let current = hovered_index.get();
1089                            let updated = text_layout.index_for_position(event.position).ok();
1090                            if current != updated {
1091                                hovered_index.set(updated);
1092                                if let Some(hover_listener) = hover_listener.as_ref() {
1093                                    hover_listener(updated, event.clone(), window, cx);
1094                                }
1095                                cx.notify(current_view);
1096                            }
1097                        }
1098                    }
1099                });
1100
1101                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
1102                    let active_tooltip = interactive_state.active_tooltip.clone();
1103                    let build_tooltip = Rc::new({
1104                        let tooltip_is_hoverable = false;
1105                        let text_layout = text_layout.clone();
1106                        move |window: &mut Window, cx: &mut App| {
1107                            text_layout
1108                                .index_for_position(window.mouse_position())
1109                                .ok()
1110                                .and_then(|position| tooltip_builder(position, window, cx))
1111                                .map(|view| (view, tooltip_is_hoverable))
1112                        }
1113                    });
1114
1115                    // Use bounds instead of testing hitbox since this is called during prepaint.
1116                    let check_is_hovered_during_prepaint = Rc::new({
1117                        let source_bounds = hitbox.bounds;
1118                        let text_layout = text_layout.clone();
1119                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1120                        move |window: &Window| {
1121                            text_layout
1122                                .index_for_position(window.mouse_position())
1123                                .is_ok()
1124                                && source_bounds.contains(&window.mouse_position())
1125                                && pending_mouse_down.get().is_none()
1126                        }
1127                    });
1128
1129                    let check_is_hovered = Rc::new({
1130                        let hitbox = hitbox.clone();
1131                        let text_layout = text_layout.clone();
1132                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1133                        move |window: &Window| {
1134                            text_layout
1135                                .index_for_position(window.mouse_position())
1136                                .is_ok()
1137                                && hitbox.is_hovered(window)
1138                                && pending_mouse_down.get().is_none()
1139                        }
1140                    });
1141
1142                    register_tooltip_mouse_handlers(
1143                        &active_tooltip,
1144                        self.tooltip_id,
1145                        build_tooltip,
1146                        check_is_hovered,
1147                        check_is_hovered_during_prepaint,
1148                        interactive_state.long_press_tooltip_active.clone(),
1149                        None,
1150                        window,
1151                    );
1152                }
1153
1154                self.text
1155                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
1156
1157                ((), interactive_state)
1158            },
1159        );
1160    }
1161}
1162
1163impl IntoElement for InteractiveText {
1164    type Element = Self;
1165
1166    fn into_element(self) -> Self::Element {
1167        self
1168    }
1169}
1170
1171#[cfg(test)]
1172mod tests {
1173    use super::*;
1174
1175    #[test]
1176    fn test_into_element_for() {
1177        use crate::{ParentElement as _, SharedString, div};
1178        use std::borrow::Cow;
1179
1180        let _ = div().child("static str");
1181        let _ = div().child("String".to_string());
1182        let _ = div().child(Cow::Borrowed("Cow"));
1183        let _ = div().child(SharedString::from("SharedString"));
1184    }
1185
1186    #[test]
1187    fn text_macro_id() {
1188        // one call to `text!` = one id
1189        fn make_text_stable_id(happy: bool) -> Text {
1190            text!(if happy { "happy" } else { "sad" })
1191        }
1192
1193        // two calls to `text!` = two ids
1194        fn make_text_unstable_id(happy: bool) -> Text {
1195            if happy { text!("happy") } else { text!("sad") }
1196        }
1197
1198        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
1199        assert_ne!(
1200            make_text_unstable_id(false).id,
1201            make_text_unstable_id(true).id
1202        );
1203    }
1204}