Skip to main content

waft_material/
selectable_text.rs

1//! Flutter counterpart: material_ui's `selectable_text.dart`.
2//!
3//! `SelectableText` is a read-only [`EditableText`] over a private controller that builds the
4//! widget's span; the state rebuilds that controller whenever the data or span changes.
5
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8
9use waft_embedder::{
10    AppLifecycleState, BoxHeightStyle, BoxWidthStyle, Color, Offset, Radius, TargetPlatform,
11    TextAlign, TextDirection, TextEditingValue, TextHeightBehavior, TextSelection,
12};
13use waft_foundation::{
14    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsProperty,
15    DoubleProperty, EnumProperty, FlagProperty, Handle, IntProperty, Listenable, ListenableObject,
16    Listener, OptionRetained, Ref,
17};
18use waft_gestures::{DragStartBehavior, GestureTapCallback, TapDragUpDetails};
19use waft_painting::{
20    ColorProperty, InlineSpan, StrutStyle, TextScaler, TextSpan, TextStyle, TextWidthBasis,
21};
22use waft_rendering::HitTestBehavior;
23use waft_scheduler::SchedulerBinding;
24use waft_services::SelectionChangedCause;
25use waft_widgets::{
26    AnyTextEditingController, BuildContext, DefaultSelectionStyle, DefaultTextStyle, EditableText,
27    EditableTextContextMenuBuilder, EditableTextState, FocusNode, FocusNodeLeaf, FocusNodeRef,
28    GlobalKey, IntoWidget, KeyRef, MediaQuery, RepaintBoundary, ScrollBehaviorRef,
29    ScrollPhysicsRef, SelectionChangedCallback, Semantics, State, StateData, StatefulWidget,
30    TextEditingControllerData, TextEditingControllerLeaf, TextMagnifierConfiguration,
31    TextSelectionControls, TextSelectionGestureDetectorBuilder,
32    TextSelectionGestureDetectorBuilderBase, TextSelectionGestureDetectorBuilderData,
33    TextSelectionGestureDetectorBuilderDelegate, ToolbarOptions, WidgetRef,
34    debug_check_has_directionality, debug_check_has_media_query,
35};
36
37use waft_cupertino::{
38    CupertinoColors, CupertinoTheme, cupertino_desktop_text_selection_handle_controls,
39    cupertino_text_selection_handle_controls,
40};
41
42use crate::adaptive_text_selection_toolbar::AdaptiveTextSelectionToolbar;
43use crate::desktop_text_selection::desktop_text_selection_handle_controls;
44use crate::magnifier::TextMagnifier;
45use crate::text_selection::material_text_selection_handle_controls;
46use crate::theme::Theme;
47
48/// An eyeballed value that moves the cursor slightly left of where it is
49/// rendered for text on Android so its positioning more accurately matches the
50/// native iOS text cursor positioning.
51///
52/// This value is in device pixels, not logical pixels as is typically used
53/// throughout the codebase.
54pub const IOS_HORIZONTAL_OFFSET: i32 = -2;
55
56/// Dart's `_TextSpanEditingController`.
57struct TextSpanEditingController {
58    change_notifier: ChangeNotifierData,
59    text_editing_controller: TextEditingControllerData,
60    text_span: TextSpan,
61}
62
63impl TextSpanEditingController {
64    fn new(app: &mut App, text_span: TextSpan) -> Ref<TextSpanEditingController> {
65        let text = text_span.to_plain_text(false, true);
66        app.create(TextSpanEditingController {
67            change_notifier: ChangeNotifierData::new(),
68            text_editing_controller: TextEditingControllerData::new(
69                TextEditingValue::new().text(text),
70            ),
71            text_span,
72        })
73    }
74}
75
76impl ChangeNotifier for TextSpanEditingController {
77    fn change_notifier_data(&self) -> &ChangeNotifierData {
78        &self.change_notifier
79    }
80
81    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
82        &mut self.change_notifier
83    }
84}
85
86impl TextEditingControllerLeaf for TextSpanEditingController {
87    waft_widgets::text_editing_controller_accessors!();
88
89    fn build_text_span(
90        self: Handle<Self>,
91        app: &App,
92        _context: BuildContext,
93        style: Option<TextStyle>,
94        _with_composing: bool,
95    ) -> TextSpan {
96        // This does not care about composing.
97        let mut span = TextSpan::new();
98        if let Some(style) = style {
99            span = span.style(style);
100        }
101        span.children(vec![app.get(self).text_span.clone().into_span()])
102    }
103
104    fn set_text(self: Handle<Self>, _app: &mut App, _new_text: impl Into<String>) {
105        // This should never be reached.
106        unimplemented!();
107    }
108}
109
110impl Debug for TextSpanEditingController {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.debug_struct("_TextSpanEditingController")
113            .field("text_span", &self.text_span)
114            .finish_non_exhaustive()
115    }
116}
117
118/// Dart's `_SelectableTextSelectionGestureDetectorBuilder`.
119struct SelectableTextSelectionGestureDetectorBuilder {
120    builder: TextSelectionGestureDetectorBuilderData,
121    state: Handle<SelectableTextState>,
122}
123
124impl TextSelectionGestureDetectorBuilder for SelectableTextSelectionGestureDetectorBuilder {
125    waft_widgets::text_selection_gesture_detector_builder_accessors!(builder);
126
127    fn on_single_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
128        if !self.builder_data(app).delegate.selection_enabled(app) {
129            return;
130        }
131        TextSelectionGestureDetectorBuilderBase::on_single_tap_up(self, app, details);
132        let state = app.get(self).state;
133        if let Some(on_tap) = state.widget(app).on_tap.clone() {
134            on_tap.call(app);
135        }
136    }
137}
138
139/// A run of selectable text with a single style.
140///
141/// Selectable text can't receive keyboard focus by traversal: its focus node skips
142/// traversal.
143///
144/// The [`SelectableText`] widget displays a string of text with a single style.
145/// The string might break across multiple lines or might all be displayed on
146/// the same line depending on the layout constraints.
147///
148/// The [`style`](Self::style) argument is optional. When omitted, the text will use the
149/// style from the closest enclosing [`DefaultTextStyle`]. If the given style's
150/// `TextStyle::inherit` property is true (the default), the given style will
151/// be merged with the closest enclosing [`DefaultTextStyle`]. This merging
152/// behavior is useful, for example, to make the text bold while using the
153/// default font family and size.
154///
155/// [`SelectableText::rich`] shows text with several styles, as a [`TextSpan`].
156///
157/// To make [`SelectableText`] react to touch events, use callback [`on_tap`](Self::on_tap)
158/// to achieve the desired behavior.
159///
160/// See also:
161///
162///  * `Text`, which is the non selectable version of this widget.
163///  * `TextField`, which is the editable version of this widget.
164///  * `SelectionArea`, which enables the selection of multiple `Text` widgets and of other
165///    widgets.
166#[allow(clippy::type_complexity)]
167pub struct SelectableText {
168    /// See [`Widget::key`](waft_widgets::Widget::key).
169    pub key: Option<KeyRef>,
170
171    /// The text to display.
172    ///
173    /// This will be `None` if a [`text_span`](Self::text_span) is provided instead.
174    pub data: Option<String>,
175
176    /// The text to display as a [`TextSpan`].
177    ///
178    /// This will be `None` if [`data`](Self::data) is provided instead.
179    pub text_span: Option<TextSpan>,
180
181    /// Defines the focus for this widget.
182    ///
183    /// Text is only selectable when widget is focused.
184    ///
185    /// The [`focus_node`](Self::focus_node) is a long-lived object that's typically managed
186    /// by a [`StatefulWidget`] parent.
187    ///
188    /// If null, this widget will create its own [`FocusNode`] with `FocusNode::skip_traversal`
189    /// parameter set to `true`, which causes the widget to be skipped over during focus
190    /// traversal.
191    pub focus_node: Option<FocusNodeRef>,
192
193    /// The style to use for the text.
194    ///
195    /// If null, defaults to [`DefaultTextStyle`] of context.
196    pub style: Option<TextStyle>,
197
198    /// {@macro flutter.widgets.editableText.strutStyle}
199    pub strut_style: Option<StrutStyle>,
200
201    /// {@macro flutter.widgets.editableText.textAlign}
202    pub text_align: Option<TextAlign>,
203
204    /// {@macro flutter.widgets.editableText.textDirection}
205    pub text_direction: Option<TextDirection>,
206
207    /// {@macro flutter.widgets.editableText.textScaleFactor}
208    #[deprecated(
209        note = "Use text_scaler instead. Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. This feature was deprecated after v3.12.0-2.0.pre."
210    )]
211    pub text_scale_factor: Option<f64>,
212
213    /// {@macro flutter.painting.textPainter.textScaler}
214    pub text_scaler: Option<TextScaler>,
215
216    /// {@macro flutter.widgets.editableText.autofocus}
217    pub autofocus: bool,
218
219    /// {@macro flutter.widgets.editableText.minLines}
220    pub min_lines: Option<i32>,
221
222    /// {@macro flutter.widgets.editableText.maxLines}
223    pub max_lines: Option<i32>,
224
225    /// {@macro flutter.widgets.editableText.showCursor}
226    pub show_cursor: bool,
227
228    /// {@macro flutter.widgets.editableText.cursorWidth}
229    pub cursor_width: f64,
230
231    /// {@macro flutter.widgets.editableText.cursorHeight}
232    pub cursor_height: Option<f64>,
233
234    /// {@macro flutter.widgets.editableText.cursorRadius}
235    pub cursor_radius: Option<Radius>,
236
237    /// The color of the cursor.
238    ///
239    /// The cursor indicates the current text insertion point.
240    ///
241    /// If this is null it will default to [`DefaultSelectionStyle::cursor_color`].
242    /// If that is null, it will use `CupertinoThemeData::primary_color` on iOS and macOS, or
243    /// `ColorScheme::primary` on other platforms.
244    pub cursor_color: Option<Color>,
245
246    /// The color to use when painting the selection.
247    ///
248    /// If this property is null, this widget gets the selection color from the
249    /// [`DefaultSelectionStyle`], or else a 40% opacity of the primary colour.
250    pub selection_color: Option<Color>,
251
252    /// Controls how tall the selection highlight boxes are computed to be.
253    ///
254    /// See `BoxHeightStyle` for details on available styles.
255    pub selection_height_style: Option<BoxHeightStyle>,
256
257    /// Controls how wide the selection highlight boxes are computed to be.
258    ///
259    /// See `BoxWidthStyle` for details on available styles.
260    pub selection_width_style: Option<BoxWidthStyle>,
261
262    /// {@macro flutter.widgets.editableText.enableInteractiveSelection}
263    pub enable_interactive_selection: bool,
264
265    /// {@macro flutter.widgets.editableText.selectionControls}
266    pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
267
268    /// {@macro flutter.widgets.scrollable.dragStartBehavior}
269    pub drag_start_behavior: DragStartBehavior,
270
271    /// Configuration of toolbar options.
272    ///
273    /// Paste and cut will be disabled regardless.
274    ///
275    /// If not set, select all and copy will be enabled by default.
276    #[deprecated(
277        note = "Use `context_menu_builder` instead. This feature was deprecated after v3.3.0-0.5.pre."
278    )]
279    pub toolbar_options: Option<ToolbarOptions>,
280
281    /// Called when the user taps on this selectable text.
282    ///
283    /// The selectable text builds a `GestureDetector` to handle input events like tap,
284    /// to trigger focus requests, to move the caret, adjust the selection, etc.
285    /// Handling some of those events by wrapping the selectable text with a competing
286    /// `GestureDetector` is problematic.
287    ///
288    /// To unconditionally handle taps, without interfering with the selectable text's
289    /// internal gesture detector, provide this callback.
290    ///
291    /// To be notified when the text field gains or loses the focus, provide a
292    /// [`focus_node`](Self::focus_node) and add a listener to that.
293    ///
294    /// To listen to arbitrary pointer events without competing with the
295    /// selectable text's internal gesture detector, use a `Listener`.
296    pub on_tap: Option<GestureTapCallback>,
297
298    /// {@macro flutter.widgets.editableText.scrollPhysics}
299    pub scroll_physics: Option<ScrollPhysicsRef>,
300
301    /// {@macro flutter.widgets.editableText.scrollBehavior}
302    pub scroll_behavior: Option<ScrollBehaviorRef>,
303
304    /// {@macro flutter.widgets.Text.semanticsLabel}
305    pub semantics_label: Option<String>,
306
307    /// {@macro dart.ui.textHeightBehavior}
308    pub text_height_behavior: Option<TextHeightBehavior>,
309
310    /// {@macro flutter.painting.textPainter.textWidthBasis}
311    pub text_width_basis: Option<TextWidthBasis>,
312
313    /// {@macro flutter.widgets.editableText.onSelectionChanged}
314    pub on_selection_changed: Option<SelectionChangedCallback>,
315
316    /// {@macro flutter.widgets.EditableText.contextMenuBuilder}
317    pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
318
319    /// The configuration for the magnifier used when the text is selected.
320    ///
321    /// By default, builds a `CupertinoTextMagnifier` on iOS and [`TextMagnifier`] on
322    /// Android, and builds nothing on all other platforms. To suppress the magnifier,
323    /// consider passing [`TextMagnifierConfiguration::DISABLED`].
324    pub magnifier_configuration: Option<TextMagnifierConfiguration>,
325}
326
327#[allow(deprecated)]
328impl SelectableText {
329    /// Creates a selectable text widget.
330    ///
331    /// If the [`style`](Self::style) argument is null, the text will use the style from the
332    /// closest enclosing [`DefaultTextStyle`].
333    pub fn new(data: impl Into<String>) -> SelectableText {
334        SelectableText::with_content(Some(data.into()), None)
335    }
336
337    /// Creates a selectable text widget with a [`TextSpan`].
338    ///
339    /// The [`text_span`](Self::text_span) parameter must not be null and only contain
340    /// [`TextSpan`] in `TextSpan::children`. Other type of `InlineSpan` is not allowed.
341    pub fn rich(text_span: TextSpan) -> SelectableText {
342        SelectableText::with_content(None, Some(text_span))
343    }
344
345    fn with_content(data: Option<String>, text_span: Option<TextSpan>) -> SelectableText {
346        SelectableText {
347            key: None,
348            data,
349            text_span,
350            focus_node: None,
351            style: None,
352            strut_style: None,
353            text_align: None,
354            text_direction: None,
355            text_scale_factor: None,
356            text_scaler: None,
357            autofocus: false,
358            min_lines: None,
359            max_lines: None,
360            show_cursor: false,
361            cursor_width: 2.0,
362            cursor_height: None,
363            cursor_radius: None,
364            cursor_color: None,
365            selection_color: None,
366            selection_height_style: None,
367            selection_width_style: None,
368            enable_interactive_selection: true,
369            selection_controls: None,
370            drag_start_behavior: DragStartBehavior::Start,
371            toolbar_options: None,
372            on_tap: None,
373            scroll_physics: None,
374            scroll_behavior: None,
375            semantics_label: None,
376            text_height_behavior: None,
377            text_width_basis: None,
378            on_selection_changed: None,
379            context_menu_builder: Some(Rc::new(Self::default_context_menu_builder)),
380            magnifier_configuration: None,
381        }
382    }
383
384    /// Dart `SelectableText(key:)`.
385    pub fn key(mut self, key: KeyRef) -> SelectableText {
386        self.key = Some(key);
387        self
388    }
389
390    /// Dart `SelectableText(focusNode:)`.
391    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SelectableText {
392        self.focus_node = Some(focus_node);
393        self
394    }
395
396    /// Dart `SelectableText(style:)`.
397    pub fn style(mut self, style: TextStyle) -> SelectableText {
398        self.style = Some(style);
399        self
400    }
401
402    /// Dart `SelectableText(strutStyle:)`.
403    pub fn strut_style(mut self, strut_style: StrutStyle) -> SelectableText {
404        self.strut_style = Some(strut_style);
405        self
406    }
407
408    /// Dart `SelectableText(textAlign:)`.
409    pub fn text_align(mut self, text_align: TextAlign) -> SelectableText {
410        self.text_align = Some(text_align);
411        self
412    }
413
414    /// Dart `SelectableText(textDirection:)`.
415    pub fn text_direction(mut self, text_direction: TextDirection) -> SelectableText {
416        self.text_direction = Some(text_direction);
417        self
418    }
419
420    /// Dart `SelectableText(textScaleFactor:)`.
421    #[deprecated(
422        note = "Use text_scaler instead. Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. This feature was deprecated after v3.12.0-2.0.pre."
423    )]
424    pub fn text_scale_factor(mut self, text_scale_factor: f64) -> SelectableText {
425        self.text_scale_factor = Some(text_scale_factor);
426        self
427    }
428
429    /// Dart `SelectableText(textScaler:)`.
430    pub fn text_scaler(mut self, text_scaler: TextScaler) -> SelectableText {
431        self.text_scaler = Some(text_scaler);
432        self
433    }
434
435    /// Dart `SelectableText(showCursor:)`.
436    pub fn show_cursor(mut self, show_cursor: bool) -> SelectableText {
437        self.show_cursor = show_cursor;
438        self
439    }
440
441    /// Dart `SelectableText(autofocus:)`.
442    pub fn autofocus(mut self, autofocus: bool) -> SelectableText {
443        self.autofocus = autofocus;
444        self
445    }
446
447    /// Dart `SelectableText(toolbarOptions:)`.
448    #[deprecated(
449        note = "Use `context_menu_builder` instead. This feature was deprecated after v3.3.0-0.5.pre."
450    )]
451    pub fn toolbar_options(mut self, toolbar_options: ToolbarOptions) -> SelectableText {
452        self.toolbar_options = Some(toolbar_options);
453        self
454    }
455
456    /// Dart `SelectableText(minLines:)`.
457    pub fn min_lines(mut self, min_lines: i32) -> SelectableText {
458        debug_assert!(min_lines > 0);
459        self.min_lines = Some(min_lines);
460        self
461    }
462
463    /// Dart `SelectableText(maxLines:)`.
464    pub fn max_lines(mut self, max_lines: Option<i32>) -> SelectableText {
465        debug_assert!(max_lines.is_none_or(|lines| lines > 0));
466        self.max_lines = max_lines;
467        self
468    }
469
470    /// Dart `SelectableText(cursorWidth:)`.
471    pub fn cursor_width(mut self, cursor_width: f64) -> SelectableText {
472        self.cursor_width = cursor_width;
473        self
474    }
475
476    /// Dart `SelectableText(cursorHeight:)`.
477    pub fn cursor_height(mut self, cursor_height: f64) -> SelectableText {
478        self.cursor_height = Some(cursor_height);
479        self
480    }
481
482    /// Dart `SelectableText(cursorRadius:)`.
483    pub fn cursor_radius(mut self, cursor_radius: Radius) -> SelectableText {
484        self.cursor_radius = Some(cursor_radius);
485        self
486    }
487
488    /// Dart `SelectableText(cursorColor:)`.
489    pub fn cursor_color(mut self, cursor_color: Color) -> SelectableText {
490        self.cursor_color = Some(cursor_color);
491        self
492    }
493
494    /// Dart `SelectableText(selectionColor:)`.
495    pub fn selection_color(mut self, selection_color: Color) -> SelectableText {
496        self.selection_color = Some(selection_color);
497        self
498    }
499
500    /// Dart `SelectableText(selectionHeightStyle:)`.
501    pub fn selection_height_style(
502        mut self,
503        selection_height_style: BoxHeightStyle,
504    ) -> SelectableText {
505        self.selection_height_style = Some(selection_height_style);
506        self
507    }
508
509    /// Dart `SelectableText(selectionWidthStyle:)`.
510    pub fn selection_width_style(mut self, selection_width_style: BoxWidthStyle) -> SelectableText {
511        self.selection_width_style = Some(selection_width_style);
512        self
513    }
514
515    /// Dart `SelectableText(dragStartBehavior:)`.
516    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> SelectableText {
517        self.drag_start_behavior = drag_start_behavior;
518        self
519    }
520
521    /// Dart `SelectableText(enableInteractiveSelection:)`.
522    pub fn enable_interactive_selection(
523        mut self,
524        enable_interactive_selection: bool,
525    ) -> SelectableText {
526        self.enable_interactive_selection = enable_interactive_selection;
527        self
528    }
529
530    /// Dart `SelectableText(selectionControls:)`.
531    pub fn selection_controls(
532        mut self,
533        selection_controls: Rc<dyn TextSelectionControls>,
534    ) -> SelectableText {
535        self.selection_controls = Some(selection_controls);
536        self
537    }
538
539    /// Dart `SelectableText(onTap:)`.
540    pub fn on_tap(mut self, on_tap: GestureTapCallback) -> SelectableText {
541        self.on_tap = Some(on_tap);
542        self
543    }
544
545    /// Dart `SelectableText(scrollPhysics:)`.
546    pub fn scroll_physics(mut self, scroll_physics: ScrollPhysicsRef) -> SelectableText {
547        self.scroll_physics = Some(scroll_physics);
548        self
549    }
550
551    /// Dart `SelectableText(scrollBehavior:)`.
552    pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> SelectableText {
553        self.scroll_behavior = Some(scroll_behavior);
554        self
555    }
556
557    /// Dart `SelectableText(semanticsLabel:)`.
558    pub fn semantics_label(mut self, semantics_label: impl Into<String>) -> SelectableText {
559        self.semantics_label = Some(semantics_label.into());
560        self
561    }
562
563    /// Dart `SelectableText(textHeightBehavior:)`.
564    pub fn text_height_behavior(
565        mut self,
566        text_height_behavior: TextHeightBehavior,
567    ) -> SelectableText {
568        self.text_height_behavior = Some(text_height_behavior);
569        self
570    }
571
572    /// Dart `SelectableText(textWidthBasis:)`.
573    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> SelectableText {
574        self.text_width_basis = Some(text_width_basis);
575        self
576    }
577
578    /// Dart `SelectableText(onSelectionChanged:)`.
579    pub fn on_selection_changed(
580        mut self,
581        on_selection_changed: impl Fn(&mut App, TextSelection, Option<SelectionChangedCause>) + 'static,
582    ) -> SelectableText {
583        self.on_selection_changed = Some(Rc::new(on_selection_changed));
584        self
585    }
586
587    /// Dart `SelectableText(contextMenuBuilder:)`; `None` builds no context menu.
588    pub fn context_menu_builder(
589        mut self,
590        context_menu_builder: Option<EditableTextContextMenuBuilder>,
591    ) -> SelectableText {
592        self.context_menu_builder = context_menu_builder;
593        self
594    }
595
596    /// Dart `SelectableText(magnifierConfiguration:)`.
597    pub fn magnifier_configuration(
598        mut self,
599        magnifier_configuration: TextMagnifierConfiguration,
600    ) -> SelectableText {
601        self.magnifier_configuration = Some(magnifier_configuration);
602        self
603    }
604
605    /// {@macro flutter.widgets.editableText.selectionEnabled}
606    pub fn selection_enabled(&self) -> bool {
607        self.enable_interactive_selection
608    }
609
610    fn default_context_menu_builder(
611        app: &mut App,
612        _context: BuildContext,
613        editable_text_state: Handle<EditableTextState>,
614    ) -> WidgetRef {
615        AdaptiveTextSelectionToolbar::editable_text(app, editable_text_state).into_widget()
616    }
617
618    /// Dart's constructor asserts across fields.
619    fn debug_check_constructor(&self) {
620        debug_assert!(
621            self.max_lines
622                .is_none_or(|max| self.min_lines.is_none_or(|min| max >= min)),
623            "minLines can't be greater than maxLines"
624        );
625        debug_assert!(
626            self.text_scaler.is_none() || self.text_scale_factor.is_none(),
627            "textScaleFactor is deprecated and cannot be specified when textScaler is specified."
628        );
629    }
630
631    /// Dart's `textSpan ?? TextSpan(text: data)`, the span the state's controller holds.
632    fn effective_text_span(&self) -> TextSpan {
633        self.text_span.clone().unwrap_or_else(|| {
634            let mut span = TextSpan::new();
635            if let Some(data) = &self.data {
636                span = span.text(data.clone());
637            }
638            span
639        })
640    }
641}
642
643impl Debug for SelectableText {
644    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645        f.debug_struct("SelectableText")
646            .field("data", &self.data)
647            .field("semantics_label", &self.semantics_label)
648            .field("focus_node", &self.focus_node)
649            .field("style", &self.style)
650            .field("autofocus", &self.autofocus)
651            .field("show_cursor", &self.show_cursor)
652            .field("min_lines", &self.min_lines)
653            .field("max_lines", &self.max_lines)
654            .field("text_align", &self.text_align)
655            .field("text_direction", &self.text_direction)
656            .field("cursor_width", &self.cursor_width)
657            .field("selection_enabled", &self.selection_enabled())
658            .finish_non_exhaustive()
659    }
660}
661
662impl StatefulWidget for SelectableText {
663    type State = SelectableTextState;
664
665    fn key(&self) -> Option<&KeyRef> {
666        self.key.as_ref()
667    }
668
669    #[allow(deprecated)]
670    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
671        // Dart's `selectionControls` line waits for that type's `Display`.
672        properties
673            .add(DiagnosticsProperty::<String>::new("data", self.data.clone()).default_value(None));
674        properties.add(
675            DiagnosticsProperty::<String>::new("semanticsLabel", self.semantics_label.clone())
676                .default_value(None),
677        );
678        properties.add(
679            DiagnosticsProperty::<String>::new(
680                "focusNode",
681                self.focus_node.as_ref().map(|node| node.to_string(app)),
682            )
683            .default_value(None),
684        );
685        properties.add(
686            DiagnosticsProperty::<TextStyle>::new("style", self.style.clone()).default_value(None),
687        );
688        properties.add(
689            DiagnosticsProperty::<bool>::new("autofocus", self.autofocus)
690                .default_value(Some(false)),
691        );
692        properties.add(
693            DiagnosticsProperty::<bool>::new("showCursor", self.show_cursor)
694                .default_value(Some(false)),
695        );
696        properties.add(IntProperty::<i32>::new("minLines", self.min_lines).default_value(None));
697        properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).default_value(None));
698        properties
699            .add(EnumProperty::<TextAlign>::new("textAlign", self.text_align).default_value(None));
700        properties.add(
701            EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
702                .default_value(None),
703        );
704        properties.add(
705            DoubleProperty::new("textScaleFactor", self.text_scale_factor).default_value(None),
706        );
707        properties.add(
708            DiagnosticsProperty::<TextScaler>::new("textScaler", self.text_scaler.clone())
709                .default_value(None),
710        );
711        properties
712            .add(DoubleProperty::new("cursorWidth", self.cursor_width).default_value(Some(2.0)));
713        properties.add(DoubleProperty::new("cursorHeight", self.cursor_height).default_value(None));
714        properties.add(
715            DiagnosticsProperty::<Radius>::new("cursorRadius", self.cursor_radius)
716                .default_value(None),
717        );
718        properties.add(ColorProperty::new("cursorColor", self.cursor_color).default_value(None));
719        properties.add(
720            DiagnosticsProperty::<Color>::new("selectionColor", self.selection_color)
721                .default_value(None),
722        );
723        properties.add(
724            FlagProperty::new("selectionEnabled", Some(self.selection_enabled()))
725                .default_value(Some(true))
726                .if_false("selection disabled"),
727        );
728        properties.add(
729            DiagnosticsProperty::<String>::new(
730                "scrollPhysics",
731                self.scroll_physics
732                    .as_ref()
733                    .map(|physics| format!("{physics:?}")),
734            )
735            .default_value(None),
736        );
737        properties.add(
738            DiagnosticsProperty::<String>::new(
739                "scrollBehavior",
740                self.scroll_behavior
741                    .as_ref()
742                    .map(|behavior| format!("{behavior:?}")),
743            )
744            .default_value(None),
745        );
746        properties.add(
747            DiagnosticsProperty::<TextHeightBehavior>::new(
748                "textHeightBehavior",
749                self.text_height_behavior,
750            )
751            .default_value(None),
752        );
753    }
754
755    fn debug_check_constructor(&self) {
756        SelectableText::debug_check_constructor(self);
757    }
758
759    fn create_state(&self) -> SelectableTextState {
760        SelectableTextState {
761            state: StateData::new(),
762            controller: None,
763            focus_node: None,
764            show_selection_handles: false,
765            selection_gesture_detector_builder: None,
766            force_press_enabled: None,
767            editable_text_key: GlobalKey::new(),
768        }
769    }
770}
771
772/// Dart's `_SelectableTextState`.
773pub struct SelectableTextState {
774    state: StateData<SelectableText>,
775    controller: Option<Ref<TextSpanEditingController>>,
776    focus_node: Option<Ref<FocusNode>>,
777    show_selection_handles: bool,
778    selection_gesture_detector_builder: Option<Ref<SelectableTextSelectionGestureDetectorBuilder>>,
779    /// Dart's `late bool forcePressEnabled`, which `build` sets.
780    force_press_enabled: Option<bool>,
781    editable_text_key: GlobalKey,
782}
783
784impl SelectableTextState {
785    fn editable_text(self: Handle<Self>, app: &mut App) -> Option<Handle<EditableTextState>> {
786        let key = app.get(self).editable_text_key.clone();
787        key.current_state::<EditableTextState>(app)
788    }
789
790    fn controller(self: Handle<Self>, app: &App) -> Handle<TextSpanEditingController> {
791        app.get(self)
792            .controller
793            .handle()
794            .expect("created in init_state")
795    }
796
797    fn effective_focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
798        if let Some(focus_node) = self.widget(app).focus_node.clone() {
799            return focus_node;
800        }
801        if let Some(focus_node) = app.get(self).focus_node.as_ref() {
802            return focus_node.erase();
803        }
804        let focus_node = FocusNode::new(app);
805        focus_node.set_skip_traversal(app, true);
806        app.get_mut(self).focus_node = Some(focus_node.clone());
807        focus_node.into_erased()
808    }
809
810    fn selection_gesture_detector_builder(
811        self: Handle<Self>,
812        app: &App,
813    ) -> Handle<SelectableTextSelectionGestureDetectorBuilder> {
814        app.get(self)
815            .selection_gesture_detector_builder
816            .handle()
817            .expect("created in init_state")
818    }
819
820    fn create_controller(self: Handle<Self>, app: &mut App) {
821        let text_span = self.widget(app).effective_text_span();
822        let controller = TextSpanEditingController::new(app, text_span);
823        app.get_mut(self).controller = Some(controller.clone());
824        controller.add_listener(
825            app,
826            Listener::handle_method(self, Self::on_controller_changed),
827        );
828    }
829
830    fn on_controller_changed(self: Handle<Self>, app: &mut App) {
831        let has_focus = self.effective_focus_node(app).has_focus(app);
832        let show_selection_handles =
833            !has_focus || !self.controller(app).selection(app).is_collapsed();
834        if show_selection_handles == app.get(self).show_selection_handles {
835            return;
836        }
837        self.set_state(app, |state| {
838            state.show_selection_handles = show_selection_handles;
839        });
840    }
841
842    fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
843        if !self.effective_focus_node(app).has_focus(app)
844            && SchedulerBinding::lifecycle_state(app) == Some(AppLifecycleState::Resumed)
845        {
846            // We should only clear the selection when this SelectableText loses
847            // focus while the application is currently running. It is possible
848            // that the application is not currently running, for example on desktop
849            // platforms, clicking on a different window switches the focus to
850            // the new window causing the Flutter application to go inactive. In this
851            // case we want to retain the selection so it remains when we return to
852            // the Flutter application.
853            let controller = self.controller(app);
854            let text = controller.value(app).text.clone();
855            controller.set_value(app, TextEditingValue::new().text(text));
856        }
857    }
858
859    fn handle_selection_changed(
860        self: Handle<Self>,
861        app: &mut App,
862        selection: TextSelection,
863        cause: Option<SelectionChangedCause>,
864    ) {
865        let will_show_selection_handles = self.should_show_selection_handles(app, cause);
866        if will_show_selection_handles != app.get(self).show_selection_handles {
867            self.set_state(app, |state| {
868                state.show_selection_handles = will_show_selection_handles;
869            });
870        }
871
872        if let Some(on_selection_changed) = self.widget(app).on_selection_changed.clone() {
873            on_selection_changed(app, selection, cause);
874        }
875
876        let context = self.context(app);
877        match Theme::of(app, context).platform {
878            TargetPlatform::IOS | TargetPlatform::MacOS => {
879                if cause == Some(SelectionChangedCause::LongPress)
880                    && let Some(editable_text) = self.editable_text(app)
881                {
882                    editable_text.bring_into_view(app, selection.base());
883                }
884            }
885            TargetPlatform::Android
886            | TargetPlatform::Fuchsia
887            | TargetPlatform::Linux
888            | TargetPlatform::Windows => {
889                // Do nothing.
890            }
891        }
892    }
893
894    fn handle_selection_handle_tapped(self: Handle<Self>, app: &mut App) {
895        if self.controller(app).selection(app).is_collapsed() {
896            self.editable_text(app)
897                .expect("the EditableText is mounted")
898                .toggle_toolbar(app, true);
899        }
900    }
901
902    fn should_show_selection_handles(
903        self: Handle<Self>,
904        app: &App,
905        cause: Option<SelectionChangedCause>,
906    ) -> bool {
907        // When the text field is activated by something that doesn't trigger the
908        // selection overlay, we shouldn't show the handles either.
909        if !self
910            .selection_gesture_detector_builder(app)
911            .should_show_selection_toolbar(app)
912        {
913            return false;
914        }
915
916        let controller = self.controller(app);
917        if controller.selection(app).is_collapsed() {
918            return false;
919        }
920
921        if cause == Some(SelectionChangedCause::Keyboard) {
922            return false;
923        }
924
925        if cause == Some(SelectionChangedCause::LongPress) {
926            return true;
927        }
928
929        if !controller.text_value(app).is_empty() {
930            return true;
931        }
932
933        false
934    }
935}
936
937impl State for SelectableTextState {
938    type Widget = SelectableText;
939    waft_widgets::state_accessors!();
940
941    fn init_state(self: Handle<Self>, app: &mut App) {
942        let builder = app.create(SelectableTextSelectionGestureDetectorBuilder {
943            builder: TextSelectionGestureDetectorBuilderData::new(
944                self.as_text_selection_gesture_detector_builder_delegate(),
945            ),
946            state: self,
947        });
948        app.get_mut(self).selection_gesture_detector_builder = Some(builder);
949        self.create_controller(app);
950        let focus_node = self.effective_focus_node(app);
951        focus_node.add_listener(
952            app,
953            Listener::handle_method(self, Self::handle_focus_changed),
954        );
955    }
956
957    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectableText) {
958        let widget = self.widget(app);
959        let text_span_changed = match (&widget.text_span, &old_widget.text_span) {
960            (None, None) => false,
961            (Some(new), Some(old)) => !new.eq_span(old),
962            _ => true,
963        };
964        if widget.data != old_widget.data || text_span_changed {
965            let controller = self.controller(app);
966            controller.remove_listener(
967                app,
968                &Listener::handle_method(self, Self::on_controller_changed),
969            );
970            controller.as_controller().dispose(app);
971            self.create_controller(app);
972        }
973        if self.widget(app).focus_node != old_widget.focus_node {
974            if let Some(old_focus) = old_widget
975                .focus_node
976                .clone()
977                .or_else(|| app.get(self).focus_node.as_ref().map(Ref::erase))
978            {
979                old_focus.remove_listener(
980                    app,
981                    &Listener::handle_method(self, Self::handle_focus_changed),
982                );
983            }
984            if let Some(new_focus) = self
985                .widget(app)
986                .focus_node
987                .clone()
988                .or_else(|| app.get(self).focus_node.as_ref().map(Ref::erase))
989            {
990                new_focus.add_listener(
991                    app,
992                    Listener::handle_method(self, Self::handle_focus_changed),
993                );
994            }
995        }
996        let has_focus = self.effective_focus_node(app).has_focus(app);
997        let show_selection_handles =
998            !(has_focus && self.controller(app).selection(app).is_collapsed());
999        app.get_mut(self).show_selection_handles = show_selection_handles;
1000    }
1001
1002    fn dispose(self: Handle<Self>, app: &mut App) {
1003        let focus_node = self.effective_focus_node(app);
1004        focus_node.remove_listener(
1005            app,
1006            &Listener::handle_method(self, Self::handle_focus_changed),
1007        );
1008        if let Some(focus_node) = app.get(self).focus_node.handle() {
1009            focus_node.dispose(app);
1010        }
1011        self.controller(app).as_controller().dispose(app);
1012    }
1013
1014    #[allow(deprecated)]
1015    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1016        // TODO(garyq): Assert to block WidgetSpans from being used here are removed,
1017        // but we still do not yet have nice handling of things like carets, clipboard,
1018        // and other features. We should add proper support. Currently, caret handling
1019        // is blocked on SkParagraph switch and https://github.com/flutter/engine/pull/27010
1020        // should be landed in SkParagraph after the switch is complete.
1021        debug_assert!(debug_check_has_media_query(app, context));
1022        debug_assert!(debug_check_has_directionality(
1023            app, context, None, None, None
1024        ));
1025        debug_assert!(
1026            !self
1027                .widget(app)
1028                .style
1029                .as_ref()
1030                .is_some_and(|style| !style.inherit
1031                    && (style.font_size.is_none() || style.text_baseline.is_none())),
1032            "inherit false style must supply fontSize and textBaseline"
1033        );
1034
1035        let theme = Theme::of(app, context);
1036        let selection_style = DefaultSelectionStyle::of(app, context);
1037        let focus_node = self.effective_focus_node(app);
1038
1039        let widget = self.widget(app);
1040        let mut text_selection_controls = widget.selection_controls.clone();
1041        let paint_cursor_above_text;
1042        let cursor_opacity_animates;
1043        let mut cursor_offset = None;
1044        let cursor_color: Color;
1045        let selection_color: Color;
1046        let mut cursor_radius = widget.cursor_radius;
1047        let widget_cursor_color = widget.cursor_color;
1048        let style_cursor_color = selection_style
1049            .cursor_color
1050            .as_ref()
1051            .map(|color| color.color());
1052        let style_selection_color = selection_style
1053            .selection_color
1054            .as_ref()
1055            .map(|color| color.color());
1056
1057        let force_press_enabled;
1058        match theme.platform {
1059            TargetPlatform::IOS => {
1060                let cupertino_theme = CupertinoTheme::of(app, context);
1061                force_press_enabled = true;
1062                text_selection_controls
1063                    .get_or_insert_with(cupertino_text_selection_handle_controls);
1064                paint_cursor_above_text = true;
1065                cursor_opacity_animates = true;
1066                cursor_color = widget_cursor_color
1067                    .or(style_cursor_color)
1068                    .unwrap_or_else(|| cupertino_theme.primary_color().color());
1069                selection_color = style_selection_color
1070                    .unwrap_or_else(|| cupertino_theme.primary_color().color().with_opacity(0.40));
1071                cursor_radius.get_or_insert(Radius::circular(2.0));
1072                cursor_offset = Some(Offset::new(
1073                    f64::from(IOS_HORIZONTAL_OFFSET)
1074                        / MediaQuery::device_pixel_ratio_of(app, context),
1075                    0.0,
1076                ));
1077            }
1078            TargetPlatform::MacOS => {
1079                let cupertino_theme = CupertinoTheme::of(app, context);
1080                force_press_enabled = false;
1081                text_selection_controls
1082                    .get_or_insert_with(cupertino_desktop_text_selection_handle_controls);
1083                paint_cursor_above_text = true;
1084                cursor_opacity_animates = true;
1085                cursor_color = widget_cursor_color
1086                    .or(style_cursor_color)
1087                    .unwrap_or_else(|| cupertino_theme.primary_color().color());
1088                selection_color = style_selection_color
1089                    .unwrap_or_else(|| cupertino_theme.primary_color().color().with_opacity(0.40));
1090                cursor_radius.get_or_insert(Radius::circular(2.0));
1091                cursor_offset = Some(Offset::new(
1092                    f64::from(IOS_HORIZONTAL_OFFSET)
1093                        / MediaQuery::device_pixel_ratio_of(app, context),
1094                    0.0,
1095                ));
1096            }
1097            TargetPlatform::Android | TargetPlatform::Fuchsia => {
1098                force_press_enabled = false;
1099                text_selection_controls.get_or_insert_with(material_text_selection_handle_controls);
1100                paint_cursor_above_text = false;
1101                cursor_opacity_animates = false;
1102                cursor_color = widget_cursor_color
1103                    .or(style_cursor_color)
1104                    .unwrap_or(theme.color_scheme.primary());
1105                selection_color = style_selection_color
1106                    .unwrap_or_else(|| theme.color_scheme.primary().with_opacity(0.40));
1107            }
1108            TargetPlatform::Linux | TargetPlatform::Windows => {
1109                force_press_enabled = false;
1110                text_selection_controls.get_or_insert_with(desktop_text_selection_handle_controls);
1111                paint_cursor_above_text = false;
1112                cursor_opacity_animates = false;
1113                cursor_color = widget_cursor_color
1114                    .or(style_cursor_color)
1115                    .unwrap_or(theme.color_scheme.primary());
1116                selection_color = style_selection_color
1117                    .unwrap_or_else(|| theme.color_scheme.primary().with_opacity(0.40));
1118            }
1119        }
1120        app.get_mut(self).force_press_enabled = Some(force_press_enabled);
1121
1122        let default_text_style = DefaultTextStyle::of(app, context);
1123        let widget = self.widget(app);
1124        let controller = app
1125            .get(self)
1126            .controller
1127            .clone()
1128            .expect("created in init_state");
1129        let mut effective_text_style = widget.style.clone();
1130        if effective_text_style
1131            .as_ref()
1132            .is_none_or(|style| style.inherit)
1133        {
1134            let span_style = app.get(&controller).text_span.style.clone();
1135            effective_text_style = Some(
1136                default_text_style
1137                    .style
1138                    .merge(widget.style.as_ref().or(span_style.as_ref())),
1139            );
1140        }
1141        let effective_scaler = widget
1142            .text_scaler
1143            .clone()
1144            .or_else(|| widget.text_scale_factor.map(TextScaler::linear));
1145
1146        let this = self;
1147        let mut editable = EditableText::new(
1148            controller.erase::<AnyTextEditingController>(),
1149            focus_node.clone(),
1150            effective_text_style.expect("filled above"),
1151            cursor_color,
1152            CupertinoColors::INACTIVE_GRAY.color(),
1153        )
1154        .key(app.get(self).editable_text_key.clone().into())
1155        .read_only(true)
1156        .text_width_basis(
1157            widget
1158                .text_width_basis
1159                .unwrap_or(default_text_style.text_width_basis),
1160        )
1161        .show_selection_handles(app.get(self).show_selection_handles)
1162        .show_cursor(widget.show_cursor)
1163        .text_align(
1164            widget
1165                .text_align
1166                .or(default_text_style.text_align)
1167                .unwrap_or(TextAlign::Start),
1168        )
1169        .autofocus(widget.autofocus)
1170        .force_line(false)
1171        .max_lines(widget.max_lines.or(default_text_style.max_lines))
1172        .selection_color(widget.selection_color.unwrap_or(selection_color))
1173        .on_selection_changed(move |app, selection, cause| {
1174            this.handle_selection_changed(app, selection, cause);
1175        })
1176        .on_selection_handle_tapped(Listener::handle_method(
1177            this,
1178            Self::handle_selection_handle_tapped,
1179        ))
1180        .renderer_ignores_pointer(true)
1181        .cursor_width(widget.cursor_width)
1182        .cursor_opacity_animates(cursor_opacity_animates)
1183        .paint_cursor_above_text(paint_cursor_above_text)
1184        .enable_interactive_selection(widget.enable_interactive_selection)
1185        .magnifier_configuration(
1186            widget
1187                .magnifier_configuration
1188                .clone()
1189                .unwrap_or_else(|| TextMagnifier::adaptive_magnifier_configuration(app)),
1190        )
1191        .drag_start_behavior(widget.drag_start_behavior);
1192        if let Some(toolbar_options) = widget.toolbar_options {
1193            editable = editable.toolbar_options(toolbar_options);
1194        }
1195        if let Some(text_height_behavior) = widget
1196            .text_height_behavior
1197            .or(default_text_style.text_height_behavior)
1198        {
1199            editable = editable.text_height_behavior(text_height_behavior);
1200        }
1201        if let Some(text_direction) = widget.text_direction {
1202            editable = editable.text_direction(text_direction);
1203        }
1204        if let Some(effective_scaler) = effective_scaler {
1205            editable = editable.text_scaler(effective_scaler);
1206        }
1207        if let Some(min_lines) = widget.min_lines {
1208            editable = editable.min_lines(min_lines);
1209        }
1210        if let Some(strut_style) = widget.strut_style.clone() {
1211            editable = editable.strut_style(strut_style);
1212        }
1213        if widget.selection_enabled()
1214            && let Some(text_selection_controls) = text_selection_controls
1215        {
1216            editable = editable.selection_controls(text_selection_controls);
1217        }
1218        if let Some(cursor_height) = widget.cursor_height {
1219            editable = editable.cursor_height(cursor_height);
1220        }
1221        if let Some(cursor_radius) = cursor_radius {
1222            editable = editable.cursor_radius(cursor_radius);
1223        }
1224        if let Some(selection_height_style) = widget.selection_height_style {
1225            editable = editable.selection_height_style(selection_height_style);
1226        }
1227        if let Some(selection_width_style) = widget.selection_width_style {
1228            editable = editable.selection_width_style(selection_width_style);
1229        }
1230        if let Some(cursor_offset) = cursor_offset {
1231            editable = editable.cursor_offset(cursor_offset);
1232        }
1233        if let Some(scroll_physics) = widget.scroll_physics.clone() {
1234            editable = editable.scroll_physics(scroll_physics);
1235        }
1236        if let Some(scroll_behavior) = widget.scroll_behavior.clone() {
1237            editable = editable.scroll_behavior(scroll_behavior);
1238        }
1239        if let Some(context_menu_builder) = widget.context_menu_builder.clone() {
1240            editable = editable.context_menu_builder(context_menu_builder);
1241        }
1242        let child = RepaintBoundary::new().child(editable);
1243
1244        let semantics_label = self.widget(app).semantics_label.clone();
1245        let mut semantics = Semantics::new()
1246            .exclude_semantics(semantics_label.is_some())
1247            .on_long_press(Rc::new(move |app| {
1248                this.effective_focus_node(app).request_focus(app, None);
1249            }));
1250        if let Some(semantics_label) = semantics_label {
1251            semantics = semantics.label(semantics_label);
1252        }
1253        let builder = self.selection_gesture_detector_builder(app);
1254        semantics
1255            .child(TextSelectionGestureDetectorBuilder::build_gesture_detector(
1256                builder,
1257                app,
1258                None,
1259                Some(HitTestBehavior::Translucent),
1260                child.into_widget(),
1261            ))
1262            .into_widget()
1263    }
1264}
1265
1266impl TextSelectionGestureDetectorBuilderDelegate for SelectableTextState {
1267    fn editable_text_key(self: Handle<Self>, app: &App) -> GlobalKey {
1268        app.get(self).editable_text_key.clone()
1269    }
1270
1271    fn force_press_enabled(self: Handle<Self>, app: &App) -> bool {
1272        app.get(self)
1273            .force_press_enabled
1274            .expect("build sets force_press_enabled")
1275    }
1276
1277    fn selection_enabled(self: Handle<Self>, app: &App) -> bool {
1278        self.widget(app).selection_enabled()
1279    }
1280}
1281
1282#[cfg(test)]
1283mod tests {
1284    use std::cell::{Cell, RefCell};
1285    use std::time::Duration;
1286
1287    use waft_cupertino::{CupertinoButton, cupertino_text_selection_controls};
1288    use waft_embedder::Size;
1289    use waft_embedder::{TextAffinity, TextPosition};
1290    use waft_foundation::UniqueKey;
1291    use waft_rendering::{RenderBox as _, RenderEditable};
1292    use waft_services::{
1293        LogicalKeyboardKey, PhysicalKeyboardKey, SystemMouseCursors, TextInputClient,
1294    };
1295    use waft_test::{MockClipboard, TestPlatform};
1296    use waft_widgets::{
1297        AnyElement, AnyTextEditingController, Center, Column, DefaultTextStyle, Focus,
1298        FocusNodeLeaf, IntoWidget, MediaQueryData, ScrollBehaviorRef, SizedBox, Text,
1299    };
1300
1301    use waft_widgets::testing::{
1302        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_n_widgets,
1303        finds_nothing, finds_one_widget, test_widgets, test_widgets_variant,
1304    };
1305
1306    use super::*;
1307    use crate::colors::Colors;
1308    use crate::material::Material;
1309    use crate::test_support::material_app;
1310    use crate::text_button::TextButton;
1311    use crate::text_selection::material_text_selection_controls;
1312    use crate::theme_data::ThemeData;
1313
1314    const K_THREE_LINES: &str =
1315        "First line of text is\nSecond line goes until\nThird line of stuff";
1316    const K_MORE_THAN_FOUR_LINES: &str = "First line of text is\nSecond line goes until\nThird line of stuff\nFourth line won't display and ends at";
1317    const ATWATER: &str = "Atwater Peel Sherbrooke Bonaventure";
1318
1319    /// A tester on `platform` whose host clipboard the case reads back.
1320    fn tester_with_clipboard(platform: TargetPlatform) -> (WidgetTester, MockClipboard) {
1321        let clipboard = MockClipboard::new();
1322        let tester = WidgetTester::with_platform(
1323            TestPlatform::new()
1324                .on(platform)
1325                .with_clipboard(Rc::new(clipboard.clone())),
1326        );
1327        (tester, clipboard)
1328    }
1329
1330    /// Dart's `MaterialApp(home: Material(child: child))`.
1331    fn material_home<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) -> WidgetRef {
1332        let theme = ThemeData::new(&tester.cell.borrow());
1333        material_app(theme, Material::new().child(child).into_widget())
1334    }
1335
1336    /// Dart's `overlay(child: child)`: the child centred on a `Material` under the app's
1337    /// overlay.
1338    fn overlay<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) -> WidgetRef {
1339        let theme = ThemeData::builder()
1340            .use_material3(false)
1341            .build(&tester.cell.borrow());
1342        material_app(
1343            theme,
1344            Center::new()
1345                .child(Material::new().child(child))
1346                .into_widget(),
1347        )
1348    }
1349
1350    fn editable_elements(tester: &WidgetTester) -> Vec<AnyElement> {
1351        find::by_type::<EditableText>().evaluate(tester)
1352    }
1353
1354    fn controller_at(
1355        tester: &WidgetTester,
1356        index: usize,
1357    ) -> waft_widgets::TextEditingControllerRef {
1358        tester.widget(editable_elements(tester)[index], |widget: &EditableText| {
1359            widget.controller.clone()
1360        })
1361    }
1362
1363    fn controller(tester: &WidgetTester) -> AnyTextEditingController {
1364        controller_at(tester, 0).handle()
1365    }
1366
1367    fn selection(tester: &WidgetTester) -> TextSelection {
1368        controller(tester).selection(&tester.cell.borrow())
1369    }
1370
1371    fn editable_state(tester: &WidgetTester) -> Handle<EditableTextState> {
1372        let element = editable_elements(tester)[0];
1373        element
1374            .state_handle::<EditableTextState>(&tester.cell.borrow())
1375            .expect("an EditableText state")
1376    }
1377
1378    fn render_editable_at(
1379        tester: &WidgetTester,
1380        index: usize,
1381    ) -> waft_rendering::RenderHandle<RenderEditable> {
1382        tester.all::<RenderEditable>()[index]
1383    }
1384
1385    /// Dart's `textOffsetToPosition(tester, offset)`.
1386    fn text_offset_to_position(tester: &WidgetTester, offset: i32) -> Offset {
1387        text_offset_to_position_at(tester, offset, 0)
1388    }
1389
1390    fn text_offset_to_position_at(tester: &WidgetTester, offset: i32, index: usize) -> Offset {
1391        let editable = render_editable_at(tester, index);
1392        let mut app = tester.cell.borrow_mut();
1393        let endpoints = editable.get_endpoints_for_selection(
1394            &mut app,
1395            TextSelection::collapsed(offset, TextAffinity::Downstream),
1396        );
1397        assert_eq!(endpoints.len(), 1);
1398        editable
1399            .as_box()
1400            .local_to_global(&app, endpoints[0].point, None)
1401            + Offset::new(0.0, -2.0)
1402    }
1403
1404    /// Dart's `tester.getTopLeft(find.byType(SelectableText)) + Offset(dx, 5.0)`.
1405    fn selectable_text_start_plus(tester: &WidgetTester, dx: f64) -> Offset {
1406        top_left_of_selectable_text(tester, 0) + Offset::new(dx, 5.0)
1407    }
1408
1409    fn top_left_of_selectable_text(tester: &WidgetTester, index: usize) -> Offset {
1410        let element = find::by_type::<SelectableText>().evaluate(tester)[index];
1411        tester.get_rect(element).top_left()
1412    }
1413
1414    fn center_of_selectable_text(tester: &WidgetTester) -> Offset {
1415        let element = find::by_type::<SelectableText>().evaluate(tester)[0];
1416        tester.get_rect(element).center()
1417    }
1418
1419    fn selection_overlay(tester: &WidgetTester) -> Handle<waft_widgets::TextSelectionOverlay> {
1420        let state = editable_state(tester);
1421        state
1422            .selection_overlay(&tester.cell.borrow())
1423            .expect("a selection overlay")
1424    }
1425
1426    fn handles_are_visible(tester: &WidgetTester) -> bool {
1427        selection_overlay(tester).handles_are_visible(&tester.cell.borrow())
1428    }
1429
1430    fn toolbar_is_visible(tester: &WidgetTester) -> bool {
1431        selection_overlay(tester).toolbar_is_visible(&tester.cell.borrow())
1432    }
1433
1434    fn physical_of(logical: LogicalKeyboardKey) -> PhysicalKeyboardKey {
1435        [
1436            (
1437                LogicalKeyboardKey::SHIFT_LEFT,
1438                PhysicalKeyboardKey::SHIFT_LEFT,
1439            ),
1440            (
1441                LogicalKeyboardKey::CONTROL_LEFT,
1442                PhysicalKeyboardKey::CONTROL_LEFT,
1443            ),
1444            (
1445                LogicalKeyboardKey::CONTROL_RIGHT,
1446                PhysicalKeyboardKey::CONTROL_RIGHT,
1447            ),
1448            (
1449                LogicalKeyboardKey::ARROW_LEFT,
1450                PhysicalKeyboardKey::ARROW_LEFT,
1451            ),
1452            (
1453                LogicalKeyboardKey::ARROW_RIGHT,
1454                PhysicalKeyboardKey::ARROW_RIGHT,
1455            ),
1456            (LogicalKeyboardKey::ARROW_UP, PhysicalKeyboardKey::ARROW_UP),
1457            (
1458                LogicalKeyboardKey::ARROW_DOWN,
1459                PhysicalKeyboardKey::ARROW_DOWN,
1460            ),
1461            (LogicalKeyboardKey::KEY_A, PhysicalKeyboardKey::KEY_A),
1462            (LogicalKeyboardKey::KEY_C, PhysicalKeyboardKey::KEY_C),
1463        ]
1464        .into_iter()
1465        .find_map(|(l, p)| (l == logical).then_some(p))
1466        .expect("a key the cases press")
1467    }
1468
1469    /// Dart's `expectMaterialSelectionToolbar()`.
1470    fn expect_material_selection_toolbar(tester: &WidgetTester, platform: TargetPlatform) {
1471        if platform == TargetPlatform::Android {
1472            expect(tester, &find::by_type::<TextButton>(), finds_n_widgets(3));
1473            expect(tester, &find::text("Copy"), finds_one_widget());
1474            expect(tester, &find::text("Share"), finds_one_widget());
1475            expect(tester, &find::text("Select all"), finds_one_widget());
1476        } else {
1477            expect(tester, &find::by_type::<TextButton>(), finds_n_widgets(2));
1478            expect(tester, &find::text("Copy"), finds_one_widget());
1479            expect(tester, &find::text("Select all"), finds_one_widget());
1480        }
1481    }
1482
1483    /// Dart's `expectCupertinoSelectionToolbar()`.
1484    fn expect_cupertino_selection_toolbar(tester: &WidgetTester, platform: TargetPlatform) {
1485        if platform == TargetPlatform::IOS {
1486            expect(
1487                tester,
1488                &find::by_type::<CupertinoButton>(),
1489                finds_n_widgets(4),
1490            );
1491            expect(tester, &find::text("Copy"), finds_one_widget());
1492            expect(tester, &find::text("Look Up"), finds_one_widget());
1493            expect(tester, &find::text("Search Web"), finds_one_widget());
1494            expect(tester, &find::text("Share..."), finds_one_widget());
1495        } else {
1496            expect(
1497                tester,
1498                &find::by_type::<CupertinoButton>(),
1499                finds_one_widget(),
1500            );
1501            expect(tester, &find::text("Copy"), finds_one_widget());
1502        }
1503    }
1504
1505    const ALL_PLATFORMS: [TargetPlatform; 6] = [
1506        TargetPlatform::Android,
1507        TargetPlatform::Fuchsia,
1508        TargetPlatform::IOS,
1509        TargetPlatform::Linux,
1510        TargetPlatform::MacOS,
1511        TargetPlatform::Windows,
1512    ];
1513
1514    #[test]
1515    fn has_expected_defaults() {
1516        let selectable_text = SelectableText::new("selectable text");
1517        assert!(!selectable_text.show_cursor);
1518        assert!(!selectable_text.autofocus);
1519        assert_eq!(
1520            selectable_text.drag_start_behavior,
1521            DragStartBehavior::Start
1522        );
1523        assert_eq!(selectable_text.cursor_width, 2.0);
1524        assert!(selectable_text.cursor_height.is_none());
1525        assert!(selectable_text.enable_interactive_selection);
1526    }
1527
1528    #[test]
1529    fn rich_selectable_text_holds_its_span_and_no_data() {
1530        let selectable_text = SelectableText::rich(TextSpan::new().children(vec![
1531            TextSpan::new().text("First line!").into_span(),
1532            TextSpan::new().text("Second line!\n").into_span(),
1533        ]));
1534        assert!(selectable_text.data.is_none());
1535        assert!(selectable_text.text_span.is_some());
1536        assert!(!selectable_text.show_cursor);
1537        assert!(selectable_text.enable_interactive_selection);
1538    }
1539
1540    #[test]
1541    fn uses_default_selection_style_for_selection_and_cursor_colors_if_provided() {
1542        test_widgets(|tester| {
1543            let selection_color = Colors::ORANGE.primary();
1544            let cursor_color = Colors::RED.primary();
1545            let root = material_home(
1546                tester,
1547                DefaultSelectionStyle::new(SelectableText::new("text"))
1548                    .selection_color(selection_color)
1549                    .cursor_color(cursor_color),
1550            );
1551            tester.pump_widget(root);
1552            tester.pump();
1553            let (selection, cursor) = tester
1554                .widget::<EditableText, _>(editable_elements(tester)[0], |widget| {
1555                    (widget.selection_color, widget.cursor_color)
1556                });
1557            assert_eq!(selection, Some(selection_color));
1558            assert_eq!(cursor, cursor_color);
1559        });
1560    }
1561
1562    #[test]
1563    fn selectable_text_can_have_custom_selection_color() {
1564        test_widgets(|tester| {
1565            let selection_color = Colors::ORANGE.primary();
1566            let default_selection_color = Colors::RED.primary();
1567            let root = material_home(
1568                tester,
1569                DefaultSelectionStyle::new(
1570                    SelectableText::new("text").selection_color(selection_color),
1571                )
1572                .selection_color(default_selection_color),
1573            );
1574            tester.pump_widget(root);
1575            tester.pump();
1576            let selection = tester
1577                .widget::<EditableText, _>(editable_elements(tester)[0], |w| w.selection_color);
1578            assert_eq!(selection, Some(selection_color));
1579        });
1580    }
1581
1582    #[test]
1583    fn can_switch_between_text_height_behavior() {
1584        test_widgets(|tester| {
1585            let text_height_behavior = TextHeightBehavior {
1586                apply_height_to_first_ascent: false,
1587                apply_height_to_last_descent: false,
1588                ..TextHeightBehavior::default()
1589            };
1590            let root = overlay(tester, SelectableText::new("selectable text"));
1591            tester.pump_widget(root);
1592            let editable = render_editable_at(tester, 0);
1593            assert_eq!(editable.text_height_behavior(&tester.cell.borrow()), None);
1594
1595            let root = overlay(
1596                tester,
1597                SelectableText::new("selectable text").text_height_behavior(text_height_behavior),
1598            );
1599            tester.pump_widget(root);
1600            let editable = render_editable_at(tester, 0);
1601            assert_eq!(
1602                editable.text_height_behavior(&tester.cell.borrow()),
1603                Some(text_height_behavior)
1604            );
1605        });
1606    }
1607
1608    #[test]
1609    fn cursor_blinks_when_show_cursor_is_true() {
1610        test_widgets(|tester| {
1611            let root = overlay(tester, SelectableText::new("some text").show_cursor(true));
1612            tester.pump_widget(root);
1613            let at = center_of_selectable_text(tester);
1614            tester.tap_at(at, 1);
1615
1616            let editable_text = editable_state(tester);
1617            let visible = |tester: &WidgetTester| {
1618                editable_text.cursor_currently_visible(&tester.cell.borrow())
1619            };
1620            let interval = EditableTextState::cursor_blink_interval();
1621
1622            // Check that the cursor visibility toggles after each blink interval.
1623            let initial_show_cursor = visible(tester);
1624            tester.pump_by(interval);
1625            assert_eq!(visible(tester), !initial_show_cursor);
1626            tester.pump_by(interval);
1627            assert_eq!(visible(tester), initial_show_cursor);
1628            tester.pump_by(interval / 10);
1629            assert_eq!(visible(tester), initial_show_cursor);
1630            tester.pump_by(interval);
1631            assert_eq!(visible(tester), !initial_show_cursor);
1632            tester.pump_by(interval);
1633            assert_eq!(visible(tester), initial_show_cursor);
1634        });
1635    }
1636
1637    #[test]
1638    fn caret_position_is_updated_on_tap() {
1639        test_widgets(|tester| {
1640            let root = overlay(tester, SelectableText::new("abc def ghi"));
1641            tester.pump_widget(root);
1642            assert_eq!(selection(tester).base_offset, -1);
1643            assert_eq!(selection(tester).extent_offset, -1);
1644
1645            // Tap to reposition the caret.
1646            let tap_index = 4;
1647            let e_pos = text_offset_to_position(tester, tap_index);
1648            tester.tap_at(e_pos, 1);
1649            tester.pump();
1650
1651            assert_eq!(selection(tester).base_offset, tap_index);
1652            assert_eq!(selection(tester).extent_offset, tap_index);
1653        });
1654    }
1655
1656    #[test]
1657    fn enable_interactive_selection_false_tap() {
1658        test_widgets(|tester| {
1659            let root = overlay(
1660                tester,
1661                SelectableText::new("abc def ghi").enable_interactive_selection(false),
1662            );
1663            tester.pump_widget(root);
1664            assert_eq!(selection(tester).base_offset, -1);
1665            assert_eq!(selection(tester).extent_offset, -1);
1666
1667            // Tap would ordinarily reposition the caret.
1668            let e_pos = text_offset_to_position(tester, 4);
1669            tester.tap_at(e_pos, 1);
1670            tester.pump();
1671
1672            assert_eq!(selection(tester).base_offset, -1);
1673            assert_eq!(selection(tester).extent_offset, -1);
1674        });
1675    }
1676
1677    #[test]
1678    fn enable_interactive_selection_false_long_press() {
1679        test_widgets(|tester| {
1680            let root = overlay(
1681                tester,
1682                SelectableText::new("abc def ghi").enable_interactive_selection(false),
1683            );
1684            tester.pump_widget(root);
1685            assert_eq!(selection(tester).base_offset, -1);
1686            assert_eq!(selection(tester).extent_offset, -1);
1687
1688            // Long press the 'e' to select 'def'.
1689            let e_pos = text_offset_to_position(tester, 5);
1690            let mut gesture = TestPointer::touch(7);
1691            tester.down(&mut gesture, e_pos);
1692            tester.pump_by(Duration::from_secs(2));
1693            tester.up(&gesture);
1694            tester.pump();
1695
1696            assert!(selection(tester).is_collapsed());
1697            assert_eq!(selection(tester).base_offset, -1);
1698            assert_eq!(selection(tester).extent_offset, -1);
1699        });
1700    }
1701
1702    #[test]
1703    fn can_long_press_to_select() {
1704        test_widgets(|tester| {
1705            let root = overlay(tester, SelectableText::new("abc def ghi"));
1706            tester.pump_widget(root);
1707            assert!(selection(tester).is_collapsed());
1708
1709            // Long press the 'e' to select 'def'.
1710            let e_pos = text_offset_to_position(tester, 5);
1711            tester.long_press_at(e_pos, 1);
1712            tester.pump();
1713
1714            // 'def' is selected.
1715            assert_eq!(selection(tester).base_offset, 4);
1716            assert_eq!(selection(tester).extent_offset, 7);
1717
1718            // Tapping elsewhere immediately collapses and moves the cursor.
1719            let at = text_offset_to_position(tester, 9);
1720            tester.tap_at(at, 2);
1721            tester.pump();
1722
1723            assert!(selection(tester).is_collapsed());
1724            assert_eq!(selection(tester).base_offset, 9);
1725        });
1726    }
1727
1728    #[test]
1729    fn mouse_long_press_is_just_like_a_tap() {
1730        test_widgets(|tester| {
1731            let root = overlay(tester, SelectableText::new("abc def ghi"));
1732            tester.pump_widget(root);
1733
1734            // Long press the 'e' using a mouse device.
1735            let e_index = 5;
1736            let e_pos = text_offset_to_position(tester, e_index);
1737            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1738            tester.down(&mut gesture, e_pos);
1739            tester.pump_by(Duration::from_secs(2));
1740            tester.up(&gesture);
1741            tester.pump();
1742
1743            // The cursor is placed just like a regular tap.
1744            assert_eq!(selection(tester).base_offset, e_index);
1745            assert_eq!(selection(tester).extent_offset, e_index);
1746        });
1747    }
1748
1749    #[test]
1750    fn selectable_text_has_adaptive_size() {
1751        test_widgets(|tester| {
1752            let root = overlay(tester, SelectableText::new("s"));
1753            tester.pump_widget(root);
1754            assert_eq!(
1755                selectable_text_size(tester),
1756                waft_embedder::Size::new(17.0, 14.0)
1757            );
1758
1759            let root = overlay(tester, SelectableText::new("very very long"));
1760            tester.pump_widget(root);
1761            assert_eq!(
1762                selectable_text_size(tester),
1763                waft_embedder::Size::new(199.0, 14.0)
1764            );
1765        });
1766    }
1767
1768    #[test]
1769    #[allow(deprecated)]
1770    fn can_scale_with_text_scale_factor() {
1771        test_widgets(|tester| {
1772            let root = overlay(tester, SelectableText::new("selectable text"));
1773            tester.pump_widget(root);
1774            assert_eq!(selectable_text_size(tester).height(), 14.0);
1775
1776            let root = overlay(
1777                tester,
1778                SelectableText::new("selectable text").text_scale_factor(1.9),
1779            );
1780            tester.pump_widget(root);
1781            assert_eq!(selectable_text_size(tester).height(), 27.0);
1782        });
1783    }
1784
1785    #[test]
1786    fn can_switch_between_text_width_basis() {
1787        test_widgets(|tester| {
1788            const TEXT: &str = "I can face roll keyboardkeyboardaszzaaaaszzaaaaszzaaaaszzaaaa";
1789            let root = overlay(
1790                tester,
1791                SelectableText::new(TEXT).text_width_basis(TextWidthBasis::Parent),
1792            );
1793            tester.pump_widget(root);
1794            assert_eq!(
1795                selectable_text_size(tester),
1796                waft_embedder::Size::new(800.0, 28.0)
1797            );
1798
1799            let root = overlay(
1800                tester,
1801                SelectableText::new(TEXT).text_width_basis(TextWidthBasis::LongestLine),
1802            );
1803            tester.pump_widget(root);
1804            assert_eq!(
1805                selectable_text_size(tester),
1806                waft_embedder::Size::new(633.0, 28.0)
1807            );
1808        });
1809    }
1810
1811    #[test]
1812    fn selectable_text_basic() {
1813        test_widgets(|tester| {
1814            let root = overlay(tester, SelectableText::new("selectable"));
1815            tester.pump_widget(root);
1816            tester.pump();
1817            tester.pump_by(Duration::from_millis(200));
1818            assert!(selection(tester).is_collapsed());
1819
1820            let at = center_of_selectable_text(tester);
1821            tester.tap_at(at, 1);
1822            tester.pump();
1823
1824            // Collapse selection should not paint.
1825            assert!(!handles_are_visible(tester));
1826            // Long press on the 't' character of text 'selectable' to show context menu.
1827            let d_pos = text_offset_to_position(tester, 5);
1828            tester.long_press_at(d_pos, 2);
1829            tester.pump();
1830
1831            // Context menu should not have paste and cut.
1832            expect(tester, &find::text("Copy"), finds_one_widget());
1833            expect(tester, &find::text("Paste"), finds_nothing());
1834            expect(tester, &find::text("Cut"), finds_nothing());
1835        });
1836    }
1837
1838    #[test]
1839    #[allow(deprecated)]
1840    fn selectable_text_can_disable_toolbar_options() {
1841        test_widgets(|tester| {
1842            let root = overlay(
1843                tester,
1844                SelectableText::new("a selectable text").toolbar_options(ToolbarOptions {
1845                    select_all: true,
1846                    ..ToolbarOptions::default()
1847                }),
1848            );
1849            tester.pump_widget(root);
1850            let d_pos = text_offset_to_position(tester, 5);
1851            tester.long_press_at(d_pos, 1);
1852            tester.pump();
1853            // Context menu should not have copy.
1854            expect(tester, &find::text("Copy"), finds_nothing());
1855            expect(tester, &find::text("Select all"), finds_one_widget());
1856        });
1857    }
1858
1859    #[test]
1860    fn can_select_text_by_dragging_with_a_mouse() {
1861        test_widgets(|tester| {
1862            let root = material_home(
1863                tester,
1864                SelectableText::new("abc def ghi").drag_start_behavior(DragStartBehavior::Down),
1865            );
1866            tester.pump_widget(root);
1867
1868            let e_pos = text_offset_to_position(tester, 5);
1869            let g_pos = text_offset_to_position(tester, 8);
1870
1871            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
1872            tester.down(&mut gesture, e_pos);
1873            tester.pump();
1874            tester.move_to(&mut gesture, g_pos, true);
1875            tester.pump();
1876            tester.up(&gesture);
1877            tester.pump_and_settle();
1878
1879            assert_eq!(selection(tester).base_offset, 5);
1880            assert_eq!(selection(tester).extent_offset, 8);
1881        });
1882    }
1883
1884    #[test]
1885    fn can_use_selection_toolbar() {
1886        test_widgets(|_tester| {
1887            let (mut tester, clipboard) = tester_with_clipboard(TargetPlatform::Android);
1888            clipboard.set_clipboard_data(Some("Clipboard data".to_owned()));
1889            let test_value = "abc def ghi";
1890            let root = material_home(&mut tester, SelectableText::new(test_value));
1891            tester.pump_widget(root);
1892
1893            // Tap the selection handle to bring up the "paste / select all" menu.
1894            let at = text_offset_to_position(&tester, test_value.find('e').unwrap() as i32);
1895            tester.tap_at(at, 1);
1896            tester.pump();
1897            // Skip past the frame where the opacity is zero.
1898            tester.pump_by(Duration::from_millis(200));
1899            let render_editable = render_editable_at(&tester, 0);
1900            let controller = controller(&tester);
1901            let handle_point = {
1902                let mut app = tester.cell.borrow_mut();
1903                let selection = controller.selection(&app);
1904                let endpoints = render_editable.get_endpoints_for_selection(&mut app, selection);
1905                render_editable
1906                    .as_box()
1907                    .local_to_global(&app, endpoints[0].point, None)
1908            };
1909            // Tapping on the part of the handle's GestureDetector where it overlaps
1910            // with the text itself does not show the menu, so add a small vertical
1911            // offset to tap below the text.
1912            tester.tap_at(handle_point + Offset::new(1.0, 13.0), 2);
1913            tester.pump();
1914            // Skip past the frame where the opacity is zero.
1915            tester.pump_by(Duration::from_millis(200));
1916
1917            // Select all should select all the text.
1918            let select_all = find::text("Select all").evaluate(&tester)[0];
1919            let at = tester.get_rect(select_all).center();
1920            tester.tap_at(at, 3);
1921            tester.pump();
1922            assert_eq!(selection(&tester).base_offset, 0);
1923            assert_eq!(selection(&tester).extent_offset, test_value.len() as i32);
1924
1925            // Copy should reset the selection.
1926            let copy = find::text("Copy").evaluate(&tester)[0];
1927            let at = tester.get_rect(copy).center();
1928            tester.tap_at(at, 4);
1929            tester.pump();
1930            tester.pump_by(Duration::from_millis(200));
1931            assert!(selection(&tester).is_collapsed());
1932        });
1933    }
1934
1935    fn selectable_text_builder(
1936        tester: &mut WidgetTester,
1937        text: &str,
1938        max_lines: Option<i32>,
1939        min_lines: Option<i32>,
1940    ) -> WidgetRef {
1941        let mut selectable_text = SelectableText::new(text)
1942            .style(TextStyle::new().color(Colors::BLACK).font_size(34.0))
1943            .max_lines(max_lines);
1944        if let Some(min_lines) = min_lines {
1945            selectable_text = selectable_text.min_lines(min_lines);
1946        }
1947        overlay(tester, selectable_text)
1948    }
1949
1950    fn selectable_text_size(tester: &WidgetTester) -> waft_embedder::Size {
1951        let element = find::by_type::<SelectableText>().evaluate(tester)[0];
1952        let render = tester.render_box_of(element);
1953        render.size(&tester.cell.borrow())
1954    }
1955
1956    #[test]
1957    fn selectable_height_with_max_line() {
1958        test_widgets(|tester| {
1959            let root = selectable_text_builder(tester, "", Some(1), None);
1960            tester.pump_widget(root);
1961            let empty_input_size = selectable_text_size(tester);
1962
1963            let root = selectable_text_builder(tester, "No wrapping here.", Some(1), None);
1964            tester.pump_widget(root);
1965            assert_eq!(
1966                selectable_text_size(tester).height(),
1967                empty_input_size.height()
1968            );
1969
1970            // Even when entering multiline text, SelectableText doesn't grow. It's a single
1971            // line input.
1972            let root = selectable_text_builder(tester, K_THREE_LINES, Some(1), None);
1973            tester.pump_widget(root);
1974            assert_eq!(
1975                selectable_text_size(tester).height(),
1976                empty_input_size.height()
1977            );
1978
1979            // maxLines: 3 makes the SelectableText 3 lines tall.
1980            let root = selectable_text_builder(tester, "", Some(3), None);
1981            tester.pump_widget(root);
1982            assert!(selectable_text_size(tester).height() > empty_input_size.height());
1983            let three_line_input_size = selectable_text_size(tester);
1984
1985            // Filling with 3 lines of text stays the same size.
1986            let root = selectable_text_builder(tester, K_THREE_LINES, Some(3), None);
1987            tester.pump_widget(root);
1988            assert_eq!(
1989                selectable_text_size(tester).height(),
1990                three_line_input_size.height()
1991            );
1992
1993            // An extra line won't increase the size because we max at 3.
1994            let root = selectable_text_builder(tester, K_MORE_THAN_FOUR_LINES, Some(3), None);
1995            tester.pump_widget(root);
1996            assert_eq!(
1997                selectable_text_size(tester).height(),
1998                three_line_input_size.height()
1999            );
2000
2001            // But now it will... but it will max at four.
2002            let root = selectable_text_builder(tester, K_MORE_THAN_FOUR_LINES, Some(4), None);
2003            tester.pump_widget(root);
2004            assert!(selectable_text_size(tester).height() > three_line_input_size.height());
2005            let four_line_input_size = selectable_text_size(tester);
2006
2007            // Now it won't max out until the end.
2008            let root = selectable_text_builder(tester, "", None, None);
2009            tester.pump_widget(root);
2010            assert_eq!(selectable_text_size(tester), empty_input_size);
2011            let root = selectable_text_builder(tester, K_THREE_LINES, None, None);
2012            tester.pump_widget(root);
2013            assert_eq!(
2014                selectable_text_size(tester).height(),
2015                three_line_input_size.height()
2016            );
2017            let root = selectable_text_builder(tester, K_MORE_THAN_FOUR_LINES, None, None);
2018            tester.pump_widget(root);
2019            assert!(selectable_text_size(tester).height() > four_line_input_size.height());
2020        });
2021    }
2022
2023    #[test]
2024    #[should_panic(expected = "minLines can't be greater than maxLines")]
2025    fn min_lines_cannot_be_greater_than_max_lines() {
2026        let _ = SelectableText::new("abcd")
2027            .max_lines(Some(3))
2028            .min_lines(4)
2029            .into_widget();
2030    }
2031
2032    #[test]
2033    fn selectable_height_with_min_line() {
2034        test_widgets(|tester| {
2035            let root = selectable_text_builder(tester, "", Some(1), None);
2036            tester.pump_widget(root);
2037            let empty_input_size = selectable_text_size(tester);
2038
2039            // Even if the text is a one liner, minimum height of SelectableText will
2040            // determined by minLines.
2041            let root = selectable_text_builder(tester, "No wrapping here.", Some(3), Some(2));
2042            tester.pump_widget(root);
2043            assert_eq!(
2044                selectable_text_size(tester).height(),
2045                empty_input_size.height() * 2.0
2046            );
2047        });
2048    }
2049
2050    #[test]
2051    fn tapping_outside_selectable_text_clears_the_selection() {
2052        test_widgets(|tester| {
2053            let root = material_home(
2054                tester,
2055                Center::new().child(Column::new().children(vec![
2056                    SelectableText::new("first selectable text").into_widget(),
2057                    SelectableText::new("second selectable text").into_widget(),
2058                ])),
2059            );
2060            tester.pump_widget(root);
2061            // Setting the app lifecycle state to AppLifecycleState.resumed to simulate
2062            // an applications default running mode, i.e. the application window is focused.
2063            SchedulerBinding::handle_app_lifecycle_state_changed(
2064                &mut tester.cell.borrow_mut(),
2065                AppLifecycleState::Resumed,
2066            );
2067            tester.pump_and_settle();
2068
2069            // First tap on the first SelectableText sets the cursor.
2070            let at = text_offset_to_position(tester, 5);
2071            tester.tap_at(at, 1);
2072            tester.pump_and_settle();
2073
2074            let controller_a = controller_at(tester, 0);
2075            let controller_b = controller_at(tester, 1);
2076            let read = |tester: &WidgetTester, controller: AnyTextEditingController| {
2077                controller.selection(&tester.cell.borrow())
2078            };
2079            let empty = TextSelection::collapsed(-1, TextAffinity::Downstream);
2080
2081            assert_eq!(
2082                read(tester, controller_a.handle()),
2083                TextSelection::collapsed(5, TextAffinity::Downstream)
2084            );
2085            assert_eq!(read(tester, controller_b.handle()), empty);
2086
2087            // Tapping on the second SelectableText sets the cursor on it, and clears the
2088            // selection from the first SelectableText.
2089            let selectable_text_start = top_left_of_selectable_text(tester, 1);
2090            tester.tap_at(selectable_text_start, 2);
2091            tester.pump_and_settle();
2092            assert_eq!(read(tester, controller_a.handle()), empty);
2093            assert_eq!(
2094                read(tester, controller_b.handle()),
2095                TextSelection::collapsed(0, TextAffinity::Downstream)
2096            );
2097
2098            // Setting the app lifecycle state to AppLifecycleState.inactive to simulate
2099            // a lose of window focus. Selection should remain the same.
2100            SchedulerBinding::handle_app_lifecycle_state_changed(
2101                &mut tester.cell.borrow_mut(),
2102                AppLifecycleState::Inactive,
2103            );
2104            tester.pump_and_settle();
2105            assert_eq!(read(tester, controller_a.handle()), empty);
2106            assert_eq!(
2107                read(tester, controller_b.handle()),
2108                TextSelection::collapsed(0, TextAffinity::Downstream)
2109            );
2110        });
2111    }
2112
2113    #[test]
2114    fn selectable_text_is_skipped_during_focus_traversal() {
2115        test_widgets(|tester| {
2116            let (first_field_focus, last_field_focus) = {
2117                let mut app = tester.cell.borrow_mut();
2118                (FocusNode::new(&mut app), FocusNode::new(&mut app))
2119            };
2120            // Dart's two `TextField`s, which this case only needs to take focus by traversal.
2121            let root = material_home(
2122                tester,
2123                Center::new().child(Column::new().children(vec![
2124                    Focus::new(SizedBox::new().width(10.0).height(10.0))
2125                        .focus_node(first_field_focus.erase())
2126                        .autofocus(true)
2127                        .into_widget(),
2128                    SelectableText::new("some text").into_widget(),
2129                    Focus::new(SizedBox::new().width(10.0).height(10.0))
2130                        .focus_node(last_field_focus.erase())
2131                        .into_widget(),
2132                ])),
2133            );
2134            tester.pump_widget(root);
2135            tester.pump();
2136
2137            assert!(first_field_focus.has_focus(&mut tester.cell.borrow_mut()));
2138            assert!(!last_field_focus.has_focus(&mut tester.cell.borrow_mut()));
2139
2140            first_field_focus
2141                .as_node()
2142                .next_focus(&mut tester.cell.borrow_mut());
2143            tester.pump();
2144
2145            // Expecting focus to skip straight to the second field.
2146            assert!(!first_field_focus.has_focus(&mut tester.cell.borrow_mut()));
2147            assert!(last_field_focus.has_focus(&mut tester.cell.borrow_mut()));
2148        });
2149    }
2150
2151    /// Dart's `setupWidget` of the 'Keyboard Tests' group.
2152    fn setup_keyboard_widget(tester: &mut WidgetTester, text: &str) {
2153        let root = material_home(tester, SelectableText::new(text).max_lines(Some(3)));
2154        tester.pump_widget(root);
2155        let at = center_of_selectable_text(tester);
2156        tester.tap_at(at, 1);
2157        tester.pump_and_settle();
2158    }
2159
2160    fn selection_delta(tester: &WidgetTester) -> i32 {
2161        let selection = selection(tester);
2162        selection.extent_offset - selection.base_offset
2163    }
2164
2165    #[test]
2166    fn keyboard_shift_test_1() {
2167        test_widgets(|tester| {
2168            setup_keyboard_widget(tester, "a big house");
2169
2170            tester.send_key_down_event(
2171                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2172                LogicalKeyboardKey::SHIFT_LEFT,
2173            );
2174            tester.send_key_down_event(
2175                physical_of(LogicalKeyboardKey::ARROW_LEFT),
2176                LogicalKeyboardKey::ARROW_LEFT,
2177            );
2178            assert_eq!(selection_delta(tester), -1);
2179        });
2180    }
2181
2182    #[test]
2183    fn keyboard_shift_test_2() {
2184        test_widgets(|tester| {
2185            setup_keyboard_widget(tester, "abcdefghi");
2186
2187            controller(tester).set_selection(
2188                &mut tester.cell.borrow_mut(),
2189                TextSelection::collapsed(3, TextAffinity::Downstream),
2190            );
2191            tester.pump();
2192
2193            tester.send_key_down_event(
2194                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2195                LogicalKeyboardKey::SHIFT_LEFT,
2196            );
2197            tester.send_key_down_event(
2198                physical_of(LogicalKeyboardKey::ARROW_RIGHT),
2199                LogicalKeyboardKey::ARROW_RIGHT,
2200            );
2201            tester.pump_and_settle();
2202            assert_eq!(selection_delta(tester), 1);
2203        });
2204    }
2205
2206    #[test]
2207    fn keyboard_control_shift_test() {
2208        test_widgets(|tester| {
2209            setup_keyboard_widget(tester, "their big house");
2210
2211            tester.send_key_down_event(
2212                physical_of(LogicalKeyboardKey::CONTROL_LEFT),
2213                LogicalKeyboardKey::CONTROL_LEFT,
2214            );
2215            tester.send_key_down_event(
2216                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2217                LogicalKeyboardKey::SHIFT_LEFT,
2218            );
2219            tester.send_key_down_event(
2220                physical_of(LogicalKeyboardKey::ARROW_LEFT),
2221                LogicalKeyboardKey::ARROW_LEFT,
2222            );
2223            tester.pump_and_settle();
2224
2225            assert_eq!(selection_delta(tester), -5);
2226        });
2227    }
2228
2229    #[test]
2230    fn keyboard_down_and_up_test() {
2231        test_widgets(|tester| {
2232            setup_keyboard_widget(tester, "a big house");
2233
2234            tester.send_key_down_event(
2235                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2236                LogicalKeyboardKey::SHIFT_LEFT,
2237            );
2238            tester.send_key_down_event(
2239                physical_of(LogicalKeyboardKey::ARROW_UP),
2240                LogicalKeyboardKey::ARROW_UP,
2241            );
2242            tester.pump_and_settle();
2243
2244            assert_eq!(selection_delta(tester), -11);
2245
2246            tester.send_key_up_event(
2247                physical_of(LogicalKeyboardKey::ARROW_UP),
2248                LogicalKeyboardKey::ARROW_UP,
2249            );
2250            tester.send_key_up_event(
2251                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2252                LogicalKeyboardKey::SHIFT_LEFT,
2253            );
2254            tester.send_key_down_event(
2255                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2256                LogicalKeyboardKey::SHIFT_LEFT,
2257            );
2258            tester.send_key_down_event(
2259                physical_of(LogicalKeyboardKey::ARROW_DOWN),
2260                LogicalKeyboardKey::ARROW_DOWN,
2261            );
2262            tester.pump_and_settle();
2263
2264            assert_eq!(selection_delta(tester), 0);
2265        });
2266    }
2267
2268    #[test]
2269    fn copy_test() {
2270        test_widgets(|_tester| {
2271            let (mut tester, clipboard) = tester_with_clipboard(TargetPlatform::Android);
2272            let test_value = "a big house\njumped over a mouse";
2273            let root = material_home(
2274                &mut tester,
2275                SelectableText::new(test_value).max_lines(Some(3)),
2276            );
2277            tester.pump_widget(root);
2278            let at = center_of_selectable_text(&tester);
2279            tester.tap_at(at, 1);
2280            tester.pump_and_settle();
2281
2282            controller(&tester).set_selection(
2283                &mut tester.cell.borrow_mut(),
2284                TextSelection::collapsed(0, TextAffinity::Downstream),
2285            );
2286            tester.pump();
2287
2288            // Select the first 5 characters.
2289            tester.send_key_down_event(
2290                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2291                LogicalKeyboardKey::SHIFT_LEFT,
2292            );
2293            for _ in 0..5 {
2294                tester.send_key_event(
2295                    physical_of(LogicalKeyboardKey::ARROW_RIGHT),
2296                    LogicalKeyboardKey::ARROW_RIGHT,
2297                );
2298                tester.pump_and_settle();
2299            }
2300            tester.send_key_up_event(
2301                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2302                LogicalKeyboardKey::SHIFT_LEFT,
2303            );
2304
2305            // Copy them.
2306            tester.send_key_down_event(
2307                physical_of(LogicalKeyboardKey::CONTROL_RIGHT),
2308                LogicalKeyboardKey::CONTROL_RIGHT,
2309            );
2310            tester.send_key_down_event(
2311                physical_of(LogicalKeyboardKey::KEY_C),
2312                LogicalKeyboardKey::KEY_C,
2313            );
2314            tester.send_key_up_event(
2315                physical_of(LogicalKeyboardKey::KEY_C),
2316                LogicalKeyboardKey::KEY_C,
2317            );
2318            tester.send_key_up_event(
2319                physical_of(LogicalKeyboardKey::CONTROL_RIGHT),
2320                LogicalKeyboardKey::CONTROL_RIGHT,
2321            );
2322            tester.pump_and_settle();
2323
2324            assert_eq!(clipboard.clipboard_data().as_deref(), Some("a big"));
2325        });
2326    }
2327
2328    #[test]
2329    fn select_all_test() {
2330        test_widgets(|tester| {
2331            let test_value = "a big house\njumped over a mouse";
2332            let root = material_home(tester, SelectableText::new(test_value).max_lines(Some(3)));
2333            tester.pump_widget(root);
2334            let at = center_of_selectable_text(tester);
2335            tester.tap_at(at, 1);
2336            tester.pump_and_settle();
2337
2338            // Select All.
2339            tester.send_key_down_event(
2340                physical_of(LogicalKeyboardKey::CONTROL_LEFT),
2341                LogicalKeyboardKey::CONTROL_LEFT,
2342            );
2343            tester.send_key_event(
2344                physical_of(LogicalKeyboardKey::KEY_A),
2345                LogicalKeyboardKey::KEY_A,
2346            );
2347            tester.send_key_up_event(
2348                physical_of(LogicalKeyboardKey::CONTROL_LEFT),
2349                LogicalKeyboardKey::CONTROL_LEFT,
2350            );
2351            tester.pump_and_settle();
2352
2353            assert_eq!(selection(tester).base_offset, 0);
2354            assert_eq!(selection(tester).extent_offset, 31);
2355        });
2356    }
2357
2358    #[test]
2359    fn keyboard_selection_should_call_on_selection_changed() {
2360        test_widgets(|tester| {
2361            let new_selection: Rc<RefCell<Option<TextSelection>>> = Rc::new(RefCell::new(None));
2362            let test_value = "a big house\njumped over a mouse";
2363            let recorded = Rc::clone(&new_selection);
2364            let root = material_home(
2365                tester,
2366                SelectableText::new(test_value)
2367                    .max_lines(Some(3))
2368                    .on_selection_changed(move |_app, selection, _cause| {
2369                        assert!(recorded.borrow().is_none());
2370                        *recorded.borrow_mut() = Some(selection);
2371                    }),
2372            );
2373            tester.pump_widget(root);
2374            let at = center_of_selectable_text(tester);
2375            tester.tap_at(at, 1);
2376            tester.pump_and_settle();
2377            let tapped = new_selection.borrow_mut().take().expect("a tap selects");
2378            assert_eq!(tapped.base_offset, 31);
2379            assert_eq!(tapped.extent_offset, 31);
2380
2381            controller(tester).set_selection(
2382                &mut tester.cell.borrow_mut(),
2383                TextSelection::collapsed(0, TextAffinity::Downstream),
2384            );
2385            tester.pump();
2386
2387            // Select the first 5 characters.
2388            tester.send_key_down_event(
2389                physical_of(LogicalKeyboardKey::SHIFT_LEFT),
2390                LogicalKeyboardKey::SHIFT_LEFT,
2391            );
2392            for i in 0..5 {
2393                tester.send_key_event(
2394                    physical_of(LogicalKeyboardKey::ARROW_RIGHT),
2395                    LogicalKeyboardKey::ARROW_RIGHT,
2396                );
2397                tester.pump_and_settle();
2398                let selection = new_selection.borrow_mut().take().expect("a key selects");
2399                assert_eq!(selection.base_offset, 0);
2400                assert_eq!(selection.extent_offset, i + 1);
2401            }
2402        });
2403    }
2404
2405    #[test]
2406    fn on_tap_is_called_upon_tap() {
2407        test_widgets(|tester| {
2408            let tap_count = Rc::new(Cell::new(0));
2409            let counted = Rc::clone(&tap_count);
2410            let root = overlay(
2411                tester,
2412                SelectableText::new("something")
2413                    .on_tap(Listener::new(move |_app| counted.set(counted.get() + 1))),
2414            );
2415            tester.pump_widget(root);
2416
2417            assert_eq!(tap_count.get(), 0);
2418            for pointer in 1..=3 {
2419                let at = center_of_selectable_text(tester);
2420                tester.tap_at(at, pointer);
2421                // Wait a bit so they're all single taps and not double taps.
2422                tester.pump_by(Duration::from_millis(300));
2423            }
2424            assert_eq!(tap_count.get(), 3);
2425        });
2426    }
2427
2428    #[test]
2429    fn selectable_text_style_is_merged_with_default_text_style() {
2430        test_widgets(|tester| {
2431            let default_style = TextStyle::new().color(Colors::BLUE.shade500());
2432            let build_frame = |tester: &mut WidgetTester, style: TextStyle| {
2433                material_home(
2434                    tester,
2435                    DefaultTextStyle::new(
2436                        default_style.clone(),
2437                        Center::new().child(SelectableText::new("something").style(style)),
2438                    ),
2439                )
2440            };
2441            let editable_style = |tester: &WidgetTester| {
2442                tester.widget::<EditableText, _>(editable_elements(tester)[0], |w| w.style.clone())
2443            };
2444
2445            // Empty TextStyle is overridden by theme.
2446            let root = build_frame(tester, TextStyle::new());
2447            tester.pump_widget(root);
2448            let style = editable_style(tester);
2449            assert_eq!(style.color, default_style.color);
2450            assert_eq!(style.background, default_style.background);
2451            assert_eq!(style.shadows, default_style.shadows);
2452            assert_eq!(style.decoration, default_style.decoration);
2453            assert_eq!(style.word_spacing, default_style.word_spacing);
2454
2455            // Properties set on TextStyle override theme.
2456            let set_color = Colors::RED.primary();
2457            let root = build_frame(tester, TextStyle::new().color(set_color));
2458            tester.pump_widget(root);
2459            assert_eq!(editable_style(tester).color, Some(set_color.into()));
2460
2461            // inherit: false causes nothing to be merged in from theme.
2462            let root = build_frame(
2463                tester,
2464                TextStyle::new()
2465                    .font_size(24.0)
2466                    .text_baseline(waft_embedder::TextBaseline::Alphabetic)
2467                    .inherit(false),
2468            );
2469            tester.pump_widget(root);
2470            assert!(editable_style(tester).color.is_none());
2471        });
2472    }
2473
2474    /// Dart's `'Atwater Peel Sherbrooke Bonaventure'` centred on a `Material` in a
2475    /// `MaterialApp`, with `selection_controls` when a case gives them.
2476    fn atwater(
2477        tester: &mut WidgetTester,
2478        selection_controls: Option<Rc<dyn TextSelectionControls>>,
2479    ) -> WidgetRef {
2480        let mut selectable_text = SelectableText::new(ATWATER);
2481        if let Some(selection_controls) = selection_controls {
2482            selectable_text = selectable_text.selection_controls(selection_controls);
2483        }
2484        material_home(tester, Center::new().child(selectable_text))
2485    }
2486
2487    #[test]
2488    fn tap_moves_cursor_to_the_edge_of_the_word_it_tapped() {
2489        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
2490            let root = atwater(tester, None);
2491            tester.pump_widget(root);
2492
2493            let at = selectable_text_start_plus(tester, 50.0);
2494            tester.tap_at(at, 1);
2495            tester.pump();
2496
2497            // We moved the cursor.
2498            assert_eq!(
2499                selection(tester),
2500                TextSelection::collapsed(7, TextAffinity::Upstream)
2501            );
2502
2503            // But don't trigger the toolbar.
2504            expect(tester, &find::by_type::<CupertinoButton>(), finds_nothing());
2505        });
2506    }
2507
2508    #[test]
2509    fn tap_moves_cursor_to_the_position_tapped() {
2510        for platform in ALL_PLATFORMS
2511            .into_iter()
2512            .filter(|platform| *platform != TargetPlatform::IOS)
2513        {
2514            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2515                let root = atwater(tester, None);
2516                tester.pump_widget(root);
2517
2518                let at = selectable_text_start_plus(tester, 50.0);
2519                tester.tap_at(at, 1);
2520                tester.pump();
2521
2522                // We moved the cursor.
2523                assert_eq!(
2524                    selection(tester),
2525                    TextSelection::collapsed(4, TextAffinity::Upstream),
2526                    "{platform:?}"
2527                );
2528
2529                // But don't trigger the toolbar.
2530                expect(tester, &find::by_type::<TextButton>(), finds_nothing());
2531            });
2532        }
2533    }
2534
2535    #[test]
2536    fn two_slow_taps_do_not_trigger_a_word_selection_on_ios() {
2537        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
2538            let root = atwater(tester, None);
2539            tester.pump_widget(root);
2540
2541            let at = selectable_text_start_plus(tester, 50.0);
2542            tester.tap_at(at, 1);
2543            tester.pump_by(Duration::from_millis(500));
2544            tester.tap_at(at, 2);
2545            tester.pump();
2546
2547            // Plain collapsed selection.
2548            assert_eq!(
2549                selection(tester),
2550                TextSelection::collapsed(7, TextAffinity::Upstream)
2551            );
2552
2553            // No toolbar.
2554            expect(tester, &find::by_type::<CupertinoButton>(), finds_nothing());
2555        });
2556    }
2557
2558    #[test]
2559    fn two_slow_taps_do_not_trigger_a_word_selection() {
2560        for platform in ALL_PLATFORMS
2561            .into_iter()
2562            .filter(|platform| *platform != TargetPlatform::IOS)
2563        {
2564            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2565                let root = atwater(tester, None);
2566                tester.pump_widget(root);
2567
2568                let at = selectable_text_start_plus(tester, 50.0);
2569                tester.tap_at(at, 1);
2570                tester.pump_by(Duration::from_millis(500));
2571                tester.tap_at(at, 2);
2572                tester.pump();
2573
2574                // Plain collapsed selection.
2575                assert_eq!(
2576                    selection(tester),
2577                    TextSelection::collapsed(4, TextAffinity::Upstream),
2578                    "{platform:?}"
2579                );
2580
2581                // No toolbar.
2582                expect(tester, &find::by_type::<CupertinoButton>(), finds_nothing());
2583            });
2584        }
2585    }
2586
2587    #[test]
2588    fn double_tap_selects_word_and_first_tap_of_double_tap_moves_cursor() {
2589        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
2590            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2591                let root = atwater(tester, None);
2592                tester.pump_widget(root);
2593
2594                // This tap just puts the cursor somewhere different than where the double
2595                // tap will occur to test that the double tap moves the existing cursor first.
2596                let at = selectable_text_start_plus(tester, 50.0);
2597                tester.tap_at(at, 1);
2598                tester.pump_by(Duration::from_millis(500));
2599
2600                let at = selectable_text_start_plus(tester, 150.0);
2601                tester.tap_at(at, 2);
2602                tester.pump_by(Duration::from_millis(50));
2603
2604                // First tap moved the cursor.
2605                // On iOS, this moves the cursor to the closest word edge.
2606                // On macOS, this moves the cursor to the tapped position.
2607                assert_eq!(
2608                    selection(tester),
2609                    TextSelection::collapsed(
2610                        if platform == TargetPlatform::IOS {
2611                            12
2612                        } else {
2613                            11
2614                        },
2615                        TextAffinity::Upstream
2616                    ),
2617                    "{platform:?}"
2618                );
2619                tester.tap_at(at, 3);
2620                tester.pump();
2621
2622                // Second tap selects the word around the cursor.
2623                assert_eq!(selection(tester), TextSelection::new(8, 12), "{platform:?}");
2624
2625                expect_cupertino_selection_toolbar(tester, platform);
2626            });
2627        }
2628    }
2629
2630    #[test]
2631    fn double_tap_selects_word_and_first_tap_of_double_tap_moves_cursor_and_shows_toolbar_android()
2632    {
2633        test_widgets(|tester| {
2634            let root = atwater(tester, None);
2635            tester.pump_widget(root);
2636
2637            let at = selectable_text_start_plus(tester, 50.0);
2638            tester.tap_at(at, 1);
2639            tester.pump_by(Duration::from_millis(500));
2640
2641            let at = selectable_text_start_plus(tester, 150.0);
2642            tester.tap_at(at, 2);
2643            tester.pump_by(Duration::from_millis(50));
2644
2645            // First tap moved the cursor.
2646            assert_eq!(
2647                selection(tester),
2648                TextSelection::collapsed(11, TextAffinity::Upstream)
2649            );
2650            tester.tap_at(at, 3);
2651            tester.pump();
2652
2653            // Second tap selects the word around the cursor.
2654            assert_eq!(selection(tester), TextSelection::new(8, 12));
2655
2656            expect_material_selection_toolbar(tester, TargetPlatform::Android);
2657        });
2658    }
2659
2660    #[test]
2661    fn double_tap_on_top_of_cursor_also_selects_word_android() {
2662        test_widgets(|tester| {
2663            let root = atwater(tester, None);
2664            tester.pump_widget(root);
2665
2666            // Tap to put the cursor after the "w".
2667            let index = 3;
2668            let at = text_offset_to_position(tester, index);
2669            tester.tap_at(at, 1);
2670            tester.pump_by(Duration::from_millis(500));
2671
2672            assert_eq!(
2673                selection(tester),
2674                TextSelection::collapsed(index, TextAffinity::Downstream)
2675            );
2676
2677            // Double tap on the same location.
2678            tester.tap_at(at, 2);
2679            tester.pump_by(Duration::from_millis(50));
2680
2681            // First tap doesn't change the selection.
2682            assert_eq!(
2683                selection(tester),
2684                TextSelection::collapsed(index, TextAffinity::Downstream)
2685            );
2686
2687            // Second tap selects the word around the cursor.
2688            tester.tap_at(at, 3);
2689            tester.pump();
2690            assert_eq!(selection(tester), TextSelection::new(0, 7));
2691
2692            expect_material_selection_toolbar(tester, TargetPlatform::Android);
2693        });
2694    }
2695
2696    #[test]
2697    fn long_press_selects_word_and_shows_toolbar_ios() {
2698        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
2699            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2700                let root = atwater(tester, None);
2701                tester.pump_widget(root);
2702
2703                let at = selectable_text_start_plus(tester, 50.0);
2704                tester.long_press_at(at, 1);
2705                tester.pump();
2706
2707                // The long pressed word is selected.
2708                assert_eq!(selection(tester), TextSelection::new(0, 7), "{platform:?}");
2709
2710                expect_cupertino_selection_toolbar(tester, platform);
2711            });
2712        }
2713    }
2714
2715    #[test]
2716    fn long_press_selects_word_and_shows_toolbar_android() {
2717        test_widgets(|tester| {
2718            let root = atwater(tester, None);
2719            tester.pump_widget(root);
2720
2721            let at = selectable_text_start_plus(tester, 50.0);
2722            tester.long_press_at(at, 1);
2723            tester.pump();
2724
2725            assert_eq!(selection(tester), TextSelection::new(0, 7));
2726
2727            expect_material_selection_toolbar(tester, TargetPlatform::Android);
2728        });
2729    }
2730
2731    #[test]
2732    fn long_press_selects_word_and_shows_custom_toolbar_cupertino() {
2733        for platform in ALL_PLATFORMS {
2734            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2735                let root = atwater(tester, Some(cupertino_text_selection_controls()));
2736                tester.pump_widget(root);
2737
2738                let at = selectable_text_start_plus(tester, 50.0);
2739                tester.long_press_at(at, 1);
2740                tester.pump();
2741
2742                // The long pressed word is selected.
2743                assert_eq!(selection(tester), TextSelection::new(0, 7), "{platform:?}");
2744
2745                // Toolbar shows one button (copy).
2746                expect(
2747                    tester,
2748                    &find::by_type::<CupertinoButton>(),
2749                    finds_one_widget(),
2750                );
2751                expect(tester, &find::text("Copy"), finds_one_widget());
2752            });
2753        }
2754    }
2755
2756    #[test]
2757    fn long_press_selects_word_and_shows_custom_toolbar_material() {
2758        for platform in ALL_PLATFORMS {
2759            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2760                let root = atwater(tester, Some(material_text_selection_controls()));
2761                tester.pump_widget(root);
2762
2763                let at = selectable_text_start_plus(tester, 50.0);
2764                tester.long_press_at(at, 1);
2765                tester.pump();
2766
2767                assert_eq!(selection(tester), TextSelection::new(0, 7), "{platform:?}");
2768
2769                // Collapsed toolbar shows 2 buttons: copy, select all
2770                assert_eq!(
2771                    find::by_type::<TextButton>().evaluate(tester).len(),
2772                    2,
2773                    "{platform:?}"
2774                );
2775                expect(tester, &find::text("Copy"), finds_one_widget());
2776                expect(tester, &find::text("Select all"), finds_one_widget());
2777            });
2778        }
2779    }
2780
2781    #[test]
2782    fn text_selection_controls_is_passed_to_editable_text() {
2783        test_widgets(|tester| {
2784            let controls = material_text_selection_controls();
2785            let root = atwater(tester, Some(Rc::clone(&controls)));
2786            tester.pump_widget(root);
2787
2788            let passed = tester.widget::<EditableText, _>(editable_elements(tester)[0], |w| {
2789                w.selection_controls.clone()
2790            });
2791            assert!(passed.is_some_and(|passed| Rc::ptr_eq(&passed, &controls)));
2792        });
2793    }
2794
2795    fn abc_def_ghi(tester: &mut WidgetTester) -> WidgetRef {
2796        material_home(tester, SelectableText::new("abc def ghi"))
2797    }
2798
2799    #[test]
2800    fn long_press_shows_handles_and_toolbar() {
2801        test_widgets(|tester| {
2802            let root = abc_def_ghi(tester);
2803            tester.pump_widget(root);
2804
2805            // Long press at 'e' in 'def'.
2806            let e_pos = text_offset_to_position(tester, 5);
2807            tester.long_press_at(e_pos, 1);
2808            tester.pump_and_settle();
2809
2810            assert!(handles_are_visible(tester));
2811            assert!(toolbar_is_visible(tester));
2812        });
2813    }
2814
2815    #[test]
2816    fn double_tap_shows_handles_and_toolbar() {
2817        test_widgets(|tester| {
2818            let root = abc_def_ghi(tester);
2819            tester.pump_widget(root);
2820
2821            // Double tap at 'e' in 'def'.
2822            let e_pos = text_offset_to_position(tester, 5);
2823            tester.tap_at(e_pos, 1);
2824            tester.pump_by(Duration::from_millis(50));
2825            tester.tap_at(e_pos, 2);
2826            tester.pump();
2827
2828            assert!(handles_are_visible(tester));
2829            assert!(toolbar_is_visible(tester));
2830        });
2831    }
2832
2833    #[test]
2834    fn mouse_tap_does_not_show_handles_nor_toolbar() {
2835        test_widgets(|tester| {
2836            let root = abc_def_ghi(tester);
2837            tester.pump_widget(root);
2838
2839            let e_pos = text_offset_to_position(tester, 5);
2840            let mut gesture = TestPointer::mouse(7, waft_gestures::K_PRIMARY_BUTTON);
2841            tester.down(&mut gesture, e_pos);
2842            tester.pump();
2843            tester.up(&gesture);
2844            tester.pump();
2845
2846            assert!(!toolbar_is_visible(tester));
2847            assert!(!handles_are_visible(tester));
2848        });
2849    }
2850
2851    #[test]
2852    fn mouse_long_press_does_not_show_handles_nor_toolbar() {
2853        test_widgets(|tester| {
2854            let root = abc_def_ghi(tester);
2855            tester.pump_widget(root);
2856
2857            let e_pos = text_offset_to_position(tester, 5);
2858            let mut gesture = TestPointer::mouse(7, waft_gestures::K_PRIMARY_BUTTON);
2859            tester.down(&mut gesture, e_pos);
2860            tester.pump_by(Duration::from_secs(2));
2861            tester.up(&gesture);
2862            tester.pump();
2863
2864            assert!(!toolbar_is_visible(tester));
2865            assert!(!handles_are_visible(tester));
2866        });
2867    }
2868
2869    #[test]
2870    fn mouse_double_tap_does_not_show_handles_nor_toolbar() {
2871        test_widgets(|tester| {
2872            let root = abc_def_ghi(tester);
2873            tester.pump_widget(root);
2874
2875            // Double tap to trigger the selectable text.
2876            let at = center_of_selectable_text(tester);
2877            let mut gesture = TestPointer::mouse(7, waft_gestures::K_PRIMARY_BUTTON);
2878            tester.down(&mut gesture, at);
2879            tester.pump_by(Duration::from_millis(50));
2880            tester.up(&gesture);
2881            tester.pump();
2882            tester.send(&gesture, waft_embedder::PointerChange::Down);
2883            tester.pump();
2884            tester.up(&gesture);
2885            tester.pump();
2886
2887            assert!(!toolbar_is_visible(tester));
2888            assert!(!handles_are_visible(tester));
2889        });
2890    }
2891
2892    #[test]
2893    fn on_selection_changed_is_called_when_selection_changes() {
2894        test_widgets(|tester| {
2895            let count = Rc::new(Cell::new(0));
2896            let counted = Rc::clone(&count);
2897            let root = material_home(
2898                tester,
2899                SelectableText::new("abc def ghi").on_selection_changed(
2900                    move |_app, _selection, _cause| counted.set(counted.get() + 1),
2901                ),
2902            );
2903            tester.pump_widget(root);
2904
2905            // Long press to select 'abc'.
2906            let a_location = text_offset_to_position(tester, 1);
2907            tester.long_press_at(a_location, 1);
2908            tester.pump();
2909            assert_eq!(count.get(), 1);
2910            // Long press to select 'def'.
2911            let at = text_offset_to_position(tester, 5);
2912            tester.long_press_at(at, 2);
2913            tester.pump();
2914            assert_eq!(count.get(), 2);
2915            // Tap on 'Select all' option to select the whole text.
2916            let select_all = find::text("Select all").evaluate(tester)[0];
2917            let at = tester.get_rect(select_all).center();
2918            tester.tap_at(at, 3);
2919            assert_eq!(count.get(), 3);
2920        });
2921    }
2922
2923    #[test]
2924    fn selectable_text_rich_span_style_is_merged_with_default_text_style() {
2925        test_widgets(|tester| {
2926            let text_style = TextStyle::new()
2927                .color(Color::new(0xff00ff00))
2928                .font_size(12.0);
2929            let theme = ThemeData::builder()
2930                .use_material3(false)
2931                .build(&tester.cell.borrow());
2932            let root = material_app(
2933                theme,
2934                SelectableText::rich(TextSpan::new().text("Abcd").style(text_style.clone()))
2935                    .into_widget(),
2936            );
2937            tester.pump_widget(root);
2938
2939            let font_size = tester
2940                .widget::<EditableText, _>(editable_elements(tester)[0], |w| w.style.font_size);
2941            assert_eq!(font_size, text_style.font_size);
2942        });
2943    }
2944
2945    #[test]
2946    fn a_second_tap_at_the_same_place_does_not_call_on_selection_changed() {
2947        test_widgets(|tester| {
2948            let selection_seen: Rc<RefCell<Option<TextSelection>>> = Rc::new(RefCell::new(None));
2949            let count = Rc::new(Cell::new(0));
2950            let (recorded, counted) = (Rc::clone(&selection_seen), Rc::clone(&count));
2951            let theme = ThemeData::builder()
2952                .use_material3(false)
2953                .build(&tester.cell.borrow());
2954            let root = material_app(
2955                theme,
2956                SelectableText::new("I love Flutter!")
2957                    .on_selection_changed(move |_app, selection, _cause| {
2958                        *recorded.borrow_mut() = Some(selection);
2959                        counted.set(counted.get() + 1);
2960                    })
2961                    .into_widget(),
2962            );
2963            tester.pump_widget(root);
2964
2965            assert!(selection_seen.borrow().is_none());
2966            assert_eq!(count.get(), 0);
2967
2968            // Tap to put the cursor before the "F".
2969            let index = 7;
2970            let at = text_offset_to_position(tester, index);
2971            tester.tap_at(at, 1);
2972            tester.pump_by(Duration::from_millis(500));
2973            assert_eq!(
2974                *selection_seen.borrow(),
2975                Some(TextSelection::collapsed(index, TextAffinity::Downstream))
2976            );
2977            // The `onSelectionChanged` will be triggered one time.
2978            assert_eq!(count.get(), 1);
2979
2980            // Tap on the same location again.
2981            tester.tap_at(at, 2);
2982            tester.pump_by(Duration::from_millis(50));
2983            assert_eq!(
2984                *selection_seen.borrow(),
2985                Some(TextSelection::collapsed(index, TextAffinity::Downstream))
2986            );
2987            // The `onSelectionChanged` will not be triggered.
2988            assert_eq!(count.get(), 1);
2989        });
2990    }
2991
2992    #[test]
2993    fn changing_the_data_gives_the_editable_text_a_new_controller() {
2994        test_widgets(|tester| {
2995            let root = abc_def_ghi(tester);
2996            tester.pump_widget(root);
2997            let first = controller(tester);
2998            assert_eq!(first.text_value(&tester.cell.borrow()), "abc def ghi");
2999
3000            let root = material_home(tester, SelectableText::new("jkl"));
3001            tester.pump_widget(root);
3002            let second = controller(tester);
3003            assert!(first != second);
3004            assert_eq!(second.text_value(&tester.cell.borrow()), "jkl");
3005
3006            let root = material_home(tester, SelectableText::new("jkl"));
3007            tester.pump_widget(root);
3008            assert!(controller(tester) == second);
3009        });
3010    }
3011
3012    #[test]
3013    fn the_editable_text_is_read_only_and_does_not_force_a_line() {
3014        test_widgets(|tester| {
3015            let root = abc_def_ghi(tester);
3016            tester.pump_widget(root);
3017            let (read_only, force_line, max_lines) = tester
3018                .widget::<EditableText, _>(editable_elements(tester)[0], |w| {
3019                    (w.read_only, w.force_line, w.max_lines)
3020                });
3021            assert!(read_only);
3022            assert!(!force_line);
3023            assert_eq!(max_lines, None);
3024        });
3025    }
3026
3027    #[test]
3028    fn no_text_keyboard_when_widget_is_focused() {
3029        test_widgets(|tester| {
3030            let root = overlay(tester, SelectableText::new("selectable text"));
3031            tester.pump_widget(root);
3032            tester.tap(find::by_type::<SelectableText>());
3033            tester.cell.checkpoint();
3034            assert!(!tester.test_text_input().has_any_clients());
3035        });
3036    }
3037
3038    #[test]
3039    fn scroll_behavior_can_be_overridden() {
3040        test_widgets(|tester| {
3041            let root = material_home(
3042                tester,
3043                SelectableText::new(K_MORE_THAN_FOUR_LINES)
3044                    .drag_start_behavior(DragStartBehavior::Down)
3045                    .style(TextStyle::new().color(Colors::BLACK).font_size(34.0))
3046                    .max_lines(Some(2)),
3047            );
3048            tester.pump_widget(root);
3049            let editable_behavior = tester
3050                .widget::<EditableText, _>(find::by_type::<EditableText>(), |widget| {
3051                    widget.scroll_behavior.clone()
3052                });
3053            assert!(editable_behavior.is_none());
3054            let scroll_behavior = tester.widget::<waft_widgets::Scrollable, _>(
3055                find::by_type::<waft_widgets::Scrollable>(),
3056                |widget| widget.scroll_behavior.clone(),
3057            );
3058            assert!(scroll_behavior.is_some());
3059
3060            let behavior =
3061                ScrollBehaviorRef::new(ScrollBehaviorRef::plain().copy_with().scrollbars(false));
3062            let root = material_home(
3063                tester,
3064                SelectableText::new(K_MORE_THAN_FOUR_LINES)
3065                    .drag_start_behavior(DragStartBehavior::Down)
3066                    .style(TextStyle::new().color(Colors::BLACK).font_size(34.0))
3067                    .max_lines(Some(2))
3068                    .scroll_behavior(behavior.clone()),
3069            );
3070            tester.pump_widget(root);
3071            let editable_behavior = tester
3072                .widget::<EditableText, _>(find::by_type::<EditableText>(), |widget| {
3073                    widget.scroll_behavior.clone()
3074                });
3075            assert_eq!(editable_behavior, Some(behavior.clone()));
3076            let scroll_behavior = tester
3077                .widget::<waft_widgets::Scrollable, _>(
3078                    find::by_type::<waft_widgets::Scrollable>(),
3079                    |widget| widget.scroll_behavior.clone(),
3080                )
3081                .expect("the scrollable has a behavior");
3082            assert_eq!(scroll_behavior, behavior);
3083        });
3084    }
3085
3086    #[test]
3087    fn caret_works_when_max_lines_is_null() {
3088        test_widgets(|tester| {
3089            let root = overlay(tester, SelectableText::new("x"));
3090            tester.pump_widget(root);
3091            assert_eq!(selection(tester).base_offset, -1);
3092
3093            tester.tap_at(text_offset_to_position(tester, 0), 1);
3094            tester.pump();
3095            tester.pump_by(Duration::from_millis(200));
3096            assert_eq!(selection(tester).base_offset, 0);
3097        });
3098    }
3099
3100    #[test]
3101    fn double_tap_hold_selects_word() {
3102        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
3103            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3104                let root = material_home(tester, Center::new().child(SelectableText::new(ATWATER)));
3105                tester.pump_widget(root);
3106                let start = top_left_of_selectable_text(tester, 0);
3107                tester.tap_at(start + Offset::new(150.0, 5.0), 1);
3108                tester.pump_by(Duration::from_millis(50));
3109
3110                let mut gesture = TestPointer::touch(2);
3111                tester.down(&mut gesture, start + Offset::new(150.0, 5.0));
3112                tester.pump_by(Duration::from_millis(500));
3113                assert_eq!(selection(tester), TextSelection::new(8, 12));
3114                expect_cupertino_selection_toolbar(tester, platform);
3115
3116                tester.up(&gesture);
3117                tester.pump();
3118                assert_eq!(selection(tester), TextSelection::new(8, 12));
3119                expect_cupertino_selection_toolbar(tester, platform);
3120            });
3121        }
3122    }
3123
3124    #[test]
3125    fn tap_after_a_double_tap_select_is_not_affected_ios() {
3126        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
3127            let root = material_home(tester, Center::new().child(SelectableText::new(ATWATER)));
3128            tester.pump_widget(root);
3129            let start = top_left_of_selectable_text(tester, 0);
3130
3131            tester.tap_at(start + Offset::new(150.0, 5.0), 1);
3132            tester.pump_by(Duration::from_millis(50));
3133            assert_eq!(
3134                selection(tester),
3135                TextSelection::collapsed(12, TextAffinity::Upstream)
3136            );
3137            tester.tap_at(start + Offset::new(150.0, 5.0), 2);
3138            tester.pump_by(Duration::from_millis(500));
3139            tester.tap_at(start + Offset::new(100.0, 5.0), 3);
3140            tester.pump();
3141            assert_eq!(
3142                selection(tester),
3143                TextSelection::collapsed(7, TextAffinity::Downstream)
3144            );
3145            assert!(
3146                find::by_type::<CupertinoButton>()
3147                    .evaluate(tester)
3148                    .is_empty()
3149            );
3150        });
3151    }
3152
3153    #[test]
3154    fn tap_after_a_double_tap_select_is_not_affected_macos() {
3155        test_widgets_variant(
3156            TargetPlatformVariant::only(TargetPlatform::MacOS),
3157            |tester| {
3158                let root = material_home(tester, Center::new().child(SelectableText::new(ATWATER)));
3159                tester.pump_widget(root);
3160                let start = top_left_of_selectable_text(tester, 0);
3161
3162                tester.tap_at(start + Offset::new(150.0, 5.0), 1);
3163                tester.pump_by(Duration::from_millis(50));
3164                assert_eq!(
3165                    selection(tester),
3166                    TextSelection::collapsed(11, TextAffinity::Upstream)
3167                );
3168                tester.tap_at(start + Offset::new(150.0, 5.0), 2);
3169                tester.pump_by(Duration::from_millis(500));
3170                tester.tap_at(start + Offset::new(100.0, 5.0), 3);
3171                tester.pump();
3172                assert_eq!(
3173                    selection(tester),
3174                    TextSelection::collapsed(7, TextAffinity::Downstream)
3175                );
3176                assert!(
3177                    find::by_type::<CupertinoButton>()
3178                        .evaluate(tester)
3179                        .is_empty()
3180                );
3181            },
3182        );
3183    }
3184
3185    #[test]
3186    fn long_press_tap_cannot_initiate_a_double_tap_on_macos() {
3187        test_widgets_variant(
3188            TargetPlatformVariant::only(TargetPlatform::MacOS),
3189            |tester| {
3190                let root = material_home(tester, Center::new().child(SelectableText::new(ATWATER)));
3191                tester.pump_widget(root);
3192                let start = top_left_of_selectable_text(tester, 0);
3193
3194                tester.long_press_at(start + Offset::new(50.0, 5.0), 1);
3195                tester.pump_by(Duration::from_millis(50));
3196                editable_state(tester).hide_toolbar(&mut tester.cell.borrow_mut(), false);
3197                tester.pump_and_settle();
3198
3199                tester.tap_at(start + Offset::new(50.0, 5.0), 2);
3200                tester.pump();
3201                assert_eq!(
3202                    selection(tester),
3203                    TextSelection::collapsed(4, TextAffinity::Upstream)
3204                );
3205                assert!(
3206                    find::by_type::<CupertinoButton>()
3207                        .evaluate(tester)
3208                        .is_empty()
3209                );
3210            },
3211        );
3212    }
3213
3214    #[test]
3215    fn long_press_tap_cannot_initiate_a_double_tap_on_ios() {
3216        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
3217            let root = material_home(tester, Center::new().child(SelectableText::new(ATWATER)));
3218            tester.pump_widget(root);
3219            let start = top_left_of_selectable_text(tester, 0);
3220
3221            tester.long_press_at(start + Offset::new(50.0, 5.0), 1);
3222            tester.pump_by(Duration::from_millis(50));
3223            editable_state(tester).hide_toolbar(&mut tester.cell.borrow_mut(), false);
3224            tester.pump_and_settle();
3225
3226            tester.tap_at(start + Offset::new(50.0, 5.0), 2);
3227            tester.pump();
3228            assert_eq!(selection(tester), TextSelection::new(0, 7));
3229            expect(
3230                tester,
3231                &find::by_type::<CupertinoButton>(),
3232                finds_n_widgets(4),
3233            );
3234        });
3235    }
3236
3237    #[test]
3238    fn selectable_text_changes_mouse_cursor_when_hovered() {
3239        test_widgets(|tester| {
3240            let root = material_home(tester, Center::new().child(SelectableText::new("test")));
3241            tester.pump_widget(root);
3242            let at = tester.get_center(find::by_type::<EditableText>());
3243            let mut pointer = TestPointer::mouse(1, 0);
3244            tester.add_pointer(&mut pointer, at);
3245            tester.pump();
3246            tester.move_to(&mut pointer, at, false);
3247            tester.pump();
3248            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
3249        });
3250    }
3251
3252    #[test]
3253    fn the_handles_show_after_pressing_select_all() {
3254        for platform in [TargetPlatform::Android, TargetPlatform::Fuchsia] {
3255            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3256                let root = material_home(tester, SelectableText::new("abc def ghi"));
3257                tester.pump_widget(root);
3258                let at = text_offset_to_position(tester, 5);
3259                tester.long_press_at(at, 1);
3260                tester.pump_and_settle();
3261                expect(tester, &find::text("Select all"), finds_one_widget());
3262                expect(tester, &find::text("Copy"), finds_one_widget());
3263                expect(tester, &find::text("Paste"), finds_nothing());
3264                expect(tester, &find::text("Cut"), finds_nothing());
3265                assert!(handles_are_visible(tester));
3266                assert!(toolbar_is_visible(tester));
3267
3268                tester.tap(find::text("Select all"));
3269                tester.pump();
3270                expect(tester, &find::text("Copy"), finds_one_widget());
3271                expect(tester, &find::text("Select all"), finds_nothing());
3272                expect(tester, &find::text("Paste"), finds_nothing());
3273                expect(tester, &find::text("Cut"), finds_nothing());
3274                assert!(handles_are_visible(tester));
3275            });
3276        }
3277    }
3278
3279    #[test]
3280    fn the_select_all_calls_on_selection_changed() {
3281        for platform in [TargetPlatform::Android, TargetPlatform::Fuchsia] {
3282            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3283                let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3284                let recorded = Rc::clone(&seen);
3285                let root = material_home(
3286                    tester,
3287                    SelectableText::new("abc def ghi").on_selection_changed(
3288                        move |_app, selection, _cause| {
3289                            assert!(recorded.borrow().is_none());
3290                            *recorded.borrow_mut() = Some(selection);
3291                        },
3292                    ),
3293                );
3294                tester.pump_widget(root);
3295                let at = text_offset_to_position(tester, 5);
3296                tester.long_press_at(at, 1);
3297                tester.pump_and_settle();
3298                let selection = seen.borrow_mut().take().expect("the long press selects");
3299                assert_eq!(selection, TextSelection::new(4, 7));
3300
3301                tester.tap(find::text("Select all"));
3302                tester.pump();
3303                let selection = seen.borrow_mut().take().expect("select all selects");
3304                assert_eq!(selection, TextSelection::new(0, 11));
3305            });
3306        }
3307    }
3308
3309    #[test]
3310    fn selectable_text_does_not_crash_at_zero_area() {
3311        test_widgets(|tester| {
3312            let root = material_app(
3313                ThemeData::new(&tester.cell.borrow()),
3314                Center::new()
3315                    .child(SizedBox::shrink().child(SelectableText::new("XYZ")))
3316                    .into_widget(),
3317            );
3318            tester.pump_widget(root);
3319            assert_eq!(
3320                tester.get_size(find::by_type::<SelectableText>()),
3321                Size::ZERO
3322            );
3323
3324            let state = editable_state(tester);
3325            state.update_editing_value(
3326                &mut tester.cell.borrow_mut(),
3327                TextEditingValue::new()
3328                    .text("XYZ")
3329                    .selection(TextSelection::new(0, 3)),
3330            );
3331            tester.pump();
3332        });
3333    }
3334
3335    /// The global endpoints of `selection`, as Dart's `globalize` gives them.
3336    fn global_endpoints(tester: &WidgetTester, selection: TextSelection) -> Vec<Offset> {
3337        let render = render_editable_at(tester, 0);
3338        let mut app = tester.cell.borrow_mut();
3339        render
3340            .get_endpoints_for_selection(&mut app, selection)
3341            .into_iter()
3342            .map(|endpoint| render.as_box().local_to_global(&app, endpoint.point, None))
3343            .collect()
3344    }
3345
3346    #[test]
3347    fn can_drag_handles_to_change_selection() {
3348        test_widgets(|tester| {
3349            let root = material_home(
3350                tester,
3351                SelectableText::new("abc def ghi").drag_start_behavior(DragStartBehavior::Down),
3352            );
3353            tester.pump_widget(root);
3354            let at = text_offset_to_position(tester, 5);
3355            tester.long_press_at(at, 7);
3356            tester.pump();
3357            tester.pump_by(Duration::from_millis(200));
3358            assert_eq!(selection(tester), TextSelection::new(4, 7));
3359
3360            let endpoints = global_endpoints(tester, TextSelection::new(4, 7));
3361            assert_eq!(endpoints.len(), 2);
3362            let mut gesture = TestPointer::touch(7);
3363            tester.down(&mut gesture, endpoints[1] + Offset::new(1.0, 1.0));
3364            tester.pump();
3365            tester.move_to(&mut gesture, text_offset_to_position(tester, 11), true);
3366            tester.pump();
3367            tester.up(&gesture);
3368            tester.pump();
3369            assert_eq!(selection(tester), TextSelection::new(4, 11));
3370
3371            tester.down(&mut gesture, endpoints[0] + Offset::new(-1.0, 1.0));
3372            tester.pump();
3373            tester.move_to(&mut gesture, text_offset_to_position(tester, 0), true);
3374            tester.pump();
3375            tester.up(&gesture);
3376            tester.pump();
3377            assert_eq!(selection(tester), TextSelection::new(0, 11));
3378        });
3379    }
3380
3381    #[test]
3382    fn dragging_handles_calls_on_selection_changed() {
3383        test_widgets(|tester| {
3384            let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3385            let recorded = Rc::clone(&seen);
3386            let root = material_home(
3387                tester,
3388                SelectableText::new("abc def ghi")
3389                    .drag_start_behavior(DragStartBehavior::Down)
3390                    .on_selection_changed(move |_app, selection, _cause| {
3391                        assert!(recorded.borrow().is_none());
3392                        *recorded.borrow_mut() = Some(selection);
3393                    }),
3394            );
3395            tester.pump_widget(root);
3396            let at = text_offset_to_position(tester, 5);
3397            tester.long_press_at(at, 7);
3398            tester.pump();
3399            tester.pump_by(Duration::from_millis(200));
3400            let first = seen.borrow_mut().take().expect("the long press selects");
3401            assert_eq!(first, TextSelection::new(4, 7));
3402
3403            let endpoints = global_endpoints(tester, first);
3404            let mut gesture = TestPointer::touch(7);
3405            tester.down(&mut gesture, endpoints[1] + Offset::new(1.0, 1.0));
3406            tester.pump();
3407            tester.move_to(&mut gesture, text_offset_to_position(tester, 9), true);
3408            tester.pump();
3409            tester.up(&gesture);
3410            tester.pump();
3411            let dragged = seen.borrow_mut().take().expect("the handle selects");
3412            assert_eq!(dragged, TextSelection::new(4, 9));
3413        });
3414    }
3415
3416    #[test]
3417    fn cannot_drag_one_handle_past_the_other() {
3418        test_widgets(|tester| {
3419            let root = material_home(
3420                tester,
3421                SelectableText::new("abc def ghi").drag_start_behavior(DragStartBehavior::Down),
3422            );
3423            tester.pump_widget(root);
3424            let at = text_offset_to_position(tester, 5);
3425            tester.long_press_at(at, 7);
3426            tester.pump();
3427            tester.pump_by(Duration::from_millis(200));
3428            assert_eq!(selection(tester), TextSelection::new(4, 7));
3429
3430            let endpoints = global_endpoints(tester, TextSelection::new(4, 7));
3431            let mut gesture = TestPointer::touch(7);
3432            tester.down(&mut gesture, endpoints[1] + Offset::new(1.0, 1.0));
3433            tester.pump();
3434            tester.move_to(&mut gesture, text_offset_to_position(tester, 5), true);
3435            tester.pump();
3436            assert_eq!(selection(tester), TextSelection::new(4, 5));
3437
3438            tester.move_to(&mut gesture, text_offset_to_position(tester, 2), true);
3439            tester.pump();
3440            tester.up(&gesture);
3441            tester.pump();
3442            assert_eq!(selection(tester), TextSelection::new(4, 5));
3443        });
3444    }
3445
3446    #[test]
3447    fn can_drag_handles_to_change_selection_in_multiline() {
3448        test_widgets(|tester| {
3449            let root = material_home(
3450                tester,
3451                SelectableText::new(K_THREE_LINES)
3452                    .style(TextStyle::new().color(Colors::BLACK).font_size(34.0))
3453                    .max_lines(Some(3))
3454                    .drag_start_behavior(DragStartBehavior::Down),
3455            );
3456            tester.pump_widget(root);
3457            let at =
3458                text_offset_to_position(tester, K_THREE_LINES.find("until").unwrap() as i32 + 1);
3459            tester.long_press_at(at, 7);
3460            tester.pump();
3461            tester.pump_by(Duration::from_millis(200));
3462            assert_eq!(selection(tester), TextSelection::new(39, 44));
3463
3464            let endpoints = global_endpoints(tester, TextSelection::new(39, 44));
3465            assert_eq!(endpoints.len(), 2);
3466            let mut gesture = TestPointer::touch(7);
3467            tester.down(&mut gesture, endpoints[1] + Offset::new(1.0, 1.0));
3468            tester.pump();
3469            tester.move_to(
3470                &mut gesture,
3471                text_offset_to_position(tester, K_THREE_LINES.find("Third").unwrap() as i32 + 5)
3472                    + Offset::new(0.0, 3.0),
3473                true,
3474            );
3475            tester.pump();
3476            tester.up(&gesture);
3477            tester.pump();
3478            assert_eq!(selection(tester), TextSelection::new(39, 50));
3479
3480            tester.down(&mut gesture, endpoints[0] + Offset::new(-1.0, 1.0));
3481            tester.pump();
3482            tester.move_to(
3483                &mut gesture,
3484                text_offset_to_position(tester, K_THREE_LINES.find("First").unwrap() as i32 + 5),
3485                true,
3486            );
3487            tester.pump();
3488            tester.up(&gesture);
3489            tester.pump();
3490            assert_eq!(selection(tester).base_offset, 5);
3491            assert_eq!(selection(tester).extent_offset, 50);
3492        });
3493    }
3494
3495    #[test]
3496    fn continuous_dragging_does_not_cause_flickering() {
3497        test_widgets(|tester| {
3498            let root = material_home(
3499                tester,
3500                SelectableText::new("abc def ghi")
3501                    .drag_start_behavior(DragStartBehavior::Down)
3502                    .style(TextStyle::new().font_size(10.0)),
3503            );
3504            tester.pump_widget(root);
3505            let changed = Rc::new(Cell::new(0));
3506            let count = Rc::clone(&changed);
3507            controller(tester).add_listener(
3508                &mut tester.cell.borrow_mut(),
3509                Listener::new(move |_app| count.set(count.get() + 1)),
3510            );
3511
3512            let c = text_offset_to_position(tester, 2);
3513            let g = text_offset_to_position(tester, 8);
3514            let h = text_offset_to_position(tester, 9);
3515            let mut pointer = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3516            tester.down(&mut pointer, c);
3517            tester.pump();
3518            tester.move_to(&mut pointer, g, true);
3519            tester.pump_and_settle();
3520            assert!(changed.get() > 0);
3521            changed.set(0);
3522            assert_eq!(selection(tester), TextSelection::new(2, 8));
3523
3524            tester.move_to(&mut pointer, g + Offset::new(4.0, 0.0), true);
3525            tester.pump_and_settle();
3526            assert_eq!(changed.get(), 0);
3527
3528            tester.move_to(&mut pointer, h, true);
3529            tester.pump();
3530            tester.up(&pointer);
3531            tester.pump_and_settle();
3532            assert_eq!(changed.get(), 1);
3533            assert_eq!(selection(tester), TextSelection::new(2, 9));
3534        });
3535    }
3536
3537    #[test]
3538    fn dragging_in_opposite_direction_also_works() {
3539        test_widgets(|tester| {
3540            let root = material_home(
3541                tester,
3542                SelectableText::new("abc def ghi").drag_start_behavior(DragStartBehavior::Down),
3543            );
3544            tester.pump_widget(root);
3545            let e = text_offset_to_position(tester, 5);
3546            let g = text_offset_to_position(tester, 8);
3547            let mut pointer = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3548            tester.down(&mut pointer, g);
3549            tester.pump();
3550            tester.move_to(&mut pointer, e, true);
3551            tester.pump();
3552            tester.up(&pointer);
3553            tester.pump_and_settle();
3554            assert_eq!(selection(tester), TextSelection::new(8, 5));
3555        });
3556    }
3557
3558    #[test]
3559    fn slow_mouse_dragging_also_selects_text() {
3560        test_widgets(|tester| {
3561            let root = material_home(
3562                tester,
3563                SelectableText::new("abc def ghi").drag_start_behavior(DragStartBehavior::Down),
3564            );
3565            tester.pump_widget(root);
3566            let e = text_offset_to_position(tester, 5);
3567            let g = text_offset_to_position(tester, 8);
3568            let mut pointer = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3569            tester.down(&mut pointer, e);
3570            tester.pump_by(Duration::from_secs(2));
3571            tester.move_to(&mut pointer, g, true);
3572            tester.pump();
3573            tester.up(&pointer);
3574            assert_eq!(selection(tester), TextSelection::new(5, 8));
3575        });
3576    }
3577
3578    #[test]
3579    fn selecting_a_space_selects_the_previous_word_on_mobile() {
3580        for platform in [TargetPlatform::IOS, TargetPlatform::Android] {
3581            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3582                let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3583                let recorded = Rc::clone(&seen);
3584                let root = material_app(
3585                    ThemeData::new(&tester.cell.borrow()),
3586                    SelectableText::new(" blah blah")
3587                        .on_selection_changed(move |_app, selection, _cause| {
3588                            *recorded.borrow_mut() = Some(selection)
3589                        })
3590                        .into_widget(),
3591                );
3592                tester.pump_widget(root);
3593                assert!(seen.borrow().is_none());
3594
3595                tester.tap_at(text_offset_to_position(tester, 10), 1);
3596                let current = seen.borrow_mut().take().expect("the tap selects");
3597                assert_eq!((current.base_offset, current.extent_offset), (10, 10));
3598
3599                tester.long_press_at(text_offset_to_position(tester, 5), 2);
3600                tester.pump_and_settle();
3601                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(1, 5)));
3602
3603                tester.tap_at(text_offset_to_position(tester, 10), 3);
3604                let current = seen.borrow_mut().take().expect("the tap selects");
3605                assert_eq!((current.base_offset, current.extent_offset), (10, 10));
3606                tester.long_press_at(text_offset_to_position(tester, 0), 4);
3607                tester.pump_and_settle();
3608                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(0, 1)));
3609            });
3610        }
3611    }
3612
3613    #[test]
3614    fn double_tapping_a_space_selects_the_previous_word_on_mobile() {
3615        for platform in [TargetPlatform::IOS, TargetPlatform::Android] {
3616            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3617                let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3618                let recorded = Rc::clone(&seen);
3619                let root = material_app(
3620                    ThemeData::builder()
3621                        .use_material3(false)
3622                        .build(&tester.cell.borrow()),
3623                    Center::new()
3624                        .child(
3625                            SelectableText::new(" blah blah  \n  blah").on_selection_changed(
3626                                move |_app, selection, _cause| {
3627                                    *recorded.borrow_mut() = Some(selection)
3628                                },
3629                            ),
3630                        )
3631                        .into_widget(),
3632                );
3633                tester.pump_widget(root);
3634
3635                tester.tap_at(text_offset_to_position(tester, 19), 1);
3636                let current = seen.borrow_mut().take().expect("the tap selects");
3637                assert_eq!((current.base_offset, current.extent_offset), (19, 19));
3638                tester.pump_by(Duration::from_millis(500));
3639                tester.tap_at(text_offset_to_position(tester, 5), 2);
3640                tester.pump_by(Duration::from_millis(50));
3641                tester.tap_at(text_offset_to_position(tester, 5), 3);
3642                tester.pump_and_settle();
3643                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(1, 5)));
3644
3645                tester.pump_by(Duration::from_millis(500));
3646                tester.tap_at(text_offset_to_position(tester, 0), 4);
3647                tester.pump_by(Duration::from_millis(50));
3648                tester.tap_at(text_offset_to_position(tester, 0), 5);
3649                tester.pump_and_settle();
3650                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(0, 1)));
3651
3652                tester.tap_at(text_offset_to_position(tester, 19), 6);
3653                let current = seen.borrow_mut().take().expect("the tap selects");
3654                assert_eq!((current.base_offset, current.extent_offset), (19, 19));
3655                tester.pump_by(Duration::from_millis(500));
3656                tester.tap_at(text_offset_to_position(tester, 14), 7);
3657                tester.pump_by(Duration::from_millis(50));
3658                tester.tap_at(text_offset_to_position(tester, 14), 8);
3659                tester.pump_and_settle();
3660                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(6, 14)));
3661            });
3662        }
3663    }
3664
3665    #[test]
3666    #[should_panic(expected = "No Overlay widget found")]
3667    fn throw_if_no_overlay_widget_exists_above() {
3668        test_widgets(|tester| {
3669            let home: waft_widgets::WidgetRef = Center::new()
3670                .child(Material::new().child(SelectableText::new("I love Flutter!")))
3671                .into_widget();
3672            let media = waft_widgets::MediaQuery::new(
3673                MediaQueryData::new().size(Size::new(800.0, 600.0)),
3674                home,
3675            )
3676            .into_widget();
3677            let root = waft_widgets::Directionality::new(TextDirection::Ltr, media);
3678            tester.pump_widget(root);
3679            let start = top_left_of_selectable_text(tester, 0);
3680            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
3681            tester.down(&mut gesture, start);
3682            tester.pump_by(Duration::from_secs(2));
3683            tester.up(&gesture);
3684            tester.pump_and_settle_by(waft_gestures::K_DOUBLE_TAP_TIMEOUT);
3685        });
3686    }
3687
3688    #[test]
3689    fn page_view_beats_selectable_text_drag_gestures_ios() {
3690        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
3691            let page_controller = {
3692                let mut app = tester.cell.borrow_mut();
3693                waft_widgets::PageController::new(&mut app, 0, true, 1.0, None, None)
3694            };
3695            let test_value = "abc def ghi jkl mno pqr stu vwx yz";
3696            let root = material_app(
3697                ThemeData::new(&tester.cell.borrow()),
3698                Material::new()
3699                    .child(
3700                        waft_widgets::PageView::new()
3701                            .controller(page_controller.clone())
3702                            .children([
3703                                Center::new()
3704                                    .child(SelectableText::new(test_value))
3705                                    .into_widget(),
3706                                SizedBox::new()
3707                                    .height(200.0)
3708                                    .child(Center::new().child(Text::new("Page 2")))
3709                                    .into_widget(),
3710                            ]),
3711                    )
3712                    .into_widget(),
3713            );
3714            tester.pump_widget(root);
3715            tester.pump_and_settle();
3716
3717            let g = text_offset_to_position(tester, test_value.find('g').unwrap() as i32);
3718            let p = text_offset_to_position(tester, test_value.find('p').unwrap() as i32);
3719            let mut gesture = TestPointer::touch(1);
3720            tester.down(&mut gesture, g);
3721            tester.pump();
3722            tester.up(&gesture);
3723            tester.pump();
3724            tester.down(&mut gesture, g);
3725            tester.pump_and_settle();
3726            tester.move_to(&mut gesture, p, true);
3727            tester.pump();
3728            tester.up(&gesture);
3729            tester.pump_and_settle();
3730            assert_eq!(
3731                selection(tester),
3732                TextSelection::new(
3733                    test_value.find('g').unwrap() as i32,
3734                    test_value.find('p').unwrap() as i32 + 3
3735                )
3736            );
3737            assert_eq!(
3738                page_controller.handle().page(&tester.cell.borrow()),
3739                Some(0.0)
3740            );
3741
3742            let rect = tester.get_rect(find::by_type::<SelectableText>());
3743            tester.drag_from(
3744                rect.center_right() - Offset::new(0.1, 0.0),
3745                Offset::new(-500.0, 0.0),
3746                9,
3747            );
3748            tester.pump_and_settle();
3749            assert_eq!(
3750                page_controller.handle().page(&tester.cell.borrow()),
3751                Some(1.0)
3752            );
3753        });
3754    }
3755
3756    #[test]
3757    fn the_select_all_calls_on_selection_changed_with_a_mouse_on_windows_and_linux() {
3758        for platform in [TargetPlatform::Windows, TargetPlatform::Linux] {
3759            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3760                let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3761                let recorded = Rc::clone(&seen);
3762                let root = material_home(
3763                    tester,
3764                    SelectableText::new("abc def ghi").on_selection_changed(
3765                        move |_app, selection, _cause| {
3766                            assert!(recorded.borrow().is_none());
3767                            *recorded.borrow_mut() = Some(selection);
3768                        },
3769                    ),
3770                );
3771                tester.pump_widget(root);
3772
3773                let e = text_offset_to_position(tester, 5);
3774                let mut gesture = TestPointer::mouse(1, waft_gestures::K_SECONDARY_BUTTON);
3775                tester.down(&mut gesture, e);
3776                tester.pump();
3777                tester.up(&gesture);
3778                tester.pump_and_settle();
3779                let first = seen.borrow_mut().take().expect("the right click selects");
3780                assert!(first.is_collapsed());
3781                assert_eq!(first.base_offset, 5);
3782
3783                tester.tap(find::text("Select all"));
3784                tester.pump();
3785                let second = seen.borrow_mut().take().expect("select all selects");
3786                assert_eq!(second.base_offset, 0);
3787                assert_eq!(second.extent_offset, 11);
3788            });
3789        }
3790    }
3791
3792    #[test]
3793    fn selecting_a_space_selects_the_space_on_non_mobile_platforms() {
3794        for platform in [
3795            TargetPlatform::MacOS,
3796            TargetPlatform::Windows,
3797            TargetPlatform::Linux,
3798            TargetPlatform::Fuchsia,
3799        ] {
3800            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3801                let seen: Rc<RefCell<Option<TextSelection>>> = Rc::default();
3802                let recorded = Rc::clone(&seen);
3803                let root = material_app(
3804                    ThemeData::new(&tester.cell.borrow()),
3805                    Material::new()
3806                        .child(Center::new().child(
3807                            SelectableText::new(" blah blah").on_selection_changed(
3808                                move |_app, selection, _cause| {
3809                                    *recorded.borrow_mut() = Some(selection)
3810                                },
3811                            ),
3812                        ))
3813                        .into_widget(),
3814                );
3815                tester.pump_widget(root);
3816                assert!(seen.borrow().is_none());
3817
3818                tester.tap_at(text_offset_to_position(tester, 10), 1);
3819                let current = seen.borrow_mut().take().expect("the tap selects");
3820                assert_eq!((current.base_offset, current.extent_offset), (10, 10));
3821
3822                tester.pump_by(Duration::from_millis(500));
3823                tester.tap_at(text_offset_to_position(tester, 5), 2);
3824                tester.pump_by(Duration::from_millis(50));
3825                tester.tap_at(text_offset_to_position(tester, 5), 3);
3826                tester.pump_and_settle();
3827                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(5, 6)));
3828
3829                tester.tap_at(text_offset_to_position(tester, 0), 4);
3830                tester.pump_and_settle();
3831                tester.tap_at(text_offset_to_position(tester, 10), 5);
3832                let current = seen.borrow_mut().take().expect("the tap selects");
3833                assert_eq!((current.base_offset, current.extent_offset), (10, 10));
3834
3835                tester.pump_by(Duration::from_millis(500));
3836                tester.tap_at(text_offset_to_position(tester, 0), 6);
3837                tester.pump_by(Duration::from_millis(50));
3838                tester.tap_at(text_offset_to_position(tester, 0), 7);
3839                tester.pump_and_settle();
3840                assert_eq!(seen.borrow_mut().take(), Some(TextSelection::new(0, 1)));
3841            });
3842        }
3843    }
3844
3845    /// Pumps `widget` centred on a `Material` in a Material 2 app, as the selectable
3846    /// text tests do.
3847    fn pump_selectable(tester: &mut WidgetTester, widget: SelectableText) {
3848        let root = material_app(
3849            crate::theme_data::ThemeData::builder()
3850                .use_material3(false)
3851                .build(&tester.cell.borrow()),
3852            Center::new()
3853                .child(Material::new().child(widget))
3854                .into_widget(),
3855        );
3856        tester.pump_widget(root);
3857    }
3858
3859    fn selectable_size(tester: &WidgetTester) -> Size {
3860        tester.get_size(find::by_type::<SelectableText>().evaluate(tester)[0])
3861    }
3862
3863    #[test]
3864    fn selectable_text_baseline_alignment_no_strut() {
3865        test_widgets(|tester| {
3866            let key_a: KeyRef = UniqueKey::new().into();
3867            let key_b: KeyRef = UniqueKey::new().into();
3868            let root = material_app(
3869                crate::theme_data::ThemeData::builder()
3870                    .use_material3(false)
3871                    .build(&tester.cell.borrow()),
3872                Center::new()
3873                    .child(
3874                        Material::new().child(
3875                            waft_widgets::Row::new()
3876                                .cross_axis_alignment(waft_widgets::CrossAxisAlignment::Baseline)
3877                                .text_baseline(waft_embedder::TextBaseline::Alphabetic)
3878                                .children([
3879                                    waft_widgets::Expanded::new(
3880                                        SelectableText::new("A")
3881                                            .key(key_a.clone())
3882                                            .strut_style(StrutStyle::DISABLED)
3883                                            .style(
3884                                                TextStyle::new()
3885                                                    .font_family("FlutterTest")
3886                                                    .font_size(10.0),
3887                                            ),
3888                                    )
3889                                    .into_widget(),
3890                                    Text::new("abc")
3891                                        .style(
3892                                            TextStyle::new()
3893                                                .font_family("FlutterTest")
3894                                                .font_size(20.0),
3895                                        )
3896                                        .into_widget(),
3897                                    waft_widgets::Expanded::new(
3898                                        SelectableText::new("B")
3899                                            .key(key_b.clone())
3900                                            .strut_style(StrutStyle::DISABLED)
3901                                            .style(
3902                                                TextStyle::new()
3903                                                    .font_family("FlutterTest")
3904                                                    .font_size(30.0),
3905                                            ),
3906                                    )
3907                                    .into_widget(),
3908                                ]),
3909                        ),
3910                    )
3911                    .into_widget(),
3912            );
3913            tester.pump_widget(root);
3914            let row_bottom = tester
3915                .get_bottom_left(find::by_type::<waft_widgets::Row>())
3916                .dy();
3917            assert_eq!(
3918                tester.get_bottom_left(find::by_key(key_a)).dy(),
3919                row_bottom - 5.0
3920            );
3921            assert_eq!(
3922                tester.get_bottom_left(find::text("abc")).dy(),
3923                row_bottom - 2.5
3924            );
3925            assert_eq!(tester.get_bottom_left(find::by_key(key_b)).dy(), row_bottom);
3926        });
3927    }
3928
3929    #[test]
3930    fn strut_basic_single_line() {
3931        test_widgets(|tester| {
3932            pump_selectable(tester, SelectableText::new("something"));
3933            assert_eq!(selectable_size(tester), Size::new(129.0, 14.0));
3934        });
3935    }
3936
3937    #[test]
3938    fn strut_text_style_increases_height() {
3939        test_widgets(|tester| {
3940            pump_selectable(
3941                tester,
3942                SelectableText::new("something").style(TextStyle::new().font_size(20.0)),
3943            );
3944            assert_eq!(selectable_size(tester), Size::new(183.0, 20.0));
3945
3946            pump_selectable(
3947                tester,
3948                SelectableText::new("something")
3949                    .style(TextStyle::new().font_size(20.0))
3950                    .strut_style(StrutStyle::DISABLED),
3951            );
3952            assert_eq!(selectable_size(tester), Size::new(183.0, 20.0));
3953        });
3954    }
3955
3956    #[test]
3957    fn strut_basic_multi_line() {
3958        test_widgets(|tester| {
3959            pump_selectable(tester, SelectableText::new("something").max_lines(Some(6)));
3960            assert_eq!(selectable_size(tester), Size::new(129.0, 84.0));
3961        });
3962    }
3963
3964    #[test]
3965    fn strut_no_force_small_strut() {
3966        test_widgets(|tester| {
3967            pump_selectable(
3968                tester,
3969                SelectableText::new("something")
3970                    .max_lines(Some(6))
3971                    .strut_style(StrutStyle::new().font_size(5.0)),
3972            );
3973            assert_eq!(selectable_size(tester), Size::new(129.0, 84.0));
3974        });
3975    }
3976
3977    #[test]
3978    fn strut_no_force_large_strut() {
3979        test_widgets(|tester| {
3980            pump_selectable(
3981                tester,
3982                SelectableText::new("something")
3983                    .max_lines(Some(6))
3984                    .strut_style(StrutStyle::new().font_size(25.0)),
3985            );
3986            assert_eq!(selectable_size(tester), Size::new(129.0, 150.0));
3987        });
3988    }
3989
3990    #[test]
3991    fn strut_height_override() {
3992        test_widgets(|tester| {
3993            pump_selectable(
3994                tester,
3995                SelectableText::new("something")
3996                    .max_lines(Some(3))
3997                    .strut_style(StrutStyle::new().font_size(8.0).force_strut_height(true)),
3998            );
3999            assert_eq!(selectable_size(tester), Size::new(129.0, 24.0));
4000        });
4001    }
4002
4003    #[test]
4004    fn strut_forces_field_taller() {
4005        test_widgets(|tester| {
4006            pump_selectable(
4007                tester,
4008                SelectableText::new("something")
4009                    .max_lines(Some(3))
4010                    .style(TextStyle::new().font_size(10.0))
4011                    .strut_style(StrutStyle::new().font_size(18.0).force_strut_height(true)),
4012            );
4013            assert_eq!(selectable_size(tester), Size::new(93.0, 54.0));
4014        });
4015    }
4016
4017    #[test]
4018    fn selectable_text_baseline_alignment() {
4019        test_widgets(|tester| {
4020            let key_a: KeyRef = UniqueKey::new().into();
4021            let key_b: KeyRef = UniqueKey::new().into();
4022            let root = material_app(
4023                crate::theme_data::ThemeData::builder()
4024                    .use_material3(false)
4025                    .build(&tester.cell.borrow()),
4026                Center::new()
4027                    .child(
4028                        Material::new().child(
4029                            waft_widgets::Row::new()
4030                                .cross_axis_alignment(waft_widgets::CrossAxisAlignment::Baseline)
4031                                .text_baseline(waft_embedder::TextBaseline::Alphabetic)
4032                                .children([
4033                                    waft_widgets::Expanded::new(
4034                                        SelectableText::new("A").key(key_a.clone()).style(
4035                                            TextStyle::new()
4036                                                .font_family("FlutterTest")
4037                                                .font_size(10.0),
4038                                        ),
4039                                    )
4040                                    .into_widget(),
4041                                    Text::new("abc")
4042                                        .style(
4043                                            TextStyle::new()
4044                                                .font_family("FlutterTest")
4045                                                .font_size(20.0),
4046                                        )
4047                                        .into_widget(),
4048                                    waft_widgets::Expanded::new(
4049                                        SelectableText::new("B").key(key_b.clone()).style(
4050                                            TextStyle::new()
4051                                                .font_family("FlutterTest")
4052                                                .font_size(30.0),
4053                                        ),
4054                                    )
4055                                    .into_widget(),
4056                                ]),
4057                        ),
4058                    )
4059                    .into_widget(),
4060            );
4061            tester.pump_widget(root);
4062            let row_bottom = tester
4063                .get_bottom_left(find::by_type::<waft_widgets::Row>())
4064                .dy();
4065            assert_eq!(
4066                tester.get_bottom_left(find::by_key(key_a)).dy(),
4067                row_bottom - 5.0
4068            );
4069            assert_eq!(
4070                tester.get_bottom_left(find::text("abc")).dy(),
4071                row_bottom - 2.5
4072            );
4073            assert_eq!(tester.get_bottom_left(find::by_key(key_b)).dy(), row_bottom);
4074        });
4075    }
4076    #[test]
4077    fn can_align_to_center() {
4078        test_widgets(|tester| {
4079            let root = material_app(
4080                crate::theme_data::ThemeData::builder()
4081                    .use_material3(false)
4082                    .build(&tester.cell.borrow()),
4083                waft_widgets::MediaQuery::new(
4084                    MediaQueryData::new().size(Size::new(800.0, 600.0)),
4085                    SizedBox::new()
4086                        .width(300.0)
4087                        .child(SelectableText::new("abcd").text_align(TextAlign::Center)),
4088                )
4089                .into_widget(),
4090            );
4091            tester.pump_widget(root);
4092            let editable = render_editable_at(tester, 0);
4093            let caret_at = |tester: &mut WidgetTester, offset: i32| {
4094                let mut app = tester.cell.borrow_mut();
4095                let rect = editable.get_local_rect_for_caret(&mut app, TextPosition::new(offset));
4096                editable
4097                    .as_box()
4098                    .local_to_global(&app, rect.top_left(), None)
4099            };
4100            assert_eq!(caret_at(tester, 2).dx(), 399.0);
4101        });
4102    }
4103
4104    #[test]
4105    fn can_align_to_center_within_center() {
4106        test_widgets(|tester| {
4107            let root = material_app(
4108                crate::theme_data::ThemeData::builder()
4109                    .use_material3(false)
4110                    .build(&tester.cell.borrow()),
4111                waft_widgets::MediaQuery::new(
4112                    MediaQueryData::new().size(Size::new(800.0, 600.0)),
4113                    SizedBox::new().width(300.0).child(
4114                        Center::new()
4115                            .child(SelectableText::new("abcd").text_align(TextAlign::Center)),
4116                    ),
4117                )
4118                .into_widget(),
4119            );
4120            tester.pump_widget(root);
4121            let editable = render_editable_at(tester, 0);
4122            let caret_at = |tester: &mut WidgetTester, offset: i32| {
4123                let mut app = tester.cell.borrow_mut();
4124                let rect = editable.get_local_rect_for_caret(&mut app, TextPosition::new(offset));
4125                editable
4126                    .as_box()
4127                    .local_to_global(&app, rect.top_left(), None)
4128            };
4129            assert_eq!(caret_at(tester, 2).dx(), 399.0);
4130        });
4131    }
4132    /// `selectable_text_test.dart`, "default SelectableText debugFillProperties".
4133    #[test]
4134    fn a_default_selectable_text_describes_its_data() {
4135        use waft_foundation::DiagnosticPropertiesBuilder;
4136
4137        let text = SelectableText::new("something");
4138        let cell = waft_foundation::AppCell::new();
4139        let app = cell.borrow();
4140        let description: Vec<String> = waft_widgets::testing::describe_properties(
4141            |properties: &mut DiagnosticPropertiesBuilder| {
4142                text.debug_fill_properties(&app, properties)
4143            },
4144        );
4145        assert_eq!(description, ["data: something"]);
4146    }
4147
4148    /// `selectable_text_test.dart`, "SelectableText implements debugFillProperties". The
4149    /// `selectionControls` line is left out until that type has a `Display`.
4150    #[test]
4151    fn a_selectable_text_describes_its_properties() {
4152        use std::rc::Rc;
4153
4154        use waft_embedder::{Color, Radius, TextDirection};
4155        use waft_foundation::DiagnosticPropertiesBuilder;
4156        use waft_painting::{TextAlign, TextScaler};
4157        use waft_widgets::ClampingScrollPhysics;
4158        use waft_widgets::ScrollBehaviorRef;
4159
4160        let green = Color::new(0xff00ff00);
4161        let text = SelectableText::new("something")
4162            .style(TextStyle::new().color(green))
4163            .text_align(TextAlign::End)
4164            .text_direction(TextDirection::Ltr)
4165            .text_scaler(TextScaler::NO_SCALING)
4166            .autofocus(true)
4167            .show_cursor(true)
4168            .min_lines(2)
4169            .max_lines(Some(10))
4170            .cursor_width(1.0)
4171            .cursor_height(1.0)
4172            .cursor_radius(Radius::ZERO)
4173            .cursor_color(green)
4174            .scroll_physics(Rc::new(ClampingScrollPhysics::new()))
4175            .scroll_behavior(ScrollBehaviorRef::plain())
4176            .semantics_label("something else")
4177            .enable_interactive_selection(false);
4178        let cell = waft_foundation::AppCell::new();
4179        let app = cell.borrow();
4180        let description: Vec<String> = waft_widgets::testing::describe_properties(
4181            |properties: &mut DiagnosticPropertiesBuilder| {
4182                text.debug_fill_properties(&app, properties)
4183            },
4184        );
4185        assert_eq!(
4186            description,
4187            [
4188                "data: something".to_string(),
4189                "semanticsLabel: something else".to_string(),
4190                format!("style: TextStyle(inherit: true, color: {green})"),
4191                "autofocus: true".to_string(),
4192                "showCursor: true".to_string(),
4193                "minLines: 2".to_string(),
4194                "maxLines: 10".to_string(),
4195                "textAlign: end".to_string(),
4196                "textDirection: ltr".to_string(),
4197                "textScaler: no scaling".to_string(),
4198                "cursorWidth: 1.0".to_string(),
4199                "cursorHeight: 1.0".to_string(),
4200                "cursorRadius: Radius.circular(0.0)".to_string(),
4201                format!("cursorColor: {green}"),
4202                "selection disabled".to_string(),
4203                "scrollPhysics: ClampingScrollPhysics".to_string(),
4204                "scrollBehavior: ScrollBehavior".to_string(),
4205            ]
4206        );
4207    }
4208}