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    add_listener: fn(&mut App, HandleId, Listener),
163    remove_listener: fn(&mut App, HandleId, &Listener),
164}
165
166impl SelectableVTable {
167    const fn of<A: Selectable>() -> SelectableVTable {
168        SelectableVTable {
169            value: |app, id| A::value(resolve(id), app),
170            push_handle_layers: |app, id, start, end| {
171                A::push_handle_layers(resolve(id), app, start, end)
172            },
173            selected_content: |app, id| A::selected_content(resolve(id), app),
174            selection: |app, id| A::selection(resolve(id), app),
175            dispatch_selection_event: |app, id, event| {
176                A::dispatch_selection_event(resolve(id), app, event)
177            },
178            content_length: |app, id| A::content_length(resolve(id), app),
179            get_transform_to: |app, id, ancestor| A::get_transform_to(resolve(id), app, ancestor),
180            size: |app, id| A::size(resolve(id), app),
181            bounding_boxes: |app, id| A::bounding_boxes(resolve(id), app),
182            dispose_selectable: |app, id| A::dispose_selectable(resolve(id), app),
183            add_listener: |app, id, listener| {
184                ListenableObject::add_listener(resolve::<A>(id), app, listener)
185            },
186            remove_listener: |app, id, listener| {
187                ListenableObject::remove_listener(resolve::<A>(id), app, listener)
188            },
189        }
190    }
191}
192
193fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
194    Handle::from_id(id)
195}
196
197impl AnySelectable {
198    /// The arena id behind this handle.
199    pub fn id(self) -> HandleId {
200        self.id
201    }
202
203    /// See [`SelectionHandler::value`].
204    pub fn value(self, app: &App) -> SelectionGeometry {
205        (self.vtable.value)(app, self.id)
206    }
207
208    /// See [`SelectionHandler::push_handle_layers`].
209    pub fn push_handle_layers(
210        self,
211        app: &mut App,
212        start_handle: Option<Ref<LayerLink>>,
213        end_handle: Option<Ref<LayerLink>>,
214    ) {
215        (self.vtable.push_handle_layers)(app, self.id, start_handle, end_handle)
216    }
217
218    /// See [`SelectionHandler::selected_content`].
219    pub fn selected_content(self, app: &App) -> Option<SelectedContent> {
220        (self.vtable.selected_content)(app, self.id)
221    }
222
223    /// See [`SelectionHandler::selection`].
224    pub fn selection(self, app: &App) -> Option<SelectedContentRange> {
225        (self.vtable.selection)(app, self.id)
226    }
227
228    /// See [`SelectionHandler::dispatch_selection_event`].
229    pub fn dispatch_selection_event(
230        self,
231        app: &mut App,
232        event: &SelectionEvent,
233    ) -> SelectionResult {
234        (self.vtable.dispatch_selection_event)(app, self.id, event)
235    }
236
237    /// See [`SelectionHandler::content_length`].
238    pub fn content_length(self, app: &App) -> usize {
239        (self.vtable.content_length)(app, self.id)
240    }
241
242    /// See [`Selectable::get_transform_to`].
243    pub fn get_transform_to(self, app: &App, ancestor: Option<AnyRenderObject>) -> Matrix4 {
244        (self.vtable.get_transform_to)(app, self.id, ancestor)
245    }
246
247    /// See [`Selectable::size`].
248    pub fn size(self, app: &mut App) -> Size {
249        (self.vtable.size)(app, self.id)
250    }
251
252    /// See [`Selectable::bounding_boxes`].
253    pub fn bounding_boxes(self, app: &mut App) -> Vec<Rect> {
254        (self.vtable.bounding_boxes)(app, self.id)
255    }
256
257    /// See [`Selectable::dispose_selectable`].
258    pub fn dispose_selectable(self, app: &mut App) {
259        (self.vtable.dispose_selectable)(app, self.id)
260    }
261
262    /// Registers `listener` with the selectable's [`Listenable`], as Dart's
263    /// `selectable.addListener`.
264    pub fn add_listener(self, app: &mut App, listener: Listener) {
265        (self.vtable.add_listener)(app, self.id, listener)
266    }
267
268    /// Removes `listener` from the selectable, as Dart's `selectable.removeListener`.
269    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
270        (self.vtable.remove_listener)(app, self.id, listener)
271    }
272}
273
274impl std::fmt::Debug for AnySelectable {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.debug_struct("AnySelectable")
277            .field("id", &self.id)
278            .finish()
279    }
280}
281
282waft_foundation::erased_handle!(AnySelectable: Selectable => Selectable::as_selectable);
283
284/// The fields of Dart's `SelectionRegistrant` mixin.
285#[derive(Debug, Default)]
286pub struct SelectionRegistrantData {
287    registrar: Option<SelectionRegistrarRef>,
288    subscribed_to_selection_registrar: bool,
289}
290
291impl SelectionRegistrantData {
292    /// Creates registrant fields with no registrar.
293    pub fn new() -> SelectionRegistrantData {
294        SelectionRegistrantData::default()
295    }
296}
297
298/// A mixin that auto-registers the mixer with its registrar.
299///
300/// Set [`registrar`](SelectionRegistrant::registrar) to the registrar to register to. The mixin
301/// only registers while the [`SelectionGeometry::has_content`] returned by the selectable is true.
302pub trait SelectionRegistrant: Selectable {
303    /// The fields of this mixin.
304    fn selection_registrant_data(self: Handle<Self>, app: &App) -> &SelectionRegistrantData;
305
306    /// The fields of this mixin, mutably.
307    fn selection_registrant_data_mut(
308        self: Handle<Self>,
309        app: &mut App,
310    ) -> &mut SelectionRegistrantData;
311
312    /// The registrar this mixin will be or is registered to.
313    fn registrar(self: Handle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
314        self.selection_registrant_data(app)
315            .registrar
316            .as_ref()
317            .map(Retained::handle)
318    }
319
320    /// Dart `SelectionRegistrant.registrar =`.
321    fn set_registrar(self: Handle<Self>, app: &mut App, value: Option<SelectionRegistrarRef>) {
322        let registrar = self.registrar(app);
323        if value.as_ref().map(Retained::handle) == registrar {
324            return;
325        }
326        let listener = Listener::handle_method(self, Self::update_selection_registrar_subscription);
327        if value.is_none() {
328            // When registrar goes from non-null to null.
329            self.remove_listener_from(app, &listener);
330        } else if registrar.is_none() {
331            // When registrar goes from null to non-null.
332            self.add_listener_to(app, listener);
333        }
334        self.remove_selection_registrar_subscription(app);
335        self.selection_registrant_data_mut(app).registrar = value;
336        self.update_selection_registrar_subscription(app);
337    }
338
339    /// Dart's `_updateSelectionRegistrarSubscription`.
340    fn update_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
341        let Some(registrar) = self.registrar(app) else {
342            self.selection_registrant_data_mut(app)
343                .subscribed_to_selection_registrar = false;
344            return;
345        };
346        let has_content = self.value(app).has_content;
347        let subscribed = self
348            .selection_registrant_data(app)
349            .subscribed_to_selection_registrar;
350        if subscribed && !has_content {
351            registrar.remove(app, self.as_selectable());
352            self.selection_registrant_data_mut(app)
353                .subscribed_to_selection_registrar = false;
354        } else if !subscribed && has_content {
355            registrar.add(app, self.as_selectable());
356            self.selection_registrant_data_mut(app)
357                .subscribed_to_selection_registrar = true;
358        }
359    }
360
361    /// Dart's `_removeSelectionRegistrarSubscription`.
362    fn remove_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
363        if self
364            .selection_registrant_data(app)
365            .subscribed_to_selection_registrar
366        {
367            let registrar = self
368                .registrar(app)
369                .expect("a subscribed registrant has a registrar");
370            registrar.remove(app, self.as_selectable());
371            self.selection_registrant_data_mut(app)
372                .subscribed_to_selection_registrar = false;
373        }
374    }
375
376    /// Dart `SelectionRegistrant.dispose`'s own part; the mixer then runs the rest of its
377    /// `dispose`, as Dart's `super.dispose()`.
378    fn dispose_selection_registrant(self: Handle<Self>, app: &mut App) {
379        self.remove_selection_registrar_subscription(app);
380    }
381}
382
383/// A registrar that keeps track of the [`Selectable`]s in a subtree.
384pub trait SelectionRegistrar: Sized + 'static {
385    /// Erases this registrar, as Dart's implicit upcast.
386    fn as_selection_registrar(self: Handle<Self>) -> AnySelectionRegistrar {
387        AnySelectionRegistrar {
388            id: self.id(),
389            vtable: const { &SelectionRegistrarVTable::of::<Self>() },
390        }
391    }
392
393    /// Adds `selectable` to the registrar.
394    fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
395
396    /// Removes `selectable` from the registrar.
397    fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
398}
399
400/// Erased [`SelectionRegistrar`], for a registrant that does not name the concrete registrar.
401#[derive(Clone, Copy)]
402pub struct AnySelectionRegistrar {
403    id: HandleId,
404    vtable: &'static SelectionRegistrarVTable,
405}
406
407struct SelectionRegistrarVTable {
408    add: fn(&mut App, HandleId, AnySelectable),
409    remove: fn(&mut App, HandleId, AnySelectable),
410}
411
412impl SelectionRegistrarVTable {
413    const fn of<A: SelectionRegistrar>() -> SelectionRegistrarVTable {
414        SelectionRegistrarVTable {
415            add: |app, id, selectable| A::add(resolve(id), app, selectable),
416            remove: |app, id, selectable| A::remove(resolve(id), app, selectable),
417        }
418    }
419}
420
421impl AnySelectionRegistrar {
422    /// The arena id behind this handle.
423    pub fn id(self) -> HandleId {
424        self.id
425    }
426
427    /// See [`SelectionRegistrar::add`].
428    pub fn add(self, app: &mut App, selectable: AnySelectable) {
429        (self.vtable.add)(app, self.id, selectable)
430    }
431
432    /// See [`SelectionRegistrar::remove`].
433    pub fn remove(self, app: &mut App, selectable: AnySelectable) {
434        (self.vtable.remove)(app, self.id, selectable)
435    }
436}
437
438impl std::fmt::Debug for AnySelectionRegistrar {
439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440        f.debug_struct("AnySelectionRegistrar")
441            .field("id", &self.id)
442            .finish()
443    }
444}
445
446/// A field that keeps a registrar: a paragraph's, a registrant's, a widget's.
447///
448/// A registrar holds its selectables as bare [`AnySelectable`]s, never kept, so a selectable that
449/// keeps its registrar makes no cycle; a selectable removes itself before it is freed.
450pub type SelectionRegistrarRef = Retained<AnySelectionRegistrar>;
451
452waft_foundation::erased_handle!(AnySelectionRegistrar: SelectionRegistrar => SelectionRegistrar::as_selection_registrar);
453
454/// The status of a selection: whether there is one and whether it is collapsed.
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
456pub enum SelectionStatus {
457    /// The selection is not collapsed.
458    Uncollapsed,
459    /// The selection starts and ends at the same location.
460    Collapsed,
461    /// No selection.
462    None,
463}
464
465/// The geometry of the current selection, in the local coordinates of the selectable.
466#[derive(Clone, Debug, PartialEq)]
467pub struct SelectionGeometry {
468    /// The geometry at the selection start, `None` when it is offstage.
469    pub start_selection_point: Option<SelectionPoint>,
470    /// The geometry at the selection end, `None` when it is offstage.
471    pub end_selection_point: Option<SelectionPoint>,
472    /// The status of the ongoing selection.
473    pub status: SelectionStatus,
474    /// The rects that represent the selection, if there is any.
475    pub selection_rects: Vec<Rect>,
476    /// Whether there is any selectable content.
477    pub has_content: bool,
478}
479
480impl SelectionGeometry {
481    /// Creates a selection geometry with no selection points and no rects; the setters give
482    /// them, as Dart's optional arguments.
483    pub fn new(status: SelectionStatus, has_content: bool) -> SelectionGeometry {
484        SelectionGeometry {
485            start_selection_point: None,
486            end_selection_point: None,
487            status,
488            selection_rects: Vec::new(),
489            has_content,
490        }
491    }
492
493    /// Dart `SelectionGeometry(startSelectionPoint:)`.
494    pub fn start_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
495        self.start_selection_point = value;
496        self.debug_assert_points_have_selection();
497        self
498    }
499
500    /// Dart `SelectionGeometry(endSelectionPoint:)`.
501    pub fn end_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
502        self.end_selection_point = value;
503        self.debug_assert_points_have_selection();
504        self
505    }
506
507    /// Dart `SelectionGeometry(selectionRects:)`.
508    pub fn selection_rects(mut self, value: Vec<Rect>) -> SelectionGeometry {
509        self.selection_rects = value;
510        self
511    }
512
513    /// Dart `SelectionGeometry(status:)`.
514    pub fn status(mut self, value: SelectionStatus) -> SelectionGeometry {
515        self.status = value;
516        self
517    }
518
519    /// Dart `SelectionGeometry(hasContent:)`.
520    pub fn has_content(mut self, value: bool) -> SelectionGeometry {
521        self.has_content = value;
522        self
523    }
524
525    fn debug_assert_points_have_selection(&self) {
526        debug_assert!(
527            (self.start_selection_point.is_none() && self.end_selection_point.is_none())
528                || self.status != SelectionStatus::None
529        );
530    }
531
532    /// Whether there is an ongoing selection.
533    pub fn has_selection(&self) -> bool {
534        self.status != SelectionStatus::None
535    }
536
537    /// A copy the setters then change, as Dart's `copyWith`.
538    pub fn copy_with(&self) -> SelectionGeometry {
539        self.clone()
540    }
541}
542
543/// The geometry information of one selection point.
544#[derive(Clone, Copy, Debug, PartialEq)]
545pub struct SelectionPoint {
546    /// The position of the selection point in the containing selectable's coordinates.
547    pub local_position: Offset,
548    /// The line height at the selection point.
549    pub line_height: f64,
550    /// The selection handle to build at the point.
551    pub handle_type: TextSelectionHandleType,
552}
553
554impl SelectionPoint {
555    /// Creates a selection point.
556    pub fn new(
557        local_position: Offset,
558        line_height: f64,
559        handle_type: TextSelectionHandleType,
560    ) -> SelectionPoint {
561        SelectionPoint {
562            local_position,
563            line_height,
564            handle_type,
565        }
566    }
567}
568
569/// The type of selection handle to display.
570#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
571pub enum TextSelectionHandleType {
572    /// The selection handle is to the left of the selection end point.
573    Left,
574    /// The selection handle is to the right of the selection end point.
575    Right,
576    /// The start and end of the selection are co-incident at this point.
577    Collapsed,
578}
579
580/// A utility class that provides useful methods for handling selection events.
581pub struct SelectionUtils;
582
583impl SelectionUtils {
584    /// Determines a [`SelectionResult`] purely from the target rectangle.
585    ///
586    /// [`SelectionResult::End`] when `point` is inside `target_rect`, [`SelectionResult::Previous`]
587    /// when it is above it in screen order, and [`SelectionResult::Next`] when below.
588    pub fn get_result_based_on_rect(target_rect: Rect, point: Offset) -> SelectionResult {
589        if target_rect.contains(point) {
590            return SelectionResult::End;
591        }
592        if point.dy() < target_rect.top {
593            return SelectionResult::Previous;
594        }
595        if point.dy() > target_rect.bottom {
596            return SelectionResult::Next;
597        }
598        if point.dx() >= target_rect.right {
599            SelectionResult::Next
600        } else {
601            SelectionResult::Previous
602        }
603    }
604
605    /// Adjusts a dragging offset to lie within `target_rect`.
606    ///
607    /// A point above the rect (or left of it, when at or above the bottom edge) moves to the top
608    /// leading corner; any other outside point moves to the bottom trailing corner. Leading and
609    /// trailing follow `direction`, as Dart's default `TextDirection.ltr` does.
610    pub fn adjust_drag_offset(
611        target_rect: Rect,
612        point: Offset,
613        direction: TextDirection,
614    ) -> Offset {
615        if target_rect.contains(point) {
616            return point;
617        }
618        if point.dy() <= target_rect.top
619            || point.dy() <= target_rect.bottom && point.dx() <= target_rect.left
620        {
621            // Area 1.
622            if direction == TextDirection::Ltr {
623                Offset::new(target_rect.left, target_rect.top)
624            } else {
625                Offset::new(target_rect.right, target_rect.top)
626            }
627        } else {
628            // Area 2.
629            if direction == TextDirection::Ltr {
630                Offset::new(target_rect.right, target_rect.bottom)
631            } else {
632                Offset::new(target_rect.left, target_rect.bottom)
633            }
634        }
635    }
636}
637
638/// The unit of how selection handles move in text.
639#[derive(Clone, Copy, Debug, PartialEq, Eq)]
640pub enum TextGranularity {
641    /// Each character is an atomic unit.
642    Character,
643    /// A word is an atomic unit.
644    Word,
645    /// A paragraph is an atomic unit.
646    Paragraph,
647    /// Each line break is an atomic unit.
648    Line,
649    /// The entire document is an atomic unit.
650    Document,
651}
652
653/// The direction to extend a selection.
654#[derive(Clone, Copy, Debug, PartialEq, Eq)]
655pub enum SelectionExtendDirection {
656    /// Move one edge vertically to the previous adjacent line.
657    PreviousLine,
658    /// Move one edge vertically to the next adjacent line.
659    NextLine,
660    /// Move the selection edges forward to a horizontal offset in the same line.
661    Forward,
662    /// Move the selection edges backward to a horizontal offset in the same line.
663    Backward,
664}
665
666/// A selection event sent to a [`SelectionHandler`].
667///
668/// Dart's abstract `SelectionEvent` and its subclasses are one enum: the subclass is the variant,
669/// and [`SelectionEventType`] follows from it.
670#[derive(Clone, Debug)]
671pub enum SelectionEvent {
672    /// Updates the selection start edge.
673    StartEdgeUpdate {
674        /// The new location of the edge, in global coordinates.
675        global_position: Offset,
676        /// The granularity the edge moves by.
677        granularity: TextGranularity,
678    },
679    /// Updates the selection end edge.
680    EndEdgeUpdate {
681        /// The new location of the edge, in global coordinates.
682        global_position: Offset,
683        /// The granularity the edge moves by.
684        granularity: TextGranularity,
685    },
686    /// Clears the current selection.
687    Clear,
688    /// Selects all the available content.
689    SelectAll,
690    /// Selects the word at `global_position`.
691    SelectWord {
692        /// The position in global coordinates to select a word at.
693        global_position: Offset,
694    },
695    /// Selects the paragraph at `global_position`.
696    SelectParagraph {
697        /// The position in global coordinates to select a paragraph at.
698        global_position: Offset,
699        /// Whether the selectable should be absorbed into an encompassing paragraph.
700        absorb: bool,
701    },
702    /// Extends the start or end of the selection by `granularity`.
703    GranularlyExtendSelection {
704        /// Whether to extend the selection forward.
705        forward: bool,
706        /// Whether this event updates the end edge.
707        is_end: bool,
708        /// The granularity to extend by.
709        granularity: TextGranularity,
710    },
711    /// Extends the current selection with respect to `direction`.
712    DirectionallyExtendSelection {
713        /// The horizontal offset to move to, in global coordinates.
714        dx: f64,
715        /// Whether this event updates the end edge.
716        is_end: bool,
717        /// The direction to move.
718        direction: SelectionExtendDirection,
719    },
720}
721
722impl SelectionEvent {
723    /// The type of this event.
724    pub fn ty(&self) -> SelectionEventType {
725        match self {
726            SelectionEvent::StartEdgeUpdate { .. } => SelectionEventType::StartEdgeUpdate,
727            SelectionEvent::EndEdgeUpdate { .. } => SelectionEventType::EndEdgeUpdate,
728            SelectionEvent::Clear => SelectionEventType::Clear,
729            SelectionEvent::SelectAll => SelectionEventType::SelectAll,
730            SelectionEvent::SelectWord { .. } => SelectionEventType::SelectWord,
731            SelectionEvent::SelectParagraph { .. } => SelectionEventType::SelectParagraph,
732            SelectionEvent::GranularlyExtendSelection { .. } => {
733                SelectionEventType::GranularlyExtendSelection
734            }
735            SelectionEvent::DirectionallyExtendSelection { .. } => {
736                SelectionEventType::DirectionallyExtendSelection
737            }
738        }
739    }
740
741    /// Creates a start-edge update at `global_position`, at character granularity unless given.
742    pub fn for_start(
743        global_position: Offset,
744        granularity: Option<TextGranularity>,
745    ) -> SelectionEvent {
746        SelectionEvent::StartEdgeUpdate {
747            global_position,
748            granularity: granularity.unwrap_or(TextGranularity::Character),
749        }
750    }
751
752    /// Creates an end-edge update at `global_position`, at character granularity unless given.
753    pub fn for_end(
754        global_position: Offset,
755        granularity: Option<TextGranularity>,
756    ) -> SelectionEvent {
757        SelectionEvent::EndEdgeUpdate {
758            global_position,
759            granularity: granularity.unwrap_or(TextGranularity::Character),
760        }
761    }
762
763    /// A copy with the given values replaced.
764    pub fn copy_with(
765        &self,
766        dx: Option<f64>,
767        is_end: Option<bool>,
768        direction: Option<SelectionExtendDirection>,
769    ) -> SelectionEvent {
770        match self {
771            SelectionEvent::DirectionallyExtendSelection {
772                dx: old_dx,
773                is_end: old_is_end,
774                direction: old_direction,
775            } => SelectionEvent::DirectionallyExtendSelection {
776                dx: dx.unwrap_or(*old_dx),
777                is_end: is_end.unwrap_or(*old_is_end),
778                direction: direction.unwrap_or(*old_direction),
779            },
780            event => event.clone(),
781        }
782    }
783}
784
785/// The type of a [`SelectionEvent`].
786#[derive(Clone, Copy, Debug, PartialEq, Eq)]
787pub enum SelectionEventType {
788    /// An event to update the selection start edge.
789    StartEdgeUpdate,
790    /// An event to update the selection end edge.
791    EndEdgeUpdate,
792    /// An event to clear the current selection.
793    Clear,
794    /// An event to select all the available content.
795    SelectAll,
796    /// An event to select a word at a location.
797    SelectWord,
798    /// An event to select a paragraph at a location.
799    SelectParagraph,
800    /// An event that extends the selection by a [`TextGranularity`].
801    GranularlyExtendSelection,
802    /// An event that extends the selection in a [`SelectionExtendDirection`].
803    DirectionallyExtendSelection,
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    const RECT: Rect = Rect::from_ltrb(100.0, 100.0, 300.0, 600.0);
811    const OUTSIDE_TOP_LEFT: Offset = Offset::new(50.0, 50.0);
812    const OUTSIDE_LEFT: Offset = Offset::new(50.0, 200.0);
813    const OUTSIDE_BOTTOM_LEFT: Offset = Offset::new(50.0, 700.0);
814    const OUTSIDE_TOP: Offset = Offset::new(200.0, 50.0);
815    const OUTSIDE_TOP_RIGHT: Offset = Offset::new(350.0, 50.0);
816    const OUTSIDE_RIGHT: Offset = Offset::new(350.0, 200.0);
817    const OUTSIDE_BOTTOM_RIGHT: Offset = Offset::new(350.0, 700.0);
818    const OUTSIDE_BOTTOM: Offset = Offset::new(200.0, 700.0);
819    const CENTER: Offset = Offset::new(150.0, 300.0);
820
821    // selection_test.dart 'selectionBasedOnRect works'.
822    #[test]
823    fn selection_based_on_rect_works() {
824        assert_eq!(
825            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_LEFT),
826            SelectionResult::Previous
827        );
828        assert_eq!(
829            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_LEFT),
830            SelectionResult::Previous
831        );
832        assert_eq!(
833            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_LEFT),
834            SelectionResult::Next
835        );
836        assert_eq!(
837            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP),
838            SelectionResult::Previous
839        );
840        assert_eq!(
841            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_RIGHT),
842            SelectionResult::Previous
843        );
844        assert_eq!(
845            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_RIGHT),
846            SelectionResult::Next
847        );
848        assert_eq!(
849            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_RIGHT),
850            SelectionResult::Next
851        );
852        assert_eq!(
853            SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM),
854            SelectionResult::Next
855        );
856        assert_eq!(
857            SelectionUtils::get_result_based_on_rect(RECT, CENTER),
858            SelectionResult::End
859        );
860    }
861
862    // selection_test.dart 'adjustDragOffset works'.
863    #[test]
864    fn adjust_drag_offset_works() {
865        let top_left = Offset::new(RECT.left, RECT.top);
866        let top_right = Offset::new(RECT.right, RECT.top);
867        let bottom_left = Offset::new(RECT.left, RECT.bottom);
868        let bottom_right = Offset::new(RECT.right, RECT.bottom);
869
870        // ltr
871        for (point, expected) in [
872            (OUTSIDE_TOP_LEFT, top_left),
873            (OUTSIDE_LEFT, top_left),
874            (OUTSIDE_BOTTOM_LEFT, bottom_right),
875            (OUTSIDE_TOP, top_left),
876            (OUTSIDE_TOP_RIGHT, top_left),
877            (OUTSIDE_RIGHT, bottom_right),
878            (OUTSIDE_BOTTOM_RIGHT, bottom_right),
879            (OUTSIDE_BOTTOM, bottom_right),
880            (CENTER, CENTER),
881        ] {
882            assert_eq!(
883                SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Ltr),
884                expected
885            );
886        }
887        // rtl
888        for (point, expected) in [
889            (OUTSIDE_TOP_LEFT, top_right),
890            (OUTSIDE_LEFT, top_right),
891            (OUTSIDE_BOTTOM_LEFT, bottom_left),
892            (OUTSIDE_TOP, top_right),
893            (OUTSIDE_TOP_RIGHT, top_right),
894            (OUTSIDE_RIGHT, bottom_left),
895            (OUTSIDE_BOTTOM_RIGHT, bottom_left),
896            (OUTSIDE_BOTTOM, bottom_left),
897            (CENTER, CENTER),
898        ] {
899            assert_eq!(
900                SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Rtl),
901                expected
902            );
903        }
904    }
905}