Skip to main content

waft_widgets/widgets/
text.rs

1//! Flutter counterpart: `widgets/text.dart`, plus the public `RichText` from `basic.dart`.
2//!
3//! [`Text`] builds [`RichText`]. Under a [`SelectionContainer`], as under a `SelectableRegion`,
4//! it builds a container of its own: a `SelectableTextContainer` whose delegate handles the
5//! paragraph's selection, over the foundation in `selectable_region.rs`. `Locale` and `Semantics`
6//! wait; see `PORTING.md`.
7
8use std::cmp::Ordering;
9use std::rc::Rc;
10
11use waft_embedder::{Color, FontWeight, TextAlign, TextDirection, TextHeightBehavior};
12use waft_foundation::{
13    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, Diagnosticable,
14    DiagnosticsProperty, DiagnosticsTreeStyle, EnumProperty, FlagProperty, Handle, IntProperty,
15    Ref, StringProperty,
16};
17use waft_painting::{
18    InlineSpanRef, StrutStyle, TextOverflow, TextScaler, TextSpan, TextStyle, TextWidthBasis,
19    transform_rect,
20};
21use waft_rendering::{
22    AnyRenderObject, AnySelectable, RenderBox, RenderHandle, RenderParagraph, SelectedContentRange,
23    SelectionEvent, SelectionGeometry, SelectionHandler, SelectionRegistrar, SelectionRegistrarRef,
24    SelectionResult,
25};
26use waft_services::SystemMouseCursors;
27
28use crate::framework::{
29    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectWidget,
30    RenderObjectWidget, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
31};
32use crate::view::View;
33use crate::widgets::basic::{Builder, Directionality, ExcludeSemantics, MouseRegion, Semantics};
34use crate::widgets::default_selection_style::DefaultSelectionStyle;
35use crate::widgets::inherited_theme::InheritedTheme;
36use crate::widgets::media_query::MediaQuery;
37use crate::widgets::selectable_region::{
38    MultiSelectableSelectionContainerDelegate, MultiSelectableSelectionContainerDelegateBase,
39    MultiSelectableSelectionContainerDelegateData, StaticSelectionContainerDelegate,
40    StaticSelectionContainerDelegateBase, StaticSelectionContainerDelegateData,
41    compare_horizontally, compare_vertically,
42};
43use crate::widgets::selection_container::{
44    SelectionContainer, SelectionContainerDelegate, SelectionContainerDelegateData,
45};
46use crate::widgets::widget_span::WidgetSpan;
47
48// ---------------------------------------------------------------------------------------------
49// DefaultTextStyle
50
51/// The text style to apply to descendant [`Text`] widgets which don't have an explicit style.
52///
53/// A `MediaQuery` ancestor of a [`Text`] widget may still override the `TextStyle.height`,
54/// `TextStyle.letterSpacing`, and `TextStyle.wordSpacing` of the [`TextStyle`] set by this
55/// [`DefaultTextStyle`] widget through its `MediaQueryData.lineHeightScaleFactorOverride`,
56/// `MediaQueryData.letterSpacingOverride`, and `MediaQueryData.wordSpacingOverride` members.
57///
58/// See also:
59///
60///  * `AnimatedDefaultTextStyle`, which animates changes in the text style smoothly over a
61///    given duration.
62///  * `DefaultTextStyleTransition`, which takes a provided `Animation` to animate changes in
63///    text style smoothly over time.
64///
65/// Dart's named constructor arguments are the fluent setters
66/// (`DefaultTextStyle::new(style, child).max_lines(2)`).
67#[derive(Clone, Debug)]
68pub struct DefaultTextStyle {
69    /// See [`InheritedWidget::key`].
70    pub key: Option<KeyRef>,
71    /// The text style to apply.
72    pub style: TextStyle,
73    /// How each line of text in the Text widget should be aligned horizontally.
74    pub text_align: Option<TextAlign>,
75    /// Whether the text should break at soft line breaks.
76    ///
77    /// If false, the glyphs in the text will be positioned as if there was unlimited
78    /// horizontal space.
79    ///
80    /// This also decides the `overflow` property's behavior. If this is true or null, the
81    /// glyph causing overflow, and those that follow, will not be rendered.
82    pub soft_wrap: bool,
83    /// How visual overflow should be handled.
84    ///
85    /// If `soft_wrap` is true or null, the glyph causing overflow, and those that follow,
86    /// will not be rendered. Otherwise, it will be shown with the given overflow option.
87    pub overflow: TextOverflow,
88    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
89    /// the text exceeds the given number of lines, it will be truncated according to
90    /// `overflow`.
91    ///
92    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
93    /// box.
94    ///
95    /// If this is non-null, it will override even explicit null values of `Text.max_lines`.
96    pub max_lines: Option<i32>,
97    /// The strategy to use when calculating the width of the Text.
98    ///
99    /// See [`TextWidthBasis`] for possible values and their implications.
100    pub text_width_basis: TextWidthBasis,
101    /// Defines how to apply `TextStyle.height` over and under text.
102    pub text_height_behavior: Option<TextHeightBehavior>,
103    /// The widget below this widget in the tree.
104    pub child: WidgetRef,
105}
106
107impl DefaultTextStyle {
108    /// Creates a default text style for the given subtree.
109    ///
110    /// Consider using `DefaultTextStyle.merge` to inherit styling information from the
111    /// current default text style for a given [`BuildContext`].
112    ///
113    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
114    /// not `None`, it must be greater than zero.
115    #[cfg_attr(debug_assertions, track_caller)]
116    pub fn new<K>(style: TextStyle, child: impl IntoWidget<K>) -> DefaultTextStyle {
117        DefaultTextStyle {
118            key: None,
119            style,
120            text_align: None,
121            soft_wrap: true,
122            overflow: TextOverflow::Clip,
123            max_lines: None,
124            text_width_basis: TextWidthBasis::Parent,
125            text_height_behavior: None,
126            child: child.into_widget(),
127        }
128    }
129
130    /// A default text style that provides fallback values.
131    ///
132    /// Returned from [`of`](Self::of) when the given [`BuildContext`] doesn't have an
133    /// enclosing default text style.
134    ///
135    /// This constructor creates a [`DefaultTextStyle`] with an invalid `child`, which means
136    /// the constructed value cannot be incorporated into the tree.
137    pub fn fallback() -> DefaultTextStyle {
138        DefaultTextStyle::new(TextStyle::new(), NullWidget)
139    }
140
141    /// Creates a default text style that overrides the text styles in scope at this point in
142    /// the widget tree.
143    ///
144    /// The given `style` is merged with the `style` from the default text style for the
145    /// [`BuildContext`] where the widget is inserted, and any of the other arguments that are
146    /// not `None` replace the corresponding properties on that same default text style.
147    ///
148    /// This constructor cannot be used to override the `max_lines` property of the ancestor
149    /// with the value `None`, since `None` here is used to mean "defer to ancestor". To
150    /// replace a non-`None` `max_lines` from an ancestor with the `None` value (to remove the
151    /// restriction on number of lines), manually obtain the ambient [`DefaultTextStyle`]
152    /// using [`of`](Self::of), then create a new [`DefaultTextStyle`] using
153    /// [`new`](Self::new) directly.
154    ///
155    /// If a `text_height_behavior` is provided, the existing configuration will be replaced
156    /// completely. To retain part of the original `text_height_behavior`, manually obtain the
157    /// ambient [`DefaultTextStyle`] using [`of`](Self::of).
158    ///
159    /// Dart's optional named arguments are the setters of the [`DefaultTextStyleMerge`] this
160    /// returns.
161    #[cfg_attr(debug_assertions, track_caller)]
162    pub fn merge<K>(child: impl IntoWidget<K>) -> DefaultTextStyleMerge {
163        DefaultTextStyleMerge {
164            key: None,
165            style: None,
166            text_align: None,
167            soft_wrap: None,
168            overflow: None,
169            max_lines: None,
170            text_width_basis: None,
171            text_height_behavior: None,
172            child: child.into_widget(),
173        }
174    }
175
176    /// Dart `DefaultTextStyle(key:)`.
177    pub fn key(mut self, key: KeyRef) -> DefaultTextStyle {
178        self.key = Some(key);
179        self
180    }
181
182    /// Dart `DefaultTextStyle(textAlign:)`.
183    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyle {
184        self.text_align = Some(text_align);
185        self
186    }
187
188    /// Dart `DefaultTextStyle(softWrap:)`.
189    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyle {
190        self.soft_wrap = soft_wrap;
191        self
192    }
193
194    /// Dart `DefaultTextStyle(overflow:)`.
195    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyle {
196        self.overflow = overflow;
197        self
198    }
199
200    /// Dart `DefaultTextStyle(maxLines:)`. Must be greater than zero.
201    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyle {
202        debug_assert!(max_lines > 0);
203        self.max_lines = Some(max_lines);
204        self
205    }
206
207    /// Dart `DefaultTextStyle(textWidthBasis:)`.
208    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyle {
209        self.text_width_basis = text_width_basis;
210        self
211    }
212
213    /// Dart `DefaultTextStyle(textHeightBehavior:)`.
214    pub fn text_height_behavior(
215        mut self,
216        text_height_behavior: TextHeightBehavior,
217    ) -> DefaultTextStyle {
218        self.text_height_behavior = Some(text_height_behavior);
219        self
220    }
221
222    /// The closest instance of this class that encloses the given context.
223    ///
224    /// If no such instance exists, returns an instance created by
225    /// [`fallback`](Self::fallback), which contains fallback values.
226    ///
227    /// Typical usage is as follows:
228    ///
229    /// ```text
230    /// let style = DefaultTextStyle::of(app, context);
231    /// ```
232    pub fn of(app: &mut App, context: BuildContext) -> DefaultTextStyle {
233        context
234            .depend_on_inherited_widget_of_exact_type::<DefaultTextStyle>(app)
235            .cloned()
236            .unwrap_or_else(DefaultTextStyle::fallback)
237    }
238}
239
240/// Dart's `DefaultTextStyle.merge(..)` before its optional arguments are known: a `Builder`
241/// that merges them into the ambient [`DefaultTextStyle`].
242#[derive(Debug)]
243pub struct DefaultTextStyleMerge {
244    key: Option<KeyRef>,
245    style: Option<TextStyle>,
246    text_align: Option<TextAlign>,
247    soft_wrap: Option<bool>,
248    overflow: Option<TextOverflow>,
249    max_lines: Option<i32>,
250    text_width_basis: Option<TextWidthBasis>,
251    text_height_behavior: Option<TextHeightBehavior>,
252    child: WidgetRef,
253}
254
255impl DefaultTextStyleMerge {
256    /// Dart `DefaultTextStyle.merge(key:)`.
257    pub fn key(mut self, key: KeyRef) -> DefaultTextStyleMerge {
258        self.key = Some(key);
259        self
260    }
261
262    /// Dart `DefaultTextStyle.merge(style:)`.
263    pub fn style(mut self, style: TextStyle) -> DefaultTextStyleMerge {
264        self.style = Some(style);
265        self
266    }
267
268    /// Dart `DefaultTextStyle.merge(textAlign:)`.
269    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleMerge {
270        self.text_align = Some(text_align);
271        self
272    }
273
274    /// Dart `DefaultTextStyle.merge(softWrap:)`.
275    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleMerge {
276        self.soft_wrap = Some(soft_wrap);
277        self
278    }
279
280    /// Dart `DefaultTextStyle.merge(overflow:)`.
281    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleMerge {
282        self.overflow = Some(overflow);
283        self
284    }
285
286    /// Dart `DefaultTextStyle.merge(maxLines:)`. Must be greater than zero.
287    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleMerge {
288        debug_assert!(max_lines > 0);
289        self.max_lines = Some(max_lines);
290        self
291    }
292
293    /// Dart `DefaultTextStyle.merge(textWidthBasis:)`.
294    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyleMerge {
295        self.text_width_basis = Some(text_width_basis);
296        self
297    }
298
299    /// Dart `DefaultTextStyle.merge(textHeightBehavior:)`.
300    pub fn text_height_behavior(
301        mut self,
302        text_height_behavior: TextHeightBehavior,
303    ) -> DefaultTextStyleMerge {
304        self.text_height_behavior = Some(text_height_behavior);
305        self
306    }
307}
308
309/// The kind tag of [`IntoWidget`] for a [`DefaultTextStyleMerge`].
310pub struct DefaultTextStyleMergeKind;
311
312impl IntoWidget<DefaultTextStyleMergeKind> for DefaultTextStyleMerge {
313    #[cfg_attr(debug_assertions, track_caller)]
314    fn into_widget(self) -> WidgetRef {
315        Builder::new(move |app, context| {
316            let parent = DefaultTextStyle::of(app, context);
317            DefaultTextStyle {
318                key: self.key.clone(),
319                style: parent.style.merge(self.style.as_ref()),
320                text_align: self.text_align.or(parent.text_align),
321                soft_wrap: self.soft_wrap.unwrap_or(parent.soft_wrap),
322                overflow: self.overflow.unwrap_or(parent.overflow),
323                max_lines: self.max_lines.or(parent.max_lines),
324                text_width_basis: self.text_width_basis.unwrap_or(parent.text_width_basis),
325                text_height_behavior: self.text_height_behavior.or(parent.text_height_behavior),
326                child: self.child.clone(),
327            }
328            .into_widget()
329        })
330        .into_widget()
331    }
332}
333
334impl InheritedWidget for DefaultTextStyle {
335    fn key(&self) -> Option<&KeyRef> {
336        self.key.as_ref()
337    }
338
339    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
340        Diagnosticable::debug_fill_properties(&self.style, properties);
341        properties
342            .add(EnumProperty::<TextAlign>::new("textAlign", self.text_align).default_value(None));
343        properties.add(
344            FlagProperty::new("softWrap", Some(self.soft_wrap))
345                .if_true("wrapping at box width")
346                .if_false("no wrapping except at line break characters")
347                .with_show_name(true),
348        );
349        properties
350            .add(EnumProperty::<TextOverflow>::new("overflow", self.overflow).default_value(None));
351        properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).default_value(None));
352        properties.add(
353            EnumProperty::new("textWidthBasis", self.text_width_basis)
354                .default_value(Some(TextWidthBasis::Parent)),
355        );
356        properties.add(
357            DiagnosticsProperty::<String>::new(
358                "textHeightBehavior",
359                self.text_height_behavior
360                    .map(|behavior| behavior.to_string()),
361            )
362            .default_value(None),
363        );
364    }
365
366    fn child(&self) -> &WidgetRef {
367        &self.child
368    }
369
370    fn update_should_notify(&self, old_widget: &DefaultTextStyle) -> bool {
371        self.style != old_widget.style
372            || self.text_align != old_widget.text_align
373            || self.soft_wrap != old_widget.soft_wrap
374            || self.overflow != old_widget.overflow
375            || self.max_lines != old_widget.max_lines
376            || self.text_width_basis != old_widget.text_width_basis
377            || self.text_height_behavior != old_widget.text_height_behavior
378    }
379
380    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
381        Some(self)
382    }
383}
384
385impl InheritedTheme for DefaultTextStyle {
386    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
387        DefaultTextStyle {
388            key: None,
389            style: self.style.clone(),
390            text_align: self.text_align,
391            soft_wrap: self.soft_wrap,
392            overflow: self.overflow,
393            max_lines: self.max_lines,
394            text_width_basis: self.text_width_basis,
395            text_height_behavior: self.text_height_behavior,
396            child,
397        }
398        .into_widget()
399    }
400}
401
402/// Dart's `_NullWidget`: the child of [`DefaultTextStyle::fallback`], which must never build.
403#[derive(Debug)]
404struct NullWidget;
405
406impl StatelessWidget for NullWidget {
407    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
408        panic!(
409            "A DefaultTextStyle constructed with DefaultTextStyle::fallback cannot be \
410             incorporated into the widget tree, it is meant only to provide a fallback value \
411             returned by DefaultTextStyle::of() when no enclosing default text style is \
412             present in a BuildContext."
413        );
414    }
415}
416
417// ---------------------------------------------------------------------------------------------
418// DefaultTextHeightBehavior
419
420/// The [`TextHeightBehavior`] that will apply to descendant [`Text`] and `EditableText`
421/// widgets which have not explicitly set `Text.text_height_behavior`.
422///
423/// If there is a [`DefaultTextStyle`] with a non-null `DefaultTextStyle.text_height_behavior`
424/// below this widget, the `DefaultTextStyle.text_height_behavior` will be used over this
425/// widget's [`TextHeightBehavior`].
426///
427/// See also:
428///
429///  * [`DefaultTextStyle`], which defines a [`TextStyle`] to apply to descendant [`Text`]
430///    widgets.
431#[derive(Debug)]
432pub struct DefaultTextHeightBehavior {
433    /// See [`InheritedWidget::key`].
434    pub key: Option<KeyRef>,
435    /// Defines how to apply `TextStyle.height` over and under text.
436    pub text_height_behavior: TextHeightBehavior,
437    /// The widget below this widget in the tree.
438    pub child: WidgetRef,
439}
440
441impl DefaultTextHeightBehavior {
442    /// Creates a default text height behavior for the given subtree.
443    #[cfg_attr(debug_assertions, track_caller)]
444    pub fn new<K>(
445        text_height_behavior: TextHeightBehavior,
446        child: impl IntoWidget<K>,
447    ) -> DefaultTextHeightBehavior {
448        DefaultTextHeightBehavior {
449            key: None,
450            text_height_behavior,
451            child: child.into_widget(),
452        }
453    }
454
455    /// Dart `DefaultTextHeightBehavior(key:)`.
456    pub fn key(mut self, key: KeyRef) -> DefaultTextHeightBehavior {
457        self.key = Some(key);
458        self
459    }
460
461    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
462    /// context, or `None` if none is found.
463    ///
464    /// Calling this method will create a dependency on the closest
465    /// [`DefaultTextHeightBehavior`] in the `context`, if there is one.
466    ///
467    /// See also:
468    ///
469    /// * [`of`](Self::of), which is similar to this method, but asserts if no
470    ///   [`DefaultTextHeightBehavior`] ancestor is found.
471    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<TextHeightBehavior> {
472        context
473            .depend_on_inherited_widget_of_exact_type::<DefaultTextHeightBehavior>(app)
474            .map(|widget| widget.text_height_behavior)
475    }
476
477    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
478    /// context.
479    ///
480    /// If no such instance exists, this method panics.
481    ///
482    /// Calling this method will create a dependency on the closest
483    /// [`DefaultTextHeightBehavior`] in the `context`.
484    ///
485    /// See also:
486    ///
487    /// * [`maybe_of`](Self::maybe_of), which is similar to this method, but returns `None`
488    ///   if no [`DefaultTextHeightBehavior`] ancestor is found.
489    pub fn of(app: &mut App, context: BuildContext) -> TextHeightBehavior {
490        let behavior = Self::maybe_of(app, context);
491        behavior.expect(
492            "DefaultTextHeightBehavior::of() was called with a context that does not contain \
493             a DefaultTextHeightBehavior widget.\n\
494             No DefaultTextHeightBehavior widget ancestor could be found starting from the \
495             context that was passed to DefaultTextHeightBehavior::of(). This can happen \
496             because you are using a widget that looks for a DefaultTextHeightBehavior \
497             ancestor, but no such ancestor exists.",
498        )
499    }
500}
501
502impl InheritedWidget for DefaultTextHeightBehavior {
503    fn key(&self) -> Option<&KeyRef> {
504        self.key.as_ref()
505    }
506
507    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
508        properties.add(
509            DiagnosticsProperty::<String>::new(
510                "textHeightBehavior",
511                Some(self.text_height_behavior.to_string()),
512            )
513            .default_value(None),
514        );
515    }
516
517    fn child(&self) -> &WidgetRef {
518        &self.child
519    }
520
521    fn update_should_notify(&self, old_widget: &DefaultTextHeightBehavior) -> bool {
522        self.text_height_behavior != old_widget.text_height_behavior
523    }
524
525    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
526        Some(self)
527    }
528}
529
530impl InheritedTheme for DefaultTextHeightBehavior {
531    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
532        DefaultTextHeightBehavior::new(self.text_height_behavior, child).into_widget()
533    }
534}
535
536// ---------------------------------------------------------------------------------------------
537// Text
538
539/// A run of text with a single style.
540///
541/// The [`Text`] widget displays a string of text with single style. The string might break
542/// across multiple lines or might all be displayed on the same line depending on the layout
543/// constraints.
544///
545/// The `style` argument is optional. When omitted, the text will use the style from the
546/// closest enclosing [`DefaultTextStyle`]. If the given style's `TextStyle.inherit` property
547/// is true (the default), the given style will be merged with the closest enclosing
548/// [`DefaultTextStyle`]. This merging behavior is useful, for example, to make the text bold
549/// while using the default font family and size.
550///
551/// This example shows how to display text using the [`Text`] widget with the `overflow` set
552/// to [`TextOverflow::Ellipsis`].
553///
554/// ```text
555/// Text::new("Hello, how are you?").overflow(TextOverflow::Ellipsis)
556/// ```
557///
558/// Setting `max_lines` to `1` is not equivalent to disabling soft wrapping with `soft_wrap`.
559/// This is apparent when using [`TextOverflow::Fade`]: with `max_lines(1)` a second line
560/// overflows and the fade appears in a horizontal direction at the bottom; with
561/// `soft_wrap(false)` the single line overflows and the fade appears in a vertical direction
562/// at the right.
563///
564/// Using the [`rich`](Self::rich) constructor, the [`Text`] widget can display a paragraph
565/// with differently styled [`TextSpan`]s.
566///
567/// ## Interactivity
568///
569/// To make [`Text`] react to touch events, wrap it in a `GestureDetector` widget with a
570/// `GestureDetector.on_tap` handler.
571///
572/// To make sections of the text interactive, use [`RichText`] and specify a
573/// `TapGestureRecognizer` as the `TextSpan.recognizer` of the relevant part of the text.
574///
575/// ## Selection
576///
577/// [`Text`] is not selectable by default. To make a [`Text`] selectable, one can wrap a
578/// subtree with a `SelectionArea` widget.
579///
580/// See also:
581///
582///  * [`RichText`], which gives you more control over the text styles.
583///  * [`DefaultTextStyle`], which sets default styles for [`Text`] widgets.
584///
585/// Dart's named constructor arguments are the fluent setters
586/// (`Text::new("Hi").max_lines(1)`).
587#[derive(Debug)]
588pub struct Text {
589    /// See [`StatelessWidget::key`].
590    pub key: Option<KeyRef>,
591    /// The text to display.
592    ///
593    /// This will be `None` if a `text_span` is provided instead.
594    pub data: Option<String>,
595    /// The text to display as an [`InlineSpan`](waft_painting::InlineSpan).
596    ///
597    /// This will be `None` if `data` is provided instead.
598    pub text_span: Option<InlineSpanRef>,
599    /// If non-null, the style to use for this text.
600    ///
601    /// If the style's "inherit" property is true, the style will be merged with the closest
602    /// enclosing [`DefaultTextStyle`]. Otherwise, the style will replace the closest
603    /// enclosing [`DefaultTextStyle`].
604    pub style: Option<TextStyle>,
605    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
606    /// layout metrics.
607    ///
608    /// Omitting or providing `None` will disable strut.
609    ///
610    /// The user or platform may override this strut's [`StrutStyle::height`] via a
611    /// [`MediaQuery`] ancestor's `MediaQueryData.lineHeightScaleFactorOverride`.
612    pub strut_style: Option<StrutStyle>,
613    /// How the text should be aligned horizontally.
614    pub text_align: Option<TextAlign>,
615    /// The directionality of the text.
616    ///
617    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
618    /// are interpreted.
619    ///
620    /// This is also used to disambiguate how to render bidirectional text. For example, if
621    /// the `data` is an English phrase followed by a Hebrew phrase, in a
622    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
623    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
624    /// will be on the right and the Hebrew phrase on its left.
625    ///
626    /// Defaults to the ambient `Directionality`, if any.
627    pub text_direction: Option<TextDirection>,
628    /// Whether the text should break at soft line breaks.
629    ///
630    /// If false, the glyphs in the text will be positioned as if there was unlimited
631    /// horizontal space.
632    pub soft_wrap: Option<bool>,
633    /// How visual overflow should be handled.
634    ///
635    /// If this is `None`, `TextStyle.overflow` will be used, otherwise the value from the
636    /// nearest [`DefaultTextStyle`] ancestor will be used.
637    pub overflow: Option<TextOverflow>,
638    /// The font scaling strategy to use when laying out and rendering the text.
639    pub text_scaler: Option<TextScaler>,
640    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
641    /// the text exceeds the given number of lines, it will be truncated according to
642    /// `overflow`.
643    ///
644    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
645    /// box.
646    ///
647    /// If this is `None`, but there is an ambient [`DefaultTextStyle`] that specifies an
648    /// explicit number for its `DefaultTextStyle.max_lines`, then the [`DefaultTextStyle`]
649    /// value will take precedence. You can use a [`RichText`] widget directly to entirely
650    /// override the [`DefaultTextStyle`].
651    pub max_lines: Option<i32>,
652    /// An alternative semantics label for this text.
653    ///
654    /// If present, the semantics of this widget will contain this value instead
655    /// of the actual text. This will overwrite any of the semantics labels applied
656    /// directly to the [`TextSpan`]s.
657    ///
658    /// This is useful for replacing abbreviations or shorthands with the full
659    /// text value: `Text::new("$$").semantics_label("Double dollars")`.
660    pub semantics_label: Option<String>,
661    /// A unique identifier for the semantics node for this widget.
662    ///
663    /// This is useful for cases where the text widget needs to have a uniquely
664    /// identifiable ID that is recognized through the automation tools without
665    /// having a dependency on the actual content of the text that can possibly be
666    /// dynamic in nature.
667    pub semantics_identifier: Option<String>,
668    /// Defines how to measure the width of the rendered text.
669    pub text_width_basis: Option<TextWidthBasis>,
670    /// Defines how to apply `TextStyle.height` over and under text.
671    pub text_height_behavior: Option<TextHeightBehavior>,
672    /// The color to use when painting the selection.
673    ///
674    /// This is ignored if [`SelectionContainer::maybe_of`] returns `None` in the
675    /// [`BuildContext`] of this widget.
676    ///
677    /// If `None`, the ambient [`DefaultSelectionStyle`] is used (if any); failing that, the
678    /// selection color defaults to [`DefaultSelectionStyle::DEFAULT_COLOR`].
679    pub selection_color: Option<Color>,
680}
681
682impl Text {
683    /// Creates a text widget.
684    ///
685    /// If the `style` argument is `None`, the text will use the style from the closest
686    /// enclosing [`DefaultTextStyle`].
687    ///
688    /// The `overflow` property's behavior is affected by the `soft_wrap` argument. If the
689    /// `soft_wrap` is true or `None`, the glyph causing overflow, and those that follow, will
690    /// not be rendered. Otherwise, it will be shown with the given overflow option.
691    pub fn new(data: impl Into<String>) -> Text {
692        Text::unstyled(Some(data.into()), None)
693    }
694
695    /// Creates a text widget with an [`InlineSpan`](waft_painting::InlineSpan).
696    ///
697    /// The following subclasses of `InlineSpan` may be used to build rich text:
698    ///
699    /// * [`TextSpan`]s define text and children `InlineSpan`s.
700    /// * `WidgetSpan`s define embedded inline widgets.
701    ///
702    /// See [`RichText`] which provides a lower-level way to draw text.
703    pub fn rich(text_span: InlineSpanRef) -> Text {
704        Text::unstyled(None, Some(text_span))
705    }
706
707    /// The fields both constructors leave unset.
708    fn unstyled(data: Option<String>, text_span: Option<InlineSpanRef>) -> Text {
709        Text {
710            key: None,
711            data,
712            text_span,
713            style: None,
714            strut_style: None,
715            text_align: None,
716            text_direction: None,
717            soft_wrap: None,
718            overflow: None,
719            text_scaler: None,
720            max_lines: None,
721            semantics_label: None,
722            semantics_identifier: None,
723            text_width_basis: None,
724            text_height_behavior: None,
725            selection_color: None,
726        }
727    }
728
729    /// Dart `Text(key:)`.
730    pub fn key(mut self, key: KeyRef) -> Text {
731        self.key = Some(key);
732        self
733    }
734
735    /// Dart `Text(style:)`.
736    pub fn style(mut self, style: TextStyle) -> Text {
737        self.style = Some(style);
738        self
739    }
740
741    /// Dart `Text(strutStyle:)`.
742    pub fn strut_style(mut self, strut_style: StrutStyle) -> Text {
743        self.strut_style = Some(strut_style);
744        self
745    }
746
747    /// Dart `Text(textAlign:)`.
748    pub fn text_align(mut self, text_align: TextAlign) -> Text {
749        self.text_align = Some(text_align);
750        self
751    }
752
753    /// Dart `Text(textDirection:)`.
754    pub fn text_direction(mut self, text_direction: TextDirection) -> Text {
755        self.text_direction = Some(text_direction);
756        self
757    }
758
759    /// Dart `Text(softWrap:)`.
760    pub fn soft_wrap(mut self, soft_wrap: bool) -> Text {
761        self.soft_wrap = Some(soft_wrap);
762        self
763    }
764
765    /// Dart `Text(overflow:)`.
766    pub fn overflow(mut self, overflow: TextOverflow) -> Text {
767        self.overflow = Some(overflow);
768        self
769    }
770
771    /// Dart `Text(textScaler:)`.
772    pub fn text_scaler(mut self, text_scaler: TextScaler) -> Text {
773        self.text_scaler = Some(text_scaler);
774        self
775    }
776
777    /// Dart `Text(maxLines:)`.
778    pub fn max_lines(mut self, max_lines: i32) -> Text {
779        self.max_lines = Some(max_lines);
780        self
781    }
782
783    /// Dart `Text(semanticsLabel:)`.
784    pub fn semantics_label(mut self, semantics_label: impl Into<String>) -> Text {
785        self.semantics_label = Some(semantics_label.into());
786        self
787    }
788
789    /// Dart `Text(semanticsIdentifier:)`.
790    pub fn semantics_identifier(mut self, semantics_identifier: impl Into<String>) -> Text {
791        self.semantics_identifier = Some(semantics_identifier.into());
792        self
793    }
794
795    /// Dart `Text(textWidthBasis:)`.
796    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> Text {
797        self.text_width_basis = Some(text_width_basis);
798        self
799    }
800
801    /// Dart `Text(textHeightBehavior:)`.
802    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> Text {
803        self.text_height_behavior = Some(text_height_behavior);
804        self
805    }
806
807    /// Dart `Text(selectionColor:)`.
808    pub fn selection_color(mut self, selection_color: Color) -> Text {
809        self.selection_color = Some(selection_color);
810        self
811    }
812}
813
814impl StatelessWidget for Text {
815    fn key(&self) -> Option<&KeyRef> {
816        self.key.as_ref()
817    }
818
819    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
820        properties.add(StringProperty::new("data", self.data.clone()).with_show_name(false));
821        if let Some(text_span) = &self.text_span {
822            properties.add_rc(Rc::new(text_span.diagnostics_node(
823                Some("textSpan".to_string()),
824                Some(DiagnosticsTreeStyle::Transition),
825            )));
826        }
827        if let Some(style) = &self.style {
828            Diagnosticable::debug_fill_properties(style, properties);
829        }
830        properties
831            .add(EnumProperty::<TextAlign>::new("textAlign", self.text_align).default_value(None));
832        properties.add(
833            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
834                .default_value(None),
835        );
836        properties.add(
837            FlagProperty::new("softWrap", self.soft_wrap)
838                .if_true("wrapping at box width")
839                .if_false("no wrapping except at line break characters")
840                .with_show_name(true),
841        );
842        properties
843            .add(EnumProperty::<TextOverflow>::new("overflow", self.overflow).default_value(None));
844        properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).default_value(None));
845        properties.add(
846            EnumProperty::<TextWidthBasis>::new("textWidthBasis", self.text_width_basis)
847                .default_value(None),
848        );
849        properties.add(
850            DiagnosticsProperty::<StrutStyle>::new("strutStyle", self.strut_style.clone())
851                .default_value(None),
852        );
853        properties.add(
854            DiagnosticsProperty::<String>::new(
855                "textHeightBehavior",
856                self.text_height_behavior
857                    .map(|behavior| behavior.to_string()),
858            )
859            .default_value(None),
860        );
861    }
862
863    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
864        let default_text_style = DefaultTextStyle::of(app, context);
865        let mut effective_text_style = self.style.clone();
866        if self.style.as_ref().is_none_or(|style| style.inherit) {
867            effective_text_style = Some(default_text_style.style.merge(self.style.as_ref()));
868        }
869        if MediaQuery::bold_text_of(app, context) {
870            let bold = TextStyle::new().font_weight(FontWeight::BOLD);
871            effective_text_style = Some(
872                effective_text_style
873                    .expect("the style is set above")
874                    .merge(Some(&bold)),
875            );
876        }
877        // Flutter leaves `MediaQueryData.paragraphSpacingOverride` to its own text components.
878        let line_height_scale_factor =
879            MediaQuery::maybe_line_height_scale_factor_override_of(app, context);
880        let letter_spacing = MediaQuery::maybe_letter_spacing_override_of(app, context);
881        let word_spacing = MediaQuery::maybe_word_spacing_override_of(app, context);
882        let effective_text_span = apply_text_spacing_overrides(
883            line_height_scale_factor,
884            letter_spacing,
885            word_spacing,
886            TextSpan {
887                style: effective_text_style.clone(),
888                text: self.data.clone(),
889                children: self
890                    .text_span
891                    .as_ref()
892                    .map(|text_span| vec![text_span.clone()]),
893                ..TextSpan::default()
894            },
895        );
896        let effective_strut_style = self.strut_style.as_ref().map(|strut_style| {
897            line_height_scale_factor.map_or_else(
898                || strut_style.clone(),
899                |height| strut_style.merge(Some(&StrutStyle::new().height(height))),
900            )
901        });
902        let text_scaler = self
903            .text_scaler
904            .clone()
905            .unwrap_or_else(|| MediaQuery::text_scaler_of(app, context));
906        let text_height_behavior = self
907            .text_height_behavior
908            .or(default_text_style.text_height_behavior)
909            .or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
910        let text_align = self
911            .text_align
912            .or(default_text_style.text_align)
913            .unwrap_or(TextAlign::Start);
914        let soft_wrap = self.soft_wrap.unwrap_or(default_text_style.soft_wrap);
915        let overflow = self
916            .overflow
917            .or(effective_text_style
918                .as_ref()
919                .and_then(|style| style.overflow))
920            .unwrap_or(default_text_style.overflow);
921        let text_width_basis = self
922            .text_width_basis
923            .unwrap_or(default_text_style.text_width_basis);
924        let max_lines = self.max_lines.or(default_text_style.max_lines);
925        let default_selection_style = DefaultSelectionStyle::of(app, context);
926        let selection_color = self
927            .selection_color
928            .or_else(|| default_selection_style.selection_color.as_deref().copied())
929            .unwrap_or(DefaultSelectionStyle::DEFAULT_COLOR);
930        let registrar = SelectionContainer::maybe_of(app, context);
931        let mut result = if registrar.is_some() {
932            // A mouse hovering the selectable text shows the text cursor, as `SelectableRegion`'s
933            // text does.
934            let cursor = default_selection_style
935                .mouse_cursor
936                .clone()
937                .unwrap_or_else(|| SystemMouseCursors::TEXT.into());
938            MouseRegion::new()
939                .cursor(cursor)
940                .child(SelectableTextContainer {
941                    text: effective_text_span,
942                    text_align,
943                    text_direction: self.text_direction,
944                    soft_wrap,
945                    overflow,
946                    text_scaler,
947                    max_lines,
948                    text_width_basis,
949                    text_height_behavior,
950                    strut_style: effective_strut_style,
951                    selection_color,
952                })
953                .into_widget()
954        } else {
955            let mut rich_text = RichText::new(effective_text_span.into_span())
956                .text_align(text_align)
957                .soft_wrap(soft_wrap)
958                .overflow(overflow)
959                .text_scaler(text_scaler)
960                .text_width_basis(text_width_basis)
961                .selection_color(selection_color);
962            // RichText uses Directionality.of to obtain a default if this is None.
963            if let Some(text_direction) = self.text_direction {
964                rich_text = rich_text.text_direction(text_direction);
965            }
966            if let Some(max_lines) = max_lines {
967                rich_text = rich_text.max_lines(max_lines);
968            }
969            if let Some(text_height_behavior) = text_height_behavior {
970                rich_text = rich_text.text_height_behavior(text_height_behavior);
971            }
972            if let Some(strut_style) = effective_strut_style {
973                rich_text = rich_text.strut_style(strut_style);
974            }
975            rich_text.into_widget()
976        };
977        if self.semantics_label.is_some() || self.semantics_identifier.is_some() {
978            let mut semantics = Semantics::new();
979            if let Some(text_direction) = self.text_direction {
980                semantics = semantics.text_direction(text_direction);
981            }
982            if let Some(semantics_label) = &self.semantics_label {
983                semantics = semantics.label(semantics_label.clone());
984            }
985            if let Some(semantics_identifier) = &self.semantics_identifier {
986                semantics = semantics.identifier(semantics_identifier.clone());
987            }
988            result = semantics
989                .child(
990                    ExcludeSemantics::new()
991                        .excluding(self.semantics_label.is_some())
992                        .child(result),
993                )
994                .into_widget();
995        }
996        result
997    }
998}
999
1000// ---------------------------------------------------------------------------------------------
1001// SelectableTextContainer
1002
1003/// Dart's `_SelectableTextContainer`: the [`SelectionContainer`] a selectable [`Text`] builds, so
1004/// that its paragraph's selectables register with it and its delegate handles the paragraph's
1005/// selection.
1006#[derive(Debug)]
1007struct SelectableTextContainer {
1008    text: TextSpan,
1009    text_align: TextAlign,
1010    text_direction: Option<TextDirection>,
1011    soft_wrap: bool,
1012    overflow: TextOverflow,
1013    text_scaler: TextScaler,
1014    max_lines: Option<i32>,
1015    text_width_basis: TextWidthBasis,
1016    text_height_behavior: Option<TextHeightBehavior>,
1017    strut_style: Option<StrutStyle>,
1018    selection_color: Color,
1019}
1020
1021impl StatefulWidget for SelectableTextContainer {
1022    type State = SelectableTextContainerState;
1023
1024    fn create_state(&self) -> SelectableTextContainerState {
1025        SelectableTextContainerState {
1026            state: StateData::new(),
1027            selection_delegate: None,
1028            text_key: GlobalKey::new(),
1029        }
1030    }
1031}
1032
1033/// The state of a [`SelectableTextContainer`]: Dart's `_SelectableTextContainerState`.
1034struct SelectableTextContainerState {
1035    state: StateData<SelectableTextContainer>,
1036    selection_delegate: Option<Ref<SelectableTextContainerDelegate>>,
1037    /// The key of the paragraph below, which the delegate finds its `RenderParagraph` by.
1038    text_key: GlobalKey,
1039}
1040
1041impl SelectableTextContainerState {
1042    fn selection_delegate(
1043        self: Handle<Self>,
1044        app: &App,
1045    ) -> Handle<SelectableTextContainerDelegate> {
1046        app.get(self)
1047            .selection_delegate
1048            .as_ref()
1049            .expect("the delegate is created in init_state")
1050            .handle()
1051    }
1052}
1053
1054impl State for SelectableTextContainerState {
1055    type Widget = SelectableTextContainer;
1056    crate::state_accessors!();
1057
1058    fn init_state(self: Handle<Self>, app: &mut App) {
1059        let text_key = app.get(self).text_key.clone();
1060        let delegate = SelectableTextContainerDelegate::new(app, text_key);
1061        app.get_mut(self).selection_delegate = Some(delegate);
1062    }
1063
1064    fn dispose(self: Handle<Self>, app: &mut App) {
1065        let delegate = self.selection_delegate(app);
1066        MultiSelectableSelectionContainerDelegate::dispose(delegate, app);
1067    }
1068
1069    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1070        let delegate = self.selection_delegate(app).keep(app).into_erased();
1071        let widget = self.widget(app);
1072        SelectionContainer::new(
1073            delegate,
1074            SelectableRichText {
1075                text_key: app.get(self).text_key.clone(),
1076                text: widget.text.clone(),
1077                text_align: widget.text_align,
1078                text_direction: widget.text_direction,
1079                soft_wrap: widget.soft_wrap,
1080                overflow: widget.overflow,
1081                text_scaler: widget.text_scaler.clone(),
1082                max_lines: widget.max_lines,
1083                text_width_basis: widget.text_width_basis,
1084                text_height_behavior: widget.text_height_behavior,
1085                strut_style: widget.strut_style.clone(),
1086                selection_color: widget.selection_color,
1087            },
1088        )
1089        .into_widget()
1090    }
1091}
1092
1093/// Dart's `_RichText`: the [`RichText`] under the container, which reads the container's
1094/// registrar and registers the paragraph's selectables with it.
1095#[derive(Debug)]
1096struct SelectableRichText {
1097    text_key: GlobalKey,
1098    text: TextSpan,
1099    text_align: TextAlign,
1100    text_direction: Option<TextDirection>,
1101    soft_wrap: bool,
1102    overflow: TextOverflow,
1103    text_scaler: TextScaler,
1104    max_lines: Option<i32>,
1105    text_width_basis: TextWidthBasis,
1106    text_height_behavior: Option<TextHeightBehavior>,
1107    strut_style: Option<StrutStyle>,
1108    selection_color: Color,
1109}
1110
1111impl StatelessWidget for SelectableRichText {
1112    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1113        let registrar = SelectionContainer::maybe_of(app, context)
1114            .expect("the text's own selection container hosts a registrar");
1115        let mut rich_text = RichText::new(self.text.clone().into_span())
1116            .key(KeyRef::Global(self.text_key.clone()))
1117            .text_align(self.text_align)
1118            .soft_wrap(self.soft_wrap)
1119            .overflow(self.overflow)
1120            .text_scaler(self.text_scaler.clone())
1121            .text_width_basis(self.text_width_basis)
1122            .selection_registrar(registrar)
1123            .selection_color(self.selection_color);
1124        if let Some(text_direction) = self.text_direction {
1125            rich_text = rich_text.text_direction(text_direction);
1126        }
1127        if let Some(max_lines) = self.max_lines {
1128            rich_text = rich_text.max_lines(max_lines);
1129        }
1130        if let Some(text_height_behavior) = self.text_height_behavior {
1131            rich_text = rich_text.text_height_behavior(text_height_behavior);
1132        }
1133        if let Some(strut_style) = self.strut_style.clone() {
1134            rich_text = rich_text.strut_style(strut_style);
1135        }
1136        rich_text.into_widget()
1137    }
1138}
1139
1140// ---------------------------------------------------------------------------------------------
1141// SelectableTextContainerDelegate
1142
1143/// Dart's `_SelectableTextContainerDelegate`: the delegate of a [`Text`]'s selection container.
1144///
1145/// It handles the paragraph's selection across the fragments a `WidgetSpan` splits it into, and
1146/// finds its `RenderParagraph` through the container's global key.
1147struct SelectableTextContainerDelegate {
1148    selection_container_delegate: SelectionContainerDelegateData,
1149    multi_selectable_selection_container_delegate: MultiSelectableSelectionContainerDelegateData,
1150    static_selection_container_delegate: StaticSelectionContainerDelegateData,
1151    /// The key of the paragraph this delegate handles the selection of.
1152    text_key: GlobalKey,
1153    /// Where each fragment of the paragraph after its first starts in it, recorded when the
1154    /// selectables change: reading it needs `&mut App`, and `selection` has `&App` (see
1155    /// `PORTING.md`).
1156    selectable_content_starts: Vec<(AnySelectable, i32)>,
1157}
1158
1159impl SelectableTextContainerDelegate {
1160    fn new(app: &mut App, text_key: GlobalKey) -> Ref<SelectableTextContainerDelegate> {
1161        app.create(SelectableTextContainerDelegate {
1162            selection_container_delegate: SelectionContainerDelegateData::new(),
1163            multi_selectable_selection_container_delegate:
1164                MultiSelectableSelectionContainerDelegateData::new(),
1165            static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
1166            text_key,
1167            selectable_content_starts: Vec::new(),
1168        })
1169    }
1170
1171    /// Dart's `paragraph` getter.
1172    fn paragraph(self: Handle<Self>, app: &App) -> RenderHandle<RenderParagraph> {
1173        let context = app
1174            .get(self)
1175            .text_key
1176            .current_context(app)
1177            .expect("the text's paragraph is in the tree");
1178        context
1179            .find_render_object(app)
1180            .expect("the text's paragraph has a render object")
1181            .downcast::<RenderParagraph>(app)
1182            .expect("the text's render object is a RenderParagraph")
1183    }
1184
1185    /// Where `selectable` starts in the paragraph, as recorded by
1186    /// [`record_selectable_content_starts`](Self::record_selectable_content_starts).
1187    fn selectable_content_start(
1188        self: Handle<Self>,
1189        app: &App,
1190        selectable: AnySelectable,
1191    ) -> Option<i32> {
1192        app.get(self)
1193            .selectable_content_starts
1194            .iter()
1195            .find_map(|(held, start)| (*held == selectable).then_some(*start))
1196    }
1197
1198    /// Records where each fragment after the paragraph's first starts in it: Flutter reads it
1199    /// from the fragment's first box when it computes the range, which needs `&mut App` there.
1200    fn record_selectable_content_starts(self: Handle<Self>, app: &mut App) {
1201        let selectables = self
1202            .multi_selectable_selection_container_delegate_data(app)
1203            .selectables
1204            .clone();
1205        let mut starts = Vec::new();
1206        for (index, selectable) in selectables.iter().enumerate() {
1207            if index == 0 {
1208                continue;
1209            }
1210            let paragraph = self.paragraph(app);
1211            if !paragraph.selectable_belongs_to_paragraph(app, *selectable) {
1212                continue;
1213            }
1214            let Some(first_box) = selectable.bounding_boxes(app).into_iter().next() else {
1215                continue;
1216            };
1217            let position = paragraph.get_position_for_offset(app, first_box.center_left());
1218            starts.push((*selectable, position.offset));
1219        }
1220        app.get_mut(self).selectable_content_starts = starts;
1221    }
1222
1223    /// Dart's `compareOrder` for a text paragraph: sorts the selectables by their first
1224    /// bounding box's top left, where the multi-selectable delegate sorts by their union.
1225    fn compare_top_left_screen_order(
1226        self: Handle<Self>,
1227        app: &mut App,
1228        a: AnySelectable,
1229        b: AnySelectable,
1230    ) -> Ordering {
1231        let rect_a = transform_rect(
1232            &a.get_transform_to(app, None),
1233            a.bounding_boxes(app)
1234                .into_iter()
1235                .next()
1236                .expect("a selectable has a bounding box"),
1237        );
1238        let rect_b = transform_rect(
1239            &b.get_transform_to(app, None),
1240            b.bounding_boxes(app)
1241                .into_iter()
1242                .next()
1243                .expect("a selectable has a bounding box"),
1244        );
1245        let result = compare_vertically(rect_a, rect_b);
1246        if result != Ordering::Equal {
1247            return result;
1248        }
1249        compare_horizontally(rect_a, rect_b)
1250    }
1251
1252    /// Dart's `handleSelectParagraph`, whose own body is `_handleSelectParagraph`.
1253    fn handle_select_paragraph_body(
1254        self: Handle<Self>,
1255        app: &mut App,
1256        event: &SelectionEvent,
1257    ) -> SelectionResult {
1258        let SelectionEvent::SelectParagraph {
1259            global_position,
1260            absorb,
1261        } = event
1262        else {
1263            panic!("a paragraph selection event selects a paragraph");
1264        };
1265        let global_position = *global_position;
1266        let selectables = self
1267            .multi_selectable_selection_container_delegate_data(app)
1268            .selectables
1269            .clone();
1270        if *absorb {
1271            for selectable in &selectables {
1272                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1273                    self,
1274                    app,
1275                    *selectable,
1276                    event,
1277                );
1278            }
1279            let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1280            data.current_selection_start_index = 0;
1281            data.current_selection_end_index = selectables.len() as i32 - 1;
1282            return SelectionResult::Next;
1283        }
1284
1285        // First pass: if the position is on a placeholder, dispatch the selection event to the
1286        // selectable at the location and terminate.
1287        let paragraph = self.paragraph(app);
1288        for (index, selectable) in selectables.iter().enumerate() {
1289            let selectable_is_placeholder =
1290                !paragraph.selectable_belongs_to_paragraph(app, *selectable);
1291            if selectable_is_placeholder {
1292                let boxes = selectable.bounding_boxes(app);
1293                if !boxes.is_empty() {
1294                    let transform = selectable.get_transform_to(app, None);
1295                    for rect in boxes {
1296                        let global_rect = transform_rect(&transform, rect);
1297                        if global_rect.contains(global_position) {
1298                            let data =
1299                                self.multi_selectable_selection_container_delegate_data_mut(app);
1300                            data.current_selection_start_index = index as i32;
1301                            data.current_selection_end_index = index as i32;
1302                            return MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1303                                self, app, *selectable, event,
1304                            );
1305                        }
1306                    }
1307                }
1308            }
1309        }
1310
1311        let mut last_selection_result: Option<SelectionResult> = None;
1312        let mut found_start = false;
1313        let mut last_next_index: Option<i32> = None;
1314        for (index, selectable) in selectables.iter().enumerate() {
1315            if !paragraph.selectable_belongs_to_paragraph(app, *selectable) {
1316                if found_start {
1317                    let synthesized_event = SelectionEvent::SelectParagraph {
1318                        global_position,
1319                        absorb: true,
1320                    };
1321                    let result =
1322                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1323                            self,
1324                            app,
1325                            *selectable,
1326                            &synthesized_event,
1327                        );
1328                    if selectables.len() - 1 == index {
1329                        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1330                        data.current_selection_end_index = index as i32;
1331                        MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(
1332                            self, app,
1333                        );
1334                        return result;
1335                    }
1336                }
1337                continue;
1338            }
1339            let existing_geometry = selectable.value(app);
1340            last_selection_result = Some(
1341                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1342                    self,
1343                    app,
1344                    *selectable,
1345                    event,
1346                ),
1347            );
1348            let result = last_selection_result.expect("assigned just now");
1349            if index == selectables.len() - 1 && result == SelectionResult::Next {
1350                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1351                if found_start {
1352                    data.current_selection_end_index = index as i32;
1353                } else {
1354                    data.current_selection_start_index = index as i32;
1355                    data.current_selection_end_index = index as i32;
1356                }
1357                return SelectionResult::Next;
1358            }
1359            if result == SelectionResult::Next {
1360                if selectable.value(app) == existing_geometry && !found_start {
1361                    last_next_index = Some(index as i32);
1362                }
1363                if selectable.value(app) != existing_geometry && !found_start {
1364                    let boxes = selectable.bounding_boxes(app);
1365                    debug_assert!(!boxes.is_empty());
1366                    let selection_rects = selectable.value(app).selection_rects;
1367                    debug_assert!(!selection_rects.is_empty());
1368                    let selection_at_start_of_selectable = boxes[0].overlaps(selection_rects[0]);
1369                    let start_index = if let Some(last_next_index) = last_next_index
1370                        && selection_at_start_of_selectable
1371                    {
1372                        last_next_index + 1
1373                    } else if last_next_index.is_none() && selection_at_start_of_selectable {
1374                        0
1375                    } else {
1376                        index as i32
1377                    };
1378                    for selectable in &selectables[start_index as usize..index] {
1379                        let synthesized_event = SelectionEvent::SelectParagraph {
1380                            global_position,
1381                            absorb: true,
1382                        };
1383                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1384                            self,
1385                            app,
1386                            *selectable,
1387                            &synthesized_event,
1388                        );
1389                    }
1390                    let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1391                    data.current_selection_start_index = start_index;
1392                    found_start = true;
1393                }
1394                continue;
1395            }
1396            if index == 0 && result == SelectionResult::Previous {
1397                return SelectionResult::Previous;
1398            }
1399            if selectable.value(app) != existing_geometry {
1400                if !found_start && last_next_index.is_none() {
1401                    let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1402                    data.current_selection_start_index = 0;
1403                    for selectable in &selectables[..index] {
1404                        let synthesized_event = SelectionEvent::SelectParagraph {
1405                            global_position,
1406                            absorb: true,
1407                        };
1408                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1409                            self,
1410                            app,
1411                            *selectable,
1412                            &synthesized_event,
1413                        );
1414                    }
1415                }
1416                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1417                data.current_selection_end_index = index as i32;
1418                // Geometry changed as a result of selecting a paragraph; clear the other
1419                // selectables to keep the selection in sync.
1420                MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(self, app);
1421            }
1422            return SelectionResult::End;
1423        }
1424        debug_assert!(last_selection_result.is_none());
1425        SelectionResult::End
1426    }
1427
1428    /// Dart's `_adjustSelection`: [`MultiSelectableSelectionContainerDelegateBase::adjust_selection`]
1429    /// with the crossing of the opposite edge that a paragraph selection needs.
1430    fn adjust_selection(
1431        self: Handle<Self>,
1432        app: &mut App,
1433        event: &SelectionEvent,
1434        is_end: bool,
1435    ) -> SelectionResult {
1436        let selectables = self
1437            .multi_selectable_selection_container_delegate_data(app)
1438            .selectables
1439            .clone();
1440        let value = SelectionHandler::value(self, app);
1441        let is_current_edge_within_viewport = if is_end {
1442            value.end_selection_point.is_some()
1443        } else {
1444            value.start_selection_point.is_some()
1445        };
1446        let is_opposite_edge_within_viewport = if is_end {
1447            value.start_selection_point.is_some()
1448        } else {
1449            value.end_selection_point.is_some()
1450        };
1451        let data = self.multi_selectable_selection_container_delegate_data(app);
1452        let mut new_index: i32 = if is_end {
1453            if is_current_edge_within_viewport {
1454                data.current_selection_end_index
1455            } else if is_opposite_edge_within_viewport {
1456                data.current_selection_start_index
1457            } else {
1458                0
1459            }
1460        } else if is_current_edge_within_viewport {
1461            data.current_selection_start_index
1462        } else if is_opposite_edge_within_viewport {
1463            data.current_selection_end_index
1464        } else {
1465            0
1466        };
1467        debug_assert!(new_index < selectables.len() as i32 && new_index >= 0);
1468        let mut forward: Option<bool> = None;
1469        let mut final_result: Option<SelectionResult> = None;
1470        while (new_index as usize) < selectables.len() && new_index >= 0 && final_result.is_none() {
1471            let current_selectable_result =
1472                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1473                    self,
1474                    app,
1475                    selectables[new_index as usize],
1476                    event,
1477                );
1478            match current_selectable_result {
1479                SelectionResult::End | SelectionResult::Pending | SelectionResult::None => {
1480                    final_result = Some(current_selectable_result);
1481                }
1482                SelectionResult::Next => {
1483                    if forward == Some(false) {
1484                        new_index += 1;
1485                        final_result = Some(SelectionResult::End);
1486                    } else if new_index as usize == selectables.len() - 1 {
1487                        final_result = Some(current_selectable_result);
1488                    } else {
1489                        forward = Some(true);
1490                        new_index += 1;
1491                    }
1492                }
1493                SelectionResult::Previous => {
1494                    if forward == Some(true) {
1495                        new_index -= 1;
1496                        final_result = Some(SelectionResult::End);
1497                    } else if new_index == 0 {
1498                        final_result = Some(current_selectable_result);
1499                    } else {
1500                        forward = Some(false);
1501                        new_index -= 1;
1502                    }
1503                }
1504            }
1505        }
1506        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1507        if is_end {
1508            let forward_selection =
1509                data.current_selection_end_index >= data.current_selection_start_index;
1510            if let Some(forward) = forward
1511                && ((!forward_selection
1512                    && forward
1513                    && new_index >= data.current_selection_start_index)
1514                    || (forward_selection
1515                        && !forward
1516                        && new_index <= data.current_selection_start_index))
1517            {
1518                data.current_selection_start_index = data.current_selection_end_index;
1519            }
1520            data.current_selection_end_index = new_index;
1521        } else {
1522            let forward_selection =
1523                data.current_selection_end_index >= data.current_selection_start_index;
1524            if let Some(forward) = forward
1525                && ((!forward_selection
1526                    && !forward
1527                    && new_index <= data.current_selection_end_index)
1528                    || (forward_selection
1529                        && forward
1530                        && new_index >= data.current_selection_end_index))
1531            {
1532                data.current_selection_end_index = data.current_selection_start_index;
1533            }
1534            data.current_selection_start_index = new_index;
1535        }
1536        MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(self, app);
1537        final_result.expect("the loop answered a result")
1538    }
1539
1540    /// Dart's `_calculateLocalRange`: the selectables' ranges, with a fragment that is not the
1541    /// paragraph's first offset by where it starts in the paragraph.
1542    fn calculate_local_range(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
1543        let data = self.multi_selectable_selection_container_delegate_data(app);
1544        if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
1545            return None;
1546        }
1547        let selectables = data.selectables.clone();
1548        let mut start_offset = 0i32;
1549        let mut end_offset = 0i32;
1550        let mut found_start = false;
1551        let mut forward_selection =
1552            data.current_selection_end_index >= data.current_selection_start_index;
1553        if data.current_selection_end_index == data.current_selection_start_index {
1554            // Determining the direction is inaccurate when both edges share a selectable; the
1555            // range within it is the source of truth.
1556            let range = selectables[data.current_selection_start_index as usize]
1557                .selection(app)
1558                .expect("the selectable holding both edges has a selection");
1559            forward_selection = range.end_offset >= range.start_offset;
1560        }
1561        for (index, selectable) in selectables.iter().enumerate() {
1562            let Some(range) = selectable.selection(app) else {
1563                if found_start {
1564                    return Some(SelectedContentRange::new(
1565                        if forward_selection {
1566                            start_offset
1567                        } else {
1568                            end_offset
1569                        },
1570                        if forward_selection {
1571                            end_offset
1572                        } else {
1573                            start_offset
1574                        },
1575                    ));
1576                }
1577                start_offset += selectable.content_length(app) as i32;
1578                end_offset = start_offset;
1579                continue;
1580            };
1581            let selection_start_normalized = range.start_offset.min(range.end_offset);
1582            let selection_end_normalized = range.start_offset.max(range.end_offset);
1583            if !found_start {
1584                // A `RenderParagraph` may split its content into several selectables, so a
1585                // fragment that is not the paragraph's first starts partway through it.
1586                let should_consider_content_start = index > 0
1587                    && self
1588                        .paragraph(app)
1589                        .selectable_belongs_to_paragraph(app, *selectable);
1590                let selectable_content_start = if should_consider_content_start {
1591                    self.selectable_content_start(app, *selectable)
1592                        .expect("a fragment's start is recorded when the selectables change")
1593                } else {
1594                    0
1595                };
1596                start_offset += (selection_start_normalized - selectable_content_start).abs();
1597                end_offset =
1598                    start_offset + (selection_end_normalized - selection_start_normalized).abs();
1599                found_start = true;
1600            } else {
1601                end_offset += (selection_end_normalized - selection_start_normalized).abs();
1602            }
1603        }
1604        debug_assert!(
1605            found_start,
1606            "The start of the selection has not been found despite this selection delegate \
1607             having an existing currentSelectionStartIndex and currentSelectionEndIndex."
1608        );
1609        Some(SelectedContentRange::new(
1610            if forward_selection {
1611                start_offset
1612            } else {
1613                end_offset
1614            },
1615            if forward_selection {
1616                end_offset
1617            } else {
1618                start_offset
1619            },
1620        ))
1621    }
1622}
1623
1624impl SelectionContainerDelegate for SelectableTextContainerDelegate {
1625    fn selection_container_delegate_data(
1626        self: Handle<Self>,
1627        app: &App,
1628    ) -> &SelectionContainerDelegateData {
1629        &app.get(self).selection_container_delegate
1630    }
1631
1632    fn selection_container_delegate_data_mut(
1633        self: Handle<Self>,
1634        app: &mut App,
1635    ) -> &mut SelectionContainerDelegateData {
1636        &mut app.get_mut(self).selection_container_delegate
1637    }
1638}
1639
1640impl MultiSelectableSelectionContainerDelegate for SelectableTextContainerDelegate {
1641    crate::multi_selectable_selection_container_delegate_accessors!();
1642
1643    fn did_change_selectables(self: Handle<Self>, app: &mut App) {
1644        self.record_selectable_content_starts(app);
1645        StaticSelectionContainerDelegateBase::did_change_selectables(self, app);
1646    }
1647
1648    fn compare_order(
1649        self: Handle<Self>,
1650        app: &mut App,
1651        a: AnySelectable,
1652        b: AnySelectable,
1653    ) -> Ordering {
1654        self.compare_top_left_screen_order(app, a, b)
1655    }
1656
1657    fn handle_select_all(
1658        self: Handle<Self>,
1659        app: &mut App,
1660        event: &SelectionEvent,
1661    ) -> SelectionResult {
1662        StaticSelectionContainerDelegateBase::handle_select_all(self, app, event)
1663    }
1664
1665    fn handle_select_word(
1666        self: Handle<Self>,
1667        app: &mut App,
1668        event: &SelectionEvent,
1669    ) -> SelectionResult {
1670        StaticSelectionContainerDelegateBase::handle_select_word(self, app, event)
1671    }
1672
1673    fn handle_select_paragraph(
1674        self: Handle<Self>,
1675        app: &mut App,
1676        event: &SelectionEvent,
1677    ) -> SelectionResult {
1678        let result = self.handle_select_paragraph_body(app, event);
1679        StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
1680        result
1681    }
1682
1683    fn handle_clear_selection(
1684        self: Handle<Self>,
1685        app: &mut App,
1686        event: &SelectionEvent,
1687    ) -> SelectionResult {
1688        StaticSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
1689    }
1690
1691    fn handle_selection_edge_update(
1692        self: Handle<Self>,
1693        app: &mut App,
1694        event: &SelectionEvent,
1695    ) -> SelectionResult {
1696        let (global_position, for_end, granularity) = match event {
1697            SelectionEvent::StartEdgeUpdate {
1698                global_position,
1699                granularity,
1700            } => (*global_position, false, *granularity),
1701            SelectionEvent::EndEdgeUpdate {
1702                global_position,
1703                granularity,
1704            } => (*global_position, true, *granularity),
1705            _ => panic!("a selection edge update names an edge"),
1706        };
1707        if granularity != waft_rendering::TextGranularity::Paragraph {
1708            return StaticSelectionContainerDelegateBase::handle_selection_edge_update(
1709                self, app, event,
1710            );
1711        }
1712        StaticSelectionContainerDelegate::update_last_selection_edge_location(
1713            self,
1714            app,
1715            global_position,
1716            for_end,
1717        );
1718        let selection_index = {
1719            let data = self.multi_selectable_selection_container_delegate_data(app);
1720            if for_end {
1721                data.current_selection_end_index
1722            } else {
1723                data.current_selection_start_index
1724            }
1725        };
1726        if selection_index == -1 {
1727            return StaticSelectionContainerDelegateBase::handle_selection_edge_update(
1728                self, app, event,
1729            );
1730        }
1731        self.adjust_selection(app, event, for_end)
1732    }
1733
1734    fn dispose(self: Handle<Self>, app: &mut App) {
1735        StaticSelectionContainerDelegateBase::dispose(self, app);
1736    }
1737
1738    fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
1739        StaticSelectionContainerDelegateBase::ensure_child_updated(self, app, selectable);
1740    }
1741
1742    fn dispatch_selection_event_to_child(
1743        self: Handle<Self>,
1744        app: &mut App,
1745        selectable: AnySelectable,
1746        event: &SelectionEvent,
1747    ) -> SelectionResult {
1748        StaticSelectionContainerDelegateBase::dispatch_selection_event_to_child(
1749            self, app, selectable, event,
1750        )
1751    }
1752}
1753
1754impl StaticSelectionContainerDelegate for SelectableTextContainerDelegate {
1755    crate::static_selection_container_delegate_accessors!();
1756}
1757
1758impl SelectionHandler for SelectableTextContainerDelegate {
1759    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
1760        StaticSelectionContainerDelegateBase::value(self, app)
1761    }
1762
1763    fn push_handle_layers(
1764        self: Handle<Self>,
1765        app: &mut App,
1766        start_handle: Option<Ref<waft_rendering::LayerLink>>,
1767        end_handle: Option<Ref<waft_rendering::LayerLink>>,
1768    ) {
1769        StaticSelectionContainerDelegateBase::push_handle_layers(
1770            self,
1771            app,
1772            start_handle,
1773            end_handle,
1774        );
1775    }
1776
1777    fn selected_content(self: Handle<Self>, app: &App) -> Option<waft_rendering::SelectedContent> {
1778        StaticSelectionContainerDelegateBase::selected_content(self, app)
1779    }
1780
1781    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
1782        self.calculate_local_range(app)
1783    }
1784
1785    fn dispatch_selection_event(
1786        self: Handle<Self>,
1787        app: &mut App,
1788        event: &SelectionEvent,
1789    ) -> SelectionResult {
1790        StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
1791    }
1792
1793    fn content_length(self: Handle<Self>, app: &App) -> usize {
1794        StaticSelectionContainerDelegateBase::content_length(self, app)
1795    }
1796}
1797
1798impl SelectionRegistrar for SelectableTextContainerDelegate {
1799    crate::static_selection_container_delegate_selection_registrar!();
1800}
1801
1802impl ChangeNotifier for SelectableTextContainerDelegate {
1803    fn change_notifier_data(&self) -> &ChangeNotifierData {
1804        &self
1805            .multi_selectable_selection_container_delegate
1806            .change_notifier
1807    }
1808
1809    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1810        &mut self
1811            .multi_selectable_selection_container_delegate
1812            .change_notifier
1813    }
1814}
1815
1816// ---------------------------------------------------------------------------------------------
1817// ---------------------------------------------------------------------------------------------
1818// RichText (basic.dart)
1819
1820/// Dart's `_OverridingTextStyleTextSpanUtils.applyTextSpacingOverrides`: overrides the text
1821/// styles of a [`TextSpan`] tree with the `MediaQuery` spacing overrides.
1822pub(crate) fn apply_text_spacing_overrides(
1823    line_height_scale_factor: Option<f64>,
1824    letter_spacing: Option<f64>,
1825    word_spacing: Option<f64>,
1826    text_span: TextSpan,
1827) -> TextSpan {
1828    if line_height_scale_factor.is_none() && letter_spacing.is_none() && word_spacing.is_none() {
1829        return text_span;
1830    }
1831    let mut override_text_style = TextStyle::new();
1832    if let Some(height) = line_height_scale_factor {
1833        override_text_style = override_text_style.height(height);
1834    }
1835    if let Some(letter_spacing) = letter_spacing {
1836        override_text_style = override_text_style.letter_spacing(letter_spacing);
1837    }
1838    if let Some(word_spacing) = word_spacing {
1839        override_text_style = override_text_style.word_spacing(word_spacing);
1840    }
1841    apply_text_style_overrides(&override_text_style, &text_span)
1842}
1843
1844/// Dart's `_OverridingTextStyleTextSpanUtils._applyTextStyleOverrides`.
1845fn apply_text_style_overrides(override_text_style: &TextStyle, text_span: &TextSpan) -> TextSpan {
1846    TextSpan {
1847        text: text_span.text.clone(),
1848        children: text_span.children.as_ref().map(|children| {
1849            children
1850                .iter()
1851                .map(|child| match child.as_any().downcast_ref::<TextSpan>() {
1852                    Some(child) => {
1853                        apply_text_style_overrides(override_text_style, child).into_span()
1854                    }
1855                    None => child.clone(),
1856                })
1857                .collect()
1858        }),
1859        style: Some(match &text_span.style {
1860            Some(style) => style.merge(Some(override_text_style)),
1861            None => override_text_style.clone(),
1862        }),
1863        recognizer: text_span.recognizer.clone(),
1864        mouse_cursor: text_span.mouse_cursor.clone(),
1865        on_enter: text_span.on_enter.clone(),
1866        on_exit: text_span.on_exit.clone(),
1867    }
1868}
1869
1870/// A paragraph of rich text.
1871///
1872/// The [`RichText`] widget displays text that uses multiple different styles. The text to
1873/// display is described using a tree of [`TextSpan`] objects, each of which has an
1874/// associated style that is used for that subtree. The text might break across multiple
1875/// lines or might all be displayed on the same line depending on the layout constraints.
1876///
1877/// Text displayed in a [`RichText`] widget must be explicitly styled. When picking which
1878/// style to use, consider using [`DefaultTextStyle::of`] the current [`BuildContext`] to
1879/// provide defaults. For more details on how to style text in a [`RichText`] widget, see the
1880/// documentation for [`TextStyle`].
1881///
1882/// Consider using the [`Text`] widget to integrate with the [`DefaultTextStyle`]
1883/// automatically. When all the text uses the same style, the default constructor is less
1884/// verbose. The [`Text::rich`] constructor allows you to style multiple spans with the
1885/// default text style while still allowing specified styles per span.
1886///
1887/// ```text
1888/// RichText::new(
1889///     TextSpan::new()
1890///         .text("Hello ")
1891///         .style(DefaultTextStyle::of(app, context).style)
1892///         .children(vec![
1893///             TextSpan::new().text("bold").style(TextStyle::new().font_weight(FontWeight::BOLD)).into_span(),
1894///             TextSpan::new().text(" world!").into_span(),
1895///         ])
1896///         .into_span(),
1897/// )
1898/// ```
1899///
1900/// See also:
1901///
1902///  * [`TextStyle`], which discusses how to style text.
1903///  * [`TextSpan`], which is used to describe the text in a paragraph.
1904///  * [`Text`], which automatically applies the ambient styles described by a
1905///    [`DefaultTextStyle`] to a single string.
1906///  * [`Text::rich`], a text widget that provides similar functionality as [`RichText`].
1907///    [`Text::rich`] will inherit [`TextStyle`] from [`DefaultTextStyle`].
1908///
1909/// Dart's named constructor arguments are the fluent setters
1910/// (`RichText::new(span).text_align(TextAlign::Center)`).
1911#[derive(Debug)]
1912pub struct RichText {
1913    /// See [`RenderObjectWidget::key`].
1914    pub key: Option<KeyRef>,
1915    /// The text to display in this widget.
1916    pub text: InlineSpanRef,
1917    /// The inline widgets of [`text`](Self::text), its `WidgetSpan`s at
1918    /// [`text_scaler`](Self::text_scaler), as Dart's constructor extracts them.
1919    children: Vec<WidgetRef>,
1920    /// How the text should be aligned horizontally.
1921    pub text_align: TextAlign,
1922    /// The directionality of the text.
1923    ///
1924    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
1925    /// are interpreted.
1926    ///
1927    /// This is also used to disambiguate how to render bidirectional text. For example, if
1928    /// the `text` is an English phrase followed by a Hebrew phrase, in a
1929    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
1930    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
1931    /// will be on the right and the Hebrew phrase on its left.
1932    ///
1933    /// Defaults to the ambient `Directionality`, if any. If there is no ambient
1934    /// `Directionality`, then this must not be `None`.
1935    pub text_direction: Option<TextDirection>,
1936    /// Whether the text should break at soft line breaks.
1937    ///
1938    /// If false, the glyphs in the text will be positioned as if there was unlimited
1939    /// horizontal space.
1940    pub soft_wrap: bool,
1941    /// How visual overflow should be handled.
1942    pub overflow: TextOverflow,
1943    /// The font scaling strategy to use when laying out and rendering the text.
1944    pub text_scaler: TextScaler,
1945    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
1946    /// the text exceeds the given number of lines, it will be truncated according to
1947    /// `overflow`.
1948    ///
1949    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
1950    /// box.
1951    pub max_lines: Option<i32>,
1952    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
1953    /// layout metrics.
1954    pub strut_style: Option<StrutStyle>,
1955    /// Defines how to measure the width of the rendered text.
1956    pub text_width_basis: TextWidthBasis,
1957    /// Defines how to apply `TextStyle.height` over and under text.
1958    pub text_height_behavior: Option<TextHeightBehavior>,
1959    /// The [`SelectionRegistrar`](waft_rendering::SelectionRegistrar) this rich text is
1960    /// subscribed to.
1961    ///
1962    /// If this is set, [`selection_color`](Self::selection_color) must be non-null.
1963    pub selection_registrar: Option<SelectionRegistrarRef>,
1964    /// The color to use when painting the selection.
1965    pub selection_color: Option<Color>,
1966}
1967
1968impl RichText {
1969    /// Creates a paragraph of rich text.
1970    ///
1971    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
1972    /// not `None`, it must be greater than zero.
1973    ///
1974    /// The `text_direction`, if `None`, defaults to the ambient `Directionality`, which in
1975    /// that case must not be null.
1976    pub fn new(text: InlineSpanRef) -> RichText {
1977        RichText {
1978            key: None,
1979            children: WidgetSpan::extract_from_inline_span(&*text, &TextScaler::NO_SCALING),
1980            text,
1981            text_align: TextAlign::Start,
1982            text_direction: None,
1983            soft_wrap: true,
1984            overflow: TextOverflow::Clip,
1985            text_scaler: TextScaler::NO_SCALING,
1986            max_lines: None,
1987            strut_style: None,
1988            text_width_basis: TextWidthBasis::Parent,
1989            text_height_behavior: None,
1990            selection_registrar: None,
1991            selection_color: None,
1992        }
1993    }
1994
1995    /// Dart `RichText(key:)`.
1996    pub fn key(mut self, key: KeyRef) -> RichText {
1997        self.key = Some(key);
1998        self
1999    }
2000
2001    /// Dart `RichText(textAlign:)`.
2002    pub fn text_align(mut self, text_align: TextAlign) -> RichText {
2003        self.text_align = text_align;
2004        self
2005    }
2006
2007    /// Dart `RichText(textDirection:)`.
2008    pub fn text_direction(mut self, text_direction: TextDirection) -> RichText {
2009        self.text_direction = Some(text_direction);
2010        self
2011    }
2012
2013    /// Dart `RichText(softWrap:)`.
2014    pub fn soft_wrap(mut self, soft_wrap: bool) -> RichText {
2015        self.soft_wrap = soft_wrap;
2016        self
2017    }
2018
2019    /// Dart `RichText(overflow:)`.
2020    pub fn overflow(mut self, overflow: TextOverflow) -> RichText {
2021        self.overflow = overflow;
2022        self
2023    }
2024
2025    /// Dart `RichText(textScaler:)`.
2026    pub fn text_scaler(mut self, text_scaler: TextScaler) -> RichText {
2027        self.children = WidgetSpan::extract_from_inline_span(&*self.text, &text_scaler);
2028        self.text_scaler = text_scaler;
2029        self
2030    }
2031
2032    /// Dart `RichText(maxLines:)`. Must be greater than zero.
2033    pub fn max_lines(mut self, max_lines: i32) -> RichText {
2034        debug_assert!(max_lines > 0);
2035        self.max_lines = Some(max_lines);
2036        self
2037    }
2038
2039    /// Dart `RichText(strutStyle:)`.
2040    pub fn strut_style(mut self, strut_style: StrutStyle) -> RichText {
2041        self.strut_style = Some(strut_style);
2042        self
2043    }
2044
2045    /// Dart `RichText(textWidthBasis:)`.
2046    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> RichText {
2047        self.text_width_basis = text_width_basis;
2048        self
2049    }
2050
2051    /// Dart `RichText(textHeightBehavior:)`.
2052    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> RichText {
2053        self.text_height_behavior = Some(text_height_behavior);
2054        self
2055    }
2056
2057    /// Dart `RichText(selectionRegistrar:)`.
2058    pub fn selection_registrar(mut self, registrar: SelectionRegistrarRef) -> RichText {
2059        self.selection_registrar = Some(registrar);
2060        self
2061    }
2062
2063    /// Dart `RichText(selectionColor:)`.
2064    pub fn selection_color(mut self, color: Color) -> RichText {
2065        self.selection_color = Some(color);
2066        self
2067    }
2068
2069    /// Dart's `_getDevicePixelRatio`.
2070    fn device_pixel_ratio(app: &mut App, context: BuildContext) -> f64 {
2071        MediaQuery::maybe_device_pixel_ratio_of(app, context)
2072            .or_else(|| View::maybe_of(app, context).map(|view| view.metrics().device_pixel_ratio))
2073            .unwrap_or(1.0)
2074    }
2075}
2076
2077impl RenderObjectWidget for RichText {
2078    type RenderObject = RenderParagraph;
2079
2080    fn key(&self) -> Option<&KeyRef> {
2081        self.key.as_ref()
2082    }
2083
2084    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2085        properties.add(
2086            EnumProperty::new("textAlign", self.text_align).default_value(Some(TextAlign::Start)),
2087        );
2088        properties.add(
2089            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
2090                .default_value(None),
2091        );
2092        properties.add(
2093            FlagProperty::new("softWrap", Some(self.soft_wrap))
2094                .if_true("wrapping at box width")
2095                .if_false("no wrapping except at line break characters")
2096                .with_show_name(true),
2097        );
2098        properties.add(
2099            EnumProperty::new("overflow", self.overflow).default_value(Some(TextOverflow::Clip)),
2100        );
2101        properties.add(
2102            DiagnosticsProperty::new("textScaler", self.text_scaler.clone())
2103                .default_value(Some(TextScaler::NO_SCALING)),
2104        );
2105        properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).if_null("unlimited"));
2106        properties.add(
2107            EnumProperty::new("textWidthBasis", self.text_width_basis)
2108                .default_value(Some(TextWidthBasis::Parent)),
2109        );
2110        properties.add(StringProperty::new(
2111            "text",
2112            Some(self.text.to_plain_text(true, true)),
2113        ));
2114        properties.add(
2115            DiagnosticsProperty::<StrutStyle>::new("strutStyle", self.strut_style.clone())
2116                .default_value(None),
2117        );
2118        properties.add(
2119            DiagnosticsProperty::<String>::new(
2120                "textHeightBehavior",
2121                self.text_height_behavior
2122                    .map(|behavior| behavior.to_string()),
2123            )
2124            .default_value(None),
2125        );
2126    }
2127
2128    fn debug_check_constructor(&self) {
2129        debug_assert!(self.selection_registrar.is_none() || self.selection_color.is_some());
2130    }
2131
2132    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
2133        let text_direction = self
2134            .text_direction
2135            .unwrap_or_else(|| Directionality::of(app, context));
2136        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
2137        let render_object = RenderParagraph::new(app, self.text.clone(), text_direction, None);
2138        render_object.set_text_align(app, self.text_align);
2139        render_object.set_soft_wrap(app, self.soft_wrap);
2140        render_object.set_overflow(app, self.overflow);
2141        render_object.set_text_scaler(app, self.text_scaler.clone());
2142        render_object.set_max_lines(app, self.max_lines);
2143        render_object.set_text_width_basis(app, self.text_width_basis);
2144        render_object.set_text_height_behavior(app, self.text_height_behavior);
2145        render_object.set_strut_style(app, self.strut_style.clone());
2146        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
2147        render_object.set_registrar(app, self.selection_registrar.clone());
2148        render_object.set_selection_color(app, self.selection_color);
2149        render_object.as_object()
2150    }
2151
2152    fn update_render_object(
2153        &self,
2154        app: &mut App,
2155        context: BuildContext,
2156        render_object: RenderHandle<RenderParagraph>,
2157    ) {
2158        let text_direction = self
2159            .text_direction
2160            .unwrap_or_else(|| Directionality::of(app, context));
2161        render_object.set_text(app, self.text.clone());
2162        render_object.set_text_align(app, self.text_align);
2163        render_object.set_text_direction(app, text_direction);
2164        render_object.set_soft_wrap(app, self.soft_wrap);
2165        render_object.set_overflow(app, self.overflow);
2166        render_object.set_text_scaler(app, self.text_scaler.clone());
2167        render_object.set_max_lines(app, self.max_lines);
2168        render_object.set_text_width_basis(app, self.text_width_basis);
2169        render_object.set_text_height_behavior(app, self.text_height_behavior);
2170        render_object.set_strut_style(app, self.strut_style.clone());
2171        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
2172        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
2173        render_object.set_registrar(app, self.selection_registrar.clone());
2174        render_object.set_selection_color(app, self.selection_color);
2175    }
2176}
2177
2178impl MultiChildRenderObjectWidget for RichText {
2179    fn children(&self) -> &[WidgetRef] {
2180        &self.children
2181    }
2182}
2183
2184/// The text `element`'s widget shows, as flutter_test's `find.text` reads it: an `EditableText`'s
2185/// controller's text, or a `Text`'s plain text, its data or its span's. A `RichText` shows none,
2186/// so that a `Text` is not counted twice, as itself and as the `RichText` it builds.
2187pub(crate) fn shown_text(app: &App, element: crate::AnyElement) -> Option<String> {
2188    let widget = element.widget(app);
2189    if let Some(editable) = crate::downcast_widget::<crate::EditableText>(&**widget) {
2190        return Some(editable.controller.value(app).text.clone());
2191    }
2192    let text = crate::downcast_widget::<Text>(&**widget)?;
2193    match (&text.data, &text.text_span) {
2194        (Some(data), _) => Some(data.clone()),
2195        (None, Some(span)) => Some(span.to_plain_text(true, true)),
2196        (None, None) => None,
2197    }
2198}
2199
2200#[cfg(test)]
2201mod tests {
2202    use waft_foundation::AppCell;
2203
2204    use waft_embedder::{Color, Offset, Rect, Size, TextLeadingDistribution, TextPosition};
2205    use waft_foundation::ValueKey;
2206    use waft_painting::{PaintingBinding, transform_point};
2207
2208    use crate::{PlaceholderDimensions, TextPainter};
2209
2210    use super::*;
2211    use crate::test_harness::Harness;
2212    use crate::widgets::media_query::MediaQueryData;
2213
2214    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
2215    fn install_fonts(app: &mut App) {
2216        let binding = PaintingBinding::instance(app);
2217        if !binding.has_fonts(app) {
2218            binding.install_fonts(app, |fonts| {
2219                fonts.add_source(valo_system_fonts::SystemFonts::load());
2220            });
2221        }
2222    }
2223
2224    /// Dart tests wrap text in a `Directionality`, which `RichText` requires.
2225    fn ltr(child: WidgetRef) -> WidgetRef {
2226        Directionality::new(TextDirection::Ltr, child).into_widget()
2227    }
2228
2229    /// Mounts `child` with fonts installed and pumps the first frame.
2230    fn mount(app: &mut App, child: WidgetRef) -> Harness {
2231        install_fonts(app);
2232        let harness = Harness::mount(app, ltr(child));
2233        harness.pump(app);
2234        harness
2235    }
2236
2237    /// The `RenderParagraph` directly under the test root.
2238    fn paragraph_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderParagraph> {
2239        harness
2240            .render_root(app)
2241            .child(app)
2242            .expect("a child")
2243            .as_object()
2244            .downcast::<RenderParagraph>(app)
2245            .expect("a RenderParagraph")
2246    }
2247
2248    fn style_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> TextStyle {
2249        paragraph
2250            .text(app)
2251            .style()
2252            .cloned()
2253            .expect("Text always styles its span")
2254    }
2255
2256    fn plain_text_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> String {
2257        paragraph.text(app).to_plain_text(true, true)
2258    }
2259
2260    #[test]
2261    fn a_text_lays_out_a_paragraph_with_the_fallback_style() {
2262        let cell = AppCell::new();
2263        let mut app = cell.borrow_mut();
2264        let harness = mount(&mut app, Text::new("Hello").into_widget());
2265        let paragraph = paragraph_under_root(&harness, &app);
2266        let size = paragraph.size(&app);
2267        assert!(size.width() > 0.0 && size.height() > 0.0);
2268        assert_eq!(plain_text_of(paragraph, &app), "Hello");
2269        assert_eq!(
2270            style_of(paragraph, &app),
2271            TextStyle::new(),
2272            "DefaultTextStyle::fallback"
2273        );
2274        assert_eq!(paragraph.text_direction(&app), TextDirection::Ltr);
2275        assert_eq!(paragraph.text_align(&app), TextAlign::Start);
2276        assert_eq!(paragraph.max_lines(&app), None);
2277        assert_eq!(paragraph.overflow(&app), TextOverflow::Clip);
2278    }
2279
2280    #[test]
2281    fn a_rich_text_span_becomes_the_child_of_the_styled_span() {
2282        let cell = AppCell::new();
2283        let mut app = cell.borrow_mut();
2284        let span = TextSpan::new().text("Hello").into_span();
2285        let harness = mount(&mut app, Text::rich(span).into_widget());
2286        let paragraph = paragraph_under_root(&harness, &app);
2287        assert_eq!(plain_text_of(paragraph, &app), "Hello");
2288        assert!(paragraph.size(&app).width() > 0.0);
2289    }
2290
2291    #[test]
2292    fn a_default_text_style_styles_the_text_and_notifies_on_change() {
2293        let cell = AppCell::new();
2294        let mut app = cell.borrow_mut();
2295        // One Text instance, reused like a `const` widget, so only the default style decides
2296        // rebuilds.
2297        let text: WidgetRef = Text::new("Hello").into_widget();
2298        let styled = |font_size: f64| {
2299            DefaultTextStyle::new(TextStyle::new().font_size(font_size), text.clone()).into_widget()
2300        };
2301        let harness = mount(&mut app, styled(12.0));
2302        let paragraph = paragraph_under_root(&harness, &app);
2303        assert_eq!(style_of(paragraph, &app).font_size, Some(12.0));
2304        let small = paragraph.size(&app);
2305
2306        harness.set_child(&mut app, ltr(styled(24.0)));
2307        harness.pump(&mut app);
2308        assert_eq!(
2309            paragraph_under_root(&harness, &app),
2310            paragraph,
2311            "the same paragraph is restyled"
2312        );
2313        assert_eq!(style_of(paragraph, &app).font_size, Some(24.0));
2314        assert!(paragraph.size(&app).height() > small.height());
2315    }
2316
2317    #[test]
2318    fn an_explicit_style_merges_into_the_default_unless_it_does_not_inherit() {
2319        let cell = AppCell::new();
2320        let mut app = cell.borrow_mut();
2321        let red = Color::from_argb(255, 255, 0, 0);
2322        let under_default = |style: TextStyle| {
2323            DefaultTextStyle::new(
2324                TextStyle::new().font_size(12.0),
2325                Text::new("Hello").style(style),
2326            )
2327            .into_widget()
2328        };
2329        let harness = mount(&mut app, under_default(TextStyle::new().color(red)));
2330        let paragraph = paragraph_under_root(&harness, &app);
2331        let merged = style_of(paragraph, &app);
2332        assert_eq!(merged.font_size, Some(12.0));
2333        assert_eq!(merged.color, Some(red.into()));
2334
2335        harness.set_child(
2336            &mut app,
2337            ltr(under_default(
2338                TextStyle::new().inherit(false).font_size(30.0),
2339            )),
2340        );
2341        harness.pump(&mut app);
2342        let replaced = style_of(paragraph, &app);
2343        assert_eq!(replaced.font_size, Some(30.0));
2344        assert_eq!(
2345            replaced.color, None,
2346            "a non-inheriting style replaces the default"
2347        );
2348    }
2349
2350    #[test]
2351    fn a_new_string_updates_the_same_paragraph() {
2352        let cell = AppCell::new();
2353        let mut app = cell.borrow_mut();
2354        let harness = mount(&mut app, Text::new("Hello").into_widget());
2355        let paragraph = paragraph_under_root(&harness, &app);
2356        let short = paragraph.size(&app);
2357
2358        harness.set_child(&mut app, ltr(Text::new("Hello there, world").into_widget()));
2359        harness.pump(&mut app);
2360        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
2361        assert_eq!(plain_text_of(paragraph, &app), "Hello there, world");
2362        assert!(paragraph.size(&app).width() > short.width());
2363    }
2364
2365    #[test]
2366    fn max_lines_and_overflow_reach_the_render_object() {
2367        let cell = AppCell::new();
2368        let mut app = cell.borrow_mut();
2369        let harness = mount(
2370            &mut app,
2371            Text::new("Hello")
2372                .max_lines(2)
2373                .overflow(TextOverflow::Ellipsis)
2374                .soft_wrap(false)
2375                .text_direction(TextDirection::Rtl)
2376                .text_align(TextAlign::End)
2377                .into_widget(),
2378        );
2379        let paragraph = paragraph_under_root(&harness, &app);
2380        assert_eq!(paragraph.max_lines(&app), Some(2));
2381        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
2382        assert!(!paragraph.soft_wrap(&app));
2383        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
2384        assert_eq!(paragraph.text_align(&app), TextAlign::End);
2385    }
2386
2387    #[test]
2388    fn a_default_text_style_supplies_what_the_text_leaves_unset() {
2389        let cell = AppCell::new();
2390        let mut app = cell.borrow_mut();
2391        let under_default = |text: Text| {
2392            DefaultTextStyle::new(TextStyle::new(), text)
2393                .max_lines(1)
2394                .overflow(TextOverflow::Fade)
2395                .text_align(TextAlign::Center)
2396                .soft_wrap(false)
2397                .into_widget()
2398        };
2399        let harness = mount(&mut app, under_default(Text::new("Hello")));
2400        let paragraph = paragraph_under_root(&harness, &app);
2401        assert_eq!(paragraph.max_lines(&app), Some(1));
2402        assert_eq!(paragraph.overflow(&app), TextOverflow::Fade);
2403        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
2404        assert!(!paragraph.soft_wrap(&app));
2405
2406        harness.set_child(
2407            &mut app,
2408            ltr(under_default(Text::new("Hello").max_lines(3))),
2409        );
2410        harness.pump(&mut app);
2411        assert_eq!(
2412            paragraph.max_lines(&app),
2413            Some(3),
2414            "the Text's own value wins"
2415        );
2416    }
2417
2418    #[test]
2419    fn the_style_overflow_beats_the_default_text_style_overflow() {
2420        let cell = AppCell::new();
2421        let mut app = cell.borrow_mut();
2422        let harness = mount(
2423            &mut app,
2424            DefaultTextStyle::new(
2425                TextStyle::new(),
2426                Text::new("Hello").style(TextStyle::new().overflow(TextOverflow::Ellipsis)),
2427            )
2428            .overflow(TextOverflow::Fade)
2429            .into_widget(),
2430        );
2431        let paragraph = paragraph_under_root(&harness, &app);
2432        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
2433    }
2434
2435    #[test]
2436    fn a_default_text_height_behavior_reaches_the_paragraph_and_notifies_on_change() {
2437        let cell = AppCell::new();
2438        let mut app = cell.borrow_mut();
2439        let text: WidgetRef = Text::new("Hello").into_widget();
2440        let under_behavior = |leading_distribution: TextLeadingDistribution| {
2441            DefaultTextHeightBehavior::new(
2442                TextHeightBehavior {
2443                    leading_distribution,
2444                    ..TextHeightBehavior::default()
2445                },
2446                text.clone(),
2447            )
2448            .into_widget()
2449        };
2450        let harness = mount(&mut app, under_behavior(TextLeadingDistribution::Even));
2451        let paragraph = paragraph_under_root(&harness, &app);
2452        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
2453        assert_eq!(behavior.leading_distribution, TextLeadingDistribution::Even);
2454
2455        harness.set_child(
2456            &mut app,
2457            ltr(under_behavior(TextLeadingDistribution::Proportional)),
2458        );
2459        harness.pump(&mut app);
2460        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
2461        assert_eq!(
2462            behavior.leading_distribution,
2463            TextLeadingDistribution::Proportional
2464        );
2465    }
2466
2467    #[test]
2468    fn a_rich_text_forwards_its_configuration_in_place() {
2469        let cell = AppCell::new();
2470        let mut app = cell.borrow_mut();
2471        let rich = |text: &str| {
2472            RichText::new(TextSpan::new().text(text).into_span())
2473                .text_align(TextAlign::Center)
2474                .text_direction(TextDirection::Rtl)
2475                .max_lines(1)
2476                .into_widget()
2477        };
2478        let harness = mount(&mut app, rich("Hello"));
2479        let paragraph = paragraph_under_root(&harness, &app);
2480        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
2481        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
2482        assert_eq!(paragraph.max_lines(&app), Some(1));
2483
2484        harness.set_child(&mut app, ltr(rich("Goodbye")));
2485        harness.pump(&mut app);
2486        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
2487        assert_eq!(plain_text_of(paragraph, &app), "Goodbye");
2488    }
2489
2490    #[test]
2491    fn a_changed_key_replaces_the_paragraph_where_the_same_key_keeps_it() {
2492        let cell = AppCell::new();
2493        let mut app = cell.borrow_mut();
2494        let keyed = |key: &str| {
2495            Text::new("Hello")
2496                .key(ValueKey::new(key.to_owned()).into())
2497                .into_widget()
2498        };
2499        let harness = mount(&mut app, keyed("a"));
2500        let paragraph = paragraph_under_root(&harness, &app);
2501
2502        harness.set_child(&mut app, ltr(keyed("a")));
2503        harness.pump(&mut app);
2504        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
2505
2506        harness.set_child(&mut app, ltr(keyed("b")));
2507        harness.pump(&mut app);
2508        assert_ne!(paragraph_under_root(&harness, &app), paragraph);
2509    }
2510
2511    #[test]
2512    fn a_media_query_bolds_scales_and_spaces_the_text() {
2513        let cell = AppCell::new();
2514        let mut app = cell.borrow_mut();
2515        let data = MediaQueryData::new()
2516            .bold_text(true)
2517            .text_scaler(TextScaler::linear(2.0))
2518            .line_height_scale_factor_override(1.5)
2519            .letter_spacing_override(3.0)
2520            .word_spacing_override(4.0);
2521        let harness = mount(
2522            &mut app,
2523            MediaQuery::new(data, Text::new("Hello")).into_widget(),
2524        );
2525        let paragraph = paragraph_under_root(&harness, &app);
2526        let style = style_of(paragraph, &app);
2527        assert_eq!(style.font_weight, Some(FontWeight::BOLD));
2528        assert_eq!(style.height, Some(1.5));
2529        assert_eq!(style.letter_spacing, Some(3.0));
2530        assert_eq!(style.word_spacing, Some(4.0));
2531        assert_eq!(paragraph.text_scaler(&app), TextScaler::linear(2.0));
2532    }
2533
2534    // ---- selection ----
2535
2536    use waft_rendering::{SelectionEvent, SelectionStatus};
2537
2538    use waft_scheduler::{FrameTarget, SchedulerBinding};
2539
2540    use crate::testing::{WidgetTester, find, test_widgets};
2541    use crate::widgets::basic::{Column, SizedBox};
2542    use crate::widgets::selectable_region::PlainStaticSelectionContainerDelegate;
2543    use crate::widgets::selection_container::SelectionContainer;
2544
2545    /// Pumps `texts` in a column under a selection container, as under a `SelectableRegion`, and
2546    /// answers the container's delegate.
2547    fn pump_selectable_texts(
2548        tester: &mut WidgetTester,
2549        texts: Vec<WidgetRef>,
2550    ) -> Ref<PlainStaticSelectionContainerDelegate> {
2551        let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
2552        tester.pump_widget(Directionality::new(
2553            TextDirection::Ltr,
2554            SelectionContainer::new(delegate.erase(), Column::new().children(texts)),
2555        ));
2556        tester.pump_and_settle();
2557        // The outer container registers itself from a microtask after the frame, so its
2558        // selectable reaches the delegate at the next frame.
2559        tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
2560        tester.pump();
2561        tester.pump_and_settle();
2562        delegate
2563    }
2564
2565    /// The global position of the caret at `offset` in `paragraph`, five pixels down from the
2566    /// top of the line.
2567    fn position_of(
2568        tester: &mut WidgetTester,
2569        paragraph: RenderHandle<RenderParagraph>,
2570        offset: i32,
2571    ) -> Offset {
2572        tester.update(|app| {
2573            let local = paragraph.get_offset_for_caret(app, TextPosition::new(offset), Rect::ZERO)
2574                + Offset::new(0.0, 5.0);
2575            transform_point(&paragraph.as_object().get_transform_to(app, None), local)
2576        })
2577    }
2578
2579    /// Sends `event` to `handle`.
2580    fn dispatch<D: SelectionHandler>(
2581        tester: &mut WidgetTester,
2582        handle: Handle<D>,
2583        event: SelectionEvent,
2584    ) {
2585        tester.update(|app| {
2586            SelectionHandler::dispatch_selection_event(handle, app, &event);
2587        });
2588    }
2589
2590    /// The selected range and status of `handle`.
2591    fn assert_selection<D: SelectionHandler>(
2592        tester: &WidgetTester,
2593        handle: Handle<D>,
2594        expected_range: Option<(i32, i32)>,
2595        expected_status: SelectionStatus,
2596    ) {
2597        tester.update(|app| {
2598            let range = SelectionHandler::selection(handle, app);
2599            assert_eq!(
2600                range.map(|range| (range.start_offset, range.end_offset)),
2601                expected_range
2602            );
2603            assert_eq!(SelectionHandler::value(handle, app).status, expected_status);
2604        });
2605    }
2606
2607    /// The plain text `handle` has selected, or `None`.
2608    fn selected_text<D: SelectionHandler>(
2609        tester: &WidgetTester,
2610        handle: Handle<D>,
2611    ) -> Option<String> {
2612        tester.update(|app| {
2613            SelectionHandler::selected_content(handle, app).map(|content| content.plain_text)
2614        })
2615    }
2616
2617    /// The paragraph showing `text`.
2618    fn paragraph_showing(tester: &WidgetTester, text: &str) -> RenderHandle<RenderParagraph> {
2619        let paragraphs = tester.all::<RenderParagraph>();
2620        tester.update(|app| {
2621            *paragraphs
2622                .iter()
2623                .find(|paragraph| paragraph.text(app).to_plain_text(true, true) == text)
2624                .unwrap_or_else(|| panic!("a paragraph showing {text}"))
2625        })
2626    }
2627
2628    /// `paragraph`'s one selection, as its start and end.
2629    fn paragraph_selection(
2630        tester: &WidgetTester,
2631        paragraph: RenderHandle<RenderParagraph>,
2632    ) -> (i32, i32) {
2633        tester.update(|app| {
2634            let selections = paragraph.selections(app);
2635            assert_eq!(selections.len(), 1, "one selection");
2636            (selections[0].start(), selections[0].end())
2637        })
2638    }
2639
2640    // selectable_region_test.dart 'onSelectionChanged SelectedContentRange is accurate', now
2641    // through `Text`, which builds its own selection container.
2642    #[test]
2643    fn the_selection_range_covers_the_texts_between_the_edges() {
2644        test_widgets(|tester| {
2645            let delegate = pump_selectable_texts(
2646                tester,
2647                vec![
2648                    Text::new("How are you?").into_widget(),
2649                    Text::new("Good, and you?").into_widget(),
2650                    Text::new("Fine, thank you.").into_widget(),
2651                ],
2652            );
2653            let paragraphs = tester.all::<RenderParagraph>();
2654            assert_eq!(paragraphs.len(), 3);
2655            let start = position_of(tester, paragraphs[0], 4);
2656            dispatch(
2657                tester,
2658                delegate.handle(),
2659                SelectionEvent::for_start(start, None),
2660            );
2661
2662            let end = position_of(tester, paragraphs[0], 7);
2663            dispatch(
2664                tester,
2665                delegate.handle(),
2666                SelectionEvent::for_end(end, None),
2667            );
2668            assert_selection(
2669                tester,
2670                delegate.handle(),
2671                Some((4, 7)),
2672                SelectionStatus::Uncollapsed,
2673            );
2674
2675            let end = position_of(tester, paragraphs[0], 10);
2676            dispatch(
2677                tester,
2678                delegate.handle(),
2679                SelectionEvent::for_end(end, None),
2680            );
2681            assert_selection(
2682                tester,
2683                delegate.handle(),
2684                Some((4, 10)),
2685                SelectionStatus::Uncollapsed,
2686            );
2687
2688            let end = position_of(tester, paragraphs[1], 10);
2689            dispatch(
2690                tester,
2691                delegate.handle(),
2692                SelectionEvent::for_end(end, None),
2693            );
2694            assert_selection(
2695                tester,
2696                delegate.handle(),
2697                Some((4, 22)),
2698                SelectionStatus::Uncollapsed,
2699            );
2700
2701            let end = position_of(tester, paragraphs[2], 10);
2702            dispatch(
2703                tester,
2704                delegate.handle(),
2705                SelectionEvent::for_end(end, None),
2706            );
2707            assert_selection(
2708                tester,
2709                delegate.handle(),
2710                Some((4, 36)),
2711                SelectionStatus::Uncollapsed,
2712            );
2713
2714            // A collapsed selection, as a click makes one.
2715            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
2716            let point = position_of(tester, paragraphs[0], 3);
2717            dispatch(
2718                tester,
2719                delegate.handle(),
2720                SelectionEvent::for_start(point, None),
2721            );
2722            dispatch(
2723                tester,
2724                delegate.handle(),
2725                SelectionEvent::for_end(point, None),
2726            );
2727            assert_selection(
2728                tester,
2729                delegate.handle(),
2730                Some((3, 3)),
2731                SelectionStatus::Collapsed,
2732            );
2733
2734            // A backward selection.
2735            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
2736            let start = position_of(tester, paragraphs[2], 4);
2737            let end = position_of(tester, paragraphs[0], 0);
2738            dispatch(
2739                tester,
2740                delegate.handle(),
2741                SelectionEvent::for_start(start, None),
2742            );
2743            dispatch(
2744                tester,
2745                delegate.handle(),
2746                SelectionEvent::for_end(end, None),
2747            );
2748            assert_selection(
2749                tester,
2750                delegate.handle(),
2751                Some((30, 0)),
2752                SelectionStatus::Uncollapsed,
2753            );
2754        });
2755    }
2756
2757    // selectable_region_test.dart 'can select word when selectable is broken up by an
2758    // unselectable WidgetSpan': the fragment that starts after the span is selected, and the
2759    // range counts from the paragraph's start.
2760    #[test]
2761    fn a_word_after_a_widget_span_is_selected_and_ranged_from_the_paragraph_start() {
2762        const BEFORE: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
2763        // The 123 characters, then the placeholder, then "Hello, world.": the word is at 124.
2764        assert_eq!(BEFORE.len(), 123, "as in the test");
2765        test_widgets(|tester| {
2766            let span = TextSpan::new()
2767                .children(vec![
2768                    TextSpan::new().text(BEFORE).into_span(),
2769                    WidgetSpan::new(SizedBox::shrink()).into_span(),
2770                    TextSpan::new().text("Hello, world.").into_span(),
2771                ])
2772                .into_span();
2773            let delegate = pump_selectable_texts(tester, vec![Text::rich(span).into_widget()]);
2774            let paragraphs = tester.all::<RenderParagraph>();
2775            assert_eq!(paragraphs.len(), 1);
2776            let position = position_of(tester, paragraphs[0], 125);
2777            dispatch(
2778                tester,
2779                delegate.handle(),
2780                SelectionEvent::SelectWord {
2781                    global_position: position,
2782                },
2783            );
2784
2785            assert_eq!(paragraph_selection(tester, paragraphs[0]), (124, 129));
2786            assert_eq!(
2787                selected_text(tester, delegate.handle()),
2788                Some("Hello".to_string())
2789            );
2790            // Dart's range counts the first fragment's whole content and then the distance to
2791            // where the selected fragment starts in the paragraph, so the placeholder the
2792            // unselected fragment ends at is not counted.
2793            assert_selection(
2794                tester,
2795                delegate.handle(),
2796                Some((123, 128)),
2797                SelectionStatus::Uncollapsed,
2798            );
2799        });
2800    }
2801
2802    // selectable_region_test.dart 'selects backwards across multiple Text widgets and
2803    // WidgetSpans via mouse drag': every inner and outer text is fully selected.
2804    #[test]
2805    fn a_backward_drag_selects_every_inner_and_outer_text() {
2806        test_widgets(|tester| {
2807            let texts = (0..5)
2808                .map(|index| {
2809                    let number = index + 1;
2810                    Text::rich(
2811                        TextSpan::new()
2812                            .children(vec![
2813                                WidgetSpan::new(Text::new(format!("{number}. "))).into_span(),
2814                                TextSpan::new().text(format!("Item {number}")).into_span(),
2815                            ])
2816                            .into_span(),
2817                    )
2818                    .key(ValueKey::new(index as usize).into())
2819                    .into_widget()
2820                })
2821                .collect();
2822            let delegate = pump_selectable_texts(tester, texts);
2823            let drag_start = tester.get_bottom_right(find::by_key(ValueKey::new(4usize)));
2824            let drag_end = tester.get_top_left(find::by_key(ValueKey::new(0usize)));
2825            dispatch(
2826                tester,
2827                delegate.handle(),
2828                SelectionEvent::for_start(drag_start, None),
2829            );
2830            dispatch(
2831                tester,
2832                delegate.handle(),
2833                SelectionEvent::for_end(drag_end, None),
2834            );
2835
2836            for index in 0..5 {
2837                let number = index + 1;
2838                let inner = paragraph_showing(tester, &format!("{number}. "));
2839                let length =
2840                    tester.update(|app| inner.text(app).to_plain_text(true, true).len() as i32);
2841                assert_eq!(paragraph_selection(tester, inner), (0, length));
2842
2843                let outer_text = format!("\u{FFFC}Item {number}");
2844                let outer = paragraph_showing(tester, &outer_text);
2845                assert_eq!(
2846                    paragraph_selection(tester, outer),
2847                    (1, outer_text.chars().count() as i32)
2848                );
2849            }
2850        });
2851    }
2852
2853    // selectable_region_test.dart 'mouse can select multiple widgets on triple click drag when
2854    // selecting inside a WidgetSpan': a paragraph extension drag selects every line it crosses,
2855    // and the range counts each inner text's content.
2856    #[test]
2857    fn a_paragraph_extension_selects_the_lines_it_crosses() {
2858        test_widgets(|tester| {
2859            let texts: Vec<WidgetRef> = (0..5)
2860                .map(|index| {
2861                    Text::new(format!("Text widget {}.", (b'A' + index) as char)).into_widget()
2862                })
2863                .collect();
2864            let span = WidgetSpan::new(Column::new().children(texts)).into_span();
2865            let delegate = pump_selectable_texts(tester, vec![Text::rich(span).into_widget()]);
2866            let paragraph_c = paragraph_showing(tester, "Text widget C.");
2867            let paragraph_e = paragraph_showing(tester, "Text widget E.");
2868            let point_c = position_of(tester, paragraph_c, 2);
2869            dispatch(
2870                tester,
2871                delegate.handle(),
2872                SelectionEvent::SelectParagraph {
2873                    global_position: point_c,
2874                    absorb: false,
2875                },
2876            );
2877            assert_eq!(paragraph_selection(tester, paragraph_c), (0, 14));
2878
2879            let point_e = position_of(tester, paragraph_e, 5);
2880            dispatch(
2881                tester,
2882                delegate.handle(),
2883                SelectionEvent::for_end(point_e, Some(waft_rendering::TextGranularity::Paragraph)),
2884            );
2885            assert_eq!(paragraph_selection(tester, paragraph_c), (0, 14));
2886            assert_eq!(
2887                paragraph_selection(tester, paragraph_showing(tester, "Text widget D.")),
2888                (0, 14)
2889            );
2890            assert_eq!(paragraph_selection(tester, paragraph_e), (0, 14));
2891            // A, B, C, D and E are 14 characters each; C through E is 28..70.
2892            assert_selection(
2893                tester,
2894                delegate.handle(),
2895                Some((28, 70)),
2896                SelectionStatus::Uncollapsed,
2897            );
2898        });
2899    }
2900
2901    #[test]
2902    fn force_strut_height_applies_to_widget_spans() {
2903        let cell = AppCell::new();
2904        let mut app = cell.borrow_mut();
2905        let fonts = PaintingBinding::instance(&mut app).install_flutter_test_fonts(&mut app);
2906        let span = TextSpan::new()
2907            .children(vec![
2908                WidgetSpan::new(crate::widgets::basic::SizedBox::new()).into_span(),
2909            ])
2910            .into_span();
2911        let mut painter = TextPainter::new();
2912        painter.set_text(Some(span));
2913        painter.set_text_direction(Some(TextDirection::Ltr));
2914        painter.set_strut_style(Some(
2915            StrutStyle::new()
2916                .height(10.0)
2917                .font_size(10.0)
2918                .force_strut_height(true),
2919        ));
2920        painter.set_placeholder_dimensions(Some(vec![PlaceholderDimensions::new(
2921            Size::new(1000.0, 1000.0),
2922            waft_embedder::PlaceholderAlignment::Bottom,
2923        )]));
2924        painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
2925        assert_eq!(painter.height(), 100.0);
2926    }
2927
2928    #[test]
2929    fn text_rich_respects_the_media_query_spacing_overrides_on_its_strut() {
2930        let cell = AppCell::new();
2931        let mut app = cell.borrow_mut();
2932        let overridden = MediaQuery::new(
2933            MediaQueryData::new()
2934                .line_height_scale_factor_override(2.0)
2935                .letter_spacing_override(2.0)
2936                .word_spacing_override(2.0),
2937            Text::rich(TextSpan::new().text("Hello").into_span())
2938                .text_direction(TextDirection::Ltr)
2939                .strut_style(StrutStyle::new().height(0.9)),
2940        )
2941        .into_widget();
2942        let harness = mount(&mut app, overridden);
2943        let paragraph = paragraph_under_root(&harness, &app);
2944        let span_style = paragraph.text(&app).style().cloned();
2945        assert_eq!(
2946            span_style.as_ref().and_then(|style| style.height),
2947            Some(2.0)
2948        );
2949        assert_eq!(
2950            span_style.as_ref().and_then(|style| style.letter_spacing),
2951            Some(2.0)
2952        );
2953        assert_eq!(
2954            span_style.as_ref().and_then(|style| style.word_spacing),
2955            Some(2.0)
2956        );
2957        assert_eq!(
2958            paragraph
2959                .strut_style(&app)
2960                .and_then(|strut_style| strut_style.height),
2961            Some(2.0)
2962        );
2963
2964        harness.set_child(
2965            &mut app,
2966            ltr(Text::rich(TextSpan::new().text("Hello").into_span())
2967                .text_direction(TextDirection::Ltr)
2968                .strut_style(StrutStyle::new().height(0.9))
2969                .into_widget()),
2970        );
2971        harness.pump(&mut app);
2972        let paragraph = paragraph_under_root(&harness, &app);
2973        let span_style = paragraph.text(&app).style().cloned();
2974        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
2975        assert_eq!(
2976            span_style.as_ref().and_then(|style| style.letter_spacing),
2977            None
2978        );
2979        assert_eq!(
2980            span_style.as_ref().and_then(|style| style.word_spacing),
2981            None
2982        );
2983        assert_eq!(
2984            paragraph
2985                .strut_style(&app)
2986                .and_then(|strut_style| strut_style.height),
2987            Some(0.9)
2988        );
2989    }
2990
2991    #[test]
2992    fn rich_text_ignores_the_media_query_spacing_overrides() {
2993        let cell = AppCell::new();
2994        let mut app = cell.borrow_mut();
2995        let overridden = MediaQuery::new(
2996            MediaQueryData::new()
2997                .line_height_scale_factor_override(2.0)
2998                .letter_spacing_override(2.0)
2999                .word_spacing_override(2.0),
3000            RichText::new(TextSpan::new().text("Hello").into_span())
3001                .text_direction(TextDirection::Ltr)
3002                .strut_style(StrutStyle::new().height(0.9)),
3003        )
3004        .into_widget();
3005        let harness = mount(&mut app, overridden);
3006        let paragraph = paragraph_under_root(&harness, &app);
3007        let span_style = paragraph.text(&app).style().cloned();
3008        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
3009        assert_eq!(
3010            span_style.as_ref().and_then(|style| style.letter_spacing),
3011            None
3012        );
3013        assert_eq!(
3014            span_style.as_ref().and_then(|style| style.word_spacing),
3015            None
3016        );
3017        assert_eq!(
3018            paragraph
3019                .strut_style(&app)
3020                .and_then(|strut_style| strut_style.height),
3021            Some(0.9)
3022        );
3023    }
3024}