Skip to main content

waft_widgets/widgets/
selection_container.rs

1//! Flutter counterpart: `widgets/selection_container.dart`.
2//!
3//! A container that handles [`SelectionEvent`]s for the selectables in a subtree. It hosts its
4//! delegate through [`SelectionRegistrarScope`], and registers itself with the registrar above it
5//! as one selectable.
6
7use waft_embedder::{Matrix4, Rect, Size};
8use waft_foundation::{App, Handle, HandleId, ListenableObject, Listener, Ref};
9use waft_rendering::{
10    AnyRenderObject, AnySelectable, AnySelectionRegistrar, LayerLink, Selectable, SelectedContent,
11    SelectedContentRange, SelectionEvent, SelectionGeometry, SelectionHandler, SelectionRegistrant,
12    SelectionRegistrantData, SelectionRegistrar, SelectionRegistrarRef, SelectionResult,
13    SelectionStatus,
14};
15
16use crate::framework::IntoWidget;
17use crate::framework::{
18    BuildContext, InheritedWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
19};
20
21/// A container that handles selection events for the selectables in its subtree.
22///
23/// Its state is a single selectable, and registers itself with the [`registrar`](Self::registrar)
24/// when one is given and with the registrar from the context otherwise. The selectables below it
25/// are collected by [`delegate`](Self::delegate), which the state hosts as the subtree's
26/// [`SelectionRegistrar`].
27pub struct SelectionContainer {
28    pub key: Option<KeyRef>,
29
30    /// The registrar this container is registered to; the context's when `None`.
31    pub registrar: Option<SelectionRegistrarRef>,
32
33    /// The delegate for the events sent to this container; `None` disables selection.
34    pub delegate: Option<SelectionContainerDelegateRef>,
35
36    /// The widget below this widget in the tree.
37    pub child: WidgetRef,
38}
39
40/// A field that keeps a selection container delegate: the widget's.
41pub type SelectionContainerDelegateRef = waft_foundation::Retained<AnySelectionContainerDelegate>;
42
43impl SelectionContainer {
44    /// Creates a selection container for `child` that collects its selectables through
45    /// `delegate`.
46    #[cfg_attr(debug_assertions, track_caller)]
47    pub fn new<K>(delegate: SelectionContainerDelegateRef, child: impl IntoWidget<K>) -> Self {
48        SelectionContainer {
49            key: None,
50            registrar: None,
51            delegate: Some(delegate),
52            child: child.into_widget(),
53        }
54    }
55
56    /// Creates a selection container that disables selection for its subtree.
57    #[cfg_attr(debug_assertions, track_caller)]
58    pub fn disabled<K>(child: impl IntoWidget<K>) -> Self {
59        SelectionContainer {
60            key: None,
61            registrar: None,
62            delegate: None,
63            child: child.into_widget(),
64        }
65    }
66
67    /// Dart `SelectionContainer(key:)`.
68    pub fn key(mut self, key: KeyRef) -> Self {
69        self.key = Some(key);
70        self
71    }
72
73    /// Dart `SelectionContainer(registrar:)`.
74    pub fn registrar(mut self, registrar: SelectionRegistrarRef) -> Self {
75        self.registrar = Some(registrar);
76        self
77    }
78
79    /// The immediate ancestor [`SelectionRegistrar`] of `context`, `None` when there is no
80    /// selection container above it or the immediate one is disabled.
81    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<SelectionRegistrarRef> {
82        context
83            .depend_on_inherited_widget_of_exact_type::<SelectionRegistrarScope>(app)
84            .and_then(|scope| scope.registrar.clone())
85    }
86
87    fn is_disabled(&self) -> bool {
88        self.delegate.is_none()
89    }
90
91    fn delegate_handle(&self) -> Option<AnySelectionContainerDelegate> {
92        self.delegate
93            .as_ref()
94            .map(SelectionContainerDelegateRef::handle)
95    }
96}
97
98impl std::fmt::Debug for SelectionContainer {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.debug_struct("SelectionContainer")
101            .field("delegate", &self.delegate)
102            .finish_non_exhaustive()
103    }
104}
105
106impl StatefulWidget for SelectionContainer {
107    type State = SelectionContainerState;
108
109    fn key(&self) -> Option<&KeyRef> {
110        self.key.as_ref()
111    }
112
113    fn create_state(&self) -> SelectionContainerState {
114        SelectionContainerState {
115            state: StateData::new(),
116            selection_registrant: SelectionRegistrantData::new(),
117            listeners: Vec::new(),
118        }
119    }
120}
121
122/// The state of a [`SelectionContainer`]: Dart's `_SelectionContainerState`.
123///
124/// It is a [`Selectable`] whose listeners are the delegate's: adding one adds it to the delegate
125/// and remembers it, so a new delegate receives them all.
126pub struct SelectionContainerState {
127    state: StateData<SelectionContainer>,
128    selection_registrant: SelectionRegistrantData,
129    listeners: Vec<Listener>,
130}
131
132const DISABLED_GEOMETRY: SelectionGeometry = SelectionGeometry {
133    start_selection_point: None,
134    end_selection_point: None,
135    status: SelectionStatus::None,
136    selection_rects: Vec::new(),
137    has_content: true,
138};
139
140impl SelectionContainerState {
141    /// The enabled widget's delegate; Dart's `widget.delegate!`.
142    fn delegate(self: Handle<Self>, app: &App) -> AnySelectionContainerDelegate {
143        self.widget(app)
144            .delegate_handle()
145            .expect("an enabled selection container has a delegate")
146    }
147}
148
149impl State for SelectionContainerState {
150    type Widget = SelectionContainer;
151    crate::state_accessors!();
152
153    fn init_state(self: Handle<Self>, app: &mut App) {
154        let widget = self.widget(app);
155        if !widget.is_disabled() {
156            let registrar = widget.registrar.clone();
157            self.delegate(app)
158                .set_selection_container_context(app, Some(self.context(app)));
159            if let Some(registrar) = registrar {
160                self.set_registrar(app, Some(registrar));
161            }
162        }
163    }
164
165    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectionContainer) {
166        let widget = self.widget(app);
167        let new_delegate = widget.delegate_handle();
168        let disabled = widget.is_disabled();
169        let registrar = widget.registrar.clone();
170        let old_delegate = old_widget.delegate_handle();
171        if old_delegate != new_delegate {
172            let listeners = app.get(self).listeners.clone();
173            if let Some(old_delegate) = old_delegate {
174                old_delegate.set_selection_container_context(app, None);
175                for listener in &listeners {
176                    old_delegate.remove_listener(app, listener);
177                }
178            }
179            if let Some(new_delegate) = new_delegate {
180                new_delegate.set_selection_container_context(app, Some(self.context(app)));
181                for listener in &listeners {
182                    new_delegate.add_listener(app, listener.clone());
183                }
184            }
185            let old_value = old_delegate.map(|delegate| delegate.value(app));
186            let new_value = new_delegate.map(|delegate| delegate.value(app));
187            if old_value != new_value {
188                for listener in &listeners {
189                    listener.call(app);
190                }
191            }
192        }
193        if disabled {
194            self.set_registrar(app, None);
195        } else if let Some(registrar) = registrar {
196            self.set_registrar(app, Some(registrar));
197        }
198        debug_assert!(!disabled || self.registrar(app).is_none());
199    }
200
201    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
202        let widget = self.widget(app);
203        let disabled = widget.is_disabled();
204        if widget.registrar.is_none() && !disabled {
205            let registrar = SelectionContainer::maybe_of(app, self.context(app));
206            self.set_registrar(app, registrar);
207        }
208        debug_assert!(!disabled || self.registrar(app).is_none());
209    }
210
211    fn dispose(self: Handle<Self>, app: &mut App) {
212        if !self.widget(app).is_disabled() {
213            let delegate = self.delegate(app);
214            delegate.set_selection_container_context(app, None);
215            for listener in app.get(self).listeners.clone() {
216                delegate.remove_listener(app, &listener);
217            }
218        }
219        self.dispose_selection_registrant(app);
220    }
221
222    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
223        let widget = self.widget(app);
224        match &widget.delegate {
225            None => SelectionRegistrarScope::disabled(widget.child.clone()).into_widget(),
226            Some(delegate) => {
227                SelectionRegistrarScope::new(delegate.erase(), widget.child.clone()).into_widget()
228            }
229        }
230    }
231}
232
233impl ListenableObject for SelectionContainerState {
234    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
235        debug_assert!(!self.widget(app).is_disabled());
236        self.delegate(app).add_listener(app, listener.clone());
237        let listeners = &mut app.get_mut(self).listeners;
238        if !listeners.contains(&listener) {
239            listeners.push(listener);
240        }
241    }
242
243    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
244        if let Some(delegate) = self.widget(app).delegate_handle() {
245            delegate.remove_listener(app, listener);
246        }
247        app.get_mut(self)
248            .listeners
249            .retain(|registered| registered != listener);
250    }
251}
252
253impl SelectionHandler for SelectionContainerState {
254    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
255        if self.widget(app).is_disabled() {
256            return DISABLED_GEOMETRY;
257        }
258        self.delegate(app).value(app)
259    }
260
261    fn push_handle_layers(
262        self: Handle<Self>,
263        app: &mut App,
264        start_handle: Option<Ref<LayerLink>>,
265        end_handle: Option<Ref<LayerLink>>,
266    ) {
267        self.delegate(app)
268            .push_handle_layers(app, start_handle, end_handle);
269    }
270
271    fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
272        self.delegate(app).selected_content(app)
273    }
274
275    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
276        self.delegate(app).selection(app)
277    }
278
279    fn dispatch_selection_event(
280        self: Handle<Self>,
281        app: &mut App,
282        event: &SelectionEvent,
283    ) -> SelectionResult {
284        self.delegate(app).dispatch_selection_event(app, event)
285    }
286
287    fn content_length(self: Handle<Self>, app: &App) -> usize {
288        self.delegate(app).content_length(app)
289    }
290}
291
292impl Selectable for SelectionContainerState {
293    fn get_transform_to(
294        self: Handle<Self>,
295        app: &App,
296        ancestor: Option<AnyRenderObject>,
297    ) -> Matrix4 {
298        debug_assert!(!self.widget(app).is_disabled());
299        container_render_object(app, self.context(app)).get_transform_to(app, ancestor)
300    }
301
302    fn size(self: Handle<Self>, app: &mut App) -> Size {
303        container_render_box(app, self.context(app)).size(app)
304    }
305
306    fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
307        vec![
308            container_render_box(app, self.context(app))
309                .as_object()
310                .paint_bounds(app),
311        ]
312    }
313
314    fn dispose_selectable(self: Handle<Self>, app: &mut App) {
315        self.dispose_selection_registrant(app);
316    }
317}
318
319impl SelectionRegistrant for SelectionContainerState {
320    fn selection_registrant_data(self: Handle<Self>, app: &App) -> &SelectionRegistrantData {
321        &app.get(self).selection_registrant
322    }
323
324    fn selection_registrant_data_mut(
325        self: Handle<Self>,
326        app: &mut App,
327    ) -> &mut SelectionRegistrantData {
328        &mut app.get_mut(self).selection_registrant
329    }
330}
331
332/// `context.findRenderObject()!`.
333fn container_render_object(app: &App, context: BuildContext) -> AnyRenderObject {
334    context
335        .find_render_object(app)
336        .expect("a selection container's context has a render object once it is built")
337}
338
339/// `context.findRenderObject()! as RenderBox`.
340fn container_render_box(app: &App, context: BuildContext) -> waft_rendering::AnyRenderBox {
341    container_render_object(app, context)
342        .as_box()
343        .expect("a selection container's render object is a box")
344}
345
346/// An inherited widget that hosts a [`SelectionRegistrar`] for its subtree.
347pub struct SelectionRegistrarScope {
348    pub key: Option<KeyRef>,
349
350    /// The registrar hosted by this scope; `None` disables selection for the subtree.
351    pub registrar: Option<SelectionRegistrarRef>,
352
353    pub child: WidgetRef,
354}
355
356impl SelectionRegistrarScope {
357    /// Creates a scope that hosts `registrar`.
358    #[cfg_attr(debug_assertions, track_caller)]
359    pub fn new<K>(registrar: SelectionRegistrarRef, child: impl IntoWidget<K>) -> Self {
360        SelectionRegistrarScope {
361            key: None,
362            registrar: Some(registrar),
363            child: child.into_widget(),
364        }
365    }
366
367    fn disabled(child: WidgetRef) -> Self {
368        SelectionRegistrarScope {
369            key: None,
370            registrar: None,
371            child,
372        }
373    }
374
375    /// Dart `SelectionRegistrarScope(key:)`.
376    pub fn key(mut self, key: KeyRef) -> Self {
377        self.key = Some(key);
378        self
379    }
380}
381
382impl std::fmt::Debug for SelectionRegistrarScope {
383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384        f.debug_struct("SelectionRegistrarScope")
385            .field("registrar", &self.registrar)
386            .finish_non_exhaustive()
387    }
388}
389
390impl InheritedWidget for SelectionRegistrarScope {
391    fn key(&self) -> Option<&KeyRef> {
392        self.key.as_ref()
393    }
394
395    fn child(&self) -> &WidgetRef {
396        &self.child
397    }
398
399    fn update_should_notify(&self, old_widget: &SelectionRegistrarScope) -> bool {
400        old_widget.registrar != self.registrar
401    }
402}
403
404/// The fields of Dart's `SelectionContainerDelegate`.
405#[derive(Debug, Default)]
406pub struct SelectionContainerDelegateData {
407    selection_container_context: Option<BuildContext>,
408}
409
410impl SelectionContainerDelegateData {
411    /// Creates delegate fields with no container context.
412    pub fn new() -> Self {
413        Self::default()
414    }
415}
416
417/// A delegate to handle selection events for a [`SelectionContainer`].
418///
419/// The delegate also receives the selectables in the subtree through [`SelectionRegistrar`].
420pub trait SelectionContainerDelegate: SelectionHandler + SelectionRegistrar {
421    /// Erases this delegate for a [`SelectionContainer`], as Dart's implicit upcast.
422    fn as_selection_container_delegate(self: Handle<Self>) -> AnySelectionContainerDelegate {
423        AnySelectionContainerDelegate {
424            id: self.id(),
425            vtable: const { &SelectionContainerDelegateVTable::of::<Self>() },
426        }
427    }
428
429    /// The fields of this class.
430    fn selection_container_delegate_data(
431        self: Handle<Self>,
432        app: &App,
433    ) -> &SelectionContainerDelegateData;
434
435    /// The fields of this class, mutably.
436    fn selection_container_delegate_data_mut(
437        self: Handle<Self>,
438        app: &mut App,
439    ) -> &mut SelectionContainerDelegateData;
440
441    /// Gets the paint transform from the [`Selectable`] child to the [`SelectionContainer`] of
442    /// this delegate; the container must have been laid out.
443    fn get_transform_from(self: Handle<Self>, app: &App, child: AnySelectable) -> Matrix4 {
444        let container = container_render_object(app, self.selection_container_context(app));
445        child.get_transform_to(app, Some(container))
446    }
447
448    /// Gets the paint transform from the [`SelectionContainer`] of this delegate to `ancestor`;
449    /// the container must have been laid out.
450    fn get_transform_to(
451        self: Handle<Self>,
452        app: &App,
453        ancestor: Option<AnyRenderObject>,
454    ) -> Matrix4 {
455        container_render_object(app, self.selection_container_context(app))
456            .get_transform_to(app, ancestor)
457    }
458
459    /// Whether the [`SelectionContainer`] has undergone layout and has a size.
460    fn has_size(self: Handle<Self>, app: &App) -> bool {
461        container_render_box(app, self.selection_container_context(app)).has_size(app)
462    }
463
464    /// Gets the size of the [`SelectionContainer`] of this delegate; it must have been laid out.
465    fn container_size(self: Handle<Self>, app: &App) -> Size {
466        debug_assert!(
467            self.has_size(app),
468            "containerSize cannot be called before SelectionContainer is laid out."
469        );
470        container_render_box(app, self.selection_container_context(app)).size(app)
471    }
472
473    /// Dart's `_selectionContainerContext!`: the context of the container this delegate serves.
474    fn selection_container_context(self: Handle<Self>, app: &App) -> BuildContext {
475        self.selection_container_delegate_data(app)
476            .selection_container_context
477            .expect("the delegate's SelectionContainer has been built")
478    }
479}
480
481fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
482    Handle::from_id(id)
483}
484
485/// Erased [`SelectionContainerDelegate`], the type a [`SelectionContainer`] holds.
486#[derive(Clone, Copy)]
487pub struct AnySelectionContainerDelegate {
488    id: HandleId,
489    vtable: &'static SelectionContainerDelegateVTable,
490}
491
492struct SelectionContainerDelegateVTable {
493    value: fn(&App, HandleId) -> SelectionGeometry,
494    push_handle_layers: waft_rendering::PushHandleLayers,
495    selected_content: fn(&App, HandleId) -> Option<SelectedContent>,
496    selection: fn(&App, HandleId) -> Option<SelectedContentRange>,
497    dispatch_selection_event: fn(&mut App, HandleId, &SelectionEvent) -> SelectionResult,
498    content_length: fn(&App, HandleId) -> usize,
499    add: fn(&mut App, HandleId, AnySelectable),
500    remove: fn(&mut App, HandleId, AnySelectable),
501    add_listener: fn(&mut App, HandleId, Listener),
502    remove_listener: fn(&mut App, HandleId, &Listener),
503    set_selection_container_context: fn(&mut App, HandleId, Option<BuildContext>),
504    get_transform_from: fn(&App, HandleId, AnySelectable) -> Matrix4,
505    get_transform_to: fn(&App, HandleId, Option<AnyRenderObject>) -> Matrix4,
506    has_size: fn(&App, HandleId) -> bool,
507    container_size: fn(&App, HandleId) -> Size,
508    as_selection_registrar: fn(HandleId) -> AnySelectionRegistrar,
509}
510
511impl SelectionContainerDelegateVTable {
512    const fn of<A: SelectionContainerDelegate>() -> SelectionContainerDelegateVTable {
513        SelectionContainerDelegateVTable {
514            value: |app, id| A::value(resolve(id), app),
515            push_handle_layers: |app, id, start, end| {
516                A::push_handle_layers(resolve(id), app, start, end)
517            },
518            selected_content: |app, id| A::selected_content(resolve(id), app),
519            selection: |app, id| A::selection(resolve(id), app),
520            dispatch_selection_event: |app, id, event| {
521                A::dispatch_selection_event(resolve(id), app, event)
522            },
523            content_length: |app, id| A::content_length(resolve(id), app),
524            add: |app, id, selectable| A::add(resolve(id), app, selectable),
525            remove: |app, id, selectable| A::remove(resolve(id), app, selectable),
526            add_listener: |app, id, listener| {
527                ListenableObject::add_listener(resolve::<A>(id), app, listener)
528            },
529            remove_listener: |app, id, listener| {
530                ListenableObject::remove_listener(resolve::<A>(id), app, listener)
531            },
532            set_selection_container_context: |app, id, context| {
533                A::selection_container_delegate_data_mut(resolve(id), app)
534                    .selection_container_context = context;
535            },
536            get_transform_from: |app, id, child| A::get_transform_from(resolve(id), app, child),
537            get_transform_to: |app, id, ancestor| A::get_transform_to(resolve(id), app, ancestor),
538            has_size: |app, id| A::has_size(resolve(id), app),
539            container_size: |app, id| A::container_size(resolve(id), app),
540            as_selection_registrar: |id| {
541                SelectionRegistrar::as_selection_registrar(resolve::<A>(id))
542            },
543        }
544    }
545}
546
547impl AnySelectionContainerDelegate {
548    /// The arena id behind this handle.
549    pub fn id(self) -> HandleId {
550        self.id
551    }
552
553    pub fn value(self, app: &App) -> SelectionGeometry {
554        (self.vtable.value)(app, self.id)
555    }
556
557    pub fn push_handle_layers(
558        self,
559        app: &mut App,
560        start_handle: Option<Ref<LayerLink>>,
561        end_handle: Option<Ref<LayerLink>>,
562    ) {
563        (self.vtable.push_handle_layers)(app, self.id, start_handle, end_handle)
564    }
565
566    pub fn selected_content(self, app: &App) -> Option<SelectedContent> {
567        (self.vtable.selected_content)(app, self.id)
568    }
569
570    pub fn selection(self, app: &App) -> Option<SelectedContentRange> {
571        (self.vtable.selection)(app, self.id)
572    }
573
574    pub fn dispatch_selection_event(
575        self,
576        app: &mut App,
577        event: &SelectionEvent,
578    ) -> SelectionResult {
579        (self.vtable.dispatch_selection_event)(app, self.id, event)
580    }
581
582    pub fn content_length(self, app: &App) -> usize {
583        (self.vtable.content_length)(app, self.id)
584    }
585
586    pub fn add(self, app: &mut App, selectable: AnySelectable) {
587        (self.vtable.add)(app, self.id, selectable)
588    }
589
590    pub fn remove(self, app: &mut App, selectable: AnySelectable) {
591        (self.vtable.remove)(app, self.id, selectable)
592    }
593
594    pub fn add_listener(self, app: &mut App, listener: Listener) {
595        (self.vtable.add_listener)(app, self.id, listener)
596    }
597
598    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
599        (self.vtable.remove_listener)(app, self.id, listener)
600    }
601
602    pub fn set_selection_container_context(self, app: &mut App, context: Option<BuildContext>) {
603        (self.vtable.set_selection_container_context)(app, self.id, context)
604    }
605
606    pub fn get_transform_from(self, app: &App, child: AnySelectable) -> Matrix4 {
607        (self.vtable.get_transform_from)(app, self.id, child)
608    }
609
610    pub fn get_transform_to(self, app: &App, ancestor: Option<AnyRenderObject>) -> Matrix4 {
611        (self.vtable.get_transform_to)(app, self.id, ancestor)
612    }
613
614    pub fn has_size(self, app: &App) -> bool {
615        (self.vtable.has_size)(app, self.id)
616    }
617
618    pub fn container_size(self, app: &App) -> Size {
619        (self.vtable.container_size)(app, self.id)
620    }
621
622    pub fn as_selection_registrar(self) -> AnySelectionRegistrar {
623        (self.vtable.as_selection_registrar)(self.id)
624    }
625}
626
627impl std::fmt::Debug for AnySelectionContainerDelegate {
628    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629        f.debug_struct("AnySelectionContainerDelegate")
630            .field("id", &self.id)
631            .finish()
632    }
633}
634
635waft_foundation::erased_handle!(
636    AnySelectionContainerDelegate: SelectionContainerDelegate => SelectionContainerDelegate::as_selection_container_delegate
637);
638
639/// The delegate as the registrar its container hosts: Dart's implicit upcast of
640/// `SelectionContainerDelegate implements SelectionRegistrar`.
641impl From<AnySelectionContainerDelegate> for AnySelectionRegistrar {
642    fn from(delegate: AnySelectionContainerDelegate) -> AnySelectionRegistrar {
643        delegate.as_selection_registrar()
644    }
645}