Skip to main content

waft_rendering/
selection.rs

1//! Flutter counterpart: `rendering/selection.dart`.
2//!
3//! The types a selection stack builds on: what can be selected ([`Selectable`]), what keeps
4//! track of it ([`SelectionRegistrar`]), the events sent to it, and the geometry and content read
5//! back from it. A widget's side of this (`SelectionContainer`) lives in `waft-widgets`.
6//!
7//! [`AnySelectable`] and [`AnySelectionRegistrar`] are Dart's abstract classes used as types: an
8//! identity plus a vtable, so a registrar can hold selectables of more than one kind and a widget
9//! can hold a registrar without naming its concrete type.
10
11use waft_embedder::{Matrix4, Offset, Rect, Size, TextDirection};
12use waft_foundation::{
13    App, Handle, HandleId, ListenableHandle, ListenableObject, Listener, Ref, Retained,
14};
15
16use crate::layer::LayerLink;
17use crate::object::AnyRenderObject;
18
19/// The result after handling a [`SelectionEvent`].
20///
21/// A [`SelectionContainer`](https://api.flutter.dev/flutter/widgets/SelectionContainer-class.html)
22/// uses it to decide how a selection expands across its selectables.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum SelectionResult {
25    /// There is nothing left to select forward in this selectable, and further selection should
26    /// extend to the next selectable in screen order.
27    Next,
28    /// Selection does not reach this selectable and is located before it in screen order.
29    Previous,
30    /// Selection ends in this selectable.
31    End,
32    /// The result can't be determined in this frame; the subtree is scrolling to reveal content.
33    Pending,
34    /// There is no result for the event, as for select-all, clear and select-word.
35    None,
36}
37
38/// The selected range of one selectable or handler, in content offsets.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub struct SelectedContentRange {
41    /// The start of the selection relative to the start of the content.
42    pub start_offset: i32,
43    /// The end of the selection relative to the start of the content.
44    pub end_offset: i32,
45}
46
47impl SelectedContentRange {
48    /// Creates a range; both offsets are non-negative, as Dart asserts.
49    pub fn new(start_offset: i32, end_offset: i32) -> SelectedContentRange {
50        debug_assert!(start_offset >= 0 && end_offset >= 0);
51        SelectedContentRange {
52            start_offset,
53            end_offset,
54        }
55    }
56}
57
58/// The selected content in a selectable or handler; only plain text so far.
59#[derive(Clone, Debug)]
60pub struct SelectedContent {
61    /// The selected content in plain text format.
62    pub plain_text: String,
63}
64
65impl SelectedContent {
66    /// Creates selected content of plain text.
67    pub fn new(plain_text: impl Into<String>) -> SelectedContent {
68        SelectedContent {
69            plain_text: plain_text.into(),
70        }
71    }
72}
73
74/// The abstract interface to handle [`SelectionEvent`]s.
75///
76/// Extended by [`Selectable`] and by a widget's selection container delegate. This class returns
77/// a [`SelectionGeometry`] as its [`value`](Self::value) and notifies its listeners when that
78/// geometry changes, as Dart's `ValueListenable<SelectionGeometry>`.
79pub trait SelectionHandler: ListenableObject {
80    /// The geometry of the current selection.
81    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry;
82
83    /// Marks this handler responsible for pushing [`LeaderLayer`](crate::LeaderLayer)s for the
84    /// selection handles. `None` cleans up a layer it pushed before.
85    fn push_handle_layers(
86        self: Handle<Self>,
87        app: &mut App,
88        start_handle: Option<Ref<LayerLink>>,
89        end_handle: Option<Ref<LayerLink>>,
90    );
91
92    /// The selected content in this object, if anything is selected.
93    fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent>;
94
95    /// The selected range in this object; `None` when nothing is selected.
96    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange>;
97
98    /// Handles a selection event sent to this object.
99    fn dispatch_selection_event(
100        self: Handle<Self>,
101        app: &mut App,
102        event: &SelectionEvent,
103    ) -> SelectionResult;
104
105    /// The length of the content in this object.
106    fn content_length(self: Handle<Self>, app: &App) -> usize;
107}
108
109/// A mixin that can be selected by users under a `SelectionArea`.
110///
111/// Receives selection events; [`value`](SelectionHandler::value) must reflect the current
112/// selection, and listeners are notified when it changes. The object draws the selection
113/// highlight itself. It registers with a [`SelectionRegistrar`] through [`SelectionRegistrant`].
114pub trait Selectable: SelectionHandler {
115    /// Erases this selectable for a registrar, as Dart's implicit upcast.
116    fn as_selectable(self: Handle<Self>) -> AnySelectable {
117        AnySelectable {
118            id: self.id(),
119            vtable: const { &SelectableVTable::of::<Self>() },
120        }
121    }
122
123    /// {@macro flutter.rendering.RenderObject.getTransformTo}
124    fn get_transform_to(
125        self: Handle<Self>,
126        app: &App,
127        ancestor: Option<AnyRenderObject>,
128    ) -> Matrix4;
129
130    /// The size of this selectable.
131    fn size(self: Handle<Self>, app: &mut App) -> Size;
132
133    /// The bounding boxes of this selectable in its local coordinates.
134    fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect>;
135
136    /// Disposes resources held by the mixin.
137    fn dispose_selectable(self: Handle<Self>, app: &mut App);
138}
139
140/// Erased [`Selectable`]: one identity and a static vtable, as a registrar holds selectables of
141/// more than one concrete type.
142#[derive(Clone, Copy)]
143pub struct AnySelectable {
144    id: HandleId,
145    vtable: &'static SelectableVTable,
146}
147
148/// The erased `pushHandleLayers`: the object, its two links, and the app whose paint it marks.
149pub type PushHandleLayers = fn(&mut App, HandleId, Option<Ref<LayerLink>>, Option<Ref<LayerLink>>);
150
151struct SelectableVTable {
152    value: fn(&App, HandleId) -> SelectionGeometry,
153    push_handle_layers: PushHandleLayers,
154    selected_content: fn(&App, HandleId) -> Option<SelectedContent>,
155    selection: fn(&App, HandleId) -> Option<SelectedContentRange>,
156    dispatch_selection_event: fn(&mut App, HandleId, &SelectionEvent) -> SelectionResult,
157    content_length: fn(&App, HandleId) -> usize,
158    get_transform_to: fn(&App, HandleId, Option<AnyRenderObject>) -> Matrix4,
159    size: fn(&mut App, HandleId) -> Size,
160    bounding_boxes: fn(&mut App, HandleId) -> Vec<Rect>,
161    dispose_selectable: fn(&mut App, HandleId),
162}
163
164impl SelectableVTable {
165    const fn of<A: Selectable>() -> SelectableVTable {
166        SelectableVTable {
167            value: |app, id| A::value(resolve(id), app),
168            push_handle_layers: |app, id, start, end| {
169                A::push_handle_layers(resolve(id), app, start, end)
170            },
171            selected_content: |app, id| A::selected_content(resolve(id), app),
172            selection: |app, id| A::selection(resolve(id), app),
173            dispatch_selection_event: |app, id, event| {
174                A::dispatch_selection_event(resolve(id), app, event)
175            },
176            content_length: |app, id| A::content_length(resolve(id), app),
177            get_transform_to: |app, id, ancestor| A::get_transform_to(resolve(id), app, ancestor),
178            size: |app, id| A::size(resolve(id), app),
179            bounding_boxes: |app, id| A::bounding_boxes(resolve(id), app),
180            dispose_selectable: |app, id| A::dispose_selectable(resolve(id), app),
181        }
182    }
183}
184
185fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
186    Handle::from_id(id)
187}
188
189impl AnySelectable {
190    /// The arena id behind this handle.
191    pub fn id(self) -> HandleId {
192        self.id
193    }
194
195    /// See [`SelectionHandler::value`].
196    pub fn value(self, app: &App) -> SelectionGeometry {
197        (self.vtable.value)(app, self.id)
198    }
199
200    /// See [`SelectionHandler::push_handle_layers`].
201    pub fn push_handle_layers(
202        self,
203        app: &mut App,
204        start_handle: Option<Ref<LayerLink>>,
205        end_handle: Option<Ref<LayerLink>>,
206    ) {
207        (self.vtable.push_handle_layers)(app, self.id, start_handle, end_handle)
208    }
209
210    /// See [`SelectionHandler::selected_content`].
211    pub fn selected_content(self, app: &App) -> Option<SelectedContent> {
212        (self.vtable.selected_content)(app, self.id)
213    }
214
215    /// See [`SelectionHandler::selection`].
216    pub fn selection(self, app: &App) -> Option<SelectedContentRange> {
217        (self.vtable.selection)(app, self.id)
218    }
219
220    /// See [`SelectionHandler::dispatch_selection_event`].
221    pub fn dispatch_selection_event(
222        self,
223        app: &mut App,
224        event: &SelectionEvent,
225    ) -> SelectionResult {
226        (self.vtable.dispatch_selection_event)(app, self.id, event)
227    }
228
229    /// See [`SelectionHandler::content_length`].
230    pub fn content_length(self, app: &App) -> usize {
231        (self.vtable.content_length)(app, self.id)
232    }
233
234    /// See [`Selectable::get_transform_to`].
235    pub fn get_transform_to(self, app: &App, ancestor: Option<AnyRenderObject>) -> Matrix4 {
236        (self.vtable.get_transform_to)(app, self.id, ancestor)
237    }
238
239    /// See [`Selectable::size`].
240    pub fn size(self, app: &mut App) -> Size {
241        (self.vtable.size)(app, self.id)
242    }
243
244    /// See [`Selectable::bounding_boxes`].
245    pub fn bounding_boxes(self, app: &mut App) -> Vec<Rect> {
246        (self.vtable.bounding_boxes)(app, self.id)
247    }
248
249    /// See [`Selectable::dispose_selectable`].
250    pub fn dispose_selectable(self, app: &mut App) {
251        (self.vtable.dispose_selectable)(app, self.id)
252    }
253}
254
255impl std::fmt::Debug for AnySelectable {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        f.debug_struct("AnySelectable")
258            .field("id", &self.id)
259            .finish()
260    }
261}
262
263waft_foundation::erased_handle!(AnySelectable: Selectable => Selectable::as_selectable);
264
265/// The fields of Dart's `SelectionRegistrant` mixin.
266#[derive(Debug, Default)]
267pub struct SelectionRegistrantData {
268    registrar: Option<SelectionRegistrarRef>,
269    subscribed_to_selection_registrar: bool,
270}
271
272impl SelectionRegistrantData {
273    /// Creates registrant fields with no registrar.
274    pub fn new() -> SelectionRegistrantData {
275        SelectionRegistrantData::default()
276    }
277}
278
279/// A mixin that auto-registers the mixer with its registrar.
280///
281/// Set [`registrar`](SelectionRegistrant::registrar) to the registrar to register to. The mixin
282/// only registers while the [`SelectionGeometry::has_content`] returned by the selectable is true.
283pub trait SelectionRegistrant: Selectable {
284    /// The fields of this mixin.
285    fn selection_registrant_data(self: Handle<Self>, app: &App) -> &SelectionRegistrantData;
286
287    /// The fields of this mixin, mutably.
288    fn selection_registrant_data_mut(
289        self: Handle<Self>,
290        app: &mut App,
291    ) -> &mut SelectionRegistrantData;
292
293    /// The registrar this mixin will be or is registered to.
294    fn registrar(self: Handle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
295        self.selection_registrant_data(app)
296            .registrar
297            .as_ref()
298            .map(Retained::handle)
299    }
300
301    /// Dart `SelectionRegistrant.registrar =`.
302    fn set_registrar(self: Handle<Self>, app: &mut App, value: Option<SelectionRegistrarRef>) {
303        let registrar = self.registrar(app);
304        if value.as_ref().map(Retained::handle) == registrar {
305            return;
306        }
307        let listener = Listener::handle_method(self, Self::update_selection_registrar_subscription);
308        if value.is_none() {
309            // When registrar goes from non-null to null.
310            self.remove_listener_from(app, &listener);
311        } else if registrar.is_none() {
312            // When registrar goes from null to non-null.
313            self.add_listener_to(app, listener);
314        }
315        self.remove_selection_registrar_subscription(app);
316        self.selection_registrant_data_mut(app).registrar = value;
317        self.update_selection_registrar_subscription(app);
318    }
319
320    /// Dart's `_updateSelectionRegistrarSubscription`.
321    fn update_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
322        let Some(registrar) = self.registrar(app) else {
323            self.selection_registrant_data_mut(app)
324                .subscribed_to_selection_registrar = false;
325            return;
326        };
327        let has_content = self.value(app).has_content;
328        let subscribed = self
329            .selection_registrant_data(app)
330            .subscribed_to_selection_registrar;
331        if subscribed && !has_content {
332            registrar.remove(app, self.as_selectable());
333            self.selection_registrant_data_mut(app)
334                .subscribed_to_selection_registrar = false;
335        } else if !subscribed && has_content {
336            registrar.add(app, self.as_selectable());
337            self.selection_registrant_data_mut(app)
338                .subscribed_to_selection_registrar = true;
339        }
340    }
341
342    /// Dart's `_removeSelectionRegistrarSubscription`.
343    fn remove_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
344        if self
345            .selection_registrant_data(app)
346            .subscribed_to_selection_registrar
347        {
348            let registrar = self
349                .registrar(app)
350                .expect("a subscribed registrant has a registrar");
351            registrar.remove(app, self.as_selectable());
352            self.selection_registrant_data_mut(app)
353                .subscribed_to_selection_registrar = false;
354        }
355    }
356
357    /// Dart `SelectionRegistrant.dispose`'s own part; the mixer then runs the rest of its
358    /// `dispose`, as Dart's `super.dispose()`.
359    fn dispose_selection_registrant(self: Handle<Self>, app: &mut App) {
360        self.remove_selection_registrar_subscription(app);
361    }
362}
363
364/// A registrar that keeps track of the [`Selectable`]s in a subtree.
365pub trait SelectionRegistrar: Sized + 'static {
366    /// Erases this registrar, as Dart's implicit upcast.
367    fn as_selection_registrar(self: Handle<Self>) -> AnySelectionRegistrar {
368        AnySelectionRegistrar {
369            id: self.id(),
370            vtable: const { &SelectionRegistrarVTable::of::<Self>() },
371        }
372    }
373
374    /// Adds `selectable` to the registrar.
375    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
376
377    /// Removes `selectable` from the registrar.
378    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
379}
380
381/// Erased [`SelectionRegistrar`], for a registrant that does not name the concrete registrar.
382#[derive(Clone, Copy)]
383pub struct AnySelectionRegistrar {
384    id: HandleId,
385    vtable: &'static SelectionRegistrarVTable,
386}
387
388struct SelectionRegistrarVTable {
389    add: fn(&mut App, HandleId, AnySelectable),
390    remove: fn(&mut App, HandleId, AnySelectable),
391}
392
393impl SelectionRegistrarVTable {
394    const fn of<A: SelectionRegistrar>() -> SelectionRegistrarVTable {
395        SelectionRegistrarVTable {
396            add: |app, id, selectable| A::add(resolve(id), app, selectable),
397            remove: |app, id, selectable| A::remove(resolve(id), app, selectable),
398        }
399    }
400}
401
402impl AnySelectionRegistrar {
403    /// The arena id behind this handle.
404    pub fn id(self) -> HandleId {
405        self.id
406    }
407
408    /// See [`SelectionRegistrar::add`].
409    pub fn add(self, app: &mut App, selectable: AnySelectable) {
410        (self.vtable.add)(app, self.id, selectable)
411    }
412
413    /// See [`SelectionRegistrar::remove`].
414    pub fn remove(self, app: &mut App, selectable: AnySelectable) {
415        (self.vtable.remove)(app, self.id, selectable)
416    }
417}
418
419impl std::fmt::Debug for AnySelectionRegistrar {
420    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421        f.debug_struct("AnySelectionRegistrar")
422            .field("id", &self.id)
423            .finish()
424    }
425}
426
427/// A field that keeps a registrar: a paragraph's, a registrant's, a widget's.
428///
429/// A registrar holds its selectables as bare [`AnySelectable`]s, never kept, so a selectable that
430/// keeps its registrar makes no cycle; a selectable removes itself before it is freed.
431pub type SelectionRegistrarRef = Retained<AnySelectionRegistrar>;
432
433waft_foundation::erased_handle!(AnySelectionRegistrar: SelectionRegistrar => SelectionRegistrar::as_selection_registrar);
434
435/// The status of a selection: whether there is one and whether it is collapsed.
436#[derive(Clone, Copy, Debug, PartialEq, Eq)]
437pub enum SelectionStatus {
438    /// The selection is not collapsed.
439    Uncollapsed,
440    /// The selection starts and ends at the same location.
441    Collapsed,
442    /// No selection.
443    None,
444}
445
446/// The geometry of the current selection, in the local coordinates of the selectable.
447#[derive(Clone, Debug, PartialEq)]
448pub struct SelectionGeometry {
449    /// The geometry at the selection start, `None` when it is offstage.
450    pub start_selection_point: Option<SelectionPoint>,
451    /// The geometry at the selection end, `None` when it is offstage.
452    pub end_selection_point: Option<SelectionPoint>,
453    /// The status of the ongoing selection.
454    pub status: SelectionStatus,
455    /// The rects that represent the selection, if there is any.
456    pub selection_rects: Vec<Rect>,
457    /// Whether there is any selectable content.
458    pub has_content: bool,
459}
460
461impl SelectionGeometry {
462    /// Creates a selection geometry with no selection points and no rects; the setters give
463    /// them, as Dart's optional arguments.
464    pub fn new(status: SelectionStatus, has_content: bool) -> SelectionGeometry {
465        SelectionGeometry {
466            start_selection_point: None,
467            end_selection_point: None,
468            status,
469            selection_rects: Vec::new(),
470            has_content,
471        }
472    }
473
474    /// Dart `SelectionGeometry(startSelectionPoint:)`.
475    pub fn start_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
476        self.start_selection_point = value;
477        self.debug_assert_points_have_selection();
478        self
479    }
480
481    /// Dart `SelectionGeometry(endSelectionPoint:)`.
482    pub fn end_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
483        self.end_selection_point = value;
484        self.debug_assert_points_have_selection();
485        self
486    }
487
488    /// Dart `SelectionGeometry(selectionRects:)`.
489    pub fn selection_rects(mut self, value: Vec<Rect>) -> SelectionGeometry {
490        self.selection_rects = value;
491        self
492    }
493
494    /// Dart `SelectionGeometry(status:)`.
495    pub fn status(mut self, value: SelectionStatus) -> SelectionGeometry {
496        self.status = value;
497        self
498    }
499
500    /// Dart `SelectionGeometry(hasContent:)`.
501    pub fn has_content(mut self, value: bool) -> SelectionGeometry {
502        self.has_content = value;
503        self
504    }
505
506    fn debug_assert_points_have_selection(&self) {
507        debug_assert!(
508            (self.start_selection_point.is_none() && self.end_selection_point.is_none())
509                || self.status != SelectionStatus::None
510        );
511    }
512
513    /// Whether there is an ongoing selection.
514    pub fn has_selection(&self) -> bool {
515        self.status != SelectionStatus::None
516    }
517
518    /// A copy the setters then change, as Dart's `copyWith`.
519    pub fn copy_with(&self) -> SelectionGeometry {
520        self.clone()
521    }
522}
523
524/// The geometry information of one selection point.
525#[derive(Clone, Copy, Debug, PartialEq)]
526pub struct SelectionPoint {
527    /// The position of the selection point in the containing selectable's coordinates.
528    pub local_position: Offset,
529    /// The line height at the selection point.
530    pub line_height: f64,
531    /// The selection handle to build at the point.
532    pub handle_type: TextSelectionHandleType,
533}
534
535impl SelectionPoint {
536    /// Creates a selection point.
537    pub fn new(
538        local_position: Offset,
539        line_height: f64,
540        handle_type: TextSelectionHandleType,
541    ) -> SelectionPoint {
542        SelectionPoint {
543            local_position,
544            line_height,
545            handle_type,
546        }
547    }
548}
549
550/// The type of selection handle to display.
551#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
552pub enum TextSelectionHandleType {
553    /// The selection handle is to the left of the selection end point.
554    Left,
555    /// The selection handle is to the right of the selection end point.
556    Right,
557    /// The start and end of the selection are co-incident at this point.
558    Collapsed,
559}
560
561/// A utility class that provides useful methods for handling selection events.
562pub struct SelectionUtils;
563
564impl SelectionUtils {
565    /// Determines a [`SelectionResult`] purely from the target rectangle.
566    ///
567    /// [`SelectionResult::End`] when `point` is inside `target_rect`, [`SelectionResult::Previous`]
568    /// when it is above it in screen order, and [`SelectionResult::Next`] when below.
569    pub fn get_result_based_on_rect(target_rect: Rect, point: Offset) -> SelectionResult {
570        if target_rect.contains(point) {
571            return SelectionResult::End;
572        }
573        if point.dy() < target_rect.top {
574            return SelectionResult::Previous;
575        }
576        if point.dy() > target_rect.bottom {
577            return SelectionResult::Next;
578        }
579        if point.dx() >= target_rect.right {
580            SelectionResult::Next
581        } else {
582            SelectionResult::Previous
583        }
584    }
585
586    /// Adjusts a dragging offset to lie within `target_rect`.
587    ///
588    /// A point above the rect (or left of it, when at or above the bottom edge) moves to the top
589    /// leading corner; any other outside point moves to the bottom trailing corner. Leading and
590    /// trailing follow `direction`, as Dart's default `TextDirection.ltr` does.
591    pub fn adjust_drag_offset(
592        target_rect: Rect,
593        point: Offset,
594        direction: TextDirection,
595    ) -> Offset {
596        if target_rect.contains(point) {
597            return point;
598        }
599        if point.dy() <= target_rect.top
600            || point.dy() <= target_rect.bottom && point.dx() <= target_rect.left
601        {
602            // Area 1.
603            if direction == TextDirection::Ltr {
604                Offset::new(target_rect.left, target_rect.top)
605            } else {
606                Offset::new(target_rect.right, target_rect.top)
607            }
608        } else {
609            // Area 2.
610            if direction == TextDirection::Ltr {
611                Offset::new(target_rect.right, target_rect.bottom)
612            } else {
613                Offset::new(target_rect.left, target_rect.bottom)
614            }
615        }
616    }
617}
618
619/// The unit of how selection handles move in text.
620#[derive(Clone, Copy, Debug, PartialEq, Eq)]
621pub enum TextGranularity {
622    /// Each character is an atomic unit.
623    Character,
624    /// A word is an atomic unit.
625    Word,
626    /// A paragraph is an atomic unit.
627    Paragraph,
628    /// Each line break is an atomic unit.
629    Line,
630    /// The entire document is an atomic unit.
631    Document,
632}
633
634/// The direction to extend a selection.
635#[derive(Clone, Copy, Debug, PartialEq, Eq)]
636pub enum SelectionExtendDirection {
637    /// Move one edge vertically to the previous adjacent line.
638    PreviousLine,
639    /// Move one edge vertically to the next adjacent line.
640    NextLine,
641    /// Move the selection edges forward to a horizontal offset in the same line.
642    Forward,
643    /// Move the selection edges backward to a horizontal offset in the same line.
644    Backward,
645}
646
647/// A selection event sent to a [`SelectionHandler`].
648///
649/// Dart's abstract `SelectionEvent` and its subclasses are one enum: the subclass is the variant,
650/// and [`SelectionEventType`] follows from it.
651#[derive(Clone, Debug)]
652pub enum SelectionEvent {
653    /// Updates the selection start edge.
654    StartEdgeUpdate {
655        /// The new location of the edge, in global coordinates.
656        global_position: Offset,
657        /// The granularity the edge moves by.
658        granularity: TextGranularity,
659    },
660    /// Updates the selection end edge.
661    EndEdgeUpdate {
662        /// The new location of the edge, in global coordinates.
663        global_position: Offset,
664        /// The granularity the edge moves by.
665        granularity: TextGranularity,
666    },
667    /// Clears the current selection.
668    Clear,
669    /// Selects all the available content.
670    SelectAll,
671    /// Selects the word at `global_position`.
672    SelectWord {
673        /// The position in global coordinates to select a word at.
674        global_position: Offset,
675    },
676    /// Selects the paragraph at `global_position`.
677    SelectParagraph {
678        /// The position in global coordinates to select a paragraph at.
679        global_position: Offset,
680        /// Whether the selectable should be absorbed into an encompassing paragraph.
681        absorb: bool,
682    },
683    /// Extends the start or end of the selection by `granularity`.
684    GranularlyExtendSelection {
685        /// Whether to extend the selection forward.
686        forward: bool,
687        /// Whether this event updates the end edge.
688        is_end: bool,
689        /// The granularity to extend by.
690        granularity: TextGranularity,
691    },
692    /// Extends the current selection with respect to `direction`.
693    DirectionallyExtendSelection {
694        /// The horizontal offset to move to, in global coordinates.
695        dx: f64,
696        /// Whether this event updates the end edge.
697        is_end: bool,
698        /// The direction to move.
699        direction: SelectionExtendDirection,
700    },
701}
702
703impl SelectionEvent {
704    /// The type of this event.
705    pub fn ty(&self) -> SelectionEventType {
706        match self {
707            SelectionEvent::StartEdgeUpdate { .. } => SelectionEventType::StartEdgeUpdate,
708            SelectionEvent::EndEdgeUpdate { .. } => SelectionEventType::EndEdgeUpdate,
709            SelectionEvent::Clear => SelectionEventType::Clear,
710            SelectionEvent::SelectAll => SelectionEventType::SelectAll,
711            SelectionEvent::SelectWord { .. } => SelectionEventType::SelectWord,
712            SelectionEvent::SelectParagraph { .. } => SelectionEventType::SelectParagraph,
713            SelectionEvent::GranularlyExtendSelection { .. } => {
714                SelectionEventType::GranularlyExtendSelection
715            }
716            SelectionEvent::DirectionallyExtendSelection { .. } => {
717                SelectionEventType::DirectionallyExtendSelection
718            }
719        }
720    }
721
722    /// Creates a start-edge update at `global_position`, at character granularity unless given.
723    pub fn for_start(
724        global_position: Offset,
725        granularity: Option<TextGranularity>,
726    ) -> SelectionEvent {
727        SelectionEvent::StartEdgeUpdate {
728            global_position,
729            granularity: granularity.unwrap_or(TextGranularity::Character),
730        }
731    }
732
733    /// Creates an end-edge update at `global_position`, at character granularity unless given.
734    pub fn for_end(
735        global_position: Offset,
736        granularity: Option<TextGranularity>,
737    ) -> SelectionEvent {
738        SelectionEvent::EndEdgeUpdate {
739            global_position,
740            granularity: granularity.unwrap_or(TextGranularity::Character),
741        }
742    }
743
744    /// A copy with the given values replaced.
745    pub fn copy_with(
746        &self,
747        dx: Option<f64>,
748        is_end: Option<bool>,
749        direction: Option<SelectionExtendDirection>,
750    ) -> SelectionEvent {
751        match self {
752            SelectionEvent::DirectionallyExtendSelection {
753                dx: old_dx,
754                is_end: old_is_end,
755                direction: old_direction,
756            } => SelectionEvent::DirectionallyExtendSelection {
757                dx: dx.unwrap_or(*old_dx),
758                is_end: is_end.unwrap_or(*old_is_end),
759                direction: direction.unwrap_or(*old_direction),
760            },
761            event => event.clone(),
762        }
763    }
764}
765
766/// The type of a [`SelectionEvent`].
767#[derive(Clone, Copy, Debug, PartialEq, Eq)]
768pub enum SelectionEventType {
769    /// An event to update the selection start edge.
770    StartEdgeUpdate,
771    /// An event to update the selection end edge.
772    EndEdgeUpdate,
773    /// An event to clear the current selection.
774    Clear,
775    /// An event to select all the available content.
776    SelectAll,
777    /// An event to select a word at a location.
778    SelectWord,
779    /// An event to select a paragraph at a location.
780    SelectParagraph,
781    /// An event that extends the selection by a [`TextGranularity`].
782    GranularlyExtendSelection,
783    /// An event that extends the selection in a [`SelectionExtendDirection`].
784    DirectionallyExtendSelection,
785}
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790
791    const RECT: Rect = Rect::from_ltrb(100.0, 100.0, 300.0, 600.0);
792    const OUTSIDE_TOP_LEFT: Offset = Offset::new(50.0, 50.0);
793    const OUTSIDE_LEFT: Offset = Offset::new(50.0, 200.0);
794    const OUTSIDE_BOTTOM_LEFT: Offset = Offset::new(50.0, 700.0);
795    const OUTSIDE_TOP: Offset = Offset::new(200.0, 50.0);
796    const OUTSIDE_TOP_RIGHT: Offset = Offset::new(350.0, 50.0);
797    const OUTSIDE_RIGHT: Offset = Offset::new(350.0, 200.0);
798    const OUTSIDE_BOTTOM_RIGHT: Offset = Offset::new(350.0, 700.0);
799    const OUTSIDE_BOTTOM: Offset = Offset::new(200.0, 700.0);
800    const CENTER: Offset = Offset::new(150.0, 300.0);
801
802    // selection_test.dart 'selectionBasedOnRect works'.
803    #[test]
804    fn selection_based_on_rect_works() {
805        assert_eq!(
806            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_LEFT),
807            SelectionResult::Previous
808        );
809        assert_eq!(
810            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_LEFT),
811            SelectionResult::Previous
812        );
813        assert_eq!(
814            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_LEFT),
815            SelectionResult::Next
816        );
817        assert_eq!(
818            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP),
819            SelectionResult::Previous
820        );
821        assert_eq!(
822            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_RIGHT),
823            SelectionResult::Previous
824        );
825        assert_eq!(
826            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_RIGHT),
827            SelectionResult::Next
828        );
829        assert_eq!(
830            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_RIGHT),
831            SelectionResult::Next
832        );
833        assert_eq!(
834            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM),
835            SelectionResult::Next
836        );
837        assert_eq!(
838            SelectionUtils::get_result_based_on_rect(RECT, CENTER),
839            SelectionResult::End
840        );
841    }
842
843    // selection_test.dart 'adjustDragOffset works'.
844    #[test]
845    fn adjust_drag_offset_works() {
846        let top_left = Offset::new(RECT.left, RECT.top);
847        let top_right = Offset::new(RECT.right, RECT.top);
848        let bottom_left = Offset::new(RECT.left, RECT.bottom);
849        let bottom_right = Offset::new(RECT.right, RECT.bottom);
850
851        // ltr
852        for (point, expected) in [
853            (OUTSIDE_TOP_LEFT, top_left),
854            (OUTSIDE_LEFT, top_left),
855            (OUTSIDE_BOTTOM_LEFT, bottom_right),
856            (OUTSIDE_TOP, top_left),
857            (OUTSIDE_TOP_RIGHT, top_left),
858            (OUTSIDE_RIGHT, bottom_right),
859            (OUTSIDE_BOTTOM_RIGHT, bottom_right),
860            (OUTSIDE_BOTTOM, bottom_right),
861            (CENTER, CENTER),
862        ] {
863            assert_eq!(
864                SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Ltr),
865                expected
866            );
867        }
868        // rtl
869        for (point, expected) in [
870            (OUTSIDE_TOP_LEFT, top_right),
871            (OUTSIDE_LEFT, top_right),
872            (OUTSIDE_BOTTOM_LEFT, bottom_left),
873            (OUTSIDE_TOP, top_right),
874            (OUTSIDE_TOP_RIGHT, top_right),
875            (OUTSIDE_RIGHT, bottom_left),
876            (OUTSIDE_BOTTOM_RIGHT, bottom_left),
877            (OUTSIDE_BOTTOM, bottom_left),
878            (CENTER, CENTER),
879        ] {
880            assert_eq!(
881                SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Rtl),
882                expected
883            );
884        }
885    }
886}