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 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 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        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, 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    fast_clickable_hitboxes: crate::fast::interactive_text::ClickableHitboxes,
873}
874
875struct InteractiveTextClickEvent {
876    mouse_down_index: usize,
877    mouse_up_index: usize,
878}
879
880#[doc(hidden)]
881#[derive(Default)]
882pub struct InteractiveTextState {
883    mouse_down_index: Rc<Cell<Option<usize>>>,
884    hovered_index: Rc<Cell<Option<usize>>>,
885    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
886    long_press_tooltip_active: Rc<Cell<bool>>,
887}
888
889/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
890impl InteractiveText {
891    /// Creates a new InteractiveText from the given text.
892    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
893        Self {
894            element_id: id.into(),
895            text,
896            click_listener: None,
897            hover_listener: None,
898            tooltip_builder: None,
899            tooltip_id: None,
900            clickable_ranges: Vec::new(),
901            fast_clickable_hitboxes: crate::fast::interactive_text::ClickableHitboxes::default(),
902        }
903    }
904
905    /// on_click is called when the user clicks on one of the given ranges, passing the index of
906    /// the clicked range.
907    pub fn on_click(
908        mut self,
909        ranges: Vec<Range<usize>>,
910        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
911    ) -> Self {
912        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
913            for (range_ix, range) in ranges.iter().enumerate() {
914                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
915                {
916                    listener(range_ix, window, cx);
917                }
918            }
919        }));
920        self.clickable_ranges = ranges;
921        self
922    }
923
924    /// on_hover is called when the mouse moves over a character within the text, passing the
925    /// index of the hovered character, or None if the mouse leaves the text.
926    pub fn on_hover(
927        mut self,
928        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
929    ) -> Self {
930        self.hover_listener = Some(Box::new(listener));
931        self
932    }
933
934    /// tooltip lets you specify a tooltip for a given character index in the string.
935    pub fn tooltip(
936        mut self,
937        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
938    ) -> Self {
939        self.tooltip_builder = Some(Rc::new(builder));
940        self
941    }
942}
943
944impl Element for InteractiveText {
945    type RequestLayoutState = ();
946    type PrepaintState = Hitbox;
947
948    fn id(&self) -> Option<ElementId> {
949        Some(self.element_id.clone())
950    }
951
952    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
953        None
954    }
955
956    fn a11y_role(&self) -> Option<accesskit::Role> {
957        Some(accesskit::Role::Label)
958    }
959
960    fn write_a11y_info(&self, node: &mut accesskit::Node) {
961        node.set_value(self.text.text.to_string());
962    }
963
964    fn request_layout(
965        &mut self,
966        _id: Option<&GlobalElementId>,
967        inspector_id: Option<&InspectorElementId>,
968        window: &mut Window,
969        cx: &mut App,
970    ) -> (LayoutId, Self::RequestLayoutState) {
971        self.text.request_layout(None, inspector_id, window, cx)
972    }
973
974    fn prepaint(
975        &mut self,
976        global_id: Option<&GlobalElementId>,
977        inspector_id: Option<&InspectorElementId>,
978        bounds: Bounds<Pixels>,
979        state: &mut Self::RequestLayoutState,
980        window: &mut Window,
981        cx: &mut App,
982    ) -> Hitbox {
983        window.with_optional_element_state::<InteractiveTextState, _>(
984            global_id,
985            |interactive_state, window| {
986                let mut interactive_state = interactive_state
987                    .map(|interactive_state| interactive_state.unwrap_or_default());
988
989                if let Some(interactive_state) = interactive_state.as_mut() {
990                    if self.tooltip_builder.is_some() {
991                        self.tooltip_id =
992                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
993                    } else {
994                        // If there is no longer a tooltip builder, remove the active tooltip.
995                        interactive_state.long_press_tooltip_active.set(false);
996                        interactive_state.active_tooltip.take();
997                    }
998                }
999
1000                self.text
1001                    .prepaint(None, inspector_id, bounds, state, window, cx);
1002                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1003                crate::fast::interactive_text::insert_clickable_hitboxes(
1004                    &mut self.fast_clickable_hitboxes,
1005                    self.text.layout(),
1006                    &self.clickable_ranges,
1007                    window,
1008                );
1009                (hitbox, interactive_state)
1010            },
1011        )
1012    }
1013
1014    fn paint(
1015        &mut self,
1016        global_id: Option<&GlobalElementId>,
1017        inspector_id: Option<&InspectorElementId>,
1018        bounds: Bounds<Pixels>,
1019        _: &mut Self::RequestLayoutState,
1020        hitbox: &mut Hitbox,
1021        window: &mut Window,
1022        cx: &mut App,
1023    ) {
1024        let current_view = window.current_view();
1025        let text_layout = self.text.layout().clone();
1026        window.with_element_state::<InteractiveTextState, _>(
1027            global_id.unwrap(),
1028            |interactive_state, window| {
1029                let interactive_state = interactive_state.unwrap_or_default();
1030                if let Some(click_listener) = self.click_listener.take() {
1031                    crate::fast::interactive_text::set_clickable_cursor(
1032                        &self.fast_clickable_hitboxes,
1033                        window,
1034                    );
1035
1036                    let text_layout = text_layout.clone();
1037                    let mouse_down = interactive_state.mouse_down_index.clone();
1038                    if let Some(mouse_down_index) = mouse_down.get() {
1039                        let hitbox = hitbox.clone();
1040                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
1041                        window.on_mouse_event(
1042                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
1043                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1044                                    if let Ok(mouse_up_index) =
1045                                        text_layout.index_for_position(event.position)
1046                                    {
1047                                        click_listener(
1048                                            &clickable_ranges,
1049                                            InteractiveTextClickEvent {
1050                                                mouse_down_index,
1051                                                mouse_up_index,
1052                                            },
1053                                            window,
1054                                            cx,
1055                                        )
1056                                    }
1057
1058                                    mouse_down.take();
1059                                    window.refresh();
1060                                }
1061                            },
1062                        );
1063                    } else {
1064                        let hitbox = hitbox.clone();
1065                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
1066                            if phase == DispatchPhase::Bubble
1067                                && hitbox.is_hovered(window)
1068                                && let Ok(mouse_down_index) =
1069                                    text_layout.index_for_position(event.position)
1070                            {
1071                                mouse_down.set(Some(mouse_down_index));
1072                                window.refresh();
1073                            }
1074                        });
1075                    }
1076                }
1077
1078                window.on_mouse_event({
1079                    let hover_listener = self.hover_listener.take();
1080                    let hitbox = hitbox.clone();
1081                    let text_layout = text_layout.clone();
1082                    let hovered_index = interactive_state.hovered_index.clone();
1083                    move |event: &MouseMoveEvent, phase, window, cx| {
1084                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1085                            let current = hovered_index.get();
1086                            let updated = text_layout.index_for_position(event.position).ok();
1087                            if current != updated {
1088                                hovered_index.set(updated);
1089                                if let Some(hover_listener) = hover_listener.as_ref() {
1090                                    hover_listener(updated, event.clone(), window, cx);
1091                                }
1092                                crate::fast::interactive_text::notify_hovered_index(
1093                                    hover_listener.is_some(),
1094                                    current_view,
1095                                    cx,
1096                                );
1097                            }
1098                        }
1099                    }
1100                });
1101
1102                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
1103                    let active_tooltip = interactive_state.active_tooltip.clone();
1104                    let build_tooltip = Rc::new({
1105                        let tooltip_is_hoverable = false;
1106                        let text_layout = text_layout.clone();
1107                        move |window: &mut Window, cx: &mut App| {
1108                            text_layout
1109                                .index_for_position(window.mouse_position())
1110                                .ok()
1111                                .and_then(|position| tooltip_builder(position, window, cx))
1112                                .map(|view| (view, tooltip_is_hoverable))
1113                        }
1114                    });
1115
1116                    // Use bounds instead of testing hitbox since this is called during prepaint.
1117                    let check_is_hovered_during_prepaint = Rc::new({
1118                        let source_bounds = hitbox.bounds;
1119                        let text_layout = text_layout.clone();
1120                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1121                        move |window: &Window| {
1122                            text_layout
1123                                .index_for_position(window.mouse_position())
1124                                .is_ok()
1125                                && source_bounds.contains(&window.mouse_position())
1126                                && pending_mouse_down.get().is_none()
1127                        }
1128                    });
1129
1130                    let check_is_hovered = Rc::new({
1131                        let hitbox = hitbox.clone();
1132                        let text_layout = text_layout.clone();
1133                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1134                        move |window: &Window| {
1135                            text_layout
1136                                .index_for_position(window.mouse_position())
1137                                .is_ok()
1138                                && hitbox.is_hovered(window)
1139                                && pending_mouse_down.get().is_none()
1140                        }
1141                    });
1142
1143                    register_tooltip_mouse_handlers(
1144                        &active_tooltip,
1145                        self.tooltip_id,
1146                        build_tooltip,
1147                        check_is_hovered,
1148                        check_is_hovered_during_prepaint,
1149                        interactive_state.long_press_tooltip_active.clone(),
1150                        None,
1151                        window,
1152                    );
1153                }
1154
1155                self.text
1156                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
1157
1158                ((), interactive_state)
1159            },
1160        );
1161    }
1162}
1163
1164impl IntoElement for InteractiveText {
1165    type Element = Self;
1166
1167    fn into_element(self) -> Self::Element {
1168        self
1169    }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use super::*;
1175
1176    #[test]
1177    fn test_into_element_for() {
1178        use crate::{ParentElement as _, SharedString, div};
1179        use std::borrow::Cow;
1180
1181        let _ = div().child("static str");
1182        let _ = div().child("String".to_string());
1183        let _ = div().child(Cow::Borrowed("Cow"));
1184        let _ = div().child(SharedString::from("SharedString"));
1185    }
1186
1187    #[test]
1188    fn text_macro_id() {
1189        // one call to `text!` = one id
1190        fn make_text_stable_id(happy: bool) -> Text {
1191            text!(if happy { "happy" } else { "sad" })
1192        }
1193
1194        // two calls to `text!` = two ids
1195        fn make_text_unstable_id(happy: bool) -> Text {
1196            if happy { text!("happy") } else { text!("sad") }
1197        }
1198
1199        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
1200        assert_ne!(
1201            make_text_unstable_id(false).id,
1202            make_text_unstable_id(true).id
1203        );
1204    }
1205}