Skip to main content

waft_widgets/widgets/
actions.rs

1//! Flutter counterpart: `widgets/actions.dart`.
2//!
3//! The action system: [`Intent`] describes what should happen, [`Action`] performs it, the
4//! [`Actions`] widget maps one to the other for its descendants, and [`ActionDispatcher`]
5//! invokes the action that was found. [`FocusableActionDetector`] combines [`Actions`],
6//! `Shortcuts`, `Focus` and `MouseRegion` into the detector a control is built from.
7
8use std::any::{Any, TypeId};
9use std::collections::{HashMap, HashSet};
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12
13use waft_foundation::{
14    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, HandleId, Listener,
15    OptionRetained, Ref, Retained, ValueChanged, describe_identity,
16};
17use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
18use waft_services::{MouseCursor, MouseCursorRef};
19
20use crate::framework::{
21    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
22    WidgetRef,
23};
24use crate::view::View;
25use crate::widgets::basic::MouseRegion;
26use crate::widgets::focus_manager::{
27    FocusHighlightMode, FocusManager, FocusNodeRef, HighlightModeListener, KeyEventResult,
28    primary_focus,
29};
30use crate::widgets::focus_scope::Focus;
31use crate::widgets::media_query::{MediaQuery, NavigationMode};
32use crate::widgets::shortcuts::{ShortcutMap, Shortcuts};
33
34/// Returns the parent [`BuildContext`] of a given `context`.
35///
36/// [`BuildContext`] doesn't have a `parent` accessor, but the parent can be obtained using
37/// [`BuildContext::visit_ancestor_elements`](crate::AnyElement::visit_ancestor_elements).
38///
39/// [`BuildContext::get_element_for_inherited_widget_of_exact_type`](crate::AnyElement::get_element_for_inherited_widget_of_exact_type)
40/// returns the same [`BuildContext`] if it happens to be of the correct type. To obtain the
41/// previous inherited widget, the search must therefore start from the parent; this is what
42/// `get_parent` is used for.
43///
44/// `get_parent` is O(1), because it always stops at the first ancestor.
45fn get_parent(app: &App, context: BuildContext) -> Option<BuildContext> {
46    let mut parent = None;
47    context.visit_ancestor_elements(app, &mut |ancestor| {
48        parent = Some(ancestor);
49        false
50    });
51    parent
52}
53
54// ---------------------------------------------------------------------------------------------
55// Intent
56
57/// A particular configuration of an [`Action`].
58///
59/// This trait is what the `Shortcuts::shortcuts` map has as values, and is used by an
60/// [`ActionDispatcher`] to look up an action and invoke it, giving it this object to extract
61/// configuration information from.
62///
63/// See also:
64///
65///  * `Shortcuts`, a widget used to bind key combinations to [`Intent`]s.
66///  * [`Actions`], a widget used to map [`Intent`]s to [`Action`]s.
67///  * [`Actions::invoke`], which invokes the action associated with a specified [`Intent`]
68///    using the [`Actions`] widget that most tightly encloses the given [`BuildContext`].
69pub trait Intent: Debug + 'static {
70    /// The value behind the erased intent, for the downcast an [`Action`] does to recover its
71    /// own intent type.
72    fn as_any(&self) -> &dyn Any;
73
74    /// Dart's `intent.runtimeType`: the key an [`Actions`] map is looked up with.
75    fn intent_type(&self) -> TypeId {
76        self.as_any().type_id()
77    }
78
79    /// Dart's `Intent.debugFillProperties`, from `Diagnosticable`: an intent adds its own
80    /// fields.
81    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
82        let _ = properties;
83    }
84
85    /// Dart's `Intent.toStringShort`: the type and the identity.
86    fn to_string_short(&self) -> String {
87        describe_identity(
88            waft_foundation::bare_type_name(std::any::type_name::<Self>()),
89            self as *const Self as *const () as usize as u64,
90        )
91    }
92
93    /// Dart's `Intent.toDiagnosticsNode(name:)`, from `Diagnosticable`.
94    fn diagnostics_node(&self, name: Option<String>) -> waft_foundation::DiagnosticableNode {
95        let mut builder = DiagnosticPropertiesBuilder::new();
96        self.debug_fill_properties(&mut builder);
97        waft_foundation::DiagnosticableNode::from_parts(name, self.to_string_short(), builder)
98    }
99
100    /// Dart's `Diagnosticable.toString`, which a property holding an intent prints.
101    fn diagnostic_string(&self) -> String {
102        use waft_foundation::{DiagnosticLevel, DiagnosticsNode, DiagnosticsTreeStyle};
103        self.diagnostics_node(None)
104            .with_style(DiagnosticsTreeStyle::SingleLine)
105            .to_string_with(None, DiagnosticLevel::Info)
106    }
107}
108
109/// The erased [`Intent`] value: what a field or parameter Dart types as `Intent` becomes.
110pub type IntentRef = Rc<dyn Intent>;
111
112/// An intent that is mapped to a [`DoNothingAction`], which, as the name implies, does
113/// nothing.
114///
115/// This intent is mapped to an action in the `WidgetsApp` that does nothing, so that it can be
116/// bound to a key in a `Shortcuts` widget in order to disable a key binding made above it in
117/// the hierarchy.
118///
119/// Dart's `Intent.doNothing`.
120pub const DO_NOTHING: DoNothingIntent = DoNothingIntent::new();
121
122/// The type argument of an [`Action`]: Dart's `T extends Intent` in `Action<T>`.
123///
124/// Every [`Intent`] implements it, and so does `dyn Intent`, which is Dart's `Action<Intent>` —
125/// an action that handles every intent.
126pub trait ActionIntent: 'static {
127    /// Dart's `intent is T`.
128    fn cast_intent(intent: &dyn Intent) -> Option<&Self>;
129
130    /// This value back as the erased [`Intent`], for the lookups keyed by intent type.
131    fn as_intent(&self) -> &dyn Intent;
132}
133
134impl<T: Intent> ActionIntent for T {
135    fn cast_intent(intent: &dyn Intent) -> Option<&T> {
136        intent.as_any().downcast_ref::<T>()
137    }
138
139    fn as_intent(&self) -> &dyn Intent {
140        self
141    }
142}
143
144impl ActionIntent for dyn Intent {
145    fn cast_intent(intent: &dyn Intent) -> Option<&dyn Intent> {
146        Some(intent)
147    }
148
149    fn as_intent(&self) -> &dyn Intent {
150        self
151    }
152}
153
154// ---------------------------------------------------------------------------------------------
155// Action
156
157/// The kind of callback that an [`Action`] uses to notify of changes to the action's state.
158///
159/// To register an action listener, call [`Action::add_action_listener`].
160pub type ActionListenerCallback = Rc<dyn Fn(&mut App, AnyAction)>;
161
162/// The fields Dart's `Action` declares; every action carries this bag under the field
163/// `action`.
164pub struct ActionData {
165    listeners: Vec<ActionListenerCallback>,
166    current_calling_action: Option<ActionRef>,
167}
168
169impl ActionData {
170    /// The bag of a freshly created action.
171    pub fn new() -> ActionData {
172        ActionData {
173            listeners: Vec::new(),
174            current_calling_action: None,
175        }
176    }
177}
178
179impl Default for ActionData {
180    fn default() -> ActionData {
181        ActionData::new()
182    }
183}
184
185/// The accessors [`Action`] asks for, for a struct whose bag is the field `action`.
186#[macro_export]
187macro_rules! action_accessors {
188    () => {
189        fn action_data(
190            self: ::waft_foundation::Handle<Self>,
191            app: &::waft_foundation::App,
192        ) -> &$crate::ActionData {
193            &app.get(self).action
194        }
195
196        fn action_data_mut(
197            self: ::waft_foundation::Handle<Self>,
198            app: &mut ::waft_foundation::App,
199        ) -> &mut $crate::ActionData {
200            &mut app.get_mut(self).action
201        }
202    };
203}
204
205/// The overrides a [`ContextAction`] leaf adds to its `impl Action`: the type-erased handle
206/// that carries the context through, the two context-less entry points Dart gets from an optional
207/// parameter, and the overridable form.
208#[macro_export]
209macro_rules! context_action_overrides {
210    () => {
211        fn as_action(self: ::waft_foundation::Handle<Self>) -> $crate::AnyAction {
212            $crate::AnyAction::of_context::<Self>(self)
213        }
214
215        fn is_enabled(
216            self: ::waft_foundation::Handle<Self>,
217            app: &mut ::waft_foundation::App,
218            intent: &Self::Intent,
219        ) -> bool {
220            $crate::ContextAction::is_enabled(self, app, intent, None)
221        }
222
223        fn invoke(
224            self: ::waft_foundation::Handle<Self>,
225            app: &mut ::waft_foundation::App,
226            intent: &Self::Intent,
227        ) -> Option<::std::rc::Rc<dyn ::std::any::Any>> {
228            $crate::ContextAction::invoke(self, app, intent, None)
229        }
230
231        fn make_overridable_action(
232            self: ::waft_foundation::Handle<Self>,
233            app: &mut ::waft_foundation::App,
234            context: $crate::BuildContext,
235        ) -> $crate::ActionRef {
236            let default_action: $crate::ActionRef = self.keep(app).into_erased();
237            $crate::OverridableContextAction::<Self::Intent>::new(app, default_action, context)
238                .into_erased()
239        }
240    };
241}
242
243/// Base trait for an action or command to be performed.
244///
245/// [`Action`]s are typically invoked as a result of a user action. For example, the `Shortcuts`
246/// widget will map a keyboard shortcut into an [`Intent`], which is given to an
247/// [`ActionDispatcher`] to map the [`Intent`] to an [`Action`] and invoke it.
248///
249/// The [`ActionDispatcher`] can invoke an [`Action`] on the primary focus, or without regard
250/// for focus.
251///
252/// ### Action Overriding
253///
254/// When using a leaf widget to build a more specialized widget, it's sometimes desirable to
255/// change the default handling of an [`Intent`] defined in the leaf widget. For instance, a
256/// text field's select-all intent by default selects the text it currently contains, but in a
257/// US phone number widget that consists of 3 different text fields (area code, prefix and line
258/// number), it should instead select the text within all 3 text fields.
259///
260/// An overridable [`Action`] is a special kind of [`Action`] created using
261/// [`AnyAction::overridable`]. It has access to a default [`Action`], and an optional override
262/// [`Action`]. It has the same behavior as its override if that exists, and mirrors the
263/// behavior of its `default_action` otherwise.
264///
265/// See also:
266///
267///  * `Shortcuts`, which is a widget that contains a key map, in which it looks up key
268///    combinations in order to invoke actions.
269///  * [`Actions`], which is a widget that defines a map of [`Intent`] to [`Action`] and allows
270///    redefining of actions for its descendants.
271///  * [`ActionDispatcher`], a class that takes an [`Action`] and invokes it, passing a given
272///    [`Intent`].
273pub trait Action: Sized + 'static {
274    /// Dart's type argument `T extends Intent`.
275    ///
276    /// `dyn Intent` is Dart's `Action<Intent>`: an action that handles every intent.
277    type Intent: ActionIntent + ?Sized;
278
279    /// Dart's `Action` fields, held under the field `action`
280    /// ([`action_accessors!`](crate::action_accessors)).
281    fn action_data(self: Handle<Self>, app: &App) -> &ActionData;
282
283    /// See [`action_data`](Self::action_data).
284    fn action_data_mut(self: Handle<Self>, app: &mut App) -> &mut ActionData;
285
286    /// Dart's `Action.debugFillProperties`, from `Diagnosticable`: an action adds its own
287    /// fields.
288    fn debug_fill_properties(
289        self: Handle<Self>,
290        app: &App,
291        properties: &mut DiagnosticPropertiesBuilder,
292    ) {
293        let _ = (self, app, properties);
294    }
295
296    /// This action as the erased [`AnyAction`] — what to pass where a Dart API takes an
297    /// `Action<Intent>`.
298    ///
299    /// A [`ContextAction`] overrides this with
300    /// [`context_action_overrides!`](crate::context_action_overrides), so that the type-erased
301    /// handle carries the invoking context through.
302    fn as_action(self: Handle<Self>) -> AnyAction {
303        AnyAction::of::<Self>(self)
304    }
305
306    /// Gets the type of intent this action responds to.
307    fn intent_type() -> TypeId {
308        TypeId::of::<Self::Intent>()
309    }
310
311    /// The [`Action`] overridden by this [`Action`].
312    ///
313    /// [`AnyAction::overridable`] creates an overridable [`Action`] that allows itself to be
314    /// overridden by the closest ancestor [`Action`], and falls back to its own
315    /// `default_action` when no overrides can be found. When an override is present, an
316    /// overridable [`Action`] forwards all incoming method calls to the override, and allows
317    /// the override to access the `default_action` via its
318    /// [`calling_action`](Self::calling_action) property.
319    ///
320    /// Before forwarding the call to the override, the overridable [`Action`] is responsible
321    /// for setting [`calling_action`](Self::calling_action) to its `default_action`, which is
322    /// already taken care of by the overridable [`Action`] created using
323    /// [`AnyAction::overridable`].
324    ///
325    /// This property is only set when this [`Action`] is an override of the calling action,
326    /// and is currently being invoked from it.
327    ///
328    /// Invoking the calling action's methods, or accessing its properties, is allowed and does
329    /// not introduce infinite loops or infinite recursions.
330    fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
331        self.action_data(app).current_calling_action.handle()
332    }
333
334    /// Sets [`calling_action`](Self::calling_action); overridden by the overridable actions so
335    /// that the default action sees it too.
336    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
337        self.action_data_mut(app).current_calling_action = value;
338    }
339
340    /// Returns true if the action is enabled and is ready to be invoked.
341    ///
342    /// This will be called by the [`ActionDispatcher`] before attempting to invoke the action.
343    ///
344    /// If the action's enable state depends on a [`BuildContext`], implement [`ContextAction`]
345    /// instead.
346    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
347        let _ = intent;
348        self.is_action_enabled(app)
349    }
350
351    /// Whether this [`Action`] is inherently enabled.
352    ///
353    /// If [`is_action_enabled`](Self::is_action_enabled) is false, then this [`Action`] is
354    /// disabled for any given [`Intent`].
355    ///
356    /// If the enabled state changes, overriding implementations must call
357    /// [`notify_action_listeners`](Self::notify_action_listeners) to notify any listeners of
358    /// the change.
359    ///
360    /// In the case of an overridable action, accessing this property creates a dependency on
361    /// the overridable action's lookup context.
362    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
363        let _ = app;
364        true
365    }
366
367    /// Indicates whether this action should treat key events mapped to this action as being
368    /// "handled" when it is invoked via the key event.
369    ///
370    /// If the key is handled, then no other key event handlers in the focus chain will receive
371    /// the event.
372    ///
373    /// If the key event is not handled, it will be passed back to the engine, and continue to
374    /// be processed there, allowing text fields and non-Flutter widgets to receive the key
375    /// event.
376    ///
377    /// The default implementation returns true.
378    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
379        let _ = (app, intent);
380        true
381    }
382
383    /// Converts the result of [`invoke`](Self::invoke) of this action to a [`KeyEventResult`].
384    ///
385    /// This is typically used when the action is invoked in response to a keyboard shortcut.
386    ///
387    /// The `invoke_result` argument is the value returned by [`invoke`](Self::invoke).
388    ///
389    /// By default, calls [`consumes_key`](Self::consumes_key) and converts the returned boolean
390    /// to [`KeyEventResult::Handled`] if it's true, and
391    /// [`KeyEventResult::SkipRemainingHandlers`] if it's false.
392    fn to_key_event_result(
393        self: Handle<Self>,
394        app: &mut App,
395        intent: &Self::Intent,
396        invoke_result: Option<&Rc<dyn Any>>,
397    ) -> KeyEventResult {
398        let _ = invoke_result;
399        if self.consumes_key(app, intent) {
400            KeyEventResult::Handled
401        } else {
402            KeyEventResult::SkipRemainingHandlers
403        }
404    }
405
406    /// Called when the action is to be performed.
407    ///
408    /// This is called by the [`ActionDispatcher`] when an action is invoked via
409    /// [`Actions::invoke`], or when an action is invoked using
410    /// [`ActionDispatcher::invoke_action`] directly.
411    ///
412    /// This method is only meant to be invoked by an [`ActionDispatcher`], and only when
413    /// [`is_enabled`](Self::is_enabled) is true.
414    ///
415    /// To receive the result of invoking an action, it must be invoked using
416    /// [`Actions::invoke`], or by invoking it using an [`ActionDispatcher`]. An action invoked
417    /// via a `Shortcuts` widget will have its return value ignored.
418    ///
419    /// If the action's behavior depends on a [`BuildContext`], implement [`ContextAction`]
420    /// instead.
421    fn invoke(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> Option<Rc<dyn Any>>;
422
423    /// Register a callback to listen for changes to the state of this action.
424    ///
425    /// If you call this, you must call
426    /// [`remove_action_listener`](Self::remove_action_listener) a matching number of times, or
427    /// memory leaks will occur. To help manage this and avoid memory leaks, use of the
428    /// [`ActionListener`] widget to register and unregister your listener appropriately is
429    /// highly recommended.
430    fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
431        self.action_data_mut(app).listeners.push(listener);
432    }
433
434    /// Remove a previously registered closure from the list of closures that are notified when
435    /// the object changes.
436    ///
437    /// If the given listener is not registered, the call is ignored.
438    fn remove_action_listener(
439        self: Handle<Self>,
440        app: &mut App,
441        listener: &ActionListenerCallback,
442    ) {
443        let listeners = &mut self.action_data_mut(app).listeners;
444        if let Some(index) = listeners
445            .iter()
446            .position(|registered| Rc::ptr_eq(registered, listener))
447        {
448            listeners.remove(index);
449        }
450    }
451
452    /// Call all the registered listeners.
453    ///
454    /// Implementations should call this method whenever the object changes, to notify any
455    /// clients the object may have changed. Listeners that are added during this iteration
456    /// will not be visited. Listeners that are removed during this iteration will not be
457    /// visited after they are removed.
458    fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
459        if self.action_data(app).listeners.is_empty() {
460            return;
461        }
462        // Make a local copy so that a listener can unregister while the list is being iterated
463        // over.
464        let local_listeners = self.action_data(app).listeners.clone();
465        let this = self.as_action();
466        for listener in local_listeners {
467            let still_registered = self
468                .action_data(app)
469                .listeners
470                .iter()
471                .any(|registered| Rc::ptr_eq(registered, &listener));
472            if still_registered {
473                listener(app, this);
474            }
475        }
476    }
477
478    /// Dart's `Action._makeOverridableAction`: the overridable form of this action, which
479    /// [`AnyAction::overridable`] hands back.
480    fn make_overridable_action(
481        self: Handle<Self>,
482        app: &mut App,
483        context: BuildContext,
484    ) -> ActionRef {
485        let default_action: ActionRef = self.keep(app).into_erased();
486        OverridableAction::<Self::Intent>::new(app, default_action, context).into_erased()
487    }
488}
489
490/// An [`Action`] that adds an optional [`BuildContext`] to the
491/// [`is_enabled`](Self::is_enabled) and [`invoke`](Self::invoke) methods to be able to provide
492/// context to actions.
493///
494/// [`ActionDispatcher::invoke_action`] checks to see if the action it is invoking is a
495/// [`ContextAction`], and if it is, supplies it with a context; the type-erased handle a
496/// [`ContextAction`] hands out ([`context_action_overrides!`](crate::context_action_overrides))
497/// is what answers that check.
498pub trait ContextAction: Action {
499    /// Returns true if the action is enabled and is ready to be invoked.
500    ///
501    /// This will be called by the [`ActionDispatcher`] before attempting to invoke the action.
502    ///
503    /// The optional `context` parameter is the context of the invocation of the action, and in
504    /// the case of an action invoked by a `ShortcutManager`, via a `Shortcuts` widget, will be
505    /// the context of the `Shortcuts` widget.
506    fn is_enabled(
507        self: Handle<Self>,
508        app: &mut App,
509        intent: &Self::Intent,
510        context: Option<BuildContext>,
511    ) -> bool {
512        let _ = (intent, context);
513        Action::is_action_enabled(self, app)
514    }
515
516    /// Called when the action is to be performed.
517    ///
518    /// This is called by the [`ActionDispatcher`] when an action is invoked via
519    /// [`Actions::invoke`], or when an action is invoked using
520    /// [`ActionDispatcher::invoke_action`] directly.
521    ///
522    /// This method is only meant to be invoked by an [`ActionDispatcher`], and only when
523    /// [`is_enabled`](Self::is_enabled) is true.
524    ///
525    /// The optional `context` parameter is the context of the invocation of the action, and in
526    /// the case of an action invoked by a `ShortcutManager`, via a `Shortcuts` widget, will be
527    /// the context of the `Shortcuts` widget.
528    fn invoke(
529        self: Handle<Self>,
530        app: &mut App,
531        intent: &Self::Intent,
532        context: Option<BuildContext>,
533    ) -> Option<Rc<dyn Any>>;
534}
535
536/// The vtable's `Action.toKeyEventResult`, over the erased invoke result.
537type ToKeyEventResultFn =
538    fn(&mut App, HandleId, &dyn Intent, Option<&Rc<dyn Any>>) -> KeyEventResult;
539
540/// The vtable's `Action._invoke`.
541type InvokeFn = fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> Option<Rc<dyn Any>>;
542
543/// The vtable of an erased [`AnyAction`]: one `&'static` table per leaf type, built by
544/// [`ActionVTable::of`] or [`ActionVTable::of_context`].
545struct ActionVTable {
546    type_name: fn() -> &'static str,
547    intent_type: fn() -> TypeId,
548    calling_action: fn(&App, HandleId) -> Option<AnyAction>,
549    update_calling_action: fn(&mut App, HandleId, Option<ActionRef>),
550    is_enabled: fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> bool,
551    is_action_enabled: fn(&mut App, HandleId) -> bool,
552    consumes_key: fn(&mut App, HandleId, &dyn Intent) -> bool,
553    to_key_event_result: ToKeyEventResultFn,
554    invoke: InvokeFn,
555    add_action_listener: fn(&mut App, HandleId, ActionListenerCallback),
556    remove_action_listener: fn(&mut App, HandleId, &ActionListenerCallback),
557    notify_action_listeners: fn(&mut App, HandleId),
558    make_overridable_action: fn(&mut App, HandleId, BuildContext) -> ActionRef,
559    debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
560}
561
562/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
563fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
564    Handle::from_id(id)
565}
566
567/// Dart's `_debugCanHandleIntent`, which has to succeed for the leaf to see its own intent.
568fn cast_intent<L: Action>(intent: &dyn Intent) -> &L::Intent {
569    <L::Intent as ActionIntent>::cast_intent(intent).unwrap_or_else(|| {
570        panic!(
571            "An Intent of type {:?} cannot be handled by {}: the Intent must be of a subtype \
572             of {}.",
573            intent,
574            std::any::type_name::<L>(),
575            std::any::type_name::<L::Intent>()
576        )
577    })
578}
579
580impl ActionVTable {
581    /// The table for a plain [`Action`] leaf: Dart's `_isEnabled` / `_invoke` drop the context
582    /// because the action is not a `ContextAction`.
583    const fn of<L: Action>() -> ActionVTable {
584        ActionVTable {
585            type_name: std::any::type_name::<L>,
586            intent_type: L::intent_type,
587            calling_action: |app, id| L::calling_action(resolve(id), app),
588            update_calling_action: |app, id, value| {
589                L::update_calling_action(resolve(id), app, value)
590            },
591            is_enabled: |app, id, intent, _context| {
592                L::is_enabled(resolve(id), app, cast_intent::<L>(intent))
593            },
594            is_action_enabled: |app, id| L::is_action_enabled(resolve(id), app),
595            consumes_key: |app, id, intent| {
596                L::consumes_key(resolve(id), app, cast_intent::<L>(intent))
597            },
598            to_key_event_result: |app, id, intent, invoke_result| {
599                L::to_key_event_result(resolve(id), app, cast_intent::<L>(intent), invoke_result)
600            },
601            invoke: |app, id, intent, _context| {
602                L::invoke(resolve(id), app, cast_intent::<L>(intent))
603            },
604            add_action_listener: |app, id, listener| {
605                L::add_action_listener(resolve(id), app, listener)
606            },
607            remove_action_listener: |app, id, listener| {
608                L::remove_action_listener(resolve(id), app, listener)
609            },
610            notify_action_listeners: |app, id| L::notify_action_listeners(resolve(id), app),
611            make_overridable_action: |app, id, context| {
612                L::make_overridable_action(resolve(id), app, context)
613            },
614            debug_fill_properties: |app, id, properties| {
615                L::debug_fill_properties(resolve(id), app, properties)
616            },
617        }
618    }
619
620    /// The table for a [`ContextAction`] leaf: Dart's `_isEnabled` / `_invoke` hand the context
621    /// on.
622    const fn of_context<L: ContextAction>() -> ActionVTable {
623        ActionVTable {
624            is_enabled: |app, id, intent, context| {
625                ContextAction::is_enabled(resolve::<L>(id), app, cast_intent::<L>(intent), context)
626            },
627            invoke: |app, id, intent, context| {
628                ContextAction::invoke(resolve::<L>(id), app, cast_intent::<L>(intent), context)
629            },
630            ..ActionVTable::of::<L>()
631        }
632    }
633}
634
635/// Erased `Action<Intent>`: one identity and a static vtable, the fat pointer rustc cannot
636/// build for an arena id.
637///
638/// This is what a field or parameter Dart types as `Action<Intent>` becomes; the leaf stays in
639/// the [`App`] under its own type, and [`downcast`](Self::downcast) gets the typed handle back.
640///
641/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they
642/// address the same action.
643#[derive(Clone, Copy)]
644pub struct AnyAction {
645    id: HandleId,
646    vtable: &'static ActionVTable,
647}
648
649/// A field Dart types as the erased object, kept: AnyAction with its count.
650pub type ActionRef = Retained<AnyAction>;
651
652waft_foundation::erased_handle!(AnyAction: Action => Action::as_action);
653
654impl fmt::Debug for AnyAction {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
657    }
658}
659
660impl AnyAction {
661    /// Dart's `Action.toStringShort`: the type and the identity.
662    pub fn to_string_short(self) -> String {
663        describe_identity(
664            waft_foundation::bare_type_name((self.vtable.type_name)()),
665            self.id.identity_hash(),
666        )
667    }
668
669    /// Dart's `action.debugFillProperties`.
670    pub fn debug_fill_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
671        (self.vtable.debug_fill_properties)(app, self.id, properties);
672    }
673
674    /// The type-erased handle of a plain [`Action`] leaf; [`Action::as_action`] calls this.
675    pub fn of<L: Action>(action: Handle<L>) -> AnyAction {
676        AnyAction {
677            id: action.id(),
678            vtable: const { &ActionVTable::of::<L>() },
679        }
680    }
681
682    /// The type-erased handle of a [`ContextAction`] leaf;
683    /// [`context_action_overrides!`](crate::context_action_overrides) calls this.
684    pub fn of_context<L: ContextAction>(action: Handle<L>) -> AnyAction {
685        AnyAction {
686            id: action.id(),
687            vtable: const { &ActionVTable::of_context::<L>() },
688        }
689    }
690
691    /// Creates an [`Action`] that allows itself to be overridden by the closest ancestor
692    /// [`Action`] in the given `context` that handles the same [`Intent`], if one exists.
693    ///
694    /// When invoked, the resulting [`Action`] tries to find the closest [`Action`] in the given
695    /// `context` that handles the same type of [`Intent`] as the `default_action`, then calls
696    /// its [`invoke`](Self::invoke) method. When no override [`Action`]s can be found, it
697    /// invokes the `default_action`.
698    ///
699    /// An overridable action delegates everything to its override if one exists, and has the
700    /// same behavior as its `default_action` otherwise. For this reason, the override has full
701    /// control over whether and how an [`Intent`] should be handled, or a key event should be
702    /// consumed. An override [`Action`]'s [`Action::calling_action`] property will be set to
703    /// the [`Action`] it currently overrides, giving it access to the default behavior.
704    ///
705    /// The `context` argument is the [`BuildContext`] to find the override with. It is
706    /// typically a [`BuildContext`] above the [`Actions`] widget that contains this overridable
707    /// [`Action`].
708    ///
709    /// The `default_action` argument is the [`Action`] to be invoked where no ancestor
710    /// [`Action`]s can be found in `context` that handle the same type of [`Intent`].
711    ///
712    /// Dart's `Action.overridable`.
713    pub fn overridable(
714        app: &mut App,
715        default_action: ActionRef,
716        context: BuildContext,
717    ) -> ActionRef {
718        default_action.make_overridable_action(app, context)
719    }
720
721    /// The arena id behind this handle.
722    pub fn id(self) -> HandleId {
723        self.id
724    }
725
726    /// Dart's `action as T`: the typed handle when this action is a `T`, else `None`.
727    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
728        app.handle::<T>(self.id)
729    }
730
731    /// See [`Action::intent_type`].
732    pub fn intent_type(self) -> TypeId {
733        (self.vtable.intent_type)()
734    }
735
736    /// See [`Action::calling_action`].
737    pub fn calling_action(self, app: &App) -> Option<AnyAction> {
738        (self.vtable.calling_action)(app, self.id)
739    }
740
741    /// See [`Action::update_calling_action`].
742    pub fn update_calling_action(self, app: &mut App, value: Option<ActionRef>) {
743        (self.vtable.update_calling_action)(app, self.id, value);
744    }
745
746    /// Dart's `Action._isEnabled`: [`ContextAction::is_enabled`] when the action is a
747    /// [`ContextAction`], [`Action::is_enabled`] otherwise.
748    pub fn is_enabled(
749        self,
750        app: &mut App,
751        intent: &dyn Intent,
752        context: Option<BuildContext>,
753    ) -> bool {
754        (self.vtable.is_enabled)(app, self.id, intent, context)
755    }
756
757    /// See [`Action::is_action_enabled`].
758    pub fn is_action_enabled(self, app: &mut App) -> bool {
759        (self.vtable.is_action_enabled)(app, self.id)
760    }
761
762    /// See [`Action::consumes_key`].
763    pub fn consumes_key(self, app: &mut App, intent: &dyn Intent) -> bool {
764        (self.vtable.consumes_key)(app, self.id, intent)
765    }
766
767    /// See [`Action::to_key_event_result`].
768    pub fn to_key_event_result(
769        self,
770        app: &mut App,
771        intent: &dyn Intent,
772        invoke_result: Option<&Rc<dyn Any>>,
773    ) -> KeyEventResult {
774        (self.vtable.to_key_event_result)(app, self.id, intent, invoke_result)
775    }
776
777    /// Dart's `Action._invoke`: [`ContextAction::invoke`] when the action is a
778    /// [`ContextAction`], [`Action::invoke`] otherwise.
779    pub fn invoke(
780        self,
781        app: &mut App,
782        intent: &dyn Intent,
783        context: Option<BuildContext>,
784    ) -> Option<Rc<dyn Any>> {
785        (self.vtable.invoke)(app, self.id, intent, context)
786    }
787
788    /// See [`Action::add_action_listener`].
789    pub fn add_action_listener(self, app: &mut App, listener: ActionListenerCallback) {
790        (self.vtable.add_action_listener)(app, self.id, listener);
791    }
792
793    /// See [`Action::remove_action_listener`].
794    pub fn remove_action_listener(self, app: &mut App, listener: &ActionListenerCallback) {
795        (self.vtable.remove_action_listener)(app, self.id, listener);
796    }
797
798    /// See [`Action::notify_action_listeners`].
799    pub fn notify_action_listeners(self, app: &mut App) {
800        (self.vtable.notify_action_listeners)(app, self.id);
801    }
802
803    /// See [`Action::make_overridable_action`].
804    fn make_overridable_action(self, app: &mut App, context: BuildContext) -> ActionRef {
805        (self.vtable.make_overridable_action)(app, self.id, context)
806    }
807}
808
809// ---------------------------------------------------------------------------------------------
810// ActionListener
811
812/// A helper widget for making sure that listeners on an action are removed properly.
813///
814/// Listeners on an [`Action`] must have their listener callbacks removed with
815/// [`Action::remove_action_listener`] when the listener is disposed of. This widget helps with
816/// that, by providing a lifetime for the connection between the
817/// [`listener`](Self::listener) and the [`action`](Self::action), and by handling the adding
818/// and removing of the [`listener`](Self::listener) at the right points in the widget
819/// lifecycle.
820///
821/// If you listen to an [`Action`] in a widget hierarchy, you should use this widget. If you are
822/// using an [`Action`] outside of a widget context, then you must call
823/// [`Action::remove_action_listener`] yourself.
824pub struct ActionListener {
825    /// See [`Widget::key`](crate::Widget::key).
826    pub key: Option<KeyRef>,
827
828    /// The [`ActionListenerCallback`] callback to register with the [`action`](Self::action).
829    pub listener: ActionListenerCallback,
830
831    /// The [`Action`] that the callback will be registered with.
832    pub action: ActionRef,
833
834    /// The widget below this widget in the tree.
835    pub child: WidgetRef,
836}
837
838impl ActionListener {
839    /// Creates an [`ActionListener`].
840    #[cfg_attr(debug_assertions, track_caller)]
841    pub fn new<K>(
842        listener: ActionListenerCallback,
843        action: ActionRef,
844        child: impl IntoWidget<K>,
845    ) -> ActionListener {
846        ActionListener {
847            key: None,
848            listener,
849            action,
850            child: child.into_widget(),
851        }
852    }
853
854    /// Dart `ActionListener(key:)`.
855    pub fn key(mut self, key: KeyRef) -> ActionListener {
856        self.key = Some(key);
857        self
858    }
859}
860
861impl fmt::Debug for ActionListener {
862    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863        f.debug_struct("ActionListener")
864            .field("action", &self.action)
865            .finish_non_exhaustive()
866    }
867}
868
869impl StatefulWidget for ActionListener {
870    type State = ActionListenerState;
871
872    fn key(&self) -> Option<&KeyRef> {
873        self.key.as_ref()
874    }
875
876    fn create_state(&self) -> ActionListenerState {
877        ActionListenerState {
878            state: StateData::new(),
879        }
880    }
881}
882
883/// Dart's `_ActionListenerState`.
884pub struct ActionListenerState {
885    state: StateData<ActionListener>,
886}
887
888impl State for ActionListenerState {
889    type Widget = ActionListener;
890    crate::state_accessors!();
891
892    fn init_state(self: Handle<Self>, app: &mut App) {
893        let widget = self.widget(app);
894        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
895        action.add_action_listener(app, listener);
896    }
897
898    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ActionListener) {
899        let widget = self.widget(app);
900        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
901        if old_widget.action == action && Rc::ptr_eq(&old_widget.listener, &listener) {
902            return;
903        }
904        let (old_action, old_listener) =
905            (old_widget.action.handle(), Rc::clone(&old_widget.listener));
906        old_action.remove_action_listener(app, &old_listener);
907        action.add_action_listener(app, listener);
908    }
909
910    fn dispose(self: Handle<Self>, app: &mut App) {
911        let widget = self.widget(app);
912        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
913        action.remove_action_listener(app, &listener);
914    }
915
916    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
917        self.widget(app).child.clone()
918    }
919}
920
921// ---------------------------------------------------------------------------------------------
922// CallbackAction
923
924/// The signature of a callback accepted by `CallbackAction::on_invoke`.
925///
926/// Such callbacks are implementations of [`Action::invoke`]. The returned value is the return
927/// value of [`Action::invoke`], the argument is the intent passed to [`Action::invoke`], and so
928/// forth.
929pub type OnInvokeCallback<T> = Rc<dyn Fn(&mut App, &T) -> Option<Rc<dyn Any>>>;
930
931/// An [`Action`] that takes a callback in order to configure it without having to create an
932/// explicit [`Action`] implementation just to call a callback.
933///
934/// See also:
935///
936///  * `Shortcuts`, which is a widget that contains a key map, in which it looks up key
937///    combinations in order to invoke actions.
938///  * [`Actions`], which is a widget that defines a map of [`Intent`] to [`Action`] and allows
939///    redefining of actions for its descendants.
940///  * [`ActionDispatcher`], a class that takes an [`Action`] and invokes it using a `FocusNode`
941///    for context.
942pub struct CallbackAction<T: Intent> {
943    action: ActionData,
944
945    /// The callback to be called when invoked.
946    ///
947    /// This is effectively the implementation of [`Action::invoke`].
948    on_invoke: OnInvokeCallback<T>,
949}
950
951impl<T: Intent> CallbackAction<T> {
952    /// A constructor for a [`CallbackAction`].
953    ///
954    /// The given callback is used as the implementation of [`Action::invoke`].
955    pub fn new(app: &mut App, on_invoke: OnInvokeCallback<T>) -> Ref<CallbackAction<T>> {
956        app.create(CallbackAction {
957            action: ActionData::new(),
958            on_invoke,
959        })
960    }
961}
962
963impl<T: Intent> Action for CallbackAction<T> {
964    type Intent = T;
965    crate::action_accessors!();
966
967    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
968        let on_invoke = Rc::clone(&app.get(self).on_invoke);
969        on_invoke(app, intent)
970    }
971}
972
973// ---------------------------------------------------------------------------------------------
974// ActionDispatcher
975
976/// The erased [`ActionDispatcher`]: what `Actions::dispatcher` holds.
977pub type ActionDispatcherRef = Rc<dyn ActionDispatcher>;
978
979/// An action dispatcher that invokes the actions given to it.
980///
981/// [`invoke_action`](Self::invoke_action) directly calls [`Action::invoke`] on the [`Action`]
982/// object.
983///
984/// For [`ContextAction`] actions, if no `context` is provided, the [`BuildContext`] of the
985/// [`primary_focus`] is used instead.
986///
987/// Dart's instantiable `const ActionDispatcher()` is [`PlainActionDispatcher`].
988///
989/// See also:
990///
991///  * `ShortcutManager`, that uses this class to invoke actions.
992///  * `Shortcuts`, which defines key mappings to [`Intent`]s.
993///  * [`Actions`], which defines a mapping between an [`Intent`] type and an [`Action`].
994pub trait ActionDispatcher: Debug {
995    /// Dart's `ActionDispatcher.toStringShort`, which a dump of an [`Actions`] widget prints:
996    /// the type and the identity.
997    fn to_string_short(&self) -> String {
998        describe_identity(
999            waft_foundation::bare_type_name(std::any::type_name::<Self>()),
1000            self as *const Self as *const () as usize as u64,
1001        )
1002    }
1003
1004    /// Invokes the given `action`, passing it the given `intent`.
1005    ///
1006    /// The action will be invoked with the given `context`, if given, but only if the action is
1007    /// a [`ContextAction`]. If no `context` is given, and the action is a [`ContextAction`],
1008    /// then the context from the [`primary_focus`] is used.
1009    ///
1010    /// Returns the object returned from [`Action::invoke`].
1011    ///
1012    /// The caller must receive a `true` result from [`AnyAction::is_enabled`] before calling
1013    /// this function. This function will assert if the action is not enabled when called.
1014    ///
1015    /// Consider using [`invoke_action_if_enabled`](Self::invoke_action_if_enabled) to invoke
1016    /// the action conditionally based on whether it is enabled or not, without having to check
1017    /// first.
1018    fn invoke_action(
1019        &self,
1020        app: &mut App,
1021        action: AnyAction,
1022        intent: &dyn Intent,
1023        context: Option<BuildContext>,
1024    ) -> Option<Rc<dyn Any>> {
1025        let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
1026        debug_assert!(
1027            action.is_enabled(app, intent, target),
1028            "Action must be enabled when calling invokeAction"
1029        );
1030        action.invoke(app, intent, target)
1031    }
1032
1033    /// Invokes the given `action`, passing it the given `intent`, but only if the action is
1034    /// enabled.
1035    ///
1036    /// The action will be invoked with the given `context`, if given, but only if the action is
1037    /// a [`ContextAction`]. If no `context` is given, and the action is a [`ContextAction`],
1038    /// then the context from the [`primary_focus`] is used.
1039    ///
1040    /// The return value has two components. The first is a boolean indicating if the action was
1041    /// enabled (as per [`AnyAction::is_enabled`]). If this is false, the second return value is
1042    /// `None`. Otherwise, the second return value is the object returned from
1043    /// [`Action::invoke`].
1044    ///
1045    /// Consider using [`invoke_action`](Self::invoke_action) if the enabled state of the action
1046    /// is not in question; this avoids calling [`AnyAction::is_enabled`] redundantly.
1047    fn invoke_action_if_enabled(
1048        &self,
1049        app: &mut App,
1050        action: AnyAction,
1051        intent: &dyn Intent,
1052        context: Option<BuildContext>,
1053    ) -> (bool, Option<Rc<dyn Any>>) {
1054        let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
1055        if action.is_enabled(app, intent, target) {
1056            return (true, action.invoke(app, intent, target));
1057        }
1058        (false, None)
1059    }
1060}
1061
1062/// Dart's instantiable `const ActionDispatcher()`: the dispatcher
1063/// [`Actions::of`] falls back to.
1064#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1065pub struct PlainActionDispatcher;
1066
1067impl PlainActionDispatcher {
1068    /// Creates an action dispatcher that invokes actions directly.
1069    pub fn new() -> PlainActionDispatcher {
1070        PlainActionDispatcher
1071    }
1072}
1073
1074impl ActionDispatcher for PlainActionDispatcher {
1075    /// Dart's `const ActionDispatcher()` names itself `ActionDispatcher`, whatever the Rust
1076    /// leaf is called.
1077    fn to_string_short(&self) -> String {
1078        describe_identity(
1079            "ActionDispatcher",
1080            self as *const Self as *const () as usize as u64,
1081        )
1082    }
1083}
1084
1085// ---------------------------------------------------------------------------------------------
1086// Actions
1087
1088/// A widget that maps [`Intent`]s to [`Action`]s to be used by its descendants when invoking an
1089/// [`Action`].
1090///
1091/// Actions are typically invoked using `Shortcuts`. They can also be invoked using
1092/// [`Actions::invoke`] on a context containing an ambient [`Actions`] widget.
1093///
1094/// See also:
1095///
1096///  * `Shortcuts`, a widget used to bind key combinations to [`Intent`]s.
1097///  * [`Intent`], a trait for values that contain configuration information for running an
1098///    [`Action`].
1099///  * [`Action`], a trait for containing and defining an invocation of a user action.
1100///  * [`ActionDispatcher`], the object that this widget uses to manage actions.
1101pub struct Actions {
1102    /// See [`Widget::key`](crate::Widget::key).
1103    pub key: Option<KeyRef>,
1104
1105    /// The [`ActionDispatcher`] object that invokes actions.
1106    ///
1107    /// This is what is returned from [`Actions::of`], and used by [`Actions::invoke`].
1108    ///
1109    /// If this [`dispatcher`](Self::dispatcher) is `None`, then [`Actions::of`] and
1110    /// [`Actions::invoke`] will look up the tree until they find an [`Actions`] widget that has
1111    /// a dispatcher set. If no such widget is found, then they will return/use a
1112    /// [`PlainActionDispatcher`].
1113    pub dispatcher: Option<ActionDispatcherRef>,
1114
1115    /// A map of [`Intent`] types to [`Action`] objects that defines which actions this widget
1116    /// knows about.
1117    ///
1118    /// For performance reasons, it is recommended that a pre-built map is passed in here
1119    /// instead of defining it inline in the build function.
1120    pub actions: HashMap<TypeId, ActionRef>,
1121
1122    /// The widget below this widget in the tree.
1123    pub child: WidgetRef,
1124}
1125
1126impl Actions {
1127    /// Creates an [`Actions`] widget.
1128    #[cfg_attr(debug_assertions, track_caller)]
1129    pub fn new<K>(actions: HashMap<TypeId, ActionRef>, child: impl IntoWidget<K>) -> Actions {
1130        Actions {
1131            key: None,
1132            dispatcher: None,
1133            actions,
1134            child: child.into_widget(),
1135        }
1136    }
1137
1138    /// Dart `Actions(key:)`.
1139    pub fn key(mut self, key: KeyRef) -> Actions {
1140        self.key = Some(key);
1141        self
1142    }
1143
1144    /// Dart `Actions(dispatcher:)`.
1145    pub fn dispatcher(mut self, dispatcher: ActionDispatcherRef) -> Actions {
1146        self.dispatcher = Some(dispatcher);
1147        self
1148    }
1149
1150    /// Visits the [`Actions`] widget ancestors of the given element. Returns true if the
1151    /// visitor found what it was looking for.
1152    fn visit_actions_ancestors(
1153        app: &mut App,
1154        context: BuildContext,
1155        visitor: &mut dyn FnMut(&mut App, BuildContext) -> bool,
1156    ) -> bool {
1157        if !context.mounted(app) {
1158            return false;
1159        }
1160        let mut actions_element =
1161            context.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app);
1162        while let Some(element) = actions_element {
1163            if visitor(app, element) {
1164                break;
1165            }
1166            // `get_parent` is needed here because
1167            // `get_element_for_inherited_widget_of_exact_type` will return itself if it happens
1168            // to be of the correct type.
1169            actions_element = get_parent(app, element).and_then(|parent| {
1170                parent.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app)
1171            });
1172        }
1173        actions_element.is_some()
1174    }
1175
1176    /// Finds the nearest valid [`ActionDispatcher`], or creates a new one if it doesn't find
1177    /// one.
1178    fn find_dispatcher(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
1179        let mut dispatcher: Option<ActionDispatcherRef> = None;
1180        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1181            let found = Actions::scope_of(app, element).dispatcher.clone();
1182            match found {
1183                Some(found) => {
1184                    dispatcher = Some(found);
1185                    true
1186                }
1187                None => false,
1188            }
1189        });
1190        dispatcher.unwrap_or_else(|| Rc::new(PlainActionDispatcher::new()))
1191    }
1192
1193    /// The `_ActionsScope` an ancestor element found by
1194    /// [`visit_actions_ancestors`](Self::visit_actions_ancestors) holds.
1195    fn scope_of(app: &App, element: BuildContext) -> &ActionsScope {
1196        crate::framework::downcast_widget::<ActionsScope>(&**element.widget(app))
1197            .expect("the element of an _ActionsScope holds one")
1198    }
1199
1200    /// Returns a handler that invokes the bound action for the given `intent` if the action is
1201    /// enabled, and returns `None` if the action is not enabled, or no matching action is
1202    /// found.
1203    ///
1204    /// This is intended to be used in widgets which have something similar to an `on_tap`
1205    /// handler, which takes a `GestureTapCallback`, and can be set to the result of calling
1206    /// this function.
1207    ///
1208    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
1209    /// actions change, the context will be rebuilt and find the updated action.
1210    ///
1211    /// The value returned from [`Action::invoke`] is discarded when the returned callback is
1212    /// called. If the return value is needed, consider using [`Actions::invoke`] instead.
1213    pub fn handler(app: &mut App, context: BuildContext, intent: IntentRef) -> Option<Listener> {
1214        let action = Actions::maybe_find(app, context, intent.intent_type())?;
1215        if action.is_enabled(app, &*intent, Some(context)) {
1216            let action = action.keep(app);
1217            return Some(Listener::new(move |app| {
1218                // Could be that the action was enabled when the closure was created, but is now
1219                // no longer enabled, so check again.
1220                if action.is_enabled(app, &*intent, Some(context)) {
1221                    Actions::of(app, context).invoke_action(
1222                        app,
1223                        action.handle(),
1224                        &*intent,
1225                        Some(context),
1226                    );
1227                }
1228            }));
1229        }
1230        None
1231    }
1232
1233    /// Finds the [`Action`] bound to the given `intent_type` in the given `context`.
1234    ///
1235    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
1236    /// actions change, the context will be rebuilt and find the updated action.
1237    ///
1238    /// If no [`Actions`] widget surrounds the given context, or no action is bound to
1239    /// `intent_type`, this function panics.
1240    ///
1241    /// See also:
1242    ///
1243    ///  * [`maybe_find`](Self::maybe_find), which is similar to this function, but will return
1244    ///    `None` if no [`Actions`] ancestor is found.
1245    pub fn find(app: &mut App, context: BuildContext, intent_type: TypeId) -> AnyAction {
1246        Actions::maybe_find(app, context, intent_type).expect(
1247            "Unable to find an action for the given intent type in an Actions widget in the \
1248             given context.\nActions.find() was called on a context that doesn't contain an \
1249             Actions widget with a mapping for the given intent type.",
1250        )
1251    }
1252
1253    /// Finds the [`Action`] bound to the given `intent_type` in the given `context`.
1254    ///
1255    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
1256    /// actions change, the context will be rebuilt and find the updated action.
1257    ///
1258    /// If no [`Actions`] widget surrounds the given context, this function returns `None`.
1259    ///
1260    /// See also:
1261    ///
1262    ///  * [`find`](Self::find), which is similar to this function, but will panic if no
1263    ///    [`Actions`] ancestor is found.
1264    pub fn maybe_find(
1265        app: &mut App,
1266        context: BuildContext,
1267        intent_type: TypeId,
1268    ) -> Option<AnyAction> {
1269        let mut action: Option<AnyAction> = None;
1270        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1271            let result = Actions::get_action_for_intent(app, element, intent_type);
1272            match result {
1273                Some(result) => {
1274                    context.depend_on_inherited_element(app, element, None);
1275                    action = Some(result);
1276                    true
1277                }
1278                None => false,
1279            }
1280        });
1281        action
1282    }
1283
1284    /// Dart's `Actions._maybeFindWithoutDependingOn`.
1285    fn maybe_find_without_depending_on(
1286        app: &mut App,
1287        context: BuildContext,
1288        intent_type: TypeId,
1289    ) -> Option<AnyAction> {
1290        let mut action: Option<AnyAction> = None;
1291        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1292            let result = Actions::get_action_for_intent(app, element, intent_type);
1293            match result {
1294                Some(result) => {
1295                    action = Some(result);
1296                    true
1297                }
1298                None => false,
1299            }
1300        });
1301        action
1302    }
1303
1304    /// Dart's `Actions._getActionForIntent`.
1305    fn get_action_for_intent(
1306        app: &App,
1307        element: BuildContext,
1308        intent_type: TypeId,
1309    ) -> Option<AnyAction> {
1310        Actions::scope_of(app, element)
1311            .actions
1312            .get(&intent_type)
1313            .map(Retained::handle)
1314    }
1315
1316    /// Returns the [`ActionDispatcher`] associated with the [`Actions`] widget that most tightly
1317    /// encloses the given [`BuildContext`].
1318    ///
1319    /// Will return a newly created [`PlainActionDispatcher`] if no ambient [`Actions`] widget is
1320    /// found.
1321    pub fn of(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
1322        let marker = context
1323            .depend_on_inherited_widget_of_exact_type::<ActionsScope>(app)
1324            .and_then(|scope| scope.dispatcher.clone());
1325        match marker {
1326            Some(dispatcher) => dispatcher,
1327            None => Actions::find_dispatcher(app, context),
1328        }
1329    }
1330
1331    /// Invokes the action associated with the given [`Intent`] using the [`Actions`] widget that
1332    /// most tightly encloses the given [`BuildContext`].
1333    ///
1334    /// This method returns the result of invoking the action's [`Action::invoke`] method.
1335    ///
1336    /// If the given `intent` doesn't map to an action, then it will look to the next ancestor
1337    /// [`Actions`] widget in the hierarchy until it reaches the root.
1338    ///
1339    /// This method panics if no ambient [`Actions`] widget is found.
1340    pub fn invoke(
1341        app: &mut App,
1342        context: BuildContext,
1343        intent: &dyn Intent,
1344    ) -> Option<Rc<dyn Any>> {
1345        let mut return_value: Option<Rc<dyn Any>> = None;
1346        let action_found = Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1347            let result = Actions::get_action_for_intent(app, element, intent.intent_type());
1348            if let Some(result) = result
1349                && result.is_enabled(app, intent, Some(context))
1350            {
1351                // Invoke the action we found using the relevant dispatcher from the Actions
1352                // element we found.
1353                return_value = Actions::find_dispatcher(app, element).invoke_action(
1354                    app,
1355                    result,
1356                    intent,
1357                    Some(context),
1358                );
1359            }
1360            result.is_some()
1361        });
1362        debug_assert!(
1363            action_found,
1364            "Unable to find an action for an Intent with type {intent:?} in an Actions widget in \
1365             the given context."
1366        );
1367        return_value
1368    }
1369
1370    /// Invokes the action associated with the given [`Intent`] using the [`Actions`] widget that
1371    /// most tightly encloses the given [`BuildContext`].
1372    ///
1373    /// This method returns the result of invoking the action's [`Action::invoke`] method. If no
1374    /// action mapping was found for the specified intent, or if the first action found was
1375    /// disabled, or the action itself returns `None` from [`Action::invoke`], then this method
1376    /// returns `None`.
1377    ///
1378    /// If the given `intent` doesn't map to an action, then it will look to the next ancestor
1379    /// [`Actions`] widget in the hierarchy until it reaches the root. If a suitable [`Action`]
1380    /// is found but its [`AnyAction::is_enabled`] returns false, the search will stop and this
1381    /// method will return `None`.
1382    pub fn maybe_invoke(
1383        app: &mut App,
1384        context: BuildContext,
1385        intent: &dyn Intent,
1386    ) -> Option<Rc<dyn Any>> {
1387        let mut return_value: Option<Rc<dyn Any>> = None;
1388        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1389            let result = Actions::get_action_for_intent(app, element, intent.intent_type());
1390            if let Some(result) = result
1391                && result.is_enabled(app, intent, Some(context))
1392            {
1393                return_value = Actions::find_dispatcher(app, element).invoke_action(
1394                    app,
1395                    result,
1396                    intent,
1397                    Some(context),
1398                );
1399            }
1400            result.is_some()
1401        });
1402        return_value
1403    }
1404}
1405
1406impl fmt::Debug for Actions {
1407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408        f.debug_struct("Actions")
1409            .field("dispatcher", &self.dispatcher)
1410            .field("actions", &self.actions)
1411            .finish_non_exhaustive()
1412    }
1413}
1414
1415impl StatefulWidget for Actions {
1416    type State = ActionsState;
1417
1418    fn key(&self) -> Option<&KeyRef> {
1419        self.key.as_ref()
1420    }
1421
1422    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1423        properties.add(DiagnosticsProperty::<String>::new(
1424            "dispatcher",
1425            self.dispatcher
1426                .as_ref()
1427                .map(|dispatcher| dispatcher.to_string_short()),
1428        ));
1429        let mut entries: Vec<(String, String)> = self
1430            .actions
1431            .iter()
1432            .map(|(intent_type, action)| (format!("{intent_type:?}"), action.to_string_short()))
1433            .collect();
1434        entries.sort();
1435        let actions = entries
1436            .into_iter()
1437            .map(|(intent_type, action)| format!("{intent_type}: {action}"))
1438            .collect::<Vec<_>>()
1439            .join(", ");
1440        properties.add(DiagnosticsProperty::<String>::new(
1441            "actions",
1442            Some(format!("{{{actions}}}")),
1443        ));
1444    }
1445
1446    fn create_state(&self) -> ActionsState {
1447        ActionsState {
1448            state: StateData::new(),
1449            listened_actions: HashSet::new(),
1450            action_changed: None,
1451            rebuild_key: 0,
1452        }
1453    }
1454}
1455
1456/// Dart's `_ActionsState`.
1457pub struct ActionsState {
1458    state: StateData<Actions>,
1459    /// The set of actions that this [`Actions`] widget is currently listening to.
1460    listened_actions: HashSet<ActionRef>,
1461    /// Dart's `_handleActionChanged` tear-off, kept so that it can be removed again.
1462    action_changed: Option<ActionListenerCallback>,
1463    /// Used to tell the marker to rebuild its dependencies when the state of an action in the
1464    /// map changes.
1465    rebuild_key: u64,
1466}
1467
1468impl ActionsState {
1469    fn handle_action_changed(self: Handle<Self>, app: &mut App) {
1470        // Generate a new key so that the marker notifies dependents.
1471        self.set_state(app, |state| state.rebuild_key += 1);
1472    }
1473
1474    fn update_action_listeners(self: Handle<Self>, app: &mut App) {
1475        let widget_actions: HashSet<ActionRef> =
1476            self.widget(app).actions.values().cloned().collect();
1477        let listened = app.get(self).listened_actions.clone();
1478        let removed_actions: Vec<AnyAction> = listened
1479            .difference(&widget_actions)
1480            .map(Retained::handle)
1481            .collect();
1482        let added_actions: Vec<AnyAction> = widget_actions
1483            .difference(&listened)
1484            .map(Retained::handle)
1485            .collect();
1486
1487        let handler = self.action_changed(app);
1488        for action in removed_actions {
1489            action.remove_action_listener(app, &handler);
1490        }
1491        for action in added_actions {
1492            action.add_action_listener(app, Rc::clone(&handler));
1493        }
1494        app.get_mut(self).listened_actions = widget_actions;
1495    }
1496
1497    /// The `Rc` behind Dart's `_handleActionChanged` tear-off, minted once so that every
1498    /// add / remove pair matches.
1499    fn action_changed(self: Handle<Self>, app: &mut App) -> ActionListenerCallback {
1500        if let Some(handler) = app.get(self).action_changed.clone() {
1501            return handler;
1502        }
1503        let handler: ActionListenerCallback =
1504            Rc::new(move |app: &mut App, _action: AnyAction| self.handle_action_changed(app));
1505        app.get_mut(self).action_changed = Some(Rc::clone(&handler));
1506        handler
1507    }
1508}
1509
1510impl State for ActionsState {
1511    type Widget = Actions;
1512    crate::state_accessors!();
1513
1514    fn init_state(self: Handle<Self>, app: &mut App) {
1515        self.update_action_listeners(app);
1516    }
1517
1518    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Actions) {
1519        self.update_action_listeners(app);
1520    }
1521
1522    fn dispose(self: Handle<Self>, app: &mut App) {
1523        let handler = self.action_changed(app);
1524        for action in std::mem::take(&mut app.get_mut(self).listened_actions) {
1525            action.remove_action_listener(app, &handler);
1526        }
1527    }
1528
1529    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1530        let rebuild_key = app.get(self).rebuild_key;
1531        let widget = self.widget(app);
1532        ActionsScope {
1533            dispatcher: widget.dispatcher.clone(),
1534            actions: widget.actions.clone(),
1535            rebuild_key,
1536            child: widget.child.clone(),
1537        }
1538        .into_widget()
1539    }
1540}
1541
1542/// An inherited widget used by the [`Actions`] widget for fast lookup of the [`Actions`] widget
1543/// information.
1544#[derive(Debug)]
1545struct ActionsScope {
1546    dispatcher: Option<ActionDispatcherRef>,
1547    actions: HashMap<TypeId, ActionRef>,
1548    rebuild_key: u64,
1549    child: WidgetRef,
1550}
1551
1552impl InheritedWidget for ActionsScope {
1553    fn child(&self) -> &WidgetRef {
1554        &self.child
1555    }
1556
1557    fn update_should_notify(&self, old_widget: &ActionsScope) -> bool {
1558        self.rebuild_key != old_widget.rebuild_key
1559            || !same_dispatcher(&old_widget.dispatcher, &self.dispatcher)
1560            || old_widget.actions != self.actions
1561    }
1562}
1563
1564/// Dart's `oldWidget.dispatcher != dispatcher` on a reference type.
1565fn same_dispatcher(a: &Option<ActionDispatcherRef>, b: &Option<ActionDispatcherRef>) -> bool {
1566    match (a, b) {
1567        (None, None) => true,
1568        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1569        _ => false,
1570    }
1571}
1572
1573// ---------------------------------------------------------------------------------------------
1574// FocusableActionDetector
1575
1576/// A widget that combines the functionality of [`Actions`], `Shortcuts`, `MouseRegion` and a
1577/// `Focus` widget to create a detector that defines actions and key bindings, and provides
1578/// callbacks for handling focus and hover highlights.
1579///
1580/// This widget can be used to give a control the required detection modes for focus and hover
1581/// handling. It is most often used when authoring a new control widget, and the new control
1582/// should be enabled for keyboard traversal and activation.
1583///
1584/// This widget doesn't have any visual representation, it is just a detector that provides
1585/// focus and hover capabilities.
1586///
1587/// It hosts its own `FocusNode` or uses [`focus_node`](Self::focus_node), if given.
1588pub struct FocusableActionDetector {
1589    /// See [`Widget::key`](crate::Widget::key).
1590    pub key: Option<KeyRef>,
1591
1592    /// Is this widget enabled or not.
1593    ///
1594    /// If disabled, will not send any notifications needed to update highlight or focus state,
1595    /// and will not define or respond to any actions or shortcuts.
1596    ///
1597    /// When disabled, adds `Focus` to the widget tree, but sets `Focus::can_request_focus` to
1598    /// false.
1599    pub enabled: bool,
1600
1601    /// An optional focus node to use as the focus node for this widget.
1602    pub focus_node: Option<FocusNodeRef>,
1603
1604    /// True if this widget will be selected as the initial focus when no other node in its
1605    /// scope is currently focused.
1606    pub autofocus: bool,
1607
1608    /// If false, will make this widget's descendants unfocusable.
1609    pub descendants_are_focusable: bool,
1610
1611    /// If false, will make this widget's descendants untraversable.
1612    pub descendants_are_traversable: bool,
1613
1614    /// A map of [`Intent`] types to [`Action`] objects that defines which actions this widget
1615    /// knows about.
1616    pub actions: Option<HashMap<TypeId, ActionRef>>,
1617
1618    /// The map of shortcuts that describes the mapping between a key sequence defined by a
1619    /// `ShortcutActivator` and the [`Intent`] that will be emitted when that key sequence is
1620    /// pressed.
1621    pub shortcuts: Option<ShortcutMap>,
1622
1623    /// A function that will be called when the focus highlight should be shown or hidden.
1624    ///
1625    /// This method is not triggered at the unmount of the widget.
1626    pub on_show_focus_highlight: Option<ValueChanged<bool>>,
1627
1628    /// A function that will be called when the hover highlight should be shown or hidden.
1629    ///
1630    /// This method is not triggered at the unmount of the widget.
1631    pub on_show_hover_highlight: Option<ValueChanged<bool>>,
1632
1633    /// A function that will be called when the focus changes.
1634    ///
1635    /// Called with true if the [`focus_node`](Self::focus_node) has primary focus.
1636    pub on_focus_change: Option<ValueChanged<bool>>,
1637
1638    /// The cursor for a mouse pointer when it enters or is hovering over the widget.
1639    ///
1640    /// The [`mouse_cursor`](Self::mouse_cursor) defaults to `MouseCursor.defer`, deferring the
1641    /// choice of cursor to the next region behind it in hit-test order.
1642    pub mouse_cursor: MouseCursorRef,
1643
1644    /// Whether to include semantics from `Focus`.
1645    ///
1646    /// Defaults to true.
1647    pub include_focus_semantics: bool,
1648
1649    /// The child widget for this [`FocusableActionDetector`] widget.
1650    pub child: WidgetRef,
1651}
1652
1653impl FocusableActionDetector {
1654    /// Creates a [`FocusableActionDetector`].
1655    #[cfg_attr(debug_assertions, track_caller)]
1656    pub fn new<K>(child: impl IntoWidget<K>) -> FocusableActionDetector {
1657        FocusableActionDetector {
1658            key: None,
1659            enabled: true,
1660            focus_node: None,
1661            autofocus: false,
1662            descendants_are_focusable: true,
1663            descendants_are_traversable: true,
1664            actions: None,
1665            shortcuts: None,
1666            on_show_focus_highlight: None,
1667            on_show_hover_highlight: None,
1668            on_focus_change: None,
1669            mouse_cursor: <dyn MouseCursor>::defer(),
1670            include_focus_semantics: true,
1671            child: child.into_widget(),
1672        }
1673    }
1674
1675    /// Dart `FocusableActionDetector(key:)`.
1676    pub fn key(mut self, key: KeyRef) -> FocusableActionDetector {
1677        self.key = Some(key);
1678        self
1679    }
1680
1681    /// Dart `FocusableActionDetector(enabled:)`.
1682    pub fn enabled(mut self, enabled: bool) -> FocusableActionDetector {
1683        self.enabled = enabled;
1684        self
1685    }
1686
1687    /// Dart `FocusableActionDetector(focusNode:)`.
1688    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> FocusableActionDetector {
1689        self.focus_node = Some(focus_node);
1690        self
1691    }
1692
1693    /// Dart `FocusableActionDetector(autofocus:)`.
1694    pub fn autofocus(mut self, autofocus: bool) -> FocusableActionDetector {
1695        self.autofocus = autofocus;
1696        self
1697    }
1698
1699    /// Dart `FocusableActionDetector(descendantsAreFocusable:)`.
1700    pub fn descendants_are_focusable(
1701        mut self,
1702        descendants_are_focusable: bool,
1703    ) -> FocusableActionDetector {
1704        self.descendants_are_focusable = descendants_are_focusable;
1705        self
1706    }
1707
1708    /// Dart `FocusableActionDetector(descendantsAreTraversable:)`.
1709    pub fn descendants_are_traversable(
1710        mut self,
1711        descendants_are_traversable: bool,
1712    ) -> FocusableActionDetector {
1713        self.descendants_are_traversable = descendants_are_traversable;
1714        self
1715    }
1716
1717    /// Dart `FocusableActionDetector(actions:)`.
1718    pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> FocusableActionDetector {
1719        self.actions = Some(actions);
1720        self
1721    }
1722
1723    /// Dart `FocusableActionDetector(shortcuts:)`.
1724    pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> FocusableActionDetector {
1725        self.shortcuts = Some(shortcuts);
1726        self
1727    }
1728
1729    /// Dart `FocusableActionDetector(onShowFocusHighlight:)`.
1730    pub fn on_show_focus_highlight(
1731        mut self,
1732        on_show_focus_highlight: impl Fn(&mut App, bool) + 'static,
1733    ) -> FocusableActionDetector {
1734        self.on_show_focus_highlight = Some(Rc::new(on_show_focus_highlight));
1735        self
1736    }
1737
1738    /// Dart `FocusableActionDetector(onShowHoverHighlight:)`.
1739    pub fn on_show_hover_highlight(
1740        mut self,
1741        on_show_hover_highlight: impl Fn(&mut App, bool) + 'static,
1742    ) -> FocusableActionDetector {
1743        self.on_show_hover_highlight = Some(Rc::new(on_show_hover_highlight));
1744        self
1745    }
1746
1747    /// Dart `FocusableActionDetector(onFocusChange:)`.
1748    pub fn on_focus_change(
1749        mut self,
1750        on_focus_change: impl Fn(&mut App, bool) + 'static,
1751    ) -> FocusableActionDetector {
1752        self.on_focus_change = Some(Rc::new(on_focus_change));
1753        self
1754    }
1755
1756    /// Dart `FocusableActionDetector(mouseCursor:)`.
1757    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> FocusableActionDetector {
1758        self.mouse_cursor = mouse_cursor;
1759        self
1760    }
1761
1762    /// Dart `FocusableActionDetector(includeFocusSemantics:)`.
1763    pub fn include_focus_semantics(
1764        mut self,
1765        include_focus_semantics: bool,
1766    ) -> FocusableActionDetector {
1767        self.include_focus_semantics = include_focus_semantics;
1768        self
1769    }
1770}
1771
1772impl fmt::Debug for FocusableActionDetector {
1773    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774        f.debug_struct("FocusableActionDetector")
1775            .field("enabled", &self.enabled)
1776            .field("focusNode", &self.focus_node)
1777            .finish_non_exhaustive()
1778    }
1779}
1780
1781impl StatefulWidget for FocusableActionDetector {
1782    type State = FocusableActionDetectorState;
1783
1784    fn key(&self) -> Option<&KeyRef> {
1785        self.key.as_ref()
1786    }
1787
1788    fn create_state(&self) -> FocusableActionDetectorState {
1789        FocusableActionDetectorState {
1790            state: StateData::new(),
1791            can_show_highlight: false,
1792            hovering: false,
1793            focused: false,
1794            highlight_mode_listener: None,
1795            // This global key is needed to keep only the necessary widgets in the tree while
1796            // maintaining the subtree's state.
1797            mouse_region_key: GlobalKey::new(),
1798        }
1799    }
1800}
1801
1802/// Dart's `_FocusableActionDetectorState`.
1803pub struct FocusableActionDetectorState {
1804    state: StateData<FocusableActionDetector>,
1805    can_show_highlight: bool,
1806    hovering: bool,
1807    focused: bool,
1808    highlight_mode_listener: Option<HighlightModeListener>,
1809    mouse_region_key: GlobalKey,
1810}
1811
1812/// Dart's `VoidCallback? task` argument of `_mayTriggerCallback`, which mutates the state
1813/// between the two readings.
1814type HighlightTask<'a> = &'a dyn Fn(Handle<FocusableActionDetectorState>, &mut App);
1815
1816/// The state Dart's `_mayTriggerCallback` records before and after its task.
1817#[derive(Clone, Copy)]
1818struct HighlightState {
1819    hover: bool,
1820    focus: bool,
1821}
1822
1823impl FocusableActionDetectorState {
1824    fn update_highlight_mode(self: Handle<Self>, app: &mut App, _mode: FocusHighlightMode) {
1825        self.may_trigger_callback(
1826            app,
1827            None,
1828            Some(&|this, app| {
1829                let mode = FocusManager::instance(app).highlight_mode(app);
1830                app.get_mut(this).can_show_highlight = match mode {
1831                    FocusHighlightMode::Touch => false,
1832                    FocusHighlightMode::Traditional => true,
1833                };
1834            }),
1835        );
1836    }
1837
1838    /// Have to have this separate from
1839    /// [`update_highlight_mode`](Self::update_highlight_mode) because it gets called in
1840    /// `init_state`, where things aren't mounted yet.
1841    ///
1842    /// Since this method is a highlight mode listener, it is only called immediately following
1843    /// pointer events.
1844    fn handle_focus_highlight_mode_change(
1845        self: Handle<Self>,
1846        app: &mut App,
1847        mode: FocusHighlightMode,
1848    ) {
1849        if !self.mounted(app) {
1850            return;
1851        }
1852        self.update_highlight_mode(app, mode);
1853    }
1854
1855    fn handle_mouse_enter(self: Handle<Self>, app: &mut App) {
1856        if !app.get(self).hovering {
1857            self.may_trigger_callback(
1858                app,
1859                None,
1860                Some(&|this, app| {
1861                    app.get_mut(this).hovering = true;
1862                }),
1863            );
1864        }
1865    }
1866
1867    fn handle_mouse_exit(self: Handle<Self>, app: &mut App) {
1868        if app.get(self).hovering {
1869            self.may_trigger_callback(
1870                app,
1871                None,
1872                Some(&|this, app| {
1873                    app.get_mut(this).hovering = false;
1874                }),
1875            );
1876        }
1877    }
1878
1879    fn handle_focus_change(self: Handle<Self>, app: &mut App, focused: bool) {
1880        if app.get(self).focused != focused {
1881            self.may_trigger_callback(
1882                app,
1883                None,
1884                Some(&|this, app| {
1885                    app.get_mut(this).focused = focused;
1886                }),
1887            );
1888            if let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
1889                let focused = app.get(self).focused;
1890                on_focus_change(app, focused);
1891            }
1892        }
1893    }
1894
1895    fn should_show_hover_highlight(self: Handle<Self>, app: &App, target_enabled: bool) -> bool {
1896        app.get(self).hovering && target_enabled && app.get(self).can_show_highlight
1897    }
1898
1899    fn can_request_focus(self: Handle<Self>, app: &mut App, target_enabled: bool) -> bool {
1900        let context = self.context(app);
1901        match MediaQuery::maybe_navigation_mode_of(app, context) {
1902            None | Some(NavigationMode::Traditional) => target_enabled,
1903            Some(NavigationMode::Directional) => true,
1904        }
1905    }
1906
1907    fn should_show_focus_highlight(
1908        self: Handle<Self>,
1909        app: &mut App,
1910        target_enabled: bool,
1911    ) -> bool {
1912        app.get(self).focused
1913            && app.get(self).can_show_highlight
1914            && self.can_request_focus(app, target_enabled)
1915    }
1916
1917    fn highlight_state(self: Handle<Self>, app: &mut App, target_enabled: bool) -> HighlightState {
1918        HighlightState {
1919            hover: self.should_show_hover_highlight(app, target_enabled),
1920            focus: self.should_show_focus_highlight(app, target_enabled),
1921        }
1922    }
1923
1924    /// Record old states, do `task` if given, then compare old states with the new states, and
1925    /// trigger callbacks if necessary.
1926    ///
1927    /// The old states are collected from `old_enabled` if it is provided (Dart passes the whole
1928    /// `oldWidget`, of which this is the only field read), or the current widget (before doing
1929    /// `task`) otherwise. The new states are always collected from the current widget.
1930    fn may_trigger_callback(
1931        self: Handle<Self>,
1932        app: &mut App,
1933        old_enabled: Option<bool>,
1934        task: Option<HighlightTask<'_>>,
1935    ) {
1936        debug_assert!(
1937            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks
1938        );
1939        let old_enabled = old_enabled.unwrap_or_else(|| self.widget(app).enabled);
1940        let did = self.highlight_state(app, old_enabled);
1941        if let Some(task) = task {
1942            task(self, app);
1943        }
1944        let enabled = self.widget(app).enabled;
1945        let do_show = self.highlight_state(app, enabled);
1946        if did.focus != do_show.focus
1947            && let Some(callback) = self.widget(app).on_show_focus_highlight.clone()
1948        {
1949            callback(app, do_show.focus);
1950        }
1951        if did.hover != do_show.hover
1952            && let Some(callback) = self.widget(app).on_show_hover_highlight.clone()
1953        {
1954            callback(app, do_show.hover);
1955        }
1956    }
1957}
1958
1959impl State for FocusableActionDetectorState {
1960    type Widget = FocusableActionDetector;
1961    crate::state_accessors!();
1962
1963    fn init_state(self: Handle<Self>, app: &mut App) {
1964        SchedulerBinding::add_post_frame_callback(
1965            app,
1966            FrameCallback::new(move |app, _duration| {
1967                // Removed within the frame it was made in: Dart's callback then runs on the
1968                // defunct state and changes nothing, but a Rust handle to it is gone.
1969                if !self.mounted(app) {
1970                    return;
1971                }
1972                let mode = FocusManager::instance(app).highlight_mode(app);
1973                self.update_highlight_mode(app, mode);
1974            }),
1975            View::maybe_id_of(app, self.context(app)),
1976        );
1977        let listener: HighlightModeListener =
1978            Rc::new(move |app: &mut App, mode| self.handle_focus_highlight_mode_change(app, mode));
1979        app.get_mut(self).highlight_mode_listener = Some(Rc::clone(&listener));
1980        FocusManager::instance(app).add_highlight_mode_listener(app, listener);
1981    }
1982
1983    fn dispose(self: Handle<Self>, app: &mut App) {
1984        if let Some(listener) = app.get_mut(self).highlight_mode_listener.take() {
1985            FocusManager::instance(app).remove_highlight_mode_listener(app, &listener);
1986        }
1987    }
1988
1989    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusableActionDetector) {
1990        if self.widget(app).enabled != old_widget.enabled {
1991            let old_enabled = old_widget.enabled;
1992            SchedulerBinding::add_post_frame_callback(
1993                app,
1994                FrameCallback::new(move |app, _duration| {
1995                    self.may_trigger_callback(app, Some(old_enabled), None);
1996                }),
1997                View::maybe_id_of(app, self.context(app)),
1998            );
1999        }
2000    }
2001
2002    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2003        let can_request_focus = {
2004            let enabled = self.widget(app).enabled;
2005            self.can_request_focus(app, enabled)
2006        };
2007        let widget = self.widget(app);
2008        let (
2009            focus_node,
2010            autofocus,
2011            descendants_are_focusable,
2012            descendants_are_traversable,
2013            include_focus_semantics,
2014            mouse_cursor,
2015            child,
2016            enabled,
2017        ) = (
2018            widget.focus_node.clone(),
2019            widget.autofocus,
2020            widget.descendants_are_focusable,
2021            widget.descendants_are_traversable,
2022            widget.include_focus_semantics,
2023            Rc::clone(&widget.mouse_cursor),
2024            widget.child.clone(),
2025            widget.enabled,
2026        );
2027        let mouse_region_key = app.get(self).mouse_region_key.clone();
2028
2029        let mut focus = Focus::new(child)
2030            .autofocus(autofocus)
2031            .descendants_are_focusable(descendants_are_focusable)
2032            .descendants_are_traversable(descendants_are_traversable)
2033            .can_request_focus(can_request_focus)
2034            .on_focus_change(move |app, focused| self.handle_focus_change(app, focused))
2035            .include_semantics(include_focus_semantics);
2036        if let Some(focus_node) = focus_node {
2037            focus = focus.focus_node(focus_node);
2038        }
2039
2040        let mut child: WidgetRef = MouseRegion::new()
2041            .key(mouse_region_key.into())
2042            .on_enter(Rc::new(move |app, _event| self.handle_mouse_enter(app)))
2043            .on_exit(Rc::new(move |app, _event| self.handle_mouse_exit(app)))
2044            .cursor(mouse_cursor)
2045            .child(focus)
2046            .into_widget();
2047
2048        let actions = self.widget(app).actions.clone();
2049        if let Some(actions) = actions.filter(|actions| enabled && !actions.is_empty()) {
2050            child = Actions::new(actions, child).into_widget();
2051        }
2052        let shortcuts = self.widget(app).shortcuts.clone();
2053        if let Some(shortcuts) = shortcuts.filter(|shortcuts| enabled && !shortcuts.is_empty()) {
2054            child = Shortcuts::new(shortcuts, child).into_widget();
2055        }
2056        child
2057    }
2058}
2059
2060// ---------------------------------------------------------------------------------------------
2061// The intents and actions this file declares
2062
2063/// An [`Intent`] that keeps a callback to be invoked by a [`VoidCallbackAction`] when it
2064/// receives this intent.
2065pub struct VoidCallbackIntent {
2066    /// The callback that is to be called by the [`VoidCallbackAction`] that receives this
2067    /// intent.
2068    pub callback: Listener,
2069}
2070
2071impl VoidCallbackIntent {
2072    /// Creates a [`VoidCallbackIntent`].
2073    pub fn new(callback: Listener) -> VoidCallbackIntent {
2074        VoidCallbackIntent { callback }
2075    }
2076}
2077
2078impl fmt::Debug for VoidCallbackIntent {
2079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2080        f.debug_struct("VoidCallbackIntent").finish()
2081    }
2082}
2083
2084impl Intent for VoidCallbackIntent {
2085    fn as_any(&self) -> &dyn Any {
2086        self
2087    }
2088}
2089
2090/// An [`Action`] that invokes the callback given to it in the [`VoidCallbackIntent`] passed to
2091/// it when invoked.
2092///
2093/// See also:
2094///
2095///  * [`CallbackAction`], which is an action that will invoke a callback with the intent passed
2096///    to the action's invoke method. The callback is configured on the action, not the intent,
2097///    like this class.
2098pub struct VoidCallbackAction {
2099    action: ActionData,
2100}
2101
2102impl VoidCallbackAction {
2103    /// Creates a [`VoidCallbackAction`].
2104    pub fn new(app: &mut App) -> Ref<VoidCallbackAction> {
2105        app.create(VoidCallbackAction {
2106            action: ActionData::new(),
2107        })
2108    }
2109}
2110
2111impl Action for VoidCallbackAction {
2112    type Intent = VoidCallbackIntent;
2113    crate::action_accessors!();
2114
2115    fn invoke(
2116        self: Handle<Self>,
2117        app: &mut App,
2118        intent: &VoidCallbackIntent,
2119    ) -> Option<Rc<dyn Any>> {
2120        intent.callback.call(app);
2121        None
2122    }
2123}
2124
2125/// An [`Intent`] that is bound to a [`DoNothingAction`].
2126///
2127/// Attaching a [`DoNothingIntent`] to a `Shortcuts` mapping is one way to disable a keyboard
2128/// shortcut defined by a widget higher in the widget hierarchy and consume any key event that
2129/// triggers it via a shortcut.
2130///
2131/// See also:
2132///
2133///  * [`DoNothingAndStopPropagationIntent`], a similar intent that will not handle the key
2134///    event, but will still keep it from being passed to other key handlers in the focus chain.
2135#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2136pub struct DoNothingIntent;
2137
2138impl DoNothingIntent {
2139    /// Creates a [`DoNothingIntent`].
2140    pub const fn new() -> DoNothingIntent {
2141        DoNothingIntent
2142    }
2143}
2144
2145impl Intent for DoNothingIntent {
2146    fn as_any(&self) -> &dyn Any {
2147        self
2148    }
2149}
2150
2151/// An [`Intent`] that is bound to a [`DoNothingAction`], but, in addition to not performing an
2152/// action, also stops the propagation of the key event bound to this intent to other key event
2153/// handlers in the focus chain.
2154///
2155/// Attaching a [`DoNothingAndStopPropagationIntent`] to a `Shortcuts::shortcuts` mapping is one
2156/// way to disable a keyboard shortcut defined by a widget higher in the widget hierarchy. In
2157/// addition, the bound [`DoNothingAction`] will return false from
2158/// [`Action::consumes_key`], causing the key bound to this intent to be passed on to the
2159/// platform embedding as "not handled" without passing it to other key handlers in the focus
2160/// chain (e.g. parent `Shortcuts` widgets higher up in the chain).
2161///
2162/// See also:
2163///
2164///  * [`DoNothingIntent`], a similar intent that will handle the key event.
2165#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2166pub struct DoNothingAndStopPropagationIntent;
2167
2168impl DoNothingAndStopPropagationIntent {
2169    /// Creates a [`DoNothingAndStopPropagationIntent`].
2170    pub const fn new() -> DoNothingAndStopPropagationIntent {
2171        DoNothingAndStopPropagationIntent
2172    }
2173}
2174
2175impl Intent for DoNothingAndStopPropagationIntent {
2176    fn as_any(&self) -> &dyn Any {
2177        self
2178    }
2179}
2180
2181/// An [`Action`] that doesn't perform any action when invoked.
2182///
2183/// Attaching a [`DoNothingAction`] to an [`Actions::actions`] mapping is a way to disable an
2184/// action defined by a widget higher in the widget hierarchy.
2185///
2186/// If [`Action::consumes_key`] returns false, then not only will this action do nothing, but it
2187/// will stop the propagation of the key event used to trigger it to other widgets in the focus
2188/// chain and tell the embedding that the key wasn't handled, allowing text input fields or
2189/// other non-Flutter elements to receive that key event. The return value of
2190/// [`Action::consumes_key`] can be set via the `consumes_key` argument to the constructor.
2191///
2192/// This action can be bound to any [`Intent`].
2193///
2194/// See also:
2195///
2196///  * [`DoNothingIntent`], which is an intent that can be bound to a key set in a `Shortcuts`
2197///    widget to do nothing.
2198///  * [`DoNothingAndStopPropagationIntent`], which is an intent that can be bound to a key set
2199///    in a `Shortcuts` widget to do nothing and also stop key event propagation to other key
2200///    handlers in the focus chain.
2201pub struct DoNothingAction {
2202    action: ActionData,
2203    consumes_key: bool,
2204}
2205
2206impl DoNothingAction {
2207    /// Creates a [`DoNothingAction`].
2208    ///
2209    /// Dart's optional `consumesKey` argument defaults to true.
2210    pub fn new(app: &mut App) -> Ref<DoNothingAction> {
2211        app.create(DoNothingAction {
2212            action: ActionData::new(),
2213            consumes_key: true,
2214        })
2215    }
2216
2217    /// Dart `DoNothingAction(consumesKey:)`.
2218    pub fn set_consumes_key(self: Handle<Self>, app: &mut App, consumes_key: bool) {
2219        app.get_mut(self).consumes_key = consumes_key;
2220    }
2221}
2222
2223impl Action for DoNothingAction {
2224    type Intent = dyn Intent;
2225    crate::action_accessors!();
2226
2227    fn consumes_key(self: Handle<Self>, app: &mut App, _intent: &dyn Intent) -> bool {
2228        app.get(self).consumes_key
2229    }
2230
2231    fn invoke(self: Handle<Self>, _app: &mut App, _intent: &dyn Intent) -> Option<Rc<dyn Any>> {
2232        None
2233    }
2234}
2235
2236/// An [`Intent`] that activates the currently focused control.
2237///
2238/// This intent is bound by default to the space key on all platforms, and also to the enter key
2239/// on all platforms except the web, where enter doesn't toggle selection. On the web, enter is
2240/// bound to [`ButtonActivateIntent`] instead.
2241#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2242pub struct ActivateIntent;
2243
2244impl ActivateIntent {
2245    /// Creates an intent that activates the currently focused control.
2246    pub const fn new() -> ActivateIntent {
2247        ActivateIntent
2248    }
2249}
2250
2251impl Intent for ActivateIntent {
2252    fn as_any(&self) -> &dyn Any {
2253        self
2254    }
2255}
2256
2257/// An [`Intent`] that activates the currently focused button.
2258///
2259/// This intent is bound by default to the enter key on the web, where enter can be used to
2260/// activate buttons, but not toggle selection. All other platforms bind the enter key to
2261/// [`ActivateIntent`].
2262#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2263pub struct ButtonActivateIntent;
2264
2265impl ButtonActivateIntent {
2266    /// Creates an intent that activates the currently focused control, if it's a button.
2267    pub const fn new() -> ButtonActivateIntent {
2268        ButtonActivateIntent
2269    }
2270}
2271
2272impl Intent for ButtonActivateIntent {
2273    fn as_any(&self) -> &dyn Any {
2274        self
2275    }
2276}
2277
2278/// An [`Action`] that activates the currently focused control.
2279///
2280/// This is a trait that serves as a base for actions that activate a control. By default, is
2281/// bound to the enter, game button A, and space keys in the default keyboard map in
2282/// `WidgetsApp`.
2283pub trait ActivateAction: Action<Intent = ActivateIntent> {}
2284
2285/// An [`Intent`] that selects the currently focused control.
2286#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2287pub struct SelectIntent;
2288
2289impl SelectIntent {
2290    /// Creates an intent that selects the currently focused control.
2291    pub const fn new() -> SelectIntent {
2292        SelectIntent
2293    }
2294}
2295
2296impl Intent for SelectIntent {
2297    fn as_any(&self) -> &dyn Any {
2298        self
2299    }
2300}
2301
2302/// An action that selects the currently focused control.
2303///
2304/// This is a trait that serves as a base for actions that select something. It is not bound to
2305/// any key by default.
2306pub trait SelectAction: Action<Intent = SelectIntent> {}
2307
2308/// An [`Intent`] that dismisses the currently focused widget.
2309///
2310/// `WidgetsApp::default_shortcuts` binds this intent to the escape and game button B keys.
2311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2312pub struct DismissIntent;
2313
2314impl DismissIntent {
2315    /// Creates an intent that dismisses the currently focused widget.
2316    pub const fn new() -> DismissIntent {
2317        DismissIntent
2318    }
2319}
2320
2321impl Intent for DismissIntent {
2322    fn as_any(&self) -> &dyn Any {
2323        self
2324    }
2325}
2326
2327/// An [`Action`] that dismisses the focused widget.
2328///
2329/// This is a trait that serves as a base for dismiss actions.
2330pub trait DismissAction: Action<Intent = DismissIntent> {}
2331
2332/// An [`Intent`] that evaluates a series of specified
2333/// [`ordered_intents`](Self::ordered_intents) for execution.
2334///
2335/// The first intent that matches an enabled action is used.
2336#[derive(Debug)]
2337pub struct PrioritizedIntents {
2338    /// List of intents to be evaluated in order for execution. When an
2339    /// [`AnyAction::is_enabled`] returns true, that action will be invoked and progression
2340    /// through the ordered intents stops.
2341    pub ordered_intents: Vec<IntentRef>,
2342}
2343
2344impl PrioritizedIntents {
2345    /// Creates an intent that is used with [`PrioritizedAction`] to specify a list of intents,
2346    /// the first available of which will be used.
2347    pub fn new(ordered_intents: Vec<IntentRef>) -> PrioritizedIntents {
2348        PrioritizedIntents { ordered_intents }
2349    }
2350}
2351
2352impl Intent for PrioritizedIntents {
2353    fn as_any(&self) -> &dyn Any {
2354        self
2355    }
2356}
2357
2358/// An [`Action`] that iterates through a list of [`Intent`]s, invoking the first that is
2359/// enabled.
2360///
2361/// [`ContextAction::is_enabled`] must be called before [`ContextAction::invoke`]. Calling it
2362/// configures the object by seeking the first intent with an enabled action. If the actions
2363/// have an opportunity to change enabled state, it must be called again before calling
2364/// [`ContextAction::invoke`].
2365pub struct PrioritizedAction {
2366    action: ActionData,
2367    selected_action: Option<ActionRef>,
2368    selected_intent: Option<IntentRef>,
2369}
2370
2371impl PrioritizedAction {
2372    /// Creates a [`PrioritizedAction`].
2373    pub fn new(app: &mut App) -> Ref<PrioritizedAction> {
2374        app.create(PrioritizedAction {
2375            action: ActionData::new(),
2376            selected_action: None,
2377            selected_intent: None,
2378        })
2379    }
2380}
2381
2382impl Action for PrioritizedAction {
2383    type Intent = PrioritizedIntents;
2384    crate::action_accessors!();
2385    crate::context_action_overrides!();
2386}
2387
2388impl ContextAction for PrioritizedAction {
2389    fn is_enabled(
2390        self: Handle<Self>,
2391        app: &mut App,
2392        intent: &PrioritizedIntents,
2393        context: Option<BuildContext>,
2394    ) -> bool {
2395        let Some(focus) = primary_focus(app) else {
2396            return false;
2397        };
2398        let Some(focus_context) = focus.context(app) else {
2399            return false;
2400        };
2401        for candidate_intent in intent.ordered_intents.iter() {
2402            let candidate_action =
2403                Actions::maybe_find(app, focus_context, candidate_intent.intent_type());
2404            if let Some(candidate_action) = candidate_action
2405                && candidate_action.is_enabled(app, &**candidate_intent, context)
2406            {
2407                let candidate_action = candidate_action.keep(app);
2408                let this = app.get_mut(self);
2409                this.selected_action = Some(candidate_action);
2410                this.selected_intent = Some(Rc::clone(candidate_intent));
2411                return true;
2412            }
2413        }
2414        false
2415    }
2416
2417    fn invoke(
2418        self: Handle<Self>,
2419        app: &mut App,
2420        _intent: &PrioritizedIntents,
2421        context: Option<BuildContext>,
2422    ) -> Option<Rc<dyn Any>> {
2423        let selected_action = app
2424            .get(self)
2425            .selected_action
2426            .handle()
2427            .expect("isEnabled selected an action");
2428        let selected_intent = app
2429            .get(self)
2430            .selected_intent
2431            .clone()
2432            .expect("isEnabled selected an intent");
2433        selected_action.invoke(app, &*selected_intent, context);
2434        None
2435    }
2436}
2437
2438// ---------------------------------------------------------------------------------------------
2439// The overridable actions
2440
2441/// The fields Dart's `_OverridableActionMixin` declares; both overridable actions carry this
2442/// bag under the field `overridable`.
2443struct OverridableActionData {
2444    /// The default action to invoke if an enabled override [`Action`] can't be found using
2445    /// [`lookup_context`](Self::lookup_context).
2446    default_action: ActionRef,
2447    /// The [`BuildContext`] used to find the override of this [`Action`].
2448    lookup_context: BuildContext,
2449    // When these are true, this action throws when the override calls this action's method and
2450    // the override is already being invoked from within it.
2451    debug_assert_mutually_recursive: bool,
2452    debug_assert_is_action_enabled_mutually_recursive: bool,
2453    debug_assert_is_enabled_mutually_recursive: bool,
2454    debug_assert_consume_key_mutually_recursive: bool,
2455}
2456
2457impl OverridableActionData {
2458    fn new(default_action: ActionRef, lookup_context: BuildContext) -> OverridableActionData {
2459        OverridableActionData {
2460            default_action,
2461            lookup_context,
2462            debug_assert_mutually_recursive: false,
2463            debug_assert_is_action_enabled_mutually_recursive: false,
2464            debug_assert_is_enabled_mutually_recursive: false,
2465            debug_assert_consume_key_mutually_recursive: false,
2466        }
2467    }
2468}
2469
2470/// Dart's `_OverridableActionMixin`: the shared bodies of the two overridable actions.
2471trait OverridableActionMixin: ContextAction {
2472    /// Dart's `_OverridableActionMixin` fields, held under the field `overridable`.
2473    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData;
2474
2475    /// See [`overridable_data`](Self::overridable_data).
2476    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData;
2477
2478    /// How to invoke the default action, given the caller `from_action`.
2479    fn invoke_default_action(
2480        self: Handle<Self>,
2481        app: &mut App,
2482        intent: &Self::Intent,
2483        from_action: Option<AnyAction>,
2484        context: Option<BuildContext>,
2485    ) -> Option<Rc<dyn Any>>;
2486
2487    /// Dart's `_getOverrideAction`.
2488    fn get_override_action(
2489        self: Handle<Self>,
2490        app: &mut App,
2491        intent_type: TypeId,
2492        declare_dependency: bool,
2493    ) -> Option<AnyAction> {
2494        let lookup_context = self.overridable_data(app).lookup_context;
2495        let override_action = if declare_dependency {
2496            Actions::maybe_find(app, lookup_context, intent_type)
2497        } else {
2498            Actions::maybe_find_without_depending_on(app, lookup_context, intent_type)
2499        };
2500        debug_assert!(override_action != Some(Action::as_action(self)));
2501        override_action
2502    }
2503
2504    /// Dart's `_OverridableActionMixin._updateCallingAction`.
2505    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2506        self.action_data_mut(app).current_calling_action = value.clone();
2507        let default_action = self.overridable_data(app).default_action.handle();
2508        default_action.update_calling_action(app, value);
2509    }
2510
2511    /// Dart's `_OverridableActionMixin._invokeOverride`.
2512    fn invoke_override(
2513        self: Handle<Self>,
2514        app: &mut App,
2515        override_action: AnyAction,
2516        intent: &Self::Intent,
2517        context: Option<BuildContext>,
2518    ) -> Option<Rc<dyn Any>> {
2519        debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
2520        if cfg!(debug_assertions) {
2521            self.overridable_data_mut(app)
2522                .debug_assert_mutually_recursive = true;
2523        }
2524        let default_action = self.overridable_data(app).default_action.clone();
2525        override_action.update_calling_action(app, Some(default_action));
2526        let return_value = override_action.invoke(app, intent.as_intent(), context);
2527        override_action.update_calling_action(app, None);
2528        if cfg!(debug_assertions) {
2529            self.overridable_data_mut(app)
2530                .debug_assert_mutually_recursive = false;
2531        }
2532        return_value
2533    }
2534
2535    /// Dart's `_OverridableActionMixin.invoke`.
2536    fn invoke(
2537        self: Handle<Self>,
2538        app: &mut App,
2539        intent: &Self::Intent,
2540        context: Option<BuildContext>,
2541    ) -> Option<Rc<dyn Any>> {
2542        let intent_type = intent.as_intent().intent_type();
2543        let override_action = self.get_override_action(app, intent_type, false);
2544        match override_action {
2545            None => {
2546                let calling = self.action_data(app).current_calling_action.handle();
2547                self.invoke_default_action(app, intent, calling, context)
2548            }
2549            Some(override_action) => self.invoke_override(app, override_action, intent, context),
2550        }
2551    }
2552
2553    /// Dart's `_OverridableActionMixin._isOverrideActionEnabled`.
2554    fn is_override_action_enabled(
2555        self: Handle<Self>,
2556        app: &mut App,
2557        override_action: AnyAction,
2558    ) -> bool {
2559        debug_assert!(
2560            !self
2561                .overridable_data(app)
2562                .debug_assert_is_action_enabled_mutually_recursive
2563        );
2564        if cfg!(debug_assertions) {
2565            self.overridable_data_mut(app)
2566                .debug_assert_is_action_enabled_mutually_recursive = true;
2567        }
2568        let default_action = self.overridable_data(app).default_action.clone();
2569        override_action.update_calling_action(app, Some(default_action));
2570        let is_override_enabled = override_action.is_action_enabled(app);
2571        override_action.update_calling_action(app, None);
2572        if cfg!(debug_assertions) {
2573            self.overridable_data_mut(app)
2574                .debug_assert_is_action_enabled_mutually_recursive = false;
2575        }
2576        is_override_enabled
2577    }
2578
2579    /// Dart's `_OverridableActionMixin.isActionEnabled`.
2580    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2581        let intent_type = TypeId::of::<Self::Intent>();
2582        let override_action = self.get_override_action(app, intent_type, true);
2583        match override_action {
2584            Some(override_action) => self.is_override_action_enabled(app, override_action),
2585            None => self
2586                .overridable_data(app)
2587                .default_action
2588                .is_action_enabled(app),
2589        }
2590    }
2591
2592    /// Dart's `_OverridableActionMixin.isEnabled`.
2593    fn is_enabled(
2594        self: Handle<Self>,
2595        app: &mut App,
2596        intent: &Self::Intent,
2597        context: Option<BuildContext>,
2598    ) -> bool {
2599        debug_assert!(
2600            !self
2601                .overridable_data(app)
2602                .debug_assert_is_enabled_mutually_recursive
2603        );
2604        if cfg!(debug_assertions) {
2605            self.overridable_data_mut(app)
2606                .debug_assert_is_enabled_mutually_recursive = true;
2607        }
2608
2609        let erased = intent.as_intent();
2610        let override_action = self.get_override_action(app, erased.intent_type(), false);
2611        let default_action = self.overridable_data(app).default_action.clone();
2612        if let Some(override_action) = override_action {
2613            override_action.update_calling_action(app, Some(default_action.clone()));
2614        }
2615        let return_value = override_action
2616            .unwrap_or(default_action.handle())
2617            .is_enabled(app, intent.as_intent(), context);
2618        if let Some(override_action) = override_action {
2619            override_action.update_calling_action(app, None);
2620        }
2621        if cfg!(debug_assertions) {
2622            self.overridable_data_mut(app)
2623                .debug_assert_is_enabled_mutually_recursive = false;
2624        }
2625        return_value
2626    }
2627
2628    /// Dart's `_OverridableActionMixin.consumesKey`.
2629    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
2630        debug_assert!(
2631            !self
2632                .overridable_data(app)
2633                .debug_assert_consume_key_mutually_recursive
2634        );
2635        if cfg!(debug_assertions) {
2636            self.overridable_data_mut(app)
2637                .debug_assert_consume_key_mutually_recursive = true;
2638        }
2639        let erased = intent.as_intent();
2640        let override_action = self.get_override_action(app, erased.intent_type(), false);
2641        let default_action = self.overridable_data(app).default_action.clone();
2642        if let Some(override_action) = override_action {
2643            override_action.update_calling_action(app, Some(default_action.clone()));
2644        }
2645        let is_enabled = override_action
2646            .unwrap_or(default_action.handle())
2647            .consumes_key(app, intent.as_intent());
2648        if let Some(override_action) = override_action {
2649            override_action.update_calling_action(app, None);
2650        }
2651        if cfg!(debug_assertions) {
2652            self.overridable_data_mut(app)
2653                .debug_assert_consume_key_mutually_recursive = false;
2654        }
2655        is_enabled
2656    }
2657}
2658
2659/// Dart's `_OverridableAction`: the overridable form of a plain [`Action`].
2660pub struct OverridableAction<T: ActionIntent + ?Sized> {
2661    action: ActionData,
2662    overridable: OverridableActionData,
2663    intent: std::marker::PhantomData<fn(&T)>,
2664}
2665
2666impl<T: ActionIntent + ?Sized> OverridableAction<T> {
2667    /// Dart's `_OverridableAction(defaultAction:, lookupContext:)`; reached through
2668    /// [`AnyAction::overridable`].
2669    pub fn new(
2670        app: &mut App,
2671        default_action: ActionRef,
2672        lookup_context: BuildContext,
2673    ) -> Ref<OverridableAction<T>> {
2674        app.create(OverridableAction::<T> {
2675            action: ActionData::new(),
2676            overridable: OverridableActionData::new(default_action, lookup_context),
2677            intent: std::marker::PhantomData,
2678        })
2679    }
2680}
2681
2682impl<T: ActionIntent + ?Sized> Action for OverridableAction<T> {
2683    type Intent = T;
2684    crate::action_accessors!();
2685
2686    fn debug_fill_properties(
2687        self: Handle<Self>,
2688        app: &App,
2689        properties: &mut DiagnosticPropertiesBuilder,
2690    ) {
2691        properties.add(DiagnosticsProperty::<String>::new(
2692            "defaultAction",
2693            Some(app.get(self).overridable.default_action.to_string_short()),
2694        ));
2695    }
2696
2697    fn as_action(self: Handle<Self>) -> AnyAction {
2698        AnyAction::of_context::<Self>(self)
2699    }
2700
2701    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2702        ContextAction::is_enabled(self, app, intent, None)
2703    }
2704
2705    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2706        ContextAction::invoke(self, app, intent, None)
2707    }
2708
2709    fn make_overridable_action(
2710        self: Handle<Self>,
2711        app: &mut App,
2712        context: BuildContext,
2713    ) -> ActionRef {
2714        let default_action = self.overridable_data(app).default_action.clone();
2715        OverridableAction::<T>::new(app, default_action, context).into_erased()
2716    }
2717
2718    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2719        OverridableActionMixin::update_calling_action(self, app, value);
2720    }
2721
2722    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2723        OverridableActionMixin::is_action_enabled(self, app)
2724    }
2725
2726    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2727        OverridableActionMixin::consumes_key(self, app, intent)
2728    }
2729}
2730
2731impl<T: ActionIntent + ?Sized> ContextAction for OverridableAction<T> {
2732    fn is_enabled(
2733        self: Handle<Self>,
2734        app: &mut App,
2735        intent: &T,
2736        context: Option<BuildContext>,
2737    ) -> bool {
2738        OverridableActionMixin::is_enabled(self, app, intent, context)
2739    }
2740
2741    fn invoke(
2742        self: Handle<Self>,
2743        app: &mut App,
2744        intent: &T,
2745        context: Option<BuildContext>,
2746    ) -> Option<Rc<dyn Any>> {
2747        OverridableActionMixin::invoke(self, app, intent, context)
2748    }
2749}
2750
2751impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableAction<T> {
2752    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
2753        &app.get(self).overridable
2754    }
2755
2756    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
2757        &mut app.get_mut(self).overridable
2758    }
2759
2760    fn invoke_default_action(
2761        self: Handle<Self>,
2762        app: &mut App,
2763        intent: &T,
2764        _from_action: Option<AnyAction>,
2765        _context: Option<BuildContext>,
2766    ) -> Option<Rc<dyn Any>> {
2767        let default_action = self.overridable_data(app).default_action.handle();
2768        default_action.invoke(app, intent.as_intent(), None)
2769    }
2770}
2771
2772/// Dart's `_OverridableContextAction`: the overridable form of a [`ContextAction`].
2773pub struct OverridableContextAction<T: ActionIntent + ?Sized> {
2774    action: ActionData,
2775    overridable: OverridableActionData,
2776    intent: std::marker::PhantomData<fn(&T)>,
2777}
2778
2779impl<T: ActionIntent + ?Sized> OverridableContextAction<T> {
2780    /// Dart's `_OverridableContextAction(defaultAction:, lookupContext:)`; reached through
2781    /// [`AnyAction::overridable`].
2782    pub fn new(
2783        app: &mut App,
2784        default_action: ActionRef,
2785        lookup_context: BuildContext,
2786    ) -> Ref<OverridableContextAction<T>> {
2787        app.create(OverridableContextAction::<T> {
2788            action: ActionData::new(),
2789            overridable: OverridableActionData::new(default_action, lookup_context),
2790            intent: std::marker::PhantomData,
2791        })
2792    }
2793}
2794
2795impl<T: ActionIntent + ?Sized> Action for OverridableContextAction<T> {
2796    type Intent = T;
2797    crate::action_accessors!();
2798
2799    fn as_action(self: Handle<Self>) -> AnyAction {
2800        AnyAction::of_context::<Self>(self)
2801    }
2802
2803    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2804        ContextAction::is_enabled(self, app, intent, None)
2805    }
2806
2807    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2808        ContextAction::invoke(self, app, intent, None)
2809    }
2810
2811    fn make_overridable_action(
2812        self: Handle<Self>,
2813        app: &mut App,
2814        context: BuildContext,
2815    ) -> ActionRef {
2816        let default_action = self.overridable_data(app).default_action.clone();
2817        OverridableContextAction::<T>::new(app, default_action, context).into_erased()
2818    }
2819
2820    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2821        OverridableActionMixin::update_calling_action(self, app, value);
2822    }
2823
2824    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2825        OverridableActionMixin::is_action_enabled(self, app)
2826    }
2827
2828    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2829        OverridableActionMixin::consumes_key(self, app, intent)
2830    }
2831}
2832
2833impl<T: ActionIntent + ?Sized> ContextAction for OverridableContextAction<T> {
2834    fn is_enabled(
2835        self: Handle<Self>,
2836        app: &mut App,
2837        intent: &T,
2838        context: Option<BuildContext>,
2839    ) -> bool {
2840        OverridableActionMixin::is_enabled(self, app, intent, context)
2841    }
2842
2843    fn invoke(
2844        self: Handle<Self>,
2845        app: &mut App,
2846        intent: &T,
2847        context: Option<BuildContext>,
2848    ) -> Option<Rc<dyn Any>> {
2849        OverridableActionMixin::invoke(self, app, intent, context)
2850    }
2851}
2852
2853impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableContextAction<T> {
2854    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
2855        &app.get(self).overridable
2856    }
2857
2858    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
2859        &mut app.get_mut(self).overridable
2860    }
2861
2862    /// Wraps the default [`Action`] together with the calling context in case the override is
2863    /// not a [`ContextAction`] and thus has no access to the calling [`BuildContext`].
2864    fn invoke_override(
2865        self: Handle<Self>,
2866        app: &mut App,
2867        override_action: AnyAction,
2868        intent: &T,
2869        context: Option<BuildContext>,
2870    ) -> Option<Rc<dyn Any>> {
2871        debug_assert!(context.is_some());
2872        debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
2873        if cfg!(debug_assertions) {
2874            self.overridable_data_mut(app)
2875                .debug_assert_mutually_recursive = true;
2876        }
2877
2878        let default_action = self.overridable_data(app).default_action.clone();
2879        let invoke_context = context.expect("an overridable context action is invoked with one");
2880        let wrapped_default =
2881            ContextActionToActionAdapter::<T>::new(app, invoke_context, default_action);
2882        override_action.update_calling_action(app, Some(wrapped_default.into_erased()));
2883        let return_value = override_action.invoke(app, intent.as_intent(), context);
2884        override_action.update_calling_action(app, None);
2885
2886        if cfg!(debug_assertions) {
2887            self.overridable_data_mut(app)
2888                .debug_assert_mutually_recursive = false;
2889        }
2890        return_value
2891    }
2892
2893    fn invoke_default_action(
2894        self: Handle<Self>,
2895        app: &mut App,
2896        intent: &T,
2897        _from_action: Option<AnyAction>,
2898        context: Option<BuildContext>,
2899    ) -> Option<Rc<dyn Any>> {
2900        let default_action = self.overridable_data(app).default_action.handle();
2901        default_action.invoke(app, intent.as_intent(), context)
2902    }
2903}
2904
2905/// Dart's `_ContextActionToActionAdapter`: a plain [`Action`] that calls a [`ContextAction`]
2906/// with a fixed context.
2907struct ContextActionToActionAdapter<T: ActionIntent + ?Sized> {
2908    action: ActionData,
2909    invoke_context: BuildContext,
2910    wrapped: ActionRef,
2911    intent: std::marker::PhantomData<fn(&T)>,
2912}
2913
2914impl<T: ActionIntent + ?Sized> ContextActionToActionAdapter<T> {
2915    fn new(
2916        app: &mut App,
2917        invoke_context: BuildContext,
2918        wrapped: ActionRef,
2919    ) -> Ref<ContextActionToActionAdapter<T>> {
2920        app.create(ContextActionToActionAdapter::<T> {
2921            action: ActionData::new(),
2922            invoke_context,
2923            wrapped,
2924            intent: std::marker::PhantomData,
2925        })
2926    }
2927}
2928
2929impl<T: ActionIntent + ?Sized> Action for ContextActionToActionAdapter<T> {
2930    type Intent = T;
2931    crate::action_accessors!();
2932
2933    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2934        let wrapped = app.get(self).wrapped.handle();
2935        wrapped.update_calling_action(app, value);
2936    }
2937
2938    fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
2939        app.get(self).wrapped.calling_action(app)
2940    }
2941
2942    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2943        let (wrapped, invoke_context) = {
2944            let this = app.get(self);
2945            (this.wrapped.handle(), this.invoke_context)
2946        };
2947        wrapped.is_enabled(app, intent.as_intent(), Some(invoke_context))
2948    }
2949
2950    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2951        app.get(self).wrapped.is_action_enabled(app)
2952    }
2953
2954    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2955        let wrapped = app.get(self).wrapped.handle();
2956        wrapped.consumes_key(app, intent.as_intent())
2957    }
2958
2959    fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
2960        self.action_data_mut(app)
2961            .listeners
2962            .push(Rc::clone(&listener));
2963        let wrapped = app.get(self).wrapped.handle();
2964        wrapped.add_action_listener(app, listener);
2965    }
2966
2967    fn remove_action_listener(
2968        self: Handle<Self>,
2969        app: &mut App,
2970        listener: &ActionListenerCallback,
2971    ) {
2972        let listeners = &mut self.action_data_mut(app).listeners;
2973        if let Some(index) = listeners
2974            .iter()
2975            .position(|registered| Rc::ptr_eq(registered, listener))
2976        {
2977            listeners.remove(index);
2978        }
2979        let wrapped = app.get(self).wrapped.handle();
2980        wrapped.remove_action_listener(app, listener);
2981    }
2982
2983    fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
2984        app.get(self).wrapped.notify_action_listeners(app);
2985    }
2986
2987    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2988        let (wrapped, invoke_context) = {
2989            let this = app.get(self);
2990            (this.wrapped.handle(), this.invoke_context)
2991        };
2992        wrapped.invoke(app, intent.as_intent(), Some(invoke_context))
2993    }
2994}
2995
2996#[cfg(test)]
2997mod tests {
2998    use std::cell::{Cell, RefCell};
2999
3000    use waft_embedder::Offset;
3001
3002    use super::*;
3003    use crate::testing::{TestPointer, test_widgets};
3004    use crate::widgets::basic::{Builder, SizedBox};
3005    use crate::widgets::focus_manager::{FocusHighlightStrategy, FocusNodeLeaf};
3006
3007    #[derive(Debug)]
3008    struct CountIntent {
3009        amount: i32,
3010    }
3011
3012    impl Intent for CountIntent {
3013        fn as_any(&self) -> &dyn Any {
3014            self
3015        }
3016    }
3017
3018    #[derive(Debug)]
3019    struct OtherIntent;
3020
3021    impl Intent for OtherIntent {
3022        fn as_any(&self) -> &dyn Any {
3023            self
3024        }
3025    }
3026
3027    /// An action that records that it ran and doubles the intent's amount.
3028    struct CountAction {
3029        action: ActionData,
3030        log: Rc<RefCell<Vec<String>>>,
3031        name: &'static str,
3032        enabled: bool,
3033    }
3034
3035    impl CountAction {
3036        fn new(
3037            app: &mut App,
3038            log: &Rc<RefCell<Vec<String>>>,
3039            name: &'static str,
3040        ) -> Ref<CountAction> {
3041            app.create(CountAction {
3042                action: ActionData::new(),
3043                log: Rc::clone(log),
3044                name,
3045                enabled: true,
3046            })
3047        }
3048
3049        fn set_enabled(self: Handle<Self>, app: &mut App, enabled: bool) {
3050            app.get_mut(self).enabled = enabled;
3051            self.notify_action_listeners(app);
3052        }
3053    }
3054
3055    impl Action for CountAction {
3056        type Intent = CountIntent;
3057        crate::action_accessors!();
3058
3059        fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
3060            app.get(self).enabled
3061        }
3062
3063        fn invoke(self: Handle<Self>, app: &mut App, intent: &CountIntent) -> Option<Rc<dyn Any>> {
3064            let (log, name) = {
3065                let this = app.get(self);
3066                (Rc::clone(&this.log), this.name)
3067            };
3068            log.borrow_mut().push(format!("{name}:{}", intent.amount));
3069            Some(Rc::new(intent.amount * 2))
3070        }
3071    }
3072
3073    fn map(intent_type: TypeId, action: ActionRef) -> HashMap<TypeId, ActionRef> {
3074        HashMap::from([(intent_type, action)])
3075    }
3076
3077    /// A `Builder` that records its own context.
3078    fn probe(sink: &Rc<Cell<Option<BuildContext>>>) -> WidgetRef {
3079        let sink = Rc::clone(sink);
3080        Builder::new(move |_app, context| {
3081            sink.set(Some(context));
3082            SizedBox::shrink().into_widget()
3083        })
3084        .into_widget()
3085    }
3086
3087    fn as_i32(result: Option<Rc<dyn Any>>) -> Option<i32> {
3088        result.and_then(|value| value.downcast_ref::<i32>().copied())
3089    }
3090
3091    #[test]
3092    fn invoke_reaches_the_nearest_actions_widget_that_maps_the_intent() {
3093        test_widgets(|tester| {
3094            let mut app = tester.cell.borrow_mut();
3095            let log: Rc<RefCell<Vec<String>>> = Rc::default();
3096            let outer = CountAction::new(&mut app, &log, "outer");
3097            let inner = CountAction::new(&mut app, &log, "inner");
3098            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3099            drop(app);
3100            tester.pump_widget(
3101                Actions::new(
3102                    map(TypeId::of::<CountIntent>(), outer.erase()),
3103                    Actions::new(
3104                        map(TypeId::of::<CountIntent>(), inner.erase()),
3105                        probe(&captured),
3106                    ),
3107                )
3108                .into_widget(),
3109            );
3110            let mut app = tester.cell.borrow_mut();
3111            let context = captured.get().expect("the builder ran");
3112
3113            let result = Actions::invoke(&mut app, context, &CountIntent { amount: 2 });
3114            assert_eq!(*log.borrow(), ["inner:2"]);
3115            assert_eq!(as_i32(result), Some(4));
3116
3117            // A disabled action still stops the search, so nothing is invoked.
3118            inner.set_enabled(&mut app, false);
3119            log.borrow_mut().clear();
3120            let result = Actions::maybe_invoke(&mut app, context, &CountIntent { amount: 3 });
3121            assert!(log.borrow().is_empty());
3122            assert_eq!(as_i32(result), None);
3123        });
3124    }
3125
3126    #[test]
3127    fn invoke_walks_past_an_actions_widget_that_does_not_map_the_intent() {
3128        test_widgets(|tester| {
3129            let mut app = tester.cell.borrow_mut();
3130            let log: Rc<RefCell<Vec<String>>> = Rc::default();
3131            let outer = CountAction::new(&mut app, &log, "outer");
3132            let unrelated = DoNothingAction::new(&mut app);
3133            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3134            drop(app);
3135            tester.pump_widget(
3136                Actions::new(
3137                    map(TypeId::of::<CountIntent>(), outer.erase()),
3138                    Actions::new(
3139                        map(TypeId::of::<OtherIntent>(), unrelated.erase()),
3140                        probe(&captured),
3141                    ),
3142                )
3143                .into_widget(),
3144            );
3145            let mut app = tester.cell.borrow_mut();
3146            let context = captured.get().expect("the builder ran");
3147
3148            let result = Actions::invoke(&mut app, context, &CountIntent { amount: 5 });
3149            assert_eq!(*log.borrow(), ["outer:5"]);
3150            assert_eq!(as_i32(result), Some(10));
3151        });
3152    }
3153
3154    #[test]
3155    fn maybe_find_returns_the_bound_action_and_handler_only_when_it_is_enabled() {
3156        test_widgets(|tester| {
3157            let mut app = tester.cell.borrow_mut();
3158            let log: Rc<RefCell<Vec<String>>> = Rc::default();
3159            let action = CountAction::new(&mut app, &log, "action");
3160            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3161            drop(app);
3162            tester.pump_widget(
3163                Actions::new(
3164                    map(TypeId::of::<CountIntent>(), action.erase()),
3165                    probe(&captured),
3166                )
3167                .into_widget(),
3168            );
3169            let mut app = tester.cell.borrow_mut();
3170            let context = captured.get().expect("the builder ran");
3171
3172            assert_eq!(
3173                Actions::maybe_find(&mut app, context, TypeId::of::<CountIntent>()),
3174                Some(Action::as_action(action.handle()))
3175            );
3176            assert_eq!(
3177                Actions::maybe_find(&mut app, context, TypeId::of::<OtherIntent>()),
3178                None
3179            );
3180
3181            let intent: IntentRef = Rc::new(CountIntent { amount: 7 });
3182            let handler = Actions::handler(&mut app, context, Rc::clone(&intent))
3183                .expect("an enabled action has a handler");
3184            handler.call(&mut app);
3185            assert_eq!(*log.borrow(), ["action:7"]);
3186
3187            action.set_enabled(&mut app, false);
3188            assert!(Actions::handler(&mut app, context, intent).is_none());
3189        });
3190    }
3191
3192    #[test]
3193    fn an_overridable_action_prefers_the_override_above_its_lookup_context() {
3194        test_widgets(|tester| {
3195            let mut app = tester.cell.borrow_mut();
3196            let log: Rc<RefCell<Vec<String>>> = Rc::default();
3197            let override_action = CountAction::new(&mut app, &log, "override");
3198            let default_action = CountAction::new(&mut app, &log, "default");
3199            let outer_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
3200            let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
3201            let outer_sink = Rc::clone(&outer_context);
3202            let inner_sink = Rc::clone(&inner_context);
3203            drop(app);
3204            tester.pump_widget(
3205                Actions::new(
3206                    map(TypeId::of::<CountIntent>(), override_action.erase()),
3207                    Builder::new(move |_app, context| {
3208                        outer_sink.set(Some(context));
3209                        probe(&inner_sink)
3210                    }),
3211                )
3212                .into_widget(),
3213            );
3214            let mut app = tester.cell.borrow_mut();
3215            let lookup_context = outer_context.get().expect("the builder ran");
3216
3217            let overridable =
3218                AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
3219            let intent = CountIntent { amount: 1 };
3220            overridable.invoke(&mut app, &intent, Some(lookup_context));
3221            assert_eq!(*log.borrow(), ["override:1"]);
3222
3223            // With no override above the lookup context, the default action runs.
3224        });
3225        test_widgets(|tester| {
3226            let mut app = tester.cell.borrow_mut();
3227            let log: Rc<RefCell<Vec<String>>> = Rc::default();
3228            let default_action = CountAction::new(&mut app, &log, "default");
3229            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3230            drop(app);
3231            tester.pump_widget(probe(&captured));
3232            let mut app = tester.cell.borrow_mut();
3233            let lookup_context = captured.get().expect("the builder ran");
3234            let intent = CountIntent { amount: 1 };
3235            let overridable =
3236                AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
3237            overridable.invoke(&mut app, &intent, Some(lookup_context));
3238            assert_eq!(*log.borrow(), ["default:1"]);
3239        });
3240    }
3241
3242    #[test]
3243    fn the_detector_reports_the_focus_highlight() {
3244        test_widgets(|tester| {
3245            let mut app = tester.cell.borrow_mut();
3246            FocusManager::instance(&mut app)
3247                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3248            let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3249            let focused: Rc<RefCell<Vec<bool>>> = Rc::default();
3250            let highlight_sink = Rc::clone(&focus_highlights);
3251            let focus_sink = Rc::clone(&focused);
3252            drop(app);
3253            tester.pump_widget(
3254                FocusableActionDetector::new(SizedBox::expand())
3255                    .autofocus(true)
3256                    .on_show_focus_highlight(move |_app, show| {
3257                        highlight_sink.borrow_mut().push(show)
3258                    })
3259                    .on_focus_change(move |_app, has_focus| focus_sink.borrow_mut().push(has_focus))
3260                    .into_widget(),
3261            );
3262            // The post-frame callback `init_state` registered decides whether a highlight may show.
3263            tester.pump();
3264
3265            assert_eq!(*focused.borrow(), [true]);
3266            assert_eq!(*focus_highlights.borrow(), [true]);
3267        });
3268    }
3269
3270    #[test]
3271    fn the_detector_reports_the_hover_highlight() {
3272        test_widgets(|tester| {
3273            let mut app = tester.cell.borrow_mut();
3274            FocusManager::instance(&mut app)
3275                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3276            let hover_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3277            let sink = Rc::clone(&hover_highlights);
3278            drop(app);
3279            tester.pump_widget(
3280                FocusableActionDetector::new(SizedBox::expand())
3281                    .on_show_hover_highlight(move |_app, show| sink.borrow_mut().push(show))
3282                    .into_widget(),
3283            );
3284            tester.pump();
3285
3286            let mut mouse = TestPointer::mouse(1, 0);
3287            tester.move_to(&mut mouse, Offset::new(10.0, 10.0), false);
3288            assert_eq!(*hover_highlights.borrow(), [true]);
3289
3290            tester.move_to(&mut mouse, Offset::new(10_000.0, 10_000.0), false);
3291            assert_eq!(*hover_highlights.borrow(), [true, false]);
3292        });
3293    }
3294
3295    #[test]
3296    fn a_disabled_detector_shows_no_highlight() {
3297        test_widgets(|tester| {
3298            let mut app = tester.cell.borrow_mut();
3299            FocusManager::instance(&mut app)
3300                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3301            let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3302            let sink = Rc::clone(&focus_highlights);
3303            let node = crate::FocusNode::new(&mut app);
3304            let detector = |enabled: bool, sink: Rc<RefCell<Vec<bool>>>| {
3305                FocusableActionDetector::new(SizedBox::expand())
3306                    .enabled(enabled)
3307                    .focus_node(node.erase())
3308                    .autofocus(true)
3309                    .on_show_focus_highlight(move |_app, show| sink.borrow_mut().push(show))
3310                    .into_widget()
3311            };
3312            drop(app);
3313            tester.pump_widget(detector(false, Rc::clone(&sink)));
3314            tester.pump();
3315            let mut app = tester.cell.borrow_mut();
3316            // A disabled detector sets `Focus.canRequestFocus` to false, so nothing is focused.
3317            node.request_focus(&mut app, None);
3318            app.drain_microtasks();
3319            assert!(!node.has_primary_focus(&app));
3320            assert!(focus_highlights.borrow().is_empty());
3321
3322            drop(app);
3323            tester.pump_widget(detector(true, Rc::clone(&sink)));
3324            tester.pump();
3325            let mut app = tester.cell.borrow_mut();
3326            node.request_focus(&mut app, None);
3327            app.drain_microtasks();
3328            assert!(node.has_primary_focus(&app));
3329            assert_eq!(*focus_highlights.borrow(), [true]);
3330        });
3331    }
3332}
3333
3334#[cfg(test)]
3335mod diagnostics_tests {
3336    use std::collections::HashMap;
3337
3338    use waft_rendering::testing::ignoring_hash_codes;
3339
3340    use super::*;
3341    use crate::Container;
3342    use crate::testing::describe_properties;
3343
3344    /// `actions_test.dart`, "default Intent debugFillProperties".
3345    #[test]
3346    fn a_default_intent_adds_no_properties() {
3347        let intent = ActivateIntent;
3348        assert_eq!(
3349            describe_properties(|properties| intent.debug_fill_properties(properties)),
3350            Vec::<String>::new()
3351        );
3352    }
3353
3354    /// `actions_test.dart`, "default Actions debugFillProperties".
3355    #[test]
3356    fn the_default_actions_describe_their_dispatcher_and_empty_map() {
3357        let actions = Actions::new(HashMap::new(), Container::new())
3358            .dispatcher(Rc::new(PlainActionDispatcher::new()));
3359        let cell = waft_foundation::AppCell::new();
3360        let app = cell.borrow();
3361        let description =
3362            describe_properties(|properties| actions.debug_fill_properties(&app, properties));
3363        assert_eq!(description.len(), 2);
3364        assert_eq!(
3365            ignoring_hash_codes(&description.join("\n")),
3366            "dispatcher: ActionDispatcher#00000\nactions: {}"
3367        );
3368    }
3369}