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, TooltipId, WhiteSpace, Window, WrappedLine, WrappedLineLayout,
6 register_tooltip_mouse_handlers, set_tooltip_on_window,
7};
8use anyhow::Context as _;
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 RequestLayoutState = TextLayout;
21 type PrepaintState = ();
22
23 fn id(&self) -> Option<ElementId> {
24 None
25 }
26
27 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
28 None
29 }
30
31 fn request_layout(
32 &mut self,
33 _id: Option<&GlobalElementId>,
34 _inspector_id: Option<&InspectorElementId>,
35 window: &mut Window,
36 cx: &mut App,
37 ) -> (LayoutId, Self::RequestLayoutState) {
38 let mut state = TextLayout::default();
39 let layout_id = state.layout(SharedString::from(*self), None, window, cx);
40 (layout_id, state)
41 }
42
43 fn prepaint(
44 &mut self,
45 _id: Option<&GlobalElementId>,
46 _inspector_id: Option<&InspectorElementId>,
47 bounds: Bounds<Pixels>,
48 text_layout: &mut Self::RequestLayoutState,
49 _window: &mut Window,
50 _cx: &mut App,
51 ) {
52 text_layout.prepaint(bounds, self)
53 }
54
55 fn paint(
56 &mut self,
57 _id: Option<&GlobalElementId>,
58 _inspector_id: Option<&InspectorElementId>,
59 _bounds: Bounds<Pixels>,
60 text_layout: &mut TextLayout,
61 _: &mut (),
62 window: &mut Window,
63 cx: &mut App,
64 ) {
65 text_layout.paint(self, window, cx)
66 }
67}
68
69impl IntoElement for &'static str {
70 type Element = Self;
71
72 fn into_element(self) -> Self::Element {
73 self
74 }
75}
76
77impl IntoElement for String {
78 type Element = SharedString;
79
80 fn into_element(self) -> Self::Element {
81 self.into()
82 }
83}
84
85impl Element for SharedString {
86 type RequestLayoutState = TextLayout;
87 type PrepaintState = ();
88
89 fn id(&self) -> Option<ElementId> {
90 None
91 }
92
93 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
94 None
95 }
96
97 fn request_layout(
98 &mut self,
99 _id: Option<&GlobalElementId>,
100 _inspector_id: Option<&InspectorElementId>,
101 window: &mut Window,
102 cx: &mut App,
103 ) -> (LayoutId, Self::RequestLayoutState) {
104 let mut state = TextLayout::default();
105 let layout_id = state.layout(self.clone(), None, window, cx);
106 (layout_id, state)
107 }
108
109 fn prepaint(
110 &mut self,
111 _id: Option<&GlobalElementId>,
112 _inspector_id: Option<&InspectorElementId>,
113 bounds: Bounds<Pixels>,
114 text_layout: &mut Self::RequestLayoutState,
115 _window: &mut Window,
116 _cx: &mut App,
117 ) {
118 text_layout.prepaint(bounds, self.as_ref())
119 }
120
121 fn paint(
122 &mut self,
123 _id: Option<&GlobalElementId>,
124 _inspector_id: Option<&InspectorElementId>,
125 _bounds: Bounds<Pixels>,
126 text_layout: &mut Self::RequestLayoutState,
127 _: &mut Self::PrepaintState,
128 window: &mut Window,
129 cx: &mut App,
130 ) {
131 text_layout.paint(self.as_ref(), window, cx)
132 }
133}
134
135impl IntoElement for SharedString {
136 type Element = Self;
137
138 fn into_element(self) -> Self::Element {
139 self
140 }
141}
142
143pub struct StyledText {
149 text: SharedString,
150 runs: Option<Vec<TextRun>>,
151 delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
152 layout: TextLayout,
153}
154
155impl StyledText {
156 pub fn new(text: impl Into<SharedString>) -> Self {
158 StyledText {
159 text: text.into(),
160 runs: None,
161 delayed_highlights: None,
162 layout: TextLayout::default(),
163 }
164 }
165
166 pub fn layout(&self) -> &TextLayout {
168 &self.layout
169 }
170
171 pub fn with_default_highlights(
174 mut self,
175 default_style: &TextStyle,
176 highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
177 ) -> Self {
178 debug_assert!(
179 self.delayed_highlights.is_none(),
180 "Can't use `with_default_highlights` and `with_highlights`"
181 );
182 let runs = Self::compute_runs(&self.text, default_style, highlights);
183 self.runs = Some(runs);
184 self
185 }
186
187 pub fn with_highlights(
190 mut self,
191 highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
192 ) -> Self {
193 debug_assert!(
194 self.runs.is_none(),
195 "Can't use `with_highlights` and `with_default_highlights`"
196 );
197 self.delayed_highlights = Some(highlights.into_iter().collect::<Vec<_>>());
198 self
199 }
200
201 fn compute_runs(
202 text: &str,
203 default_style: &TextStyle,
204 highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
205 ) -> Vec<TextRun> {
206 let mut runs = Vec::new();
207 let mut ix = 0;
208 for (range, highlight) in highlights {
209 if ix < range.start {
210 runs.push(default_style.clone().to_run(range.start - ix));
211 }
212 runs.push(
213 default_style
214 .clone()
215 .highlight(highlight)
216 .to_run(range.len()),
217 );
218 ix = range.end;
219 }
220 if ix < text.len() {
221 runs.push(default_style.to_run(text.len() - ix));
222 }
223 runs
224 }
225
226 pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
228 self.runs = Some(runs);
229 self
230 }
231}
232
233impl Element for StyledText {
234 type RequestLayoutState = ();
235 type PrepaintState = ();
236
237 fn id(&self) -> Option<ElementId> {
238 None
239 }
240
241 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
242 None
243 }
244
245 fn request_layout(
246 &mut self,
247 _id: Option<&GlobalElementId>,
248 _inspector_id: Option<&InspectorElementId>,
249 window: &mut Window,
250 cx: &mut App,
251 ) -> (LayoutId, Self::RequestLayoutState) {
252 let runs = self.runs.take().or_else(|| {
253 self.delayed_highlights.take().map(|delayed_highlights| {
254 Self::compute_runs(&self.text, &window.text_style(), delayed_highlights)
255 })
256 });
257
258 let layout_id = self.layout.layout(self.text.clone(), runs, window, cx);
259 (layout_id, ())
260 }
261
262 fn prepaint(
263 &mut self,
264 _id: Option<&GlobalElementId>,
265 _inspector_id: Option<&InspectorElementId>,
266 bounds: Bounds<Pixels>,
267 _: &mut Self::RequestLayoutState,
268 _window: &mut Window,
269 _cx: &mut App,
270 ) {
271 self.layout.prepaint(bounds, &self.text)
272 }
273
274 fn paint(
275 &mut self,
276 _id: Option<&GlobalElementId>,
277 _inspector_id: Option<&InspectorElementId>,
278 _bounds: Bounds<Pixels>,
279 _: &mut Self::RequestLayoutState,
280 _: &mut Self::PrepaintState,
281 window: &mut Window,
282 cx: &mut App,
283 ) {
284 self.layout.paint(&self.text, window, cx)
285 }
286}
287
288impl IntoElement for StyledText {
289 type Element = Self;
290
291 fn into_element(self) -> Self::Element {
292 self
293 }
294}
295
296#[derive(Default, Clone)]
298pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);
299
300struct TextLayoutInner {
301 len: usize,
302 lines: SmallVec<[WrappedLine; 1]>,
303 line_height: Pixels,
304 wrap_width: Option<Pixels>,
305 truncate_width: Option<Pixels>,
306 size: Option<Size<Pixels>>,
307 bounds: Option<Bounds<Pixels>>,
308}
309
310fn cached_size_for_constraints(
311 cached: &TextLayoutInner,
312 wrap_width: Option<Pixels>,
313 truncate_width: Option<Pixels>,
314) -> Option<Size<Pixels>> {
315 if (wrap_width.is_none() || wrap_width == cached.wrap_width)
316 && truncate_width.is_none()
317 && cached.truncate_width.is_none()
318 {
319 cached.size
320 } else {
321 None
322 }
323}
324
325fn all_shaped_line_widths_fit(
326 widths: impl IntoIterator<Item = Pixels>,
327 truncate_width: Pixels,
328) -> bool {
329 widths.into_iter().all(|width| width <= truncate_width)
330}
331
332impl TextLayout {
333 fn layout(
334 &self,
335 text: SharedString,
336 runs: Option<Vec<TextRun>>,
337 window: &mut Window,
338 _: &mut App,
339 ) -> LayoutId {
340 let text_style = window.text_style();
341 let font_size = text_style.font_size.to_pixels(window.rem_size());
342 let line_height = window.pixel_snap(
343 text_style
344 .line_height
345 .to_pixels(font_size.into(), window.rem_size()),
346 );
347
348 let mut runs = if let Some(runs) = runs {
349 runs
350 } else {
351 vec![text_style.to_run(text.len())]
352 };
353
354 window.request_measured_layout(Default::default(), {
355 let element_state = self.clone();
356
357 move |known_dimensions, available_space, window, cx| {
358 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
359 known_dimensions.width.or(match available_space.width {
360 crate::AvailableSpace::Definite(x) => Some(x),
361 _ => None,
362 })
363 } else {
364 None
365 };
366
367 let (truncate_width, truncation_suffix) =
368 if let Some(text_overflow) = text_style.text_overflow.clone() {
369 let width = known_dimensions.width.or(match available_space.width {
370 crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
371 Some(max_lines) => Some(x * max_lines),
372 None => Some(x),
373 },
374 _ => None,
375 });
376
377 match text_overflow {
378 TextOverflow::Truncate(s) => (width, s),
379 }
380 } else {
381 (None, "".into())
382 };
383
384 if let Some(size) = element_state.0.borrow().as_ref().and_then(|cached| {
385 cached_size_for_constraints(cached, wrap_width, truncate_width)
386 }) {
387 return size;
388 }
389
390 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
391 let text = if let Some(truncate_width) = truncate_width {
392 let unclipped_text_fits = wrap_width.is_none()
393 && window
394 .text_system()
395 .shape_text(text.clone(), font_size, &runs, None, None)
396 .log_err()
397 .is_some_and(|lines| {
398 all_shaped_line_widths_fit(
399 lines.iter().map(|line| line.size(line_height).width),
400 truncate_width,
401 )
402 });
403
404 if unclipped_text_fits {
405 text.clone()
406 } else {
407 line_wrapper.truncate_line(
408 text.clone(),
409 truncate_width,
410 &truncation_suffix,
411 &mut runs,
412 )
413 }
414 } else {
415 text.clone()
416 };
417 let len = text.len();
418
419 let Some(lines) = window
420 .text_system()
421 .shape_text(
422 text,
423 font_size,
424 &runs,
425 wrap_width, text_style.line_clamp, )
428 .log_err()
429 else {
430 element_state.0.borrow_mut().replace(TextLayoutInner {
431 lines: Default::default(),
432 len: 0,
433 line_height,
434 wrap_width,
435 truncate_width,
436 size: Some(Size::default()),
437 bounds: None,
438 });
439 return Size::default();
440 };
441
442 let mut size: Size<Pixels> = Size::default();
443 for line in &lines {
444 let line_size = line.size(line_height);
445 size.height += line_size.height;
446 size.width = size.width.max(line_size.width).ceil();
447 }
448
449 element_state.0.borrow_mut().replace(TextLayoutInner {
450 lines,
451 len,
452 line_height,
453 wrap_width,
454 truncate_width,
455 size: Some(size),
456 bounds: None,
457 });
458
459 size
460 }
461 })
462 }
463
464 fn prepaint(&self, bounds: Bounds<Pixels>, text: &str) {
465 let mut element_state = self.0.borrow_mut();
466 let element_state = element_state
467 .as_mut()
468 .with_context(|| format!("measurement has not been performed on {text}"))
469 .unwrap();
470 element_state.bounds = Some(bounds);
471 }
472
473 fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
474 let element_state = self.0.borrow();
475 let element_state = element_state
476 .as_ref()
477 .with_context(|| format!("measurement has not been performed on {text}"))
478 .unwrap();
479 let bounds = element_state
480 .bounds
481 .with_context(|| format!("prepaint has not been performed on {text}"))
482 .unwrap();
483
484 let line_height = element_state.line_height;
485 let mut line_origin = bounds.origin;
486 let text_style = window.text_style();
487 for line in &element_state.lines {
488 line.paint_background(
489 line_origin,
490 line_height,
491 text_style.text_align,
492 Some(bounds),
493 window,
494 cx,
495 )
496 .log_err();
497 line.paint(
498 line_origin,
499 line_height,
500 text_style.text_align,
501 Some(bounds),
502 window,
503 cx,
504 )
505 .log_err();
506 line_origin.y += line.size(line_height).height;
507 }
508 }
509
510 pub fn index_for_position(&self, mut position: Point<Pixels>) -> Result<usize, usize> {
512 let element_state = self.0.borrow();
513 let element_state = element_state
514 .as_ref()
515 .expect("measurement has not been performed");
516 let bounds = element_state
517 .bounds
518 .expect("prepaint has not been performed");
519
520 if position.y < bounds.top() {
521 return Err(0);
522 }
523
524 let line_height = element_state.line_height;
525 let mut line_origin = bounds.origin;
526 let mut line_start_ix = 0;
527 for line in &element_state.lines {
528 let line_bottom = line_origin.y + line.size(line_height).height;
529 if position.y > line_bottom {
530 line_origin.y = line_bottom;
531 line_start_ix += line.len() + 1;
532 } else {
533 let position_within_line = position - line_origin;
534 match line.index_for_position(position_within_line, line_height) {
535 Ok(index_within_line) => return Ok(line_start_ix + index_within_line),
536 Err(index_within_line) => return Err(line_start_ix + index_within_line),
537 }
538 }
539 }
540
541 Err(line_start_ix.saturating_sub(1))
542 }
543
544 pub fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
546 let element_state = self.0.borrow();
547 let element_state = element_state
548 .as_ref()
549 .expect("measurement has not been performed");
550 let bounds = element_state
551 .bounds
552 .expect("prepaint has not been performed");
553 let line_height = element_state.line_height;
554
555 let mut line_origin = bounds.origin;
556 let mut line_start_ix = 0;
557
558 for line in &element_state.lines {
559 let line_end_ix = line_start_ix + line.len();
560 if index < line_start_ix {
561 break;
562 } else if index > line_end_ix {
563 line_origin.y += line.size(line_height).height;
564 line_start_ix = line_end_ix + 1;
565 continue;
566 } else {
567 let ix_within_line = index - line_start_ix;
568 return Some(line_origin + line.position_for_index(ix_within_line, line_height)?);
569 }
570 }
571
572 None
573 }
574
575 pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
577 let element_state = self.0.borrow();
578 let element_state = element_state
579 .as_ref()
580 .expect("measurement has not been performed");
581 let bounds = element_state
582 .bounds
583 .expect("prepaint has not been performed");
584 let line_height = element_state.line_height;
585
586 let mut line_origin = bounds.origin;
587 let mut line_start_ix = 0;
588
589 for line in &element_state.lines {
590 let line_end_ix = line_start_ix + line.len();
591 if index < line_start_ix {
592 break;
593 } else if index > line_end_ix {
594 line_origin.y += line.size(line_height).height;
595 line_start_ix = line_end_ix + 1;
596 continue;
597 } else {
598 return Some(line.layout.clone());
599 }
600 }
601
602 None
603 }
604
605 pub fn bounds(&self) -> Bounds<Pixels> {
607 self.0.borrow().as_ref().unwrap().bounds.unwrap()
608 }
609
610 pub fn line_height(&self) -> Pixels {
612 self.0.borrow().as_ref().unwrap().line_height
613 }
614
615 pub fn len(&self) -> usize {
617 self.0.borrow().as_ref().unwrap().len
618 }
619
620 pub fn text(&self) -> String {
622 self.0
623 .borrow()
624 .as_ref()
625 .unwrap()
626 .lines
627 .iter()
628 .map(|s| s.text.to_string())
629 .collect::<Vec<_>>()
630 .join("\n")
631 }
632
633 pub fn wrapped_text(&self) -> String {
635 let mut lines = Vec::new();
636 for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
637 let mut seen = 0;
638 for boundary in wrapped.layout.wrap_boundaries.iter() {
639 let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
640 [boundary.glyph_ix]
641 .index;
642
643 lines.push(wrapped.text[seen..index].to_string());
644 seen = index;
645 }
646 lines.push(wrapped.text[seen..].to_string());
647 }
648
649 lines.join("\n")
650 }
651}
652
653pub struct InteractiveText {
655 element_id: ElementId,
656 text: StyledText,
657 click_listener:
658 Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
659 hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
660 tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
661 tooltip_id: Option<TooltipId>,
662 clickable_ranges: Vec<Range<usize>>,
663}
664
665struct InteractiveTextClickEvent {
666 mouse_down_index: usize,
667 mouse_up_index: usize,
668}
669
670#[doc(hidden)]
671#[derive(Default)]
672pub struct InteractiveTextState {
673 mouse_down_index: Rc<Cell<Option<usize>>>,
674 hovered_index: Rc<Cell<Option<usize>>>,
675 active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
676}
677
678impl InteractiveText {
680 pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
682 Self {
683 element_id: id.into(),
684 text,
685 click_listener: None,
686 hover_listener: None,
687 tooltip_builder: None,
688 tooltip_id: None,
689 clickable_ranges: Vec::new(),
690 }
691 }
692
693 pub fn on_click(
696 mut self,
697 ranges: Vec<Range<usize>>,
698 listener: impl Fn(usize, &mut Window, &mut App) + 'static,
699 ) -> Self {
700 self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
701 for (range_ix, range) in ranges.iter().enumerate() {
702 if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
703 {
704 listener(range_ix, window, cx);
705 }
706 }
707 }));
708 self.clickable_ranges = ranges;
709 self
710 }
711
712 pub fn on_hover(
715 mut self,
716 listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
717 ) -> Self {
718 self.hover_listener = Some(Box::new(listener));
719 self
720 }
721
722 pub fn tooltip(
724 mut self,
725 builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
726 ) -> Self {
727 self.tooltip_builder = Some(Rc::new(builder));
728 self
729 }
730}
731
732impl Element for InteractiveText {
733 type RequestLayoutState = ();
734 type PrepaintState = Hitbox;
735
736 fn id(&self) -> Option<ElementId> {
737 Some(self.element_id.clone())
738 }
739
740 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
741 None
742 }
743
744 fn a11y_role(&self) -> Option<accesskit::Role> {
745 Some(accesskit::Role::Label)
746 }
747
748 fn write_a11y_info(&self, node: &mut accesskit::Node) {
749 node.set_value(self.text.text.to_string());
750 }
751
752 fn request_layout(
753 &mut self,
754 _id: Option<&GlobalElementId>,
755 inspector_id: Option<&InspectorElementId>,
756 window: &mut Window,
757 cx: &mut App,
758 ) -> (LayoutId, Self::RequestLayoutState) {
759 self.text.request_layout(None, inspector_id, window, cx)
760 }
761
762 fn prepaint(
763 &mut self,
764 global_id: Option<&GlobalElementId>,
765 inspector_id: Option<&InspectorElementId>,
766 bounds: Bounds<Pixels>,
767 state: &mut Self::RequestLayoutState,
768 window: &mut Window,
769 cx: &mut App,
770 ) -> Hitbox {
771 window.with_optional_element_state::<InteractiveTextState, _>(
772 global_id,
773 |interactive_state, window| {
774 let mut interactive_state = interactive_state
775 .map(|interactive_state| interactive_state.unwrap_or_default());
776
777 if let Some(interactive_state) = interactive_state.as_mut() {
778 if self.tooltip_builder.is_some() {
779 self.tooltip_id =
780 set_tooltip_on_window(&interactive_state.active_tooltip, window);
781 } else {
782 interactive_state.active_tooltip.take();
784 }
785 }
786
787 self.text
788 .prepaint(None, inspector_id, bounds, state, window, cx);
789 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
790 (hitbox, interactive_state)
791 },
792 )
793 }
794
795 fn paint(
796 &mut self,
797 global_id: Option<&GlobalElementId>,
798 inspector_id: Option<&InspectorElementId>,
799 bounds: Bounds<Pixels>,
800 _: &mut Self::RequestLayoutState,
801 hitbox: &mut Hitbox,
802 window: &mut Window,
803 cx: &mut App,
804 ) {
805 let current_view = window.current_view();
806 let text_layout = self.text.layout().clone();
807 window.with_element_state::<InteractiveTextState, _>(
808 global_id.unwrap(),
809 |interactive_state, window| {
810 let mut interactive_state = interactive_state.unwrap_or_default();
811 if let Some(click_listener) = self.click_listener.take() {
812 let mouse_position = window.mouse_position();
813 if let Ok(ix) = text_layout.index_for_position(mouse_position)
814 && self
815 .clickable_ranges
816 .iter()
817 .any(|range| range.contains(&ix))
818 {
819 window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
820 }
821
822 let text_layout = text_layout.clone();
823 let mouse_down = interactive_state.mouse_down_index.clone();
824 if let Some(mouse_down_index) = mouse_down.get() {
825 let hitbox = hitbox.clone();
826 let clickable_ranges = mem::take(&mut self.clickable_ranges);
827 window.on_mouse_event(
828 move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
829 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
830 if let Ok(mouse_up_index) =
831 text_layout.index_for_position(event.position)
832 {
833 click_listener(
834 &clickable_ranges,
835 InteractiveTextClickEvent {
836 mouse_down_index,
837 mouse_up_index,
838 },
839 window,
840 cx,
841 )
842 }
843
844 mouse_down.take();
845 window.refresh();
846 }
847 },
848 );
849 } else {
850 let hitbox = hitbox.clone();
851 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _| {
852 if phase == DispatchPhase::Bubble
853 && hitbox.is_hovered(window)
854 && let Ok(mouse_down_index) =
855 text_layout.index_for_position(event.position)
856 {
857 mouse_down.set(Some(mouse_down_index));
858 window.refresh();
859 }
860 });
861 }
862 }
863
864 window.on_mouse_event({
865 let mut hover_listener = self.hover_listener.take();
866 let hitbox = hitbox.clone();
867 let text_layout = text_layout.clone();
868 let hovered_index = interactive_state.hovered_index.clone();
869 move |event: &MouseMoveEvent, phase, window, cx| {
870 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
871 let current = hovered_index.get();
872 let updated = text_layout.index_for_position(event.position).ok();
873 if current != updated {
874 hovered_index.set(updated);
875 if let Some(hover_listener) = hover_listener.as_ref() {
876 hover_listener(updated, event.clone(), window, cx);
877 }
878 cx.notify(current_view);
879 }
880 }
881 }
882 });
883
884 if let Some(tooltip_builder) = self.tooltip_builder.clone() {
885 let active_tooltip = interactive_state.active_tooltip.clone();
886 let build_tooltip = Rc::new({
887 let tooltip_is_hoverable = false;
888 let text_layout = text_layout.clone();
889 move |window: &mut Window, cx: &mut App| {
890 text_layout
891 .index_for_position(window.mouse_position())
892 .ok()
893 .and_then(|position| tooltip_builder(position, window, cx))
894 .map(|view| (view, tooltip_is_hoverable))
895 }
896 });
897
898 let check_is_hovered_during_prepaint = Rc::new({
900 let source_bounds = hitbox.bounds;
901 let text_layout = text_layout.clone();
902 let pending_mouse_down = interactive_state.mouse_down_index.clone();
903 move |window: &Window| {
904 text_layout
905 .index_for_position(window.mouse_position())
906 .is_ok()
907 && source_bounds.contains(&window.mouse_position())
908 && pending_mouse_down.get().is_none()
909 }
910 });
911
912 let check_is_hovered = Rc::new({
913 let hitbox = hitbox.clone();
914 let text_layout = text_layout.clone();
915 let pending_mouse_down = interactive_state.mouse_down_index.clone();
916 move |window: &Window| {
917 text_layout
918 .index_for_position(window.mouse_position())
919 .is_ok()
920 && hitbox.is_hovered(window)
921 && pending_mouse_down.get().is_none()
922 }
923 });
924
925 register_tooltip_mouse_handlers(
926 &active_tooltip,
927 self.tooltip_id,
928 build_tooltip,
929 check_is_hovered,
930 check_is_hovered_during_prepaint,
931 None,
932 window,
933 );
934 }
935
936 self.text
937 .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
938
939 ((), interactive_state)
940 },
941 );
942 }
943}
944
945impl IntoElement for InteractiveText {
946 type Element = Self;
947
948 fn into_element(self) -> Self::Element {
949 self
950 }
951}
952
953#[cfg(test)]
954mod tests {
955 use super::*;
956 use crate::{px, size};
957
958 #[test]
959 fn truncated_layout_is_not_reused_for_an_unconstrained_measurement() {
960 let cached = TextLayoutInner {
961 len: 4,
962 lines: SmallVec::new(),
963 line_height: px(16.0),
964 wrap_width: None,
965 truncate_width: Some(px(24.0)),
966 size: Some(size(px(24.0), px(16.0))),
967 bounds: None,
968 };
969
970 assert_eq!(cached_size_for_constraints(&cached, None, None), None);
971 }
972
973 #[test]
974 fn exact_fit_shaped_text_does_not_require_truncation() {
975 assert!(all_shaped_line_widths_fit([px(72.0), px(80.0)], px(80.0)));
976 assert!(!all_shaped_line_widths_fit([px(80.5)], px(80.0)));
977 }
978}