Skip to main content

gpui/elements/
text.rs

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