Skip to main content

waft_widgets/widgets/
selectable_region.rs

1//! Flutter counterpart: `widgets/selectable_region.dart` (the selection container delegates).
2//!
3//! A delegate owns the [`AnySelectable`]s a [`SelectionContainer`](crate::SelectionContainer)
4//! collects from its subtree and folds their geometries into one, so a region can select across
5//! several texts, or across a scrollable.
6//!
7//! [`MultiSelectableSelectionContainerDelegate`] is Dart's abstract class: a trait with the
8//! class's bodies, over [`MultiSelectableSelectionContainerDelegateData`]. The bodies an override
9//! reaches with `super` live on [`MultiSelectableSelectionContainerDelegateBase`], which every
10//! delegate implements. [`StaticSelectionContainerDelegate`] is the concrete class that remembers
11//! which selectables received the start and end edges and synthesizes the missing one; its
12//! bodies live on [`StaticSelectionContainerDelegateBase`], and
13//! [`PlainStaticSelectionContainerDelegate`] is Dart's instantiable `StaticSelectionContainerDelegate()`.
14//! A subclass implements the trait and writes [`static_selection_container_delegate_overrides!`]
15//! where Dart writes `extends StaticSelectionContainerDelegate`.
16//!
17//! The text and scrollable delegates, and `SelectableRegion` itself, wait for later.
18
19use std::any::TypeId;
20use std::cmp::Ordering;
21use std::collections::{HashMap, HashSet};
22use std::rc::Rc;
23
24use waft_embedder::{
25    AppLifecycleState, Offset, PointerDeviceKind, Rect, TargetPlatform, TextDirection, clamp_double,
26};
27use waft_foundation::{
28    App, ChangeNotifier, ChangeNotifierData, Handle, ListenableObject, Listener,
29    PRECISION_ERROR_TOLERANCE, Ref, ValueChanged, ValueListenable, ValueListenableHandle,
30};
31use waft_gestures::{
32    BaseTapAndDragGestureRecognizer, DragEndDetails, DragStartBehavior, DragStartDetails,
33    DragUpdateDetails, LongPressGestureRecognizer, LongPressMoveUpdateDetails,
34    LongPressStartDetails, TapAndHorizontalDragGestureRecognizer, TapAndPanGestureRecognizer,
35    TapDownDetails, TapDragDownDetails, TapDragEndDetails, TapDragStartDetails, TapDragUpDetails,
36    TapDragUpdateDetails, TapGestureRecognizer, TapStatusTracker,
37};
38use waft_painting::{transform_point, transform_rect};
39use waft_rendering::{
40    AnySelectable, HitTestBehavior, LayerLink, SelectedContent, SelectedContentRange,
41    SelectionEvent, SelectionEventType, SelectionExtendDirection, SelectionGeometry,
42    SelectionHandler, SelectionPoint, SelectionRegistrar, SelectionResult, SelectionStatus,
43    TextGranularity, TextSelectionHandleType, TextSelectionPoint,
44};
45use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
46use waft_services::{
47    Clipboard, ClipboardData, HapticFeedback, HardwareKeyboard, LogicalKeyboardKey,
48    SelectionChangedCause,
49};
50
51use crate::framework::{
52    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
53};
54use crate::widgets::actions::{
55    Action, ActionData, ActionRef, Actions, AnyAction, CallbackAction, ContextAction,
56    DismissIntent, Intent,
57};
58use crate::widgets::basic::CompositedTransformTarget;
59use crate::widgets::context_menu_button_item::{ContextMenuButtonItem, ContextMenuButtonType};
60use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf, FocusNodeRef};
61use crate::widgets::focus_scope::Focus;
62use crate::widgets::gesture_detector::{
63    GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
64    RawGestureDetector,
65};
66use crate::widgets::magnifier::{MagnifierInfo, TextMagnifierConfiguration};
67use crate::widgets::media_query::{MediaQuery, Orientation};
68use crate::widgets::selection_container::{
69    SelectionContainer, SelectionContainerDelegate, SelectionContainerDelegateData,
70};
71use crate::widgets::tap_region::TapRegion;
72use crate::widgets::text_editing_intents::{
73    CopySelectionTextIntent, ExpandSelectionToDocumentBoundaryIntent,
74    ExpandSelectionToLineBreakIntent, ExtendSelectionByCharacterIntent,
75    ExtendSelectionToDocumentBoundaryIntent, ExtendSelectionToLineBreakIntent,
76    ExtendSelectionToNextWordBoundaryIntent,
77    ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
78    ExtendSelectionVerticallyToAdjacentLineIntent, SelectAllTextIntent,
79};
80use crate::widgets::text_selection::{SelectionOverlay, TextSelectionControls};
81use crate::widgets::text_selection_toolbar_anchors::TextSelectionToolbarAnchors;
82
83/// In practice some selectables, such as widget spans, shift several pixels. When the vertical
84/// position difference is within this threshold, the screen order compares horizontally too.
85const K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD: f64 = 3.0;
86
87/// The padding around the [`SelectionContainer`](crate::SelectionContainer) added to the
88/// selection handle drawable area; a handle outside it is hidden.
89const K_SELECTION_HANDLE_DRAWABLE_AREA_PADDING: f64 = 5.0;
90
91/// Dart's `Set<Selectable>`: whether `set` holds `selectable`.
92fn set_contains(set: &[AnySelectable], selectable: AnySelectable) -> bool {
93    set.contains(&selectable)
94}
95
96/// Dart's `Set<Selectable>.add`: whether `selectable` was new.
97fn set_add(set: &mut Vec<AnySelectable>, selectable: AnySelectable) -> bool {
98    if set_contains(set, selectable) {
99        return false;
100    }
101    set.push(selectable);
102    true
103}
104
105/// Dart's `Set<Selectable>.remove`: whether `selectable` was there.
106fn set_remove(set: &mut Vec<AnySelectable>, selectable: AnySelectable) -> bool {
107    let Some(index) = set.iter().position(|held| *held == selectable) else {
108        return false;
109    };
110    set.remove(index);
111    true
112}
113
114/// The listener a delegate registers with each selectable, for Dart's
115/// `_handleSelectableGeometryChange` tear-off.
116fn selectable_geometry_change_listener<T: MultiSelectableSelectionContainerDelegate>(
117    this: Handle<T>,
118) -> Listener {
119    Listener::handle_method(this, notify_selectable_geometry_change::<T>)
120}
121
122/// The body of [`selectable_geometry_change_listener`], as a function item so it keeps the
123/// identity a tear-off has.
124fn notify_selectable_geometry_change<T: MultiSelectableSelectionContainerDelegate>(
125    this: Handle<T>,
126    app: &mut App,
127) {
128    MultiSelectableSelectionContainerDelegateBase::handle_selectable_geometry_change(this, app);
129}
130
131/// The microtask that folds this frame's added selectables in, for Dart's `runScheduledTask`
132/// closure.
133fn scheduled_update_listener<T: MultiSelectableSelectionContainerDelegate>(
134    this: Handle<T>,
135) -> Listener {
136    Listener::handle_method(this, run_scheduled_task_tearoff::<T>)
137}
138
139/// The frame callback that folds this frame's added selectables in.
140fn scheduled_update_frame_callback<T: MultiSelectableSelectionContainerDelegate>(
141    this: Handle<T>,
142) -> FrameCallback {
143    FrameCallback::handle_method(this, post_frame_run_scheduled_task_tearoff::<T>)
144}
145
146/// The body of [`scheduled_update_listener`].
147fn run_scheduled_task_tearoff<T: MultiSelectableSelectionContainerDelegate>(
148    this: Handle<T>,
149    app: &mut App,
150) {
151    MultiSelectableSelectionContainerDelegateBase::run_scheduled_task(this, app);
152}
153
154/// The body of [`scheduled_update_frame_callback`].
155fn post_frame_run_scheduled_task_tearoff<T: MultiSelectableSelectionContainerDelegate>(
156    this: Handle<T>,
157    app: &mut App,
158    _time_stamp: std::time::Duration,
159) {
160    MultiSelectableSelectionContainerDelegateBase::run_scheduled_task(this, app);
161}
162
163// ---------------------------------------------------------------------------------------------
164// MultiSelectableSelectionContainerDelegate
165
166/// The fields of Dart's `MultiSelectableSelectionContainerDelegate`.
167pub struct MultiSelectableSelectionContainerDelegateData {
168    /// The `ChangeNotifier` side of the delegate; `notify_listeners` runs it.
169    pub change_notifier: ChangeNotifierData,
170
171    /// Gets the list of [`AnySelectable`]s this delegate is managing.
172    pub selectables: Vec<AnySelectable>,
173
174    /// The current selectable that contains the selection end edge, or `-1`.
175    pub current_selection_end_index: i32,
176
177    /// The current selectable that contains the selection start edge, or `-1`.
178    pub current_selection_start_index: i32,
179
180    start_handle_layer: Option<Ref<LayerLink>>,
181    start_handle_layer_owner: Option<AnySelectable>,
182    end_handle_layer: Option<Ref<LayerLink>>,
183    end_handle_layer_owner: Option<AnySelectable>,
184
185    /// Whether a selection event is being handled, so a selectable's own change is not folded
186    /// back in before the event has finished.
187    is_handling_selection_event: bool,
188
189    /// Whether an update of the selectables is already scheduled for after this frame.
190    scheduled_selectable_update: bool,
191
192    /// Whether a selection is in progress, which keeps the selectables sorted for the gesture.
193    selection_in_progress: bool,
194
195    /// The selectables added since the last update, in the order they arrived.
196    additions: Vec<AnySelectable>,
197
198    /// Whether a granular or directional extension is in progress, which keeps the selection
199    /// indices where the gesture put them, collapsed selectables included.
200    extend_selection_in_progress: bool,
201
202    selection_geometry: SelectionGeometry,
203}
204
205impl MultiSelectableSelectionContainerDelegateData {
206    /// Creates the delegate's fields, with no selectables and no selection.
207    pub fn new() -> MultiSelectableSelectionContainerDelegateData {
208        MultiSelectableSelectionContainerDelegateData {
209            change_notifier: ChangeNotifierData::new(),
210            selectables: Vec::new(),
211            current_selection_end_index: -1,
212            current_selection_start_index: -1,
213            start_handle_layer: None,
214            start_handle_layer_owner: None,
215            end_handle_layer: None,
216            end_handle_layer_owner: None,
217            is_handling_selection_event: false,
218            scheduled_selectable_update: false,
219            selection_in_progress: false,
220            additions: Vec::new(),
221            extend_selection_in_progress: false,
222            selection_geometry: SelectionGeometry::new(SelectionStatus::None, false),
223        }
224    }
225}
226
227impl Default for MultiSelectableSelectionContainerDelegateData {
228    fn default() -> Self {
229        Self::new()
230    }
231}
232
233/// The accessors [`MultiSelectableSelectionContainerDelegate`] asks for, for a struct whose bag
234/// is the field `multi_selectable_selection_container_delegate`.
235#[macro_export]
236macro_rules! multi_selectable_selection_container_delegate_accessors {
237    () => {
238        fn multi_selectable_selection_container_delegate_data(
239            self: ::waft_foundation::Handle<Self>,
240            app: &::waft_foundation::App,
241        ) -> &$crate::MultiSelectableSelectionContainerDelegateData {
242            &app.get(self).multi_selectable_selection_container_delegate
243        }
244
245        fn multi_selectable_selection_container_delegate_data_mut(
246            self: ::waft_foundation::Handle<Self>,
247            app: &mut ::waft_foundation::App,
248        ) -> &mut $crate::MultiSelectableSelectionContainerDelegateData {
249            &mut app
250                .get_mut(self)
251                .multi_selectable_selection_container_delegate
252        }
253    };
254}
255
256/// A delegate that handles events and updates for multiple [`AnySelectable`] children.
257///
258/// Updates are optimized by tracking which selectables reside on the edges of a selection.
259/// A subclass implements [`ensure_child_updated`](Self::ensure_child_updated) to describe how a
260/// selectable behaves when it is added to a selection.
261pub trait MultiSelectableSelectionContainerDelegate:
262    SelectionContainerDelegate + ChangeNotifier + Sized + 'static
263{
264    /// Dart's `MultiSelectableSelectionContainerDelegate` fields, held under the field
265    /// `multi_selectable_selection_container_delegate`
266    /// ([`multi_selectable_selection_container_delegate_accessors!`](crate::multi_selectable_selection_container_delegate_accessors)).
267    fn multi_selectable_selection_container_delegate_data(
268        self: Handle<Self>,
269        app: &App,
270    ) -> &MultiSelectableSelectionContainerDelegateData;
271
272    /// See [`multi_selectable_selection_container_delegate_data`](Self::multi_selectable_selection_container_delegate_data).
273    fn multi_selectable_selection_container_delegate_data_mut(
274        self: Handle<Self>,
275        app: &mut App,
276    ) -> &mut MultiSelectableSelectionContainerDelegateData;
277
278    /// Notifies this delegate that layout of the container has changed.
279    fn layout_did_change(self: Handle<Self>, app: &mut App) {
280        MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
281    }
282
283    /// Called when this delegate finishes updating the selectables.
284    fn did_change_selectables(self: Handle<Self>, app: &mut App) {
285        MultiSelectableSelectionContainerDelegateBase::did_change_selectables(self, app);
286    }
287
288    /// The combined [`SelectionGeometry`] for child selectables.
289    fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
290        MultiSelectableSelectionContainerDelegateBase::get_selection_geometry(self, app)
291    }
292
293    /// The compare function this delegate uses for the selection order of the selectables.
294    ///
295    /// Defaults to screen order.
296    fn compare_order(
297        self: Handle<Self>,
298        app: &mut App,
299        a: AnySelectable,
300        b: AnySelectable,
301    ) -> Ordering {
302        MultiSelectableSelectionContainerDelegateBase::compare_order(self, app, a, b)
303    }
304
305    /// Selects all contents of all selectables.
306    fn handle_select_all(
307        self: Handle<Self>,
308        app: &mut App,
309        event: &SelectionEvent,
310    ) -> SelectionResult {
311        MultiSelectableSelectionContainerDelegateBase::handle_select_all(self, app, event)
312    }
313
314    /// Selects a word in a selectable at the location the event names.
315    fn handle_select_word(
316        self: Handle<Self>,
317        app: &mut App,
318        event: &SelectionEvent,
319    ) -> SelectionResult {
320        MultiSelectableSelectionContainerDelegateBase::handle_select_word(self, app, event)
321    }
322
323    /// Selects a paragraph in a selectable at the location the event names.
324    fn handle_select_paragraph(
325        self: Handle<Self>,
326        app: &mut App,
327        event: &SelectionEvent,
328    ) -> SelectionResult {
329        MultiSelectableSelectionContainerDelegateBase::handle_select_paragraph(self, app, event)
330    }
331
332    /// Removes the selection of all selectables this delegate manages.
333    fn handle_clear_selection(
334        self: Handle<Self>,
335        app: &mut App,
336        event: &SelectionEvent,
337    ) -> SelectionResult {
338        MultiSelectableSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
339    }
340
341    /// Extends the current selection by a [`waft_rendering::TextGranularity`].
342    fn handle_granularly_extend_selection(
343        self: Handle<Self>,
344        app: &mut App,
345        event: &SelectionEvent,
346    ) -> SelectionResult {
347        MultiSelectableSelectionContainerDelegateBase::handle_granularly_extend_selection(
348            self, app, event,
349        )
350    }
351
352    /// Extends the current selection in a [`SelectionExtendDirection`].
353    fn handle_directionally_extend_selection(
354        self: Handle<Self>,
355        app: &mut App,
356        event: &SelectionEvent,
357    ) -> SelectionResult {
358        MultiSelectableSelectionContainerDelegateBase::handle_directionally_extend_selection(
359            self, app, event,
360        )
361    }
362
363    /// Updates the selection edges.
364    fn handle_selection_edge_update(
365        self: Handle<Self>,
366        app: &mut App,
367        event: &SelectionEvent,
368    ) -> SelectionResult {
369        MultiSelectableSelectionContainerDelegateBase::handle_selection_edge_update(
370            self, app, event,
371        )
372    }
373
374    /// Discards the resources the delegate holds; Dart's `dispose`, as `ChangeNotifier.dispose`
375    /// takes it.
376    fn dispose(self: Handle<Self>, app: &mut App) {
377        MultiSelectableSelectionContainerDelegateBase::dispose(self, app);
378    }
379
380    /// Ensures the selectable child has received an up to date selection event.
381    ///
382    /// This is called when a new selectable is added to the delegate and its screen location
383    /// falls into the previous selection. Subclasses describe how the newly added selectable is
384    /// updated.
385    fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
386
387    /// Dispatches a selection event to one selectable.
388    ///
389    /// Override this method when a subclass needs to generate additional events or treatments
390    /// before sending the [`SelectionEvent`].
391    fn dispatch_selection_event_to_child(
392        self: Handle<Self>,
393        app: &mut App,
394        selectable: AnySelectable,
395        event: &SelectionEvent,
396    ) -> SelectionResult {
397        MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event_to_child(
398            self, app, selectable, event,
399        )
400    }
401}
402
403/// The bodies of Dart's `MultiSelectableSelectionContainerDelegate`, over
404/// [`MultiSelectableSelectionContainerDelegateData`].
405///
406/// Every [`MultiSelectableSelectionContainerDelegate`] implements this, so an override that runs
407/// the inherited body calls it trait-qualified,
408/// `MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable)`, where Dart
409/// writes `super.remove(selectable)`.
410pub trait MultiSelectableSelectionContainerDelegateBase:
411    MultiSelectableSelectionContainerDelegate
412{
413    /// Dart's `MultiSelectableSelectionContainerDelegate.add`: queue the selectable until after
414    /// this frame, when the container has laid it out.
415    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
416        let data = self.multi_selectable_selection_container_delegate_data(app);
417        debug_assert!(!data.selectables.contains(&selectable));
418        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
419        set_add(&mut data.additions, selectable);
420        MultiSelectableSelectionContainerDelegateBase::schedule_selectable_update(self, app);
421    }
422
423    /// Dart's `MultiSelectableSelectionContainerDelegate.remove`.
424    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
425        if set_remove(
426            &mut self
427                .multi_selectable_selection_container_delegate_data_mut(app)
428                .additions,
429            selectable,
430        ) {
431            // The same selectable was added in the same frame and is not yet incorporated into
432            // the selectables; removing it needs no selection geometry update.
433            return;
434        }
435        self.remove_selectable(app, selectable);
436        MultiSelectableSelectionContainerDelegateBase::schedule_selectable_update(self, app);
437    }
438
439    /// Dart's `dispatchSelectionEventToChild`: send the event to the selectable.
440    fn dispatch_selection_event_to_child(
441        self: Handle<Self>,
442        app: &mut App,
443        selectable: AnySelectable,
444        event: &SelectionEvent,
445    ) -> SelectionResult {
446        selectable.dispatch_selection_event(app, event)
447    }
448
449    /// Dart's `_scheduleSelectableUpdate`: one update per frame, on the microtask queue when the
450    /// frame's own callbacks are running so a nested container is updated in the same frame.
451    fn schedule_selectable_update(self: Handle<Self>, app: &mut App) {
452        if self
453            .multi_selectable_selection_container_delegate_data(app)
454            .scheduled_selectable_update
455        {
456            return;
457        }
458        self.multi_selectable_selection_container_delegate_data_mut(app)
459            .scheduled_selectable_update = true;
460        if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PostFrameCallbacks {
461            app.schedule_microtask(scheduled_update_listener(self));
462        } else {
463            SchedulerBinding::add_post_frame_callback(
464                app,
465                scheduled_update_frame_callback(self),
466                None,
467            );
468        }
469    }
470
471    /// Dart's `runScheduledTask`.
472    fn run_scheduled_task(self: Handle<Self>, app: &mut App) {
473        if !self
474            .multi_selectable_selection_container_delegate_data(app)
475            .scheduled_selectable_update
476        {
477            return;
478        }
479        self.multi_selectable_selection_container_delegate_data_mut(app)
480            .scheduled_selectable_update = false;
481        MultiSelectableSelectionContainerDelegateBase::update_selectables(self, app);
482    }
483
484    /// Dart's `_updateSelectables`: fold the selectables added since the last frame in, then let
485    /// the geometry catch up with them.
486    ///
487    /// Dart's first step, removing off-screen selectables, is the registrant's own: a selectable
488    /// with no content removes itself from its registrar.
489    fn update_selectables(self: Handle<Self>, app: &mut App) {
490        if !self
491            .multi_selectable_selection_container_delegate_data(app)
492            .additions
493            .is_empty()
494        {
495            self.flush_additions(app);
496        }
497        MultiSelectableSelectionContainerDelegate::did_change_selectables(self, app);
498    }
499
500    /// Dart's `_flushAdditions`: merge the new selectables into screen order, keeping the
501    /// selection indices on the selectables they named.
502    fn flush_additions(self: Handle<Self>, app: &mut App) {
503        let mut merging_selectables = self
504            .multi_selectable_selection_container_delegate_data(app)
505            .additions
506            .clone();
507        waft_foundation::merge_sort(&mut merging_selectables, |a, b| {
508            MultiSelectableSelectionContainerDelegate::compare_order(self, app, *a, *b)
509        });
510        let existing_selectables = self
511            .multi_selectable_selection_container_delegate_data(app)
512            .selectables
513            .clone();
514        let current_selection_start_index = self
515            .multi_selectable_selection_container_delegate_data(app)
516            .current_selection_start_index;
517        let current_selection_end_index = self
518            .multi_selectable_selection_container_delegate_data(app)
519            .current_selection_end_index;
520        let mut selectables = Vec::new();
521        let mut selection_start_index = current_selection_start_index;
522        let mut selection_end_index = current_selection_end_index;
523        let mut merging_index = 0;
524        let mut existing_index = 0;
525        // Merge two sorted lists.
526        while merging_index < merging_selectables.len()
527            || existing_index < existing_selectables.len()
528        {
529            if merging_index >= merging_selectables.len()
530                || (existing_index < existing_selectables.len()
531                    && MultiSelectableSelectionContainerDelegate::compare_order(
532                        self,
533                        app,
534                        existing_selectables[existing_index],
535                        merging_selectables[merging_index],
536                    ) == Ordering::Less)
537            {
538                if existing_index as i32 == current_selection_start_index {
539                    selection_start_index = selectables.len() as i32;
540                }
541                if existing_index as i32 == current_selection_end_index {
542                    selection_end_index = selectables.len() as i32;
543                }
544                selectables.push(existing_selectables[existing_index]);
545                existing_index += 1;
546                continue;
547            }
548
549            // If the merging selectable falls in the selection range, its selection needs to be
550            // updated.
551            let merging_selectable = merging_selectables[merging_index];
552            if (existing_index as i32)
553                < current_selection_start_index.max(current_selection_end_index)
554                && (existing_index as i32)
555                    > current_selection_start_index.min(current_selection_end_index)
556            {
557                MultiSelectableSelectionContainerDelegate::ensure_child_updated(
558                    self,
559                    app,
560                    merging_selectable,
561                );
562            }
563            merging_selectable.add_listener(app, selectable_geometry_change_listener(self));
564            selectables.push(merging_selectable);
565            merging_index += 1;
566        }
567        debug_assert_eq!(merging_index, merging_selectables.len());
568        debug_assert_eq!(existing_index, existing_selectables.len());
569        debug_assert_eq!(
570            selectables.len(),
571            existing_index + merging_index,
572            "the merged list holds every selectable once"
573        );
574        debug_assert!(
575            selection_start_index >= -1 || (selection_start_index as usize) < selectables.len()
576        );
577        debug_assert!(
578            selection_end_index >= -1 || (selection_end_index as usize) < selectables.len()
579        );
580        // Selection indices should not be set to -1 unless they originally were.
581        debug_assert_eq!(
582            current_selection_start_index == -1,
583            selection_start_index == -1
584        );
585        debug_assert_eq!(current_selection_end_index == -1, selection_end_index == -1);
586        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
587        data.selectables = selectables;
588        data.current_selection_end_index = selection_end_index;
589        data.current_selection_start_index = selection_start_index;
590        data.additions = Vec::new();
591    }
592
593    /// Dart's `_removeSelectable`.
594    fn remove_selectable(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
595        let data = self.multi_selectable_selection_container_delegate_data(app);
596        debug_assert!(
597            data.selectables.contains(&selectable),
598            "The selectable is not in this registrar."
599        );
600        let index = data
601            .selectables
602            .iter()
603            .position(|held| *held == selectable)
604            .expect("checked just now");
605        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
606        data.selectables.remove(index);
607        if index as i32 <= data.current_selection_end_index {
608            data.current_selection_end_index -= 1;
609        }
610        if index as i32 <= data.current_selection_start_index {
611            data.current_selection_start_index -= 1;
612        }
613        selectable.remove_listener(app, &selectable_geometry_change_listener(self));
614    }
615
616    /// Dart's `didChangeSelectables`.
617    fn did_change_selectables(self: Handle<Self>, app: &mut App) {
618        MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
619    }
620
621    /// Dart's `value`: the combined geometry of the selectables.
622    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
623        self.multi_selectable_selection_container_delegate_data(app)
624            .selection_geometry
625            .clone()
626    }
627
628    /// Dart's `_updateSelectionGeometry`: fold the selectables' geometries into `value`, telling
629    /// listeners when it changed, and hand the handles to the selectables on the edges.
630    fn update_selection_geometry(self: Handle<Self>, app: &mut App) {
631        let new_value =
632            MultiSelectableSelectionContainerDelegate::get_selection_geometry(self, app);
633        if self
634            .multi_selectable_selection_container_delegate_data(app)
635            .selection_geometry
636            != new_value
637        {
638            self.multi_selectable_selection_container_delegate_data_mut(app)
639                .selection_geometry = new_value;
640            self.notify_listeners(app);
641        }
642        self.update_handle_layers_and_owners(app);
643    }
644
645    /// Dart's `_handleSelectableGeometryChange`.
646    fn handle_selectable_geometry_change(self: Handle<Self>, app: &mut App) {
647        // Geometries of selectable children may change several times while a selection event is
648        // handled; this delegate's own geometry is updated once the event has finished.
649        if self
650            .multi_selectable_selection_container_delegate_data(app)
651            .is_handling_selection_event
652        {
653            return;
654        }
655        MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
656    }
657
658    /// Dart's `getSelectionGeometry`: one geometry covering the selectables from the start edge
659    /// to the end edge, in the container's coordinates.
660    fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
661        {
662            let data = self.multi_selectable_selection_container_delegate_data(app);
663            if data.current_selection_end_index == -1
664                || data.current_selection_start_index == -1
665                || data.selectables.is_empty()
666            {
667                // There is no valid selection.
668                return SelectionGeometry::new(SelectionStatus::None, !data.selectables.is_empty());
669            }
670            if !data.extend_selection_in_progress {
671                let start = self.adjust_selection_index_based_on_selection_geometry(
672                    app,
673                    data.current_selection_start_index,
674                    data.current_selection_end_index,
675                );
676                let end = self.adjust_selection_index_based_on_selection_geometry(
677                    app,
678                    data.current_selection_end_index,
679                    start,
680                );
681                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
682                data.current_selection_start_index = start;
683                data.current_selection_end_index = end;
684            }
685        }
686        let start_index = self
687            .multi_selectable_selection_container_delegate_data(app)
688            .current_selection_start_index;
689        let end_index = self
690            .multi_selectable_selection_container_delegate_data(app)
691            .current_selection_end_index;
692        let selectables = self
693            .multi_selectable_selection_container_delegate_data(app)
694            .selectables
695            .clone();
696        let forward_selection = end_index >= start_index;
697
698        // Need to find a non-null start selection point.
699        let mut start_geometry = selectables[start_index as usize].value(app);
700        let mut start_index_walker = start_index;
701        while start_index_walker != end_index && start_geometry.start_selection_point.is_none() {
702            start_index_walker += if forward_selection { 1 } else { -1 };
703            start_geometry = selectables[start_index_walker as usize].value(app);
704        }
705        let start_point = start_geometry.start_selection_point.and_then(|point| {
706            let transform = self.get_transform_from(app, selectables[start_index_walker as usize]);
707            let start = transform_point(&transform, point.local_position);
708            // It can be NaN if it is detached or off-screen.
709            start
710                .is_finite()
711                .then(|| SelectionPoint::new(start, point.line_height, point.handle_type))
712        });
713
714        // Need to find a non-null end selection point.
715        let mut end_geometry = selectables[end_index as usize].value(app);
716        let mut end_index_walker = end_index;
717        while end_index_walker != start_index && end_geometry.end_selection_point.is_none() {
718            end_index_walker += if forward_selection { -1 } else { 1 };
719            end_geometry = selectables[end_index_walker as usize].value(app);
720        }
721        let end_point = end_geometry.end_selection_point.and_then(|point| {
722            let transform = self.get_transform_from(app, selectables[end_index_walker as usize]);
723            let end = transform_point(&transform, point.local_position);
724            // It can be NaN if it is detached or off-screen.
725            end.is_finite()
726                .then(|| SelectionPoint::new(end, point.line_height, point.handle_type))
727        });
728
729        // Need to collect selection rects from the selectables from the start index to the end
730        // index; a reverse selection gives none, as Dart's ascending loop does.
731        let mut selection_rects = Vec::new();
732        let drawable_area = if self.has_size(app) {
733            let size = self.container_size(app);
734            Some(Rect::from_ltrb(0.0, 0.0, size.width(), size.height()))
735        } else {
736            None
737        };
738        for index in start_index..=end_index {
739            let selectable = selectables[index as usize];
740            let transform = self.get_transform_from(app, selectable);
741            for selection_rect in selectable.value(app).selection_rects {
742                let local_rect = transform_rect(&transform, selection_rect);
743                let within_drawable_area =
744                    drawable_area.map_or(local_rect, |area| area.intersect(local_rect));
745                if within_drawable_area.is_finite() && !within_drawable_area.is_empty() {
746                    selection_rects.push(within_drawable_area);
747                }
748            }
749        }
750
751        SelectionGeometry {
752            start_selection_point: start_point,
753            end_selection_point: end_point,
754            selection_rects,
755            status: if start_geometry != end_geometry {
756                SelectionStatus::Uncollapsed
757            } else {
758                start_geometry.status
759            },
760            // Would have at least one selectable child.
761            has_content: true,
762        }
763    }
764
765    /// Dart's `_adjustSelectionIndexBasedOnSelectionGeometry`: the current edge index may point
766    /// at a selectable whose own selection is collapsed at its edge, so move it toward the
767    /// opposite edge to one with a selection.
768    fn adjust_selection_index_based_on_selection_geometry(
769        self: Handle<Self>,
770        app: &App,
771        current_index: i32,
772        toward_index: i32,
773    ) -> i32 {
774        let forward = toward_index > current_index;
775        let mut index = current_index;
776        while index != toward_index {
777            let selectable = self
778                .multi_selectable_selection_container_delegate_data(app)
779                .selectables[index as usize];
780            if selectable.value(app).status == SelectionStatus::Uncollapsed {
781                break;
782            }
783            index += if forward { 1 } else { -1 };
784        }
785        index
786    }
787
788    /// Dart's `compareOrder`: the default is screen order.
789    fn compare_order(
790        self: Handle<Self>,
791        app: &mut App,
792        a: AnySelectable,
793        b: AnySelectable,
794    ) -> Ordering {
795        let rect_a = transform_rect(
796            &a.get_transform_to(app, None),
797            self.get_bounding_box(app, a),
798        );
799        let rect_b = transform_rect(
800            &b.get_transform_to(app, None),
801            self.get_bounding_box(app, b),
802        );
803        let result = compare_vertically(rect_a, rect_b);
804        if result != Ordering::Equal {
805            return result;
806        }
807        compare_horizontally(rect_a, rect_b)
808    }
809
810    /// Dart's `_getBoundingBox`: every bounding box of the selectable, unioned.
811    fn get_bounding_box(self: Handle<Self>, app: &mut App, selectable: AnySelectable) -> Rect {
812        let mut boxes = selectable.bounding_boxes(app).into_iter();
813        let mut result = boxes.next().expect("a selectable has a bounding box");
814        for other in boxes {
815            result = result.expand_to_include(other);
816        }
817        result
818    }
819
820    /// Dart's `pushHandleLayers`.
821    fn push_handle_layers(
822        self: Handle<Self>,
823        app: &mut App,
824        start_handle: Option<Ref<LayerLink>>,
825        end_handle: Option<Ref<LayerLink>>,
826    ) {
827        {
828            let data = self.multi_selectable_selection_container_delegate_data(app);
829            if data.start_handle_layer == start_handle && data.end_handle_layer == end_handle {
830                return;
831            }
832        }
833        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
834        data.start_handle_layer = start_handle;
835        data.end_handle_layer = end_handle;
836        self.update_handle_layers_and_owners(app);
837    }
838
839    /// Dart's `_updateHandleLayersAndOwners`: hand both handle layers to the selectables that
840    /// hold the selection edges, hiding a handle outside the container's drawable area.
841    fn update_handle_layers_and_owners(self: Handle<Self>, app: &mut App) {
842        let start_layer = self
843            .multi_selectable_selection_container_delegate_data(app)
844            .start_handle_layer
845            .clone();
846        let end_layer = self
847            .multi_selectable_selection_container_delegate_data(app)
848            .end_handle_layer
849            .clone();
850        let mut effective_start_handle = start_layer.clone();
851        let mut effective_end_handle = end_layer.clone();
852        if effective_start_handle.is_some() || effective_end_handle.is_some() {
853            let drawable_area = if self.has_size(app) {
854                let size = self.container_size(app);
855                Some(
856                    Rect::from_ltrb(0.0, 0.0, size.width(), size.height())
857                        .inflate(K_SELECTION_HANDLE_DRAWABLE_AREA_PADDING),
858                )
859            } else {
860                None
861            };
862            let value = SelectionHandler::value(self, app);
863            let hide_start_handle = value.start_selection_point.is_none()
864                || drawable_area.is_none()
865                || !drawable_area.expect("checked just now").contains(
866                    value
867                        .start_selection_point
868                        .expect("checked just now")
869                        .local_position,
870                );
871            let hide_end_handle = value.end_selection_point.is_none()
872                || drawable_area.is_none()
873                || !drawable_area.expect("checked just now").contains(
874                    value
875                        .end_selection_point
876                        .expect("checked just now")
877                        .local_position,
878                );
879            effective_start_handle = if hide_start_handle { None } else { start_layer };
880            effective_end_handle = if hide_end_handle { None } else { end_layer };
881        }
882        let start_index = self
883            .multi_selectable_selection_container_delegate_data(app)
884            .current_selection_start_index;
885        let end_index = self
886            .multi_selectable_selection_container_delegate_data(app)
887            .current_selection_end_index;
888        if start_index == -1 || end_index == -1 {
889            // No valid selection.
890            let start_owner = self
891                .multi_selectable_selection_container_delegate_data_mut(app)
892                .start_handle_layer_owner
893                .take();
894            if let Some(owner) = start_owner {
895                owner.push_handle_layers(app, None, None);
896            }
897            let end_owner = self
898                .multi_selectable_selection_container_delegate_data_mut(app)
899                .end_handle_layer_owner
900                .take();
901            if let Some(owner) = end_owner {
902                owner.push_handle_layers(app, None, None);
903            }
904            return;
905        }
906        let selectables = self
907            .multi_selectable_selection_container_delegate_data(app)
908            .selectables
909            .clone();
910        let start_selectable = selectables[start_index as usize];
911        let end_selectable = selectables[end_index as usize];
912        if self
913            .multi_selectable_selection_container_delegate_data(app)
914            .start_handle_layer_owner
915            != Some(start_selectable)
916            && let Some(owner) = self
917                .multi_selectable_selection_container_delegate_data(app)
918                .start_handle_layer_owner
919        {
920            owner.push_handle_layers(app, None, None);
921        }
922        if self
923            .multi_selectable_selection_container_delegate_data(app)
924            .end_handle_layer_owner
925            != Some(end_selectable)
926            && let Some(owner) = self
927                .multi_selectable_selection_container_delegate_data(app)
928                .end_handle_layer_owner
929        {
930            owner.push_handle_layers(app, None, None);
931        }
932        {
933            let data = self.multi_selectable_selection_container_delegate_data_mut(app);
934            data.start_handle_layer_owner = Some(start_selectable);
935            if start_index == end_index {
936                // The selection edges are on the same selectable.
937                data.end_handle_layer_owner = Some(start_selectable);
938            } else {
939                data.end_handle_layer_owner = Some(end_selectable);
940            }
941        }
942        if start_index == end_index {
943            start_selectable.push_handle_layers(app, effective_start_handle, effective_end_handle);
944            return;
945        }
946        start_selectable.push_handle_layers(app, effective_start_handle, None);
947        end_selectable.push_handle_layers(app, None, effective_end_handle);
948    }
949
950    /// Dart's `getSelectedContent`: the selected contents of all selectables, concatenated.
951    fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
952        let selectables = self
953            .multi_selectable_selection_container_delegate_data(app)
954            .selectables
955            .clone();
956        let selections: Vec<SelectedContent> = selectables
957            .iter()
958            .filter_map(|selectable| selectable.selected_content(app))
959            .collect();
960        if selections.is_empty() {
961            return None;
962        }
963        let mut plain_text = String::new();
964        for selection in selections {
965            plain_text.push_str(&selection.plain_text);
966        }
967        Some(SelectedContent::new(plain_text))
968    }
969
970    /// Dart's `contentLength`: the sum of every selectable's content length.
971    fn content_length(self: Handle<Self>, app: &App) -> usize {
972        self.multi_selectable_selection_container_delegate_data(app)
973            .selectables
974            .iter()
975            .map(|selectable| selectable.content_length(app))
976            .sum()
977    }
978
979    /// Dart's `getSelection`: the selection range across the selectables, in content offsets.
980    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
981        let selectables = self
982            .multi_selectable_selection_container_delegate_data(app)
983            .selectables
984            .clone();
985        let selections: Vec<(usize, Option<SelectedContentRange>)> = selectables
986            .iter()
987            .map(|selectable| (selectable.content_length(app), selectable.selection(app)))
988            .collect();
989        self.calculate_local_range(app, &selections)
990    }
991
992    /// Dart's `_calculateLocalRange`: the range the selectables' own ranges make up, offset by
993    /// the content before them.
994    fn calculate_local_range(
995        self: Handle<Self>,
996        app: &App,
997        selections: &[(usize, Option<SelectedContentRange>)],
998    ) -> Option<SelectedContentRange> {
999        let data = self.multi_selectable_selection_container_delegate_data(app);
1000        if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
1001            return None;
1002        }
1003        let mut start_offset = 0i32;
1004        let mut end_offset = 0i32;
1005        let mut found_start = false;
1006        let mut forward_selection =
1007            data.current_selection_end_index >= data.current_selection_start_index;
1008        if data.current_selection_end_index == data.current_selection_start_index {
1009            // Determining the selection direction is inaccurate when the two edges share a
1010            // selectable; the range within it is the source of truth.
1011            let range_at_selectable_in_selection = data.selectables
1012                [data.current_selection_start_index as usize]
1013                .selection(app)
1014                .expect("the selectable holding both edges has a selection");
1015            forward_selection = range_at_selectable_in_selection.end_offset
1016                >= range_at_selectable_in_selection.start_offset;
1017        }
1018        for (content_length, range) in selections {
1019            let Some(range) = range else {
1020                if found_start {
1021                    return Some(SelectedContentRange::new(
1022                        if forward_selection {
1023                            start_offset
1024                        } else {
1025                            end_offset
1026                        },
1027                        if forward_selection {
1028                            end_offset
1029                        } else {
1030                            start_offset
1031                        },
1032                    ));
1033                }
1034                start_offset += *content_length as i32;
1035                end_offset = start_offset;
1036                continue;
1037            };
1038            let selection_start_normalized = range.start_offset.min(range.end_offset);
1039            let selection_end_normalized = range.start_offset.max(range.end_offset);
1040            if !found_start {
1041                start_offset += selection_start_normalized;
1042                end_offset =
1043                    start_offset + (selection_end_normalized - selection_start_normalized).abs();
1044                found_start = true;
1045            } else {
1046                end_offset += (selection_end_normalized - selection_start_normalized).abs();
1047            }
1048        }
1049        debug_assert!(
1050            found_start,
1051            "The start of the selection has not been found despite this selection delegate \
1052             having an existing currentSelectionStartIndex and currentSelectionEndIndex."
1053        );
1054        Some(SelectedContentRange::new(
1055            if forward_selection {
1056                start_offset
1057            } else {
1058                end_offset
1059            },
1060            if forward_selection {
1061                end_offset
1062            } else {
1063                start_offset
1064            },
1065        ))
1066    }
1067
1068    /// Dart's `_flushInactiveSelections`: clear the selection of every selectable outside the
1069    /// edges, or of every selectable but the one edge that exists.
1070    fn flush_inactive_selections(self: Handle<Self>, app: &mut App) {
1071        let start_index = self
1072            .multi_selectable_selection_container_delegate_data(app)
1073            .current_selection_start_index;
1074        let end_index = self
1075            .multi_selectable_selection_container_delegate_data(app)
1076            .current_selection_end_index;
1077        if start_index == -1 && end_index == -1 {
1078            return;
1079        }
1080        if start_index == -1 || end_index == -1 {
1081            let skip_index = if start_index == -1 {
1082                end_index
1083            } else {
1084                start_index
1085            };
1086            self.clear_selectables(app, Some(skip_index));
1087            return;
1088        }
1089        let skip_start = start_index.min(end_index);
1090        let skip_end = start_index.max(end_index);
1091        let selectables = self
1092            .multi_selectable_selection_container_delegate_data(app)
1093            .selectables
1094            .clone();
1095        for (index, selectable) in selectables.iter().enumerate() {
1096            if (index as i32) >= skip_start && (index as i32) <= skip_end {
1097                continue;
1098            }
1099            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1100                self,
1101                app,
1102                *selectable,
1103                &SelectionEvent::Clear,
1104            );
1105        }
1106    }
1107
1108    /// Dart's `handleSelectAll`: select every selectable.
1109    fn handle_select_all(
1110        self: Handle<Self>,
1111        app: &mut App,
1112        event: &SelectionEvent,
1113    ) -> SelectionResult {
1114        let selectables = self
1115            .multi_selectable_selection_container_delegate_data(app)
1116            .selectables
1117            .clone();
1118        for selectable in &selectables {
1119            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1120                self,
1121                app,
1122                *selectable,
1123                event,
1124            );
1125        }
1126        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1127        data.current_selection_start_index = 0;
1128        data.current_selection_end_index = selectables.len() as i32 - 1;
1129        SelectionResult::None
1130    }
1131
1132    /// Dart's `_clearSelectables`: clear the selection of every selectable but `skip_index`.
1133    fn clear_selectables(self: Handle<Self>, app: &mut App, skip_index: Option<i32>) {
1134        let selectables = self
1135            .multi_selectable_selection_container_delegate_data(app)
1136            .selectables
1137            .clone();
1138        for (index, selectable) in selectables.iter().enumerate() {
1139            if Some(index as i32) == skip_index {
1140                continue;
1141            }
1142            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1143                self,
1144                app,
1145                *selectable,
1146                &SelectionEvent::Clear,
1147            );
1148        }
1149    }
1150
1151    /// Dart's `_handleSelectBoundary`: the word or paragraph at the event's position, in the
1152    /// selectable under it, or the nearest one when no bounding box contains it.
1153    fn handle_select_boundary(
1154        self: Handle<Self>,
1155        app: &mut App,
1156        event: &SelectionEvent,
1157    ) -> SelectionResult {
1158        debug_assert!(
1159            matches!(
1160                event,
1161                SelectionEvent::SelectWord { .. } | SelectionEvent::SelectParagraph { .. }
1162            ),
1163            "This method should only be given selection events that select text boundaries."
1164        );
1165        let effective_global_position = match event {
1166            SelectionEvent::SelectWord { global_position } => *global_position,
1167            SelectionEvent::SelectParagraph {
1168                global_position, ..
1169            } => *global_position,
1170            _ => panic!("Unsupported selection event"),
1171        };
1172        let selectables = self
1173            .multi_selectable_selection_container_delegate_data(app)
1174            .selectables
1175            .clone();
1176        let mut last_selection_result: Option<SelectionResult> = None;
1177        // For tracking the nearest index if no bounding box contains the position.
1178        let mut min_distance_squared = f64::INFINITY;
1179        let mut nearest_index = 0usize;
1180        for index in 0..selectables.len() {
1181            let mut global_rects_contain_position = false;
1182            let transform = selectables[index].get_transform_to(app, None);
1183            for rect in selectables[index].bounding_boxes(app) {
1184                let global_rect = transform_rect(&transform, rect);
1185                if global_rect.contains(effective_global_position) {
1186                    global_rects_contain_position = true;
1187                    break;
1188                }
1189                let dx = effective_global_position.dx()
1190                    - clamp_double(
1191                        effective_global_position.dx(),
1192                        global_rect.left,
1193                        global_rect.right,
1194                    );
1195                let dy = effective_global_position.dy()
1196                    - clamp_double(
1197                        effective_global_position.dy(),
1198                        global_rect.top,
1199                        global_rect.bottom,
1200                    );
1201                let distance_squared = dx * dx + dy * dy;
1202                if distance_squared < min_distance_squared {
1203                    min_distance_squared = distance_squared;
1204                    nearest_index = index;
1205                }
1206            }
1207            if global_rects_contain_position {
1208                let existing_geometry = selectables[index].value(app);
1209                last_selection_result = Some(
1210                    MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1211                        self,
1212                        app,
1213                        selectables[index],
1214                        event,
1215                    ),
1216                );
1217                let result = last_selection_result.expect("assigned just now");
1218                if index == selectables.len() - 1 && result == SelectionResult::Next {
1219                    return SelectionResult::Next;
1220                }
1221                if result == SelectionResult::Next {
1222                    continue;
1223                }
1224                if index == 0 && result == SelectionResult::Previous {
1225                    return SelectionResult::Previous;
1226                }
1227                if selectables[index].value(app) != existing_geometry {
1228                    // The geometry has changed as a result of selecting a boundary; clear the
1229                    // other selectables to keep the selection in sync.
1230                    self.clear_selectables(app, Some(index as i32));
1231                    let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1232                    data.current_selection_start_index = index as i32;
1233                    data.current_selection_end_index = index as i32;
1234                }
1235                return SelectionResult::End;
1236            } else if last_selection_result == Some(SelectionResult::Next) {
1237                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1238                data.current_selection_start_index = index as i32 - 1;
1239                data.current_selection_end_index = index as i32 - 1;
1240                return SelectionResult::End;
1241            }
1242        }
1243        debug_assert!(last_selection_result.is_none());
1244        // No selectable's bounding box contained the position. Clamp to the nearest selectable
1245        // so that the boundary selection event always produces a valid selection.
1246        if !selectables.is_empty() {
1247            let existing_geometry = selectables[nearest_index].value(app);
1248            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1249                self,
1250                app,
1251                selectables[nearest_index],
1252                event,
1253            );
1254            if selectables[nearest_index].value(app) != existing_geometry {
1255                // The geometry has changed as a result of selecting a boundary; clear the other
1256                // selectables to keep the selection in sync.
1257                self.clear_selectables(app, Some(nearest_index as i32));
1258                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1259                data.current_selection_start_index = nearest_index as i32;
1260                data.current_selection_end_index = nearest_index as i32;
1261            }
1262        }
1263        SelectionResult::End
1264    }
1265
1266    /// Dart's `handleSelectWord`.
1267    fn handle_select_word(
1268        self: Handle<Self>,
1269        app: &mut App,
1270        event: &SelectionEvent,
1271    ) -> SelectionResult {
1272        self.handle_select_boundary(app, event)
1273    }
1274
1275    /// Dart's `handleSelectParagraph`.
1276    fn handle_select_paragraph(
1277        self: Handle<Self>,
1278        app: &mut App,
1279        event: &SelectionEvent,
1280    ) -> SelectionResult {
1281        self.handle_select_boundary(app, event)
1282    }
1283
1284    /// Dart's `handleClearSelection`: clear the selection of every selectable.
1285    fn handle_clear_selection(
1286        self: Handle<Self>,
1287        app: &mut App,
1288        event: &SelectionEvent,
1289    ) -> SelectionResult {
1290        let selectables = self
1291            .multi_selectable_selection_container_delegate_data(app)
1292            .selectables
1293            .clone();
1294        for selectable in &selectables {
1295            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1296                self,
1297                app,
1298                *selectable,
1299                event,
1300            );
1301        }
1302        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1303        data.current_selection_end_index = -1;
1304        data.current_selection_start_index = -1;
1305        SelectionResult::None
1306    }
1307
1308    /// Dart's `handleGranularlyExtendSelection`.
1309    fn handle_granularly_extend_selection(
1310        self: Handle<Self>,
1311        app: &mut App,
1312        event: &SelectionEvent,
1313    ) -> SelectionResult {
1314        let SelectionEvent::GranularlyExtendSelection {
1315            forward, is_end, ..
1316        } = event
1317        else {
1318            panic!("a granular extension event updates the selection");
1319        };
1320        let (forward, is_end) = (*forward, *is_end);
1321        self.assert_selection_indices_agree(app);
1322        let selectables = self
1323            .multi_selectable_selection_container_delegate_data(app)
1324            .selectables
1325            .clone();
1326        if self
1327            .multi_selectable_selection_container_delegate_data(app)
1328            .current_selection_start_index
1329            == -1
1330        {
1331            let index = if forward {
1332                0
1333            } else {
1334                selectables.len() as i32 - 1
1335            };
1336            let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1337            data.current_selection_start_index = index;
1338            data.current_selection_end_index = index;
1339        }
1340        let mut target_index = {
1341            let data = self.multi_selectable_selection_container_delegate_data(app);
1342            if is_end {
1343                data.current_selection_end_index
1344            } else {
1345                data.current_selection_start_index
1346            }
1347        };
1348        let mut result =
1349            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1350                self,
1351                app,
1352                selectables[target_index as usize],
1353                event,
1354            );
1355        if forward {
1356            debug_assert_ne!(result, SelectionResult::Previous);
1357            while (target_index as usize) < selectables.len() - 1 && result == SelectionResult::Next
1358            {
1359                target_index += 1;
1360                result =
1361                    MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1362                        self,
1363                        app,
1364                        selectables[target_index as usize],
1365                        event,
1366                    );
1367                debug_assert_ne!(result, SelectionResult::Previous);
1368            }
1369        } else {
1370            debug_assert_ne!(result, SelectionResult::Next);
1371            while target_index > 0 && result == SelectionResult::Previous {
1372                target_index -= 1;
1373                result =
1374                    MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1375                        self,
1376                        app,
1377                        selectables[target_index as usize],
1378                        event,
1379                    );
1380                debug_assert_ne!(result, SelectionResult::Next);
1381            }
1382        }
1383        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1384        if is_end {
1385            data.current_selection_end_index = target_index;
1386        } else {
1387            data.current_selection_start_index = target_index;
1388        }
1389        result
1390    }
1391
1392    /// Dart's `handleDirectionallyExtendSelection`.
1393    fn handle_directionally_extend_selection(
1394        self: Handle<Self>,
1395        app: &mut App,
1396        event: &SelectionEvent,
1397    ) -> SelectionResult {
1398        let SelectionEvent::DirectionallyExtendSelection {
1399            is_end, direction, ..
1400        } = event
1401        else {
1402            panic!("a directional extension event updates the selection");
1403        };
1404        let (is_end, direction) = (*is_end, *direction);
1405        self.assert_selection_indices_agree(app);
1406        let selectables = self
1407            .multi_selectable_selection_container_delegate_data(app)
1408            .selectables
1409            .clone();
1410        if self
1411            .multi_selectable_selection_container_delegate_data(app)
1412            .current_selection_start_index
1413            == -1
1414        {
1415            let index = match direction {
1416                SelectionExtendDirection::PreviousLine | SelectionExtendDirection::Backward => {
1417                    selectables.len() as i32 - 1
1418                }
1419                SelectionExtendDirection::NextLine | SelectionExtendDirection::Forward => 0,
1420            };
1421            let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1422            data.current_selection_start_index = index;
1423            data.current_selection_end_index = index;
1424        }
1425        let mut target_index = {
1426            let data = self.multi_selectable_selection_container_delegate_data(app);
1427            if is_end {
1428                data.current_selection_end_index
1429            } else {
1430                data.current_selection_start_index
1431            }
1432        };
1433        let mut result =
1434            MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1435                self,
1436                app,
1437                selectables[target_index as usize],
1438                event,
1439            );
1440        match direction {
1441            SelectionExtendDirection::PreviousLine => {
1442                debug_assert!(
1443                    result == SelectionResult::End || result == SelectionResult::Previous
1444                );
1445                if result == SelectionResult::Previous && target_index > 0 {
1446                    target_index -= 1;
1447                    result = MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(self,
1448                        app,
1449                        selectables[target_index as usize],
1450                        &event.copy_with(None, None, Some(SelectionExtendDirection::Backward)),
1451                    );
1452                    debug_assert_eq!(result, SelectionResult::End);
1453                }
1454            }
1455            SelectionExtendDirection::NextLine => {
1456                debug_assert!(result == SelectionResult::End || result == SelectionResult::Next);
1457                if result == SelectionResult::Next
1458                    && (target_index as usize) < selectables.len() - 1
1459                {
1460                    target_index += 1;
1461                    result = MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(self,
1462                        app,
1463                        selectables[target_index as usize],
1464                        &event.copy_with(None, None, Some(SelectionExtendDirection::Forward)),
1465                    );
1466                    debug_assert_eq!(result, SelectionResult::End);
1467                }
1468            }
1469            SelectionExtendDirection::Forward | SelectionExtendDirection::Backward => {
1470                debug_assert_eq!(result, SelectionResult::End);
1471            }
1472        }
1473        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1474        if is_end {
1475            data.current_selection_end_index = target_index;
1476        } else {
1477            data.current_selection_start_index = target_index;
1478        }
1479        result
1480    }
1481
1482    /// Dart's `assert((currentSelectionStartIndex == -1) == (currentSelectionEndIndex == -1))`,
1483    /// as a debug check.
1484    fn assert_selection_indices_agree(self: Handle<Self>, app: &App) {
1485        let data = self.multi_selectable_selection_container_delegate_data(app);
1486        debug_assert_eq!(
1487            data.current_selection_start_index == -1,
1488            data.current_selection_end_index == -1,
1489            "both selection edges exist, or neither does"
1490        );
1491    }
1492
1493    /// Dart's `handleSelectionEdgeUpdate`: start the selection when the edge is new, and move it
1494    /// across the selectables otherwise.
1495    fn handle_selection_edge_update(
1496        self: Handle<Self>,
1497        app: &mut App,
1498        event: &SelectionEvent,
1499    ) -> SelectionResult {
1500        let is_end = event.ty() == SelectionEventType::EndEdgeUpdate;
1501        let edge_index = {
1502            let data = self.multi_selectable_selection_container_delegate_data(app);
1503            if is_end {
1504                data.current_selection_end_index
1505            } else {
1506                data.current_selection_start_index
1507            }
1508        };
1509        if edge_index == -1 {
1510            self.init_selection(app, event, is_end)
1511        } else {
1512            self.adjust_selection(app, event, is_end)
1513        }
1514    }
1515
1516    /// Dart's `_initSelection`: find the selectable that contains the new edge, sweeping from
1517    /// the opposite edge when it exists.
1518    fn init_selection(
1519        self: Handle<Self>,
1520        app: &mut App,
1521        event: &SelectionEvent,
1522        is_end: bool,
1523    ) -> SelectionResult {
1524        let selectables = self
1525            .multi_selectable_selection_container_delegate_data(app)
1526            .selectables
1527            .clone();
1528        let opposite_edge_index = {
1529            let data = self.multi_selectable_selection_container_delegate_data(app);
1530            if is_end {
1531                data.current_selection_start_index
1532            } else {
1533                data.current_selection_end_index
1534            }
1535        };
1536        let mut new_index: i32 = -1;
1537        let mut has_found_edge_index = false;
1538        let mut result: Option<SelectionResult> = None;
1539        let mut forward: Option<bool> = None;
1540        let mut index = opposite_edge_index.max(0);
1541        while index >= 0 && (index as usize) < selectables.len() {
1542            let child = selectables[index as usize];
1543            let child_result =
1544                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1545                    self, app, child, event,
1546                );
1547            match child_result {
1548                SelectionResult::Next => {
1549                    if forward == Some(false) {
1550                        has_found_edge_index = true;
1551                        result = Some(SelectionResult::End);
1552                    } else {
1553                        forward = Some(true);
1554                        new_index = index;
1555                    }
1556                }
1557                SelectionResult::None => new_index = index,
1558                SelectionResult::End => {
1559                    new_index = index;
1560                    result = Some(SelectionResult::End);
1561                    has_found_edge_index = true;
1562                }
1563                SelectionResult::Previous => {
1564                    if index == 0 {
1565                        has_found_edge_index = true;
1566                        new_index = 0;
1567                        result = Some(SelectionResult::Previous);
1568                    } else if forward == Some(true) {
1569                        has_found_edge_index = true;
1570                        result = Some(SelectionResult::End);
1571                    } else {
1572                        forward = Some(false);
1573                        new_index = index;
1574                    }
1575                }
1576                SelectionResult::Pending => {
1577                    new_index = index;
1578                    result = Some(SelectionResult::Pending);
1579                    has_found_edge_index = true;
1580                }
1581            }
1582            if has_found_edge_index {
1583                break;
1584            }
1585            index += if forward.unwrap_or(true) { 1 } else { -1 };
1586        }
1587
1588        if new_index == -1 {
1589            debug_assert!(selectables.is_empty());
1590            return SelectionResult::None;
1591        }
1592        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1593        if is_end {
1594            data.current_selection_end_index = new_index;
1595        } else {
1596            data.current_selection_start_index = new_index;
1597        }
1598        self.flush_inactive_selections(app);
1599        // The result can only be absent if the loop went through the whole list without any
1600        // selectable answering end or previous; the caller then finds the next selectable.
1601        result.unwrap_or(SelectionResult::Next)
1602    }
1603
1604    /// Dart's `_adjustSelection`: move an edge that already has a selectable, searching from the
1605    /// opposite edge when the current one is out of the viewport.
1606    fn adjust_selection(
1607        self: Handle<Self>,
1608        app: &mut App,
1609        event: &SelectionEvent,
1610        is_end: bool,
1611    ) -> SelectionResult {
1612        let selectables = self
1613            .multi_selectable_selection_container_delegate_data(app)
1614            .selectables
1615            .clone();
1616        let value = self
1617            .multi_selectable_selection_container_delegate_data(app)
1618            .selection_geometry
1619            .clone();
1620        let is_current_edge_within_viewport = if is_end {
1621            value.end_selection_point.is_some()
1622        } else {
1623            value.start_selection_point.is_some()
1624        };
1625        let is_opposite_edge_within_viewport = if is_end {
1626            value.start_selection_point.is_some()
1627        } else {
1628            value.end_selection_point.is_some()
1629        };
1630        let data = self.multi_selectable_selection_container_delegate_data(app);
1631        let mut new_index: i32 = if is_end {
1632            if is_current_edge_within_viewport {
1633                data.current_selection_end_index
1634            } else if is_opposite_edge_within_viewport {
1635                data.current_selection_start_index
1636            } else {
1637                0
1638            }
1639        } else if is_current_edge_within_viewport {
1640            data.current_selection_start_index
1641        } else if is_opposite_edge_within_viewport {
1642            data.current_selection_end_index
1643        } else {
1644            0
1645        };
1646        debug_assert!(new_index < selectables.len() as i32 && new_index >= 0);
1647        let mut final_result: Option<SelectionResult> = None;
1648        let mut forward: Option<bool> = None;
1649        // This loop sends the event to one of the following to determine the direction of the
1650        // search: the current edge's selectable if it is in the viewport, the opposite edge's
1651        // when it is not, and the first one when neither is.
1652        while (new_index as usize) < selectables.len() && new_index >= 0 && final_result.is_none() {
1653            let current_selectable_result =
1654                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
1655                    self,
1656                    app,
1657                    selectables[new_index as usize],
1658                    event,
1659                );
1660            match current_selectable_result {
1661                SelectionResult::End | SelectionResult::Pending | SelectionResult::None => {
1662                    final_result = Some(current_selectable_result);
1663                }
1664                SelectionResult::Next => {
1665                    if forward == Some(false) {
1666                        new_index += 1;
1667                        final_result = Some(SelectionResult::End);
1668                    } else if new_index as usize == selectables.len() - 1 {
1669                        final_result = Some(current_selectable_result);
1670                    } else {
1671                        forward = Some(true);
1672                        new_index += 1;
1673                    }
1674                }
1675                SelectionResult::Previous => {
1676                    if forward == Some(true) {
1677                        new_index -= 1;
1678                        final_result = Some(SelectionResult::End);
1679                    } else if new_index == 0 {
1680                        final_result = Some(current_selectable_result);
1681                    } else {
1682                        forward = Some(false);
1683                        new_index -= 1;
1684                    }
1685                }
1686            }
1687        }
1688        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1689        if is_end {
1690            data.current_selection_end_index = new_index;
1691        } else {
1692            data.current_selection_start_index = new_index;
1693        }
1694        self.flush_inactive_selections(app);
1695        final_result.expect("the loop answered a result")
1696    }
1697
1698    /// Dart's `dispatchSelectionEvent`: hand the event to the handler its type names, keeping
1699    /// the selectables in screen order while a selection is in progress.
1700    fn dispatch_selection_event(
1701        self: Handle<Self>,
1702        app: &mut App,
1703        event: &SelectionEvent,
1704    ) -> SelectionResult {
1705        let selection_will_be_in_progress = event.ty() != SelectionEventType::Clear;
1706        let was_in_progress = self
1707            .multi_selectable_selection_container_delegate_data(app)
1708            .selection_in_progress;
1709        if !was_in_progress && selection_will_be_in_progress {
1710            // Sort the selectables every time a selection starts.
1711            let mut selectables = self
1712                .multi_selectable_selection_container_delegate_data(app)
1713                .selectables
1714                .clone();
1715            waft_foundation::merge_sort(&mut selectables, |a, b| {
1716                MultiSelectableSelectionContainerDelegate::compare_order(self, app, *a, *b)
1717            });
1718            self.multi_selectable_selection_container_delegate_data_mut(app)
1719                .selectables = selectables;
1720        }
1721        self.multi_selectable_selection_container_delegate_data_mut(app)
1722            .selection_in_progress = selection_will_be_in_progress;
1723        self.multi_selectable_selection_container_delegate_data_mut(app)
1724            .is_handling_selection_event = true;
1725        let result = match event.ty() {
1726            SelectionEventType::StartEdgeUpdate | SelectionEventType::EndEdgeUpdate => {
1727                self.set_extend_selection_in_progress(app, false);
1728                MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
1729                    self, app, event,
1730                )
1731            }
1732            SelectionEventType::Clear => {
1733                self.set_extend_selection_in_progress(app, false);
1734                MultiSelectableSelectionContainerDelegate::handle_clear_selection(self, app, event)
1735            }
1736            SelectionEventType::SelectAll => {
1737                self.set_extend_selection_in_progress(app, false);
1738                MultiSelectableSelectionContainerDelegate::handle_select_all(self, app, event)
1739            }
1740            SelectionEventType::SelectWord => {
1741                self.set_extend_selection_in_progress(app, false);
1742                MultiSelectableSelectionContainerDelegate::handle_select_word(self, app, event)
1743            }
1744            SelectionEventType::SelectParagraph => {
1745                self.set_extend_selection_in_progress(app, false);
1746                MultiSelectableSelectionContainerDelegate::handle_select_paragraph(self, app, event)
1747            }
1748            SelectionEventType::GranularlyExtendSelection => {
1749                self.set_extend_selection_in_progress(app, true);
1750                MultiSelectableSelectionContainerDelegate::handle_granularly_extend_selection(
1751                    self, app, event,
1752                )
1753            }
1754            SelectionEventType::DirectionallyExtendSelection => {
1755                self.set_extend_selection_in_progress(app, true);
1756                MultiSelectableSelectionContainerDelegate::handle_directionally_extend_selection(
1757                    self, app, event,
1758                )
1759            }
1760        };
1761        self.multi_selectable_selection_container_delegate_data_mut(app)
1762            .is_handling_selection_event = false;
1763        MultiSelectableSelectionContainerDelegateBase::update_selection_geometry(self, app);
1764        result
1765    }
1766
1767    /// Dart's `_extendSelectionInProgress =`.
1768    fn set_extend_selection_in_progress(self: Handle<Self>, app: &mut App, value: bool) {
1769        self.multi_selectable_selection_container_delegate_data_mut(app)
1770            .extend_selection_in_progress = value;
1771    }
1772
1773    /// Dart's `dispose`: stop listening to the selectables, forget them, and dispose the
1774    /// `ChangeNotifier`.
1775    fn dispose(self: Handle<Self>, app: &mut App) {
1776        let selectables = self
1777            .multi_selectable_selection_container_delegate_data(app)
1778            .selectables
1779            .clone();
1780        for selectable in &selectables {
1781            selectable.remove_listener(app, &selectable_geometry_change_listener(self));
1782        }
1783        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
1784        data.selectables = Vec::new();
1785        data.scheduled_selectable_update = false;
1786        ChangeNotifierData::dispose(app, self);
1787    }
1788}
1789
1790/// Dart's `_compareVertically`: two rectangles in screen order by their vertical positions only,
1791/// equal when one cannot be placed above the other within the threshold.
1792pub(crate) fn compare_vertically(a: Rect, b: Rect) -> Ordering {
1793    // A selectable a sliver no longer paints, such as a kept-alive child with a selection, has
1794    // a zero transform. Dart's `transformRect` turns that into NaN, whose comparisons make it
1795    // sort before the others; `transform_rect` here keeps the infinities, which would sort it
1796    // last, so it is put before them here.
1797    if !a.is_finite() || !b.is_finite() {
1798        return Ordering::Less;
1799    }
1800    if (a.top - b.top < K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD
1801        && a.bottom - b.bottom > -K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD)
1802        || (b.top - a.top < K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD
1803            && b.bottom - a.bottom > -K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD)
1804    {
1805        return Ordering::Equal;
1806    }
1807    if (a.top - b.top).abs() > K_SELECTABLE_VERTICAL_COMPARING_THRESHOLD {
1808        return if a.top > b.top {
1809            Ordering::Greater
1810        } else {
1811            Ordering::Less
1812        };
1813    }
1814    if a.bottom > b.bottom {
1815        Ordering::Greater
1816    } else {
1817        Ordering::Less
1818    }
1819}
1820
1821/// Dart's `_compareHorizontally`: two rectangles in screen order by their horizontal positions,
1822/// assuming one encloses the other vertically.
1823pub(crate) fn compare_horizontally(a: Rect, b: Rect) -> Ordering {
1824    // a encloses b.
1825    if a.left - b.left < PRECISION_ERROR_TOLERANCE && a.right - b.right > -PRECISION_ERROR_TOLERANCE
1826    {
1827        return Ordering::Less;
1828    }
1829    // b encloses a.
1830    if b.left - a.left < PRECISION_ERROR_TOLERANCE && b.right - a.right > -PRECISION_ERROR_TOLERANCE
1831    {
1832        return Ordering::Greater;
1833    }
1834    if (a.left - b.left).abs() > PRECISION_ERROR_TOLERANCE {
1835        return if a.left > b.left {
1836            Ordering::Greater
1837        } else {
1838            Ordering::Less
1839        };
1840    }
1841    if a.right > b.right {
1842        Ordering::Greater
1843    } else {
1844        Ordering::Less
1845    }
1846}
1847
1848// ---------------------------------------------------------------------------------------------
1849// StaticSelectionContainerDelegate
1850
1851/// The fields of Dart's `StaticSelectionContainerDelegate`.
1852pub struct StaticSelectionContainerDelegateData {
1853    /// The selectables that have received start events.
1854    has_received_start_event: Vec<AnySelectable>,
1855
1856    /// The selectables that have received end events.
1857    has_received_end_event: Vec<AnySelectable>,
1858
1859    /// The global position of the last selection start edge update.
1860    last_start_edge_update_global_position: Option<Offset>,
1861
1862    /// The global position of the last selection end edge update.
1863    last_end_edge_update_global_position: Option<Offset>,
1864}
1865
1866impl StaticSelectionContainerDelegateData {
1867    /// Creates the delegate's fields, with no selectable marked and no edge update seen.
1868    pub fn new() -> StaticSelectionContainerDelegateData {
1869        StaticSelectionContainerDelegateData {
1870            has_received_start_event: Vec::new(),
1871            has_received_end_event: Vec::new(),
1872            last_start_edge_update_global_position: None,
1873            last_end_edge_update_global_position: None,
1874        }
1875    }
1876}
1877
1878impl Default for StaticSelectionContainerDelegateData {
1879    fn default() -> Self {
1880        Self::new()
1881    }
1882}
1883
1884/// The accessors [`StaticSelectionContainerDelegate`] asks for, for a struct whose bag is the
1885/// field `static_selection_container_delegate`.
1886#[macro_export]
1887macro_rules! static_selection_container_delegate_accessors {
1888    () => {
1889        fn static_selection_container_delegate_data(
1890            self: ::waft_foundation::Handle<Self>,
1891            app: &::waft_foundation::App,
1892        ) -> &$crate::StaticSelectionContainerDelegateData {
1893            &app.get(self).static_selection_container_delegate
1894        }
1895
1896        fn static_selection_container_delegate_data_mut(
1897            self: ::waft_foundation::Handle<Self>,
1898            app: &mut ::waft_foundation::App,
1899        ) -> &mut $crate::StaticSelectionContainerDelegateData {
1900            &mut app.get_mut(self).static_selection_container_delegate
1901        }
1902    };
1903}
1904
1905/// A delegate that handles selection events for selectables of more than one kind, remembering
1906/// which edge each one has already received so a child that comes into the selection is brought
1907/// up to date with a synthesized event.
1908pub trait StaticSelectionContainerDelegate: MultiSelectableSelectionContainerDelegate {
1909    /// Dart's `StaticSelectionContainerDelegate` fields, held under the field
1910    /// `static_selection_container_delegate`
1911    /// ([`static_selection_container_delegate_accessors!`](crate::static_selection_container_delegate_accessors)).
1912    fn static_selection_container_delegate_data(
1913        self: Handle<Self>,
1914        app: &App,
1915    ) -> &StaticSelectionContainerDelegateData;
1916
1917    /// See [`static_selection_container_delegate_data`](Self::static_selection_container_delegate_data).
1918    fn static_selection_container_delegate_data_mut(
1919        self: Handle<Self>,
1920        app: &mut App,
1921    ) -> &mut StaticSelectionContainerDelegateData;
1922
1923    /// Tracks whether a selection edge update event for `selectable` was received.
1924    ///
1925    /// With `for_end` `Some(true)` the selectable is registered as having received an end event,
1926    /// with `Some(false)` a start event, and with `None` both.
1927    ///
1928    /// Call this when a [`SelectionEvent`] is dispatched to a child selectable managed by this
1929    /// delegate.
1930    fn did_receive_selection_event_for(
1931        self: Handle<Self>,
1932        app: &mut App,
1933        selectable: AnySelectable,
1934        for_end: Option<bool>,
1935    ) {
1936        StaticSelectionContainerDelegateBase::did_receive_selection_event_for(
1937            self, app, selectable, for_end,
1938        );
1939    }
1940
1941    /// Updates the internal selection state after a [`SelectionEvent`] that selects a boundary,
1942    /// such as select-word, select-paragraph and select-all.
1943    fn did_receive_selection_boundary_events(self: Handle<Self>, app: &mut App) {
1944        StaticSelectionContainerDelegateBase::did_receive_selection_boundary_events(self, app);
1945    }
1946
1947    /// Updates the last selection edge location of the edge `for_end` names.
1948    fn update_last_selection_edge_location(
1949        self: Handle<Self>,
1950        app: &mut App,
1951        global_selection_edge_location: Offset,
1952        for_end: bool,
1953    ) {
1954        StaticSelectionContainerDelegateBase::update_last_selection_edge_location(
1955            self,
1956            app,
1957            global_selection_edge_location,
1958            for_end,
1959        );
1960    }
1961
1962    /// Clears the internal selection state: no selectable under this delegate has received a
1963    /// start or end event, and no edge location is remembered.
1964    fn clear_internal_selection_state(self: Handle<Self>, app: &mut App) {
1965        StaticSelectionContainerDelegateBase::clear_internal_selection_state(self, app);
1966    }
1967
1968    /// Clears the internal selection state of `selectable`.
1969    fn clear_internal_selection_state_for_selectable(
1970        self: Handle<Self>,
1971        app: &mut App,
1972        selectable: AnySelectable,
1973    ) {
1974        StaticSelectionContainerDelegateBase::clear_internal_selection_state_for_selectable(
1975            self, app, selectable,
1976        );
1977    }
1978}
1979
1980/// The `SelectionHandler` a leaf of [`StaticSelectionContainerDelegate`] that keeps Static's
1981/// selection handling writes inside `impl SelectionHandler for MyDelegate`.
1982#[macro_export]
1983macro_rules! static_selection_container_delegate_selection_handler {
1984    () => {
1985        fn value(
1986            self: ::waft_foundation::Handle<Self>,
1987            app: &::waft_foundation::App,
1988        ) -> ::waft_rendering::SelectionGeometry {
1989            $crate::StaticSelectionContainerDelegateBase::value(self, app)
1990        }
1991
1992        fn push_handle_layers(
1993            self: ::waft_foundation::Handle<Self>,
1994            app: &mut ::waft_foundation::App,
1995            start_handle: ::std::option::Option<
1996                ::waft_foundation::Ref<::waft_rendering::LayerLink>,
1997            >,
1998            end_handle: ::std::option::Option<::waft_foundation::Ref<::waft_rendering::LayerLink>>,
1999        ) {
2000            $crate::StaticSelectionContainerDelegateBase::push_handle_layers(
2001                self,
2002                app,
2003                start_handle,
2004                end_handle,
2005            )
2006        }
2007
2008        fn selected_content(
2009            self: ::waft_foundation::Handle<Self>,
2010            app: &::waft_foundation::App,
2011        ) -> ::std::option::Option<::waft_rendering::SelectedContent> {
2012            $crate::StaticSelectionContainerDelegateBase::selected_content(self, app)
2013        }
2014
2015        fn selection(
2016            self: ::waft_foundation::Handle<Self>,
2017            app: &::waft_foundation::App,
2018        ) -> ::std::option::Option<::waft_rendering::SelectedContentRange> {
2019            $crate::StaticSelectionContainerDelegateBase::selection(self, app)
2020        }
2021
2022        fn dispatch_selection_event(
2023            self: ::waft_foundation::Handle<Self>,
2024            app: &mut ::waft_foundation::App,
2025            event: &::waft_rendering::SelectionEvent,
2026        ) -> ::waft_rendering::SelectionResult {
2027            $crate::StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
2028        }
2029
2030        fn content_length(
2031            self: ::waft_foundation::Handle<Self>,
2032            app: &::waft_foundation::App,
2033        ) -> usize {
2034            $crate::StaticSelectionContainerDelegateBase::content_length(self, app)
2035        }
2036    };
2037}
2038
2039/// The `SelectionRegistrar` a leaf of [`StaticSelectionContainerDelegate`] writes inside
2040/// `impl SelectionRegistrar for MyDelegate`.
2041#[macro_export]
2042macro_rules! static_selection_container_delegate_selection_registrar {
2043    () => {
2044        fn add(
2045            self: ::waft_foundation::Handle<Self>,
2046            app: &mut ::waft_foundation::App,
2047            selectable: ::waft_rendering::AnySelectable,
2048        ) {
2049            $crate::StaticSelectionContainerDelegateBase::add(self, app, selectable)
2050        }
2051
2052        fn remove(
2053            self: ::waft_foundation::Handle<Self>,
2054            app: &mut ::waft_foundation::App,
2055            selectable: ::waft_rendering::AnySelectable,
2056        ) {
2057            $crate::StaticSelectionContainerDelegateBase::remove(self, app, selectable)
2058        }
2059    };
2060}
2061
2062/// The overrides a [`StaticSelectionContainerDelegate`] leaf keeps from the class: the members
2063/// Static handles itself. Write it inside
2064/// `impl MultiSelectableSelectionContainerDelegate for MyDelegate { .. }`, beside
2065/// [`multi_selectable_selection_container_delegate_accessors!`](crate::multi_selectable_selection_container_delegate_accessors).
2066///
2067/// A subclass that changes one of them writes its own method instead and calls
2068/// [`StaticSelectionContainerDelegateBase`] for the inherited body.
2069#[macro_export]
2070macro_rules! static_selection_container_delegate_overrides {
2071    () => {
2072        fn did_change_selectables(
2073            self: ::waft_foundation::Handle<Self>,
2074            app: &mut ::waft_foundation::App,
2075        ) {
2076            $crate::StaticSelectionContainerDelegateBase::did_change_selectables(self, app)
2077        }
2078
2079        fn handle_select_all(
2080            self: ::waft_foundation::Handle<Self>,
2081            app: &mut ::waft_foundation::App,
2082            event: &::waft_rendering::SelectionEvent,
2083        ) -> ::waft_rendering::SelectionResult {
2084            $crate::StaticSelectionContainerDelegateBase::handle_select_all(self, app, event)
2085        }
2086
2087        fn handle_select_word(
2088            self: ::waft_foundation::Handle<Self>,
2089            app: &mut ::waft_foundation::App,
2090            event: &::waft_rendering::SelectionEvent,
2091        ) -> ::waft_rendering::SelectionResult {
2092            $crate::StaticSelectionContainerDelegateBase::handle_select_word(self, app, event)
2093        }
2094
2095        fn handle_select_paragraph(
2096            self: ::waft_foundation::Handle<Self>,
2097            app: &mut ::waft_foundation::App,
2098            event: &::waft_rendering::SelectionEvent,
2099        ) -> ::waft_rendering::SelectionResult {
2100            $crate::StaticSelectionContainerDelegateBase::handle_select_paragraph(self, app, event)
2101        }
2102
2103        fn handle_clear_selection(
2104            self: ::waft_foundation::Handle<Self>,
2105            app: &mut ::waft_foundation::App,
2106            event: &::waft_rendering::SelectionEvent,
2107        ) -> ::waft_rendering::SelectionResult {
2108            $crate::StaticSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
2109        }
2110
2111        fn handle_selection_edge_update(
2112            self: ::waft_foundation::Handle<Self>,
2113            app: &mut ::waft_foundation::App,
2114            event: &::waft_rendering::SelectionEvent,
2115        ) -> ::waft_rendering::SelectionResult {
2116            $crate::StaticSelectionContainerDelegateBase::handle_selection_edge_update(
2117                self, app, event,
2118            )
2119        }
2120
2121        fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
2122            $crate::StaticSelectionContainerDelegateBase::dispose(self, app)
2123        }
2124
2125        fn ensure_child_updated(
2126            self: ::waft_foundation::Handle<Self>,
2127            app: &mut ::waft_foundation::App,
2128            selectable: ::waft_rendering::AnySelectable,
2129        ) {
2130            $crate::StaticSelectionContainerDelegateBase::ensure_child_updated(
2131                self, app, selectable,
2132            )
2133        }
2134
2135        fn dispatch_selection_event_to_child(
2136            self: ::waft_foundation::Handle<Self>,
2137            app: &mut ::waft_foundation::App,
2138            selectable: ::waft_rendering::AnySelectable,
2139            event: &::waft_rendering::SelectionEvent,
2140        ) -> ::waft_rendering::SelectionResult {
2141            $crate::StaticSelectionContainerDelegateBase::dispatch_selection_event_to_child(
2142                self, app, selectable, event,
2143            )
2144        }
2145    };
2146}
2147
2148/// The bodies of Dart's `StaticSelectionContainerDelegate`.
2149///
2150/// Every [`StaticSelectionContainerDelegate`] implements this, so an override that runs the
2151/// inherited body calls it trait-qualified,
2152/// `StaticSelectionContainerDelegateBase::handle_select_all(self, app, event)`, where Dart
2153/// writes `super.handleSelectAll(event)`.
2154pub trait StaticSelectionContainerDelegateBase: StaticSelectionContainerDelegate {
2155    /// Dart's `getSelectedContent`, inherited.
2156    fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
2157        MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
2158    }
2159
2160    /// Dart's `value`, inherited.
2161    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
2162        MultiSelectableSelectionContainerDelegateBase::value(self, app)
2163    }
2164
2165    /// Dart's `pushHandleLayers`, inherited.
2166    fn push_handle_layers(
2167        self: Handle<Self>,
2168        app: &mut App,
2169        start_handle: Option<Ref<LayerLink>>,
2170        end_handle: Option<Ref<LayerLink>>,
2171    ) {
2172        MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
2173            self,
2174            app,
2175            start_handle,
2176            end_handle,
2177        );
2178    }
2179
2180    /// Dart's `getSelection`, inherited.
2181    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
2182        MultiSelectableSelectionContainerDelegateBase::selection(self, app)
2183    }
2184
2185    /// Dart's `dispatchSelectionEvent`, inherited.
2186    fn dispatch_selection_event(
2187        self: Handle<Self>,
2188        app: &mut App,
2189        event: &SelectionEvent,
2190    ) -> SelectionResult {
2191        MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
2192    }
2193
2194    /// Dart's `contentLength`, inherited.
2195    fn content_length(self: Handle<Self>, app: &App) -> usize {
2196        MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
2197    }
2198
2199    /// Dart's `add`, inherited.
2200    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
2201        MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
2202    }
2203
2204    /// Dart's `StaticSelectionContainerDelegate.remove`.
2205    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
2206        StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
2207            self, app, selectable,
2208        );
2209        MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
2210    }
2211
2212    /// Dart's `didReceiveSelectionEventFor`.
2213    fn did_receive_selection_event_for(
2214        self: Handle<Self>,
2215        app: &mut App,
2216        selectable: AnySelectable,
2217        for_end: Option<bool>,
2218    ) {
2219        let data = self.static_selection_container_delegate_data_mut(app);
2220        match for_end {
2221            Some(true) => {
2222                set_add(&mut data.has_received_end_event, selectable);
2223            }
2224            Some(false) => {
2225                set_add(&mut data.has_received_start_event, selectable);
2226            }
2227            None => {
2228                set_add(&mut data.has_received_start_event, selectable);
2229                set_add(&mut data.has_received_end_event, selectable);
2230            }
2231        }
2232    }
2233
2234    /// Dart's `didReceiveSelectionBoundaryEvents`.
2235    fn did_receive_selection_boundary_events(self: Handle<Self>, app: &mut App) {
2236        let data = self.multi_selectable_selection_container_delegate_data(app);
2237        if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
2238            return;
2239        }
2240        let start = data
2241            .current_selection_start_index
2242            .min(data.current_selection_end_index);
2243        let end = data
2244            .current_selection_start_index
2245            .max(data.current_selection_end_index);
2246        let selectables = data.selectables.clone();
2247        for index in start..=end {
2248            StaticSelectionContainerDelegate::did_receive_selection_event_for(
2249                self,
2250                app,
2251                selectables[index as usize],
2252                None,
2253            );
2254        }
2255        self.update_last_selection_edge_locations_from_geometries(app);
2256    }
2257
2258    /// Dart's `updateLastSelectionEdgeLocation`.
2259    fn update_last_selection_edge_location(
2260        self: Handle<Self>,
2261        app: &mut App,
2262        global_selection_edge_location: Offset,
2263        for_end: bool,
2264    ) {
2265        let data = self.static_selection_container_delegate_data_mut(app);
2266        if for_end {
2267            data.last_end_edge_update_global_position = Some(global_selection_edge_location);
2268        } else {
2269            data.last_start_edge_update_global_position = Some(global_selection_edge_location);
2270        }
2271    }
2272
2273    /// Dart's `_updateLastSelectionEdgeLocationsFromGeometries`.
2274    fn update_last_selection_edge_locations_from_geometries(self: Handle<Self>, app: &mut App) {
2275        let data = self.multi_selectable_selection_container_delegate_data(app);
2276        let start_index = data.current_selection_start_index;
2277        let end_index = data.current_selection_end_index;
2278        let selectables = data.selectables.clone();
2279        if start_index != -1 && selectables[start_index as usize].value(app).has_selection() {
2280            let start = selectables[start_index as usize];
2281            let point = start
2282                .value(app)
2283                .start_selection_point
2284                .expect("a selectable with a selection has a start point");
2285            let local_start_edge =
2286                point.local_position + Offset::new(0.0, -point.line_height / 2.0);
2287            let global_start_edge =
2288                transform_point(&start.get_transform_to(app, None), local_start_edge);
2289            StaticSelectionContainerDelegate::update_last_selection_edge_location(
2290                self,
2291                app,
2292                global_start_edge,
2293                false,
2294            );
2295        }
2296        if end_index != -1 && selectables[end_index as usize].value(app).has_selection() {
2297            let end = selectables[end_index as usize];
2298            let point = end
2299                .value(app)
2300                .end_selection_point
2301                .expect("a selectable with a selection has an end point");
2302            let local_end_edge = point.local_position + Offset::new(0.0, -point.line_height / 2.0);
2303            let global_end_edge = transform_point(&end.get_transform_to(app, None), local_end_edge);
2304            StaticSelectionContainerDelegate::update_last_selection_edge_location(
2305                self,
2306                app,
2307                global_end_edge,
2308                true,
2309            );
2310        }
2311    }
2312
2313    /// Dart's `clearInternalSelectionState`.
2314    fn clear_internal_selection_state(self: Handle<Self>, app: &mut App) {
2315        let selectables = self
2316            .multi_selectable_selection_container_delegate_data(app)
2317            .selectables
2318            .clone();
2319        for selectable in &selectables {
2320            StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
2321                self,
2322                app,
2323                *selectable,
2324            );
2325        }
2326        let data = self.static_selection_container_delegate_data_mut(app);
2327        data.last_start_edge_update_global_position = None;
2328        data.last_end_edge_update_global_position = None;
2329    }
2330
2331    /// Dart's `clearInternalSelectionStateForSelectable`.
2332    fn clear_internal_selection_state_for_selectable(
2333        self: Handle<Self>,
2334        app: &mut App,
2335        selectable: AnySelectable,
2336    ) {
2337        let data = self.static_selection_container_delegate_data_mut(app);
2338        set_remove(&mut data.has_received_start_event, selectable);
2339        set_remove(&mut data.has_received_end_event, selectable);
2340    }
2341
2342    /// Dart's `handleSelectAll`.
2343    fn handle_select_all(
2344        self: Handle<Self>,
2345        app: &mut App,
2346        event: &SelectionEvent,
2347    ) -> SelectionResult {
2348        let result =
2349            MultiSelectableSelectionContainerDelegateBase::handle_select_all(self, app, event);
2350        StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
2351        result
2352    }
2353
2354    /// Dart's `handleSelectWord`.
2355    fn handle_select_word(
2356        self: Handle<Self>,
2357        app: &mut App,
2358        event: &SelectionEvent,
2359    ) -> SelectionResult {
2360        let result =
2361            MultiSelectableSelectionContainerDelegateBase::handle_select_word(self, app, event);
2362        StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
2363        result
2364    }
2365
2366    /// Dart's `handleSelectParagraph`.
2367    fn handle_select_paragraph(
2368        self: Handle<Self>,
2369        app: &mut App,
2370        event: &SelectionEvent,
2371    ) -> SelectionResult {
2372        let result = MultiSelectableSelectionContainerDelegateBase::handle_select_paragraph(
2373            self, app, event,
2374        );
2375        StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
2376        result
2377    }
2378
2379    /// Dart's `handleClearSelection`.
2380    fn handle_clear_selection(
2381        self: Handle<Self>,
2382        app: &mut App,
2383        event: &SelectionEvent,
2384    ) -> SelectionResult {
2385        let result =
2386            MultiSelectableSelectionContainerDelegateBase::handle_clear_selection(self, app, event);
2387        StaticSelectionContainerDelegate::clear_internal_selection_state(self, app);
2388        result
2389    }
2390
2391    /// Dart's `handleSelectionEdgeUpdate`.
2392    fn handle_selection_edge_update(
2393        self: Handle<Self>,
2394        app: &mut App,
2395        event: &SelectionEvent,
2396    ) -> SelectionResult {
2397        let (global_position, for_end) = match event {
2398            SelectionEvent::StartEdgeUpdate {
2399                global_position, ..
2400            } => (*global_position, false),
2401            SelectionEvent::EndEdgeUpdate {
2402                global_position, ..
2403            } => (*global_position, true),
2404            _ => panic!("a selection edge update names an edge"),
2405        };
2406        StaticSelectionContainerDelegate::update_last_selection_edge_location(
2407            self,
2408            app,
2409            global_position,
2410            for_end,
2411        );
2412        MultiSelectableSelectionContainerDelegateBase::handle_selection_edge_update(
2413            self, app, event,
2414        )
2415    }
2416
2417    /// Dart's `dispose`.
2418    fn dispose(self: Handle<Self>, app: &mut App) {
2419        StaticSelectionContainerDelegate::clear_internal_selection_state(self, app);
2420        MultiSelectableSelectionContainerDelegateBase::dispose(self, app);
2421    }
2422
2423    /// Dart's `dispatchSelectionEventToChild`: mark the edge the child is about to receive, and
2424    /// bring it up to date, before sending the event on.
2425    fn dispatch_selection_event_to_child(
2426        self: Handle<Self>,
2427        app: &mut App,
2428        selectable: AnySelectable,
2429        event: &SelectionEvent,
2430    ) -> SelectionResult {
2431        match event.ty() {
2432            SelectionEventType::StartEdgeUpdate => {
2433                StaticSelectionContainerDelegate::did_receive_selection_event_for(
2434                    self,
2435                    app,
2436                    selectable,
2437                    Some(false),
2438                );
2439                MultiSelectableSelectionContainerDelegate::ensure_child_updated(
2440                    self, app, selectable,
2441                );
2442            }
2443            SelectionEventType::EndEdgeUpdate => {
2444                StaticSelectionContainerDelegate::did_receive_selection_event_for(
2445                    self,
2446                    app,
2447                    selectable,
2448                    Some(true),
2449                );
2450                MultiSelectableSelectionContainerDelegate::ensure_child_updated(
2451                    self, app, selectable,
2452                );
2453            }
2454            SelectionEventType::Clear => {
2455                StaticSelectionContainerDelegate::clear_internal_selection_state_for_selectable(
2456                    self, app, selectable,
2457                );
2458            }
2459            SelectionEventType::SelectAll
2460            | SelectionEventType::SelectWord
2461            | SelectionEventType::SelectParagraph => {}
2462            SelectionEventType::GranularlyExtendSelection
2463            | SelectionEventType::DirectionallyExtendSelection => {
2464                StaticSelectionContainerDelegate::did_receive_selection_event_for(
2465                    self, app, selectable, None,
2466                );
2467                MultiSelectableSelectionContainerDelegate::ensure_child_updated(
2468                    self, app, selectable,
2469                );
2470            }
2471        }
2472        MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event_to_child(
2473            self, app, selectable, event,
2474        )
2475    }
2476
2477    /// Dart's `ensureChildUpdated`: synthesize the edge event the child has not seen, from the
2478    /// last edge location, so a selectable added inside the selection is selected at once.
2479    fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
2480        let last_end = self
2481            .static_selection_container_delegate_data(app)
2482            .last_end_edge_update_global_position;
2483        if let Some(global_position) = last_end
2484            && set_add(
2485                &mut self
2486                    .static_selection_container_delegate_data_mut(app)
2487                    .has_received_end_event,
2488                selectable,
2489            )
2490        {
2491            let synthesized_event = SelectionEvent::for_end(global_position, None);
2492            if self
2493                .multi_selectable_selection_container_delegate_data(app)
2494                .current_selection_end_index
2495                == -1
2496            {
2497                MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
2498                    self,
2499                    app,
2500                    &synthesized_event,
2501                );
2502            }
2503            selectable.dispatch_selection_event(app, &synthesized_event);
2504        }
2505        let last_start = self
2506            .static_selection_container_delegate_data(app)
2507            .last_start_edge_update_global_position;
2508        if let Some(global_position) = last_start
2509            && set_add(
2510                &mut self
2511                    .static_selection_container_delegate_data_mut(app)
2512                    .has_received_start_event,
2513                selectable,
2514            )
2515        {
2516            let synthesized_event = SelectionEvent::for_start(global_position, None);
2517            if self
2518                .multi_selectable_selection_container_delegate_data(app)
2519                .current_selection_start_index
2520                == -1
2521            {
2522                MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
2523                    self,
2524                    app,
2525                    &synthesized_event,
2526                );
2527            }
2528            selectable.dispatch_selection_event(app, &synthesized_event);
2529        }
2530    }
2531
2532    /// Dart's `didChangeSelectables`: replay the last edge updates over the new list, then drop
2533    /// the selectables that are gone from the edge bookkeeping.
2534    fn did_change_selectables(self: Handle<Self>, app: &mut App) {
2535        let last_end = self
2536            .static_selection_container_delegate_data(app)
2537            .last_end_edge_update_global_position;
2538        if let Some(global_position) = last_end {
2539            MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
2540                self,
2541                app,
2542                &SelectionEvent::for_end(global_position, None),
2543            );
2544        }
2545        let last_start = self
2546            .static_selection_container_delegate_data(app)
2547            .last_start_edge_update_global_position;
2548        if let Some(global_position) = last_start {
2549            MultiSelectableSelectionContainerDelegate::handle_selection_edge_update(
2550                self,
2551                app,
2552                &SelectionEvent::for_start(global_position, None),
2553            );
2554        }
2555        let selectable_set = self
2556            .multi_selectable_selection_container_delegate_data(app)
2557            .selectables
2558            .clone();
2559        let data = self.static_selection_container_delegate_data_mut(app);
2560        data.has_received_end_event
2561            .retain(|selectable| set_contains(&selectable_set, *selectable));
2562        data.has_received_start_event
2563            .retain(|selectable| set_contains(&selectable_set, *selectable));
2564        MultiSelectableSelectionContainerDelegateBase::did_change_selectables(self, app);
2565    }
2566}
2567
2568impl<T: StaticSelectionContainerDelegate> StaticSelectionContainerDelegateBase for T {}
2569
2570/// Dart's instantiable `StaticSelectionContainerDelegate()`.
2571///
2572/// A delegate that handles selection events for the selectables in a `SelectionContainer`, which
2573/// `SelectableRegion` uses. A Waft app that needs another behavior writes its own struct of
2574/// [`StaticSelectionContainerDelegate`] and overrides the members it changes.
2575pub struct PlainStaticSelectionContainerDelegate {
2576    selection_container_delegate: SelectionContainerDelegateData,
2577    multi_selectable_selection_container_delegate: MultiSelectableSelectionContainerDelegateData,
2578    static_selection_container_delegate: StaticSelectionContainerDelegateData,
2579}
2580
2581impl PlainStaticSelectionContainerDelegate {
2582    /// Creates a delegate over no selectables and no selection.
2583    pub fn new(app: &mut App) -> Ref<PlainStaticSelectionContainerDelegate> {
2584        app.create(PlainStaticSelectionContainerDelegate {
2585            selection_container_delegate: SelectionContainerDelegateData::new(),
2586            multi_selectable_selection_container_delegate:
2587                MultiSelectableSelectionContainerDelegateData::new(),
2588            static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
2589        })
2590    }
2591}
2592
2593impl SelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
2594    fn selection_container_delegate_data(
2595        self: Handle<Self>,
2596        app: &App,
2597    ) -> &SelectionContainerDelegateData {
2598        &app.get(self).selection_container_delegate
2599    }
2600
2601    fn selection_container_delegate_data_mut(
2602        self: Handle<Self>,
2603        app: &mut App,
2604    ) -> &mut SelectionContainerDelegateData {
2605        &mut app.get_mut(self).selection_container_delegate
2606    }
2607}
2608
2609impl MultiSelectableSelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
2610    crate::multi_selectable_selection_container_delegate_accessors!();
2611    crate::static_selection_container_delegate_overrides!();
2612}
2613
2614impl StaticSelectionContainerDelegate for PlainStaticSelectionContainerDelegate {
2615    crate::static_selection_container_delegate_accessors!();
2616}
2617
2618impl SelectionHandler for PlainStaticSelectionContainerDelegate {
2619    crate::static_selection_container_delegate_selection_handler!();
2620}
2621
2622impl SelectionRegistrar for PlainStaticSelectionContainerDelegate {
2623    crate::static_selection_container_delegate_selection_registrar!();
2624}
2625
2626impl ChangeNotifier for PlainStaticSelectionContainerDelegate {
2627    fn change_notifier_data(&self) -> &ChangeNotifierData {
2628        &self
2629            .multi_selectable_selection_container_delegate
2630            .change_notifier
2631    }
2632
2633    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2634        &mut self
2635            .multi_selectable_selection_container_delegate
2636            .change_notifier
2637    }
2638}
2639
2640impl std::fmt::Debug for PlainStaticSelectionContainerDelegate {
2641    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2642        f.debug_struct("StaticSelectionContainerDelegate")
2643            .field(
2644                "selectables",
2645                &self
2646                    .multi_selectable_selection_container_delegate
2647                    .selectables,
2648            )
2649            .finish_non_exhaustive()
2650    }
2651}
2652
2653impl<T: MultiSelectableSelectionContainerDelegate> MultiSelectableSelectionContainerDelegateBase
2654    for T
2655{
2656}
2657
2658// ---------------------------------------------------------------------------------------------
2659// SelectableRegion
2660
2661/// The status of a selection under a [`SelectableRegion`].
2662#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2663pub enum SelectableRegionSelectionStatus {
2664    /// The selection is being changed by a gesture or a keyboard shortcut.
2665    Changing,
2666    /// The selection is finalized.
2667    Finalized,
2668}
2669
2670/// Dart's `SelectableRegionContextMenuBuilder`: builds the context menu for a region.
2671pub type SelectableRegionContextMenuBuilder =
2672    Rc<dyn Fn(&mut App, BuildContext, Handle<SelectableRegionState>) -> WidgetRef>;
2673
2674/// Notifies its listeners when the [`SelectableRegion`] that created this object is changing
2675/// or finalizes its selection.
2676///
2677/// To access the notifier from the nearest [`SelectableRegion`] ancestor, use
2678/// [`SelectableRegionSelectionStatusScope::maybe_of`].
2679pub struct SelectableRegionSelectionStatusNotifier {
2680    change_notifier: ChangeNotifierData,
2681    selectable_region_selection_status: SelectableRegionSelectionStatus,
2682}
2683
2684impl SelectableRegionSelectionStatusNotifier {
2685    fn new() -> SelectableRegionSelectionStatusNotifier {
2686        SelectableRegionSelectionStatusNotifier {
2687            change_notifier: ChangeNotifierData::new(),
2688            selectable_region_selection_status: SelectableRegionSelectionStatus::Finalized,
2689        }
2690    }
2691
2692    /// Sets the [`SelectableRegionSelectionStatus`] for the [`SelectableRegion`] that owns this
2693    /// object.
2694    ///
2695    /// Listeners are notified even if the value did not change.
2696    fn set_value(self: Handle<Self>, app: &mut App, new_status: SelectableRegionSelectionStatus) {
2697        debug_assert!(
2698            new_status == SelectableRegionSelectionStatus::Finalized
2699                && *self.value_of(app) == SelectableRegionSelectionStatus::Changing
2700                || new_status == SelectableRegionSelectionStatus::Changing,
2701            "Attempting to finalize the selection when it is already finalized."
2702        );
2703        app.get_mut(self).selectable_region_selection_status = new_status;
2704        self.notify_listeners(app);
2705    }
2706
2707    fn dispose(self: Handle<Self>, app: &mut App) {
2708        ChangeNotifierData::dispose(app, self);
2709    }
2710}
2711
2712impl ChangeNotifier for SelectableRegionSelectionStatusNotifier {
2713    fn change_notifier_data(&self) -> &ChangeNotifierData {
2714        &self.change_notifier
2715    }
2716
2717    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2718        &mut self.change_notifier
2719    }
2720}
2721
2722impl ValueListenableHandle<SelectableRegionSelectionStatus>
2723    for Handle<SelectableRegionSelectionStatusNotifier>
2724{
2725    /// The current value of the [`SelectableRegionSelectionStatus`] of the [`SelectableRegion`]
2726    /// that owns this object.
2727    ///
2728    /// Defaults to [`SelectableRegionSelectionStatus::Finalized`].
2729    fn value_of(self, app: &App) -> &SelectableRegionSelectionStatus {
2730        &app.get(self).selectable_region_selection_status
2731    }
2732}
2733
2734/// An inherited widget that hosts a [`SelectableRegion`]'s selection status notifier.
2735pub struct SelectableRegionSelectionStatusScope {
2736    pub key: Option<KeyRef>,
2737    notifier: Ref<SelectableRegionSelectionStatusNotifier>,
2738    child: WidgetRef,
2739}
2740
2741impl SelectableRegionSelectionStatusScope {
2742    /// Creates the scope; Dart's private constructor.
2743    #[cfg_attr(debug_assertions, track_caller)]
2744    pub fn new<K: 'static>(
2745        notifier: Ref<SelectableRegionSelectionStatusNotifier>,
2746        child: impl IntoWidget<K>,
2747    ) -> SelectableRegionSelectionStatusScope {
2748        SelectableRegionSelectionStatusScope {
2749            key: None,
2750            notifier,
2751            child: child.into_widget(),
2752        }
2753    }
2754
2755    /// Dart `SelectableRegionSelectionStatusScope(key:)`.
2756    pub fn key(mut self, key: KeyRef) -> SelectableRegionSelectionStatusScope {
2757        self.key = Some(key);
2758        self
2759    }
2760
2761    /// The nearest region's selection status notifier, or `None`.
2762    pub fn maybe_of(
2763        app: &mut App,
2764        context: BuildContext,
2765    ) -> Option<Rc<dyn ValueListenable<SelectableRegionSelectionStatus>>> {
2766        context
2767            .depend_on_inherited_widget_of_exact_type::<SelectableRegionSelectionStatusScope>(app)
2768            .map(|scope| {
2769                Rc::new(scope.notifier.clone())
2770                    as Rc<dyn ValueListenable<SelectableRegionSelectionStatus>>
2771            })
2772    }
2773}
2774
2775impl std::fmt::Debug for SelectableRegionSelectionStatusScope {
2776    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2777        f.debug_struct("SelectableRegionSelectionStatusScope")
2778            .finish_non_exhaustive()
2779    }
2780}
2781
2782impl InheritedWidget for SelectableRegionSelectionStatusScope {
2783    fn key(&self) -> Option<&KeyRef> {
2784        self.key.as_ref()
2785    }
2786
2787    fn child(&self) -> &WidgetRef {
2788        &self.child
2789    }
2790
2791    fn update_should_notify(&self, old_widget: &SelectableRegionSelectionStatusScope) -> bool {
2792        old_widget.notifier != self.notifier
2793    }
2794}
2795
2796/// A widget that introduces an area for user selections.
2797///
2798/// Flutter widgets are not selectable by default. Wrapping a subtree with a
2799/// [`SelectableRegion`] enables selection for the widgets in the subtree that participate in
2800/// selection, such as a [`Text`](crate::Text) under it.
2801pub struct SelectableRegion {
2802    /// See [`Widget::key`](crate::Widget::key).
2803    pub key: Option<KeyRef>,
2804    /// The configuration for the magnifier used with selections in this region.
2805    pub magnifier_configuration: TextMagnifierConfiguration,
2806    /// The focus node this region uses; one of its own when `None`.
2807    pub focus_node: Option<FocusNodeRef>,
2808    /// The child widget this selection area applies to.
2809    pub child: WidgetRef,
2810    /// Builds the context menu for the region.
2811    pub context_menu_builder: Option<SelectableRegionContextMenuBuilder>,
2812    /// The delegate to build the selection handles and toolbar for mobile devices.
2813    pub selection_controls: Rc<dyn TextSelectionControls>,
2814    /// Called when the selected content changes.
2815    pub on_selection_changed: Option<ValueChanged<Option<SelectedContent>>>,
2816}
2817
2818impl SelectableRegion {
2819    /// Creates a selection area for `child`.
2820    #[cfg_attr(debug_assertions, track_caller)]
2821    pub fn new<K>(
2822        selection_controls: Rc<dyn TextSelectionControls>,
2823        child: impl IntoWidget<K>,
2824    ) -> SelectableRegion {
2825        SelectableRegion {
2826            key: None,
2827            magnifier_configuration: TextMagnifierConfiguration::DISABLED,
2828            focus_node: None,
2829            child: child.into_widget(),
2830            context_menu_builder: None,
2831            selection_controls,
2832            on_selection_changed: None,
2833        }
2834    }
2835
2836    /// Dart `SelectableRegion(key:)`.
2837    pub fn key(mut self, key: KeyRef) -> SelectableRegion {
2838        self.key = Some(key);
2839        self
2840    }
2841
2842    /// Dart `SelectableRegion(focusNode:)`.
2843    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SelectableRegion {
2844        self.focus_node = Some(focus_node);
2845        self
2846    }
2847
2848    /// Dart `SelectableRegion(magnifierConfiguration:)`.
2849    pub fn magnifier_configuration(
2850        mut self,
2851        magnifier_configuration: TextMagnifierConfiguration,
2852    ) -> SelectableRegion {
2853        self.magnifier_configuration = magnifier_configuration;
2854        self
2855    }
2856
2857    /// Dart `SelectableRegion(contextMenuBuilder:)`.
2858    pub fn context_menu_builder(
2859        mut self,
2860        context_menu_builder: SelectableRegionContextMenuBuilder,
2861    ) -> SelectableRegion {
2862        self.context_menu_builder = Some(context_menu_builder);
2863        self
2864    }
2865
2866    /// Dart `SelectableRegion(onSelectionChanged:)`.
2867    pub fn on_selection_changed(
2868        mut self,
2869        on_selection_changed: ValueChanged<Option<SelectedContent>>,
2870    ) -> SelectableRegion {
2871        self.on_selection_changed = Some(on_selection_changed);
2872        self
2873    }
2874
2875    /// The buttons of this platform's default selection menu for a region.
2876    pub fn get_selectable_button_items(
2877        app: &App,
2878        selection_geometry: &SelectionGeometry,
2879        on_copy: Listener,
2880        on_select_all: Listener,
2881        on_share: Option<Listener>,
2882    ) -> Vec<ContextMenuButtonItem> {
2883        let can_copy = selection_geometry.status == SelectionStatus::Uncollapsed;
2884        let can_select_all = selection_geometry.has_content;
2885        let platform_can_share =
2886            matches!(app.platform().target_platform(), TargetPlatform::Android)
2887                && selection_geometry.status == SelectionStatus::Uncollapsed;
2888        let can_share = on_share.is_some() && platform_can_share;
2889        let show_share_before_select_all =
2890            app.platform().target_platform() == TargetPlatform::Android;
2891        let mut items = Vec::new();
2892        if can_copy {
2893            items.push(
2894                ContextMenuButtonItem::new(Some(on_copy)).r#type(ContextMenuButtonType::Copy),
2895            );
2896        }
2897        if can_share && show_share_before_select_all {
2898            items.push(
2899                ContextMenuButtonItem::new(on_share.clone()).r#type(ContextMenuButtonType::Share),
2900            );
2901        }
2902        if can_select_all {
2903            items.push(
2904                ContextMenuButtonItem::new(Some(on_select_all))
2905                    .r#type(ContextMenuButtonType::SelectAll),
2906            );
2907        }
2908        if can_share && !show_share_before_select_all {
2909            items.push(ContextMenuButtonItem::new(on_share).r#type(ContextMenuButtonType::Share));
2910        }
2911        items
2912    }
2913}
2914
2915impl std::fmt::Debug for SelectableRegion {
2916    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2917        f.debug_struct("SelectableRegion").finish_non_exhaustive()
2918    }
2919}
2920
2921impl StatefulWidget for SelectableRegion {
2922    type State = SelectableRegionState;
2923
2924    fn key(&self) -> Option<&KeyRef> {
2925        self.key.as_ref()
2926    }
2927
2928    fn create_state(&self) -> SelectableRegionState {
2929        SelectableRegionState {
2930            state: StateData::new(),
2931            selection_delegate: None,
2932            selectable: None,
2933            start_handle_layer_link: None,
2934            end_handle_layer_link: None,
2935            toolbar_layer_link: None,
2936            selection_overlay: None,
2937            last_selected_content: None,
2938            last_orientation: None,
2939            last_secondary_tap_down_position: None,
2940            last_pointer_device_kind: None,
2941            is_shift_pressed: false,
2942            selection_start_position: None,
2943            selection_end_position: None,
2944            selection_start_handle_drag_position: Offset::ZERO,
2945            selection_end_handle_drag_position: Offset::ZERO,
2946            scheduled_selection_start_edge_update: false,
2947            scheduled_selection_end_edge_update: false,
2948            adjusting_selection_end: None,
2949            directional_horizontal_baseline: None,
2950            local_focus_node: None,
2951            gesture_recognizers: None,
2952            actions: None,
2953            selection_status_notifier: None,
2954        }
2955    }
2956}
2957
2958/// State for a [`SelectableRegion`].
2959///
2960/// It is the [`SelectionRegistrar`] the region's [`SelectionContainer`] registers with, and
2961/// sends the selection events its gestures and actions make to the one selectable that
2962/// container is.
2963pub struct SelectableRegionState {
2964    state: StateData<SelectableRegion>,
2965    selection_delegate: Option<Ref<PlainStaticSelectionContainerDelegate>>,
2966    /// There should only ever be one selectable, which is the selection container.
2967    selectable: Option<AnySelectable>,
2968    start_handle_layer_link: Option<Ref<LayerLink>>,
2969    end_handle_layer_link: Option<Ref<LayerLink>>,
2970    toolbar_layer_link: Option<Ref<LayerLink>>,
2971    selection_overlay: Option<Ref<SelectionOverlay>>,
2972    last_selected_content: Option<SelectedContent>,
2973    last_orientation: Option<Orientation>,
2974    last_secondary_tap_down_position: Option<Offset>,
2975    last_pointer_device_kind: Option<PointerDeviceKind>,
2976    /// Whether the shift key was pressed when the most recent pointer down was tracked.
2977    is_shift_pressed: bool,
2978    selection_start_position: Option<Offset>,
2979    selection_end_position: Option<Offset>,
2980    selection_start_handle_drag_position: Offset,
2981    selection_end_handle_drag_position: Offset,
2982    scheduled_selection_start_edge_update: bool,
2983    scheduled_selection_end_edge_update: bool,
2984    adjusting_selection_end: Option<bool>,
2985    directional_horizontal_baseline: Option<f64>,
2986    local_focus_node: Option<Ref<FocusNode>>,
2987    gesture_recognizers: Option<GestureRecognizerFactories>,
2988    /// Dart's `late final _actions`, built on the first build.
2989    actions: Option<HashMap<TypeId, ActionRef>>,
2990    selection_status_notifier: Option<Ref<SelectableRegionSelectionStatusNotifier>>,
2991}
2992
2993impl SelectableRegionState {
2994    fn selection_delegate(
2995        self: Handle<Self>,
2996        app: &App,
2997    ) -> Handle<PlainStaticSelectionContainerDelegate> {
2998        app.get(self)
2999            .selection_delegate
3000            .as_ref()
3001            .expect("the delegate is created in init_state")
3002            .handle()
3003    }
3004
3005    fn selection_geometry(self: Handle<Self>, app: &App) -> SelectionGeometry {
3006        SelectionHandler::value(self.selection_delegate(app), app)
3007    }
3008
3009    fn selectable(self: Handle<Self>, app: &App) -> Option<AnySelectable> {
3010        app.get(self).selectable
3011    }
3012
3013    fn selection_status_notifier(
3014        self: Handle<Self>,
3015        app: &App,
3016    ) -> Ref<SelectableRegionSelectionStatusNotifier> {
3017        app.get(self)
3018            .selection_status_notifier
3019            .as_ref()
3020            .expect("the notifier is created in init_state")
3021            .clone()
3022    }
3023
3024    fn set_selection_status(
3025        self: Handle<Self>,
3026        app: &mut App,
3027        status: SelectableRegionSelectionStatus,
3028    ) {
3029        self.selection_status_notifier(app)
3030            .handle()
3031            .set_value(app, status);
3032    }
3033
3034    fn finalize_selectable_region_status(self: Handle<Self>, app: &mut App) {
3035        let notifier = self.selection_status_notifier(app).handle();
3036        if notifier.value_of(app) != &SelectableRegionSelectionStatus::Changing {
3037            // Don't finalize the selection again if it is not currently changing.
3038            return;
3039        }
3040        notifier.set_value(app, SelectableRegionSelectionStatus::Finalized);
3041    }
3042
3043    fn focus_node(self: Handle<Self>, app: &App) -> FocusNodeRef {
3044        let widget = self.widget(app);
3045        match &widget.focus_node {
3046            Some(focus_node) => focus_node.clone(),
3047            None => app
3048                .get(self)
3049                .local_focus_node
3050                .as_ref()
3051                .expect("a local focus node is created in init_state")
3052                .erase(),
3053        }
3054    }
3055
3056    fn has_selection_overlay_geometry(self: Handle<Self>, app: &App) -> bool {
3057        let geometry = self.selection_geometry(app);
3058        geometry.start_selection_point.is_some() || geometry.end_selection_point.is_some()
3059    }
3060
3061    /// Dart's `_selectEndTo`.
3062    fn select_end_to(
3063        self: Handle<Self>,
3064        app: &mut App,
3065        offset: Offset,
3066        continuous: bool,
3067        text_granularity: Option<TextGranularity>,
3068    ) {
3069        let Some(selectable) = self.selectable(app) else {
3070            return;
3071        };
3072        if !continuous {
3073            selectable
3074                .dispatch_selection_event(app, &SelectionEvent::for_end(offset, text_granularity));
3075            return;
3076        }
3077        if app.get(self).selection_end_position != Some(offset) {
3078            app.get_mut(self).selection_end_position = Some(offset);
3079            self.trigger_selection_end_edge_update(app, text_granularity);
3080        }
3081    }
3082
3083    /// Dart's `_selectStartTo`.
3084    fn select_start_to(
3085        self: Handle<Self>,
3086        app: &mut App,
3087        offset: Offset,
3088        continuous: bool,
3089        text_granularity: Option<TextGranularity>,
3090    ) {
3091        let Some(selectable) = self.selectable(app) else {
3092            return;
3093        };
3094        if !continuous {
3095            selectable.dispatch_selection_event(
3096                app,
3097                &SelectionEvent::for_start(offset, text_granularity),
3098            );
3099            return;
3100        }
3101        if app.get(self).selection_start_position != Some(offset) {
3102            app.get_mut(self).selection_start_position = Some(offset);
3103            self.trigger_selection_start_edge_update(app, text_granularity);
3104        }
3105    }
3106
3107    /// Dart's `_triggerSelectionEndEdgeUpdate`: sends the end edge each frame until a child
3108    /// scrollable stops answering that it is pending.
3109    fn trigger_selection_end_edge_update(
3110        self: Handle<Self>,
3111        app: &mut App,
3112        text_granularity: Option<TextGranularity>,
3113    ) {
3114        let Some(offset) = app.get(self).selection_end_position else {
3115            return;
3116        };
3117        if app.get(self).scheduled_selection_end_edge_update {
3118            return;
3119        }
3120        let Some(selectable) = self.selectable(app) else {
3121            return;
3122        };
3123        if selectable
3124            .dispatch_selection_event(app, &SelectionEvent::for_end(offset, text_granularity))
3125            == SelectionResult::Pending
3126        {
3127            app.get_mut(self).scheduled_selection_end_edge_update = true;
3128            SchedulerBinding::add_post_frame_callback(
3129                app,
3130                FrameCallback::handle_method(self, move |this, app, _time_stamp| {
3131                    this.post_frame_end_edge_update(app, text_granularity)
3132                }),
3133                None,
3134            );
3135        }
3136    }
3137
3138    fn post_frame_end_edge_update(
3139        self: Handle<Self>,
3140        app: &mut App,
3141        text_granularity: Option<TextGranularity>,
3142    ) {
3143        if !app.get(self).scheduled_selection_end_edge_update {
3144            return;
3145        }
3146        app.get_mut(self).scheduled_selection_end_edge_update = false;
3147        self.trigger_selection_end_edge_update(app, text_granularity);
3148    }
3149
3150    /// Dart's `_triggerSelectionStartEdgeUpdate`.
3151    fn trigger_selection_start_edge_update(
3152        self: Handle<Self>,
3153        app: &mut App,
3154        text_granularity: Option<TextGranularity>,
3155    ) {
3156        let Some(offset) = app.get(self).selection_start_position else {
3157            return;
3158        };
3159        if app.get(self).scheduled_selection_start_edge_update {
3160            return;
3161        }
3162        let Some(selectable) = self.selectable(app) else {
3163            return;
3164        };
3165        if selectable
3166            .dispatch_selection_event(app, &SelectionEvent::for_start(offset, text_granularity))
3167            == SelectionResult::Pending
3168        {
3169            app.get_mut(self).scheduled_selection_start_edge_update = true;
3170            SchedulerBinding::add_post_frame_callback(
3171                app,
3172                FrameCallback::handle_method(self, move |this, app, _time_stamp| {
3173                    this.post_frame_start_edge_update(app, text_granularity)
3174                }),
3175                None,
3176            );
3177        }
3178    }
3179
3180    fn post_frame_start_edge_update(
3181        self: Handle<Self>,
3182        app: &mut App,
3183        text_granularity: Option<TextGranularity>,
3184    ) {
3185        if !app.get(self).scheduled_selection_start_edge_update {
3186            return;
3187        }
3188        app.get_mut(self).scheduled_selection_start_edge_update = false;
3189        self.trigger_selection_start_edge_update(app, text_granularity);
3190    }
3191
3192    /// Dart's `_stopSelectionEndEdgeUpdate`.
3193    fn stop_selection_end_edge_update(self: Handle<Self>, app: &mut App) {
3194        app.get_mut(self).scheduled_selection_end_edge_update = false;
3195        app.get_mut(self).selection_end_position = None;
3196    }
3197
3198    /// Dart's `_stopSelectionStartEdgeUpdate`.
3199    fn stop_selection_start_edge_update(self: Handle<Self>, app: &mut App) {
3200        app.get_mut(self).scheduled_selection_start_edge_update = false;
3201        app.get_mut(self).selection_end_position = None;
3202    }
3203
3204    /// Dart's `_finalizeSelection`.
3205    fn finalize_selection(self: Handle<Self>, app: &mut App) {
3206        self.stop_selection_end_edge_update(app);
3207        self.stop_selection_start_edge_update(app);
3208    }
3209
3210    /// Removes the ongoing selection for this region.
3211    pub fn clear_selection(self: Handle<Self>, app: &mut App) {
3212        self.finalize_selection(app);
3213        app.get_mut(self).directional_horizontal_baseline = None;
3214        app.get_mut(self).adjusting_selection_end = None;
3215        if let Some(selectable) = self.selectable(app) {
3216            selectable.dispatch_selection_event(app, &SelectionEvent::Clear);
3217        }
3218        self.update_selected_content_if_needed(app);
3219    }
3220
3221    /// Dart's `_selectWordAt`.
3222    fn select_word_at(self: Handle<Self>, app: &mut App, offset: Offset) {
3223        self.finalize_selection(app);
3224        if let Some(selectable) = self.selectable(app) {
3225            selectable.dispatch_selection_event(
3226                app,
3227                &SelectionEvent::SelectWord {
3228                    global_position: offset,
3229                },
3230            );
3231        }
3232    }
3233
3234    /// Dart's `_selectParagraphAt`.
3235    fn select_paragraph_at(self: Handle<Self>, app: &mut App, offset: Offset) {
3236        self.finalize_selection(app);
3237        if let Some(selectable) = self.selectable(app) {
3238            selectable.dispatch_selection_event(
3239                app,
3240                &SelectionEvent::SelectParagraph {
3241                    global_position: offset,
3242                    absorb: false,
3243                },
3244            );
3245        }
3246    }
3247
3248    /// Dart's `_collapseSelectionAt`.
3249    fn collapse_selection_at(self: Handle<Self>, app: &mut App, offset: Offset) {
3250        self.finalize_selection(app);
3251        self.select_start_to(app, offset, false, None);
3252        self.select_end_to(app, offset, false, None);
3253    }
3254
3255    /// Selects all the content of the region.
3256    pub fn select_all(self: Handle<Self>, app: &mut App, cause: Option<SelectionChangedCause>) {
3257        self.clear_selection(app);
3258        if let Some(selectable) = self.selectable(app) {
3259            selectable.dispatch_selection_event(app, &SelectionEvent::SelectAll);
3260        }
3261        if cause == Some(SelectionChangedCause::Toolbar) {
3262            self.show_handles(app);
3263            self.show_toolbar(app, None);
3264        }
3265        self.update_selected_content_if_needed(app);
3266        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3267        self.finalize_selectable_region_status(app);
3268    }
3269
3270    /// Copies the selected content to the clipboard.
3271    fn copy_selected_content(self: Handle<Self>, app: &mut App) {
3272        let Some(selectable) = self.selectable(app) else {
3273            return;
3274        };
3275        let Some(content) = selectable.selected_content(app) else {
3276            return;
3277        };
3278        drop(Clipboard::set_data(
3279            app,
3280            ClipboardData::new(content.plain_text),
3281        ));
3282    }
3283
3284    /// Dart's `_updateSelectedContentIfNeeded`.
3285    fn update_selected_content_if_needed(self: Handle<Self>, app: &mut App) {
3286        if self.widget(app).on_selection_changed.is_none() {
3287            return;
3288        }
3289        let content = self
3290            .selectable(app)
3291            .and_then(|selectable| selectable.selected_content(app));
3292        let changed = app
3293            .get(self)
3294            .last_selected_content
3295            .as_ref()
3296            .map(|last| &last.plain_text)
3297            != content.as_ref().map(|content| &content.plain_text);
3298        if changed {
3299            let callback = self
3300                .widget(app)
3301                .on_selection_changed
3302                .clone()
3303                .expect("checked just now");
3304            app.get_mut(self).last_selected_content = content.clone();
3305            callback(app, content);
3306        }
3307    }
3308
3309    /// `_positionIsOnActiveSelection`.
3310    fn position_is_on_active_selection(
3311        self: Handle<Self>,
3312        app: &App,
3313        global_position: Offset,
3314    ) -> bool {
3315        let Some(selectable) = self.selectable(app) else {
3316            return false;
3317        };
3318        let transform = selectable.get_transform_to(app, None);
3319        self.selection_geometry(app)
3320            .selection_rects
3321            .iter()
3322            .any(|rect| transform_rect(&transform, *rect).contains(global_position))
3323    }
3324
3325    /// The line height at the start of the current selection.
3326    pub fn start_glyph_height(self: Handle<Self>, app: &App) -> f64 {
3327        self.selection_geometry(app)
3328            .start_selection_point
3329            .expect("the region has a selection start")
3330            .line_height
3331    }
3332
3333    /// The line height at the end of the current selection.
3334    pub fn end_glyph_height(self: Handle<Self>, app: &App) -> f64 {
3335        self.selection_geometry(app)
3336            .end_selection_point
3337            .expect("the region has a selection end")
3338            .line_height
3339    }
3340
3341    /// The local coordinates of the endpoints of the current selection.
3342    pub fn selection_endpoints(self: Handle<Self>, app: &App) -> Vec<TextSelectionPoint> {
3343        let geometry = self.selection_geometry(app);
3344        let start = geometry.start_selection_point;
3345        let end = geometry.end_selection_point;
3346        let start_local = start
3347            .map(|point| point.local_position)
3348            .or(end.map(|point| point.local_position))
3349            .expect("the region has a selection point");
3350        let end_local = end
3351            .map(|point| point.local_position)
3352            .or(start.map(|point| point.local_position))
3353            .expect("the region has a selection point");
3354        if start_local.dy() > end_local.dy() {
3355            vec![
3356                TextSelectionPoint::new(end_local, Some(TextDirection::Ltr)),
3357                TextSelectionPoint::new(start_local, Some(TextDirection::Ltr)),
3358            ]
3359        } else {
3360            vec![
3361                TextSelectionPoint::new(start_local, Some(TextDirection::Ltr)),
3362                TextSelectionPoint::new(end_local, Some(TextDirection::Ltr)),
3363            ]
3364        }
3365    }
3366
3367    /// The buttons of this region's default context menu.
3368    pub fn context_menu_button_items(
3369        self: Handle<Self>,
3370        app: &mut App,
3371    ) -> Vec<ContextMenuButtonItem> {
3372        let geometry = self.selection_geometry(app);
3373        let on_copy = Listener::handle_method(self, Self::copy_from_context_menu);
3374        let on_select_all = Listener::handle_method(self, Self::select_all_from_context_menu);
3375        SelectableRegion::get_selectable_button_items(app, &geometry, on_copy, on_select_all, None)
3376    }
3377
3378    fn copy_from_context_menu(self: Handle<Self>, app: &mut App) {
3379        self.copy_selected_content(app);
3380        match app.platform().target_platform() {
3381            TargetPlatform::Android | TargetPlatform::Fuchsia => {
3382                self.clear_selection(app);
3383                self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3384                self.finalize_selectable_region_status(app);
3385            }
3386            TargetPlatform::IOS => self.hide_toolbar(app, false),
3387            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
3388                self.hide_toolbar(app, true)
3389            }
3390        }
3391    }
3392
3393    fn select_all_from_context_menu(self: Handle<Self>, app: &mut App) {
3394        match app.platform().target_platform() {
3395            TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {
3396                self.select_all(app, Some(SelectionChangedCause::Toolbar))
3397            }
3398            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
3399                self.select_all(app, None);
3400                self.hide_toolbar(app, true);
3401            }
3402        }
3403    }
3404
3405    /// The anchors of this region's context menu.
3406    pub fn context_menu_anchors(self: Handle<Self>, app: &mut App) -> TextSelectionToolbarAnchors {
3407        if let Some(position) = app.get(self).last_secondary_tap_down_position {
3408            app.get_mut(self).last_secondary_tap_down_position = None;
3409            return TextSelectionToolbarAnchors::new(position);
3410        }
3411        let render_box = self
3412            .context(app)
3413            .find_render_object(app)
3414            .and_then(|object| object.as_box())
3415            .expect("a SelectableRegion's render object is a RenderBox");
3416        TextSelectionToolbarAnchors::from_selection(
3417            app,
3418            render_box,
3419            self.start_glyph_height(app),
3420            self.end_glyph_height(app),
3421            &self.selection_endpoints(app),
3422        )
3423    }
3424
3425    fn selection_overlay(self: Handle<Self>, app: &App) -> Option<Ref<SelectionOverlay>> {
3426        app.get(self).selection_overlay.clone()
3427    }
3428
3429    fn create_selection_overlay(self: Handle<Self>, app: &mut App) {
3430        debug_assert!(self.has_selection_overlay_geometry(app));
3431        if app.get(self).selection_overlay.is_some() {
3432            return;
3433        }
3434        let geometry = self.selection_geometry(app);
3435        let start = geometry.start_selection_point;
3436        let end = geometry.end_selection_point;
3437        let start_type = start
3438            .map(|point| point.handle_type)
3439            .unwrap_or(TextSelectionHandleType::Collapsed);
3440        let end_type = end
3441            .map(|point| point.handle_type)
3442            .unwrap_or(TextSelectionHandleType::Collapsed);
3443        let line_height_at_start = start
3444            .map(|point| point.line_height)
3445            .or(end.map(|point| point.line_height))
3446            .unwrap_or(0.0);
3447        let line_height_at_end = end
3448            .map(|point| point.line_height)
3449            .or(start.map(|point| point.line_height))
3450            .unwrap_or(0.0);
3451        let context = self.context(app);
3452        let (start_link, end_link, toolbar_link) = {
3453            let state = app.get(self);
3454            (
3455                state
3456                    .start_handle_layer_link
3457                    .clone()
3458                    .expect("created in init_state"),
3459                state
3460                    .end_handle_layer_link
3461                    .clone()
3462                    .expect("created in init_state"),
3463                state
3464                    .toolbar_layer_link
3465                    .clone()
3466                    .expect("created in init_state"),
3467            )
3468        };
3469        let controls = self.widget(app).selection_controls.clone();
3470        let overlay = SelectionOverlay::new(
3471            app,
3472            context,
3473            start_type,
3474            line_height_at_start,
3475            end_type,
3476            line_height_at_end,
3477            self.selection_endpoints(app),
3478            Some(controls),
3479            None,
3480            None,
3481            start_link,
3482            end_link,
3483            toolbar_link,
3484        );
3485        overlay.set_on_start_handle_drag_start(
3486            app,
3487            Rc::new(move |app, details| {
3488                self.handle_selection_start_handle_drag_start(app, details)
3489            }),
3490        );
3491        overlay.set_on_start_handle_drag_update(
3492            app,
3493            Rc::new(move |app, details| {
3494                self.handle_selection_start_handle_drag_update(app, details)
3495            }),
3496        );
3497        overlay.set_on_start_handle_drag_end(
3498            app,
3499            Rc::new(move |app, details| self.handle_any_drag_end(app, details)),
3500        );
3501        overlay.set_on_end_handle_drag_start(
3502            app,
3503            Rc::new(move |app, details| self.handle_selection_end_handle_drag_start(app, details)),
3504        );
3505        overlay.set_on_end_handle_drag_update(
3506            app,
3507            Rc::new(move |app, details| self.handle_selection_end_handle_drag_update(app, details)),
3508        );
3509        overlay.set_on_end_handle_drag_end(
3510            app,
3511            Rc::new(move |app, details| self.handle_any_drag_end(app, details)),
3512        );
3513        let magnifier_configuration = self.widget(app).magnifier_configuration.clone();
3514        let overlay = overlay.magnifier_configuration(app, magnifier_configuration);
3515        app.get_mut(self).selection_overlay = Some(overlay);
3516    }
3517
3518    fn update_selection_overlay(self: Handle<Self>, app: &mut App) {
3519        let Some(overlay) = self.selection_overlay(app) else {
3520            return;
3521        };
3522        let geometry = self.selection_geometry(app);
3523        let start = geometry.start_selection_point;
3524        let end = geometry.end_selection_point;
3525        overlay.set_start_handle_type(
3526            app,
3527            start
3528                .map(|point| point.handle_type)
3529                .unwrap_or(TextSelectionHandleType::Left),
3530        );
3531        overlay.set_line_height_at_start(
3532            app,
3533            start
3534                .map(|point| point.line_height)
3535                .or(end.map(|point| point.line_height))
3536                .unwrap_or(0.0),
3537        );
3538        overlay.set_end_handle_type(
3539            app,
3540            end.map(|point| point.handle_type)
3541                .unwrap_or(TextSelectionHandleType::Right),
3542        );
3543        overlay.set_line_height_at_end(
3544            app,
3545            end.map(|point| point.line_height)
3546                .or(start.map(|point| point.line_height))
3547                .unwrap_or(0.0),
3548        );
3549        overlay.set_selection_endpoints(app, self.selection_endpoints(app));
3550    }
3551
3552    /// Shows the selection handles; answers whether they can be shown.
3553    fn show_handles(self: Handle<Self>, app: &mut App) -> bool {
3554        if let Some(overlay) = self.selection_overlay(app) {
3555            overlay.show_handles(app);
3556            return true;
3557        }
3558        if !self.has_selection_overlay_geometry(app) {
3559            return false;
3560        }
3561        self.create_selection_overlay(app);
3562        self.selection_overlay(app)
3563            .expect("created just now")
3564            .show_handles(app);
3565        true
3566    }
3567
3568    /// Shows the selection toolbar; answers whether it can be shown.
3569    fn show_toolbar(self: Handle<Self>, app: &mut App, location: Option<Offset>) -> bool {
3570        if !self.has_selection_overlay_geometry(app) && self.selection_overlay(app).is_none() {
3571            return false;
3572        }
3573        if self.selection_overlay(app).is_none() {
3574            self.create_selection_overlay(app);
3575        }
3576        let overlay = self.selection_overlay(app).expect("created just now");
3577        overlay.set_toolbar_location(app, location);
3578        let uses_handles = self
3579            .widget(app)
3580            .selection_controls
3581            .as_text_selection_handle_controls()
3582            .is_some();
3583        if !uses_handles {
3584            // The overlay's own toolbar asks a `TextSelectionDelegate` it does not have; see
3585            // PORTING.md.
3586            return false;
3587        }
3588        overlay.hide_toolbar(app);
3589        let Some(context_menu_builder) = self.widget(app).context_menu_builder.clone() else {
3590            return false;
3591        };
3592        overlay.show_toolbar(
3593            app,
3594            Some(self.context(app)),
3595            Some(Rc::new(move |app, context| {
3596                context_menu_builder(app, context, self)
3597            })),
3598        );
3599        true
3600    }
3601
3602    /// Hides the toolbar, and the handles when `hide_handles` is set.
3603    pub fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
3604        if let Some(overlay) = self.selection_overlay(app) {
3605            overlay.hide_toolbar(app);
3606            if hide_handles {
3607                overlay.hide_handles(app);
3608            }
3609        }
3610    }
3611
3612    fn hide_toolbar_if_visible(self: Handle<Self>, app: &mut App) -> bool {
3613        let visible = self
3614            .selection_overlay(app)
3615            .is_some_and(|overlay| overlay.toolbar_is_visible(app));
3616        if visible {
3617            self.hide_toolbar(app, false);
3618        }
3619        visible
3620    }
3621
3622    /// `_updateSelectionStatus`, the selectable's listener.
3623    fn update_selection_status(self: Handle<Self>, app: &mut App) {
3624        if self.has_selection_overlay_geometry(app) {
3625            self.update_selection_overlay(app);
3626        } else {
3627            if let Some(overlay) = app.get_mut(self).selection_overlay.take() {
3628                overlay.dispose(app);
3629            }
3630        }
3631    }
3632}
3633
3634impl SelectableRegionState {
3635    /// Dart's `_getEffectiveConsecutiveTapCount`.
3636    fn effective_consecutive_tap_count(self: Handle<Self>, app: &App, raw_count: i32) -> i32 {
3637        let max_consecutive_tap = 3;
3638        let platform = app.platform().target_platform();
3639        match platform {
3640            TargetPlatform::Android | TargetPlatform::Fuchsia => {
3641                let max_consecutive_tap = if app
3642                    .get(self)
3643                    .last_pointer_device_kind
3644                    .is_some_and(|kind| kind != PointerDeviceKind::Mouse)
3645                {
3646                    2
3647                } else {
3648                    max_consecutive_tap
3649                };
3650                if raw_count <= max_consecutive_tap {
3651                    raw_count
3652                } else if raw_count % max_consecutive_tap == 0 {
3653                    max_consecutive_tap
3654                } else {
3655                    raw_count % max_consecutive_tap
3656                }
3657            }
3658            TargetPlatform::Linux => {
3659                if raw_count <= max_consecutive_tap {
3660                    raw_count
3661                } else if raw_count % max_consecutive_tap == 0 {
3662                    max_consecutive_tap
3663                } else {
3664                    raw_count % max_consecutive_tap
3665                }
3666            }
3667            TargetPlatform::IOS | TargetPlatform::MacOS | TargetPlatform::Windows => {
3668                raw_count.min(max_consecutive_tap)
3669            }
3670        }
3671    }
3672
3673    /// Dart's `_isPrecisePointerDevice`.
3674    fn is_precise_pointer_device(kind: PointerDeviceKind) -> bool {
3675        matches!(kind, PointerDeviceKind::Mouse)
3676    }
3677
3678    /// Dart's `_startNewMouseSelectionGesture`.
3679    fn start_new_mouse_selection_gesture(
3680        self: Handle<Self>,
3681        app: &mut App,
3682        details: TapDragDownDetails,
3683    ) {
3684        app.get_mut(self).last_pointer_device_kind = details.kind;
3685        let kind = details.kind;
3686        let platform = app.platform().target_platform();
3687        match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
3688            1 => {
3689                self.focus_node(app).request_focus(app, None);
3690                match platform {
3691                    TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {}
3692                    TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
3693                        self.hide_toolbar(app, true);
3694                        // Extending needs a selection start; without one, collapse instead.
3695                        let is_shift_pressed_valid = app.get(self).is_shift_pressed
3696                            && self.selection_geometry(app).start_selection_point.is_some();
3697                        if is_shift_pressed_valid {
3698                            self.select_end_to(app, details.global_position, false, None);
3699                        } else {
3700                            self.clear_selection(app);
3701                            self.collapse_selection_at(app, details.global_position);
3702                        }
3703                        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3704                    }
3705                }
3706            }
3707            2 => {
3708                self.select_word_at(app, details.global_position);
3709                self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3710                if platform == TargetPlatform::IOS
3711                    && kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind))
3712                {
3713                    self.show_handles(app);
3714                }
3715            }
3716            3 => match platform {
3717                TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
3718                    if kind.is_some_and(Self::is_precise_pointer_device) {
3719                        self.select_paragraph_at(app, details.global_position);
3720                        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3721                    }
3722                }
3723                TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
3724                    self.select_paragraph_at(app, details.global_position);
3725                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3726                }
3727            },
3728            _ => {}
3729        }
3730        self.update_selected_content_if_needed(app);
3731    }
3732
3733    /// Dart's `_handleMouseDragStart`.
3734    fn handle_mouse_drag_start(self: Handle<Self>, app: &mut App, details: TapDragStartDetails) {
3735        let kind = details.kind;
3736        if self.effective_consecutive_tap_count(app, details.consecutive_tap_count) == 1 {
3737            if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
3738                return;
3739            }
3740            self.select_start_to(app, details.global_position, false, None);
3741            self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3742        }
3743        self.update_selected_content_if_needed(app);
3744    }
3745
3746    /// Dart's `_handleMouseDragUpdate`.
3747    fn handle_mouse_drag_update(self: Handle<Self>, app: &mut App, details: TapDragUpdateDetails) {
3748        let kind = details.kind;
3749        let platform = app.platform().target_platform();
3750        match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
3751            1 => {
3752                if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
3753                    return;
3754                }
3755                self.select_end_to(app, details.global_position, true, None);
3756                self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3757            }
3758            2 => match platform {
3759                TargetPlatform::Android | TargetPlatform::Fuchsia => {
3760                    self.select_end_to(
3761                        app,
3762                        details.global_position,
3763                        true,
3764                        Some(TextGranularity::Word),
3765                    );
3766                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3767                }
3768                TargetPlatform::IOS => {
3769                    self.select_end_to(
3770                        app,
3771                        details.global_position,
3772                        true,
3773                        Some(TextGranularity::Word),
3774                    );
3775                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3776                    if kind.is_some_and(|kind| !Self::is_precise_pointer_device(kind)) {
3777                        self.show_handles(app);
3778                    }
3779                }
3780                TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
3781                    self.select_end_to(
3782                        app,
3783                        details.global_position,
3784                        true,
3785                        Some(TextGranularity::Word),
3786                    );
3787                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3788                }
3789            },
3790            3 => match platform {
3791                TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
3792                    if kind.is_some_and(Self::is_precise_pointer_device) {
3793                        self.select_end_to(
3794                            app,
3795                            details.global_position,
3796                            true,
3797                            Some(TextGranularity::Paragraph),
3798                        );
3799                        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3800                    }
3801                }
3802                TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
3803                    self.select_end_to(
3804                        app,
3805                        details.global_position,
3806                        true,
3807                        Some(TextGranularity::Paragraph),
3808                    );
3809                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3810                }
3811            },
3812            _ => {}
3813        }
3814        self.update_selected_content_if_needed(app);
3815    }
3816
3817    /// Dart's `_handleMouseDragEnd`.
3818    fn handle_mouse_drag_end(self: Handle<Self>, app: &mut App, _details: TapDragEndDetails) {
3819        let is_pointer_precise = app
3820            .get(self)
3821            .last_pointer_device_kind
3822            .is_some_and(Self::is_precise_pointer_device);
3823        let should_show_selection_overlay_on_mobile = !is_pointer_precise;
3824        match app.platform().target_platform() {
3825            TargetPlatform::Android | TargetPlatform::Fuchsia => {
3826                if should_show_selection_overlay_on_mobile {
3827                    self.show_handles(app);
3828                    self.show_toolbar(app, None);
3829                }
3830            }
3831            TargetPlatform::IOS => {
3832                if should_show_selection_overlay_on_mobile {
3833                    self.show_toolbar(app, None);
3834                }
3835            }
3836            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {}
3837        }
3838        self.finalize_selection(app);
3839        self.update_selected_content_if_needed(app);
3840        self.finalize_selectable_region_status(app);
3841    }
3842
3843    /// Dart's `_handleMouseTapUp`.
3844    fn handle_mouse_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
3845        let platform = app.platform().target_platform();
3846        if platform == TargetPlatform::IOS
3847            && self.position_is_on_active_selection(app, details.global_position)
3848        {
3849            // On iOS a tap on the previous selection toggles its toolbar instead of moving it.
3850            let toolbar_is_visible = self
3851                .selection_overlay(app)
3852                .is_some_and(|overlay| overlay.toolbar_is_visible(app));
3853            if toolbar_is_visible {
3854                self.hide_toolbar(app, false);
3855            } else {
3856                self.show_toolbar(app, None);
3857            }
3858            return;
3859        }
3860        match self.effective_consecutive_tap_count(app, details.consecutive_tap_count) {
3861            1 => match platform {
3862                TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
3863                    self.hide_toolbar(app, true);
3864                    self.collapse_selection_at(app, details.global_position);
3865                    self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3866                }
3867                TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {}
3868            },
3869            2 => match platform {
3870                TargetPlatform::Android | TargetPlatform::Fuchsia => {
3871                    if !Self::is_precise_pointer_device(details.kind) {
3872                        self.show_handles(app);
3873                        self.show_toolbar(app, None);
3874                    }
3875                }
3876                TargetPlatform::IOS => {
3877                    if !Self::is_precise_pointer_device(details.kind) {
3878                        self.show_toolbar(app, None);
3879                    }
3880                }
3881                TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {}
3882            },
3883            _ => {}
3884        }
3885        self.finalize_selectable_region_status(app);
3886        self.update_selected_content_if_needed(app);
3887    }
3888
3889    /// Dart's `_handleTouchLongPressStart`.
3890    fn handle_touch_long_press_start(
3891        self: Handle<Self>,
3892        app: &mut App,
3893        details: LongPressStartDetails,
3894    ) {
3895        HapticFeedback::selection_click(app);
3896        self.focus_node(app).request_focus(app, None);
3897        self.select_word_at(app, details.global_position);
3898        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3899        // Android shows the handles when the long press ends; the others at its start.
3900        if app.platform().target_platform() != TargetPlatform::Android {
3901            self.show_handles(app);
3902        }
3903        self.update_selected_content_if_needed(app);
3904    }
3905
3906    /// Dart's `_handleTouchLongPressMoveUpdate`.
3907    fn handle_touch_long_press_move_update(
3908        self: Handle<Self>,
3909        app: &mut App,
3910        details: LongPressMoveUpdateDetails,
3911    ) {
3912        self.select_end_to(
3913            app,
3914            details.global_position,
3915            false,
3916            Some(TextGranularity::Word),
3917        );
3918        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3919        self.update_selected_content_if_needed(app);
3920    }
3921
3922    /// Dart's `_handleTouchLongPressEnd`.
3923    fn handle_touch_long_press_end(self: Handle<Self>, app: &mut App) {
3924        self.finalize_selection(app);
3925        self.update_selected_content_if_needed(app);
3926        self.finalize_selectable_region_status(app);
3927        if app.platform().target_platform() == TargetPlatform::Android {
3928            self.show_handles(app);
3929        }
3930        self.show_toolbar(app, None);
3931    }
3932
3933    /// Dart's `_handleRightClickDown`.
3934    fn handle_right_click_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
3935        let previous_secondary_tap_down_position = app.get(self).last_secondary_tap_down_position;
3936        let toolbar_is_visible = self
3937            .selection_overlay(app)
3938            .is_some_and(|overlay| overlay.toolbar_is_visible(app));
3939        app.get_mut(self).last_secondary_tap_down_position = Some(details.global_position);
3940        self.focus_node(app).request_focus(app, None);
3941        match app.platform().target_platform() {
3942            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Windows => {
3943                let on_active_selection =
3944                    self.position_is_on_active_selection(app, details.global_position);
3945                if on_active_selection {
3946                    self.show_handles(app);
3947                    self.show_toolbar(app, Some(details.global_position));
3948                    self.update_selected_content_if_needed(app);
3949                    return;
3950                }
3951                self.collapse_selection_at(app, details.global_position);
3952            }
3953            TargetPlatform::IOS => self.select_word_at(app, details.global_position),
3954            TargetPlatform::MacOS => {
3955                if previous_secondary_tap_down_position == Some(details.global_position)
3956                    && toolbar_is_visible
3957                {
3958                    self.hide_toolbar(app, true);
3959                    return;
3960                }
3961                self.select_word_at(app, details.global_position);
3962            }
3963            TargetPlatform::Linux => {
3964                if toolbar_is_visible {
3965                    self.hide_toolbar(app, true);
3966                    return;
3967                }
3968                if !self.position_is_on_active_selection(app, details.global_position) {
3969                    self.collapse_selection_at(app, details.global_position);
3970                }
3971            }
3972        }
3973        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
3974        self.finalize_selectable_region_status(app);
3975        app.get_mut(self).last_secondary_tap_down_position = Some(details.global_position);
3976        self.show_handles(app);
3977        self.show_toolbar(app, Some(details.global_position));
3978        self.update_selected_content_if_needed(app);
3979    }
3980
3981    /// Dart's `_determineIsAdjustingSelectionEnd`.
3982    fn determine_is_adjusting_selection_end(
3983        self: Handle<Self>,
3984        app: &mut App,
3985        forward: bool,
3986    ) -> bool {
3987        if let Some(adjusting) = app.get(self).adjusting_selection_end {
3988            return adjusting;
3989        }
3990        let geometry = self.selection_geometry(app);
3991        let start = geometry
3992            .start_selection_point
3993            .expect("the region has a selection start");
3994        let end = geometry
3995            .end_selection_point
3996            .expect("the region has a selection end");
3997        let is_reversed = if start.local_position.dy() > end.local_position.dy() {
3998            true
3999        } else if start.local_position.dy() < end.local_position.dy() {
4000            false
4001        } else {
4002            start.local_position.dx() > end.local_position.dx()
4003        };
4004        // Always move the selection edge that increases the selection range.
4005        let adjusting_selection_end = forward != is_reversed;
4006        app.get_mut(self).adjusting_selection_end = Some(adjusting_selection_end);
4007        adjusting_selection_end
4008    }
4009
4010    /// Dart's `_granularlyExtendSelection`.
4011    fn granularly_extend_selection(
4012        self: Handle<Self>,
4013        app: &mut App,
4014        granularity: TextGranularity,
4015        forward: bool,
4016    ) {
4017        app.get_mut(self).directional_horizontal_baseline = None;
4018        if !self.selection_geometry(app).has_selection() {
4019            return;
4020        }
4021        let is_end = self.determine_is_adjusting_selection_end(app, forward);
4022        if let Some(selectable) = self.selectable(app) {
4023            selectable.dispatch_selection_event(
4024                app,
4025                &SelectionEvent::GranularlyExtendSelection {
4026                    forward,
4027                    is_end,
4028                    granularity,
4029                },
4030            );
4031        }
4032        self.update_selected_content_if_needed(app);
4033        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
4034        self.finalize_selectable_region_status(app);
4035    }
4036
4037    /// Dart's `_directionallyExtendSelection`.
4038    fn directionally_extend_selection(self: Handle<Self>, app: &mut App, forward: bool) {
4039        if !self.selection_geometry(app).has_selection() {
4040            return;
4041        }
4042        let adjusting_selection_end = self.determine_is_adjusting_selection_end(app, forward);
4043        let geometry = self.selection_geometry(app);
4044        let baseline_point = if adjusting_selection_end {
4045            geometry
4046                .end_selection_point
4047                .expect("the region has a selection end")
4048        } else {
4049            geometry
4050                .start_selection_point
4051                .expect("the region has a selection start")
4052        };
4053        let baseline = match app.get(self).directional_horizontal_baseline {
4054            Some(baseline) => baseline,
4055            None => {
4056                let baseline = baseline_point.local_position.dx();
4057                app.get_mut(self).directional_horizontal_baseline = Some(baseline);
4058                baseline
4059            }
4060        };
4061        let context_transform = self
4062            .context(app)
4063            .find_render_object(app)
4064            .expect("the region has a render object")
4065            .get_transform_to(app, None);
4066        let global_selection_point =
4067            transform_point(&context_transform, Offset::new(baseline, 0.0));
4068        if let Some(selectable) = self.selectable(app) {
4069            selectable.dispatch_selection_event(
4070                app,
4071                &SelectionEvent::DirectionallyExtendSelection {
4072                    dx: global_selection_point.dx(),
4073                    is_end: adjusting_selection_end,
4074                    direction: if forward {
4075                        SelectionExtendDirection::NextLine
4076                    } else {
4077                        SelectionExtendDirection::PreviousLine
4078                    },
4079                },
4080            );
4081        }
4082        self.update_selected_content_if_needed(app);
4083        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
4084        self.finalize_selectable_region_status(app);
4085    }
4086
4087    /// Builds the gesture recognizers this region sends its selection gestures from.
4088    fn build_gesture_recognizers(self: Handle<Self>) -> GestureRecognizerFactories {
4089        let mut gestures: GestureRecognizerFactories = Vec::new();
4090        let mouse = GestureRecognizerFactoryWithHandlers::new(
4091            TapAndPanGestureRecognizer::new,
4092            move |app, instance: Handle<TapAndPanGestureRecognizer>| {
4093                instance
4094                    .set_supported_devices(app, Some(HashSet::from([PointerDeviceKind::Mouse])));
4095                instance.set_on_tap_track_start(
4096                    app,
4097                    Some(Listener::handle_method(self, Self::handle_tap_track_start)),
4098                );
4099                instance.set_on_tap_track_reset(
4100                    app,
4101                    Some(Listener::handle_method(self, Self::handle_tap_track_reset)),
4102                );
4103                instance.set_on_tap_down(
4104                    app,
4105                    Some(Rc::new(move |app, details| {
4106                        self.start_new_mouse_selection_gesture(app, details)
4107                    })),
4108                );
4109                instance.set_on_tap_up(
4110                    app,
4111                    Some(Rc::new(move |app, details| {
4112                        self.handle_mouse_tap_up(app, details)
4113                    })),
4114                );
4115                instance.set_on_drag_start(
4116                    app,
4117                    Some(Rc::new(move |app, details| {
4118                        self.handle_mouse_drag_start(app, details)
4119                    })),
4120                );
4121                instance.set_on_drag_update(
4122                    app,
4123                    Some(Rc::new(move |app, details| {
4124                        self.handle_mouse_drag_update(app, details)
4125                    })),
4126                );
4127                instance.set_on_drag_end(
4128                    app,
4129                    Some(Rc::new(move |app, details| {
4130                        self.handle_mouse_drag_end(app, details)
4131                    })),
4132                );
4133                instance.set_on_cancel(
4134                    app,
4135                    Some(Listener::handle_method(self, Self::handle_gesture_cancel)),
4136                );
4137                instance.set_drag_start_behavior(app, DragStartBehavior::Down);
4138            },
4139        );
4140        gestures.push((
4141            TypeId::of::<TapAndPanGestureRecognizer>(),
4142            mouse.into_factory(),
4143        ));
4144
4145        let touch = GestureRecognizerFactoryWithHandlers::new(
4146            TapAndHorizontalDragGestureRecognizer::new,
4147            move |app, instance: Handle<TapAndHorizontalDragGestureRecognizer>| {
4148                instance.set_supported_devices(
4149                    app,
4150                    Some(
4151                        [
4152                            PointerDeviceKind::Touch,
4153                            PointerDeviceKind::Stylus,
4154                            PointerDeviceKind::InvertedStylus,
4155                            PointerDeviceKind::Trackpad,
4156                            PointerDeviceKind::Unknown,
4157                        ]
4158                        .into_iter()
4159                        .collect(),
4160                    ),
4161                );
4162                // iOS waits for the other gestures to lose; the others win eagerly.
4163                instance.set_eager_victory_on_drag(
4164                    app,
4165                    app.platform().target_platform() != TargetPlatform::IOS,
4166                );
4167                instance.set_on_tap_down(
4168                    app,
4169                    Some(Rc::new(move |app, details| {
4170                        self.start_new_mouse_selection_gesture(app, details)
4171                    })),
4172                );
4173                instance.set_on_tap_up(
4174                    app,
4175                    Some(Rc::new(move |app, details| {
4176                        self.handle_mouse_tap_up(app, details)
4177                    })),
4178                );
4179                instance.set_on_drag_start(
4180                    app,
4181                    Some(Rc::new(move |app, details| {
4182                        self.handle_mouse_drag_start(app, details)
4183                    })),
4184                );
4185                instance.set_on_drag_update(
4186                    app,
4187                    Some(Rc::new(move |app, details| {
4188                        self.handle_mouse_drag_update(app, details)
4189                    })),
4190                );
4191                instance.set_on_drag_end(
4192                    app,
4193                    Some(Rc::new(move |app, details| {
4194                        self.handle_mouse_drag_end(app, details)
4195                    })),
4196                );
4197                instance.set_on_cancel(
4198                    app,
4199                    Some(Listener::handle_method(self, Self::handle_gesture_cancel)),
4200                );
4201                instance.set_drag_start_behavior(app, DragStartBehavior::Down);
4202            },
4203        );
4204        gestures.push((
4205            TypeId::of::<TapAndHorizontalDragGestureRecognizer>(),
4206            touch.into_factory(),
4207        ));
4208
4209        let long_press = GestureRecognizerFactoryWithHandlers::new(
4210            LongPressGestureRecognizer::new,
4211            move |app, instance: Handle<LongPressGestureRecognizer>| {
4212                instance.set_supported_devices(
4213                    app,
4214                    Some(
4215                        [
4216                            PointerDeviceKind::Touch,
4217                            PointerDeviceKind::Stylus,
4218                            PointerDeviceKind::InvertedStylus,
4219                        ]
4220                        .into_iter()
4221                        .collect(),
4222                    ),
4223                );
4224                instance.set_on_long_press_start(
4225                    app,
4226                    Some(Rc::new(move |app, details| {
4227                        self.handle_touch_long_press_start(app, details)
4228                    })),
4229                );
4230                instance.set_on_long_press_move_update(
4231                    app,
4232                    Some(Rc::new(move |app, details| {
4233                        self.handle_touch_long_press_move_update(app, details)
4234                    })),
4235                );
4236                instance.set_on_long_press_end(
4237                    app,
4238                    Some(Rc::new(move |app, _details| {
4239                        self.handle_touch_long_press_end(app)
4240                    })),
4241                );
4242            },
4243        );
4244        gestures.push((
4245            TypeId::of::<LongPressGestureRecognizer>(),
4246            long_press.into_factory(),
4247        ));
4248
4249        let secondary_tap = GestureRecognizerFactoryWithHandlers::new(
4250            TapGestureRecognizer::new,
4251            move |app, instance: Handle<TapGestureRecognizer>| {
4252                instance.set_on_secondary_tap_down(
4253                    app,
4254                    Some(Rc::new(move |app, details| {
4255                        self.handle_right_click_down(app, details)
4256                    })),
4257                );
4258            },
4259        );
4260        gestures.push((
4261            TypeId::of::<TapGestureRecognizer>(),
4262            secondary_tap.into_factory(),
4263        ));
4264        gestures
4265    }
4266
4267    fn handle_tap_track_start(self: Handle<Self>, app: &mut App) {
4268        let keyboard = HardwareKeyboard::instance(app);
4269        let pressed = keyboard.logical_keys_pressed(app);
4270        app.get_mut(self).is_shift_pressed = pressed.contains(&LogicalKeyboardKey::SHIFT_LEFT)
4271            || pressed.contains(&LogicalKeyboardKey::SHIFT_RIGHT);
4272    }
4273
4274    fn handle_tap_track_reset(self: Handle<Self>, app: &mut App) {
4275        app.get_mut(self).is_shift_pressed = false;
4276    }
4277
4278    fn handle_gesture_cancel(self: Handle<Self>, app: &mut App) {
4279        self.clear_selection(app);
4280    }
4281
4282    fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
4283        let has_focus = self.focus_node(app).has_focus(app);
4284        if !has_focus && SchedulerBinding::lifecycle_state(app) == Some(AppLifecycleState::Resumed)
4285        {
4286            // Only clear the selection when the region loses focus while the application
4287            // runs: switching windows should keep it.
4288            self.clear_selection(app);
4289            self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
4290            self.finalize_selectable_region_status(app);
4291        }
4292    }
4293
4294    /// Dart's `_actions`: the actions a key press or a menu item runs, each but the dismiss one
4295    /// overridable by an ancestor `Actions`.
4296    fn build_actions(self: Handle<Self>, app: &mut App) -> HashMap<TypeId, ActionRef> {
4297        let context = self.context(app);
4298        let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
4299        let mut insert_overridable = |app: &mut App, intent: TypeId, action: ActionRef| {
4300            actions.insert(intent, AnyAction::overridable(app, action, context));
4301        };
4302        // Dart's `_SelectAllAction`.
4303        let select_all = NonOverrideAction::<SelectAllTextIntent>::new(
4304            app,
4305            Rc::new(move |app, _intent| {
4306                self.select_all(app, Some(SelectionChangedCause::Keyboard));
4307            }),
4308        );
4309        insert_overridable(
4310            app,
4311            TypeId::of::<SelectAllTextIntent>(),
4312            select_all.into_erased(),
4313        );
4314        // Dart's `_CopySelectionAction`.
4315        let copy = NonOverrideAction::<CopySelectionTextIntent>::new(
4316            app,
4317            Rc::new(move |app, _intent| self.copy_selected_content(app)),
4318        );
4319        insert_overridable(
4320            app,
4321            TypeId::of::<CopySelectionTextIntent>(),
4322            copy.into_erased(),
4323        );
4324
4325        // Dart's `_GranularlyExtendSelectionAction`.
4326        macro_rules! granular_action {
4327            ($intent:ty, $granularity:expr) => {{
4328                let action = NonOverrideAction::<$intent>::new(
4329                    app,
4330                    Rc::new(move |app, intent: &$intent| {
4331                        self.granularly_extend_selection(app, $granularity, intent.forward);
4332                    }),
4333                );
4334                insert_overridable(app, TypeId::of::<$intent>(), action.into_erased());
4335            }};
4336        }
4337        // Dart's `_GranularlyExtendCaretSelectionAction`.
4338        macro_rules! granular_caret_action {
4339            ($intent:ty, $granularity:expr) => {{
4340                let action = NonOverrideAction::<$intent>::new(
4341                    app,
4342                    Rc::new(move |app, intent: &$intent| {
4343                        if intent.collapse_selection {
4344                            // Selectable region never collapses selection.
4345                            return;
4346                        }
4347                        self.granularly_extend_selection(app, $granularity, intent.forward);
4348                    }),
4349                );
4350                insert_overridable(app, TypeId::of::<$intent>(), action.into_erased());
4351            }};
4352        }
4353        granular_action!(
4354            ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
4355            TextGranularity::Word
4356        );
4357        granular_action!(
4358            ExpandSelectionToDocumentBoundaryIntent,
4359            TextGranularity::Document
4360        );
4361        granular_action!(ExpandSelectionToLineBreakIntent, TextGranularity::Line);
4362        granular_caret_action!(ExtendSelectionByCharacterIntent, TextGranularity::Character);
4363        granular_caret_action!(
4364            ExtendSelectionToNextWordBoundaryIntent,
4365            TextGranularity::Word
4366        );
4367        granular_caret_action!(ExtendSelectionToLineBreakIntent, TextGranularity::Line);
4368        // Dart's `_DirectionallyExtendCaretSelectionAction`.
4369        let directional = NonOverrideAction::<ExtendSelectionVerticallyToAdjacentLineIntent>::new(
4370            app,
4371            Rc::new(move |app, intent| {
4372                if intent.collapse_selection {
4373                    // Selectable region never collapses selection.
4374                    return;
4375                }
4376                self.directionally_extend_selection(app, intent.forward);
4377            }),
4378        );
4379        insert_overridable(
4380            app,
4381            TypeId::of::<ExtendSelectionVerticallyToAdjacentLineIntent>(),
4382            directional.into_erased(),
4383        );
4384        granular_caret_action!(
4385            ExtendSelectionToDocumentBoundaryIntent,
4386            TextGranularity::Document
4387        );
4388        let dismiss = CallbackAction::<DismissIntent>::new(
4389            app,
4390            Rc::new(move |app, intent| {
4391                if self.hide_toolbar_if_visible(app) {
4392                    None
4393                } else {
4394                    let context = self.context(app);
4395                    Actions::invoke(app, context, intent)
4396                }
4397            }),
4398        );
4399        actions.insert(TypeId::of::<DismissIntent>(), dismiss.into_erased());
4400        actions
4401    }
4402
4403    fn build_info_for_magnifier(
4404        self: Handle<Self>,
4405        app: &mut App,
4406        global_gesture_position: Offset,
4407        selection_point: SelectionPoint,
4408    ) -> MagnifierInfo {
4409        let selectable = self
4410            .selectable(app)
4411            .expect("the region has a selectable selection");
4412        let transform = selectable.get_transform_to(app, None);
4413        let storage = transform.to_flutter_array();
4414        let global_transform_as_offset = Offset::new(storage[12] as f64, storage[13] as f64);
4415        let global_selection_point_position =
4416            selection_point.local_position + global_transform_as_offset;
4417        let caret_rect = Rect::from_ltwh(
4418            global_selection_point_position.dx(),
4419            global_selection_point_position.dy() - selection_point.line_height,
4420            0.0,
4421            selection_point.line_height,
4422        );
4423        let selectable_size = selectable.size(app);
4424        let field_bounds = Rect::from_ltwh(
4425            global_transform_as_offset.dx(),
4426            global_transform_as_offset.dy(),
4427            selectable_size.width(),
4428            selectable_size.height(),
4429        );
4430        MagnifierInfo::new(
4431            global_gesture_position,
4432            caret_rect,
4433            field_bounds,
4434            field_bounds,
4435        )
4436    }
4437
4438    fn handle_selection_start_handle_drag_start(
4439        self: Handle<Self>,
4440        app: &mut App,
4441        details: DragStartDetails,
4442    ) {
4443        let Some(start) = self.selection_geometry(app).start_selection_point else {
4444            return;
4445        };
4446        let selectable = self.selectable(app).expect("a selection has a selectable");
4447        let global_transform = selectable.get_transform_to(app, None);
4448        app.get_mut(self).selection_start_handle_drag_position =
4449            transform_point(&global_transform, start.local_position);
4450        let info = self.build_info_for_magnifier(app, details.global_position, start);
4451        if let Some(overlay) = self.selection_overlay(app) {
4452            overlay.show_magnifier(app, info);
4453        }
4454        self.update_selected_content_if_needed(app);
4455    }
4456
4457    fn handle_selection_start_handle_drag_update(
4458        self: Handle<Self>,
4459        app: &mut App,
4460        details: DragUpdateDetails,
4461    ) {
4462        let Some(start) = self.selection_geometry(app).start_selection_point else {
4463            return;
4464        };
4465        let drag_position = app.get(self).selection_start_handle_drag_position + details.delta;
4466        let state = app.get_mut(self);
4467        state.selection_start_handle_drag_position = drag_position;
4468        // The value corresponds to the paint origin of the selection handle.
4469        // Offset it to the center of the line to make it feel more natural.
4470        state.selection_start_position =
4471            Some(drag_position - Offset::new(0.0, start.line_height / 2.0));
4472        self.trigger_selection_start_edge_update(app, None);
4473        let info = self.build_info_for_magnifier(app, details.global_position, start);
4474        if let Some(overlay) = self.selection_overlay(app) {
4475            overlay.update_magnifier(app, info);
4476        }
4477        self.update_selected_content_if_needed(app);
4478        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
4479    }
4480
4481    fn handle_selection_end_handle_drag_start(
4482        self: Handle<Self>,
4483        app: &mut App,
4484        details: DragStartDetails,
4485    ) {
4486        let Some(end) = self.selection_geometry(app).end_selection_point else {
4487            return;
4488        };
4489        let selectable = self.selectable(app).expect("a selection has a selectable");
4490        let global_transform = selectable.get_transform_to(app, None);
4491        app.get_mut(self).selection_end_handle_drag_position =
4492            transform_point(&global_transform, end.local_position);
4493        let info = self.build_info_for_magnifier(app, details.global_position, end);
4494        if let Some(overlay) = self.selection_overlay(app) {
4495            overlay.show_magnifier(app, info);
4496        }
4497        self.update_selected_content_if_needed(app);
4498    }
4499
4500    fn handle_selection_end_handle_drag_update(
4501        self: Handle<Self>,
4502        app: &mut App,
4503        details: DragUpdateDetails,
4504    ) {
4505        let Some(end) = self.selection_geometry(app).end_selection_point else {
4506            return;
4507        };
4508        let drag_position = app.get(self).selection_end_handle_drag_position + details.delta;
4509        let state = app.get_mut(self);
4510        state.selection_end_handle_drag_position = drag_position;
4511        // The value corresponds to the paint origin of the selection handle.
4512        // Offset it to the center of the line to make it feel more natural.
4513        state.selection_end_position =
4514            Some(drag_position - Offset::new(0.0, end.line_height / 2.0));
4515        self.trigger_selection_end_edge_update(app, None);
4516        let info = self.build_info_for_magnifier(app, details.global_position, end);
4517        if let Some(overlay) = self.selection_overlay(app) {
4518            overlay.update_magnifier(app, info);
4519        }
4520        self.update_selected_content_if_needed(app);
4521        self.set_selection_status(app, SelectableRegionSelectionStatus::Changing);
4522    }
4523
4524    fn handle_any_drag_end(self: Handle<Self>, app: &mut App, _details: DragEndDetails) {
4525        let dragging_handles = self.selection_overlay(app).is_some_and(|overlay| {
4526            overlay.is_dragging_start_handle(app) || overlay.is_dragging_end_handle(app)
4527        });
4528        if !dragging_handles {
4529            if let Some(overlay) = self.selection_overlay(app) {
4530                overlay.hide_magnifier(app);
4531            }
4532            self.show_toolbar(app, None);
4533        }
4534        self.finalize_selection(app);
4535        self.update_selected_content_if_needed(app);
4536        self.finalize_selectable_region_status(app);
4537    }
4538}
4539
4540impl State for SelectableRegionState {
4541    type Widget = SelectableRegion;
4542    crate::state_accessors!();
4543
4544    fn init_state(self: Handle<Self>, app: &mut App) {
4545        let delegate = PlainStaticSelectionContainerDelegate::new(app);
4546        let start_handle_layer_link = LayerLink::new(app);
4547        let end_handle_layer_link = LayerLink::new(app);
4548        let toolbar_layer_link = LayerLink::new(app);
4549        let local_focus_node = if self.widget(app).focus_node.is_none() {
4550            Some(FocusNode::new(app))
4551        } else {
4552            None
4553        };
4554        let selection_status_notifier = app.create(SelectableRegionSelectionStatusNotifier::new());
4555        {
4556            let state = app.get_mut(self);
4557            state.selection_delegate = Some(delegate);
4558            state.start_handle_layer_link = Some(start_handle_layer_link);
4559            state.end_handle_layer_link = Some(end_handle_layer_link);
4560            state.toolbar_layer_link = Some(toolbar_layer_link);
4561            state.local_focus_node = local_focus_node;
4562            state.selection_status_notifier = Some(selection_status_notifier);
4563        }
4564        self.focus_node(app).add_listener(
4565            app,
4566            Listener::handle_method(self, Self::handle_focus_changed),
4567        );
4568        let gestures = self.build_gesture_recognizers();
4569        app.get_mut(self).gesture_recognizers = Some(gestures);
4570    }
4571
4572    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectableRegion) {
4573        let new_focus_node = self.widget(app).focus_node.clone();
4574        if new_focus_node.as_ref().map(|node| node.id())
4575            != old_widget.focus_node.as_ref().map(|node| node.id())
4576        {
4577            if old_widget.focus_node.is_none() && new_focus_node.is_some() {
4578                if let Some(local) = app.get_mut(self).local_focus_node.take() {
4579                    local.handle().remove_listener(
4580                        app,
4581                        &Listener::handle_method(self, Self::handle_focus_changed),
4582                    );
4583                    local.handle().dispose(app);
4584                }
4585            } else if let (None, Some(old_focus_node)) = (&new_focus_node, &old_widget.focus_node) {
4586                old_focus_node.handle().remove_listener(
4587                    app,
4588                    &Listener::handle_method(self, Self::handle_focus_changed),
4589                );
4590                // Dart's `_focusNode` creates the local node on first read.
4591                let local = FocusNode::new(app);
4592                app.get_mut(self).local_focus_node = Some(local);
4593            }
4594            self.focus_node(app).add_listener(
4595                app,
4596                Listener::handle_method(self, Self::handle_focus_changed),
4597            );
4598            let has_focus = self.focus_node(app).has_focus(app);
4599            let old_has_focus = old_widget
4600                .focus_node
4601                .as_ref()
4602                .map(|node| node.handle().has_focus(app));
4603            if Some(has_focus) != old_has_focus {
4604                self.handle_focus_changed(app);
4605            }
4606        }
4607    }
4608
4609    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
4610        let platform = app.platform().target_platform();
4611        if !matches!(platform, TargetPlatform::Android | TargetPlatform::IOS) {
4612            return;
4613        }
4614        // Hide the toolbar on mobile when the orientation changes.
4615        let orientation = MediaQuery::orientation_of(app, self.context(app));
4616        let last_orientation = app.get(self).last_orientation;
4617        if last_orientation.is_none() {
4618            app.get_mut(self).last_orientation = Some(orientation);
4619            return;
4620        }
4621        if last_orientation != Some(orientation) {
4622            app.get_mut(self).last_orientation = Some(orientation);
4623            self.hide_toolbar(app, platform == TargetPlatform::Android);
4624        }
4625    }
4626
4627    fn dispose(self: Handle<Self>, app: &mut App) {
4628        if let Some(selectable) = app.get(self).selectable {
4629            selectable.remove_listener(
4630                app,
4631                &Listener::handle_method(self, Self::update_selection_status),
4632            );
4633            selectable.push_handle_layers(app, None, None);
4634        }
4635        let delegate = self.selection_delegate(app);
4636        MultiSelectableSelectionContainerDelegate::dispose(delegate, app);
4637        let notifier = self.selection_status_notifier(app);
4638        notifier.dispose(app);
4639        if let Some(local_focus_node) = app.get_mut(self).local_focus_node.take() {
4640            local_focus_node.handle().remove_listener(
4641                app,
4642                &Listener::handle_method(self, Self::handle_focus_changed),
4643            );
4644            local_focus_node.handle().dispose(app);
4645        } else if let Some(focus_node) = self.widget(app).focus_node.clone() {
4646            focus_node.handle().remove_listener(
4647                app,
4648                &Listener::handle_method(self, Self::handle_focus_changed),
4649            );
4650        }
4651        if let Some(overlay) = app.get_mut(self).selection_overlay.take() {
4652            overlay.hide_magnifier(app);
4653            overlay.dispose(app);
4654        }
4655    }
4656
4657    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
4658        let widget = self.widget(app);
4659        let notifier = self.selection_status_notifier(app);
4660        let delegate = self.selection_delegate(app).keep(app).into_erased();
4661        let registrar = SelectionRegistrar::as_selection_registrar(self).keep(app);
4662        let container =
4663            SelectionContainer::new(delegate, widget.child.clone()).registrar(registrar);
4664        let result = SelectableRegionSelectionStatusScope::new(notifier, container).into_widget();
4665        let gestures = app
4666            .get(self)
4667            .gesture_recognizers
4668            .clone()
4669            .expect("the gestures are created in init_state");
4670        if app.get(self).actions.is_none() {
4671            let actions = self.build_actions(app);
4672            app.get_mut(self).actions = Some(actions);
4673        }
4674        let actions = app.get(self).actions.clone().expect("built above");
4675        let focus_node = self.focus_node(app);
4676        let toolbar_layer_link = app
4677            .get(self)
4678            .toolbar_layer_link
4679            .clone()
4680            .expect("created in init_state");
4681        let focus = Focus::with_external_focus_node(result, focus_node).into_widget();
4682        let actions = Actions::new(actions, focus).into_widget();
4683        let detector = RawGestureDetector::new()
4684            .gestures(gestures)
4685            .behavior(HitTestBehavior::Translucent)
4686            .child(actions)
4687            .into_widget();
4688        let target = CompositedTransformTarget::new(toolbar_layer_link)
4689            .child(detector)
4690            .into_widget();
4691        TapRegion::new(target)
4692            .group_id(TypeId::of::<SelectableRegion>())
4693            .into_widget()
4694    }
4695}
4696
4697/// Dart's `_NonOverrideAction`: an action that, when it overrides another, runs the action it
4698/// overrides instead of its own body.
4699///
4700/// Dart's subclasses (`_SelectAllAction`, `_CopySelectionAction`, the granular and directional
4701/// extend actions) are the `invoke_action` closures `SelectableRegionState::build_actions` gives.
4702struct NonOverrideAction<T: Intent> {
4703    action: ActionData,
4704    invoke_action: InvokeAction<T>,
4705}
4706
4707/// Dart's `_NonOverrideAction.invokeAction`, as a subclass implements it.
4708type InvokeAction<T> = Rc<dyn Fn(&mut App, &T)>;
4709
4710impl<T: Intent> NonOverrideAction<T> {
4711    fn new(app: &mut App, invoke_action: InvokeAction<T>) -> Ref<NonOverrideAction<T>> {
4712        app.create(NonOverrideAction {
4713            action: ActionData::new(),
4714            invoke_action,
4715        })
4716    }
4717}
4718
4719impl<T: Intent> Action for NonOverrideAction<T> {
4720    type Intent = T;
4721    crate::action_accessors!();
4722    crate::context_action_overrides!();
4723}
4724
4725impl<T: Intent> ContextAction for NonOverrideAction<T> {
4726    fn invoke(
4727        self: Handle<Self>,
4728        app: &mut App,
4729        intent: &T,
4730        _context: Option<BuildContext>,
4731    ) -> Option<Rc<dyn std::any::Any>> {
4732        if let Some(calling_action) = Action::calling_action(self, app) {
4733            return calling_action.invoke(app, intent, None);
4734        }
4735        let invoke_action = Rc::clone(&app.get(self).invoke_action);
4736        invoke_action(app, intent);
4737        None
4738    }
4739}
4740
4741impl SelectionRegistrar for SelectableRegionState {
4742    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4743        debug_assert!(app.get(self).selectable.is_none());
4744        app.get_mut(self).selectable = Some(selectable);
4745        selectable.add_listener(
4746            app,
4747            Listener::handle_method(self, Self::update_selection_status),
4748        );
4749        let (start, end) = {
4750            let state = app.get(self);
4751            (
4752                state.start_handle_layer_link.clone(),
4753                state.end_handle_layer_link.clone(),
4754            )
4755        };
4756        selectable.push_handle_layers(app, start, end);
4757    }
4758
4759    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4760        debug_assert!(app.get(self).selectable == Some(selectable));
4761        selectable.remove_listener(
4762            app,
4763            &Listener::handle_method(self, Self::update_selection_status),
4764        );
4765        selectable.push_handle_layers(app, None, None);
4766        app.get_mut(self).selectable = None;
4767    }
4768}
4769
4770#[cfg(test)]
4771mod tests {
4772    //! `selection_container_test.dart`'s cases, which build a
4773    //! [`MultiSelectableSelectionContainerDelegate`], and `selectable_region_test.dart`'s
4774    //! numbers for the delegate itself.
4775
4776    use waft_embedder::{Offset, Rect, Size, TextDirection, TextPosition};
4777    use waft_foundation::{App, Handle, Ref};
4778    use waft_rendering::{RenderBox, RenderHandle, RenderParagraph};
4779
4780    use super::*;
4781    use crate::Placeholder;
4782    use crate::framework::{IntoWidget, WidgetRef};
4783    use std::time::Duration;
4784    use waft_scheduler::{FrameTarget, SchedulerBinding};
4785
4786    use crate::testing::{
4787        TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
4788    };
4789    use crate::widgets::basic::{Builder, Center, Column, SizedBox};
4790    use crate::widgets::selection_container::{SelectionContainer, SelectionRegistrarScope};
4791    use crate::widgets::text::Text;
4792
4793    /// A [`Text`] under the enclosing [`SelectionContainer`], as Flutter's is under a
4794    /// `SelectableRegion`; under a disabled container it is simply not selectable.
4795    fn selectable_text(text: &'static str) -> WidgetRef {
4796        Text::new(text)
4797            .text_direction(TextDirection::Ltr)
4798            .into_widget()
4799    }
4800
4801    /// `selectable_region_test.dart`'s `textOffsetToPosition`: the global position just above
4802    /// the bottom of the line at the caret at `offset` in `paragraph`.
4803    fn text_offset_to_position(
4804        tester: &WidgetTester,
4805        paragraph: RenderHandle<RenderParagraph>,
4806        offset: i32,
4807    ) -> Offset {
4808        tester.update(|app| {
4809            let caret = Rect::from_ltwh(0.0, 0.0, 2.0, 20.0);
4810            let local_offset =
4811                paragraph.get_offset_for_caret(app, TextPosition::new(offset), caret)
4812                    + Offset::new(0.0, paragraph.preferred_line_height(app));
4813            paragraph.as_box().local_to_global(app, local_offset, None) + Offset::new(0.0, -2.0)
4814        })
4815    }
4816
4817    /// `paragraph_test.dart`'s and `selectable_region_test.dart`'s `TestSelectionRegistrar`: it
4818    /// holds what registers with it.
4819    struct TestSelectionRegistrar {
4820        selectables: Vec<AnySelectable>,
4821    }
4822
4823    impl SelectionRegistrar for TestSelectionRegistrar {
4824        fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4825            set_add(&mut app.get_mut(self).selectables, selectable);
4826        }
4827
4828        fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4829            set_remove(&mut app.get_mut(self).selectables, selectable);
4830        }
4831    }
4832
4833    /// `selection_container_test.dart`'s `TestContainerDelegate`: the two members the container
4834    /// would ask for throw, since the cases here never send it a selection event.
4835    struct TestContainerDelegate {
4836        selection_container_delegate: SelectionContainerDelegateData,
4837        multi_selectable_selection_container_delegate:
4838            MultiSelectableSelectionContainerDelegateData,
4839    }
4840
4841    impl TestContainerDelegate {
4842        fn new(app: &mut App) -> Ref<TestContainerDelegate> {
4843            app.create(TestContainerDelegate {
4844                selection_container_delegate: SelectionContainerDelegateData::new(),
4845                multi_selectable_selection_container_delegate:
4846                    MultiSelectableSelectionContainerDelegateData::new(),
4847            })
4848        }
4849    }
4850
4851    impl SelectionContainerDelegate for TestContainerDelegate {
4852        fn selection_container_delegate_data(
4853            self: Handle<Self>,
4854            app: &App,
4855        ) -> &SelectionContainerDelegateData {
4856            &app.get(self).selection_container_delegate
4857        }
4858
4859        fn selection_container_delegate_data_mut(
4860            self: Handle<Self>,
4861            app: &mut App,
4862        ) -> &mut SelectionContainerDelegateData {
4863            &mut app.get_mut(self).selection_container_delegate
4864        }
4865    }
4866
4867    impl MultiSelectableSelectionContainerDelegate for TestContainerDelegate {
4868        crate::multi_selectable_selection_container_delegate_accessors!();
4869
4870        fn ensure_child_updated(self: Handle<Self>, _app: &mut App, _selectable: AnySelectable) {
4871            panic!("UnimplementedError");
4872        }
4873
4874        fn dispatch_selection_event_to_child(
4875            self: Handle<Self>,
4876            _app: &mut App,
4877            _selectable: AnySelectable,
4878            _event: &SelectionEvent,
4879        ) -> SelectionResult {
4880            panic!("UnimplementedError");
4881        }
4882    }
4883
4884    impl SelectionHandler for TestContainerDelegate {
4885        fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
4886            MultiSelectableSelectionContainerDelegateBase::value(self, app)
4887        }
4888
4889        fn push_handle_layers(
4890            self: Handle<Self>,
4891            app: &mut App,
4892            start_handle: Option<Ref<LayerLink>>,
4893            end_handle: Option<Ref<LayerLink>>,
4894        ) {
4895            MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
4896                self,
4897                app,
4898                start_handle,
4899                end_handle,
4900            );
4901        }
4902
4903        fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
4904            MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
4905        }
4906
4907        fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
4908            MultiSelectableSelectionContainerDelegateBase::selection(self, app)
4909        }
4910
4911        fn dispatch_selection_event(
4912            self: Handle<Self>,
4913            app: &mut App,
4914            event: &SelectionEvent,
4915        ) -> SelectionResult {
4916            MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(
4917                self, app, event,
4918            )
4919        }
4920
4921        fn content_length(self: Handle<Self>, app: &App) -> usize {
4922            MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
4923        }
4924    }
4925
4926    impl SelectionRegistrar for TestContainerDelegate {
4927        fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4928            MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
4929        }
4930
4931        fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4932            MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
4933        }
4934    }
4935
4936    impl ChangeNotifier for TestContainerDelegate {
4937        fn change_notifier_data(&self) -> &ChangeNotifierData {
4938            &self
4939                .multi_selectable_selection_container_delegate
4940                .change_notifier
4941        }
4942
4943        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
4944            &mut self
4945                .multi_selectable_selection_container_delegate
4946                .change_notifier
4947        }
4948    }
4949
4950    /// `selectable_region_test.dart`'s `ColumnSelectionContainerDelegate`: the selected
4951    /// contents of all selectables, separated by a new line.
4952    struct ColumnSelectionContainerDelegate {
4953        selection_container_delegate: SelectionContainerDelegateData,
4954        multi_selectable_selection_container_delegate:
4955            MultiSelectableSelectionContainerDelegateData,
4956        static_selection_container_delegate: StaticSelectionContainerDelegateData,
4957    }
4958
4959    impl ColumnSelectionContainerDelegate {
4960        fn new(app: &mut App) -> Ref<ColumnSelectionContainerDelegate> {
4961            app.create(ColumnSelectionContainerDelegate {
4962                selection_container_delegate: SelectionContainerDelegateData::new(),
4963                multi_selectable_selection_container_delegate:
4964                    MultiSelectableSelectionContainerDelegateData::new(),
4965                static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
4966            })
4967        }
4968    }
4969
4970    impl SelectionContainerDelegate for ColumnSelectionContainerDelegate {
4971        fn selection_container_delegate_data(
4972            self: Handle<Self>,
4973            app: &App,
4974        ) -> &SelectionContainerDelegateData {
4975            &app.get(self).selection_container_delegate
4976        }
4977
4978        fn selection_container_delegate_data_mut(
4979            self: Handle<Self>,
4980            app: &mut App,
4981        ) -> &mut SelectionContainerDelegateData {
4982            &mut app.get_mut(self).selection_container_delegate
4983        }
4984    }
4985
4986    impl MultiSelectableSelectionContainerDelegate for ColumnSelectionContainerDelegate {
4987        crate::multi_selectable_selection_container_delegate_accessors!();
4988        crate::static_selection_container_delegate_overrides!();
4989    }
4990
4991    impl StaticSelectionContainerDelegate for ColumnSelectionContainerDelegate {
4992        crate::static_selection_container_delegate_accessors!();
4993    }
4994
4995    impl SelectionHandler for ColumnSelectionContainerDelegate {
4996        fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
4997            StaticSelectionContainerDelegateBase::value(self, app)
4998        }
4999
5000        fn push_handle_layers(
5001            self: Handle<Self>,
5002            app: &mut App,
5003            start_handle: Option<Ref<LayerLink>>,
5004            end_handle: Option<Ref<LayerLink>>,
5005        ) {
5006            StaticSelectionContainerDelegateBase::push_handle_layers(
5007                self,
5008                app,
5009                start_handle,
5010                end_handle,
5011            );
5012        }
5013
5014        fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
5015            let selectables = self
5016                .multi_selectable_selection_container_delegate_data(app)
5017                .selectables
5018                .clone();
5019            let selections: Vec<SelectedContent> = selectables
5020                .iter()
5021                .filter_map(|selectable| selectable.selected_content(app))
5022                .collect();
5023            if selections.is_empty() {
5024                return None;
5025            }
5026            let plain_text = selections
5027                .iter()
5028                .map(|selection| selection.plain_text.clone())
5029                .collect::<Vec<String>>()
5030                .join("\n");
5031            Some(SelectedContent::new(plain_text))
5032        }
5033
5034        fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
5035            StaticSelectionContainerDelegateBase::selection(self, app)
5036        }
5037
5038        fn dispatch_selection_event(
5039            self: Handle<Self>,
5040            app: &mut App,
5041            event: &SelectionEvent,
5042        ) -> SelectionResult {
5043            StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
5044        }
5045
5046        fn content_length(self: Handle<Self>, app: &App) -> usize {
5047            StaticSelectionContainerDelegateBase::content_length(self, app)
5048        }
5049    }
5050
5051    impl SelectionRegistrar for ColumnSelectionContainerDelegate {
5052        crate::static_selection_container_delegate_selection_registrar!();
5053    }
5054
5055    impl ChangeNotifier for ColumnSelectionContainerDelegate {
5056        fn change_notifier_data(&self) -> &ChangeNotifierData {
5057            &self
5058                .multi_selectable_selection_container_delegate
5059                .change_notifier
5060        }
5061
5062        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
5063            &mut self
5064                .multi_selectable_selection_container_delegate
5065                .change_notifier
5066        }
5067    }
5068
5069    // ---- SelectableRegion ----
5070
5071    use std::cell::RefCell;
5072
5073    use waft_gestures::K_PRIMARY_BUTTON;
5074
5075    use crate::testing::TestWidgetsApp;
5076
5077    /// The paragraph showing `text`.
5078    fn paragraph_showing(tester: &WidgetTester, text: &str) -> RenderHandle<RenderParagraph> {
5079        let paragraphs = tester.all::<RenderParagraph>();
5080        tester.update(|app| {
5081            *paragraphs
5082                .iter()
5083                .find(|paragraph| paragraph.text(app).to_plain_text(true, true) == text)
5084                .unwrap_or_else(|| panic!("a paragraph showing {text}"))
5085        })
5086    }
5087
5088    /// `paragraph`'s one selection, as its base and extent.
5089    fn paragraph_selection(
5090        tester: &WidgetTester,
5091        paragraph: RenderHandle<RenderParagraph>,
5092    ) -> (i32, i32) {
5093        tester.update(|app| {
5094            let selections = paragraph.selections(app);
5095            assert_eq!(selections.len(), 1, "one selection");
5096            (selections[0].base_offset, selections[0].extent_offset)
5097        })
5098    }
5099
5100    /// `selectable_region_test.dart`'s `_selectableRegion`: a region with an empty context menu
5101    /// and `testTextSelectionHandleControls`.
5102    fn selectable_region<K: 'static>(child: impl IntoWidget<K>) -> SelectableRegion {
5103        SelectableRegion::new(crate::testing::test_text_selection_handle_controls(), child)
5104            .context_menu_builder(Rc::new(|_app, _context, _state| {
5105                SizedBox::shrink().into_widget()
5106            }))
5107    }
5108
5109    /// Pumps `TestWidgetsApp(home: _selectableRegion(child: child))`.
5110    fn pump_region<K: 'static>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
5111        tester.pump_widget(TestWidgetsApp::new().home(selectable_region(child)));
5112    }
5113
5114    // selectable_region_test.dart 'mouse can select single text on desktop platforms'.
5115    #[test]
5116    fn mouse_can_select_single_text_on_desktop_platforms() {
5117        test_widgets_variant(TargetPlatformVariant::desktop(), |tester| {
5118            pump_region(tester, Center::new().child(Text::new("How are you")));
5119            let paragraph = paragraph_showing(tester, "How are you");
5120            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5121            let at = text_offset_to_position(tester, paragraph, 2);
5122            tester.down(&mut gesture, at);
5123            tester.pump();
5124
5125            let at = text_offset_to_position(tester, paragraph, 4);
5126            tester.move_to(&mut gesture, at, true);
5127            tester.pump();
5128            assert_eq!(paragraph_selection(tester, paragraph), (2, 4));
5129
5130            let at = text_offset_to_position(tester, paragraph, 6);
5131            tester.move_to(&mut gesture, at, true);
5132            tester.pump();
5133            assert_eq!(paragraph_selection(tester, paragraph), (2, 6));
5134
5135            // Check backward selection.
5136            let at = text_offset_to_position(tester, paragraph, 1);
5137            tester.move_to(&mut gesture, at, true);
5138            tester.pump();
5139            assert_eq!(paragraph_selection(tester, paragraph), (2, 1));
5140
5141            // Start a new drag.
5142            tester.up(&gesture);
5143            tester.pump_and_settle();
5144
5145            let at = text_offset_to_position(tester, paragraph, 5);
5146            tester.down(&mut gesture, at);
5147            tester.pump_and_settle();
5148            assert_eq!(paragraph_selection(tester, paragraph), (5, 5));
5149
5150            // Selecting across line should select to the end.
5151            let at = text_offset_to_position(tester, paragraph, 5) + Offset::new(0.0, 200.0);
5152            tester.move_to(&mut gesture, at, true);
5153            tester.pump();
5154            assert_eq!(paragraph_selection(tester, paragraph), (5, 11));
5155
5156            tester.up(&gesture);
5157            tester.remove_pointer(&gesture);
5158        });
5159    }
5160
5161    // selectable_region_test.dart 'mouse can select multiple widgets'.
5162    #[test]
5163    fn mouse_can_select_multiple_widgets() {
5164        test_widgets(|tester| {
5165            pump_region(tester, three_texts());
5166            let paragraph_1 = paragraph_showing(tester, "How are you?");
5167            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5168            let at = text_offset_to_position(tester, paragraph_1, 2);
5169            tester.down(&mut gesture, at);
5170            tester.pump();
5171
5172            let at = text_offset_to_position(tester, paragraph_1, 4);
5173            tester.move_to(&mut gesture, at, true);
5174            tester.pump();
5175            assert_eq!(paragraph_selection(tester, paragraph_1), (2, 4));
5176
5177            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
5178            let at = text_offset_to_position(tester, paragraph_2, 5);
5179            tester.move_to(&mut gesture, at, true);
5180            // Should select the rest of paragraph 1.
5181            assert_eq!(paragraph_selection(tester, paragraph_1), (2, 12));
5182            assert_eq!(paragraph_selection(tester, paragraph_2), (0, 5));
5183
5184            let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
5185            let at = text_offset_to_position(tester, paragraph_3, 6);
5186            tester.move_to(&mut gesture, at, true);
5187            assert_eq!(paragraph_selection(tester, paragraph_1), (2, 12));
5188            assert_eq!(paragraph_selection(tester, paragraph_2), (0, 14));
5189            assert_eq!(paragraph_selection(tester, paragraph_3), (0, 6));
5190
5191            tester.up(&gesture);
5192            tester.remove_pointer(&gesture);
5193        });
5194    }
5195
5196    // selectable_region_test.dart 'mouse can reverse selection'.
5197    #[test]
5198    fn mouse_can_reverse_selection() {
5199        test_widgets(|tester| {
5200            pump_region(tester, three_texts());
5201            let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
5202            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5203            let at = text_offset_to_position(tester, paragraph_3, 10);
5204            tester.down(&mut gesture, at);
5205            tester.pump();
5206
5207            let at = text_offset_to_position(tester, paragraph_3, 4);
5208            tester.move_to(&mut gesture, at, true);
5209            tester.pump();
5210            assert_eq!(paragraph_selection(tester, paragraph_3), (10, 4));
5211
5212            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
5213            let at = text_offset_to_position(tester, paragraph_2, 5);
5214            tester.move_to(&mut gesture, at, true);
5215            assert_eq!(paragraph_selection(tester, paragraph_3), (10, 0));
5216            assert_eq!(paragraph_selection(tester, paragraph_2), (14, 5));
5217
5218            let paragraph_1 = paragraph_showing(tester, "How are you?");
5219            let at = text_offset_to_position(tester, paragraph_1, 6);
5220            tester.move_to(&mut gesture, at, true);
5221            assert_eq!(paragraph_selection(tester, paragraph_3), (10, 0));
5222            assert_eq!(paragraph_selection(tester, paragraph_2), (14, 0));
5223            assert_eq!(paragraph_selection(tester, paragraph_1), (12, 6));
5224
5225            tester.up(&gesture);
5226            tester.remove_pointer(&gesture);
5227        });
5228    }
5229
5230    /// `selectable_region_test.dart`'s `SelectionSpy`.
5231    #[derive(Debug)]
5232    struct SelectionSpy;
5233
5234    impl crate::framework::RenderObjectWidget for SelectionSpy {
5235        type RenderObject = RenderSelectionSpy;
5236
5237        fn create_render_object(
5238            &self,
5239            app: &mut App,
5240            context: BuildContext,
5241        ) -> waft_rendering::AnyRenderObject {
5242            let registrar = SelectionContainer::maybe_of(app, context);
5243            let spy = RenderHandle::new_box(
5244                app,
5245                RenderSelectionSpy {
5246                    render_object: waft_rendering::RenderObjectData::new(),
5247                    render_box: waft_rendering::RenderBoxData::new(),
5248                    selection_registrant: waft_rendering::SelectionRegistrantData::new(),
5249                    listeners: Vec::new(),
5250                    events: Vec::new(),
5251                },
5252            );
5253            waft_rendering::SelectionRegistrant::set_registrar(spy.handle(), app, registrar);
5254            spy.as_object()
5255        }
5256    }
5257
5258    impl crate::framework::LeafRenderObjectWidget for SelectionSpy {}
5259
5260    /// `selectable_region_test.dart`'s `RenderSelectionSpy`: records the events it is sent and
5261    /// answers that the selection ends at it.
5262    struct RenderSelectionSpy {
5263        render_object: waft_rendering::RenderObjectData,
5264        render_box: waft_rendering::RenderBoxData,
5265        selection_registrant: waft_rendering::SelectionRegistrantData,
5266        listeners: Vec<Listener>,
5267        events: Vec<SelectionEvent>,
5268    }
5269
5270    impl waft_rendering::RenderObject for RenderSelectionSpy {
5271        waft_rendering::render_object_accessors!();
5272
5273        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
5274            let size = self.constraints(app).biggest();
5275            self.set_size(app, size);
5276        }
5277
5278        fn dispose(self: RenderHandle<Self>, app: &mut App) {
5279            waft_rendering::SelectionRegistrant::dispose_selection_registrant(self.handle(), app);
5280            waft_rendering::RenderObjectBase::dispose(self, app);
5281        }
5282    }
5283
5284    impl RenderBox for RenderSelectionSpy {
5285        waft_rendering::render_box_accessors!();
5286    }
5287
5288    impl waft_foundation::ListenableObject for RenderSelectionSpy {
5289        fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
5290            app.get_mut(self).listeners.push(listener);
5291        }
5292
5293        fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
5294            app.get_mut(self).listeners.retain(|held| held != listener);
5295        }
5296    }
5297
5298    impl SelectionHandler for RenderSelectionSpy {
5299        fn value(self: Handle<Self>, _app: &App) -> SelectionGeometry {
5300            let point = SelectionPoint::new(Offset::ZERO, 0.0, TextSelectionHandleType::Left);
5301            SelectionGeometry::new(SelectionStatus::Uncollapsed, true)
5302                .start_selection_point(Some(point))
5303                .end_selection_point(Some(point))
5304        }
5305
5306        fn push_handle_layers(
5307            self: Handle<Self>,
5308            _app: &mut App,
5309            _start_handle: Option<Ref<LayerLink>>,
5310            _end_handle: Option<Ref<LayerLink>>,
5311        ) {
5312        }
5313
5314        fn selected_content(self: Handle<Self>, _app: &App) -> Option<SelectedContent> {
5315            Some(SelectedContent::new("content"))
5316        }
5317
5318        fn selection(self: Handle<Self>, _app: &App) -> Option<SelectedContentRange> {
5319            None
5320        }
5321
5322        fn dispatch_selection_event(
5323            self: Handle<Self>,
5324            app: &mut App,
5325            event: &SelectionEvent,
5326        ) -> SelectionResult {
5327            app.get_mut(self).events.push(event.clone());
5328            SelectionResult::End
5329        }
5330
5331        fn content_length(self: Handle<Self>, _app: &App) -> usize {
5332            1
5333        }
5334    }
5335
5336    impl waft_rendering::Selectable for RenderSelectionSpy {
5337        fn get_transform_to(
5338            self: Handle<Self>,
5339            app: &App,
5340            ancestor: Option<waft_rendering::AnyRenderObject>,
5341        ) -> waft_embedder::Matrix4 {
5342            RenderHandle::from_handle(self)
5343                .as_object()
5344                .get_transform_to(app, ancestor)
5345        }
5346
5347        fn size(self: Handle<Self>, app: &mut App) -> Size {
5348            RenderBox::size(RenderHandle::from_handle(self), app)
5349        }
5350
5351        fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
5352            vec![
5353                RenderHandle::from_handle(self)
5354                    .as_object()
5355                    .paint_bounds(app),
5356            ]
5357        }
5358
5359        fn dispose_selectable(self: Handle<Self>, _app: &mut App) {}
5360    }
5361
5362    impl waft_rendering::SelectionRegistrant for RenderSelectionSpy {
5363        fn selection_registrant_data(
5364            self: Handle<Self>,
5365            app: &App,
5366        ) -> &waft_rendering::SelectionRegistrantData {
5367            &app.get(self).selection_registrant
5368        }
5369
5370        fn selection_registrant_data_mut(
5371            self: Handle<Self>,
5372            app: &mut App,
5373        ) -> &mut waft_rendering::SelectionRegistrantData {
5374            &mut app.get_mut(self).selection_registrant
5375        }
5376    }
5377
5378    /// The spy under the region, and the events it has recorded.
5379    fn spy_events(tester: &WidgetTester) -> Vec<SelectionEvent> {
5380        let spy = tester.all::<RenderSelectionSpy>()[0];
5381        tester.update(|app| spy.get(app).events.clone())
5382    }
5383
5384    fn clear_spy_events(tester: &WidgetTester) {
5385        let spy = tester.all::<RenderSelectionSpy>()[0];
5386        tester.update(|app| spy.get_mut(app).events.clear());
5387    }
5388
5389    /// The type and global position of an edge update, as Dart's tests read a
5390    /// `SelectionEdgeUpdateEvent`.
5391    fn edge_update(event: &SelectionEvent) -> (SelectionEventType, Offset, TextGranularity) {
5392        match event {
5393            SelectionEvent::StartEdgeUpdate {
5394                global_position,
5395                granularity,
5396            } => (
5397                SelectionEventType::StartEdgeUpdate,
5398                *global_position,
5399                *granularity,
5400            ),
5401            SelectionEvent::EndEdgeUpdate {
5402                global_position,
5403                granularity,
5404            } => (
5405                SelectionEventType::EndEdgeUpdate,
5406                *global_position,
5407                *granularity,
5408            ),
5409            other => panic!("not an edge update: {other:?}"),
5410        }
5411    }
5412
5413    /// The global position of a `SelectWordSelectionEvent`.
5414    fn select_word_position(event: &SelectionEvent) -> Offset {
5415        match event {
5416            SelectionEvent::SelectWord { global_position } => *global_position,
5417            other => panic!("not a select-word event: {other:?}"),
5418        }
5419    }
5420
5421    // selectable_region_test.dart 'mouse selection single click sends correct events'.
5422    #[test]
5423    fn mouse_selection_single_click_sends_correct_events() {
5424        test_widgets(|tester| {
5425            pump_region(tester, SelectionSpy);
5426            tester.pump_and_settle();
5427
5428            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5429            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5430            tester.pump_and_settle();
5431            clear_spy_events(tester);
5432
5433            tester.move_to(&mut gesture, Offset::new(200.0, 100.0), true);
5434            let events = spy_events(tester);
5435            assert_eq!(events.len(), 2);
5436            let (ty, position, _) = edge_update(&events[0]);
5437            assert_eq!(ty, SelectionEventType::StartEdgeUpdate);
5438            assert_eq!(position, Offset::new(200.0, 200.0));
5439            let (ty, position, _) = edge_update(&events[1]);
5440            assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
5441            assert_eq!(position, Offset::new(200.0, 100.0));
5442            clear_spy_events(tester);
5443
5444            tester.move_to(&mut gesture, Offset::new(100.0, 100.0), true);
5445            let events = spy_events(tester);
5446            assert_eq!(events.len(), 1);
5447            let (ty, position, _) = edge_update(&events[0]);
5448            assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
5449            assert_eq!(position, Offset::new(100.0, 100.0));
5450
5451            tester.up(&gesture);
5452            tester.remove_pointer(&gesture);
5453        });
5454    }
5455
5456    /// Dart's double-click spy cases: a tap, then a second down and up at the same place.
5457    fn double_click_spy(tester: &mut WidgetTester, mut gesture: TestPointer) {
5458        pump_region(tester, SelectionSpy);
5459        tester.down(&mut gesture, Offset::new(200.0, 200.0));
5460        tester.pump();
5461        tester.up(&gesture);
5462        tester.pump();
5463        clear_spy_events(tester);
5464        tester.down(&mut gesture, Offset::new(200.0, 200.0));
5465        tester.pump();
5466        tester.up(&gesture);
5467        let events = spy_events(tester);
5468        assert_eq!(events.len(), 1);
5469        assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
5470        tester.remove_pointer(&gesture);
5471    }
5472
5473    // selectable_region_test.dart 'mouse double click sends select-word event'.
5474    #[test]
5475    fn mouse_double_click_sends_select_word_event() {
5476        test_widgets(|tester| {
5477            let gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5478            double_click_spy(tester, gesture);
5479        });
5480    }
5481
5482    // selectable_region_test.dart 'touch double click sends select-word event'.
5483    #[test]
5484    fn touch_double_click_sends_select_word_event() {
5485        test_widgets(|tester| {
5486            let gesture = TestPointer::touch(tester.next_pointer());
5487            double_click_spy(tester, gesture);
5488        });
5489    }
5490
5491    // selectable_region_test.dart 'touch does not accept drag'.
5492    #[test]
5493    fn touch_does_not_accept_drag() {
5494        test_widgets(|tester| {
5495            pump_region(tester, SelectionSpy);
5496            let mut gesture = TestPointer::touch(tester.next_pointer());
5497            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5498            tester.move_to(&mut gesture, Offset::new(200.0, 100.0), true);
5499            tester.up(&gesture);
5500            assert!(
5501                spy_events(tester)
5502                    .iter()
5503                    .all(|event| matches!(event, SelectionEvent::Clear))
5504            );
5505            tester.remove_pointer(&gesture);
5506        });
5507    }
5508
5509    // selectable_region_test.dart 'mouse single-click selection collapses the selection'.
5510    #[test]
5511    fn mouse_single_click_selection_collapses_the_selection() {
5512        test_widgets(|tester| {
5513            pump_region(tester, SelectionSpy);
5514            tester.pump_and_settle();
5515            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5516            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5517            tester.pump();
5518            tester.up(&gesture);
5519            tester.pump_and_settle();
5520            let events = spy_events(tester);
5521            assert_eq!(events.len(), 2);
5522            assert_eq!(
5523                edge_update(&events[0]).0,
5524                SelectionEventType::StartEdgeUpdate
5525            );
5526            assert_eq!(edge_update(&events[1]).0, SelectionEventType::EndEdgeUpdate);
5527            tester.remove_pointer(&gesture);
5528        });
5529    }
5530
5531    // selectable_region_test.dart 'touch long press sends select-word event'.
5532    #[test]
5533    fn touch_long_press_sends_select_word_event() {
5534        test_widgets(|tester| {
5535            pump_region(tester, SelectionSpy);
5536            tester.pump_and_settle();
5537            clear_spy_events(tester);
5538            let mut gesture = TestPointer::touch(tester.next_pointer());
5539            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5540            tester.pump_by(Duration::from_millis(500));
5541            tester.up(&gesture);
5542            let events = spy_events(tester);
5543            assert_eq!(events.len(), 1);
5544            assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
5545            tester.remove_pointer(&gesture);
5546        });
5547    }
5548
5549    // selectable_region_test.dart 'touch long press and drag sends correct events'.
5550    #[test]
5551    fn touch_long_press_and_drag_sends_correct_events() {
5552        test_widgets(|tester| {
5553            pump_region(tester, SelectionSpy);
5554            tester.pump_and_settle();
5555            clear_spy_events(tester);
5556            let mut gesture = TestPointer::touch(tester.next_pointer());
5557            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5558            tester.pump_by(Duration::from_millis(500));
5559            let events = spy_events(tester);
5560            assert_eq!(events.len(), 1);
5561            assert_eq!(select_word_position(&events[0]), Offset::new(200.0, 200.0));
5562
5563            clear_spy_events(tester);
5564            tester.move_to(&mut gesture, Offset::new(200.0, 50.0), true);
5565            tester.up(&gesture);
5566            let events = spy_events(tester);
5567            assert_eq!(events.len(), 1);
5568            let (ty, position, granularity) = edge_update(&events[0]);
5569            assert_eq!(ty, SelectionEventType::EndEdgeUpdate);
5570            assert_eq!(position, Offset::new(200.0, 50.0));
5571            assert_eq!(granularity, TextGranularity::Word);
5572            tester.remove_pointer(&gesture);
5573        });
5574    }
5575
5576    // selectable_region_test.dart 'mouse long press does not send select-word event'.
5577    #[test]
5578    fn mouse_long_press_does_not_send_select_word_event() {
5579        test_widgets(|tester| {
5580            pump_region(tester, SelectionSpy);
5581            tester.pump_and_settle();
5582            clear_spy_events(tester);
5583            let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5584            tester.down(&mut gesture, Offset::new(200.0, 200.0));
5585            tester.pump_by(Duration::from_millis(500));
5586            tester.up(&gesture);
5587            assert!(spy_events(tester).iter().all(|event| matches!(
5588                event,
5589                SelectionEvent::StartEdgeUpdate { .. } | SelectionEvent::EndEdgeUpdate { .. }
5590            )));
5591            tester.remove_pointer(&gesture);
5592        });
5593    }
5594
5595    /// `keyboard_utils.dart`'s `sendKeyCombination`: the modifiers down, the trigger down and up,
5596    /// a pump, then the modifiers up in reverse.
5597    fn send_key_combination(
5598        tester: &mut WidgetTester,
5599        trigger: (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey),
5600        shift: bool,
5601        alt: bool,
5602        control: bool,
5603        meta: bool,
5604    ) {
5605        use waft_services::PhysicalKeyboardKey;
5606        let modifiers: Vec<(PhysicalKeyboardKey, LogicalKeyboardKey)> = [
5607            (
5608                control,
5609                PhysicalKeyboardKey::CONTROL_LEFT,
5610                LogicalKeyboardKey::CONTROL_LEFT,
5611            ),
5612            (
5613                shift,
5614                PhysicalKeyboardKey::SHIFT_LEFT,
5615                LogicalKeyboardKey::SHIFT_LEFT,
5616            ),
5617            (
5618                alt,
5619                PhysicalKeyboardKey::ALT_LEFT,
5620                LogicalKeyboardKey::ALT_LEFT,
5621            ),
5622            (
5623                meta,
5624                PhysicalKeyboardKey::META_LEFT,
5625                LogicalKeyboardKey::META_LEFT,
5626            ),
5627        ]
5628        .into_iter()
5629        .filter(|(pressed, _, _)| *pressed)
5630        .map(|(_, physical, logical)| (physical, logical))
5631        .collect();
5632        for (physical, logical) in &modifiers {
5633            tester.send_key_down_event(*physical, *logical);
5634        }
5635        tester.send_key_down_event(trigger.0, trigger.1);
5636        tester.send_key_up_event(trigger.0, trigger.1);
5637        tester.pump();
5638        for (physical, logical) in modifiers.iter().rev() {
5639            tester.send_key_up_event(*physical, *logical);
5640        }
5641    }
5642
5643    fn arrow_right() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
5644        (
5645            waft_services::PhysicalKeyboardKey::ARROW_RIGHT,
5646            LogicalKeyboardKey::ARROW_RIGHT,
5647        )
5648    }
5649
5650    fn arrow_left() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
5651        (
5652            waft_services::PhysicalKeyboardKey::ARROW_LEFT,
5653            LogicalKeyboardKey::ARROW_LEFT,
5654        )
5655    }
5656
5657    fn arrow_up() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
5658        (
5659            waft_services::PhysicalKeyboardKey::ARROW_UP,
5660            LogicalKeyboardKey::ARROW_UP,
5661        )
5662    }
5663
5664    fn arrow_down() -> (waft_services::PhysicalKeyboardKey, LogicalKeyboardKey) {
5665        (
5666            waft_services::PhysicalKeyboardKey::ARROW_DOWN,
5667            LogicalKeyboardKey::ARROW_DOWN,
5668        )
5669    }
5670
5671    /// `paragraph`'s one selection, as Dart's tests read `selections[0].start` and `.end`.
5672    fn paragraph_selection_start_end(
5673        tester: &WidgetTester,
5674        paragraph: RenderHandle<RenderParagraph>,
5675    ) -> (i32, i32) {
5676        tester.update(|app| {
5677            let selections = paragraph.selections(app);
5678            assert_eq!(selections.len(), 1);
5679            (selections[0].start(), selections[0].end())
5680        })
5681    }
5682
5683    /// The keyboard cases' start: the three texts under a region, and a mouse drag from offset
5684    /// 2 to offset 6 of the first.
5685    fn select_two_to_six_of_the_first_text(
5686        tester: &mut WidgetTester,
5687    ) -> RenderHandle<RenderParagraph> {
5688        pump_region(tester, three_texts());
5689        let paragraph_1 = paragraph_showing(tester, "How are you?");
5690        let mut gesture = TestPointer::mouse(tester.next_pointer(), K_PRIMARY_BUTTON);
5691        let at = text_offset_to_position(tester, paragraph_1, 2);
5692        tester.down(&mut gesture, at);
5693        tester.pump();
5694        let at = text_offset_to_position(tester, paragraph_1, 6);
5695        tester.move_to(&mut gesture, at, true);
5696        tester.up(&gesture);
5697        tester.pump();
5698        tester.remove_pointer(&gesture);
5699        assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 6));
5700        paragraph_1
5701    }
5702
5703    // selectable_region_test.dart 'can use keyboard to granularly extend selection - character'.
5704    #[test]
5705    fn can_use_keyboard_to_granularly_extend_selection_character() {
5706        test_widgets_variant(TargetPlatformVariant::all(), |tester| {
5707            let paragraph_1 = select_two_to_six_of_the_first_text(tester);
5708
5709            send_key_combination(tester, arrow_right(), true, false, false, false);
5710            tester.pump();
5711            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 7));
5712
5713            for i in 0..5 {
5714                send_key_combination(tester, arrow_right(), true, false, false, false);
5715                tester.pump();
5716                assert_eq!(
5717                    paragraph_selection_start_end(tester, paragraph_1),
5718                    (2, 8 + i)
5719                );
5720            }
5721
5722            for i in 0..5 {
5723                send_key_combination(tester, arrow_left(), true, false, false, false);
5724                tester.pump();
5725                assert_eq!(
5726                    paragraph_selection_start_end(tester, paragraph_1),
5727                    (2, 11 - i)
5728                );
5729            }
5730        });
5731    }
5732
5733    // selectable_region_test.dart 'can use keyboard to granularly extend selection - word'.
5734    #[test]
5735    fn can_use_keyboard_to_granularly_extend_selection_word() {
5736        test_widgets_variant(TargetPlatformVariant::all(), |tester| {
5737            let paragraph_1 = select_two_to_six_of_the_first_text(tester);
5738            let (alt, control) = match tester.target_platform() {
5739                TargetPlatform::Android
5740                | TargetPlatform::Fuchsia
5741                | TargetPlatform::Linux
5742                | TargetPlatform::Windows => (false, true),
5743                TargetPlatform::IOS | TargetPlatform::MacOS => (true, false),
5744            };
5745
5746            send_key_combination(tester, arrow_right(), true, alt, control, false);
5747            tester.pump();
5748            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 7));
5749
5750            send_key_combination(tester, arrow_right(), true, alt, control, false);
5751            tester.pump();
5752            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 11));
5753
5754            send_key_combination(tester, arrow_right(), true, alt, control, false);
5755            tester.pump();
5756            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5757
5758            send_key_combination(tester, arrow_right(), true, alt, control, false);
5759            tester.pump();
5760            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
5761            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5762            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 4));
5763
5764            send_key_combination(tester, arrow_left(), true, alt, control, false);
5765            tester.pump();
5766            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5767            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
5768
5769            send_key_combination(tester, arrow_left(), true, alt, control, false);
5770            tester.pump();
5771            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 8));
5772            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
5773        });
5774    }
5775
5776    /// The line and document cases' modifiers: `(alt, meta)`.
5777    fn line_modifiers(platform: TargetPlatform) -> (bool, bool) {
5778        match platform {
5779            TargetPlatform::Android
5780            | TargetPlatform::Fuchsia
5781            | TargetPlatform::Linux
5782            | TargetPlatform::Windows => (true, false),
5783            TargetPlatform::IOS | TargetPlatform::MacOS => (false, true),
5784        }
5785    }
5786
5787    // selectable_region_test.dart 'can use keyboard to granularly extend selection - line'.
5788    #[test]
5789    fn can_use_keyboard_to_granularly_extend_selection_line() {
5790        test_widgets_variant(TargetPlatformVariant::all(), |tester| {
5791            let paragraph_1 = select_two_to_six_of_the_first_text(tester);
5792            let (alt, meta) = line_modifiers(tester.target_platform());
5793
5794            send_key_combination(tester, arrow_right(), true, alt, false, meta);
5795            tester.pump();
5796            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5797
5798            send_key_combination(tester, arrow_right(), true, alt, false, meta);
5799            tester.pump();
5800            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
5801            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5802            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 14));
5803
5804            send_key_combination(tester, arrow_left(), true, alt, false, meta);
5805            tester.pump();
5806            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5807            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
5808
5809            send_key_combination(tester, arrow_left(), true, alt, false, meta);
5810            tester.pump();
5811            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (0, 2));
5812        });
5813    }
5814
5815    // selectable_region_test.dart 'can use keyboard to granularly extend selection - document'.
5816    #[test]
5817    fn can_use_keyboard_to_granularly_extend_selection_document() {
5818        test_widgets_variant(TargetPlatformVariant::all(), |tester| {
5819            let paragraph_1 = select_two_to_six_of_the_first_text(tester);
5820            let (alt, meta) = line_modifiers(tester.target_platform());
5821
5822            send_key_combination(tester, arrow_down(), true, alt, false, meta);
5823            tester.pump();
5824            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
5825            let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
5826            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (2, 12));
5827            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 14));
5828            assert_eq!(paragraph_selection_start_end(tester, paragraph_3), (0, 16));
5829
5830            send_key_combination(tester, arrow_up(), true, alt, false, meta);
5831            tester.pump();
5832            assert_eq!(paragraph_selection_start_end(tester, paragraph_1), (0, 2));
5833            assert_eq!(paragraph_selection_start_end(tester, paragraph_2), (0, 0));
5834            assert_eq!(paragraph_selection_start_end(tester, paragraph_3), (0, 0));
5835        });
5836    }
5837
5838    const K_TEST_HANDLE_SIZE: f64 = 22.0;
5839
5840    /// `selectable_region_test.dart`'s `_TestDraggableSelectionControls`: selection controls with
5841    /// non-zero handle size for tests that need handle dragging.
5842    ///
5843    /// Does not mix in [`TextSelectionHandleControls`](crate::TextSelectionHandleControls).
5844    struct TestDraggableSelectionControls;
5845
5846    #[allow(deprecated)]
5847    impl TextSelectionControls for TestDraggableSelectionControls {
5848        fn build_handle(
5849            &self,
5850            _app: &mut App,
5851            _context: BuildContext,
5852            handle_type: TextSelectionHandleType,
5853            _text_line_height: f64,
5854            on_tap: Option<Listener>,
5855        ) -> WidgetRef {
5856            let mut detector = crate::widgets::gesture_detector::GestureDetector::new()
5857                .behavior(HitTestBehavior::Translucent);
5858            if let Some(on_tap) = on_tap {
5859                detector = detector.on_tap(on_tap);
5860            }
5861            let handle = SizedBox::square(Some(K_TEST_HANDLE_SIZE))
5862                .child(
5863                    crate::widgets::basic::CustomPaint::new()
5864                        .painter(TestHandlePainter)
5865                        .child(detector),
5866                )
5867                .into_widget();
5868            match handle_type {
5869                TextSelectionHandleType::Left => {
5870                    crate::widgets::basic::Transform::rotate(std::f64::consts::PI / 2.0)
5871                        .child(handle)
5872                        .into_widget()
5873                }
5874                TextSelectionHandleType::Right => handle,
5875                TextSelectionHandleType::Collapsed => {
5876                    crate::widgets::basic::Transform::rotate(std::f64::consts::PI / 4.0)
5877                        .child(handle)
5878                        .into_widget()
5879                }
5880            }
5881        }
5882
5883        fn get_handle_anchor(
5884            &self,
5885            handle_type: TextSelectionHandleType,
5886            _text_line_height: f64,
5887        ) -> Offset {
5888            match handle_type {
5889                TextSelectionHandleType::Collapsed => Offset::new(K_TEST_HANDLE_SIZE / 2.0, -4.0),
5890                TextSelectionHandleType::Left => Offset::new(K_TEST_HANDLE_SIZE, 0.0),
5891                TextSelectionHandleType::Right => Offset::ZERO,
5892            }
5893        }
5894
5895        fn get_handle_size(&self, _text_line_height: f64) -> Size {
5896            Size::new(K_TEST_HANDLE_SIZE, K_TEST_HANDLE_SIZE)
5897        }
5898
5899        fn build_toolbar(
5900            &self,
5901            _app: &mut App,
5902            _context: BuildContext,
5903            _global_editable_region: Rect,
5904            _text_line_height: f64,
5905            _selection_midpoint: Offset,
5906            _endpoints: &[waft_rendering::TextSelectionPoint],
5907            _delegate: waft_services::AnyTextSelectionDelegate,
5908            _clipboard_status: Option<Ref<crate::widgets::text_selection::ClipboardStatusNotifier>>,
5909            _last_secondary_tap_down_position: Option<Offset>,
5910        ) -> WidgetRef {
5911            SizedBox::shrink().into_widget()
5912        }
5913    }
5914
5915    /// `selectable_region_test.dart`'s `_TestHandlePainter`.
5916    struct TestHandlePainter;
5917
5918    impl waft_rendering::CustomPainter for TestHandlePainter {
5919        fn paint(&self, _app: &mut App, canvas: &mut waft_embedder::Canvas, size: Size) {
5920            let paint = waft_embedder::Paint {
5921                color: waft_embedder::Color::new(0xFF000000).into(),
5922                ..waft_embedder::Paint::default()
5923            };
5924            canvas.draw_rect(Offset::ZERO & size, &paint);
5925        }
5926
5927        fn should_repaint(
5928            &self,
5929            _app: &App,
5930            _old_delegate: &dyn waft_rendering::CustomPainter,
5931        ) -> bool {
5932            false
5933        }
5934
5935        fn as_any(&self) -> &dyn std::any::Any {
5936            self
5937        }
5938    }
5939
5940    /// The handle cases' start: the three texts in `_materialDefaultTextStyle` under a region
5941    /// with [`TestDraggableSelectionControls`], and a touch long press at the 'h' of the third,
5942    /// which selects "thank".
5943    fn long_press_thank(tester: &mut WidgetTester) -> (TestPointer, RenderHandle<RenderParagraph>) {
5944        let material_default_text_style = waft_painting::TextStyle::new()
5945            .font_size(48.0)
5946            .font_family("monospace")
5947            .font_weight(waft_embedder::FontWeight::W900);
5948        tester.pump_widget(
5949            TestWidgetsApp::new()
5950                .text_style(material_default_text_style)
5951                .home(SelectableRegion::new(
5952                    Rc::new(TestDraggableSelectionControls),
5953                    three_texts(),
5954                )),
5955        );
5956        tester.pump_and_settle();
5957        let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
5958        let mut gesture = TestPointer::touch(tester.next_pointer());
5959        // At the 'h'.
5960        let at = text_offset_to_position(tester, paragraph_3, 7);
5961        tester.down(&mut gesture, at);
5962        tester.pump_by(Duration::from_millis(500));
5963        tester.up(&gesture);
5964        tester.pump_by(Duration::from_millis(500));
5965        assert_eq!(paragraph_selection(tester, paragraph_3), (6, 11));
5966        (gesture, paragraph_3)
5967    }
5968
5969    /// The one box of `paragraph`'s selection, in global coordinates, as Dart's
5970    /// `globalize(boxes[0].toRect().…, paragraph)` reads its corners.
5971    fn selection_box(tester: &WidgetTester, paragraph: RenderHandle<RenderParagraph>) -> Rect {
5972        tester.update(|app| {
5973            let selection = paragraph.selections(app)[0];
5974            let boxes = paragraph.get_boxes_for_selection(
5975                app,
5976                selection,
5977                waft_embedder::BoxHeightStyle::Tight,
5978                waft_embedder::BoxWidthStyle::Tight,
5979            );
5980            assert_eq!(boxes.len(), 1);
5981            let rect = boxes[0].to_rect();
5982            let to_global = |point| paragraph.as_box().local_to_global(app, point, None);
5983            Rect::from_points(to_global(rect.top_left()), to_global(rect.bottom_right()))
5984        })
5985    }
5986
5987    /// `paragraph`'s height.
5988    fn paragraph_height(tester: &WidgetTester, paragraph: RenderHandle<RenderParagraph>) -> f64 {
5989        tester.update(|app| paragraph.as_box().size(app).height())
5990    }
5991
5992    // selectable_region_test.dart 'can drag start selection handle'.
5993    #[test]
5994    fn can_drag_start_selection_handle() {
5995        test_widgets(|tester| {
5996            let (mut gesture, paragraph_3) = long_press_thank(tester);
5997            let handle_pos = selection_box(tester, paragraph_3).bottom_left();
5998            tester.down(&mut gesture, handle_pos);
5999            let paragraph_2 = paragraph_showing(tester, "Good, and you?");
6000            let at = text_offset_to_position(tester, paragraph_2, 5)
6001                + Offset::new(0.0, paragraph_height(tester, paragraph_2) / 2.0);
6002            tester.move_to(&mut gesture, at, true);
6003            assert_eq!(paragraph_selection(tester, paragraph_3), (0, 11));
6004            assert_eq!(paragraph_selection(tester, paragraph_2), (5, 14));
6005
6006            let paragraph_1 = paragraph_showing(tester, "How are you?");
6007            let at = text_offset_to_position(tester, paragraph_1, 6)
6008                + Offset::new(0.0, paragraph_height(tester, paragraph_1) / 2.0);
6009            tester.move_to(&mut gesture, at, true);
6010            assert_eq!(paragraph_selection(tester, paragraph_3), (0, 11));
6011            assert_eq!(paragraph_selection(tester, paragraph_2), (0, 14));
6012            assert_eq!(paragraph_selection(tester, paragraph_1), (6, 12));
6013            tester.up(&gesture);
6014            tester.remove_pointer(&gesture);
6015        });
6016    }
6017
6018    // selectable_region_test.dart 'can drag start selection handle across end selection handle'.
6019    #[test]
6020    fn can_drag_start_selection_handle_across_end_selection_handle() {
6021        test_widgets(|tester| {
6022            let (mut gesture, paragraph_3) = long_press_thank(tester);
6023            let handle_pos = selection_box(tester, paragraph_3).bottom_left();
6024            tester.down(&mut gesture, handle_pos);
6025            let half_height = paragraph_height(tester, paragraph_3) / 2.0;
6026            let at =
6027                text_offset_to_position(tester, paragraph_3, 14) + Offset::new(0.0, half_height);
6028            tester.move_to(&mut gesture, at, true);
6029            assert_eq!(paragraph_selection(tester, paragraph_3), (14, 11));
6030
6031            let at =
6032                text_offset_to_position(tester, paragraph_3, 4) + Offset::new(0.0, half_height);
6033            tester.move_to(&mut gesture, at, true);
6034            assert_eq!(paragraph_selection(tester, paragraph_3), (4, 11));
6035            tester.up(&gesture);
6036            tester.remove_pointer(&gesture);
6037        });
6038    }
6039
6040    // selectable_region_test.dart 'can drag end selection handle across start selection handle'.
6041    #[test]
6042    fn can_drag_end_selection_handle_across_start_selection_handle() {
6043        test_widgets(|tester| {
6044            let (mut gesture, paragraph_3) = long_press_thank(tester);
6045            let handle_pos = selection_box(tester, paragraph_3).bottom_right();
6046            tester.down(&mut gesture, handle_pos);
6047            let half_height = paragraph_height(tester, paragraph_3) / 2.0;
6048            let at =
6049                text_offset_to_position(tester, paragraph_3, 4) + Offset::new(0.0, half_height);
6050            tester.move_to(&mut gesture, at, true);
6051            assert_eq!(paragraph_selection(tester, paragraph_3), (6, 4));
6052
6053            let at =
6054                text_offset_to_position(tester, paragraph_3, 12) + Offset::new(0.0, half_height);
6055            tester.move_to(&mut gesture, at, true);
6056            assert_eq!(paragraph_selection(tester, paragraph_3), (6, 12));
6057            tester.up(&gesture);
6058            tester.remove_pointer(&gesture);
6059        });
6060    }
6061
6062    /// The three texts most of `selectable_region_test.dart`'s cases select across.
6063    fn three_texts() -> Column {
6064        Column::new().children([
6065            Text::new("How are you?").into_widget(),
6066            Text::new("Good, and you?").into_widget(),
6067            Text::new("Fine, thank you.").into_widget(),
6068        ])
6069    }
6070
6071    // selectable_region_test.dart 'can select all from toolbar': a touch long press selects the
6072    // word and shows the toolbar, whose select-all button selects every text. Dart's controls
6073    // build the toolbar through the deprecated `buildToolbar`, which the port leaves out (see
6074    // PORTING.md), so the same two buttons come from the region's context menu builder here.
6075    #[test]
6076    fn a_touch_long_press_shows_the_toolbar_and_its_select_all_selects_everything() {
6077        test_widgets(|tester| {
6078            let types = Rc::new(RefCell::new(Vec::new()));
6079            let types_log = Rc::clone(&types);
6080            let region = SelectableRegion::new(
6081                Rc::new(crate::testing::TestTextSelectionHandleControls),
6082                crate::widgets::basic::Column::new().children([
6083                    Text::new("How are you?").into_widget(),
6084                    Text::new("Good, and you?").into_widget(),
6085                    Text::new("Fine, thank you.").into_widget(),
6086                ]),
6087            )
6088            .context_menu_builder(Rc::new(move |app, _context, state| {
6089                let items = state.context_menu_button_items(app);
6090                types_log
6091                    .borrow_mut()
6092                    .extend(items.iter().map(|item| item.r#type));
6093                let mut buttons = Vec::new();
6094                for item in items {
6095                    let label = match item.r#type {
6096                        ContextMenuButtonType::Copy => "Copy",
6097                        ContextMenuButtonType::SelectAll => "Select all",
6098                        _ => "Item",
6099                    };
6100                    let on_pressed = item.on_pressed.clone();
6101                    buttons.push(
6102                        crate::widgets::gesture_detector::GestureDetector::new()
6103                            .on_tap(Listener::new(move |app| {
6104                                if let Some(listener) = &on_pressed {
6105                                    listener.call(app);
6106                                }
6107                            }))
6108                            .child(Text::new(label))
6109                            .into_widget(),
6110                    );
6111                }
6112                crate::widgets::basic::Column::new()
6113                    .children(buttons)
6114                    .into_widget()
6115            }));
6116            tester.pump_widget(TestWidgetsApp::new().home(region));
6117            tester.pump_and_settle();
6118
6119            let paragraph_3 = paragraph_showing(tester, "Fine, thank you.");
6120            let at = text_offset_to_position(tester, paragraph_3, 7);
6121            let mut pointer = TestPointer::touch(tester.next_pointer());
6122            tester.down(&mut pointer, at);
6123            tester.pump_by(Duration::from_millis(500));
6124            tester.up(&pointer);
6125            tester.pump_by(Duration::from_millis(500));
6126
6127            assert_eq!(paragraph_selection(tester, paragraph_3), (6, 11));
6128            assert!(types.borrow().contains(&ContextMenuButtonType::SelectAll));
6129            tester.tap(find::text("Select all"));
6130            tester.pump();
6131
6132            assert_eq!(paragraph_selection(tester, paragraph_3), (0, 16));
6133            assert_eq!(
6134                paragraph_selection(tester, paragraph_showing(tester, "Good, and you?")),
6135                (0, 14)
6136            );
6137            assert_eq!(
6138                paragraph_selection(tester, paragraph_showing(tester, "How are you?")),
6139                (0, 12)
6140            );
6141        });
6142    }
6143
6144    /// A delegate whose order is a rock-paper-scissors cycle: lanes 0 < 1 < 2 < 0. That is not
6145    /// a total order, which Rust's `sort_by` may panic on and Flutter's merge sort tolerates.
6146    struct RockPaperScissorsDelegate {
6147        selection_container_delegate: SelectionContainerDelegateData,
6148        multi_selectable_selection_container_delegate:
6149            MultiSelectableSelectionContainerDelegateData,
6150        lanes: Vec<(AnySelectable, usize)>,
6151        seed: u64,
6152    }
6153
6154    impl RockPaperScissorsDelegate {
6155        fn new(app: &mut App) -> Ref<RockPaperScissorsDelegate> {
6156            app.create(RockPaperScissorsDelegate {
6157                selection_container_delegate: SelectionContainerDelegateData::new(),
6158                multi_selectable_selection_container_delegate:
6159                    MultiSelectableSelectionContainerDelegateData::new(),
6160                lanes: Vec::new(),
6161                seed: 12345,
6162            })
6163        }
6164
6165        fn lane(self: Handle<Self>, app: &App, selectable: AnySelectable) -> usize {
6166            app.get(self)
6167                .lanes
6168                .iter()
6169                .find_map(|(held, lane)| (*held == selectable).then_some(*lane))
6170                .unwrap_or(0)
6171        }
6172    }
6173
6174    impl SelectionContainerDelegate for RockPaperScissorsDelegate {
6175        fn selection_container_delegate_data(
6176            self: Handle<Self>,
6177            app: &App,
6178        ) -> &SelectionContainerDelegateData {
6179            &app.get(self).selection_container_delegate
6180        }
6181
6182        fn selection_container_delegate_data_mut(
6183            self: Handle<Self>,
6184            app: &mut App,
6185        ) -> &mut SelectionContainerDelegateData {
6186            &mut app.get_mut(self).selection_container_delegate
6187        }
6188    }
6189
6190    impl MultiSelectableSelectionContainerDelegate for RockPaperScissorsDelegate {
6191        crate::multi_selectable_selection_container_delegate_accessors!();
6192
6193        fn compare_order(
6194            self: Handle<Self>,
6195            app: &mut App,
6196            a: AnySelectable,
6197            b: AnySelectable,
6198        ) -> Ordering {
6199            let (a, b) = (self.lane(app, a), self.lane(app, b));
6200            if a == b {
6201                Ordering::Equal
6202            } else if (a + 1) % 3 == b {
6203                Ordering::Less
6204            } else {
6205                Ordering::Greater
6206            }
6207        }
6208
6209        fn ensure_child_updated(self: Handle<Self>, _app: &mut App, _selectable: AnySelectable) {}
6210
6211        fn dispatch_selection_event_to_child(
6212            self: Handle<Self>,
6213            _app: &mut App,
6214            _selectable: AnySelectable,
6215            _event: &SelectionEvent,
6216        ) -> SelectionResult {
6217            SelectionResult::End
6218        }
6219    }
6220
6221    impl SelectionHandler for RockPaperScissorsDelegate {
6222        fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
6223            MultiSelectableSelectionContainerDelegateBase::value(self, app)
6224        }
6225
6226        fn push_handle_layers(
6227            self: Handle<Self>,
6228            app: &mut App,
6229            start_handle: Option<Ref<LayerLink>>,
6230            end_handle: Option<Ref<LayerLink>>,
6231        ) {
6232            MultiSelectableSelectionContainerDelegateBase::push_handle_layers(
6233                self,
6234                app,
6235                start_handle,
6236                end_handle,
6237            );
6238        }
6239
6240        fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
6241            MultiSelectableSelectionContainerDelegateBase::selected_content(self, app)
6242        }
6243
6244        fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
6245            MultiSelectableSelectionContainerDelegateBase::selection(self, app)
6246        }
6247
6248        fn dispatch_selection_event(
6249            self: Handle<Self>,
6250            app: &mut App,
6251            event: &SelectionEvent,
6252        ) -> SelectionResult {
6253            MultiSelectableSelectionContainerDelegateBase::dispatch_selection_event(
6254                self, app, event,
6255            )
6256        }
6257
6258        fn content_length(self: Handle<Self>, app: &App) -> usize {
6259            MultiSelectableSelectionContainerDelegateBase::content_length(self, app)
6260        }
6261    }
6262
6263    impl SelectionRegistrar for RockPaperScissorsDelegate {
6264        fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
6265            // The lane sequence is the one that makes the comparison cyclic in a way `sort_by`
6266            // detects for fifty elements; a registration's order is its input order.
6267            let seed = app.get(self).seed;
6268            let lane = {
6269                let next = seed
6270                    .wrapping_mul(6364136223846793005)
6271                    .wrapping_add(1442695040888963407);
6272                app.get_mut(self).seed = next;
6273                ((next >> 33) as usize) % 3
6274            };
6275            app.get_mut(self).lanes.push((selectable, lane));
6276            MultiSelectableSelectionContainerDelegateBase::add(self, app, selectable);
6277        }
6278
6279        fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
6280            app.get_mut(self)
6281                .lanes
6282                .retain(|(held, _)| *held != selectable);
6283            MultiSelectableSelectionContainerDelegateBase::remove(self, app, selectable);
6284        }
6285    }
6286
6287    impl ChangeNotifier for RockPaperScissorsDelegate {
6288        fn change_notifier_data(&self) -> &ChangeNotifierData {
6289            &self
6290                .multi_selectable_selection_container_delegate
6291                .change_notifier
6292        }
6293
6294        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
6295            &mut self
6296                .multi_selectable_selection_container_delegate
6297                .change_notifier
6298        }
6299    }
6300
6301    // Not a Flutter case: the screen order is not a total order, and a list long enough makes
6302    // Rust's `sort_by` detect it and panic; the delegates sort with Flutter's merge sort.
6303    #[test]
6304    fn fifty_selectables_sort_with_a_comparator_that_is_not_a_total_order() {
6305        test_widgets(|tester| {
6306            let delegate = tester.update(RockPaperScissorsDelegate::new);
6307            let children: Vec<WidgetRef> = (0..50)
6308                .map(|_| {
6309                    SizedBox::new()
6310                        .height(10.0)
6311                        .child(SelectionSpy)
6312                        .into_widget()
6313                })
6314                .collect();
6315            tester.pump_widget(SelectionContainer::new(
6316                delegate.erase(),
6317                Column::new().children(children),
6318            ));
6319            for _ in 0..3 {
6320                tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
6321                tester.pump_and_settle();
6322            }
6323            tester.update(|app| {
6324                assert_eq!(
6325                    app.get(&delegate)
6326                        .multi_selectable_selection_container_delegate
6327                        .selectables
6328                        .len(),
6329                    50,
6330                    "the frame merged all fifty selectables"
6331                );
6332                // A selection sorts them again, which tolerates the same comparator.
6333                SelectionHandler::dispatch_selection_event(
6334                    delegate.handle(),
6335                    app,
6336                    &SelectionEvent::SelectAll,
6337                );
6338                assert!(SelectionHandler::value(delegate.handle(), app).has_content);
6339            });
6340        });
6341    }
6342
6343    // selection_container_test.dart 'updates its registrar and delegate based on the number of
6344    // selectables'.
6345    #[test]
6346    fn updates_its_registrar_and_delegate_based_on_the_number_of_selectables() {
6347        test_widgets(|tester| {
6348            let registrar = tester.update(|app| {
6349                app.create(TestSelectionRegistrar {
6350                    selectables: Vec::new(),
6351                })
6352            });
6353            let delegate = tester.update(TestContainerDelegate::new);
6354
6355            tester.pump_widget(
6356                SelectionContainer::new(
6357                    delegate.erase(),
6358                    Column::new().children([
6359                        selectable_text("column1"),
6360                        selectable_text("column2"),
6361                        selectable_text("column3"),
6362                    ]),
6363                )
6364                .registrar(registrar.erase()),
6365            );
6366            tester.pump_and_settle();
6367            tester.update(|app| {
6368                assert_eq!(app.get(&registrar).selectables.len(), 1);
6369                assert_eq!(
6370                    app.get(&delegate)
6371                        .multi_selectable_selection_container_delegate
6372                        .selectables
6373                        .len(),
6374                    3
6375                );
6376            });
6377        });
6378    }
6379
6380    // selection_container_test.dart 'disabled container'.
6381    #[test]
6382    fn a_disabled_container_registers_neither_itself_nor_its_children() {
6383        test_widgets(|tester| {
6384            let registrar = tester.update(|app| {
6385                app.create(TestSelectionRegistrar {
6386                    selectables: Vec::new(),
6387                })
6388            });
6389            let delegate = tester.update(TestContainerDelegate::new);
6390
6391            tester.pump_widget(
6392                SelectionContainer::new(
6393                    delegate.erase(),
6394                    SelectionContainer::disabled(Column::new().children([
6395                        selectable_text("column1"),
6396                        selectable_text("column2"),
6397                        selectable_text("column3"),
6398                    ])),
6399                )
6400                .registrar(registrar.erase()),
6401            );
6402
6403            tester.update(|app| {
6404                assert_eq!(app.get(&registrar).selectables.len(), 0);
6405                assert_eq!(
6406                    app.get(&delegate)
6407                        .multi_selectable_selection_container_delegate
6408                        .selectables
6409                        .len(),
6410                    0
6411                );
6412            });
6413        });
6414    }
6415
6416    // selection_container_test.dart 'Swapping out container delegate does not crash'.
6417    #[test]
6418    fn swapping_out_the_container_delegate_does_not_crash() {
6419        test_widgets(|tester| {
6420            let registrar = tester.update(|app| {
6421                app.create(TestSelectionRegistrar {
6422                    selectables: Vec::new(),
6423                })
6424            });
6425            let delegate = tester.update(TestContainerDelegate::new);
6426            let child_delegate = tester.update(TestContainerDelegate::new);
6427
6428            let pump_inner = |tester: &mut WidgetTester, inner: &Ref<TestContainerDelegate>| {
6429                let inner = inner.clone();
6430                tester.pump_widget(
6431                    SelectionContainer::new(
6432                        delegate.erase(),
6433                        Builder::new(move |app, context| {
6434                            let registrar = SelectionContainer::maybe_of(app, context)
6435                                .expect("the outer container hosts a registrar");
6436                            SelectionContainer::new(inner.erase(), selectable_text("dummy"))
6437                                .registrar(registrar)
6438                                .into_widget()
6439                        }),
6440                    )
6441                    .registrar(registrar.erase()),
6442                );
6443                tester.pump_and_settle();
6444                next_frame(tester);
6445            };
6446            pump_inner(tester, &child_delegate);
6447            tester.update(|app| {
6448                assert_eq!(app.get(&registrar).selectables.len(), 1);
6449                assert!(SelectionHandler::value(delegate.handle(), app).has_content);
6450            });
6451
6452            let new_delegate = tester.update(TestContainerDelegate::new);
6453            pump_inner(tester, &new_delegate);
6454            tester.update(|app| {
6455                assert_eq!(app.get(&registrar).selectables.len(), 1);
6456                assert!(SelectionHandler::value(delegate.handle(), app).has_content);
6457            });
6458        });
6459    }
6460
6461    // selection_container_test.dart 'Can update within one frame'.
6462    #[test]
6463    fn the_container_updates_within_one_frame() {
6464        test_widgets(|tester| {
6465            let registrar = tester.update(|app| {
6466                app.create(TestSelectionRegistrar {
6467                    selectables: Vec::new(),
6468                })
6469            });
6470            let delegate = tester.update(TestContainerDelegate::new);
6471            let child_delegate = tester.update(TestContainerDelegate::new);
6472
6473            tester.pump_widget(
6474                SelectionContainer::new(
6475                    delegate.erase(),
6476                    Builder::new(move |app, context| {
6477                        let registrar = SelectionContainer::maybe_of(app, context)
6478                            .expect("the outer container hosts a registrar");
6479                        SelectionContainer::new(child_delegate.erase(), selectable_text("dummy"))
6480                            .registrar(registrar)
6481                            .into_widget()
6482                    }),
6483                )
6484                .registrar(registrar.erase()),
6485            );
6486            // The nested delegate's update is a post-frame callback, and its microtask stands in
6487            // for `tester.idle()`; the next frame, which Flutter's `pump` always produces, folds
6488            // the nested container's selectable into the outer delegate.
6489            next_frame(tester);
6490
6491            tester.update(|app| {
6492                assert_eq!(app.get(&registrar).selectables.len(), 1);
6493                assert!(SelectionHandler::value(delegate.handle(), app).has_content);
6494            });
6495        });
6496    }
6497
6498    // selection_container_test.dart 'selection container registers itself if there is a
6499    // selectable child'.
6500    #[test]
6501    fn a_selection_container_registers_itself_if_there_is_a_selectable_child() {
6502        test_widgets(|tester| {
6503            let registrar = tester.update(|app| {
6504                app.create(TestSelectionRegistrar {
6505                    selectables: Vec::new(),
6506                })
6507            });
6508            let delegate = tester.update(TestContainerDelegate::new);
6509
6510            tester.pump_widget(
6511                SelectionContainer::new(delegate.erase(), Column::new())
6512                    .registrar(registrar.erase()),
6513            );
6514            tester.update(|app| assert_eq!(app.get(&registrar).selectables.len(), 0));
6515
6516            tester.pump_widget(
6517                SelectionContainer::new(
6518                    delegate.erase(),
6519                    Column::new().children([selectable_text("column1")]),
6520                )
6521                .registrar(registrar.erase()),
6522            );
6523            tester.pump_and_settle();
6524            tester.update(|app| assert_eq!(app.get(&registrar).selectables.len(), 1));
6525
6526            tester.pump_widget(
6527                SelectionContainer::new(delegate.erase(), Column::new())
6528                    .registrar(registrar.erase()),
6529            );
6530            tester.pump_and_settle();
6531            tester.update(|app| assert_eq!(app.get(&registrar).selectables.len(), 0));
6532        });
6533    }
6534
6535    // selection_container_test.dart 'selection container gets registrar from context if not
6536    // provided'.
6537    #[test]
6538    fn a_selection_container_gets_its_registrar_from_the_context() {
6539        test_widgets(|tester| {
6540            let registrar = tester.update(|app| {
6541                app.create(TestSelectionRegistrar {
6542                    selectables: Vec::new(),
6543                })
6544            });
6545            let delegate = tester.update(TestContainerDelegate::new);
6546
6547            tester.pump_widget(SelectionRegistrarScope::new(
6548                registrar.erase(),
6549                SelectionContainer::new(
6550                    delegate.erase(),
6551                    Column::new().children([selectable_text("column1")]),
6552                ),
6553            ));
6554            tester.pump_and_settle();
6555
6556            tester.update(|app| assert_eq!(app.get(&registrar).selectables.len(), 1));
6557        });
6558    }
6559
6560    // selection_container_test.dart 'SelectionContainer does not crash at zero area'.
6561    #[test]
6562    fn a_selection_container_does_not_crash_at_zero_area() {
6563        test_widgets(|tester| {
6564            let delegate = tester.update(TestContainerDelegate::new);
6565            tester.pump_widget(Center::new().child(SizedBox::shrink().child(
6566                SelectionContainer::new(delegate.erase(), Placeholder::new()),
6567            )));
6568            assert_eq!(
6569                tester.get_size(find::by_type::<SelectionContainer>()),
6570                Size::ZERO
6571            );
6572        });
6573    }
6574
6575    /// Runs one more frame, for an update a delegate scheduled after the last one: a nested
6576    /// container's selectable reaches its delegate a frame after the container below it, as in
6577    /// Flutter, where `pump` always produces a frame.
6578    fn next_frame(tester: &mut WidgetTester) {
6579        tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
6580        tester.pump_and_settle();
6581    }
6582
6583    /// Sends `event` to `handle`, as a gesture or a keyboard action would.
6584    fn dispatch<D: SelectionHandler>(
6585        tester: &mut WidgetTester,
6586        handle: Handle<D>,
6587        event: SelectionEvent,
6588    ) {
6589        tester.update(|app| {
6590            SelectionHandler::dispatch_selection_event(handle, app, &event);
6591        });
6592    }
6593
6594    /// The selected range and status of `handle`.
6595    fn assert_selection<D: SelectionHandler>(
6596        tester: &WidgetTester,
6597        handle: Handle<D>,
6598        expected_range: Option<(i32, i32)>,
6599        expected_status: SelectionStatus,
6600    ) {
6601        tester.update(|app| {
6602            let range = SelectionHandler::selection(handle, app);
6603            assert_eq!(
6604                range.map(|range| (range.start_offset, range.end_offset)),
6605                expected_range
6606            );
6607            let value = SelectionHandler::value(handle, app);
6608            assert_eq!(value.status, expected_status);
6609            assert!(value.has_content);
6610        });
6611    }
6612
6613    /// The plain text `handle` has selected, or `None`.
6614    fn selected_text<D: SelectionHandler>(
6615        tester: &WidgetTester,
6616        handle: Handle<D>,
6617    ) -> Option<String> {
6618        tester.update(|app| {
6619            SelectionHandler::selected_content(handle, app).map(|content| content.plain_text)
6620        })
6621    }
6622
6623    // selectable_region_test.dart 'Can extend StaticSelectionContainerDelegate': a delegate that
6624    // puts a new line between the selectables' selected contents.
6625    #[test]
6626    fn a_subclass_joins_the_selectable_contents_its_own_way() {
6627        test_widgets(|tester| {
6628            let delegate = tester.update(ColumnSelectionContainerDelegate::new);
6629            tester.pump_widget(SelectionContainer::new(
6630                delegate.erase(),
6631                Column::new().children([
6632                    selectable_text("Hello World!"),
6633                    selectable_text("How are you!"),
6634                ]),
6635            ));
6636            tester.pump_and_settle();
6637
6638            let paragraphs = tester.all::<RenderParagraph>();
6639            assert_eq!(paragraphs.len(), 2);
6640            let start = text_offset_to_position(tester, paragraphs[0], 4);
6641            let end = text_offset_to_position(tester, paragraphs[1], 10);
6642            dispatch(
6643                tester,
6644                delegate.handle(),
6645                SelectionEvent::for_start(start, None),
6646            );
6647            dispatch(
6648                tester,
6649                delegate.handle(),
6650                SelectionEvent::for_end(end, None),
6651            );
6652
6653            assert_eq!(
6654                selected_text(tester, delegate.handle()),
6655                Some("o World!\nHow are yo".to_string())
6656            );
6657            tester.update(|app| {
6658                assert_eq!(SelectionHandler::content_length(delegate.handle(), app), 24);
6659            });
6660            assert_selection(
6661                tester,
6662                delegate.handle(),
6663                Some((4, 22)),
6664                SelectionStatus::Uncollapsed,
6665            );
6666        });
6667    }
6668
6669    // The same selection through the class itself: the default joins the selectables' contents
6670    // with nothing between them.
6671    #[test]
6672    fn the_delegate_joins_the_selectable_contents_without_a_separator() {
6673        test_widgets(|tester| {
6674            let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
6675            tester.pump_widget(SelectionContainer::new(
6676                delegate.erase(),
6677                Column::new().children([
6678                    selectable_text("Hello World!"),
6679                    selectable_text("How are you!"),
6680                ]),
6681            ));
6682            tester.pump_and_settle();
6683
6684            let paragraphs = tester.all::<RenderParagraph>();
6685            assert_eq!(paragraphs.len(), 2);
6686            let start = text_offset_to_position(tester, paragraphs[0], 4);
6687            let end = text_offset_to_position(tester, paragraphs[1], 10);
6688            dispatch(
6689                tester,
6690                delegate.handle(),
6691                SelectionEvent::for_start(start, None),
6692            );
6693            dispatch(
6694                tester,
6695                delegate.handle(),
6696                SelectionEvent::for_end(end, None),
6697            );
6698
6699            assert_eq!(
6700                selected_text(tester, delegate.handle()),
6701                Some("o World!How are yo".to_string())
6702            );
6703            assert_selection(
6704                tester,
6705                delegate.handle(),
6706                Some((4, 22)),
6707                SelectionStatus::Uncollapsed,
6708            );
6709        });
6710    }
6711
6712    // selectable_region_test.dart 'onSelectionChanged SelectedContentRange is accurate' numbers,
6713    // driven through the delegate rather than a mouse. The third text is one more character
6714    // than the second, as in the test: 36 is 12 + 14 + 10, and 30 is 12 + 14 + 4.
6715    #[test]
6716    fn the_selection_range_covers_the_selectables_between_the_edges() {
6717        test_widgets(|tester| {
6718            let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
6719            tester.pump_widget(SelectionContainer::new(
6720                delegate.erase(),
6721                Column::new().children([
6722                    selectable_text("How are you?"),
6723                    selectable_text("Good, and you?"),
6724                    selectable_text("Fine, thank you."),
6725                ]),
6726            ));
6727            tester.pump_and_settle();
6728
6729            let paragraphs = tester.all::<RenderParagraph>();
6730            assert_eq!(paragraphs.len(), 3);
6731            let start = text_offset_to_position(tester, paragraphs[0], 4);
6732            dispatch(
6733                tester,
6734                delegate.handle(),
6735                SelectionEvent::for_start(start, None),
6736            );
6737
6738            // Selection on paragraph 1.
6739            let end = text_offset_to_position(tester, paragraphs[0], 7);
6740            dispatch(
6741                tester,
6742                delegate.handle(),
6743                SelectionEvent::for_end(end, None),
6744            );
6745            assert_selection(
6746                tester,
6747                delegate.handle(),
6748                Some((4, 7)),
6749                SelectionStatus::Uncollapsed,
6750            );
6751
6752            // Selection on paragraph 1.
6753            let end = text_offset_to_position(tester, paragraphs[0], 10);
6754            dispatch(
6755                tester,
6756                delegate.handle(),
6757                SelectionEvent::for_end(end, None),
6758            );
6759            assert_selection(
6760                tester,
6761                delegate.handle(),
6762                Some((4, 10)),
6763                SelectionStatus::Uncollapsed,
6764            );
6765
6766            // Selection on paragraphs 1 and 2.
6767            let end = text_offset_to_position(tester, paragraphs[1], 10);
6768            dispatch(
6769                tester,
6770                delegate.handle(),
6771                SelectionEvent::for_end(end, None),
6772            );
6773            assert_selection(
6774                tester,
6775                delegate.handle(),
6776                Some((4, 22)),
6777                SelectionStatus::Uncollapsed,
6778            );
6779
6780            // Selection on paragraphs 1, 2 and 3.
6781            let end = text_offset_to_position(tester, paragraphs[2], 10);
6782            dispatch(
6783                tester,
6784                delegate.handle(),
6785                SelectionEvent::for_end(end, None),
6786            );
6787            assert_selection(
6788                tester,
6789                delegate.handle(),
6790                Some((4, 36)),
6791                SelectionStatus::Uncollapsed,
6792            );
6793
6794            // Collapsed selection.
6795            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
6796            let point = text_offset_to_position(tester, paragraphs[0], 3);
6797            dispatch(
6798                tester,
6799                delegate.handle(),
6800                SelectionEvent::for_start(point, None),
6801            );
6802            dispatch(
6803                tester,
6804                delegate.handle(),
6805                SelectionEvent::for_end(point, None),
6806            );
6807            assert_selection(
6808                tester,
6809                delegate.handle(),
6810                Some((3, 3)),
6811                SelectionStatus::Collapsed,
6812            );
6813
6814            // Backwards selection.
6815            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
6816            let start = text_offset_to_position(tester, paragraphs[2], 4);
6817            let end = text_offset_to_position(tester, paragraphs[0], 0);
6818            dispatch(
6819                tester,
6820                delegate.handle(),
6821                SelectionEvent::for_start(start, None),
6822            );
6823            dispatch(
6824                tester,
6825                delegate.handle(),
6826                SelectionEvent::for_end(end, None),
6827            );
6828            assert_selection(
6829                tester,
6830                delegate.handle(),
6831                Some((30, 0)),
6832                SelectionStatus::Uncollapsed,
6833            );
6834
6835            // Collapsed selection at the first character.
6836            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
6837            let point = text_offset_to_position(tester, paragraphs[0], 0);
6838            dispatch(
6839                tester,
6840                delegate.handle(),
6841                SelectionEvent::for_start(point, None),
6842            );
6843            dispatch(
6844                tester,
6845                delegate.handle(),
6846                SelectionEvent::for_end(point, None),
6847            );
6848            assert_selection(
6849                tester,
6850                delegate.handle(),
6851                Some((0, 0)),
6852                SelectionStatus::Collapsed,
6853            );
6854        });
6855    }
6856
6857    // The class's own behavior: a selectable added inside the selection is brought up to date
6858    // with the last edge updates, so it is selected without the user dragging again.
6859    #[test]
6860    fn a_selectable_added_inside_the_selection_is_selected_at_once() {
6861        test_widgets(|tester| {
6862            let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
6863            let pump = |tester: &mut WidgetTester, texts: &[&'static str]| {
6864                tester.pump_widget(SelectionContainer::new(
6865                    delegate.erase(),
6866                    Column::new().children(
6867                        texts
6868                            .iter()
6869                            .map(|text| selectable_text(text))
6870                            .collect::<Vec<_>>(),
6871                    ),
6872                ));
6873                tester.pump_and_settle();
6874            };
6875
6876            pump(tester, &["AAA", "CCC"]);
6877            let paragraphs = tester.all::<RenderParagraph>();
6878            let start = text_offset_to_position(tester, paragraphs[0], 0);
6879            let end = text_offset_to_position(tester, paragraphs[1], 2);
6880            dispatch(
6881                tester,
6882                delegate.handle(),
6883                SelectionEvent::for_start(start, None),
6884            );
6885            dispatch(
6886                tester,
6887                delegate.handle(),
6888                SelectionEvent::for_end(end, None),
6889            );
6890            assert_eq!(
6891                selected_text(tester, delegate.handle()),
6892                Some("AAACC".to_string())
6893            );
6894
6895            // `BBB` takes the second line: the end edge's old global position lands inside it,
6896            // at the same offset, while `CCC` moves down out of the selection.
6897            pump(tester, &["AAA", "BBB", "CCC"]);
6898            assert_eq!(
6899                selected_text(tester, delegate.handle()),
6900                Some("AAABB".to_string())
6901            );
6902            assert_selection(
6903                tester,
6904                delegate.handle(),
6905                Some((0, 5)),
6906                SelectionStatus::Uncollapsed,
6907            );
6908        });
6909    }
6910
6911    /// Select-all, select-word, select-paragraph and clear, as the region's actions send them.
6912    #[test]
6913    fn select_all_a_word_a_paragraph_and_clear_act_on_the_selectables() {
6914        test_widgets(|tester| {
6915            let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
6916            tester.pump_widget(SelectionContainer::new(
6917                delegate.erase(),
6918                Column::new().children([
6919                    selectable_text("Hello World!"),
6920                    selectable_text("How are you!"),
6921                ]),
6922            ));
6923            tester.pump_and_settle();
6924
6925            dispatch(tester, delegate.handle(), SelectionEvent::SelectAll);
6926            assert_eq!(
6927                selected_text(tester, delegate.handle()),
6928                Some("Hello World!How are you!".to_string())
6929            );
6930            assert_selection(
6931                tester,
6932                delegate.handle(),
6933                Some((0, 24)),
6934                SelectionStatus::Uncollapsed,
6935            );
6936
6937            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
6938            assert_eq!(selected_text(tester, delegate.handle()), None);
6939            assert_selection(tester, delegate.handle(), None, SelectionStatus::None);
6940            tester.update(|app| {
6941                assert_eq!(SelectionHandler::content_length(delegate.handle(), app), 24);
6942            });
6943
6944            let paragraphs = tester.all::<RenderParagraph>();
6945            let word = text_offset_to_position(tester, paragraphs[1], 5);
6946            dispatch(
6947                tester,
6948                delegate.handle(),
6949                SelectionEvent::SelectWord {
6950                    global_position: word,
6951                },
6952            );
6953            assert_eq!(
6954                selected_text(tester, delegate.handle()),
6955                Some("are".to_string())
6956            );
6957            assert_selection(
6958                tester,
6959                delegate.handle(),
6960                Some((16, 19)),
6961                SelectionStatus::Uncollapsed,
6962            );
6963
6964            let paragraph = text_offset_to_position(tester, paragraphs[1], 5);
6965            dispatch(
6966                tester,
6967                delegate.handle(),
6968                SelectionEvent::SelectParagraph {
6969                    global_position: paragraph,
6970                    absorb: false,
6971                },
6972            );
6973            assert_eq!(
6974                selected_text(tester, delegate.handle()),
6975                Some("How are you!".to_string())
6976            );
6977            assert_selection(
6978                tester,
6979                delegate.handle(),
6980                Some((12, 24)),
6981                SelectionStatus::Uncollapsed,
6982            );
6983        });
6984    }
6985}