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 Element for Text {
171    type RequestLayoutState = TextLayout;
172    type PrepaintState = ();
173
174    fn id(&self) -> Option<ElementId> {
175        self.id.clone()
176    }
177
178    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
179        None
180    }
181
182    fn a11y_role(&self) -> Option<accesskit::Role> {
183        if self.id.is_some() {
184            Some(accesskit::Role::Label)
185        } else {
186            None
187        }
188    }
189
190    fn write_a11y_info(&self, node: &mut accesskit::Node) {
191        node.set_value(self.text.to_string());
192    }
193
194    fn request_layout(
195        &mut self,
196        id: Option<&GlobalElementId>,
197        inspector_id: Option<&InspectorElementId>,
198        window: &mut Window,
199        cx: &mut App,
200    ) -> (LayoutId, Self::RequestLayoutState) {
201        <SharedString as Element>::request_layout(&mut self.text, id, inspector_id, window, cx)
202    }
203
204    fn prepaint(
205        &mut self,
206        id: Option<&GlobalElementId>,
207        inspector_id: Option<&InspectorElementId>,
208        bounds: Bounds<Pixels>,
209        request_layout: &mut Self::RequestLayoutState,
210        window: &mut Window,
211        cx: &mut App,
212    ) -> Self::PrepaintState {
213        <SharedString as Element>::prepaint(
214            &mut self.text,
215            id,
216            inspector_id,
217            bounds,
218            request_layout,
219            window,
220            cx,
221        )
222    }
223
224    fn paint(
225        &mut self,
226        id: Option<&GlobalElementId>,
227        inspector_id: Option<&InspectorElementId>,
228        bounds: Bounds<Pixels>,
229        request_layout: &mut Self::RequestLayoutState,
230        prepaint: &mut Self::PrepaintState,
231        window: &mut Window,
232        cx: &mut App,
233    ) {
234        <SharedString as Element>::paint(
235            &mut self.text,
236            id,
237            inspector_id,
238            bounds,
239            request_layout,
240            prepaint,
241            window,
242            cx,
243        );
244    }
245}
246
247impl Element for &'static str {
248    type RequestLayoutState = TextLayout;
249    type PrepaintState = ();
250
251    fn id(&self) -> Option<ElementId> {
252        None
253    }
254
255    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
256        None
257    }
258
259    fn request_layout(
260        &mut self,
261        _id: Option<&GlobalElementId>,
262        _inspector_id: Option<&InspectorElementId>,
263        window: &mut Window,
264        cx: &mut App,
265    ) -> (LayoutId, Self::RequestLayoutState) {
266        let state = TextLayout::default();
267        let layout_id = state.layout(SharedString::new_static(self), None, window, cx);
268        (layout_id, state)
269    }
270
271    fn prepaint(
272        &mut self,
273        _id: Option<&GlobalElementId>,
274        _inspector_id: Option<&InspectorElementId>,
275        bounds: Bounds<Pixels>,
276        text_layout: &mut Self::RequestLayoutState,
277        _window: &mut Window,
278        _cx: &mut App,
279    ) {
280        crate::fast::text::prepaint_text(text_layout, bounds, self, _window, _cx)
281    }
282
283    fn paint(
284        &mut self,
285        _id: Option<&GlobalElementId>,
286        _inspector_id: Option<&InspectorElementId>,
287        _bounds: Bounds<Pixels>,
288        text_layout: &mut TextLayout,
289        _: &mut (),
290        window: &mut Window,
291        cx: &mut App,
292    ) {
293        text_layout.paint(self, window, cx)
294    }
295}
296
297impl IntoElement for String {
298    type Element = SharedString;
299
300    fn into_element(self) -> Self::Element {
301        self.into()
302    }
303}
304
305impl IntoElement for Cow<'static, str> {
306    type Element = SharedString;
307
308    fn into_element(self) -> Self::Element {
309        self.into()
310    }
311}
312
313impl Element for SharedString {
314    type RequestLayoutState = TextLayout;
315    type PrepaintState = ();
316
317    fn id(&self) -> Option<ElementId> {
318        None
319    }
320
321    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
322        None
323    }
324
325    fn request_layout(
326        &mut self,
327        _id: Option<&GlobalElementId>,
328        _inspector_id: Option<&InspectorElementId>,
329        window: &mut Window,
330        cx: &mut App,
331    ) -> (LayoutId, Self::RequestLayoutState) {
332        let state = TextLayout::default();
333        let layout_id = state.layout(self.clone(), None, window, cx);
334        (layout_id, state)
335    }
336
337    fn prepaint(
338        &mut self,
339        _id: Option<&GlobalElementId>,
340        _inspector_id: Option<&InspectorElementId>,
341        bounds: Bounds<Pixels>,
342        text_layout: &mut Self::RequestLayoutState,
343        _window: &mut Window,
344        _cx: &mut App,
345    ) {
346        crate::fast::text::prepaint_text(text_layout, bounds, self.as_ref(), _window, _cx)
347    }
348
349    fn paint(
350        &mut self,
351        _id: Option<&GlobalElementId>,
352        _inspector_id: Option<&InspectorElementId>,
353        _bounds: Bounds<Pixels>,
354        text_layout: &mut Self::RequestLayoutState,
355        _: &mut Self::PrepaintState,
356        window: &mut Window,
357        cx: &mut App,
358    ) {
359        text_layout.paint(self.as_ref(), window, cx)
360    }
361}
362
363/// Renders text with runs of different styles.
364///
365/// Callers are responsible for setting the correct style for each run.
366/// For text with a uniform style, you can usually avoid calling this constructor
367/// and just pass text directly.
368pub struct StyledText {
369    text: SharedString,
370    runs: Option<Vec<TextRun>>,
371    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
372    delayed_font_family_overrides: Option<Vec<(Range<usize>, SharedString)>>,
373    layout: TextLayout,
374}
375
376impl StyledText {
377    /// Construct a new styled text element from the given string.
378    pub fn new(text: impl Into<SharedString>) -> Self {
379        StyledText {
380            text: text.into(),
381            runs: None,
382            delayed_highlights: None,
383            delayed_font_family_overrides: None,
384            layout: TextLayout::default(),
385        }
386    }
387
388    /// Get the layout for this element. This can be used to map indices to pixels and vice versa.
389    pub fn layout(&self) -> &TextLayout {
390        &self.layout
391    }
392
393    /// Set the styling attributes for the given text, as well as
394    /// as any ranges of text that have had their style customized.
395    pub fn with_default_highlights(
396        self,
397        default_style: &TextStyle,
398        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
399    ) -> Self {
400        debug_assert!(
401            self.delayed_highlights.is_none(),
402            "Can't use `with_default_highlights` and `with_highlights`"
403        );
404        let runs = Self::compute_runs(&self.text, default_style, highlights);
405        self.with_runs(runs)
406    }
407
408    /// Set the styling attributes for the given text, as well as
409    /// as any ranges of text that have had their style customized.
410    pub fn with_highlights(
411        mut self,
412        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
413    ) -> Self {
414        debug_assert!(
415            self.runs.is_none(),
416            "Can't use `with_highlights` and `with_default_highlights`"
417        );
418        self.delayed_highlights = Some(
419            highlights
420                .into_iter()
421                .inspect(|(run, _)| {
422                    debug_assert!(self.text.is_char_boundary(run.start));
423                    debug_assert!(self.text.is_char_boundary(run.end));
424                })
425                .collect::<Vec<_>>(),
426        );
427        self
428    }
429
430    fn compute_runs(
431        text: &str,
432        default_style: &TextStyle,
433        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
434    ) -> Vec<TextRun> {
435        let mut runs = Vec::new();
436        let mut ix = 0;
437        for (range, highlight) in highlights {
438            if ix < range.start {
439                debug_assert!(text.is_char_boundary(range.start));
440                runs.push(default_style.clone().to_run(range.start - ix));
441            }
442            debug_assert!(text.is_char_boundary(range.end));
443            runs.push(
444                default_style
445                    .clone()
446                    .highlight(highlight)
447                    .to_run(range.len()),
448            );
449            ix = range.end;
450        }
451        if ix < text.len() {
452            runs.push(default_style.to_run(text.len() - ix));
453        }
454        runs
455    }
456
457    /// Override the font family for specific byte ranges of the text.
458    ///
459    /// This is resolved lazily at layout time, so the overrides are applied
460    /// on top of the inherited text style from the parent element.
461    /// Can be combined with [`with_highlights`](Self::with_highlights).
462    ///
463    /// The overrides must be sorted by range start and non-overlapping.
464    /// Each override range must fall on character boundaries.
465    pub fn with_font_family_overrides(
466        mut self,
467        overrides: impl IntoIterator<Item = (Range<usize>, SharedString)>,
468    ) -> Self {
469        self.delayed_font_family_overrides = Some(
470            overrides
471                .into_iter()
472                .inspect(|(range, _)| {
473                    debug_assert!(self.text.is_char_boundary(range.start));
474                    debug_assert!(self.text.is_char_boundary(range.end));
475                })
476                .collect(),
477        );
478        self
479    }
480
481    fn apply_font_family_overrides(
482        runs: &mut [TextRun],
483        overrides: &[(Range<usize>, SharedString)],
484    ) {
485        let mut byte_offset = 0;
486        let mut override_idx = 0;
487        for run in runs.iter_mut() {
488            let run_end = byte_offset + run.len;
489            while override_idx < overrides.len() && overrides[override_idx].0.end <= byte_offset {
490                override_idx += 1;
491            }
492            if override_idx < overrides.len() {
493                let (ref range, ref family) = overrides[override_idx];
494                if byte_offset >= range.start && run_end <= range.end {
495                    run.font.family = family.clone();
496                }
497            }
498            byte_offset = run_end;
499        }
500    }
501
502    /// Set the text runs for this piece of text.
503    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
504        let mut text = &*self.text;
505        for run in &runs {
506            text = text.get(run.len..).unwrap_or_else(|| {
507                #[cfg(debug_assertions)]
508                panic!("invalid text run. Text: '{text}', run: {run:?}");
509                #[cfg(not(debug_assertions))]
510                panic!("invalid text run");
511            });
512        }
513        assert!(text.is_empty(), "invalid text run");
514        self.runs = Some(runs);
515        self
516    }
517}
518
519impl Element for StyledText {
520    type RequestLayoutState = ();
521    type PrepaintState = ();
522
523    fn id(&self) -> Option<ElementId> {
524        None
525    }
526
527    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
528        None
529    }
530
531    fn request_layout(
532        &mut self,
533        _id: Option<&GlobalElementId>,
534        _inspector_id: Option<&InspectorElementId>,
535        window: &mut Window,
536        cx: &mut App,
537    ) -> (LayoutId, Self::RequestLayoutState) {
538        let font_family_overrides = self.delayed_font_family_overrides.take();
539        let mut runs = self.runs.take().or_else(|| {
540            self.delayed_highlights.take().map(|delayed_highlights| {
541                Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
542            })
543        });
544
545        if let Some(ref overrides) = font_family_overrides {
546            let runs =
547                runs.get_or_insert_with(|| vec![window.text_style().to_run(self.text.len())]);
548            Self::apply_font_family_overrides(runs, overrides);
549        }
550
551        let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
552        (layout_id, ())
553    }
554
555    fn prepaint(
556        &mut self,
557        _id: Option<&GlobalElementId>,
558        _inspector_id: Option<&InspectorElementId>,
559        bounds: Bounds<Pixels>,
560        _: &mut Self::RequestLayoutState,
561        _window: &mut Window,
562        _cx: &mut App,
563    ) {
564        crate::fast::text::prepaint_text(&self.layout, bounds, &self.text, _window, _cx)
565    }
566
567    fn paint(
568        &mut self,
569        _id: Option<&GlobalElementId>,
570        _inspector_id: Option<&InspectorElementId>,
571        _bounds: Bounds<Pixels>,
572        _: &mut Self::RequestLayoutState,
573        _: &mut Self::PrepaintState,
574        window: &mut Window,
575        cx: &mut App,
576    ) {
577        self.layout.paint(&self.text, window, cx)
578    }
579}
580
581/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
582#[derive(Default, Clone)]
583pub struct TextLayout(pub(crate) Rc<RefCell<Option<TextLayoutInner>>>);
584
585#[derive(Clone, Copy)]
586enum TextPaintPass {
587    All,
588    Background,
589    Foreground,
590}
591
592pub(crate) struct TextLayoutInner {
593    pub(crate) len: usize,
594    pub(crate) lines: SmallVec<[WrappedLine; 1]>,
595    pub(crate) line_height: Pixels,
596    pub(crate) wrap_width: Option<Pixels>,
597    pub(crate) truncate_width: Option<Pixels>,
598    pub(crate) size: Option<Size<Pixels>>,
599    pub(crate) bounds: Option<Bounds<Pixels>>,
600}
601
602impl TextLayout {
603    fn layout(
604        &self,
605        text: SharedString,
606        runs: Option<Vec<TextRun>>,
607        window: &mut Window,
608        fast_cx: &mut App,
609    ) -> LayoutId {
610        crate::fast::text::layout_text(self, text, runs, window, fast_cx)
611    }
612
613    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
614        if !crate::fast::text::paintable(self, text) {
615            return;
616        }
617        self.paint_lines(TextPaintPass::All, window, cx)
618            .with_context(|| format!("failed to paint {text}"))
619            .unwrap();
620    }
621
622    /// Paints the backgrounds of the text runs without the glyphs, so that callers can paint
623    /// content, such as highlights, between the backgrounds and the text. Follow it with
624    /// [`Self::paint_foreground`] to paint the glyphs.
625    pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
626        self.paint_lines(TextPaintPass::Background, window, cx)
627    }
628
629    /// Paints the glyphs and decorations of the text without the run backgrounds.
630    pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
631        self.paint_lines(TextPaintPass::Foreground, window, cx)
632    }
633
634    fn paint_lines(
635        &self,
636        pass: TextPaintPass,
637        window: &mut Window,
638        cx: &mut App,
639    ) -> anyhow::Result<()> {
640        let element_state = self.0.borrow();
641        let element_state = element_state
642            .as_ref()
643            .context("measurement has not been performed")?;
644        let bounds = element_state
645            .bounds
646            .context("prepaint has not been performed")?;
647
648        let line_height = element_state.line_height;
649        let mut line_origin = bounds.origin;
650        let text_style = crate::fast::text_style::text_paint_style(window);
651        for line in &element_state.lines {
652            if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {
653                line.paint_background(
654                    line_origin,
655                    line_height,
656                    text_style.text_align,
657                    Some(bounds),
658                    window,
659                    cx,
660                )
661                .log_err();
662            }
663            if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {
664                line.paint(
665                    line_origin,
666                    line_height,
667                    text_style.text_align,
668                    Some(bounds),
669                    window,
670                    cx,
671                )
672                .log_err();
673            }
674            line_origin.y += line.size(line_height).height;
675        }
676        Ok(())
677    }
678
679    /// Get the byte index into the input of the pixel position.
680    pub fn index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
681        let element_state = self.0.borrow();
682        let element_state = element_state
683            .as_ref()
684            .expect("measurement has not been performed");
685        let bounds = element_state
686            .bounds
687            .expect("prepaint has not been performed");
688
689        if position.y < bounds.top() {
690            return Err(0);
691        }
692
693        let line_height = element_state.line_height;
694        let mut line_origin = bounds.origin;
695        let mut line_start_ix = 0;
696        for line in &element_state.lines {
697            let line_bottom = line_origin.y + line.size(line_height).height;
698            if position.y > line_bottom {
699                line_origin.y = line_bottom;
700                line_start_ix += line.len() + 1;
701            } else {
702                let position_within_line = position - line_origin;
703                match line.index_for_position(position_within_line, line_height) {
704                    Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
705                    Err(index_within_line) => return Err(line_start_ix + index_within_line),
706                }
707            }
708        }
709
710        Err(line_start_ix.saturating_sub(1))
711    }
712
713    /// Get the pixel position for the given byte index.
714    pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
715        let element_state = self.0.borrow();
716        let element_state = element_state
717            .as_ref()
718            .expect("measurement has not been performed");
719        let bounds = element_state
720            .bounds
721            .expect("prepaint has not been performed");
722        let line_height = element_state.line_height;
723
724        let mut line_origin = bounds.origin;
725        let mut line_start_ix = 0;
726
727        for line in &element_state.lines {
728            let line_end_ix = line_start_ix + line.len();
729            if index < line_start_ix {
730                break;
731            } else if index > line_end_ix {
732                line_origin.y += line.size(line_height).height;
733                line_start_ix = line_end_ix + 1;
734                continue;
735            } else {
736                let ix_within_line = index - line_start_ix;
737                return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
738            }
739        }
740
741        None
742    }
743
744    /// Retrieve the layout for the line containing the given byte index.
745    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
746        let element_state = self.0.borrow();
747        let element_state = element_state
748            .as_ref()
749            .expect("measurement has not been performed");
750        let mut line_start_ix = 0;
751
752        for line in &element_state.lines {
753            let line_end_ix = line_start_ix + line.len();
754            if index < line_start_ix {
755                break;
756            } else if index > line_end_ix {
757                line_start_ix = line_end_ix + 1;
758                continue;
759            } else {
760                return Some(line.layout.clone());
761            }
762        }
763
764        None
765    }
766
767    /// Retrieve all line layouts in source order.
768    pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {
769        self.0
770            .borrow()
771            .as_ref()
772            .expect("measurement has not been performed")
773            .lines
774            .iter()
775            .map(|line| line.layout.clone())
776            .collect()
777    }
778
779    /// The bounds of this layout.
780    pub fn bounds(&self) -> Bounds<Pixels> {
781        self.0.borrow().as_ref().unwrap().bounds.unwrap()
782    }
783
784    /// The line height for this layout.
785    pub fn line_height(&self) -> Pixels {
786        self.0.borrow().as_ref().unwrap().line_height
787    }
788
789    /// The UTF-8 length of the underlying text.
790    pub fn len(&self) -> usize {
791        self.0.borrow().as_ref().unwrap().len
792    }
793
794    /// The text for this layout.
795    pub fn text(&self) -> String {
796        self.0
797            .borrow()
798            .as_ref()
799            .unwrap()
800            .lines
801            .iter()
802            .map(|s| &s.text)
803            .join("\n")
804    }
805
806    /// The text for this layout (with soft-wraps as newlines)
807    pub fn wrapped_text(&self) -> String {
808        let mut accumulator = String::new();
809
810        for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
811            let mut seen = 0;
812            for boundary in wrapped.layout.wrap_boundaries.iter() {
813                let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
814                    [boundary.glyph_ix]
815                    .index;
816
817                accumulator.push_str(&wrapped.text[seen..index]);
818                accumulator.push('\n');
819                seen = index;
820            }
821            accumulator.push_str(&wrapped.text[seen..]);
822            accumulator.push('\n');
823        }
824        // Remove trailing newline
825        accumulator.pop();
826        accumulator
827    }
828}
829
830/// A text element that can be interacted with.
831pub struct InteractiveText {
832    element_id: ElementId,
833    text: StyledText,
834    click_listener:
835        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
836    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
837    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
838    tooltip_id: Option<TooltipId>,
839    clickable_ranges: Vec<Range<usize>>,
840    fast_clickable_hitboxes: crate::fast::interactive_text::ClickableHitboxes,
841}
842
843struct InteractiveTextClickEvent {
844    mouse_down_index: usize,
845    mouse_up_index: usize,
846}
847
848#[doc(hidden)]
849#[derive(Default)]
850pub struct InteractiveTextState {
851    mouse_down_index: Rc<Cell<Option<usize>>>,
852    hovered_index: Rc<Cell<Option<usize>>>,
853    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
854    long_press_tooltip_active: Rc<Cell<bool>>,
855}
856
857/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
858impl InteractiveText {
859    /// Creates a new InteractiveText from the given text.
860    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
861        Self {
862            element_id: id.into(),
863            text,
864            click_listener: None,
865            hover_listener: None,
866            tooltip_builder: None,
867            tooltip_id: None,
868            clickable_ranges: Vec::new(),
869            fast_clickable_hitboxes: crate::fast::interactive_text::ClickableHitboxes::default(),
870        }
871    }
872
873    /// on_click is called when the user clicks on one of the given ranges, passing the index of
874    /// the clicked range.
875    pub fn on_click(
876        mut self,
877        ranges: Vec<Range<usize>>,
878        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
879    ) -> Self {
880        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
881            for (range_ix, range) in ranges.iter().enumerate() {
882                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
883                {
884                    listener(range_ix, window, cx);
885                }
886            }
887        }));
888        self.clickable_ranges = ranges;
889        self
890    }
891
892    /// on_hover is called when the mouse moves over a character within the text, passing the
893    /// index of the hovered character, or None if the mouse leaves the text.
894    pub fn on_hover(
895        mut self,
896        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
897    ) -> Self {
898        self.hover_listener = Some(Box::new(listener));
899        self
900    }
901
902    /// tooltip lets you specify a tooltip for a given character index in the string.
903    pub fn tooltip(
904        mut self,
905        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
906    ) -> Self {
907        self.tooltip_builder = Some(Rc::new(builder));
908        self
909    }
910}
911
912impl Element for InteractiveText {
913    type RequestLayoutState = ();
914    type PrepaintState = Hitbox;
915
916    fn id(&self) -> Option<ElementId> {
917        Some(self.element_id.clone())
918    }
919
920    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
921        None
922    }
923
924    fn a11y_role(&self) -> Option<accesskit::Role> {
925        Some(accesskit::Role::Label)
926    }
927
928    fn write_a11y_info(&self, node: &mut accesskit::Node) {
929        node.set_value(self.text.text.to_string());
930    }
931
932    fn request_layout(
933        &mut self,
934        _id: Option<&GlobalElementId>,
935        inspector_id: Option<&InspectorElementId>,
936        window: &mut Window,
937        cx: &mut App,
938    ) -> (LayoutId, Self::RequestLayoutState) {
939        self.text.request_layout(None, inspector_id, window, cx)
940    }
941
942    fn prepaint(
943        &mut self,
944        global_id: Option<&GlobalElementId>,
945        inspector_id: Option<&InspectorElementId>,
946        bounds: Bounds<Pixels>,
947        state: &mut Self::RequestLayoutState,
948        window: &mut Window,
949        cx: &mut App,
950    ) -> Hitbox {
951        window.with_optional_element_state::<InteractiveTextState, _>(
952            global_id,
953            |interactive_state, window| {
954                let mut interactive_state = interactive_state
955                    .map(|interactive_state| interactive_state.unwrap_or_default());
956
957                if let Some(interactive_state) = interactive_state.as_mut() {
958                    if self.tooltip_builder.is_some() {
959                        self.tooltip_id =
960                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
961                    } else {
962                        // If there is no longer a tooltip builder, remove the active tooltip.
963                        interactive_state.long_press_tooltip_active.set(false);
964                        interactive_state.active_tooltip.take();
965                    }
966                }
967
968                self.text
969                    .prepaint(None, inspector_id, bounds, state, window, cx);
970                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
971                crate::fast::interactive_text::insert_clickable_hitboxes(
972                    &mut self.fast_clickable_hitboxes,
973                    self.text.layout(),
974                    &self.clickable_ranges,
975                    window,
976                );
977                (hitbox, interactive_state)
978            },
979        )
980    }
981
982    fn paint(
983        &mut self,
984        global_id: Option<&GlobalElementId>,
985        inspector_id: Option<&InspectorElementId>,
986        bounds: Bounds<Pixels>,
987        _: &mut Self::RequestLayoutState,
988        hitbox: &mut Hitbox,
989        window: &mut Window,
990        cx: &mut App,
991    ) {
992        let current_view = window.current_view();
993        let text_layout = self.text.layout().clone();
994        window.with_element_state::<InteractiveTextState, _>(
995            global_id.unwrap(),
996            |interactive_state, window| {
997                let interactive_state = interactive_state.unwrap_or_default();
998                if let Some(click_listener) = self.click_listener.take() {
999                    crate::fast::interactive_text::set_clickable_cursor(
1000                        &self.fast_clickable_hitboxes,
1001                        window,
1002                    );
1003
1004                    let text_layout = text_layout.clone();
1005                    let mouse_down = interactive_state.mouse_down_index.clone();
1006                    if let Some(mouse_down_index) = mouse_down.get() {
1007                        let hitbox = hitbox.clone();
1008                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
1009                        window.on_mouse_event(
1010                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
1011                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1012                                    if let Ok(mouse_up_index) =
1013                                        text_layout.index_for_position(event.position)
1014                                    {
1015                                        click_listener(
1016                                            &clickable_ranges,
1017                                            InteractiveTextClickEvent {
1018                                                mouse_down_index,
1019                                                mouse_up_index,
1020                                            },
1021                                            window,
1022                                            cx,
1023                                        )
1024                                    }
1025
1026                                    mouse_down.take();
1027                                    window.refresh();
1028                                }
1029                            },
1030                        );
1031                    } else {
1032                        let hitbox = hitbox.clone();
1033                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
1034                            if phase == DispatchPhase::Bubble
1035                                && hitbox.is_hovered(window)
1036                                && let Ok(mouse_down_index) =
1037                                    text_layout.index_for_position(event.position)
1038                            {
1039                                mouse_down.set(Some(mouse_down_index));
1040                                window.refresh();
1041                            }
1042                        });
1043                    }
1044                }
1045
1046                window.on_mouse_event({
1047                    let hover_listener = self.hover_listener.take();
1048                    let hitbox = hitbox.clone();
1049                    let text_layout = text_layout.clone();
1050                    let hovered_index = interactive_state.hovered_index.clone();
1051                    move |event: &MouseMoveEvent, phase, window, cx| {
1052                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
1053                            let current = hovered_index.get();
1054                            let updated = text_layout.index_for_position(event.position).ok();
1055                            if current != updated {
1056                                hovered_index.set(updated);
1057                                if let Some(hover_listener) = hover_listener.as_ref() {
1058                                    hover_listener(updated, event.clone(), window, cx);
1059                                }
1060                                crate::fast::interactive_text::notify_hovered_index(
1061                                    hover_listener.is_some(),
1062                                    current_view,
1063                                    cx,
1064                                );
1065                            }
1066                        }
1067                    }
1068                });
1069
1070                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
1071                    let active_tooltip = interactive_state.active_tooltip.clone();
1072                    let build_tooltip = Rc::new({
1073                        let tooltip_is_hoverable = false;
1074                        let text_layout = text_layout.clone();
1075                        move |window: &mut Window, cx: &mut App| {
1076                            text_layout
1077                                .index_for_position(window.mouse_position())
1078                                .ok()
1079                                .and_then(|position| tooltip_builder(position, window, cx))
1080                                .map(|view| (view, tooltip_is_hoverable))
1081                        }
1082                    });
1083
1084                    // Use bounds instead of testing hitbox since this is called during prepaint.
1085                    let check_is_hovered_during_prepaint = Rc::new({
1086                        let source_bounds = hitbox.bounds;
1087                        let text_layout = text_layout.clone();
1088                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1089                        move |window: &Window| {
1090                            text_layout
1091                                .index_for_position(window.mouse_position())
1092                                .is_ok()
1093                                && source_bounds.contains(&window.mouse_position())
1094                                && pending_mouse_down.get().is_none()
1095                        }
1096                    });
1097
1098                    let check_is_hovered = Rc::new({
1099                        let hitbox = hitbox.clone();
1100                        let text_layout = text_layout.clone();
1101                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
1102                        move |window: &Window| {
1103                            text_layout
1104                                .index_for_position(window.mouse_position())
1105                                .is_ok()
1106                                && hitbox.is_hovered(window)
1107                                && pending_mouse_down.get().is_none()
1108                        }
1109                    });
1110
1111                    register_tooltip_mouse_handlers(
1112                        &active_tooltip,
1113                        self.tooltip_id,
1114                        build_tooltip,
1115                        check_is_hovered,
1116                        check_is_hovered_during_prepaint,
1117                        interactive_state.long_press_tooltip_active.clone(),
1118                        None,
1119                        window,
1120                    );
1121                }
1122
1123                self.text
1124                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
1125
1126                ((), interactive_state)
1127            },
1128        );
1129    }
1130}
1131
1132#[cfg(test)]
1133mod tests {
1134    use super::*;
1135
1136    #[test]
1137    fn test_into_element_for() {
1138        use crate::{ParentElement as _, SharedString, div};
1139        use std::borrow::Cow;
1140
1141        let _ = div().child("static str");
1142        let _ = div().child("String".to_string());
1143        let _ = div().child(Cow::Borrowed("Cow"));
1144        let _ = div().child(SharedString::from("SharedString"));
1145    }
1146
1147    #[test]
1148    fn text_macro_id() {
1149        // one call to `text!` = one id
1150        fn make_text_stable_id(happy: bool) -> Text {
1151            text!(if happy { "happy" } else { "sad" })
1152        }
1153
1154        // two calls to `text!` = two ids
1155        fn make_text_unstable_id(happy: bool) -> Text {
1156            if happy { text!("happy") } else { text!("sad") }
1157        }
1158
1159        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
1160        assert_ne!(
1161            make_text_unstable_id(false).id,
1162            make_text_unstable_id(true).id
1163        );
1164    }
1165}