text.rs

  1use crate::{
  2    ActiveTooltip, AnyTooltip, AnyView, Bounds, DispatchPhase, Element, ElementContext, ElementId,
  3    HighlightStyle, IntoElement, LayoutId, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
  4    Point, SharedString, Size, TextRun, TextStyle, WhiteSpace, WindowContext, WrappedLine,
  5    TOOLTIP_DELAY,
  6};
  7use anyhow::anyhow;
  8use parking_lot::{Mutex, MutexGuard};
  9use smallvec::SmallVec;
 10use std::{
 11    cell::{Cell, RefCell},
 12    mem,
 13    ops::Range,
 14    rc::Rc,
 15    sync::Arc,
 16};
 17use util::ResultExt;
 18
 19impl Element for &'static str {
 20    type State = TextState;
 21
 22    fn request_layout(
 23        &mut self,
 24        _: Option<Self::State>,
 25        cx: &mut ElementContext,
 26    ) -> (LayoutId, Self::State) {
 27        let mut state = TextState::default();
 28        let layout_id = state.layout(SharedString::from(*self), None, cx);
 29        (layout_id, state)
 30    }
 31
 32    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut TextState, cx: &mut ElementContext) {
 33        state.paint(bounds, self, cx)
 34    }
 35}
 36
 37impl IntoElement for &'static str {
 38    type Element = Self;
 39
 40    fn element_id(&self) -> Option<ElementId> {
 41        None
 42    }
 43
 44    fn into_element(self) -> Self::Element {
 45        self
 46    }
 47}
 48
 49impl Element for SharedString {
 50    type State = TextState;
 51
 52    fn request_layout(
 53        &mut self,
 54        _: Option<Self::State>,
 55        cx: &mut ElementContext,
 56    ) -> (LayoutId, Self::State) {
 57        let mut state = TextState::default();
 58        let layout_id = state.layout(self.clone(), None, cx);
 59        (layout_id, state)
 60    }
 61
 62    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut TextState, cx: &mut ElementContext) {
 63        let text_str: &str = self.as_ref();
 64        state.paint(bounds, text_str, cx)
 65    }
 66}
 67
 68impl IntoElement for SharedString {
 69    type Element = Self;
 70
 71    fn element_id(&self) -> Option<ElementId> {
 72        None
 73    }
 74
 75    fn into_element(self) -> Self::Element {
 76        self
 77    }
 78}
 79
 80/// Renders text with runs of different styles.
 81///
 82/// Callers are responsible for setting the correct style for each run.
 83/// For text with a uniform style, you can usually avoid calling this constructor
 84/// and just pass text directly.
 85pub struct StyledText {
 86    text: SharedString,
 87    runs: Option<Vec<TextRun>>,
 88}
 89
 90impl StyledText {
 91    /// Construct a new styled text element from the given string.
 92    pub fn new(text: impl Into<SharedString>) -> Self {
 93        StyledText {
 94            text: text.into(),
 95            runs: None,
 96        }
 97    }
 98
 99    /// Set the styling attributes for the given text, as well as
100    /// as any ranges of text that have had their style customized.
101    pub fn with_highlights(
102        mut self,
103        default_style: &TextStyle,
104        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
105    ) -> Self {
106        let mut runs = Vec::new();
107        let mut ix = 0;
108        for (range, highlight) in highlights {
109            if ix < range.start {
110                runs.push(default_style.clone().to_run(range.start - ix));
111            }
112            runs.push(
113                default_style
114                    .clone()
115                    .highlight(highlight)
116                    .to_run(range.len()),
117            );
118            ix = range.end;
119        }
120        if ix < self.text.len() {
121            runs.push(default_style.to_run(self.text.len() - ix));
122        }
123        self.runs = Some(runs);
124        self
125    }
126}
127
128impl Element for StyledText {
129    type State = TextState;
130
131    fn request_layout(
132        &mut self,
133        _: Option<Self::State>,
134        cx: &mut ElementContext,
135    ) -> (LayoutId, Self::State) {
136        let mut state = TextState::default();
137        let layout_id = state.layout(self.text.clone(), self.runs.take(), cx);
138        (layout_id, state)
139    }
140
141    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut ElementContext) {
142        state.paint(bounds, &self.text, cx)
143    }
144}
145
146impl IntoElement for StyledText {
147    type Element = Self;
148
149    fn element_id(&self) -> Option<crate::ElementId> {
150        None
151    }
152
153    fn into_element(self) -> Self::Element {
154        self
155    }
156}
157
158#[doc(hidden)]
159#[derive(Default, Clone)]
160pub struct TextState(Arc<Mutex<Option<TextStateInner>>>);
161
162struct TextStateInner {
163    lines: SmallVec<[WrappedLine; 1]>,
164    line_height: Pixels,
165    wrap_width: Option<Pixels>,
166    size: Option<Size<Pixels>>,
167}
168
169impl TextState {
170    fn lock(&self) -> MutexGuard<Option<TextStateInner>> {
171        self.0.lock()
172    }
173
174    fn layout(
175        &mut self,
176        text: SharedString,
177        runs: Option<Vec<TextRun>>,
178        cx: &mut ElementContext,
179    ) -> LayoutId {
180        let text_style = cx.text_style();
181        let font_size = text_style.font_size.to_pixels(cx.rem_size());
182        let line_height = text_style
183            .line_height
184            .to_pixels(font_size.into(), cx.rem_size());
185
186        let runs = if let Some(runs) = runs {
187            runs
188        } else {
189            vec![text_style.to_run(text.len())]
190        };
191
192        let layout_id = cx.request_measured_layout(Default::default(), {
193            let element_state = self.clone();
194
195            move |known_dimensions, available_space, cx| {
196                let wrap_width = if text_style.white_space == WhiteSpace::Normal {
197                    known_dimensions.width.or(match available_space.width {
198                        crate::AvailableSpace::Definite(x) => Some(x),
199                        _ => None,
200                    })
201                } else {
202                    None
203                };
204
205                if let Some(text_state) = element_state.0.lock().as_ref() {
206                    if text_state.size.is_some()
207                        && (wrap_width.is_none() || wrap_width == text_state.wrap_width)
208                    {
209                        return text_state.size.unwrap();
210                    }
211                }
212
213                let Some(lines) = cx
214                    .text_system()
215                    .shape_text(
216                        text.clone(),
217                        font_size,
218                        &runs,
219                        wrap_width, // Wrap if we know the width.
220                    )
221                    .log_err()
222                else {
223                    element_state.lock().replace(TextStateInner {
224                        lines: Default::default(),
225                        line_height,
226                        wrap_width,
227                        size: Some(Size::default()),
228                    });
229                    return Size::default();
230                };
231
232                let mut size: Size<Pixels> = Size::default();
233                for line in &lines {
234                    let line_size = line.size(line_height);
235                    size.height += line_size.height;
236                    size.width = size.width.max(line_size.width).ceil();
237                }
238
239                element_state.lock().replace(TextStateInner {
240                    lines,
241                    line_height,
242                    wrap_width,
243                    size: Some(size),
244                });
245
246                size
247            }
248        });
249
250        layout_id
251    }
252
253    fn paint(&mut self, bounds: Bounds<Pixels>, text: &str, cx: &mut ElementContext) {
254        let element_state = self.lock();
255        let element_state = element_state
256            .as_ref()
257            .ok_or_else(|| anyhow!("measurement has not been performed on {}", text))
258            .unwrap();
259
260        let line_height = element_state.line_height;
261        let mut line_origin = bounds.origin;
262        for line in &element_state.lines {
263            line.paint(line_origin, line_height, cx).log_err();
264            line_origin.y += line.size(line_height).height;
265        }
266    }
267
268    fn index_for_position(&self, bounds: Bounds<Pixels>, position: Point<Pixels>) -> Option<usize> {
269        if !bounds.contains(&position) {
270            return None;
271        }
272
273        let element_state = self.lock();
274        let element_state = element_state
275            .as_ref()
276            .expect("measurement has not been performed");
277
278        let line_height = element_state.line_height;
279        let mut line_origin = bounds.origin;
280        let mut line_start_ix = 0;
281        for line in &element_state.lines {
282            let line_bottom = line_origin.y + line.size(line_height).height;
283            if position.y > line_bottom {
284                line_origin.y = line_bottom;
285                line_start_ix += line.len() + 1;
286            } else {
287                let position_within_line = position - line_origin;
288                let index_within_line =
289                    line.index_for_position(position_within_line, line_height)?;
290                return Some(line_start_ix + index_within_line);
291            }
292        }
293
294        None
295    }
296}
297
298/// A text element that can be interacted with.
299pub struct InteractiveText {
300    element_id: ElementId,
301    text: StyledText,
302    click_listener:
303        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut WindowContext<'_>)>>,
304    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut WindowContext<'_>)>>,
305    tooltip_builder: Option<Rc<dyn Fn(usize, &mut WindowContext<'_>) -> Option<AnyView>>>,
306    clickable_ranges: Vec<Range<usize>>,
307}
308
309struct InteractiveTextClickEvent {
310    mouse_down_index: usize,
311    mouse_up_index: usize,
312}
313
314#[doc(hidden)]
315pub struct InteractiveTextState {
316    text_state: TextState,
317    mouse_down_index: Rc<Cell<Option<usize>>>,
318    hovered_index: Rc<Cell<Option<usize>>>,
319    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
320}
321
322/// InteractiveTest is a wrapper around StyledText that adds mouse interactions.
323impl InteractiveText {
324    /// Creates a new InteractiveText from the given text.
325    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
326        Self {
327            element_id: id.into(),
328            text,
329            click_listener: None,
330            hover_listener: None,
331            tooltip_builder: None,
332            clickable_ranges: Vec::new(),
333        }
334    }
335
336    /// on_click is called when the user clicks on one of the given ranges, passing the index of
337    /// the clicked range.
338    pub fn on_click(
339        mut self,
340        ranges: Vec<Range<usize>>,
341        listener: impl Fn(usize, &mut WindowContext<'_>) + 'static,
342    ) -> Self {
343        self.click_listener = Some(Box::new(move |ranges, event, cx| {
344            for (range_ix, range) in ranges.iter().enumerate() {
345                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
346                {
347                    listener(range_ix, cx);
348                }
349            }
350        }));
351        self.clickable_ranges = ranges;
352        self
353    }
354
355    /// on_hover is called when the mouse moves over a character within the text, passing the
356    /// index of the hovered character, or None if the mouse leaves the text.
357    pub fn on_hover(
358        mut self,
359        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut WindowContext<'_>) + 'static,
360    ) -> Self {
361        self.hover_listener = Some(Box::new(listener));
362        self
363    }
364
365    /// tooltip lets you specify a tooltip for a given character index in the string.
366    pub fn tooltip(
367        mut self,
368        builder: impl Fn(usize, &mut WindowContext<'_>) -> Option<AnyView> + 'static,
369    ) -> Self {
370        self.tooltip_builder = Some(Rc::new(builder));
371        self
372    }
373}
374
375impl Element for InteractiveText {
376    type State = InteractiveTextState;
377
378    fn request_layout(
379        &mut self,
380        state: Option<Self::State>,
381        cx: &mut ElementContext,
382    ) -> (LayoutId, Self::State) {
383        if let Some(InteractiveTextState {
384            mouse_down_index,
385            hovered_index,
386            active_tooltip,
387            ..
388        }) = state
389        {
390            let (layout_id, text_state) = self.text.request_layout(None, cx);
391            let element_state = InteractiveTextState {
392                text_state,
393                mouse_down_index,
394                hovered_index,
395                active_tooltip,
396            };
397            (layout_id, element_state)
398        } else {
399            let (layout_id, text_state) = self.text.request_layout(None, cx);
400            let element_state = InteractiveTextState {
401                text_state,
402                mouse_down_index: Rc::default(),
403                hovered_index: Rc::default(),
404                active_tooltip: Rc::default(),
405            };
406            (layout_id, element_state)
407        }
408    }
409
410    fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut ElementContext) {
411        if let Some(click_listener) = self.click_listener.take() {
412            let mouse_position = cx.mouse_position();
413            if let Some(ix) = state.text_state.index_for_position(bounds, mouse_position) {
414                if self
415                    .clickable_ranges
416                    .iter()
417                    .any(|range| range.contains(&ix))
418                    && cx.was_top_layer(&mouse_position, cx.stacking_order())
419                {
420                    cx.set_cursor_style(crate::CursorStyle::PointingHand)
421                }
422            }
423
424            let text_state = state.text_state.clone();
425            let mouse_down = state.mouse_down_index.clone();
426            if let Some(mouse_down_index) = mouse_down.get() {
427                let clickable_ranges = mem::take(&mut self.clickable_ranges);
428                cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
429                    if phase == DispatchPhase::Bubble {
430                        if let Some(mouse_up_index) =
431                            text_state.index_for_position(bounds, event.position)
432                        {
433                            click_listener(
434                                &clickable_ranges,
435                                InteractiveTextClickEvent {
436                                    mouse_down_index,
437                                    mouse_up_index,
438                                },
439                                cx,
440                            )
441                        }
442
443                        mouse_down.take();
444                        cx.refresh();
445                    }
446                });
447            } else {
448                cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
449                    if phase == DispatchPhase::Bubble {
450                        if let Some(mouse_down_index) =
451                            text_state.index_for_position(bounds, event.position)
452                        {
453                            mouse_down.set(Some(mouse_down_index));
454                            cx.refresh();
455                        }
456                    }
457                });
458            }
459        }
460        if let Some(hover_listener) = self.hover_listener.take() {
461            let text_state = state.text_state.clone();
462            let hovered_index = state.hovered_index.clone();
463            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
464                if phase == DispatchPhase::Bubble {
465                    let current = hovered_index.get();
466                    let updated = text_state.index_for_position(bounds, event.position);
467                    if current != updated {
468                        hovered_index.set(updated);
469                        hover_listener(updated, event.clone(), cx);
470                        cx.refresh();
471                    }
472                }
473            });
474        }
475        if let Some(tooltip_builder) = self.tooltip_builder.clone() {
476            let active_tooltip = state.active_tooltip.clone();
477            let pending_mouse_down = state.mouse_down_index.clone();
478            let text_state = state.text_state.clone();
479
480            cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
481                let position = text_state.index_for_position(bounds, event.position);
482                let is_hovered = position.is_some() && pending_mouse_down.get().is_none();
483                if !is_hovered {
484                    active_tooltip.take();
485                    return;
486                }
487                let position = position.unwrap();
488
489                if phase != DispatchPhase::Bubble {
490                    return;
491                }
492
493                if active_tooltip.borrow().is_none() {
494                    let task = cx.spawn({
495                        let active_tooltip = active_tooltip.clone();
496                        let tooltip_builder = tooltip_builder.clone();
497
498                        move |mut cx| async move {
499                            cx.background_executor().timer(TOOLTIP_DELAY).await;
500                            cx.update(|cx| {
501                                let new_tooltip =
502                                    tooltip_builder(position, cx).map(|tooltip| ActiveTooltip {
503                                        tooltip: Some(AnyTooltip {
504                                            view: tooltip,
505                                            cursor_offset: cx.mouse_position(),
506                                        }),
507                                        _task: None,
508                                    });
509                                *active_tooltip.borrow_mut() = new_tooltip;
510                                cx.refresh();
511                            })
512                            .ok();
513                        }
514                    });
515                    *active_tooltip.borrow_mut() = Some(ActiveTooltip {
516                        tooltip: None,
517                        _task: Some(task),
518                    });
519                }
520            });
521
522            let active_tooltip = state.active_tooltip.clone();
523            cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
524                active_tooltip.take();
525            });
526
527            if let Some(tooltip) = state
528                .active_tooltip
529                .clone()
530                .borrow()
531                .as_ref()
532                .and_then(|at| at.tooltip.clone())
533            {
534                cx.set_tooltip(tooltip);
535            }
536        }
537
538        self.text.paint(bounds, &mut state.text_state, cx)
539    }
540}
541
542impl IntoElement for InteractiveText {
543    type Element = Self;
544
545    fn element_id(&self) -> Option<ElementId> {
546        Some(self.element_id.clone())
547    }
548
549    fn into_element(self) -> Self::Element {
550        self
551    }
552}