1use std::any::Any;
6use std::fmt;
7use std::rc::Rc;
8
9use indexmap::IndexMap;
10use waft_embedder::{ParagraphBuilder, TextAffinity, TextPosition};
11use waft_foundation::{
12 App, DiagnosticPropertiesBuilder, Diagnosticable, DiagnosticableTree, DiagnosticsNode,
13 DiagnosticsTreeStyle, FlagsSummary, StringProperty, message,
14};
15use waft_gestures::{
16 HitTestEntry, HitTestTarget, PointerEnterEventListener, PointerEvent, PointerExitEventListener,
17};
18use waft_services::{MouseCursor, MouseCursorRef, MouseTrackerAnnotation, SystemMouseCursors};
19
20use crate::basic_types::RenderComparison;
21use crate::inline_span::{Accumulator, InlineSpan, InlineSpanRef, same_span, utf16_len};
22use crate::text_painter::PlaceholderDimensions;
23use crate::text_scaler::TextScaler;
24use crate::text_style::TextStyle;
25use waft_foundation::OptionRetained;
26use waft_gestures::RecognizerRef;
27
28#[derive(Clone, Default)]
43pub struct TextSpan {
44 pub text: Option<String>,
49 pub children: Option<Vec<InlineSpanRef>>,
54 pub style: Option<TextStyle>,
56 pub recognizer: Option<RecognizerRef>,
70 pub mouse_cursor: Option<MouseCursorRef>,
81 pub on_enter: Option<PointerEnterEventListener>,
83 pub on_exit: Option<PointerExitEventListener>,
85}
86
87impl TextSpan {
88 pub fn new() -> TextSpan {
90 TextSpan::default()
91 }
92
93 pub fn text(mut self, text: impl Into<String>) -> TextSpan {
95 self.text = Some(text.into());
96 self
97 }
98
99 pub fn children(mut self, children: Vec<InlineSpanRef>) -> TextSpan {
101 self.children = Some(children);
102 self
103 }
104
105 pub fn style(mut self, style: TextStyle) -> TextSpan {
107 self.style = Some(style);
108 self
109 }
110
111 pub fn recognizer(mut self, recognizer: RecognizerRef) -> TextSpan {
113 self.recognizer = Some(recognizer);
114 self
115 }
116
117 pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> TextSpan {
119 self.mouse_cursor = Some(mouse_cursor.into());
120 self
121 }
122
123 pub fn on_enter(mut self, on_enter: PointerEnterEventListener) -> TextSpan {
125 self.on_enter = Some(on_enter);
126 self
127 }
128
129 pub fn on_exit(mut self, on_exit: PointerExitEventListener) -> TextSpan {
131 self.on_exit = Some(on_exit);
132 self
133 }
134
135 pub fn effective_mouse_cursor(&self) -> MouseCursorRef {
139 match (&self.mouse_cursor, &self.recognizer) {
140 (Some(mouse_cursor), _) => Rc::clone(mouse_cursor),
141 (None, None) => <dyn MouseCursor>::defer(),
142 (None, Some(_)) => SystemMouseCursors::CLICK.into(),
143 }
144 }
145
146 pub fn mouse_tracker_annotation(&self) -> MouseTrackerAnnotation {
151 MouseTrackerAnnotation {
152 on_enter: self.on_enter.clone(),
153 on_exit: self.on_exit.clone(),
154 cursor: self.effective_mouse_cursor(),
155 valid_for_mouse_tracker: true,
156 }
157 }
158
159 pub fn into_span(self) -> InlineSpanRef {
161 std::rc::Rc::new(self)
162 }
163}
164
165impl HitTestTarget for TextSpan {
166 fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
167 if let PointerEvent::Down(event) = event
168 && let Some(recognizer) = self.recognizer.handle()
169 {
170 recognizer.add_pointer(app, event);
171 }
172 }
173}
174
175impl Diagnosticable for TextSpan {
176 fn to_string_short(&self) -> String {
177 "TextSpan".to_string()
178 }
179
180 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
181 crate::inline_span::inline_span_debug_fill_properties(self.style.as_ref(), properties);
182
183 properties.add(
184 StringProperty::new("text", self.text.clone())
185 .with_show_name(false)
186 .default_value(None),
187 );
188 if self.style.is_none() && self.text.is_none() && self.children.is_none() {
189 properties.add(message("(empty)"));
190 }
191
192 properties.add(
194 waft_foundation::DiagnosticsProperty::<String>::new(
195 "recognizer",
196 self.recognizer
197 .clone()
198 .map(|recognizer| recognizer.type_name().to_string()),
199 )
200 .default_value(None),
201 );
202
203 let mut callbacks = IndexMap::new();
204 callbacks.insert("enter".to_string(), self.on_enter.as_ref().map(|_| ()));
205 callbacks.insert("exit".to_string(), self.on_exit.as_ref().map(|_| ()));
206 properties.add(FlagsSummary::<()>::new("callbacks", callbacks));
207 properties.add(
208 waft_foundation::DiagnosticsProperty::<String>::new(
209 "mouseCursor",
210 Some(self.effective_mouse_cursor().debug_description()),
211 )
212 .default_value(Some("defer".to_string())),
213 );
214 }
215}
216
217impl DiagnosticableTree for TextSpan {
218 fn debug_describe_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
219 self.children
220 .as_ref()
221 .map(|children| {
222 children
223 .iter()
224 .map(|child| {
225 Rc::new(child.diagnostics_node(None, None)) as Rc<dyn DiagnosticsNode>
226 })
227 .collect()
228 })
229 .unwrap_or_default()
230 }
231}
232
233impl InlineSpan for TextSpan {
234 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
235 Diagnosticable::debug_fill_properties(self, properties);
236 }
237
238 fn debug_describe_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
239 DiagnosticableTree::debug_describe_children(self)
240 }
241
242 fn diagnostics_node(
243 &self,
244 name: Option<String>,
245 style: Option<DiagnosticsTreeStyle>,
246 ) -> waft_foundation::DiagnosticableTreeNode {
247 DiagnosticableTree::to_diagnostics_tree_node(self, name, style)
248 }
249
250 fn style(&self) -> Option<&TextStyle> {
251 self.style.as_ref()
252 }
253
254 fn build(
261 &self,
262 builder: &mut ParagraphBuilder,
263 text_scaler: &TextScaler,
264 dimensions: Option<&[PlaceholderDimensions]>,
265 ) {
266 debug_assert!(self.debug_assert_is_valid());
267 let has_style = self.style.is_some();
268 if let Some(style) = &self.style {
269 builder.push_style(style.get_text_style_with(text_scaler));
270 }
271 if let Some(text) = &self.text {
272 builder.add_text(text);
273 }
274 if let Some(children) = &self.children {
275 for child in children {
276 child.build(builder, text_scaler, dimensions);
277 }
278 }
279 if has_style {
280 builder.pop();
281 }
282 }
283
284 fn visit_children(self: Rc<Self>, visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool {
290 if self.text.is_some() && !visitor(&(self.clone() as InlineSpanRef)) {
291 return false;
292 }
293 if let Some(children) = &self.children {
294 for child in children {
295 if !child.clone().visit_children(visitor) {
296 return false;
297 }
298 }
299 }
300 true
301 }
302
303 fn visit_direct_children(&self, visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool {
304 if let Some(children) = &self.children {
305 for child in children {
306 if !visitor(child) {
307 return false;
308 }
309 }
310 }
311 true
312 }
313
314 fn get_span_for_position_visitor(
316 self: Rc<Self>,
317 position: TextPosition,
318 offset: &mut Accumulator,
319 ) -> Option<InlineSpanRef> {
320 let text = self.text.as_deref()?;
321 if text.is_empty() {
322 return None;
323 }
324 let affinity = position.affinity;
325 let target_offset = position.offset;
326 let end_offset = offset.value() + utf16_len(text);
327 if (offset.value() == target_offset && affinity == TextAffinity::Downstream)
328 || (offset.value() < target_offset && target_offset < end_offset)
329 || (end_offset == target_offset && affinity == TextAffinity::Upstream)
330 {
331 return Some(self);
332 }
333 offset.increment(utf16_len(text));
334 None
335 }
336
337 fn compute_to_plain_text(
338 &self,
339 buffer: &mut String,
340 include_semantics_labels: bool,
341 include_placeholders: bool,
342 ) {
343 debug_assert!(self.debug_assert_is_valid());
344 if let Some(text) = &self.text {
345 buffer.push_str(text);
346 }
347 if let Some(children) = &self.children {
348 for child in children {
349 child.compute_to_plain_text(buffer, include_semantics_labels, include_placeholders);
350 }
351 }
352 }
353
354 fn code_unit_at_visitor(&self, index: i32, offset: &mut Accumulator) -> Option<u16> {
355 let text = self.text.as_deref()?;
356 let local_offset = index - offset.value();
357 debug_assert!(local_offset >= 0);
358 let length = utf16_len(text);
359 offset.increment(length);
360 if local_offset < length {
361 text.encode_utf16().nth(local_offset as usize)
362 } else {
363 None
364 }
365 }
366
367 fn debug_assert_is_valid(&self) -> bool {
372 if cfg!(debug_assertions)
373 && let Some(children) = &self.children
374 {
375 for child in children {
376 debug_assert!(child.debug_assert_is_valid());
377 }
378 }
379 true
380 }
381
382 fn compare_to(&self, other: &dyn InlineSpan) -> RenderComparison {
383 if same_span(self, other) {
384 return RenderComparison::Identical;
385 }
386 let Some(text_span) = other.as_any().downcast_ref::<TextSpan>() else {
387 return RenderComparison::Layout;
388 };
389 if text_span.text != self.text
390 || self.children.as_ref().map(Vec::len) != text_span.children.as_ref().map(Vec::len)
391 || self.style.is_none() != text_span.style.is_none()
392 {
393 return RenderComparison::Layout;
394 }
395 let mut result = if self.recognizer == text_span.recognizer {
396 RenderComparison::Identical
397 } else {
398 RenderComparison::Metadata
399 };
400 if let (Some(style), Some(other_style)) = (&self.style, &text_span.style) {
401 let candidate = style.compare_to(other_style);
402 if candidate > result {
403 result = candidate;
404 }
405 if result == RenderComparison::Layout {
406 return result;
407 }
408 }
409 if let (Some(children), Some(other_children)) = (&self.children, &text_span.children) {
410 for (child, other_child) in children.iter().zip(other_children) {
411 let candidate = child.compare_to(&**other_child);
412 if candidate > result {
413 result = candidate;
414 }
415 if result == RenderComparison::Layout {
416 return result;
417 }
418 }
419 }
420 result
421 }
422
423 fn as_any(&self) -> &dyn Any {
424 self
425 }
426
427 fn to_hit_test_target(self: Rc<Self>) -> Option<Rc<dyn HitTestTarget>> {
428 Some(self)
429 }
430
431 fn eq_span(&self, other: &dyn InlineSpan) -> bool {
432 if same_span(self, other) {
433 return true;
434 }
435 let Some(other) = other.as_any().downcast_ref::<TextSpan>() else {
436 return false;
437 };
438 if other.style != self.style
439 || other.text != self.text
440 || other.recognizer != self.recognizer
441 || !same_listener(&self.on_enter, &other.on_enter)
442 || !same_listener(&self.on_exit, &other.on_exit)
443 || *self.effective_mouse_cursor() != *other.effective_mouse_cursor()
444 {
445 return false;
446 }
447 match (&self.children, &other.children) {
448 (None, None) => true,
449 (Some(a), Some(b)) => {
450 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_span(&**y))
451 }
452 _ => false,
453 }
454 }
455}
456
457fn same_listener<T: ?Sized>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool {
459 match (a, b) {
460 (None, None) => true,
461 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
462 _ => false,
463 }
464}
465
466impl fmt::Debug for TextSpan {
467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468 f.write_str(&Diagnosticable::to_string(self))
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use waft_embedder::Color;
475
476 use super::*;
477
478 fn tree() -> TextSpan {
479 TextSpan::new().text("ab").children(vec![
480 TextSpan::new().text("cd").into_span(),
481 TextSpan::new()
482 .children(vec![TextSpan::new().text("e😀").into_span()])
483 .into_span(),
484 ])
485 }
486
487 #[test]
489 fn text_span_to_string_deep() {
490 let span = TextSpan::new()
491 .text("a")
492 .style(TextStyle::new().font_size(10.0))
493 .children(vec![
494 TextSpan::new()
495 .text("b")
496 .children(vec![TextSpan::new().into_span()])
497 .into_span(),
498 TextSpan::new().text("c").into_span(),
499 ]);
500 assert_eq!(
501 DiagnosticableTree::to_string_deep(&span),
502 "TextSpan:\n\
503 \u{20} inherit: true\n\
504 \u{20} size: 10.0\n\
505 \u{20} \"a\"\n\
506 \u{20} TextSpan:\n\
507 \u{20} \"b\"\n\
508 \u{20} TextSpan:\n\
509 \u{20} (empty)\n\
510 \u{20} TextSpan:\n\
511 \u{20} \"c\"\n"
512 );
513 }
514
515 #[test]
517 fn text_span_to_string_deep_for_mouse() {
518 let plain = TextSpan::new().text("a");
519 assert_eq!(
520 DiagnosticableTree::to_string_deep(&plain),
521 "TextSpan:\n \"a\"\n"
522 );
523
524 let with_mouse = TextSpan::new()
525 .text("a")
526 .on_enter(Rc::new(|_app, _event| {}))
527 .on_exit(Rc::new(|_app, _event| {}))
528 .mouse_cursor(SystemMouseCursors::FORBIDDEN);
529 assert_eq!(
530 DiagnosticableTree::to_string_deep(&with_mouse),
531 "TextSpan:\n\
532 \u{20} \"a\"\n\
533 \u{20} callbacks: enter, exit\n\
534 \u{20} mouseCursor: SystemMouseCursor(forbidden)\n"
535 );
536 }
537
538 #[test]
540 fn a_text_span_dump_names_its_recognizer() {
541 use waft_foundation::AppCell;
542 use waft_gestures::TapGestureRecognizer;
543
544 let cell = AppCell::new();
545 let mut app = cell.borrow_mut();
546 let recognizer: RecognizerRef = TapGestureRecognizer::new(&mut app).erase();
547 let span = TextSpan::new().text("a").recognizer(recognizer.clone());
548 let dump = DiagnosticableTree::to_string_deep(&span);
549 assert!(
550 dump.contains("recognizer: TapGestureRecognizer\n"),
551 "{dump}"
552 );
553 assert!(
554 dump.contains("mouseCursor: SystemMouseCursor(click)\n"),
555 "{dump}"
556 );
557 recognizer.dispose(&mut app);
558 }
559
560 #[test]
563 fn an_empty_span_says_so() {
564 let empty = TextSpan::new();
565 assert_eq!(
566 DiagnosticableTree::to_string_deep(&empty),
567 "TextSpan:\n (empty)\n"
568 );
569 }
570
571 #[test]
572 fn plain_text_concatenates_text_before_children() {
573 assert_eq!(tree().to_plain_text(true, true), "abcde😀");
574 }
575
576 #[test]
577 fn code_units_are_utf16_across_the_tree() {
578 let span = tree().into_span();
579 let code_unit_at = |index| span.clone().code_unit_at(index);
580 assert_eq!(code_unit_at(0), Some(u16::from(b'a')));
581 assert_eq!(code_unit_at(2), Some(u16::from(b'c')));
582 assert_eq!(code_unit_at(4), Some(u16::from(b'e')));
583 assert_eq!(code_unit_at(5), Some(0xD83D), "the emoji's high surrogate");
584 assert_eq!(code_unit_at(7), None);
585 assert_eq!(code_unit_at(-1), None);
586 }
587
588 #[test]
589 fn span_for_position_follows_affinity_at_boundaries() {
590 let span = tree().into_span();
591 let hit = |offset: i32, affinity: TextAffinity| {
592 span.clone()
593 .get_span_for_position(TextPosition::with_affinity(offset, affinity))
594 .and_then(|found| found.as_any().downcast_ref::<TextSpan>()?.text.clone())
595 };
596 assert_eq!(hit(1, TextAffinity::Downstream).as_deref(), Some("ab"));
597 assert_eq!(hit(2, TextAffinity::Downstream).as_deref(), Some("cd"));
598 assert_eq!(hit(2, TextAffinity::Upstream).as_deref(), Some("ab"));
599 assert_eq!(hit(7, TextAffinity::Upstream).as_deref(), Some("e😀"));
600 assert_eq!(hit(7, TextAffinity::Downstream), None);
601 }
602
603 #[test]
604 fn span_for_position_returns_the_tree_s_own_span() {
605 let child = TextSpan::new().text("cd").into_span();
606 let root = TextSpan::new()
607 .text("ab")
608 .children(vec![child.clone()])
609 .into_span();
610 let found = root.clone().get_span_for_position(TextPosition::new(0));
611 assert!(Rc::ptr_eq(&found.unwrap(), &root));
612 let found = root.clone().get_span_for_position(TextPosition::new(3));
613 assert!(Rc::ptr_eq(&found.unwrap(), &child));
614 }
615
616 #[test]
617 fn compare_to_ranks_the_change() {
618 let a = tree();
619 assert_eq!(a.compare_to(&a), RenderComparison::Identical);
620 assert_eq!(a.compare_to(&tree()), RenderComparison::Identical);
621 let recolored = TextSpan::new()
622 .text("ab")
623 .style(TextStyle::new().color(Color::from_argb(255, 255, 0, 0)));
624 let resized = TextSpan::new()
625 .text("ab")
626 .style(TextStyle::new().color(Color::from_argb(255, 0, 0, 255)));
627 assert_eq!(recolored.compare_to(&resized), RenderComparison::Paint);
628 let relaid = TextSpan::new()
629 .text("ab")
630 .style(TextStyle::new().font_size(30.0));
631 assert_eq!(recolored.compare_to(&relaid), RenderComparison::Layout);
632 assert_eq!(
633 a.compare_to(&TextSpan::new().text("ab")),
634 RenderComparison::Layout
635 );
636 }
637
638 #[test]
639 fn equality_is_deep() {
640 let a: InlineSpanRef = tree().into_span();
641 let b: InlineSpanRef = tree().into_span();
642 assert!(*a == *b);
643 let c: InlineSpanRef = TextSpan::new().text("ab").into_span();
644 assert!(*a != *c);
645 }
646
647 #[test]
650 fn equality_compares_callbacks_by_identity_and_cursors_by_value() {
651 let callback1: PointerEnterEventListener = Rc::new(|_app, _event| {});
652 let callback2: PointerEnterEventListener = Rc::new(|_app, _event| {});
653 let a1 = TextSpan::new().text("a");
654 let d1 = TextSpan::new().text("a").on_enter(Rc::clone(&callback1));
655 let d2 = TextSpan::new().text("a").on_enter(Rc::clone(&callback1));
656 let d3 = TextSpan::new().text("a").on_enter(Rc::clone(&callback2));
657 let e1 = TextSpan::new()
658 .text("a")
659 .on_enter(Rc::clone(&callback2))
660 .mouse_cursor(SystemMouseCursors::FORBIDDEN);
661 let e2 = TextSpan::new()
662 .text("a")
663 .on_enter(Rc::clone(&callback2))
664 .mouse_cursor(SystemMouseCursors::FORBIDDEN);
665
666 assert!(!a1.eq_span(&d1));
667 assert!(d1.eq_span(&d2));
668 assert!(!d2.eq_span(&d3));
669 assert!(!d3.eq_span(&e1));
670 assert!(e1.eq_span(&e2));
671 }
672
673 #[test]
676 fn the_recognizer_sets_the_default_cursor() {
677 use waft_foundation::AppCell;
678 use waft_gestures::TapGestureRecognizer;
679
680 let cell = AppCell::new();
681 let mut app = cell.borrow_mut();
682 let first: RecognizerRef = TapGestureRecognizer::new(&mut app).erase();
683 let second: RecognizerRef = TapGestureRecognizer::new(&mut app).erase();
684 let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
685 let forbidden: MouseCursorRef = SystemMouseCursors::FORBIDDEN.into();
686
687 let link = TextSpan::new().text("a").recognizer(first.clone());
688 assert!(*link.effective_mouse_cursor() == *click);
689 assert!(
690 TextSpan::new()
691 .text("a")
692 .effective_mouse_cursor()
693 .is_defer()
694 );
695 let named = TextSpan::new()
696 .text("a")
697 .recognizer(first.clone())
698 .mouse_cursor(SystemMouseCursors::FORBIDDEN);
699 assert!(*named.effective_mouse_cursor() == *forbidden);
700 assert!(*link.mouse_tracker_annotation().cursor == *click);
701
702 let relinked = TextSpan::new().text("a").recognizer(second.clone());
703 assert_eq!(link.compare_to(&relinked), RenderComparison::Metadata);
704 assert!(!link.eq_span(&relinked));
705 assert!(
706 Rc::new(link).to_hit_test_target().is_some(),
707 "a text span is a target"
708 );
709 first.dispose(&mut app);
710 second.dispose(&mut app);
711 }
712}