Skip to main content

waft_material/
text_selection.rs

1//! Flutter counterpart: material_ui's `text_selection.dart`.
2
3use std::any::Any;
4use std::f64::consts::PI;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{Canvas, Color, FillRule, Offset, Paint, PathBuilder, Rect, Size};
9use waft_foundation::{App, Handle, Listenable, Listener, Ref, Task};
10use waft_painting::AlignmentGeometry;
11use waft_rendering::{CustomPainter, HitTestBehavior, TextSelectionPoint};
12use waft_services::AnyTextSelectionDelegate;
13use waft_widgets::{
14    BuildContext, ClipboardStatus, ClipboardStatusNotifier, CustomPaint, GestureDetector,
15    IntoWidget, KeyRef, SizedBox, State, StateData, StatefulWidget, Text, TextSelectionControls,
16    TextSelectionHandleControls, TextSelectionHandleType, Transform, WidgetRef,
17};
18
19use crate::debug::debug_check_has_material_localizations;
20use crate::material_localizations::MaterialLocalizations;
21use crate::text_selection_theme::TextSelectionTheme;
22use crate::text_selection_toolbar::TextSelectionToolbar;
23use crate::text_selection_toolbar_text_button::TextSelectionToolbarTextButton;
24use crate::theme::Theme;
25
26const K_HANDLE_SIZE: f64 = 22.0;
27
28// Padding between the toolbar and the anchor.
29const K_TOOLBAR_CONTENT_DISTANCE_BELOW: f64 = K_HANDLE_SIZE - 2.0;
30const K_TOOLBAR_CONTENT_DISTANCE: f64 = 8.0;
31
32/// Android Material styled text selection handle controls.
33///
34/// Specifically does not manage the toolbar, which is left to
35/// `EditableText.contextMenuBuilder`.
36#[deprecated(note = "Use `MaterialTextSelectionControls`. \
37            This feature was deprecated after v3.3.0-0.5.pre.")]
38#[derive(Debug, Default)]
39pub struct MaterialTextSelectionHandleControls;
40
41/// Android Material styled text selection controls.
42///
43/// [`material_text_selection_controls`] has a suitable instance of this class.
44#[derive(Debug, Default)]
45pub struct MaterialTextSelectionControls;
46
47impl MaterialTextSelectionControls {
48    /// Creates Android Material styled text selection controls.
49    pub const fn new() -> MaterialTextSelectionControls {
50        MaterialTextSelectionControls
51    }
52}
53
54impl TextSelectionControls for MaterialTextSelectionControls {
55    /// Returns the size of the Material handle.
56    fn get_handle_size(&self, _text_line_height: f64) -> Size {
57        Size::new(K_HANDLE_SIZE, K_HANDLE_SIZE)
58    }
59
60    /// Builder for material-style copy/paste text selection toolbar.
61    #[allow(deprecated, clippy::too_many_arguments)]
62    fn build_toolbar(
63        &self,
64        app: &mut App,
65        _context: BuildContext,
66        global_editable_region: Rect,
67        text_line_height: f64,
68        selection_midpoint: Offset,
69        endpoints: &[TextSelectionPoint],
70        delegate: AnyTextSelectionDelegate,
71        clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
72        _last_secondary_tap_down_position: Option<Offset>,
73    ) -> WidgetRef {
74        let handle_cut = self.can_cut(app, delegate).then(|| {
75            Listener::new(move |app| {
76                MaterialTextSelectionControls.handle_cut(app, delegate);
77            })
78        });
79        let handle_copy = self.can_copy(app, delegate).then(|| {
80            Listener::new(move |app| {
81                MaterialTextSelectionControls.handle_copy(app, delegate);
82            })
83        });
84        let handle_paste = self.can_paste(app, delegate).then(|| {
85            Listener::new(move |app| {
86                MaterialTextSelectionControls.handle_paste(app, delegate);
87            })
88        });
89        let handle_select_all = self.can_select_all(app, delegate).then(|| {
90            Listener::new(move |app| {
91                MaterialTextSelectionControls.handle_select_all(app, delegate);
92            })
93        });
94        TextSelectionControlsToolbar {
95            key: None,
96            global_editable_region,
97            text_line_height,
98            selection_midpoint,
99            endpoints: endpoints.to_vec(),
100            clipboard_status,
101            handle_cut,
102            handle_copy,
103            handle_paste,
104            handle_select_all,
105        }
106        .into_widget()
107    }
108
109    /// Builder for material-style text selection handles.
110    fn build_handle(
111        &self,
112        app: &mut App,
113        context: BuildContext,
114        handle_type: TextSelectionHandleType,
115        _text_line_height: f64,
116        on_tap: Option<Listener>,
117    ) -> WidgetRef {
118        let theme = Theme::of(app, context);
119        let handle_color = TextSelectionTheme::of(app, context)
120            .selection_handle_color
121            .unwrap_or(theme.color_scheme.primary());
122        let mut gesture_detector = GestureDetector::new().behavior(HitTestBehavior::Translucent);
123        if let Some(on_tap) = on_tap {
124            gesture_detector = gesture_detector.on_tap(on_tap);
125        }
126        let handle = SizedBox::square(Some(K_HANDLE_SIZE))
127            .child(
128                CustomPaint::new()
129                    .painter(TextSelectionHandlePainter {
130                        color: handle_color,
131                    })
132                    .child(gesture_detector),
133            )
134            .into_widget();
135
136        // [handle] is a circle, with a rectangle in the top left quadrant of that
137        // circle (an onion pointing to 10:30). We rotate [handle] to point
138        // straight up or up-right depending on the handle type.
139        match handle_type {
140            // points up-right
141            TextSelectionHandleType::Left => {
142                Transform::rotate(PI / 2.0).child(handle).into_widget()
143            }
144            // points up-left
145            TextSelectionHandleType::Right => handle,
146            // points up
147            TextSelectionHandleType::Collapsed => {
148                Transform::rotate(PI / 4.0).child(handle).into_widget()
149            }
150        }
151    }
152
153    /// Gets anchor for material-style text selection handles.
154    ///
155    /// See `TextSelectionControls::get_handle_anchor`.
156    fn get_handle_anchor(
157        &self,
158        handle_type: TextSelectionHandleType,
159        _text_line_height: f64,
160    ) -> Offset {
161        match handle_type {
162            TextSelectionHandleType::Collapsed => Offset::new(K_HANDLE_SIZE / 2.0, -4.0),
163            TextSelectionHandleType::Left => Offset::new(K_HANDLE_SIZE, 0.0),
164            TextSelectionHandleType::Right => Offset::ZERO,
165        }
166    }
167
168    #[allow(deprecated)]
169    fn can_select_all(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
170        // Android allows SelectAll when selection is not collapsed, unless
171        // everything has already been selected.
172        let value = delegate.text_editing_value(app);
173        delegate.select_all_enabled(app)
174            && !value.text.is_empty()
175            && !(value.selection.start() == 0
176                && value.selection.end() == value.text.encode_utf16().count() as i32)
177    }
178}
179
180#[allow(deprecated)]
181impl TextSelectionControls for MaterialTextSelectionHandleControls {
182    fn as_text_selection_handle_controls(&self) -> Option<&dyn TextSelectionHandleControls> {
183        Some(self)
184    }
185
186    fn get_handle_size(&self, text_line_height: f64) -> Size {
187        MaterialTextSelectionControls.get_handle_size(text_line_height)
188    }
189
190    #[allow(clippy::too_many_arguments)]
191    fn build_toolbar(
192        &self,
193        app: &mut App,
194        context: BuildContext,
195        global_editable_region: Rect,
196        text_line_height: f64,
197        selection_midpoint: Offset,
198        endpoints: &[TextSelectionPoint],
199        delegate: AnyTextSelectionDelegate,
200        clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
201        last_secondary_tap_down_position: Option<Offset>,
202    ) -> WidgetRef {
203        TextSelectionHandleControls::build_toolbar(
204            self,
205            app,
206            context,
207            global_editable_region,
208            text_line_height,
209            selection_midpoint,
210            endpoints,
211            delegate,
212            clipboard_status,
213            last_secondary_tap_down_position,
214        )
215    }
216
217    fn build_handle(
218        &self,
219        app: &mut App,
220        context: BuildContext,
221        handle_type: TextSelectionHandleType,
222        text_line_height: f64,
223        on_tap: Option<Listener>,
224    ) -> WidgetRef {
225        MaterialTextSelectionControls.build_handle(
226            app,
227            context,
228            handle_type,
229            text_line_height,
230            on_tap,
231        )
232    }
233
234    fn get_handle_anchor(
235        &self,
236        handle_type: TextSelectionHandleType,
237        text_line_height: f64,
238    ) -> Offset {
239        MaterialTextSelectionControls.get_handle_anchor(handle_type, text_line_height)
240    }
241
242    fn can_cut(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
243        TextSelectionHandleControls::can_cut(self, app, delegate)
244    }
245
246    fn can_copy(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
247        TextSelectionHandleControls::can_copy(self, app, delegate)
248    }
249
250    fn can_paste(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
251        TextSelectionHandleControls::can_paste(self, app, delegate)
252    }
253
254    fn can_select_all(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
255        TextSelectionHandleControls::can_select_all(self, app, delegate)
256    }
257
258    fn handle_cut(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
259        TextSelectionHandleControls::handle_cut(self, app, delegate, None);
260    }
261
262    fn handle_copy(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
263        TextSelectionHandleControls::handle_copy(self, app, delegate, None);
264    }
265
266    fn handle_paste(&self, app: &mut App, delegate: AnyTextSelectionDelegate) -> Task<()> {
267        TextSelectionHandleControls::handle_paste(self, app, delegate)
268    }
269
270    fn handle_select_all(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
271        TextSelectionHandleControls::handle_select_all(self, app, delegate);
272    }
273}
274
275#[allow(deprecated)]
276impl TextSelectionHandleControls for MaterialTextSelectionHandleControls {}
277
278// The label and callback for the available default text selection menu buttons.
279struct TextSelectionToolbarItemData {
280    label: String,
281    on_pressed: Listener,
282}
283
284// The highest level toolbar widget, built directly by buildToolbar.
285struct TextSelectionControlsToolbar {
286    key: Option<KeyRef>,
287    clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
288    endpoints: Vec<TextSelectionPoint>,
289    global_editable_region: Rect,
290    handle_cut: Option<Listener>,
291    handle_copy: Option<Listener>,
292    handle_paste: Option<Listener>,
293    handle_select_all: Option<Listener>,
294    selection_midpoint: Offset,
295    text_line_height: f64,
296}
297
298impl Debug for TextSelectionControlsToolbar {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.debug_struct("_TextSelectionControlsToolbar")
301            .finish_non_exhaustive()
302    }
303}
304
305impl StatefulWidget for TextSelectionControlsToolbar {
306    type State = TextSelectionControlsToolbarState;
307
308    fn key(&self) -> Option<&KeyRef> {
309        self.key.as_ref()
310    }
311
312    fn create_state(&self) -> TextSelectionControlsToolbarState {
313        TextSelectionControlsToolbarState {
314            state: StateData::new(),
315        }
316    }
317}
318
319struct TextSelectionControlsToolbarState {
320    state: StateData<TextSelectionControlsToolbar>,
321}
322
323impl TextSelectionControlsToolbarState {
324    fn on_changed_clipboard_status(self: Handle<Self>, app: &mut App) {
325        self.set_state(app, |_state| {
326            // Inform the widget that the value of clipboardStatus has changed.
327        });
328    }
329}
330
331impl State for TextSelectionControlsToolbarState {
332    type Widget = TextSelectionControlsToolbar;
333    waft_widgets::state_accessors!();
334
335    fn init_state(self: Handle<Self>, app: &mut App) {
336        if let Some(clipboard_status) = self.widget(app).clipboard_status.clone() {
337            clipboard_status.add_listener(
338                app,
339                Listener::handle_method(self, Self::on_changed_clipboard_status),
340            );
341        }
342    }
343
344    fn did_update_widget(
345        self: Handle<Self>,
346        app: &mut App,
347        old_widget: &TextSelectionControlsToolbar,
348    ) {
349        if self.widget(app).clipboard_status != old_widget.clipboard_status {
350            if let Some(clipboard_status) = self.widget(app).clipboard_status.clone() {
351                clipboard_status.add_listener(
352                    app,
353                    Listener::handle_method(self, Self::on_changed_clipboard_status),
354                );
355            }
356            if let Some(clipboard_status) = old_widget.clipboard_status.clone() {
357                clipboard_status.remove_listener(
358                    app,
359                    &Listener::handle_method(self, Self::on_changed_clipboard_status),
360                );
361            }
362        }
363    }
364
365    fn dispose(self: Handle<Self>, app: &mut App) {
366        if let Some(clipboard_status) = self.widget(app).clipboard_status.clone() {
367            clipboard_status.remove_listener(
368                app,
369                &Listener::handle_method(self, Self::on_changed_clipboard_status),
370            );
371        }
372    }
373
374    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
375        let widget = self.widget(app);
376        let handle_cut = widget.handle_cut.clone();
377        let handle_copy = widget.handle_copy.clone();
378        let handle_paste = widget.handle_paste.clone();
379        let handle_select_all = widget.handle_select_all.clone();
380        let clipboard_status = widget.clipboard_status.clone();
381        let endpoints = widget.endpoints.clone();
382        let text_line_height = widget.text_line_height;
383        let global_editable_region = widget.global_editable_region;
384        let selection_midpoint = widget.selection_midpoint;
385
386        // If there are no buttons to be shown, don't render anything.
387        if handle_cut.is_none()
388            && handle_copy.is_none()
389            && handle_paste.is_none()
390            && handle_select_all.is_none()
391        {
392            return SizedBox::shrink().into_widget();
393        }
394        // If the paste button is desired, don't render anything until the state of
395        // the clipboard is known, since it's used to determine if paste is shown.
396        if handle_paste.is_some()
397            && clipboard_status
398                .as_ref()
399                .is_some_and(|status| status.value(app) == ClipboardStatus::Unknown)
400        {
401            return SizedBox::shrink().into_widget();
402        }
403
404        // Calculate the positioning of the menu. It is placed above the selection
405        // if there is enough room, or otherwise below.
406        let start_text_selection_point = &endpoints[0];
407        let end_text_selection_point = if endpoints.len() > 1 {
408            &endpoints[1]
409        } else {
410            &endpoints[0]
411        };
412        let top_amount_in_editable_region =
413            start_text_selection_point.point.dy() - text_line_height;
414        let anchor_top = top_amount_in_editable_region.max(0.0) + global_editable_region.top
415            - K_TOOLBAR_CONTENT_DISTANCE;
416
417        let anchor_above = Offset::new(
418            global_editable_region.left + selection_midpoint.dx(),
419            anchor_top,
420        );
421        let anchor_below = Offset::new(
422            global_editable_region.left + selection_midpoint.dx(),
423            global_editable_region.top
424                + end_text_selection_point.point.dy()
425                + K_TOOLBAR_CONTENT_DISTANCE_BELOW,
426        );
427
428        // Determine which buttons will appear so that the order and total number is
429        // known. A button's position in the menu can slightly affect its
430        // appearance.
431        debug_assert!(debug_check_has_material_localizations(app, context));
432        let localizations = <dyn MaterialLocalizations>::of(app, context);
433        let mut item_datas: Vec<TextSelectionToolbarItemData> = Vec::new();
434        if let Some(handle_cut) = handle_cut {
435            item_datas.push(TextSelectionToolbarItemData {
436                label: localizations.cut_button_label(),
437                on_pressed: handle_cut,
438            });
439        }
440        if let Some(handle_copy) = handle_copy {
441            item_datas.push(TextSelectionToolbarItemData {
442                label: localizations.copy_button_label(),
443                on_pressed: handle_copy,
444            });
445        }
446        if let Some(handle_paste) = handle_paste
447            && clipboard_status
448                .as_ref()
449                .is_some_and(|status| status.value(app) == ClipboardStatus::Pasteable)
450        {
451            item_datas.push(TextSelectionToolbarItemData {
452                label: localizations.paste_button_label(),
453                on_pressed: handle_paste,
454            });
455        }
456        if let Some(handle_select_all) = handle_select_all {
457            item_datas.push(TextSelectionToolbarItemData {
458                label: localizations.select_all_button_label(),
459                on_pressed: handle_select_all,
460            });
461        }
462
463        // If there is no option available, build an empty widget.
464        if item_datas.is_empty() {
465            return SizedBox::shrink().into_widget();
466        }
467
468        let total = item_datas.len();
469        TextSelectionToolbar::new(
470            anchor_above,
471            anchor_below,
472            item_datas
473                .into_iter()
474                .enumerate()
475                .map(|(index, item_data)| {
476                    TextSelectionToolbarTextButton::new(
477                        Text::new(item_data.label),
478                        TextSelectionToolbarTextButton::get_padding(index, total),
479                    )
480                    .alignment(AlignmentGeometry::CENTER_START)
481                    .on_pressed(item_data.on_pressed)
482                    .into_widget()
483                }),
484        )
485        .into_widget()
486    }
487}
488
489/// Draws a single text selection handle which points up and to the left.
490struct TextSelectionHandlePainter {
491    color: Color,
492}
493
494impl CustomPainter for TextSelectionHandlePainter {
495    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
496        let paint = Paint {
497            color: self.color.into(),
498            ..Paint::default()
499        };
500        let radius = size.width() / 2.0;
501        let circle = Rect::from_circle(Offset::new(radius, radius), radius);
502        let point = Rect::from_ltwh(0.0, 0.0, radius, radius);
503        let mut path = PathBuilder::new();
504        path.rrect_radii_elliptical(circle, [[radius as f32, radius as f32]; 4]);
505        path.rect(point.into());
506        canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
507    }
508
509    fn should_repaint(&self, _app: &App, old_painter: &dyn CustomPainter) -> bool {
510        old_painter
511            .as_any()
512            .downcast_ref::<TextSelectionHandlePainter>()
513            .is_none_or(|old| self.color != old.color)
514    }
515
516    fn as_any(&self) -> &dyn Any {
517        self
518    }
519}
520
521// TODO(justinmc): Deprecate this after TextSelectionControls.buildToolbar is
522// deleted, when users should migrate back to materialTextSelectionControls.
523// See https://github.com/flutter/flutter/pull/124262
524/// Text selection handle controls that follow the Material Design specification.
525///
526/// Dart's global: every call hands out the same controls, so an `EditableText` given them
527/// again sees them unchanged.
528#[allow(deprecated)]
529pub fn material_text_selection_handle_controls() -> Rc<dyn TextSelectionControls> {
530    thread_local! {
531        static CONTROLS: Rc<dyn TextSelectionControls> = Rc::new(MaterialTextSelectionHandleControls);
532    }
533    CONTROLS.with(Rc::clone)
534}
535
536/// Text selection controls that follow the Material Design specification.
537///
538/// Dart's global: every call hands out the same controls, so an `EditableText` given them
539/// again sees them unchanged.
540pub fn material_text_selection_controls() -> Rc<dyn TextSelectionControls> {
541    thread_local! {
542        static CONTROLS: Rc<dyn TextSelectionControls> = Rc::new(MaterialTextSelectionControls);
543    }
544    CONTROLS.with(Rc::clone)
545}
546
547#[cfg(test)]
548mod tests {
549    use waft_embedder::{TextAffinity, TextSelection};
550    use waft_painting::{EdgeInsets, TextStyle};
551    use waft_services::TextSelectionDelegate;
552    use waft_widgets::{
553        Builder, Container, EditableText, EditableTextState, FittedBox, FocusNode, GlobalKey,
554        Padding, TextEditingController, TextEditingControllerLeaf,
555    };
556
557    use waft_widgets::testing::{WidgetTester, test_widgets};
558
559    use super::*;
560    use crate::colors::Colors;
561    use crate::test_support::material_app;
562    use crate::text_selection_theme::TextSelectionThemeData;
563    use crate::theme_data::ThemeData;
564
565    /// Dart's `createEditableText(key:, text:, selection:)`.
566    fn create_editable_text(
567        tester: &WidgetTester,
568        key: &GlobalKey,
569        text: Option<&str>,
570        selection: Option<TextSelection>,
571    ) -> WidgetRef {
572        let mut app = tester.cell.borrow_mut();
573        let controller = TextEditingController::new(&mut app);
574        let controller = match text {
575            Some(text) => controller.text(&mut app, text),
576            None => controller,
577        };
578        controller.set_selection(
579            &mut app,
580            selection.unwrap_or(TextSelection::collapsed(-1, TextAffinity::Downstream)),
581        );
582        let focus_node = FocusNode::new(&mut app);
583        material_app(
584            ThemeData::new(&app),
585            EditableText::new(
586                controller.erase(),
587                focus_node.erase(),
588                TextStyle::new(),
589                Colors::BLACK,
590                Colors::BLACK,
591            )
592            .key(key.clone().into())
593            .into_widget(),
594        )
595    }
596
597    /// `materialTextSelectionControls.canSelectAll(key.currentState!)`.
598    #[allow(deprecated)]
599    fn can_select_all(tester: &WidgetTester, key: &GlobalKey) -> bool {
600        let app = tester.cell.borrow();
601        let state = key
602            .current_state::<EditableTextState>(&app)
603            .expect("the EditableText is mounted");
604        material_text_selection_controls().can_select_all(&app, state.as_text_selection_delegate())
605    }
606
607    #[test]
608    fn can_select_all_should_return_false_when_there_is_no_text() {
609        test_widgets(|tester| {
610            let key = GlobalKey::new();
611            let root = create_editable_text(tester, &key, None, None);
612            tester.pump_widget(root);
613            assert!(!can_select_all(tester, &key));
614        });
615    }
616
617    #[test]
618    fn can_select_all_should_return_true_when_there_is_text_and_collapsed_selection() {
619        test_widgets(|tester| {
620            let key = GlobalKey::new();
621            let root = create_editable_text(tester, &key, Some("123"), None);
622            tester.pump_widget(root);
623            assert!(can_select_all(tester, &key));
624        });
625    }
626
627    #[test]
628    fn can_select_all_should_return_true_when_there_is_text_and_partial_uncollapsed_selection() {
629        test_widgets(|tester| {
630            let key = GlobalKey::new();
631            let root =
632                create_editable_text(tester, &key, Some("123"), Some(TextSelection::new(1, 2)));
633            tester.pump_widget(root);
634            assert!(can_select_all(tester, &key));
635        });
636    }
637
638    #[test]
639    fn can_select_all_should_return_false_when_there_is_text_and_full_selection() {
640        test_widgets(|tester| {
641            let key = GlobalKey::new();
642            let root =
643                create_editable_text(tester, &key, Some("123"), Some(TextSelection::new(0, 3)));
644            tester.pump_widget(root);
645            assert!(!can_select_all(tester, &key));
646        });
647    }
648
649    #[test]
650    fn material_handles_works_with_3_positional_parameters() {
651        test_widgets(|tester| {
652            let theme = ThemeData::builder()
653                .text_selection_theme(
654                    TextSelectionThemeData::new().selection_handle_color(Color::new(0x550000AA)),
655                )
656                .build(&tester.cell.borrow());
657            tester.pump_widget(
658                Theme::new(
659                    theme,
660                    Builder::new(|app, context| {
661                        Container::new()
662                            .color(Colors::WHITE)
663                            .height(800.0)
664                            .width(800.0)
665                            .child(Padding::new(EdgeInsets::symmetric(0.0, 250.0)).child(
666                                FittedBox::new().child(
667                                    material_text_selection_controls().build_handle(
668                                        app,
669                                        context,
670                                        TextSelectionHandleType::Right,
671                                        10.0,
672                                        None,
673                                    ),
674                                ),
675                            ))
676                            .into_widget()
677                    }),
678                )
679                .into_widget(),
680            );
681
682            // No expect here as this should simply compile / not throw any
683            // exceptions while building.
684        });
685    }
686
687    /// The matrix of the `Transform` that `build_handle` wraps the handle of `handle_type` in,
688    /// if any.
689    fn handle_rotation(
690        tester: &mut WidgetTester,
691        handle_type: TextSelectionHandleType,
692    ) -> Option<waft_embedder::Matrix4> {
693        let theme = ThemeData::new(&tester.cell.borrow());
694        let built = Rc::new(std::cell::RefCell::new(None));
695        let root = {
696            let built = Rc::clone(&built);
697            Theme::new(
698                theme,
699                Builder::new(move |app, context| {
700                    let handle = material_text_selection_controls().build_handle(
701                        app,
702                        context,
703                        handle_type,
704                        10.0,
705                        None,
706                    );
707                    *built.borrow_mut() = Some(Rc::clone(&handle));
708                    handle
709                }),
710            )
711            .into_widget()
712        };
713        tester.pump_widget(root);
714        let handle = built.borrow_mut().take().expect("the handle built");
715        waft_widgets::downcast_widget::<Transform>(&*handle).map(|transform| transform.transform)
716    }
717
718    #[test]
719    fn material_handles_point_up_left_and_turn_by_type() {
720        test_widgets(|tester| {
721            assert_eq!(
722                handle_rotation(tester, TextSelectionHandleType::Left),
723                Some(Transform::rotate(PI / 2.0).transform)
724            );
725            assert_eq!(
726                handle_rotation(tester, TextSelectionHandleType::Right),
727                None
728            );
729            assert_eq!(
730                handle_rotation(tester, TextSelectionHandleType::Collapsed),
731                Some(Transform::rotate(PI / 4.0).transform)
732            );
733        });
734    }
735
736    #[test]
737    fn material_handles_anchor_and_size_by_type() {
738        let controls = MaterialTextSelectionControls::new();
739        assert_eq!(controls.get_handle_size(10.0), Size::new(22.0, 22.0));
740        assert_eq!(
741            controls.get_handle_anchor(TextSelectionHandleType::Collapsed, 10.0),
742            Offset::new(11.0, -4.0)
743        );
744        assert_eq!(
745            controls.get_handle_anchor(TextSelectionHandleType::Left, 10.0),
746            Offset::new(22.0, 0.0)
747        );
748        assert_eq!(
749            controls.get_handle_anchor(TextSelectionHandleType::Right, 10.0),
750            Offset::ZERO
751        );
752    }
753
754    #[test]
755    fn the_handle_painter_fills_a_circle_with_its_top_left_quadrant() {
756        let cell = waft_foundation::AppCell::new();
757        let mut app = cell.borrow_mut();
758        let painter = TextSelectionHandlePainter {
759            color: Color::new(0x550000AA),
760        };
761        let mut canvas = Canvas::new();
762        painter.paint(&mut app, &mut canvas, Size::new(22.0, 22.0));
763        let picture = canvas.build();
764        let ops = waft_embedder::flattened_ops(&picture);
765        assert_eq!(ops.len(), 1, "one path");
766        let waft_embedder::valo::Op::DrawPath { path, paint, .. } = &ops[0] else {
767            panic!("the handle is a path, not {:?}", ops[0]);
768        };
769        assert_eq!(paint.color, Color::new(0x550000AA).into());
770        let bounds = path.bounds();
771        assert_eq!(
772            (bounds.x, bounds.y, bounds.width, bounds.height),
773            (0.0, 0.0, 22.0, 22.0)
774        );
775        // The square fills the corner the circle leaves open.
776        assert!(path.contains((1.0, 1.0).into(), FillRule::NonZero));
777        assert!(!path.contains((21.0, 1.0).into(), FillRule::NonZero));
778        // Where the circle and the square overlap is filled once, with no hole: what Dart's
779        // 'draws transparent handle correctly' golden guards.
780        assert!(path.contains((8.0, 8.0).into(), FillRule::NonZero));
781        assert!(path.contains((15.0, 15.0).into(), FillRule::NonZero));
782    }
783}