Skip to main content

waft_widgets/widgets/
focus_manager.rs

1//! Flutter counterpart: `widgets/focus_manager.dart`.
2//!
3//! The focus tree: [`FocusNode`] and [`FocusScopeNode`] (one arena struct per Dart leaf,
4//! joined by the type-erased handle [`AnyFocusNode`]), the [`FocusAttachment`] a host widget uses to
5//! keep a node in the tree, and the [`FocusManager`] the `BuildOwner` holds.
6
7use std::fmt;
8use std::rc::Rc;
9
10use waft_embedder::{AppLifecycleState, Offset, PointerDeviceKind, Rect, Size, TargetPlatform};
11use waft_foundation::{
12    App, ChangeNotifier, ChangeNotifierData, DiagnosticLevel, DiagnosticPropertiesBuilder,
13    DiagnosticableTreeNode, DiagnosticsNode, DiagnosticsProperty, DiagnosticsTreeStyle,
14    FlagProperty, Handle, HandleId, IterableProperty, K_IS_WEB, ListenableHandle, Listener,
15    OptionRetained, Ref, Retained, ValueChanged, describe_identity,
16};
17use waft_gestures::{GestureBinding, PointerEvent, PointerRoute};
18use waft_rendering::RendererBinding;
19use waft_scheduler::{SchedulerBinding, SchedulerPhase};
20use waft_services::{HardwareKeyboard, KeyEvent, KeyEventCallback};
21
22use crate::binding::{WidgetsBinding, WidgetsBindingObserver, WidgetsBindingObserverRef};
23use crate::framework::BuildContext;
24use crate::widgets::focus_traversal::{FocusTraversalGroup, TraversalDirection};
25
26/// An enum that describes how to handle a key event handled by a
27/// [`FocusOnKeyEventCallback`].
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum KeyEventResult {
30    /// The key event has been handled, and the event should not be propagated to other key
31    /// event handlers.
32    Handled,
33
34    /// The key event has not been handled, and the event should continue to be propagated to
35    /// other key event handlers, even non-Flutter ones.
36    Ignored,
37
38    /// The key event has not been handled, but the key event should not be propagated to
39    /// other key event handlers.
40    ///
41    /// It will be returned to the platform embedding to be propagated to text fields and
42    /// non-Flutter key event handlers on the platform.
43    SkipRemainingHandlers,
44}
45
46/// Combine the results returned by multiple [`FocusOnKeyEventCallback`]s.
47///
48/// If any callback returns [`KeyEventResult::Handled`], the node considers the message
49/// handled; otherwise, if any callback returns [`KeyEventResult::SkipRemainingHandlers`], the
50/// node skips the remaining handlers without preventing the platform to handle; otherwise the
51/// node is ignored.
52pub fn combine_key_event_results(
53    results: impl IntoIterator<Item = KeyEventResult>,
54) -> KeyEventResult {
55    let mut has_skip_remaining_handlers = false;
56    for result in results {
57        match result {
58            KeyEventResult::Handled => return KeyEventResult::Handled,
59            KeyEventResult::SkipRemainingHandlers => has_skip_remaining_handlers = true,
60            KeyEventResult::Ignored => {}
61        }
62    }
63    if has_skip_remaining_handlers {
64        KeyEventResult::SkipRemainingHandlers
65    } else {
66        KeyEventResult::Ignored
67    }
68}
69
70/// Signature of a callback used by `Focus::on_key_event` and `FocusScope::on_key_event` to
71/// receive key events.
72///
73/// The `node` is the node that received the event.
74///
75/// Returns a [`KeyEventResult`] that describes how, and whether, the key event was handled.
76pub type FocusOnKeyEventCallback = Rc<dyn Fn(&mut App, AnyFocusNode, &KeyEvent) -> KeyEventResult>;
77
78/// Signature of a callback used by [`FocusManager::add_early_key_event_handler`] and
79/// [`FocusManager::add_late_key_event_handler`].
80///
81/// The `event` parameter is a [`KeyEvent`] that is being sent to the callback to be handled.
82///
83/// The [`KeyEventResult`] return value indicates whether or not the event will continue to be
84/// propagated. If the value returned is [`KeyEventResult::Handled`] or
85/// [`KeyEventResult::SkipRemainingHandlers`], then the event will not continue to be
86/// propagated.
87pub type OnKeyEventCallback = Rc<dyn Fn(&mut App, &KeyEvent) -> KeyEventResult>;
88
89/// Signature of a closure registered with [`FocusManager::add_highlight_mode_listener`].
90pub type HighlightModeListener = Rc<dyn Fn(&mut App, FocusHighlightMode)>;
91
92/// Represents a pending autofocus request.
93struct Autofocus {
94    scope: Ref<FocusScopeNode>,
95    autofocus_node: FocusNodeRef,
96}
97
98impl Autofocus {
99    /// Applies the autofocus request, if the node is still attached to the original scope and
100    /// the scope has no focused child.
101    ///
102    /// The widget tree is responsible for calling reparent/detach on attached nodes to keep
103    /// their parent/manager information up-to-date, so here we can safely check if the
104    /// scope/node involved in each autofocus request is still attached, and discard the ones
105    /// which are no longer attached to the original manager.
106    fn apply_if_valid(self, app: &mut App, manager: Handle<FocusManager>) {
107        let scope = self.scope.as_node();
108        let should_apply = (scope.parent(app).is_some() || self.scope == *manager.root_scope(app))
109            && scope.manager(app) == Some(manager)
110            && self.scope.focused_child(app).is_none()
111            && self.autofocus_node.ancestors(app).contains(&scope);
112        if should_apply {
113            self.autofocus_node.do_request_focus(app, true);
114        }
115    }
116}
117
118/// An attachment point for a [`FocusNode`].
119///
120/// Using a [`FocusAttachment`] is rarely needed, unless building something akin to the
121/// `Focus` or `FocusScope` widgets from scratch.
122///
123/// Once created, a [`FocusNode`] must be attached to the widget tree by its _host_
124/// `StatefulWidget` via a [`FocusAttachment`] object. [`FocusAttachment`]s are owned by the
125/// `StatefulWidget` that hosts a [`FocusNode`] or [`FocusScopeNode`]. There can be multiple
126/// [`FocusAttachment`]s for each [`FocusNode`], but the node will only ever be attached to one
127/// of them at a time.
128///
129/// This attachment is created by calling [`AnyFocusNode::attach`], usually from the host
130/// widget's `State::init_state` method. If the widget is updated to have a different focus
131/// node, then the new node needs to be attached in `State::did_update_widget`, after calling
132/// [`detach`](Self::detach) on the previous [`FocusAttachment`]. Once detached, the attachment
133/// is defunct and will no longer make changes to the [`FocusNode`] through
134/// [`reparent`](Self::reparent).
135///
136/// Without these attachment points, it would be possible for a focus node to simultaneously be
137/// attached to more than one part of the widget tree during the build stage.
138pub struct FocusAttachment {
139    /// The focus node that this attachment manages an attachment for. The node may not yet
140    /// have a parent, or may have been detached from this attachment, so don't count on this
141    /// node being in a usable state.
142    node: AnyFocusNode,
143}
144
145impl FocusAttachment {
146    /// A private constructor, because [`FocusAttachment`]s are only to be created by
147    /// [`AnyFocusNode::attach`].
148    fn new(app: &mut App, node: AnyFocusNode) -> Ref<FocusAttachment> {
149        app.create(FocusAttachment { node })
150    }
151
152    /// Returns true if the associated node is attached to this attachment.
153    ///
154    /// It is possible to be attached to the widget tree, but not be placed in the focus tree
155    /// (i.e. to not have a parent yet in the focus tree).
156    pub fn is_attached(self: Handle<Self>, app: &App) -> bool {
157        let node = app.get(self).node;
158        node.data(app).attachment.handle() == Some(self)
159    }
160
161    /// Detaches the [`FocusNode`] this attachment point is associated with from the focus
162    /// tree, and disconnects it from this attachment point.
163    ///
164    /// Calling [`AnyFocusNode::dispose`] will also automatically detach the node.
165    pub fn detach(self: Handle<Self>, app: &mut App) {
166        let node = app.get(self).node;
167        if self.is_attached(app) {
168            let marked_for_focus = node
169                .manager(app)
170                .map(|manager| app.get(manager).marked_for_focus.handle());
171            if node.has_primary_focus(app) || marked_for_focus == Some(Some(node)) {
172                node.unfocus(app, UnfocusDisposition::PreviouslyFocusedChild);
173            }
174            // This node is no longer in the tree, so shouldn't send notifications anymore.
175            if let Some(manager) = node.manager(app) {
176                manager.mark_detached(app, node);
177            }
178            if let Some(parent) = node.data(app).parent {
179                parent.remove_child(app, node, true);
180            }
181            node.data_mut(app).attachment = None;
182            debug_assert!(
183                !node.has_primary_focus(app),
184                "Node {node:?} still has primary focus while being detached."
185            );
186            debug_assert!(
187                node.manager(app)
188                    .is_none_or(|manager| app.get(manager).marked_for_focus.handle() != Some(node)),
189                "Node {node:?} still marked for focus while being detached."
190            );
191        }
192        debug_assert!(!self.is_attached(app));
193    }
194
195    /// Ensures that the [`FocusNode`] attached at this attachment point has the proper parent
196    /// node, changing it if necessary.
197    ///
198    /// If given, ensures that the given `parent` node is the parent of the node that is
199    /// attached at this attachment point, changing it if necessary. However, it is usually not
200    /// necessary to supply an explicit parent, since [`reparent`](Self::reparent) will use
201    /// `Focus::maybe_of` to determine the correct parent node for the context given in
202    /// [`AnyFocusNode::attach`].
203    ///
204    /// If [`is_attached`](Self::is_attached) is false, then calling this method does nothing.
205    ///
206    /// Should be called whenever the associated widget is rebuilt in order to maintain the
207    /// focus hierarchy.
208    ///
209    /// A `StatefulWidget` that hosts a [`FocusNode`] should call this method on the node it
210    /// hosts during its `State::build` or `State::did_change_dependencies` methods in case the
211    /// widget is moved from one location in the tree to another location that has a different
212    /// `FocusScope` or context.
213    ///
214    /// The optional `parent` argument must be supplied when not using `Focus` and `FocusScope`
215    /// widgets to build the focus tree, or if there is a need to supply the parent explicitly
216    /// (which are both uncommon).
217    pub fn reparent(self: Handle<Self>, app: &mut App, parent: Option<AnyFocusNode>) {
218        if self.is_attached(app) {
219            let node = app.get(self).node;
220            let context = node.data(app).context;
221            debug_assert!(context.is_some());
222            let context = context.expect("an attached node has a context");
223            let parent = parent
224                .or_else(|| crate::widgets::focus_scope::Focus::maybe_of(app, context, true, true))
225                .or_else(|| {
226                    context
227                        .owner(app)
228                        .map(|owner| owner.focus_manager(app))
229                        .map(|manager| manager.root_scope(app).as_node())
230                })
231                .expect("the element's build owner has a focus manager");
232            parent.reparent_child(app, node);
233        }
234    }
235}
236
237/// Describe what should happen after [`AnyFocusNode::unfocus`] is called.
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
239pub enum UnfocusDisposition {
240    /// Focus the nearest focusable enclosing scope of this node, but do not descend to locate
241    /// the leaf [`FocusScopeNode::focused_child`] the way
242    /// [`PreviouslyFocusedChild`](Self::PreviouslyFocusedChild) does.
243    ///
244    /// Focusing the scope in this way clears the [`FocusScopeNode::focused_child`] history for
245    /// the enclosing scope when it receives focus. Because of this, calling a traversal method
246    /// like `FocusNode.nextFocus` after unfocusing will cause the `FocusTraversalPolicy` to
247    /// pick the node it thinks should be first in the scope.
248    ///
249    /// This is the default disposition for [`AnyFocusNode::unfocus`].
250    #[default]
251    Scope,
252
253    /// Focus the previously focused child of the nearest focusable enclosing scope of this
254    /// node.
255    ///
256    /// If there is no previously focused child, then this is equivalent to using the
257    /// [`Scope`](Self::Scope) disposition.
258    ///
259    /// Unfocusing with this disposition will cause [`AnyFocusNode::unfocus`] to walk up the
260    /// tree to the nearest focusable enclosing scope, then start to walk down the tree, looking
261    /// for a focused child at its [`FocusScopeNode::focused_child`].
262    ///
263    /// If the [`FocusScopeNode::focused_child`] is a scope, then look for its
264    /// [`FocusScopeNode::focused_child`], and so on, finding the leaf
265    /// [`FocusScopeNode::focused_child`] that is not a scope, or, failing that, a leaf scope
266    /// that has no focused child.
267    PreviouslyFocusedChild,
268}
269
270// ---------------------------------------------------------------------------------------------
271// FocusNode
272
273/// The fields Dart's `FocusNode` declares; every focus node leaf carries this bag under the
274/// field `focus_node`.
275pub struct FocusNodeData {
276    skip_traversal: bool,
277    can_request_focus: bool,
278    descendants_are_focusable: bool,
279    descendants_are_traversable: bool,
280    context: Option<BuildContext>,
281    on_key_event: Option<FocusOnKeyEventCallback>,
282    manager: Option<Handle<FocusManager>>,
283    ancestors: Option<Vec<AnyFocusNode>>,
284    descendants: Option<Vec<FocusNodeRef>>,
285    has_keyboard_token: bool,
286    parent: Option<AnyFocusNode>,
287    children: Vec<FocusNodeRef>,
288    debug_label: Option<String>,
289    attachment: Option<Ref<FocusAttachment>>,
290    enclosing_scope: Option<Handle<FocusScopeNode>>,
291    request_focus_when_reparented: bool,
292}
293
294impl FocusNodeData {
295    /// The bag of a freshly created node: Dart's constructor defaults.
296    pub fn new() -> FocusNodeData {
297        FocusNodeData {
298            skip_traversal: false,
299            can_request_focus: true,
300            descendants_are_focusable: true,
301            descendants_are_traversable: true,
302            context: None,
303            on_key_event: None,
304            manager: None,
305            ancestors: None,
306            descendants: None,
307            has_keyboard_token: false,
308            parent: None,
309            children: Vec::new(),
310            debug_label: None,
311            attachment: None,
312            enclosing_scope: None,
313            request_focus_when_reparented: false,
314        }
315    }
316}
317
318impl Default for FocusNodeData {
319    fn default() -> FocusNodeData {
320        FocusNodeData::new()
321    }
322}
323
324/// The accessors [`FocusNodeLeaf`] asks for, for a struct whose bag is the field `focus_node`.
325#[macro_export]
326macro_rules! focus_node_accessors {
327    () => {
328        fn focus_node_data(
329            self: ::waft_foundation::Handle<Self>,
330            app: &::waft_foundation::App,
331        ) -> &$crate::FocusNodeData {
332            &app.get(self).focus_node
333        }
334
335        fn focus_node_data_mut(
336            self: ::waft_foundation::Handle<Self>,
337            app: &mut ::waft_foundation::App,
338        ) -> &mut $crate::FocusNodeData {
339            &mut app.get_mut(self).focus_node
340        }
341    };
342}
343
344/// A concrete focus node: Dart's `FocusNode` and its one subclass [`FocusScopeNode`].
345///
346/// The trait holds the members a superclass body dispatches to the leaf ([`nearest_scope`],
347/// [`descendants_are_focusable`], [`traversal_children`], [`traversal_descendants`],
348/// [`do_request_focus`], and Dart's `node is FocusScopeNode` as [`as_scope`]), plus the
349/// [`as_node`] type-erased handle and one-line forwarders for the shared members, which live
350/// on [`AnyFocusNode`] because a node reaches its parent and children through that handle.
351///
352/// The defaults are `FocusNode`'s own bodies; [`FocusScopeNode`] overrides them and calls
353/// `FocusNode::…` where Dart writes `super.…`.
354///
355/// [`nearest_scope`]: Self::nearest_scope
356/// [`descendants_are_focusable`]: Self::descendants_are_focusable
357/// [`traversal_children`]: Self::traversal_children
358/// [`traversal_descendants`]: Self::traversal_descendants
359/// [`do_request_focus`]: Self::do_request_focus
360/// [`as_scope`]: Self::as_scope
361/// [`as_node`]: Self::as_node
362pub trait FocusNodeLeaf: ChangeNotifier + Sized + 'static {
363    /// Dart's `FocusNode` fields, held under the field `focus_node`
364    /// ([`focus_node_accessors!`](crate::focus_node_accessors)).
365    fn focus_node_data(self: Handle<Self>, app: &App) -> &FocusNodeData;
366
367    /// See [`focus_node_data`](Self::focus_node_data).
368    fn focus_node_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusNodeData;
369
370    /// This node as the erased [`AnyFocusNode`] — what to pass where a Dart API takes a
371    /// `FocusNode`.
372    ///
373    /// The object is untouched; this mints an erased second handle to it, so concrete members
374    /// stay reachable through the typed one.
375    fn as_node(self: Handle<Self>) -> AnyFocusNode {
376        AnyFocusNode {
377            id: self.id(),
378            vtable: const { &FocusNodeVTable::of::<Self>() },
379        }
380    }
381
382    /// Dart's `node is FocusScopeNode`.
383    fn as_scope(self: Handle<Self>) -> Option<Handle<FocusScopeNode>> {
384        let _ = self;
385        None
386    }
387
388    /// Returns the nearest enclosing scope node above this node, including this node, if it's
389    /// a scope.
390    fn nearest_scope(self: Handle<Self>, app: &mut App) -> Option<Handle<FocusScopeNode>> {
391        FocusNode::nearest_scope(self.as_node(), app)
392    }
393
394    /// If false, will disable focus for all of this node's descendants.
395    fn descendants_are_focusable(self: Handle<Self>, app: &App) -> bool {
396        FocusNode::descendants_are_focusable(self.as_node(), app)
397    }
398
399    /// An iterator over the children that are allowed to be traversed by the
400    /// `FocusTraversalPolicy`.
401    fn traversal_children(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
402        FocusNode::traversal_children(self.as_node(), app)
403    }
404
405    /// Returns all descendants which do not have the `skip_traversal` and do have the
406    /// `can_request_focus` flag set.
407    fn traversal_descendants(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
408        FocusNode::traversal_descendants(self.as_node(), app)
409    }
410
411    /// Requests the primary focus for this node; overridden by [`FocusScopeNode`].
412    fn do_request_focus(self: Handle<Self>, app: &mut App, find_first_focus: bool) {
413        FocusNode::do_request_focus(self.as_node(), app, find_first_focus);
414    }
415
416    /// Dart's `FocusNode.debugFillProperties`, which [`FocusScopeNode`]'s own body calls where
417    /// Dart writes `super`.
418    fn debug_fill_properties(
419        self: Handle<Self>,
420        app: &App,
421        properties: &mut DiagnosticPropertiesBuilder,
422    ) {
423        fill_focus_node_properties(self, app, properties);
424    }
425
426    /// Dart's `FocusNode.debugDescribeChildren`: each child, named `Child 1`, `Child 2`, ….
427    fn debug_describe_children(self: Handle<Self>, app: &mut App) -> Vec<Rc<dyn DiagnosticsNode>> {
428        let mut count = 1;
429        self.children(app)
430            .into_iter()
431            .map(|child| {
432                let node = child.to_diagnostics_node(app, Some(format!("Child {count}")));
433                count += 1;
434                Rc::new(node) as Rc<dyn DiagnosticsNode>
435            })
436            .collect()
437    }
438
439    /// Dart's `FocusNode.toStringShort`: the identity, then the debug label and the focus
440    /// markers.
441    fn to_string_short(self: Handle<Self>, app: &App) -> String {
442        let label = self.debug_label(app).filter(|label| !label.is_empty());
443        let has_focus = self.as_node().has_focus(app);
444        let has_primary_focus = self.has_primary_focus(app);
445        let mut extra = String::new();
446        if let Some(label) = &label {
447            extra.push_str(label);
448        }
449        if has_focus && label.is_some() {
450            extra.push(' ');
451        }
452        if has_focus && !has_primary_focus {
453            extra.push_str("[IN FOCUS PATH]");
454        }
455        if has_primary_focus {
456            extra.push_str("[PRIMARY FOCUS]");
457        }
458        let identity = describe_identity(
459            waft_foundation::bare_type_name(std::any::type_name::<Self>()),
460            self.id().identity_hash(),
461        );
462        if extra.is_empty() {
463            identity
464        } else {
465            format!("{identity}({extra})")
466        }
467    }
468
469    // ---- one-line forwarders to the type-erased handle ----
470
471    /// See [`AnyFocusNode::skip_traversal`].
472    fn skip_traversal(self: Handle<Self>, app: &mut App) -> bool {
473        self.as_node().skip_traversal(app)
474    }
475
476    /// See [`AnyFocusNode::set_skip_traversal`].
477    fn set_skip_traversal(self: Handle<Self>, app: &mut App, value: bool) {
478        self.as_node().set_skip_traversal(app, value);
479    }
480
481    /// See [`AnyFocusNode::can_request_focus`].
482    fn can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
483        self.as_node().can_request_focus(app)
484    }
485
486    /// See [`AnyFocusNode::set_can_request_focus`].
487    fn set_can_request_focus(self: Handle<Self>, app: &mut App, value: bool) {
488        self.as_node().set_can_request_focus(app, value);
489    }
490
491    /// See [`AnyFocusNode::set_descendants_are_focusable`].
492    fn set_descendants_are_focusable(self: Handle<Self>, app: &mut App, value: bool) {
493        self.as_node().set_descendants_are_focusable(app, value);
494    }
495
496    /// See [`AnyFocusNode::descendants_are_traversable`].
497    fn descendants_are_traversable(self: Handle<Self>, app: &App) -> bool {
498        self.as_node().descendants_are_traversable(app)
499    }
500
501    /// See [`AnyFocusNode::set_descendants_are_traversable`].
502    fn set_descendants_are_traversable(self: Handle<Self>, app: &mut App, value: bool) {
503        self.as_node().set_descendants_are_traversable(app, value);
504    }
505
506    /// See [`AnyFocusNode::context`].
507    fn context(self: Handle<Self>, app: &App) -> Option<BuildContext> {
508        self.as_node().context(app)
509    }
510
511    /// See [`AnyFocusNode::on_key_event`].
512    fn on_key_event(self: Handle<Self>, app: &App) -> Option<FocusOnKeyEventCallback> {
513        self.as_node().on_key_event(app)
514    }
515
516    /// See [`AnyFocusNode::set_on_key_event`].
517    fn set_on_key_event(self: Handle<Self>, app: &mut App, value: Option<FocusOnKeyEventCallback>) {
518        self.as_node().set_on_key_event(app, value);
519    }
520
521    /// See [`AnyFocusNode::debug_label`].
522    fn debug_label(self: Handle<Self>, app: &App) -> Option<String> {
523        self.as_node().debug_label(app)
524    }
525
526    /// See [`AnyFocusNode::set_debug_label`].
527    fn set_debug_label(self: Handle<Self>, app: &mut App, value: Option<String>) {
528        self.as_node().set_debug_label(app, value);
529    }
530
531    /// See [`AnyFocusNode::parent`].
532    fn parent(self: Handle<Self>, app: &App) -> Option<AnyFocusNode> {
533        self.as_node().parent(app)
534    }
535
536    /// See [`AnyFocusNode::children`].
537    fn children(self: Handle<Self>, app: &App) -> Vec<AnyFocusNode> {
538        self.as_node().children(app)
539    }
540
541    /// See [`AnyFocusNode::descendants`].
542    fn descendants(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
543        self.as_node().descendants(app)
544    }
545
546    /// See [`AnyFocusNode::ancestors`].
547    fn ancestors(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
548        self.as_node().ancestors(app)
549    }
550
551    /// See [`AnyFocusNode::has_focus`].
552    fn has_focus(self: Handle<Self>, app: &mut App) -> bool {
553        self.as_node().has_focus(app)
554    }
555
556    /// See [`AnyFocusNode::has_primary_focus`].
557    fn has_primary_focus(self: Handle<Self>, app: &App) -> bool {
558        self.as_node().has_primary_focus(app)
559    }
560
561    /// See [`AnyFocusNode::highlight_mode`].
562    fn highlight_mode(self: Handle<Self>, app: &mut App) -> FocusHighlightMode {
563        self.as_node().highlight_mode(app)
564    }
565
566    /// See [`AnyFocusNode::enclosing_scope`].
567    fn enclosing_scope(self: Handle<Self>, app: &mut App) -> Option<Handle<FocusScopeNode>> {
568        self.as_node().enclosing_scope(app)
569    }
570
571    /// See [`AnyFocusNode::size`].
572    fn size(self: Handle<Self>, app: &App) -> Size {
573        self.as_node().size(app)
574    }
575
576    /// See [`AnyFocusNode::offset`].
577    fn offset(self: Handle<Self>, app: &App) -> Offset {
578        self.as_node().offset(app)
579    }
580
581    /// See [`AnyFocusNode::rect`].
582    fn rect(self: Handle<Self>, app: &App) -> Rect {
583        self.as_node().rect(app)
584    }
585
586    /// See [`AnyFocusNode::unfocus`].
587    fn unfocus(self: Handle<Self>, app: &mut App, disposition: UnfocusDisposition) {
588        self.as_node().unfocus(app, disposition);
589    }
590
591    /// See [`AnyFocusNode::consume_keyboard_token`].
592    fn consume_keyboard_token(self: Handle<Self>, app: &mut App) -> bool {
593        self.as_node().consume_keyboard_token(app)
594    }
595
596    /// See [`AnyFocusNode::attach`].
597    fn attach(
598        self: Handle<Self>,
599        app: &mut App,
600        context: Option<BuildContext>,
601        on_key_event: Option<FocusOnKeyEventCallback>,
602    ) -> Ref<FocusAttachment> {
603        self.as_node().attach(app, context, on_key_event)
604    }
605
606    /// See [`AnyFocusNode::dispose`].
607    fn dispose(self: Handle<Self>, app: &mut App) {
608        self.as_node().dispose(app);
609    }
610
611    /// See [`AnyFocusNode::request_focus`].
612    fn request_focus(self: Handle<Self>, app: &mut App, node: Option<AnyFocusNode>) {
613        self.as_node().request_focus(app, node);
614    }
615}
616
617/// The vtable of an erased [`AnyFocusNode`]: one `&'static` table per leaf type, built by
618/// [`FocusNodeVTable::of`].
619///
620/// It lives outside the arena — `&'static` — because a virtual hands `&mut App` onward.
621struct FocusNodeVTable {
622    type_name: fn() -> &'static str,
623    data: fn(&App, HandleId) -> &FocusNodeData,
624    data_mut: fn(&mut App, HandleId) -> &mut FocusNodeData,
625    as_scope: fn(HandleId) -> Option<Handle<FocusScopeNode>>,
626    nearest_scope: fn(&mut App, HandleId) -> Option<Handle<FocusScopeNode>>,
627    descendants_are_focusable: fn(&App, HandleId) -> bool,
628    traversal_children: fn(&mut App, HandleId) -> Vec<AnyFocusNode>,
629    traversal_descendants: fn(&mut App, HandleId) -> Vec<AnyFocusNode>,
630    do_request_focus: fn(&mut App, HandleId, bool),
631    debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
632    debug_describe_children: fn(&mut App, HandleId) -> Vec<Rc<dyn DiagnosticsNode>>,
633    to_string_short: fn(&App, HandleId) -> String,
634    add_listener: fn(&mut App, HandleId, Listener),
635    remove_listener: fn(&mut App, HandleId, &Listener),
636    notify_listeners: fn(&mut App, HandleId),
637    dispose_notifier: fn(&mut App, HandleId),
638}
639
640/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
641fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
642    Handle::from_id(id)
643}
644
645impl FocusNodeVTable {
646    /// The table for one leaf type.
647    const fn of<L: FocusNodeLeaf>() -> FocusNodeVTable {
648        FocusNodeVTable {
649            type_name: std::any::type_name::<L>,
650            data: |app, id| L::focus_node_data(resolve(id), app),
651            data_mut: |app, id| L::focus_node_data_mut(resolve(id), app),
652            as_scope: |id| L::as_scope(resolve(id)),
653            nearest_scope: |app, id| L::nearest_scope(resolve(id), app),
654            descendants_are_focusable: |app, id| L::descendants_are_focusable(resolve(id), app),
655            traversal_children: |app, id| L::traversal_children(resolve(id), app),
656            traversal_descendants: |app, id| L::traversal_descendants(resolve(id), app),
657            do_request_focus: |app, id, find_first_focus| {
658                L::do_request_focus(resolve(id), app, find_first_focus)
659            },
660            debug_fill_properties: |app, id, properties| {
661                L::debug_fill_properties(resolve(id), app, properties)
662            },
663            debug_describe_children: |app, id| L::debug_describe_children(resolve(id), app),
664            to_string_short: |app, id| L::to_string_short(resolve(id), app),
665            add_listener: |app, id, listener| {
666                app.get_mut(resolve::<L>(id))
667                    .change_notifier_data_mut()
668                    .add_listener(listener)
669            },
670            remove_listener: |app, id, listener| {
671                app.get_mut(resolve::<L>(id))
672                    .change_notifier_data_mut()
673                    .remove_listener(listener)
674            },
675            notify_listeners: |app, id| resolve::<L>(id).notify_listeners(app),
676            dispose_notifier: |app, id| ChangeNotifierData::dispose(app, resolve::<L>(id)),
677        }
678    }
679}
680
681/// Erased `FocusNode`: one identity and a static vtable, the fat pointer rustc cannot build
682/// for an arena id. No lease.
683///
684/// This is what a field or parameter Dart types as `FocusNode` becomes; the leaf stays in the
685/// [`App`] under its own type, and [`downcast`](Self::downcast) gets the typed handle back.
686/// The shared `FocusNode` members live here because a node reaches its parent, children, and
687/// the primary focus through this handle.
688///
689/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they
690/// address the same node.
691#[derive(Clone, Copy)]
692pub struct AnyFocusNode {
693    id: HandleId,
694    vtable: &'static FocusNodeVTable,
695}
696
697/// A field Dart types as the erased object, kept: AnyFocusNode with its count.
698pub type FocusNodeRef = Retained<AnyFocusNode>;
699
700waft_foundation::erased_handle!(AnyFocusNode: FocusNodeLeaf => FocusNodeLeaf::as_node);
701
702impl fmt::Debug for AnyFocusNode {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
705    }
706}
707
708impl AnyFocusNode {
709    /// The arena id behind this handle.
710    pub fn id(self) -> HandleId {
711        self.id
712    }
713
714    /// Dart's `node as T`: the typed handle when this node is a `T`, else `None`.
715    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
716        app.handle::<T>(self.id)
717    }
718
719    /// Dart's `node.debugFillProperties`: the node's own properties, after `Diagnosticable`'s
720    /// none.
721    pub fn debug_fill_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
722        (self.vtable.debug_fill_properties)(app, self.id, properties);
723    }
724
725    /// Dart's `node.debugDescribeChildren`: the node's children.
726    pub fn debug_describe_children(self, app: &mut App) -> Vec<Rc<dyn DiagnosticsNode>> {
727        (self.vtable.debug_describe_children)(app, self.id)
728    }
729
730    /// Dart's `node.toStringShort`.
731    pub fn to_string_short(self, app: &App) -> String {
732        (self.vtable.to_string_short)(app, self.id)
733    }
734
735    /// Dart's `node.toDiagnosticsNode(name:)`: a snapshot of the node and its children.
736    pub fn to_diagnostics_node(
737        self,
738        app: &mut App,
739        name: Option<String>,
740    ) -> DiagnosticableTreeNode {
741        let mut properties = DiagnosticPropertiesBuilder::new();
742        self.debug_fill_properties(app, &mut properties);
743        let short = self.to_string_short(app);
744        let children = self.debug_describe_children(app);
745        DiagnosticableTreeNode::from_parts(name, short, properties, children)
746    }
747
748    /// Dart's `Diagnosticable.toString`, which a property holding a node prints: its short
749    /// description, then the properties at the info level or above on one line.
750    pub fn to_string(self, app: &App) -> String {
751        let short = self.to_string_short(app);
752        let mut properties = DiagnosticPropertiesBuilder::new();
753        self.debug_fill_properties(app, &mut properties);
754        waft_foundation::DiagnosticableNode::from_parts(None, short, properties)
755            .with_style(DiagnosticsTreeStyle::SingleLine)
756            .to_string_with(None, waft_foundation::DiagnosticLevel::Info)
757    }
758
759    /// Dart's `node is FocusScopeNode`.
760    pub fn as_scope(self) -> Option<Handle<FocusScopeNode>> {
761        (self.vtable.as_scope)(self.id)
762    }
763
764    /// Dart's `FocusNode` fields.
765    fn data(self, app: &App) -> &FocusNodeData {
766        (self.vtable.data)(app, self.id)
767    }
768
769    fn data_mut(self, app: &mut App) -> &mut FocusNodeData {
770        (self.vtable.data_mut)(app, self.id)
771    }
772
773    pub(crate) fn manager(self, app: &App) -> Option<Handle<FocusManager>> {
774        self.data(app).manager
775    }
776
777    /// If true, tells the focus traversal policy to skip over this node for purposes of the
778    /// traversal algorithm.
779    ///
780    /// This may be used to place nodes in the focus tree that may be focused, but not
781    /// traversed, allowing them to receive key events as part of the focus chain, but not be
782    /// traversed to via focus traversal.
783    ///
784    /// This is different from [`can_request_focus`](Self::can_request_focus) because it only
785    /// implies that the node can't be reached via traversal, not that it can't be focused. It
786    /// may still be focused explicitly.
787    pub fn skip_traversal(self, app: &mut App) -> bool {
788        if self.data(app).skip_traversal {
789            return true;
790        }
791        for ancestor in self.ancestors(app) {
792            if !ancestor.descendants_are_traversable(app) {
793                return true;
794            }
795        }
796        false
797    }
798
799    /// See [`skip_traversal`](Self::skip_traversal).
800    pub fn set_skip_traversal(self, app: &mut App, value: bool) {
801        if value != self.data(app).skip_traversal {
802            self.data_mut(app).skip_traversal = value;
803            if let Some(manager) = self.manager(app) {
804                manager.mark_properties_changed(app, self);
805            }
806        }
807    }
808
809    /// If true, this focus node may request the primary focus.
810    ///
811    /// Defaults to true. Set to false if you want this node to do nothing when
812    /// [`request_focus`](Self::request_focus) is called on it.
813    ///
814    /// If set to false on a [`FocusScopeNode`], will cause all of the children of the scope
815    /// node to not be focusable.
816    ///
817    /// If set to false on a [`FocusNode`], it will not affect the focusability of children of
818    /// the node.
819    ///
820    /// The [`has_focus`](Self::has_focus) member can still return true if this node is the
821    /// ancestor of a node with primary focus.
822    ///
823    /// This is different than [`skip_traversal`](Self::skip_traversal) because
824    /// [`skip_traversal`](Self::skip_traversal) still allows the node to be focused, just not
825    /// traversed to via the `FocusTraversalPolicy`.
826    ///
827    /// Setting [`can_request_focus`](Self::can_request_focus) to false implies that the node
828    /// will also be skipped for traversal purposes.
829    pub fn can_request_focus(self, app: &App) -> bool {
830        if !self.data(app).can_request_focus {
831            return false;
832        }
833        let ancestors = self.ancestors_without_caching(app);
834        ancestors
835            .into_iter()
836            .all(|ancestor| AnyFocusNode::allow_descendants_to_be_focused(ancestor, app))
837    }
838
839    fn allow_descendants_to_be_focused(ancestor: AnyFocusNode, app: &App) -> bool {
840        ancestor.descendants_are_focusable(app)
841    }
842
843    /// See [`can_request_focus`](Self::can_request_focus).
844    pub fn set_can_request_focus(self, app: &mut App, value: bool) {
845        if value != self.data(app).can_request_focus {
846            // Have to set this first before unfocusing, since it checks this to cull
847            // unfocusable, previously-focused children.
848            self.data_mut(app).can_request_focus = value;
849            if self.has_focus(app) && !value {
850                self.unfocus(app, UnfocusDisposition::PreviouslyFocusedChild);
851            }
852            if let Some(manager) = self.manager(app) {
853                manager.mark_properties_changed(app, self);
854            }
855        }
856    }
857
858    /// If false, will disable focus for all of this node's descendants.
859    ///
860    /// Defaults to true. Does not affect focusability of this node: for that, use
861    /// [`can_request_focus`](Self::can_request_focus).
862    ///
863    /// If any descendants are focused when this is set to false, they will be unfocused. When
864    /// [`descendants_are_focusable`](Self::descendants_are_focusable) is set to true again,
865    /// they will not be refocused, although they will be able to accept focus again.
866    ///
867    /// Does not affect the value of [`can_request_focus`](Self::can_request_focus) on the
868    /// descendants.
869    ///
870    /// If a descendant node loses focus when this value is changed, the focus will move to the
871    /// scope enclosing this node.
872    pub fn descendants_are_focusable(self, app: &App) -> bool {
873        (self.vtable.descendants_are_focusable)(app, self.id)
874    }
875
876    /// See [`descendants_are_focusable`](Self::descendants_are_focusable).
877    pub fn set_descendants_are_focusable(self, app: &mut App, value: bool) {
878        if value == self.data(app).descendants_are_focusable {
879            return;
880        }
881        // Set descendants_are_focusable before unfocusing, so the scope won't try and focus
882        // any of the children here again if it is false.
883        self.data_mut(app).descendants_are_focusable = value;
884        if !value && self.has_focus(app) {
885            self.unfocus(app, UnfocusDisposition::PreviouslyFocusedChild);
886        }
887        if let Some(manager) = self.manager(app) {
888            manager.mark_properties_changed(app, self);
889        }
890    }
891
892    /// If false, tells the focus traversal policy to skip over for all of this node's
893    /// descendants for purposes of the traversal algorithm.
894    ///
895    /// Defaults to true. Does not affect the focus traversal of this node: for that, use
896    /// [`skip_traversal`](Self::skip_traversal).
897    ///
898    /// Does not affect the value of [`skip_traversal`](Self::skip_traversal) on the
899    /// descendants. Does not affect focusability of the descendants.
900    pub fn descendants_are_traversable(self, app: &App) -> bool {
901        self.data(app).descendants_are_traversable
902    }
903
904    /// See [`descendants_are_traversable`](Self::descendants_are_traversable).
905    pub fn set_descendants_are_traversable(self, app: &mut App, value: bool) {
906        if value != self.data(app).descendants_are_traversable {
907            self.data_mut(app).descendants_are_traversable = value;
908            if let Some(manager) = self.manager(app) {
909                manager.mark_properties_changed(app, self);
910            }
911        }
912    }
913
914    /// The context that was supplied to [`attach`](Self::attach).
915    ///
916    /// This is typically the context for the widget that is being focused, as it is used to
917    /// determine the bounds of the widget.
918    pub fn context(self, app: &App) -> Option<BuildContext> {
919        self.data(app).context
920    }
921
922    /// Called if this focus node receives a key event while focused (i.e. when
923    /// [`has_focus`](Self::has_focus) returns true).
924    ///
925    /// The [`FocusManager`] receives key events from `HardwareKeyboard` and will pass them to
926    /// the focused nodes. It starts with the node with the primary focus, and will call the
927    /// `on_key_event` callback for that node. If the callback returns
928    /// [`KeyEventResult::Ignored`], indicating that it did not handle the event, the
929    /// [`FocusManager`] will move to the parent of that node and call its `on_key_event`. If
930    /// that `on_key_event` returns [`KeyEventResult::Handled`], then it will stop propagating
931    /// the event. If it reaches the root [`FocusScopeNode`], [`FocusManager::root_scope`], the
932    /// event is discarded.
933    pub fn on_key_event(self, app: &App) -> Option<FocusOnKeyEventCallback> {
934        self.data(app).on_key_event.clone()
935    }
936
937    /// See [`on_key_event`](Self::on_key_event).
938    pub fn set_on_key_event(self, app: &mut App, value: Option<FocusOnKeyEventCallback>) {
939        self.data_mut(app).on_key_event = value;
940    }
941
942    /// Returns the parent node for this object.
943    ///
944    /// All nodes except for the root [`FocusScopeNode`] ([`FocusManager::root_scope`]) will be
945    /// given a parent when they are added to the focus tree, which is done using
946    /// [`FocusAttachment::reparent`].
947    pub fn parent(self, app: &App) -> Option<AnyFocusNode> {
948        self.data(app).parent
949    }
950
951    /// An iterator over the children of this node.
952    pub fn children(self, app: &App) -> Vec<AnyFocusNode> {
953        self.data(app)
954            .children
955            .iter()
956            .map(Retained::handle)
957            .collect()
958    }
959
960    /// An iterator over the children that are allowed to be traversed by the
961    /// `FocusTraversalPolicy`.
962    ///
963    /// Returns the list of focusable, traversable children of this node, regardless of those
964    /// settings on this focus node. Will return an empty iterable if
965    /// [`descendants_are_focusable`](Self::descendants_are_focusable) is false.
966    pub fn traversal_children(self, app: &mut App) -> Vec<AnyFocusNode> {
967        (self.vtable.traversal_children)(app, self.id)
968    }
969
970    /// A debug label that is used for diagnostic output.
971    pub fn debug_label(self, app: &App) -> Option<String> {
972        self.data(app).debug_label.clone()
973    }
974
975    /// See [`debug_label`](Self::debug_label).
976    pub fn set_debug_label(self, app: &mut App, value: Option<String>) {
977        if cfg!(debug_assertions) {
978            // Only set the value in debug builds.
979            self.data_mut(app).debug_label = value;
980        }
981    }
982
983    /// The hierarchy of children below this one, in depth-first order.
984    pub fn descendants(self, app: &mut App) -> Vec<AnyFocusNode> {
985        self.fill_descendants(app);
986        self.data(app)
987            .descendants
988            .iter()
989            .flatten()
990            .map(Retained::handle)
991            .collect()
992    }
993
994    /// Fills the cache [`descendants`](Self::descendants) reads, depth first.
995    fn fill_descendants(self, app: &mut App) {
996        if self.data(app).descendants.is_some() {
997            return;
998        }
999        let mut result = Vec::new();
1000        for child in self.data(app).children.clone() {
1001            child.fill_descendants(app);
1002            result.extend(child.data(app).descendants.iter().flatten().cloned());
1003            result.push(child);
1004        }
1005        self.data_mut(app).descendants = Some(result);
1006    }
1007
1008    /// Returns all descendants which do not have the
1009    /// [`skip_traversal`](Self::skip_traversal) and do have the
1010    /// [`can_request_focus`](Self::can_request_focus) flag set.
1011    pub fn traversal_descendants(self, app: &mut App) -> Vec<AnyFocusNode> {
1012        (self.vtable.traversal_descendants)(app, self.id)
1013    }
1014
1015    /// The ancestors of this node.
1016    ///
1017    /// Iterates the ancestors of this node starting at the parent and iterating over
1018    /// successively more remote ancestors of this node, ending at the root [`FocusScopeNode`]
1019    /// ([`FocusManager::root_scope`]).
1020    pub fn ancestors(self, app: &mut App) -> Vec<AnyFocusNode> {
1021        if self.data(app).ancestors.is_none() {
1022            let mut result = Vec::new();
1023            let mut parent = self.data(app).parent;
1024            while let Some(node) = parent {
1025                result.push(node);
1026                parent = node.data(app).parent;
1027            }
1028            self.data_mut(app).ancestors = Some(result);
1029        }
1030        self.data(app)
1031            .ancestors
1032            .clone()
1033            .expect("just filled the cache")
1034    }
1035
1036    /// [`ancestors`](Self::ancestors) without filling the cache, for what reads a node through
1037    /// `&App`.
1038    fn ancestors_without_caching(self, app: &App) -> Vec<AnyFocusNode> {
1039        let mut result = Vec::new();
1040        let mut parent = self.data(app).parent;
1041        while let Some(node) = parent {
1042            result.push(node);
1043            parent = node.data(app).parent;
1044        }
1045        result
1046    }
1047
1048    /// Whether this node has input focus.
1049    ///
1050    /// A [`FocusNode`] has focus when it is an ancestor of a node that returns true from
1051    /// [`has_primary_focus`](Self::has_primary_focus), or it has the primary focus itself.
1052    ///
1053    /// The [`has_focus`](Self::has_focus) accessor is different from
1054    /// [`has_primary_focus`](Self::has_primary_focus) in that
1055    /// [`has_focus`](Self::has_focus) is true if the node is anywhere in the focus chain, but
1056    /// for [`has_primary_focus`](Self::has_primary_focus) the node must be at the end of the
1057    /// chain to return true.
1058    pub fn has_focus(self, app: &App) -> bool {
1059        if self.has_primary_focus(app) {
1060            return true;
1061        }
1062        let primary_focus = self
1063            .manager(app)
1064            .and_then(|manager| app.get(manager).primary_focus.handle());
1065        primary_focus.is_some_and(|primary| primary.ancestors_without_caching(app).contains(&self))
1066    }
1067
1068    /// Returns true if this node currently has the application-wide input focus.
1069    ///
1070    /// A [`FocusNode`] has the primary focus when the node is focused in its nearest ancestor
1071    /// [`FocusScopeNode`] and [`has_focus`](Self::has_focus) is true for all its ancestor
1072    /// nodes, but none of its descendants.
1073    pub fn has_primary_focus(self, app: &App) -> bool {
1074        self.manager(app)
1075            .is_some_and(|manager| app.get(manager).primary_focus.handle() == Some(self))
1076    }
1077
1078    /// Returns the [`FocusHighlightMode`] that is currently in effect for this node.
1079    pub fn highlight_mode(self, app: &mut App) -> FocusHighlightMode {
1080        FocusManager::instance(app).highlight_mode(app)
1081    }
1082
1083    /// Returns the nearest enclosing scope node above this node, including this node, if it's
1084    /// a scope.
1085    ///
1086    /// Returns `None` if no scope is found.
1087    ///
1088    /// Use [`enclosing_scope`](Self::enclosing_scope) to look for scopes above this node.
1089    pub fn nearest_scope(self, app: &mut App) -> Option<Handle<FocusScopeNode>> {
1090        (self.vtable.nearest_scope)(app, self.id)
1091    }
1092
1093    fn clear_enclosing_scope_cache(self, app: &mut App) {
1094        let Some(cached_scope) = self.data(app).enclosing_scope else {
1095            return;
1096        };
1097        self.data_mut(app).enclosing_scope = None;
1098        for child in self.data(app).children.clone() {
1099            if child.data(app).enclosing_scope == Some(cached_scope) {
1100                child.clear_enclosing_scope_cache(app);
1101            }
1102        }
1103    }
1104
1105    /// Returns the nearest enclosing scope node above this node, or `None` if the node has not
1106    /// yet been added to the focus tree.
1107    ///
1108    /// If this node is itself a scope, this will only return ancestors of this scope.
1109    ///
1110    /// Use [`nearest_scope`](Self::nearest_scope) to start at this node instead of above it.
1111    pub fn enclosing_scope(self, app: &mut App) -> Option<Handle<FocusScopeNode>> {
1112        if let Some(cached) = self.data(app).enclosing_scope {
1113            return Some(cached);
1114        }
1115        let parent = self.data(app).parent;
1116        // Point access: the parent is another slot, so resolve it before writing ours.
1117        let computed = parent.and_then(|parent| parent.nearest_scope(app));
1118        self.data_mut(app).enclosing_scope = computed;
1119        computed
1120    }
1121
1122    /// Returns the size of the attached widget's `RenderObject`, in logical units.
1123    ///
1124    /// Size is the size of the transformed widget in global coordinates.
1125    pub fn size(self, app: &App) -> Size {
1126        self.rect(app).size()
1127    }
1128
1129    /// Returns the global offset to the upper left corner of the attached widget's
1130    /// `RenderObject`, in logical units.
1131    ///
1132    /// Offset is the offset of the transformed widget in global coordinates.
1133    pub fn offset(self, app: &App) -> Offset {
1134        let object = self.render_box(app);
1135        object.local_to_global(app, Offset::ZERO, None)
1136    }
1137
1138    /// Returns the global rectangle of the attached widget's `RenderObject`, in logical units.
1139    ///
1140    /// Rect is the rectangle of the transformed widget in global coordinates.
1141    pub fn rect(self, app: &App) -> Rect {
1142        let object = self.render_box(app);
1143        let top_left = object.local_to_global(app, Offset::ZERO, None);
1144        let bottom_right =
1145            object.local_to_global(app, object.size(app).bottom_right(Offset::ZERO), None);
1146        Rect::from_ltrb(
1147            top_left.dx(),
1148            top_left.dy(),
1149            bottom_right.dx(),
1150            bottom_right.dy(),
1151        )
1152    }
1153
1154    /// Dart reads `context!.findRenderObject()!` and its `semanticBounds`; a focus node hosts a
1155    /// box, whose semantic bounds are `Offset.zero & size`.
1156    fn render_box(self, app: &App) -> waft_rendering::AnyRenderBox {
1157        let context = self.data(app).context.expect(
1158            "Tried to get the bounds of a focus node that didn't have its context set yet.\n\
1159             The context needs to be set before trying to evaluate traversal policies. \
1160             Setting the context is typically done with the attach method.",
1161        );
1162        context
1163            .find_render_object(app)
1164            .expect("the focus node's context has a render object")
1165            .as_box()
1166            .expect("the focus node's render object is a RenderBox")
1167    }
1168
1169    /// Removes the focus on this node by moving the primary focus to another node.
1170    ///
1171    /// This method removes focus from a node that has the primary focus, cancels any
1172    /// outstanding requests to focus it, while setting the primary focus to another node
1173    /// according to the `disposition`.
1174    ///
1175    /// It is safe to call regardless of whether this node has ever requested focus or not. If
1176    /// this node doesn't have focus or primary focus, nothing happens.
1177    ///
1178    /// If `disposition` is [`UnfocusDisposition::Scope`], then the previously focused node
1179    /// history of the enclosing scope will be cleared, and the primary focus will be moved to
1180    /// the nearest enclosing scope ancestor that is enabled for focus, ignoring the
1181    /// [`FocusScopeNode::focused_child`] for that scope.
1182    ///
1183    /// If `disposition` is [`UnfocusDisposition::PreviouslyFocusedChild`], then this node will
1184    /// be removed from the previously focused list in the
1185    /// [`enclosing_scope`](Self::enclosing_scope), and the focus will be moved to the
1186    /// previously focused node of the [`enclosing_scope`](Self::enclosing_scope), which (if it
1187    /// is a scope itself), will find its focused child, etc., until a leaf focus node is found.
1188    /// If there is no previously focused child, then the scope itself will receive focus, as if
1189    /// [`UnfocusDisposition::Scope`] were specified.
1190    pub fn unfocus(self, app: &mut App, disposition: UnfocusDisposition) {
1191        let marked_for_focus = self
1192            .manager(app)
1193            .map(|manager| app.get(manager).marked_for_focus.handle());
1194        if !self.has_focus(app) && marked_for_focus != Some(Some(self)) {
1195            return;
1196        }
1197        // If the scope is null, then this is either the root node, or a node that is not yet
1198        // in the tree, neither of which do anything when unfocused.
1199        let Some(mut scope) = self.enclosing_scope(app) else {
1200            return;
1201        };
1202        match disposition {
1203            UnfocusDisposition::Scope => {
1204                // If it can't request focus, then don't modify its focused children.
1205                if scope.can_request_focus(app) {
1206                    // Clearing the focused children here prevents re-focusing the node that we
1207                    // just unfocused if we immediately hit "next" after unfocusing, and also
1208                    // prevents choosing to refocus the next-to-last focused child if unfocus is
1209                    // called more than once.
1210                    app.get_mut(scope).scope.focused_children.clear();
1211                }
1212                while !scope.can_request_focus(app) {
1213                    scope = scope
1214                        .enclosing_scope(app)
1215                        .or_else(|| {
1216                            self.manager(app)
1217                                .map(|manager| manager.root_scope(app).handle())
1218                        })
1219                        .expect("a node with a scope has a manager");
1220                }
1221                scope.do_request_focus(app, false);
1222            }
1223            UnfocusDisposition::PreviouslyFocusedChild => {
1224                // Select the most recent focused child from the nearest focusable scope and
1225                // focus that. If there isn't one, focus the scope itself.
1226                if scope.can_request_focus(app) {
1227                    remove_focused_child(app, scope, self);
1228                }
1229                while !scope.can_request_focus(app) {
1230                    if let Some(enclosing) = scope.enclosing_scope(app) {
1231                        remove_focused_child(app, enclosing, scope.as_node());
1232                    }
1233                    scope = scope
1234                        .enclosing_scope(app)
1235                        .or_else(|| {
1236                            self.manager(app)
1237                                .map(|manager| manager.root_scope(app).handle())
1238                        })
1239                        .expect("a node with a scope has a manager");
1240                }
1241                scope.do_request_focus(app, true);
1242            }
1243        }
1244    }
1245
1246    /// Removes the keyboard token from this focus node if it has one.
1247    ///
1248    /// This mechanism helps distinguish between an input control gaining focus by default and
1249    /// gaining focus as a result of an explicit user action.
1250    ///
1251    /// When a focus node requests the focus (either via
1252    /// [`request_focus`](Self::request_focus) or [`FocusScopeNode::autofocus`]), the focus node
1253    /// receives a keyboard token if it does not already have one. Later, when the focus node
1254    /// becomes focused, the widget that manages the text input connection should show the
1255    /// keyboard only if it successfully consumes the keyboard token from the focus node.
1256    ///
1257    /// Returns true if this method successfully consumes the keyboard token.
1258    pub fn consume_keyboard_token(self, app: &mut App) -> bool {
1259        if !self.data(app).has_keyboard_token {
1260            return false;
1261        }
1262        self.data_mut(app).has_keyboard_token = false;
1263        true
1264    }
1265
1266    /// Marks the node as being the next to be focused, meaning that it will become the primary
1267    /// focus and notify listeners of a focus change the next time focus is resolved by the
1268    /// manager. If something else calls `mark_next_focus` before then, then that node will
1269    /// become the next focus instead of the previous one.
1270    fn mark_next_focus(self, app: &mut App, new_focus: AnyFocusNode) {
1271        if let Some(manager) = self.manager(app) {
1272            // If we have a manager, then let it handle the focus change.
1273            manager.mark_next_focus(app, self);
1274            return;
1275        }
1276        // If we don't have a manager, then change the focus locally.
1277        new_focus.set_as_focused_child_for_scope(app);
1278        new_focus.notify(app);
1279        if new_focus != self {
1280            self.notify(app);
1281        }
1282    }
1283
1284    /// Removes the given [`AnyFocusNode`] and its children as a child of this node.
1285    fn remove_child(self, app: &mut App, node: AnyFocusNode, remove_scope_focus: bool) {
1286        debug_assert!(
1287            self.data(app).children.iter().any(|kept| kept == node),
1288            "Tried to remove a node that wasn't a child."
1289        );
1290        debug_assert!(node.data(app).parent == Some(self));
1291        debug_assert!(node.manager(app) == self.manager(app));
1292
1293        if remove_scope_focus && let Some(node_scope) = node.enclosing_scope(app) {
1294            remove_focused_child(app, node_scope, node);
1295            for descendant in node.descendants(app) {
1296                if descendant.enclosing_scope(app) == Some(node_scope) {
1297                    remove_focused_child(app, node_scope, descendant);
1298                }
1299            }
1300        }
1301
1302        node.data_mut(app).parent = None;
1303        node.clear_enclosing_scope_cache(app);
1304        node.clear_ancestors_caches(app);
1305        self.data_mut(app).children.retain(|child| child != node);
1306        for ancestor in self.ancestors(app) {
1307            ancestor.data_mut(app).descendants = None;
1308        }
1309        self.data_mut(app).descendants = None;
1310        debug_assert!(match self.manager(app) {
1311            None => true,
1312            Some(manager) => {
1313                let root = manager.root_scope(app).as_node();
1314                !root.descendants(app).contains(&node)
1315            }
1316        });
1317    }
1318
1319    /// Forgets the ancestors this node and its descendants cached, for a node that has left its
1320    /// parent: Dart keeps reading them, but the arena frees them.
1321    fn clear_ancestors_caches(self, app: &mut App) {
1322        self.data_mut(app).ancestors = None;
1323        for descendant in self.descendants(app) {
1324            descendant.data_mut(app).ancestors = None;
1325        }
1326    }
1327
1328    fn update_manager(self, app: &mut App, manager: Option<Handle<FocusManager>>) {
1329        self.data_mut(app).manager = manager;
1330        for descendant in self.descendants(app) {
1331            let data = descendant.data_mut(app);
1332            data.manager = manager;
1333            data.ancestors = None;
1334        }
1335    }
1336
1337    /// Used by [`FocusAttachment::reparent`] to perform the actual parenting operation.
1338    fn reparent_child(self, app: &mut App, child: AnyFocusNode) {
1339        debug_assert!(
1340            child != self,
1341            "Tried to make a child into a parent of itself."
1342        );
1343        if child.data(app).parent == Some(self) {
1344            debug_assert!(
1345                self.data(app).children.iter().any(|kept| kept == child),
1346                "Found a node that says it's a child, but doesn't appear in the child list."
1347            );
1348            // The child is already a child of this parent.
1349            return;
1350        }
1351        debug_assert!(match self.manager(app) {
1352            None => true,
1353            Some(manager) => child != manager.root_scope(app).as_node(),
1354        });
1355        debug_assert!(
1356            !self.ancestors(app).contains(&child),
1357            "The supplied child is already an ancestor of this node. Loops are not allowed."
1358        );
1359        let old_scope = child.enclosing_scope(app);
1360        let had_focus = child.has_focus(app);
1361        if let Some(parent) = child.data(app).parent {
1362            let nearest_scope = self.nearest_scope(app);
1363            parent.remove_child(app, child, old_scope != nearest_scope);
1364        }
1365        let kept_child = child.keep(app);
1366        self.data_mut(app).children.push(kept_child);
1367        let child_data = child.data_mut(app);
1368        child_data.parent = Some(self);
1369        child_data.ancestors = None;
1370        let manager = self.manager(app);
1371        child.update_manager(app, manager);
1372        for ancestor in child.ancestors(app) {
1373            ancestor.data_mut(app).descendants = None;
1374        }
1375        if had_focus {
1376            // Update the focus chain for the current focus without changing it.
1377            let primary_focus = self
1378                .manager(app)
1379                .and_then(|manager| app.get(manager).primary_focus.handle());
1380            if let Some(primary_focus) = primary_focus {
1381                primary_focus.set_as_focused_child_for_scope(app);
1382            }
1383        }
1384        if let Some(old_scope) = old_scope
1385            && let Some(context) = child.data(app).context
1386            && child.enclosing_scope(app) != Some(old_scope)
1387            && let Some(policy) = FocusTraversalGroup::maybe_of(app, context)
1388        {
1389            policy.changed_scope(app, Some(child), Some(old_scope));
1390        }
1391        if child.data(app).request_focus_when_reparented {
1392            child.do_request_focus(app, true);
1393            child.data_mut(app).request_focus_when_reparented = false;
1394        }
1395    }
1396
1397    /// Called by the _host_ `StatefulWidget` to attach a [`FocusNode`] to the widget tree.
1398    ///
1399    /// In order to attach a [`FocusNode`] to the widget tree, call
1400    /// [`attach`](Self::attach), typically from the `StatefulWidget`'s `State::init_state`
1401    /// method.
1402    ///
1403    /// If the focus node in the host widget is swapped out, the new node will need to be
1404    /// attached. [`FocusAttachment::detach`] should be called on the old node, and then
1405    /// [`attach`](Self::attach) called on the new node. This typically happens in the
1406    /// `State::did_update_widget` method.
1407    pub fn attach(
1408        self,
1409        app: &mut App,
1410        context: Option<BuildContext>,
1411        on_key_event: Option<FocusOnKeyEventCallback>,
1412    ) -> Ref<FocusAttachment> {
1413        self.data_mut(app).context = context;
1414        if on_key_event.is_some() {
1415            self.data_mut(app).on_key_event = on_key_event;
1416        }
1417        let attachment = FocusAttachment::new(app, self);
1418        self.data_mut(app).attachment = Some(attachment.clone());
1419        attachment
1420    }
1421
1422    /// Discards any resources used by this node.
1423    ///
1424    /// Detaching also unfocuses and cleans up the manager's data structures.
1425    pub fn dispose(self, app: &mut App) {
1426        if let Some(attachment) = self.data(app).attachment.handle() {
1427            attachment.detach(app);
1428        }
1429        (self.vtable.dispose_notifier)(app, self.id);
1430    }
1431
1432    fn notify(self, app: &mut App) {
1433        if self.data(app).parent.is_none() {
1434            // no longer part of the tree, so don't notify.
1435            return;
1436        }
1437        if self.has_primary_focus(app) {
1438            self.set_as_focused_child_for_scope(app);
1439        }
1440        (self.vtable.notify_listeners)(app, self.id);
1441    }
1442
1443    /// Requests the primary focus for this node, or for a supplied `node`, which will also give
1444    /// focus to its [`ancestors`](Self::ancestors).
1445    ///
1446    /// If called without a node, request focus for this node. If the node hasn't been added to
1447    /// the focus tree yet, then defer the focus request until it is, allowing newly created
1448    /// widgets to request focus as soon as they are added.
1449    ///
1450    /// If the given `node` is not yet a part of the focus tree, then this method will add the
1451    /// `node` as a child of this node before requesting focus.
1452    ///
1453    /// If the given `node` is a [`FocusScopeNode`] and that focus scope node has a non-null
1454    /// [`FocusScopeNode::focused_child`], then request the focus for the focused child. This
1455    /// process is recursive and continues until it encounters either a focus scope node with a
1456    /// null focused child or an ordinary (non-scope) [`FocusNode`] is found.
1457    ///
1458    /// The node is notified that it has received the primary focus in a microtask, so
1459    /// notification may lag the request by up to one frame.
1460    pub fn request_focus(self, app: &mut App, node: Option<AnyFocusNode>) {
1461        if let Some(node) = node {
1462            if node.data(app).parent.is_none() {
1463                self.reparent_child(app, node);
1464            }
1465            debug_assert!(
1466                node.ancestors(app).contains(&self),
1467                "Focus was requested for a node that is not a descendant of the scope from \
1468                 which it was requested."
1469            );
1470            node.do_request_focus(app, true);
1471            return;
1472        }
1473        self.do_request_focus(app, true);
1474    }
1475
1476    /// Dispatches to the leaf; [`FocusScopeNode`] overrides this.
1477    fn do_request_focus(self, app: &mut App, find_first_focus: bool) {
1478        (self.vtable.do_request_focus)(app, self.id, find_first_focus);
1479    }
1480
1481    /// Sets this node as the [`FocusScopeNode::focused_child`] of the enclosing scope.
1482    ///
1483    /// Sets this node as the focused child for the enclosing scope, and that scope as the
1484    /// focused child for the scope above it, etc., until it reaches the root node. It doesn't
1485    /// change the primary focus, it just changes what node would be focused if the enclosing
1486    /// scope receives focus, and keeps track of previously focused children in that scope, so
1487    /// that if the focused child in that scope is removed, the previous focus returns.
1488    fn set_as_focused_child_for_scope(self, app: &mut App) {
1489        let mut scope_focus = self;
1490        for ancestor in self.ancestors(app) {
1491            let Some(ancestor) = ancestor.as_scope() else {
1492                continue;
1493            };
1494            debug_assert!(
1495                scope_focus != ancestor.as_node(),
1496                "Somehow made a loop by setting focusedChild to its scope."
1497            );
1498            // Remove it anywhere in the focused child history.
1499            remove_focused_child(app, ancestor, scope_focus);
1500            // Add it to the end of the list, which is also the top of the queue: the end of the
1501            // list represents the currently focused child.
1502            let kept = scope_focus.keep(app);
1503            app.get_mut(ancestor).scope.focused_children.push(kept);
1504            scope_focus = ancestor.as_node();
1505        }
1506    }
1507
1508    /// Request to move the focus to the next focus node, by calling the
1509    /// [`FocusTraversalPolicy::next`] method.
1510    ///
1511    /// Returns true if it successfully found a node and requested focus.
1512    ///
1513    /// [`FocusTraversalPolicy::next`]: crate::FocusTraversalPolicy::next
1514    pub fn next_focus(self, app: &mut App) -> bool {
1515        let context = self
1516            .data(app)
1517            .context
1518            .expect("a node in the tree has a context");
1519        FocusTraversalGroup::of(app, context).next(app, self)
1520    }
1521
1522    /// Request to move the focus to the previous focus node, by calling the
1523    /// [`FocusTraversalPolicy::previous`] method.
1524    ///
1525    /// Returns true if it successfully found a node and requested focus.
1526    ///
1527    /// [`FocusTraversalPolicy::previous`]: crate::FocusTraversalPolicy::previous
1528    pub fn previous_focus(self, app: &mut App) -> bool {
1529        let context = self
1530            .data(app)
1531            .context
1532            .expect("a node in the tree has a context");
1533        FocusTraversalGroup::of(app, context).previous(app, self)
1534    }
1535
1536    /// Request to move the focus to the nearest focus node in the given direction, by calling
1537    /// the [`FocusTraversalPolicy::in_direction`] method.
1538    ///
1539    /// Returns true if it successfully found a node and requested focus.
1540    ///
1541    /// [`FocusTraversalPolicy::in_direction`]: crate::FocusTraversalPolicy::in_direction
1542    pub fn focus_in_direction(self, app: &mut App, direction: TraversalDirection) -> bool {
1543        let context = self
1544            .data(app)
1545            .context
1546            .expect("a node in the tree has a context");
1547        FocusTraversalGroup::of(app, context).in_direction(app, self, direction)
1548    }
1549
1550    /// Register a closure to be called when this node notifies its listeners.
1551    pub fn add_listener(self, app: &mut App, listener: Listener) {
1552        (self.vtable.add_listener)(app, self.id, listener);
1553    }
1554
1555    /// Remove a previously registered closure from the list of closures this node notifies.
1556    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
1557        (self.vtable.remove_listener)(app, self.id, listener);
1558    }
1559}
1560
1561impl ListenableHandle for AnyFocusNode {
1562    fn add_listener_to(self, app: &mut App, listener: Listener) {
1563        AnyFocusNode::add_listener(self, app, listener);
1564    }
1565
1566    fn remove_listener_from(self, app: &mut App, listener: &Listener) {
1567        AnyFocusNode::remove_listener(self, app, listener);
1568    }
1569}
1570
1571/// Dart's `scope._focusedChildren.remove(node)`.
1572fn remove_focused_child(app: &mut App, scope: Handle<FocusScopeNode>, node: AnyFocusNode) {
1573    app.get_mut(scope)
1574        .scope
1575        .focused_children
1576        .retain(|child| child != node);
1577}
1578
1579/// An object that can be used by a stateful widget to obtain the keyboard focus and to handle
1580/// keyboard events.
1581///
1582/// _Please see the `Focus` and `FocusScope` widgets, which are utility widgets that manage
1583/// their own [`FocusNode`]s and [`FocusScopeNode`]s, respectively. If they aren't appropriate,
1584/// [`FocusNode`]s can be managed directly, but doing this is rare._
1585///
1586/// [`FocusNode`]s are persistent objects that form a _focus tree_ that is a representation of
1587/// the widgets in the hierarchy that are interested in focus. A focus node might need to be
1588/// created if it is passed in from an ancestor of a `Focus` widget to control the focus of the
1589/// children from the ancestor, or a widget might need to host one if the widget subsystem is
1590/// not being used, or if the `Focus` and `FocusScope` widgets provide insufficient control.
1591///
1592/// [`FocusNode`]s are organized into _scopes_ (see [`FocusScopeNode`]), which form sub-trees of
1593/// nodes that restrict traversal to a group of nodes. Within a scope, the most recent nodes to
1594/// have focus are remembered, and if a node is focused and then unfocused, the previous node
1595/// receives focus again.
1596///
1597/// The focus node hierarchy can be traversed using the [`AnyFocusNode::parent`],
1598/// [`AnyFocusNode::children`], [`AnyFocusNode::ancestors`] and [`AnyFocusNode::descendants`]
1599/// accessors.
1600///
1601/// [`FocusNode`]s are `ChangeNotifier`s, so a listener can be registered to receive a
1602/// notification when the focus changes. Listeners will also be notified when
1603/// [`AnyFocusNode::skip_traversal`], [`AnyFocusNode::can_request_focus`],
1604/// [`AnyFocusNode::descendants_are_focusable`], and
1605/// [`AnyFocusNode::descendants_are_traversable`] properties are updated.
1606///
1607/// ## Lifecycle
1608///
1609/// There are several actors involved in the lifecycle of a [`FocusNode`] / [`FocusScopeNode`].
1610/// They are created and disposed by their _owner_, attached, detached, and re-parented using a
1611/// [`FocusAttachment`] by their _host_ (which must be owned by the `State` of a
1612/// `StatefulWidget`), and they are managed by the [`FocusManager`].
1613///
1614/// Dart's optional constructor arguments (`debugLabel`, `onKeyEvent`, `skipTraversal`,
1615/// `canRequestFocus`, `descendantsAreFocusable`, `descendantsAreTraversable`) are the node's
1616/// setters; each of them is a public setter in Dart too, and none of them notifies before the
1617/// node joins a tree.
1618pub struct FocusNode {
1619    change_notifier: ChangeNotifierData,
1620    focus_node: FocusNodeData,
1621}
1622
1623impl FocusNode {
1624    /// Creates a focus node.
1625    pub fn new(app: &mut App) -> Ref<FocusNode> {
1626        app.create(FocusNode {
1627            change_notifier: ChangeNotifierData::new(),
1628            focus_node: FocusNodeData::new(),
1629        })
1630    }
1631
1632    // ---- the bodies a subclass reaches with `super` ----
1633
1634    /// `FocusNode.nearestScope`.
1635    fn nearest_scope(this: AnyFocusNode, app: &mut App) -> Option<Handle<FocusScopeNode>> {
1636        this.enclosing_scope(app)
1637    }
1638
1639    /// `FocusNode.descendantsAreFocusable`.
1640    fn descendants_are_focusable(this: AnyFocusNode, app: &App) -> bool {
1641        this.data(app).descendants_are_focusable
1642    }
1643
1644    /// `FocusNode.traversalChildren`.
1645    fn traversal_children(this: AnyFocusNode, app: &mut App) -> Vec<AnyFocusNode> {
1646        if !this.descendants_are_focusable(app) {
1647            return Vec::new();
1648        }
1649        this.children(app)
1650            .into_iter()
1651            .filter(|node| !node.skip_traversal(app) && node.can_request_focus(app))
1652            .collect()
1653    }
1654
1655    /// `FocusNode.traversalDescendants`.
1656    fn traversal_descendants(this: AnyFocusNode, app: &mut App) -> Vec<AnyFocusNode> {
1657        if !this.descendants_are_focusable(app) {
1658            return Vec::new();
1659        }
1660        this.descendants(app)
1661            .into_iter()
1662            .filter(|node| !node.skip_traversal(app) && node.can_request_focus(app))
1663            .collect()
1664    }
1665
1666    /// `FocusNode._doRequestFocus`.
1667    fn do_request_focus(this: AnyFocusNode, app: &mut App, _find_first_focus: bool) {
1668        if !this.can_request_focus(app) {
1669            return;
1670        }
1671        // If the node isn't part of the tree, then we just defer the focus request until the
1672        // next time it is reparented, so that it's possible to focus newly added widgets.
1673        if this.data(app).parent.is_none() {
1674            this.data_mut(app).request_focus_when_reparented = true;
1675            return;
1676        }
1677        this.set_as_focused_child_for_scope(app);
1678        let marked_for_focus = this
1679            .manager(app)
1680            .and_then(|manager| app.get(manager).marked_for_focus.handle());
1681        if this.has_primary_focus(app)
1682            && (marked_for_focus.is_none() || marked_for_focus == Some(this))
1683        {
1684            return;
1685        }
1686        this.data_mut(app).has_keyboard_token = true;
1687        this.mark_next_focus(app, this);
1688    }
1689}
1690
1691impl ChangeNotifier for FocusNode {
1692    fn change_notifier_data(&self) -> &ChangeNotifierData {
1693        &self.change_notifier
1694    }
1695
1696    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1697        &mut self.change_notifier
1698    }
1699}
1700
1701/// Dart's `FocusNode.debugFillProperties`, one body for [`FocusNode`] and [`FocusScopeNode`].
1702fn fill_focus_node_properties<L: FocusNodeLeaf>(
1703    node: Handle<L>,
1704    app: &App,
1705    properties: &mut DiagnosticPropertiesBuilder,
1706) {
1707    let context = node.context(app);
1708    let descendants_are_focusable = node.descendants_are_focusable(app);
1709    let descendants_are_traversable = node.descendants_are_traversable(app);
1710    let can_request_focus = node.as_node().can_request_focus(app);
1711    let has_focus = node.as_node().has_focus(app);
1712    let has_primary_focus = node.has_primary_focus(app);
1713    properties.add(
1714        DiagnosticsProperty::<String>::new(
1715            "context",
1716            context.map(|context| context.widget(app).to_string_short()),
1717        )
1718        .default_value(None),
1719    );
1720    properties.add(
1721        FlagProperty::new("descendantsAreFocusable", Some(descendants_are_focusable))
1722            .if_false("DESCENDANTS UNFOCUSABLE")
1723            .default_value(Some(true)),
1724    );
1725    properties.add(
1726        FlagProperty::new(
1727            "descendantsAreTraversable",
1728            Some(descendants_are_traversable),
1729        )
1730        .if_false("DESCENDANTS UNTRAVERSABLE")
1731        .default_value(Some(true)),
1732    );
1733    properties.add(
1734        FlagProperty::new("canRequestFocus", Some(can_request_focus))
1735            .if_false("NOT FOCUSABLE")
1736            .default_value(Some(true)),
1737    );
1738    properties.add(
1739        FlagProperty::new("hasFocus", Some(has_focus && !has_primary_focus))
1740            .if_true("IN FOCUS PATH")
1741            .default_value(Some(false)),
1742    );
1743    properties.add(
1744        FlagProperty::new("hasPrimaryFocus", Some(has_primary_focus))
1745            .if_true("PRIMARY FOCUS")
1746            .default_value(Some(false)),
1747    );
1748}
1749
1750impl FocusNodeLeaf for FocusNode {
1751    crate::focus_node_accessors!();
1752}
1753
1754// ---------------------------------------------------------------------------------------------
1755// FocusScopeNode
1756
1757/// The fields Dart's `FocusScopeNode` adds to [`FocusNodeData`].
1758pub struct FocusScopeNodeData {
1759    /// Controls the transfer of focus beyond the first and the last items of a
1760    /// [`FocusScopeNode`].
1761    ///
1762    /// Changing this field value has no immediate effect on the UI. Instead, next time focus
1763    /// traversal takes place `FocusTraversalPolicy` will read this value and apply the new
1764    /// behavior.
1765    pub traversal_edge_behavior: TraversalEdgeBehavior,
1766
1767    /// Controls the directional transfer of focus when the focus is on the first or last item.
1768    ///
1769    /// Changing this field value has no immediate effect on the UI. Instead, next time focus
1770    /// traversal takes place `FocusTraversalPolicy` will read this value and apply the new
1771    /// behavior.
1772    pub directional_traversal_edge_behavior: TraversalEdgeBehavior,
1773
1774    /// A stack of the children that have been set as the `focused_child`, most recent last
1775    /// (which is the top of the stack).
1776    focused_children: Vec<FocusNodeRef>,
1777}
1778
1779/// A subclass of [`FocusNode`] that acts as a scope for its descendants, maintaining
1780/// information about which descendant is currently or was last focused.
1781///
1782/// _Please see the `FocusScope` and `Focus` widgets, which are utility widgets that manage
1783/// their own [`FocusScopeNode`]s and [`FocusNode`]s, respectively. If they aren't appropriate,
1784/// [`FocusScopeNode`]s can be managed directly._
1785///
1786/// [`FocusScopeNode`] organizes [`FocusNode`]s into _scopes_. Scopes form sub-trees of nodes
1787/// that can be traversed as a group. Within a scope, the most recent nodes to have focus are
1788/// remembered, and if a node is focused and then removed, the original node receives focus
1789/// again.
1790///
1791/// From a [`FocusScopeNode`], calling [`set_first_focus`](Self::set_first_focus) sets the given
1792/// focus scope as the [`focused_child`](Self::focused_child) of this node, adopting if it isn't
1793/// already part of the focus tree.
1794pub struct FocusScopeNode {
1795    change_notifier: ChangeNotifierData,
1796    focus_node: FocusNodeData,
1797    scope: FocusScopeNodeData,
1798}
1799
1800impl FocusScopeNode {
1801    /// Creates a [`FocusScopeNode`].
1802    ///
1803    /// Dart's optional constructor arguments are the setters; `descendantsAreFocusable` is
1804    /// always true on a scope, which is [`FocusNodeData`]'s default.
1805    pub fn new(app: &mut App) -> Ref<FocusScopeNode> {
1806        app.create(FocusScopeNode {
1807            change_notifier: ChangeNotifierData::new(),
1808            focus_node: FocusNodeData::new(),
1809            scope: FocusScopeNodeData {
1810                traversal_edge_behavior: TraversalEdgeBehavior::ClosedLoop,
1811                directional_traversal_edge_behavior: TraversalEdgeBehavior::Stop,
1812                focused_children: Vec::new(),
1813            },
1814        })
1815    }
1816
1817    /// See [`FocusScopeNodeData::traversal_edge_behavior`].
1818    pub fn traversal_edge_behavior(self: Handle<Self>, app: &App) -> TraversalEdgeBehavior {
1819        app.get(self).scope.traversal_edge_behavior
1820    }
1821
1822    /// See [`FocusScopeNodeData::traversal_edge_behavior`].
1823    pub fn set_traversal_edge_behavior(
1824        self: Handle<Self>,
1825        app: &mut App,
1826        value: TraversalEdgeBehavior,
1827    ) {
1828        app.get_mut(self).scope.traversal_edge_behavior = value;
1829    }
1830
1831    /// See [`FocusScopeNodeData::directional_traversal_edge_behavior`].
1832    pub fn directional_traversal_edge_behavior(
1833        self: Handle<Self>,
1834        app: &App,
1835    ) -> TraversalEdgeBehavior {
1836        app.get(self).scope.directional_traversal_edge_behavior
1837    }
1838
1839    /// See [`FocusScopeNodeData::directional_traversal_edge_behavior`].
1840    pub fn set_directional_traversal_edge_behavior(
1841        self: Handle<Self>,
1842        app: &mut App,
1843        value: TraversalEdgeBehavior,
1844    ) {
1845        app.get_mut(self).scope.directional_traversal_edge_behavior = value;
1846    }
1847
1848    /// Returns true if this scope is the focused child of its parent scope.
1849    pub fn is_first_focus(self: Handle<Self>, app: &mut App) -> bool {
1850        let enclosing = self
1851            .enclosing_scope(app)
1852            .expect("a scope that is asked for isFirstFocus has an enclosing scope");
1853        enclosing.focused_child(app) == Some(self.as_node())
1854    }
1855
1856    /// Returns the child of this node that should receive focus if this scope node receives
1857    /// focus.
1858    ///
1859    /// If [`has_focus`](FocusNodeLeaf::has_focus) is true, then this points to the child of
1860    /// this node that is currently focused.
1861    ///
1862    /// Returns `None` if there is no currently focused child.
1863    pub fn focused_child(self: Handle<Self>, app: &mut App) -> Option<AnyFocusNode> {
1864        let last = app
1865            .get(self)
1866            .scope
1867            .focused_children
1868            .last()
1869            .map(Retained::handle);
1870        debug_assert!(match last {
1871            None => true,
1872            Some(last) => last.enclosing_scope(app) == Some(self),
1873        });
1874        last
1875    }
1876
1877    /// Make the given `scope` the active child scope for this scope.
1878    ///
1879    /// If the given `scope` is not yet a part of the focus tree, then add it to the tree as a
1880    /// child of this scope. If it is already part of the focus tree, the given scope must be a
1881    /// descendant of this scope.
1882    pub fn set_first_focus(self: Handle<Self>, app: &mut App, scope: Handle<FocusScopeNode>) {
1883        debug_assert!(scope != self, "Unexpected self-reference in setFirstFocus.");
1884        if scope.parent(app).is_none() {
1885            self.as_node().reparent_child(app, scope.as_node());
1886        }
1887        debug_assert!(
1888            scope.ancestors(app).contains(&self.as_node()),
1889            "A FocusScopeNode must be a child of this scope to set it as first focus."
1890        );
1891        if self.has_focus(app) {
1892            scope.do_request_focus(app, true);
1893        } else {
1894            scope.as_node().set_as_focused_child_for_scope(app);
1895        }
1896    }
1897
1898    /// If this scope lacks a focus, request that the given node become the focus.
1899    ///
1900    /// If the given node is not yet part of the focus tree, then add it as a child of this
1901    /// node.
1902    ///
1903    /// Useful for widgets that wish to grab the focus if no other widget already has the focus.
1904    ///
1905    /// The node is notified that it has received the primary focus in a microtask, so
1906    /// notification may lag the request by up to one frame.
1907    pub fn autofocus(self: Handle<Self>, app: &mut App, node: AnyFocusNode) {
1908        // Attach the node to the tree first, so in `apply_focus_change` if the node is detached
1909        // we don't add it back to the tree.
1910        if node.parent(app).is_none() {
1911            self.as_node().reparent_child(app, node);
1912        }
1913        debug_assert!(self.as_node().manager(app).is_some());
1914        if let Some(manager) = self.as_node().manager(app) {
1915            let autofocus = Autofocus {
1916                scope: self.keep(app),
1917                autofocus_node: node.keep(app),
1918            };
1919            app.get_mut(manager).pending_autofocuses.push(autofocus);
1920            manager.mark_needs_update(app);
1921        }
1922    }
1923
1924    /// Requests that the scope itself receive focus, without trying to find a descendant that
1925    /// should receive focus.
1926    ///
1927    /// This is used only if you want to park the focus on a scope itself.
1928    pub fn request_scope_focus(self: Handle<Self>, app: &mut App) {
1929        self.do_request_focus(app, false);
1930    }
1931}
1932
1933impl ChangeNotifier for FocusScopeNode {
1934    fn change_notifier_data(&self) -> &ChangeNotifierData {
1935        &self.change_notifier
1936    }
1937
1938    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1939        &mut self.change_notifier
1940    }
1941}
1942
1943impl FocusNodeLeaf for FocusScopeNode {
1944    crate::focus_node_accessors!();
1945
1946    fn as_scope(self: Handle<Self>) -> Option<Handle<FocusScopeNode>> {
1947        Some(self)
1948    }
1949
1950    fn nearest_scope(self: Handle<Self>, _app: &mut App) -> Option<Handle<FocusScopeNode>> {
1951        Some(self)
1952    }
1953
1954    fn descendants_are_focusable(self: Handle<Self>, app: &App) -> bool {
1955        app.get(self).focus_node.can_request_focus
1956            && FocusNode::descendants_are_focusable(self.as_node(), app)
1957    }
1958
1959    /// Will return an empty iterable if this scope node is not focusable, or if
1960    /// `descendants_are_focusable` is false.
1961    fn traversal_children(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
1962        if !self.can_request_focus(app) {
1963            return Vec::new();
1964        }
1965        FocusNode::traversal_children(self.as_node(), app)
1966    }
1967
1968    /// Will return an empty iterable if this scope node is not focusable, or if
1969    /// `descendants_are_focusable` is false.
1970    fn traversal_descendants(self: Handle<Self>, app: &mut App) -> Vec<AnyFocusNode> {
1971        if !self.can_request_focus(app) {
1972            return Vec::new();
1973        }
1974        FocusNode::traversal_descendants(self.as_node(), app)
1975    }
1976
1977    fn debug_fill_properties(
1978        self: Handle<Self>,
1979        app: &App,
1980        properties: &mut DiagnosticPropertiesBuilder,
1981    ) {
1982        fill_focus_node_properties(self, app, properties);
1983        if app.get(self).scope.focused_children.is_empty() {
1984            return;
1985        }
1986        let focused_children: Vec<FocusNodeRef> = app.get(self).scope.focused_children.clone();
1987        let child_list: Vec<String> = focused_children
1988            .iter()
1989            .rev()
1990            .map(|child| child.handle().to_string_short(app))
1991            .collect();
1992        properties.add(
1993            IterableProperty::<String>::new("focusedChildren", child_list)
1994                .default_value(Some(Vec::new())),
1995        );
1996        properties.add(
1997            DiagnosticsProperty::new(
1998                "traversalEdgeBehavior",
1999                app.get(self).scope.traversal_edge_behavior,
2000            )
2001            .default_value(Some(TraversalEdgeBehavior::ClosedLoop)),
2002        );
2003    }
2004
2005    fn do_request_focus(self: Handle<Self>, app: &mut App, find_first_focus: bool) {
2006        // It is possible that a previously focused child is no longer focusable, so clean out
2007        // the list if so.
2008        loop {
2009            let last = app
2010                .get(self)
2011                .scope
2012                .focused_children
2013                .last()
2014                .map(Retained::handle);
2015            let Some(last) = last else { break };
2016            if last.can_request_focus(app) && last.enclosing_scope(app).is_some() {
2017                break;
2018            }
2019            app.get_mut(self).scope.focused_children.pop();
2020        }
2021
2022        let focused_child = self.focused_child(app);
2023        // If find_first_focus is false, then the request is to make this scope the focus
2024        // instead of looking for the ultimate first focus for this scope and its descendants.
2025        let Some(focused_child) = focused_child.filter(|_| find_first_focus) else {
2026            if self.can_request_focus(app) {
2027                self.as_node().set_as_focused_child_for_scope(app);
2028                self.as_node().mark_next_focus(app, self.as_node());
2029            }
2030            return;
2031        };
2032
2033        focused_child.do_request_focus(app, true);
2034    }
2035}
2036
2037// ---------------------------------------------------------------------------------------------
2038// The highlight mode
2039
2040/// An enum to describe which kind of focus highlight behavior to use when displaying focus
2041/// information.
2042#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2043pub enum FocusHighlightMode {
2044    /// Touch interfaces will not show the focus highlight except for controls which bring up
2045    /// the soft keyboard.
2046    ///
2047    /// If a device that uses a traditional mouse and keyboard has a touch screen attached, it
2048    /// can also enter `touch` mode if the user is using the touch screen.
2049    Touch,
2050
2051    /// Traditional interfaces (keyboard and mouse) will show the currently focused control via
2052    /// a focus highlight of some sort.
2053    ///
2054    /// If a touch device (like a mobile phone) has a keyboard and/or mouse attached, it also
2055    /// can enter `traditional` mode if the user is using these input devices.
2056    Traditional,
2057}
2058
2059/// An enum to describe how the current value of [`FocusManager::highlight_mode`] is determined.
2060/// The strategy is set on [`FocusManager::set_highlight_strategy`].
2061#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2062pub enum FocusHighlightStrategy {
2063    /// Automatic switches between the various highlight modes based on the last kind of input
2064    /// that was received. This is the default.
2065    #[default]
2066    Automatic,
2067
2068    /// [`FocusManager::highlight_mode`] always returns [`FocusHighlightMode::Touch`].
2069    AlwaysTouch,
2070
2071    /// [`FocusManager::highlight_mode`] always returns [`FocusHighlightMode::Traditional`].
2072    AlwaysTraditional,
2073}
2074
2075// ---------------------------------------------------------------------------------------------
2076// FocusManager
2077
2078/// Dart's `_AppLifecycleListener`: the observer through which a [`FocusManager`] hears the
2079/// app's lifecycle, so that the manager itself is no binding observer.
2080struct AppLifecycleListener {
2081    on_lifecycle_state_changed: ValueChanged<AppLifecycleState>,
2082}
2083
2084impl WidgetsBindingObserver for AppLifecycleListener {
2085    fn did_change_app_lifecycle_state(&self, app: &mut App, state: AppLifecycleState) {
2086        (self.on_lifecycle_state_changed)(app, state);
2087    }
2088}
2089
2090/// Manages the focus tree.
2091///
2092/// The focus tree is a separate, sparser, tree from the widget tree that maintains the
2093/// hierarchical relationship between focusable widgets in the widget tree.
2094///
2095/// The focus manager is responsible for tracking which [`FocusNode`] has the primary input
2096/// focus (the [`primary_focus`](Self::primary_focus)), holding the [`FocusScopeNode`] that is
2097/// the root of the focus tree (the [`root_scope`](Self::root_scope)), and what the current
2098/// [`highlight_mode`](Self::highlight_mode) is. It also distributes [`KeyEvent`]s to the nodes
2099/// in the focus tree.
2100///
2101/// The singleton [`FocusManager`] instance is held by the `WidgetsBinding` as
2102/// `WidgetsBinding::focus_manager`, and can be conveniently accessed using the
2103/// [`FocusManager::instance`] accessor.
2104///
2105/// To find the [`FocusNode`] for a given `BuildContext`, use `Focus::of`. To find the
2106/// [`FocusScopeNode`] for a given `BuildContext`, use `FocusScope::of`.
2107///
2108/// If you would like notification whenever the [`primary_focus`](Self::primary_focus) changes,
2109/// register a listener with `add_listener`.
2110///
2111/// The [`highlight_mode`](Self::highlight_mode) describes how focus highlights should be
2112/// displayed on components in the UI. The highlight mode changes are notified separately via
2113/// [`add_highlight_mode_listener`](Self::add_highlight_mode_listener) and removed with
2114/// [`remove_highlight_mode_listener`](Self::remove_highlight_mode_listener).
2115pub struct FocusManager {
2116    change_notifier: ChangeNotifierData,
2117    highlight_manager: Ref<HighlightModeManager>,
2118    /// The root [`FocusScopeNode`] in the focus tree.
2119    root_scope: Ref<FocusScopeNode>,
2120    primary_focus: Option<FocusNodeRef>,
2121    /// The set of nodes that need to notify their listeners of changes at the next update.
2122    dirty_nodes: Vec<FocusNodeRef>,
2123    /// The node that has requested to have the primary focus, but hasn't been given it yet.
2124    marked_for_focus: Option<FocusNodeRef>,
2125    /// The list of autofocus requests made since the last `apply_focus_change` call.
2126    pending_autofocuses: Vec<Autofocus>,
2127    /// True indicates that there is an update pending.
2128    have_scheduled_update: bool,
2129    /// Allows the manager to respond to app lifecycle state changes, temporarily suspending
2130    /// the primary focus when the app is inactive.
2131    app_lifecycle_listener: Option<WidgetsBindingObserverRef>,
2132    /// The node that was focused before the app lifecycle changed. Will be restored as the
2133    /// primary focus once the app is resumed.
2134    suspended_node: Option<FocusNodeRef>,
2135}
2136
2137impl FocusManager {
2138    /// Creates an object that manages the focus tree.
2139    ///
2140    /// This constructor is rarely called directly. To access the [`FocusManager`], consider
2141    /// using the [`instance`](Self::instance) accessor instead (which gets it from the
2142    /// `WidgetsBinding` singleton).
2143    ///
2144    /// This newly constructed focus manager does not have the necessary event handlers
2145    /// registered to allow it to manage focus. To register those event handlers, callers must
2146    /// call [`register_global_handlers`](Self::register_global_handlers).
2147    pub fn new(app: &mut App) -> Ref<FocusManager> {
2148        let root_scope = FocusScopeNode::new(app);
2149        root_scope.set_debug_label(app, Some("Root Focus Scope".to_string()));
2150        let highlight_manager = HighlightModeManager::new(app);
2151        let this = app.create(FocusManager {
2152            change_notifier: ChangeNotifierData::new(),
2153            highlight_manager,
2154            root_scope: root_scope.clone(),
2155            primary_focus: None,
2156            dirty_nodes: Vec::new(),
2157            marked_for_focus: None,
2158            pending_autofocuses: Vec::new(),
2159            have_scheduled_update: false,
2160            app_lifecycle_listener: None,
2161            suspended_node: None,
2162        });
2163        this.listen_to_application_lifecycle_changes_if_supported(app);
2164        root_scope.focus_node_data_mut(app).manager = Some(this.handle());
2165        this
2166    }
2167
2168    /// Dart's `FocusManager.debugFillProperties`: the pending update, the primary focus and
2169    /// the node marked for it next. `primaryFocusCreator` is the element's debug creator chain,
2170    /// deferred with `debugCreator`.
2171    pub fn debug_fill_properties(
2172        self: Handle<Self>,
2173        app: &mut App,
2174        properties: &mut DiagnosticPropertiesBuilder,
2175    ) {
2176        let (have_scheduled_update, primary_focus, marked_for_focus) = {
2177            let manager = app.get(self);
2178            (
2179                manager.have_scheduled_update,
2180                manager.primary_focus.clone(),
2181                manager.marked_for_focus.clone(),
2182            )
2183        };
2184        properties.add(
2185            FlagProperty::new("haveScheduledUpdate", Some(have_scheduled_update))
2186                .if_true("UPDATE SCHEDULED"),
2187        );
2188        properties.add(
2189            DiagnosticsProperty::<String>::new(
2190                "primaryFocus",
2191                primary_focus.map(|node| node.to_string(app)),
2192            )
2193            .default_value(None),
2194        );
2195        properties.add(
2196            DiagnosticsProperty::<String>::new(
2197                "nextFocus",
2198                marked_for_focus.map(|node| node.to_string(app)),
2199            )
2200            .default_value(None),
2201        );
2202    }
2203
2204    /// Dart's `FocusManager.debugDescribeChildren`: the root scope.
2205    pub fn debug_describe_children(
2206        self: Handle<Self>,
2207        app: &mut App,
2208    ) -> Vec<Rc<dyn DiagnosticsNode>> {
2209        let root_scope = app.get(self).root_scope.handle();
2210        vec![Rc::new(
2211            root_scope
2212                .as_node()
2213                .to_diagnostics_node(app, Some("rootScope".to_string())),
2214        ) as Rc<dyn DiagnosticsNode>]
2215    }
2216
2217    /// Dart's `FocusManager.toStringShort`.
2218    pub fn to_string_short(self: Handle<Self>, _app: &App) -> String {
2219        describe_identity("FocusManager", self.id().identity_hash())
2220    }
2221
2222    /// Dart's `FocusManager.toStringDeep`: the manager and its focus tree, at Dart's default
2223    /// level (debug) and width.
2224    pub fn to_string_deep(self: Handle<Self>, app: &mut App) -> String {
2225        self.to_diagnostics_tree_node(app, None)
2226            .to_string_deep_with("", Some(""), None, DiagnosticLevel::Debug, 65)
2227    }
2228
2229    /// Dart's `FocusManager.toDiagnosticsNode(name:)`, from `DiagnosticableTree`.
2230    pub fn to_diagnostics_tree_node(
2231        self: Handle<Self>,
2232        app: &mut App,
2233        name: Option<String>,
2234    ) -> DiagnosticableTreeNode {
2235        let mut properties = DiagnosticPropertiesBuilder::new();
2236        self.debug_fill_properties(app, &mut properties);
2237        let short = self.to_string_short(app);
2238        let children = self.debug_describe_children(app);
2239        DiagnosticableTreeNode::from_parts(name, short, properties, children)
2240    }
2241
2242    /// It appears that some Android keyboard implementations can cause app lifecycle state
2243    /// changes: adding the app lifecycle listener would cause the text field to unfocus as the
2244    /// user is trying to type.
2245    ///
2246    /// Additionally, on iOS, input fields aren't automatically populated with relevant data
2247    /// when using autofill.
2248    ///
2249    /// Until these are resolved, we won't be adding the listener to mobile platforms.
2250    /// <https://github.com/flutter/flutter/issues/148475#issuecomment-2118407411>
2251    /// <https://github.com/flutter/flutter/pull/142930#issuecomment-1981750069>
2252    fn respond_to_lifecycle_change(app: &App) -> bool {
2253        K_IS_WEB
2254            || match app.platform().target_platform() {
2255                TargetPlatform::Android | TargetPlatform::IOS => false,
2256                TargetPlatform::Fuchsia | TargetPlatform::Linux => true,
2257                TargetPlatform::Windows | TargetPlatform::MacOS => true,
2258            }
2259    }
2260
2261    /// Enables this [`FocusManager`] to listen to changes of the application lifecycle if it
2262    /// does not already have an application lifecycle listener active, and the app isn't
2263    /// running on a native mobile platform.
2264    ///
2265    /// Typically, the application lifecycle listener for this [`FocusManager`] is set up at
2266    /// construction, but sometimes it is necessary to manually initialize it when the platform
2267    /// did not name the relevant target at the time of construction. This can happen in a test
2268    /// that changes the platform's target after the binding has built its [`FocusManager`]; the
2269    /// test then calls this method, so the [`FocusManager`] can accurately listen to
2270    /// application lifecycle changes, if supported.
2271    pub fn listen_to_application_lifecycle_changes_if_supported(self: Handle<Self>, app: &mut App) {
2272        if app.get(self).app_lifecycle_listener.is_none()
2273            && FocusManager::respond_to_lifecycle_change(app)
2274        {
2275            let listener: WidgetsBindingObserverRef = Rc::new(AppLifecycleListener {
2276                on_lifecycle_state_changed: Rc::new(move |app, state| {
2277                    self.app_lifecycle_change(app, state)
2278                }),
2279            });
2280            app.get_mut(self).app_lifecycle_listener = Some(Rc::clone(&listener));
2281            WidgetsBinding::instance(app).add_observer(app, listener);
2282        }
2283    }
2284
2285    /// Registers global input event handlers that are needed to manage focus.
2286    ///
2287    /// This calls `HardwareKeyboard::add_handler` on the shared instance of `HardwareKeyboard`
2288    /// and adds a route to the global entry in the gesture routing table. As such, only one
2289    /// [`FocusManager`] instance should register its global handlers.
2290    ///
2291    /// When this focus manager is no longer needed, calling [`dispose`](Self::dispose) on it
2292    /// will unregister these handlers.
2293    pub fn register_global_handlers(self: Handle<Self>, app: &mut App) {
2294        app.get(self)
2295            .highlight_manager
2296            .register_global_handlers(app);
2297    }
2298
2299    /// Discards any resources used by this object.
2300    pub fn dispose(self: Handle<Self>, app: &mut App) {
2301        if let Some(listener) = app.get(self).app_lifecycle_listener.clone() {
2302            WidgetsBinding::instance(app).remove_observer(app, &listener);
2303        }
2304        app.get(self).highlight_manager.dispose(app);
2305        self.root_scope(app).handle().dispose(app);
2306        ChangeNotifierData::dispose(app, self);
2307    }
2308
2309    /// Provides convenient access to the current [`FocusManager`] singleton from the
2310    /// `WidgetsBinding` instance.
2311    pub fn instance(app: &mut App) -> Handle<FocusManager> {
2312        WidgetsBinding::instance(app).focus_manager(app)
2313    }
2314
2315    /// The strategy by which [`highlight_mode`](Self::highlight_mode) is determined.
2316    ///
2317    /// If set to [`FocusHighlightStrategy::Automatic`], then the highlight mode will change
2318    /// depending upon the interaction mode used last.
2319    ///
2320    /// Defaults to [`FocusHighlightStrategy::Automatic`].
2321    pub fn highlight_strategy(self: Handle<Self>, app: &App) -> FocusHighlightStrategy {
2322        app.get(&app.get(self).highlight_manager).strategy
2323    }
2324
2325    /// See [`highlight_strategy`](Self::highlight_strategy).
2326    pub fn set_highlight_strategy(
2327        self: Handle<Self>,
2328        app: &mut App,
2329        value: FocusHighlightStrategy,
2330    ) {
2331        let highlight_manager = app.get(self).highlight_manager.handle();
2332        if app.get(highlight_manager).strategy == value {
2333            return;
2334        }
2335        highlight_manager.set_strategy(app, value);
2336    }
2337
2338    /// Indicates the current interaction mode for focus highlights.
2339    ///
2340    /// The value returned depends upon the
2341    /// [`highlight_strategy`](Self::highlight_strategy) used, and possibly the most recent
2342    /// interaction mode that the user used.
2343    ///
2344    /// If [`highlight_mode`](Self::highlight_mode) returns [`FocusHighlightMode::Touch`], then
2345    /// widgets should not draw their focus highlight unless they perform text entry.
2346    ///
2347    /// If it returns [`FocusHighlightMode::Traditional`], then widgets should draw their focus
2348    /// highlight whenever they are focused.
2349    pub fn highlight_mode(self: Handle<Self>, app: &mut App) -> FocusHighlightMode {
2350        app.get(self).highlight_manager.highlight_mode(app)
2351    }
2352
2353    /// Register a closure to be called when the [`FocusManager`] notifies its listeners that
2354    /// the value of [`highlight_mode`](Self::highlight_mode) has changed.
2355    pub fn add_highlight_mode_listener(
2356        self: Handle<Self>,
2357        app: &mut App,
2358        listener: HighlightModeListener,
2359    ) {
2360        app.get(self).highlight_manager.add_listener(app, listener);
2361    }
2362
2363    /// Remove a previously registered closure from the list of closures that the
2364    /// [`FocusManager`] notifies.
2365    pub fn remove_highlight_mode_listener(
2366        self: Handle<Self>,
2367        app: &mut App,
2368        listener: &HighlightModeListener,
2369    ) {
2370        app.get(self)
2371            .highlight_manager
2372            .remove_listener(app, listener);
2373    }
2374
2375    /// Adds a key event handler to a set of handlers that are called before any key event
2376    /// handlers in the focus tree are called.
2377    ///
2378    /// All of the handlers in the set will be called for every key event the [`FocusManager`]
2379    /// receives. If any one of the handlers returns [`KeyEventResult::Handled`] or
2380    /// [`KeyEventResult::SkipRemainingHandlers`], then none of the handlers in the focus tree
2381    /// will be called.
2382    pub fn add_early_key_event_handler(
2383        self: Handle<Self>,
2384        app: &mut App,
2385        handler: OnKeyEventCallback,
2386    ) {
2387        app.get(self)
2388            .highlight_manager
2389            .add_early_key_event_handler(app, handler);
2390    }
2391
2392    /// Removes a key handler added by calling
2393    /// [`add_early_key_event_handler`](Self::add_early_key_event_handler).
2394    pub fn remove_early_key_event_handler(
2395        self: Handle<Self>,
2396        app: &mut App,
2397        handler: &OnKeyEventCallback,
2398    ) {
2399        app.get(self)
2400            .highlight_manager
2401            .remove_early_key_event_handler(app, handler);
2402    }
2403
2404    /// Adds a key event handler to a set of handlers that are called if none of the key event
2405    /// handlers in the focus tree handle the event.
2406    ///
2407    /// If the event reaches the root of the focus tree without being handled, then all of the
2408    /// handlers in the set will be called. If any of them returns [`KeyEventResult::Handled`]
2409    /// or [`KeyEventResult::SkipRemainingHandlers`], then event propagation to the platform
2410    /// will be stopped.
2411    pub fn add_late_key_event_handler(
2412        self: Handle<Self>,
2413        app: &mut App,
2414        handler: OnKeyEventCallback,
2415    ) {
2416        app.get(self)
2417            .highlight_manager
2418            .add_late_key_event_handler(app, handler);
2419    }
2420
2421    /// Removes a key handler added by calling
2422    /// [`add_late_key_event_handler`](Self::add_late_key_event_handler).
2423    pub fn remove_late_key_event_handler(
2424        self: Handle<Self>,
2425        app: &mut App,
2426        handler: &OnKeyEventCallback,
2427    ) {
2428        app.get(self)
2429            .highlight_manager
2430            .remove_late_key_event_handler(app, handler);
2431    }
2432
2433    /// The root [`FocusScopeNode`] in the focus tree.
2434    ///
2435    /// This field is rarely used directly. To find the nearest [`FocusScopeNode`] for a given
2436    /// [`FocusNode`], call [`AnyFocusNode::nearest_scope`].
2437    pub fn root_scope(self: Handle<Self>, app: &App) -> &Ref<FocusScopeNode> {
2438        &app.get(self).root_scope
2439    }
2440
2441    /// The node that currently has the primary focus.
2442    pub fn primary_focus(self: Handle<Self>, app: &App) -> Option<AnyFocusNode> {
2443        app.get(self).primary_focus.handle()
2444    }
2445
2446    fn app_lifecycle_change(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
2447        let root_scope: FocusNodeRef = self.root_scope(app).erase();
2448        let root_has_primary_focus = self.primary_focus(app) == Some(root_scope.handle());
2449        if state == AppLifecycleState::Resumed {
2450            if !root_has_primary_focus {
2451                // The focus changed while the app was paused: the suspended node is ignored.
2452                app.get_mut(self).suspended_node = None;
2453            } else if let Some(suspended_node) = app.get(self).suspended_node.handle() {
2454                // Only restore the focus that was suspended when the app went inactive if
2455                // nothing else has requested focus in the meantime. For example, activating a
2456                // different window will cause its view to request focus.
2457                if app.get(self).marked_for_focus.is_none() {
2458                    suspended_node.request_focus(app, None);
2459                    app.get_mut(self).suspended_node = None;
2460                } else {
2461                    debug_assert!(app.get(self).have_scheduled_update);
2462                    app.get_mut(self).suspended_node = None;
2463                }
2464            }
2465        } else if !root_has_primary_focus {
2466            let manager = app.get_mut(self);
2467            manager.marked_for_focus = Some(root_scope);
2468            manager.suspended_node = manager.primary_focus.clone();
2469            self.apply_focus_changes_if_needed(app);
2470        }
2471    }
2472
2473    fn mark_detached(self: Handle<Self>, app: &mut App, node: AnyFocusNode) {
2474        // The node has been removed from the tree, so it no longer needs to be notified of
2475        // changes.
2476        let manager = app.get_mut(self);
2477        if manager.primary_focus.handle() == Some(node) {
2478            manager.primary_focus = None;
2479        }
2480        if manager.suspended_node.handle() == Some(node) {
2481            manager.suspended_node = None;
2482        }
2483        manager.dirty_nodes.retain(|dirty| dirty != node);
2484    }
2485
2486    fn mark_properties_changed(self: Handle<Self>, app: &mut App, node: AnyFocusNode) {
2487        self.mark_needs_update(app);
2488        add_dirty_node(app, self, node);
2489    }
2490
2491    fn mark_next_focus(self: Handle<Self>, app: &mut App, node: AnyFocusNode) {
2492        if self.primary_focus(app) == Some(node) {
2493            // The caller asked for the current focus to be the next focus, so just pretend that
2494            // didn't happen.
2495            app.get_mut(self).marked_for_focus = None;
2496        } else {
2497            let node = node.keep(app);
2498            app.get_mut(self).marked_for_focus = Some(node);
2499            self.mark_needs_update(app);
2500        }
2501    }
2502
2503    /// Request that an update be scheduled, optionally requesting focus for the given newFocus
2504    /// node.
2505    fn mark_needs_update(self: Handle<Self>, app: &mut App) {
2506        if app.get(self).have_scheduled_update {
2507            return;
2508        }
2509        app.get_mut(self).have_scheduled_update = true;
2510        app.schedule_microtask(Listener::handle_method(
2511            self,
2512            FocusManager::apply_focus_changes_if_needed,
2513        ));
2514    }
2515
2516    /// Applies any pending focus changes and notifies listeners that the focus has changed.
2517    ///
2518    /// Must not be called during the build phase. This method is meant to be called in a
2519    /// post-frame callback or microtask when the pending focus changes need to be resolved
2520    /// before something else occurs.
2521    ///
2522    /// It can't be called during the build phase because not all listeners are safe to be
2523    /// called with an update during a build.
2524    ///
2525    /// Typically, this is called automatically by the [`FocusManager`], but sometimes it is
2526    /// necessary to ensure that no focus changes are pending before executing an action.
2527    ///
2528    /// It is safe to call this if no focus changes are pending.
2529    pub fn apply_focus_changes_if_needed(self: Handle<Self>, app: &mut App) {
2530        debug_assert!(
2531            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
2532            "applyFocusChangesIfNeeded() should not be called during the build phase."
2533        );
2534
2535        app.get_mut(self).have_scheduled_update = false;
2536        let previous_focus = self.primary_focus(app);
2537
2538        for autofocus in std::mem::take(&mut app.get_mut(self).pending_autofocuses) {
2539            autofocus.apply_if_valid(app, self);
2540        }
2541
2542        if app.get(self).primary_focus.is_none() && app.get(self).marked_for_focus.is_none() {
2543            // If we don't have any current focus, and nobody has asked to focus yet, then
2544            // revert to the root scope.
2545            let root_scope: FocusNodeRef = self.root_scope(app).erase();
2546            app.get_mut(self).marked_for_focus = Some(root_scope);
2547        }
2548        // A node has requested to be the next focus, and isn't already the primary focus.
2549        let marked_for_focus = app.get(self).marked_for_focus.clone();
2550        if let Some(marked_for_focus) = marked_for_focus
2551            && Some(marked_for_focus.handle()) != self.primary_focus(app)
2552        {
2553            let previous_path = match previous_focus {
2554                Some(previous) => previous.ancestors(app),
2555                None => Vec::new(),
2556            };
2557            let next_path = marked_for_focus.ancestors(app);
2558            // Notify nodes that are newly focused.
2559            for node in next_path
2560                .iter()
2561                .filter(|node| !previous_path.contains(node))
2562            {
2563                add_dirty_node(app, self, *node);
2564            }
2565            // Notify nodes that are no longer focused.
2566            for node in previous_path
2567                .iter()
2568                .filter(|node| !next_path.contains(node))
2569            {
2570                add_dirty_node(app, self, *node);
2571            }
2572
2573            let manager = app.get_mut(self);
2574            manager.primary_focus = Some(marked_for_focus);
2575            manager.marked_for_focus = None;
2576        }
2577        debug_assert!(app.get(self).marked_for_focus.is_none());
2578        let primary_focus = self.primary_focus(app);
2579        if previous_focus != primary_focus {
2580            if let Some(previous_focus) = previous_focus {
2581                add_dirty_node(app, self, previous_focus);
2582            }
2583            if let Some(primary_focus) = primary_focus {
2584                add_dirty_node(app, self, primary_focus);
2585            }
2586        }
2587        for node in std::mem::take(&mut app.get_mut(self).dirty_nodes) {
2588            node.notify(app);
2589        }
2590        if previous_focus != primary_focus {
2591            self.notify_listeners(app);
2592        }
2593    }
2594}
2595
2596/// Dart's `_dirtyNodes.add(node)`: a set that keeps insertion order.
2597fn add_dirty_node(app: &mut App, manager: Handle<FocusManager>, node: AnyFocusNode) {
2598    if app
2599        .get(manager)
2600        .dirty_nodes
2601        .iter()
2602        .all(|dirty| dirty != node)
2603    {
2604        let node = node.keep(app);
2605        app.get_mut(manager).dirty_nodes.push(node);
2606    }
2607}
2608
2609impl ChangeNotifier for FocusManager {
2610    fn change_notifier_data(&self) -> &ChangeNotifierData {
2611        &self.change_notifier
2612    }
2613
2614    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2615        &mut self.change_notifier
2616    }
2617}
2618
2619// ---------------------------------------------------------------------------------------------
2620// The highlight mode manager
2621
2622/// A class to detect and manage the highlight mode transitions. An instance of this is owned by
2623/// the [`FocusManager`].
2624///
2625/// This doesn't hold a `ChangeNotifierData` because the callback passes the updated value, and
2626/// `ChangeNotifier` requires using a plain [`Listener`].
2627struct HighlightModeManager {
2628    /// If `None`, no interactions have occurred yet and the default highlight mode for the
2629    /// current platform applies.
2630    last_interaction_requires_traditional_highlights: Option<bool>,
2631    highlight_mode: Option<FocusHighlightMode>,
2632    strategy: FocusHighlightStrategy,
2633    /// The list of callbacks for early key handling.
2634    early_key_event_handlers: Vec<OnKeyEventCallback>,
2635    /// The list of callbacks for late key handling.
2636    late_key_event_handlers: Vec<OnKeyEventCallback>,
2637    /// The list of listeners for `highlight_mode` state changes.
2638    listeners: Vec<HighlightModeListener>,
2639    /// The handler `register_global_handlers` gave `HardwareKeyboard`, kept so that
2640    /// `dispose` can hand the same `Rc` back.
2641    key_event_handler: Option<KeyEventCallback>,
2642}
2643
2644impl HighlightModeManager {
2645    fn new(app: &mut App) -> Ref<HighlightModeManager> {
2646        app.create(HighlightModeManager {
2647            last_interaction_requires_traditional_highlights: None,
2648            highlight_mode: None,
2649            strategy: FocusHighlightStrategy::default(),
2650            early_key_event_handlers: Vec::new(),
2651            late_key_event_handlers: Vec::new(),
2652            listeners: Vec::new(),
2653            key_event_handler: None,
2654        })
2655    }
2656
2657    fn highlight_mode(self: Handle<Self>, app: &mut App) -> FocusHighlightMode {
2658        match app.get(self).highlight_mode {
2659            Some(mode) => mode,
2660            None => HighlightModeManager::default_mode_for_platform(app),
2661        }
2662    }
2663
2664    fn set_strategy(self: Handle<Self>, app: &mut App, value: FocusHighlightStrategy) {
2665        if app.get(self).strategy == value {
2666            return;
2667        }
2668        app.get_mut(self).strategy = value;
2669        self.update_mode(app);
2670    }
2671
2672    fn add_early_key_event_handler(
2673        self: Handle<Self>,
2674        app: &mut App,
2675        callback: OnKeyEventCallback,
2676    ) {
2677        app.get_mut(self).early_key_event_handlers.push(callback);
2678    }
2679
2680    fn remove_early_key_event_handler(
2681        self: Handle<Self>,
2682        app: &mut App,
2683        callback: &OnKeyEventCallback,
2684    ) {
2685        app.get_mut(self)
2686            .early_key_event_handlers
2687            .retain(|handler| !Rc::ptr_eq(handler, callback));
2688    }
2689
2690    fn add_late_key_event_handler(self: Handle<Self>, app: &mut App, callback: OnKeyEventCallback) {
2691        app.get_mut(self).late_key_event_handlers.push(callback);
2692    }
2693
2694    fn remove_late_key_event_handler(
2695        self: Handle<Self>,
2696        app: &mut App,
2697        callback: &OnKeyEventCallback,
2698    ) {
2699        app.get_mut(self)
2700            .late_key_event_handlers
2701            .retain(|handler| !Rc::ptr_eq(handler, callback));
2702    }
2703
2704    fn add_listener(self: Handle<Self>, app: &mut App, listener: HighlightModeListener) {
2705        app.get_mut(self).listeners.push(listener);
2706    }
2707
2708    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &HighlightModeListener) {
2709        app.get_mut(self)
2710            .listeners
2711            .retain(|registered| !Rc::ptr_eq(registered, listener));
2712    }
2713
2714    fn register_global_handlers(self: Handle<Self>, app: &mut App) {
2715        let handler: KeyEventCallback =
2716            Rc::new(move |app: &mut App, event: &KeyEvent| self.handle_key_event(app, event));
2717        app.get_mut(self).key_event_handler = Some(Rc::clone(&handler));
2718        HardwareKeyboard::instance(app).add_handler(app, handler);
2719        let router = GestureBinding::instance(app).pointer_router(app);
2720        router.add_global_route(
2721            app,
2722            PointerRoute::handle_method(self, HighlightModeManager::handle_pointer_event),
2723            None,
2724        );
2725        // Dart also listens for semantics actions here; accessibility waits.
2726    }
2727
2728    fn dispose(self: Handle<Self>, app: &mut App) {
2729        if let Some(handler) = app.get_mut(self).key_event_handler.take() {
2730            let router = GestureBinding::instance(app).pointer_router(app);
2731            router.remove_global_route(
2732                app,
2733                &PointerRoute::handle_method(self, HighlightModeManager::handle_pointer_event),
2734            );
2735            HardwareKeyboard::instance(app).remove_handler(app, &handler);
2736        }
2737        app.get_mut(self).listeners = Vec::new();
2738    }
2739
2740    fn notify_listeners(self: Handle<Self>, app: &mut App) {
2741        if app.get(self).listeners.is_empty() {
2742            return;
2743        }
2744        let highlight_mode = self.highlight_mode(app);
2745        // Make a copy to prevent problems if the list is modified during iteration.
2746        let local_listeners = app.get(self).listeners.clone();
2747        for listener in local_listeners {
2748            let still_registered = app
2749                .get(self)
2750                .listeners
2751                .iter()
2752                .any(|registered| Rc::ptr_eq(registered, &listener));
2753            if still_registered {
2754                listener(app, highlight_mode);
2755            }
2756        }
2757    }
2758
2759    fn handle_pointer_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
2760        match event.kind() {
2761            PointerDeviceKind::Touch
2762            | PointerDeviceKind::Stylus
2763            | PointerDeviceKind::InvertedStylus => {
2764                if app
2765                    .get(self)
2766                    .last_interaction_requires_traditional_highlights
2767                    != Some(true)
2768                {
2769                    app.get_mut(self)
2770                        .last_interaction_requires_traditional_highlights = Some(true);
2771                    self.update_mode(app);
2772                }
2773            }
2774            PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad | PointerDeviceKind::Unknown => {
2775            }
2776        }
2777    }
2778
2779    /// Dart's `handleKeyMessage`: the handler `HardwareKeyboard` calls for every key event.
2780    fn handle_key_event(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> bool {
2781        // Update highlight_mode first, since things responding to the keys might look at the
2782        // highlight mode, and it should be accurate.
2783        if app
2784            .get(self)
2785            .last_interaction_requires_traditional_highlights
2786            != Some(false)
2787        {
2788            app.get_mut(self)
2789                .last_interaction_requires_traditional_highlights = Some(false);
2790            self.update_mode(app);
2791        }
2792
2793        if FocusManager::instance(app).primary_focus(app).is_none() {
2794            return false;
2795        }
2796
2797        let mut handled = false;
2798        // Check to see if any of the early handlers handle the key. If so, then return early.
2799        if !app.get(self).early_key_event_handlers.is_empty() {
2800            // Make a copy to prevent problems if the list is modified during iteration.
2801            let callbacks = app.get(self).early_key_event_handlers.clone();
2802            let results: Vec<KeyEventResult> = callbacks
2803                .into_iter()
2804                .map(|callback| callback(app, event))
2805                .collect();
2806            match combine_key_event_results(results) {
2807                KeyEventResult::Ignored => {}
2808                KeyEventResult::Handled => handled = true,
2809                KeyEventResult::SkipRemainingHandlers => handled = false,
2810            }
2811        }
2812        if handled {
2813            return true;
2814        }
2815
2816        // Walk the current focus from the leaf to the root, calling each node's on_key_event on
2817        // the way up, and if one responds that they handled it or want to stop propagation,
2818        // stop.
2819        let primary_focus = FocusManager::instance(app)
2820            .primary_focus(app)
2821            .expect("checked above");
2822        let mut nodes = vec![primary_focus];
2823        nodes.extend(primary_focus.ancestors(app));
2824        for node in nodes {
2825            let results: Vec<KeyEventResult> = match node.on_key_event(app) {
2826                Some(on_key_event) => vec![on_key_event(app, node, event)],
2827                None => Vec::new(),
2828            };
2829            let result = combine_key_event_results(results);
2830            match result {
2831                KeyEventResult::Ignored => continue,
2832                KeyEventResult::Handled => handled = true,
2833                KeyEventResult::SkipRemainingHandlers => handled = false,
2834            }
2835            // Only KeyEventResult::Ignored will continue the loop. All other options will stop
2836            // the event propagation.
2837            debug_assert!(result != KeyEventResult::Ignored);
2838            break;
2839        }
2840
2841        // Check to see if any late key event handlers want to handle the event.
2842        if !handled && !app.get(self).late_key_event_handlers.is_empty() {
2843            // Make a copy to prevent problems if the list is modified during iteration.
2844            let callbacks = app.get(self).late_key_event_handlers.clone();
2845            let results: Vec<KeyEventResult> = callbacks
2846                .into_iter()
2847                .map(|callback| callback(app, event))
2848                .collect();
2849            match combine_key_event_results(results) {
2850                KeyEventResult::Ignored => {}
2851                KeyEventResult::Handled => handled = true,
2852                KeyEventResult::SkipRemainingHandlers => handled = false,
2853            }
2854        }
2855        handled
2856    }
2857
2858    /// Update function to be called whenever the state relating to `highlight_mode` changes.
2859    fn update_mode(self: Handle<Self>, app: &mut App) {
2860        let new_mode = match app.get(self).strategy {
2861            FocusHighlightStrategy::Automatic => {
2862                match app
2863                    .get(self)
2864                    .last_interaction_requires_traditional_highlights
2865                {
2866                    // If we don't have any information about the last interaction yet, then just
2867                    // rely on the default value for the platform, which will be determined based
2868                    // on the target platform if `highlight_mode` is not set.
2869                    None => return,
2870                    Some(true) => FocusHighlightMode::Touch,
2871                    Some(false) => FocusHighlightMode::Traditional,
2872                }
2873            }
2874            FocusHighlightStrategy::AlwaysTouch => FocusHighlightMode::Touch,
2875            FocusHighlightStrategy::AlwaysTraditional => FocusHighlightMode::Traditional,
2876        };
2877        // We can't just compare new_mode with `highlight_mode` here, since `highlight_mode`
2878        // could be unset, so we want to compare with the return value for the getter, since
2879        // that's what clients will be looking at.
2880        let old_mode = self.highlight_mode(app);
2881        app.get_mut(self).highlight_mode = Some(new_mode);
2882        if self.highlight_mode(app) != old_mode {
2883            self.notify_listeners(app);
2884        }
2885    }
2886
2887    fn default_mode_for_platform(app: &mut App) -> FocusHighlightMode {
2888        // Assume that if we're on one of the mobile platforms, and there's no mouse connected,
2889        // that the initial interaction will be touch-based, and that it's traditional mouse and
2890        // keyboard on all other platforms.
2891        //
2892        // This only affects the initial value: the ongoing value is updated to a known correct
2893        // value as soon as any pointer/keyboard events are received.
2894        match app.platform().target_platform() {
2895            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
2896                let mouse_tracker = RendererBinding::instance(app).mouse_tracker(app);
2897                if mouse_tracker.mouse_is_connected(app) {
2898                    FocusHighlightMode::Traditional
2899                } else {
2900                    FocusHighlightMode::Touch
2901                }
2902            }
2903            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
2904                FocusHighlightMode::Traditional
2905            }
2906        }
2907    }
2908}
2909
2910/// Provides convenient access to the current [`FocusManager::primary_focus`] from the
2911/// `WidgetsBinding` instance.
2912pub fn primary_focus(app: &mut App) -> Option<AnyFocusNode> {
2913    let manager = WidgetsBinding::instance(app).focus_manager(app);
2914    manager.primary_focus(app)
2915}
2916
2917/// Dart's `debugDescribeFocusTree`: the focus tree, with the current attributes of each node.
2918pub fn debug_describe_focus_tree(app: &mut App) -> String {
2919    let manager = WidgetsBinding::instance(app).focus_manager(app);
2920    manager.to_string_deep(app)
2921}
2922
2923// ---------------------------------------------------------------------------------------------
2924// TraversalEdgeBehavior
2925
2926/// Controls the transfer of focus beyond the first and the last items of a
2927/// [`FocusScopeNode`].
2928///
2929/// This enumeration only controls the traversal behavior performed by
2930/// `FocusTraversalPolicy`. Other methods of focus transfer, such as direct calls to
2931/// [`AnyFocusNode::request_focus`] and [`AnyFocusNode::unfocus`], are not affected by this
2932/// enumeration.
2933///
2934/// Dart declares this in `focus_traversal.dart`; it lives here, where [`FocusScopeNode`] reads
2935/// it.
2936#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2937pub enum TraversalEdgeBehavior {
2938    /// Keeps the focus among the items of the focus scope.
2939    ///
2940    /// Transfer focus to the edge node in the opposite direction of [`FocusScopeNode`] as the
2941    /// edge node continues to move, thus forming a closed loop of focusable items.
2942    #[default]
2943    ClosedLoop,
2944
2945    /// Allows the focus to leave the `FlutterView`.
2946    ///
2947    /// Requesting next focus after the last focusable item or previous to the first item will
2948    /// unfocus any focused nodes.
2949    LeaveFlutterView,
2950
2951    /// Allows focus to traverse up to parent scope.
2952    ///
2953    /// When reaching the edge of the current scope, requesting the next focus will look up to
2954    /// the parent scope of the current scope and focus the focus node next to the current
2955    /// scope.
2956    ///
2957    /// If there is no parent scope above the current scope, fallback to
2958    /// [`ClosedLoop`](Self::ClosedLoop) behavior.
2959    ParentScope,
2960
2961    /// Stops the focus traversal at the edge of the focus scope.
2962    ///
2963    /// Keeps the focus in its current position when it reaches the edge of a focus scope.
2964    Stop,
2965}
2966
2967/// Dart's enum `toString`, which a scope node's dump prints: the type and the case.
2968impl fmt::Display for TraversalEdgeBehavior {
2969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2970        write!(
2971            f,
2972            "TraversalEdgeBehavior.{}",
2973            waft_foundation::describe_enum(self)
2974        )
2975    }
2976}
2977
2978#[cfg(test)]
2979pub(crate) mod tests {
2980    use std::cell::{Cell, RefCell};
2981    use std::time::Duration;
2982
2983    use waft_embedder::{
2984        Matrix4, Rect, Size, SystemMouseCursorKind, TextEditingValue, TextInputConfiguration,
2985        TextInputHost, ViewFocusDirection, ViewFocusState, ViewHost,
2986    };
2987    use waft_services::{KeyDownEvent, LogicalKeyboardKey, PhysicalKeyboardKey, ServicesBinding};
2988    use waft_test::TestPlatform;
2989
2990    use super::*;
2991    use crate::framework::IntoWidget;
2992    use crate::testing::{TargetPlatformVariant, WidgetTester, test_widgets, test_widgets_variant};
2993    use crate::widgets::basic::{Builder, SizedBox};
2994
2995    /// A view's host whose text input answers whether it edits keys itself, and whether it
2996    /// provides Edit's commands.
2997    struct EditingHost {
2998        handles_editing_keys: bool,
2999        provides_edit_commands: bool,
3000    }
3001
3002    impl TextInputHost for EditingHost {
3003        fn set_client(&self, _configuration: &TextInputConfiguration) {}
3004
3005        fn show(&self) {}
3006
3007        fn update_config(&self, _configuration: &TextInputConfiguration) {}
3008
3009        fn clear_client(&self) {}
3010
3011        fn hide(&self) {}
3012
3013        fn set_editing_state(&self, _value: &TextEditingValue) {}
3014
3015        fn set_composing_rect(&self, _rect: Rect) {}
3016
3017        fn set_caret_rect(&self, _rect: Rect) {}
3018
3019        fn set_client_geometry(&self, _size: Size, _transform: &Matrix4) {}
3020
3021        fn handles_editing_keys(&self) -> bool {
3022            self.handles_editing_keys
3023        }
3024
3025        fn provides_edit_commands(&self) -> bool {
3026            self.provides_edit_commands
3027        }
3028    }
3029
3030    impl ViewHost for EditingHost {
3031        fn text_input(&self) -> Option<&dyn TextInputHost> {
3032            Some(self)
3033        }
3034
3035        fn activate_system_cursor(&self, _device: i64, _kind: SystemMouseCursorKind) {}
3036
3037        fn request_focus_change(&self, _state: ViewFocusState, _direction: ViewFocusDirection) {}
3038
3039        fn system_bars(&self) -> Option<&dyn waft_embedder::SystemBars> {
3040            None
3041        }
3042    }
3043
3044    /// A tester on a macOS host whose view's text input `host` answers for.
3045    fn tester_on_mac_with(host: EditingHost) -> WidgetTester {
3046        WidgetTester::with_view(
3047            TestPlatform::new().on(TargetPlatform::MacOS),
3048            waft_test::TestView::with_pixel_ratio(
3049                WidgetTester::SIZE.width() * WidgetTester::DEVICE_PIXEL_RATIO,
3050                WidgetTester::SIZE.height() * WidgetTester::DEVICE_PIXEL_RATIO,
3051                WidgetTester::DEVICE_PIXEL_RATIO,
3052            )
3053            .with_host(Rc::new(host)),
3054        )
3055    }
3056
3057    /// A tester over a macOS host that turns editing keys into edits itself, as Flutter's macOS
3058    /// and iOS embedders do.
3059    pub(crate) fn tester_whose_host_edits() -> WidgetTester {
3060        tester_on_mac_with(EditingHost {
3061            handles_editing_keys: true,
3062            provides_edit_commands: false,
3063        })
3064    }
3065
3066    /// A tester over a macOS host that reports plain keys and provides Edit's commands, as Waft's
3067    /// macOS host does with its Edit menu.
3068    pub(crate) fn tester_whose_host_provides_edit_commands() -> WidgetTester {
3069        tester_on_mac_with(EditingHost {
3070            handles_editing_keys: false,
3071            provides_edit_commands: true,
3072        })
3073    }
3074
3075    /// Pumps a tree that is one `Builder`, and answers that builder's context.
3076    fn pump_builder(tester: &mut WidgetTester) -> BuildContext {
3077        let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3078        let sink = Rc::clone(&captured);
3079        tester.pump_widget(Builder::new(move |_app, context| {
3080            sink.set(Some(context));
3081            SizedBox::shrink().into_widget()
3082        }));
3083        captured.get().expect("the builder ran")
3084    }
3085
3086    fn key_a_down() -> KeyEvent {
3087        KeyEvent::Down(KeyDownEvent::new(
3088            PhysicalKeyboardKey::KEY_A,
3089            LogicalKeyboardKey::KEY_A,
3090            Duration::ZERO,
3091        ))
3092    }
3093
3094    /// Attaches `node` under `parent`, the way a host widget's `initState` would.
3095    fn attach_under(
3096        app: &mut App,
3097        node: AnyFocusNode,
3098        context: BuildContext,
3099        parent: AnyFocusNode,
3100    ) -> Ref<FocusAttachment> {
3101        let attachment = node.attach(app, Some(context), None);
3102        attachment.reparent(app, Some(parent));
3103        attachment
3104    }
3105
3106    #[test]
3107    fn a_node_attached_under_a_scope_gains_primary_focus_on_request_focus() {
3108        test_widgets(|tester| {
3109            let context = pump_builder(tester);
3110            let mut app = tester.cell.borrow_mut();
3111            let manager = FocusManager::instance(&mut app);
3112            let root = manager.root_scope(&app).handle();
3113            let scope = FocusScopeNode::new(&mut app);
3114            attach_under(&mut app, scope.as_node(), context, root.as_node());
3115            let node = FocusNode::new(&mut app);
3116            attach_under(&mut app, node.as_node(), context, scope.as_node());
3117
3118            node.request_focus(&mut app, None);
3119            // The node is notified in a microtask, so the manager still has the old focus.
3120            assert!(!node.has_primary_focus(&app));
3121
3122            app.drain_microtasks();
3123            assert_eq!(manager.primary_focus(&app), Some(node.as_node()));
3124            assert!(node.has_primary_focus(&app));
3125            assert!(node.has_focus(&mut app));
3126            assert!(scope.has_focus(&mut app));
3127            assert!(!scope.has_primary_focus(&app));
3128            assert_eq!(scope.focused_child(&mut app), Some(node.as_node()));
3129        });
3130    }
3131
3132    #[test]
3133    fn unfocus_moves_the_focus_according_to_its_disposition() {
3134        test_widgets(|tester| {
3135            let context = pump_builder(tester);
3136            let mut app = tester.cell.borrow_mut();
3137            let manager = FocusManager::instance(&mut app);
3138            let root = manager.root_scope(&app).handle();
3139            let scope = FocusScopeNode::new(&mut app);
3140            attach_under(&mut app, scope.as_node(), context, root.as_node());
3141            let child1 = FocusNode::new(&mut app);
3142            attach_under(&mut app, child1.as_node(), context, scope.as_node());
3143            let child2 = FocusNode::new(&mut app);
3144            attach_under(&mut app, child2.as_node(), context, scope.as_node());
3145
3146            child1.request_focus(&mut app, None);
3147            app.drain_microtasks();
3148            child2.request_focus(&mut app, None);
3149            app.drain_microtasks();
3150            assert_eq!(manager.primary_focus(&app), Some(child2.as_node()));
3151
3152            // `previouslyFocusedChild` walks back down to the child focused before this one.
3153            child2.unfocus(&mut app, UnfocusDisposition::PreviouslyFocusedChild);
3154            app.drain_microtasks();
3155            assert_eq!(manager.primary_focus(&app), Some(child1.as_node()));
3156
3157            // `scope` clears the history and parks the focus on the enclosing scope.
3158            child1.unfocus(&mut app, UnfocusDisposition::Scope);
3159            app.drain_microtasks();
3160            assert_eq!(manager.primary_focus(&app), Some(scope.as_node()));
3161            assert_eq!(scope.focused_child(&mut app), None);
3162        });
3163    }
3164
3165    #[test]
3166    fn set_first_focus_adopts_the_scope_and_focuses_it_with_its_parent() {
3167        test_widgets(|tester| {
3168            let context = pump_builder(tester);
3169            let mut app = tester.cell.borrow_mut();
3170            let manager = FocusManager::instance(&mut app);
3171            let root = manager.root_scope(&app).handle();
3172            let scope1 = FocusScopeNode::new(&mut app);
3173            attach_under(&mut app, scope1.as_node(), context, root.as_node());
3174            let scope2 = FocusScopeNode::new(&mut app);
3175
3176            scope1.set_first_focus(&mut app, scope2.handle());
3177            assert_eq!(scope2.parent(&app), Some(scope1.as_node()));
3178            assert_eq!(scope1.focused_child(&mut app), Some(scope2.as_node()));
3179            assert!(!scope2.has_focus(&mut app));
3180
3181            scope1.request_focus(&mut app, None);
3182            app.drain_microtasks();
3183            assert_eq!(manager.primary_focus(&app), Some(scope2.as_node()));
3184        });
3185    }
3186
3187    #[test]
3188    fn a_node_that_cannot_request_focus_refuses_the_request() {
3189        test_widgets(|tester| {
3190            let context = pump_builder(tester);
3191            let mut app = tester.cell.borrow_mut();
3192            let manager = FocusManager::instance(&mut app);
3193            let root = manager.root_scope(&app).handle();
3194            let scope = FocusScopeNode::new(&mut app);
3195            attach_under(&mut app, scope.as_node(), context, root.as_node());
3196            let node = FocusNode::new(&mut app);
3197            attach_under(&mut app, node.as_node(), context, scope.as_node());
3198            node.set_can_request_focus(&mut app, false);
3199
3200            node.request_focus(&mut app, None);
3201            app.drain_microtasks();
3202            assert!(!node.has_primary_focus(&app));
3203            // Nothing asked for the focus, so it reverted to the root scope.
3204            assert_eq!(manager.primary_focus(&app), Some(root.as_node()));
3205        });
3206    }
3207
3208    #[test]
3209    fn descendants_are_focusable_false_unfocuses_and_blocks_the_descendants() {
3210        test_widgets(|tester| {
3211            let context = pump_builder(tester);
3212            let mut app = tester.cell.borrow_mut();
3213            let manager = FocusManager::instance(&mut app);
3214            let root = manager.root_scope(&app).handle();
3215            let scope = FocusScopeNode::new(&mut app);
3216            attach_under(&mut app, scope.as_node(), context, root.as_node());
3217            let node = FocusNode::new(&mut app);
3218            attach_under(&mut app, node.as_node(), context, scope.as_node());
3219
3220            node.request_focus(&mut app, None);
3221            app.drain_microtasks();
3222            assert_eq!(manager.primary_focus(&app), Some(node.as_node()));
3223
3224            // Dart unfocuses the node the flag was set on, so the focus leaves the scope for the
3225            // nearest focusable enclosing scope: the root.
3226            scope.set_descendants_are_focusable(&mut app, false);
3227            app.drain_microtasks();
3228            assert!(!scope.descendants_are_focusable(&app));
3229            assert!(!node.can_request_focus(&mut app));
3230            assert_eq!(manager.primary_focus(&app), Some(root.as_node()));
3231
3232            node.request_focus(&mut app, None);
3233            app.drain_microtasks();
3234            assert_eq!(manager.primary_focus(&app), Some(root.as_node()));
3235        });
3236    }
3237
3238    #[test]
3239    fn a_key_event_walks_from_the_primary_focus_to_the_root_until_one_handles_it() {
3240        test_widgets(|tester| {
3241            let context = pump_builder(tester);
3242            let mut app = tester.cell.borrow_mut();
3243            let manager = FocusManager::instance(&mut app);
3244            let root = manager.root_scope(&app).handle();
3245            let scope = FocusScopeNode::new(&mut app);
3246            attach_under(&mut app, scope.as_node(), context, root.as_node());
3247            let node = FocusNode::new(&mut app);
3248            attach_under(&mut app, node.as_node(), context, scope.as_node());
3249            node.request_focus(&mut app, None);
3250            app.drain_microtasks();
3251
3252            let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
3253            let result: Rc<Cell<KeyEventResult>> = Rc::new(Cell::new(KeyEventResult::Ignored));
3254            {
3255                let log = Rc::clone(&log);
3256                let result = Rc::clone(&result);
3257                node.set_on_key_event(
3258                    &mut app,
3259                    Some(Rc::new(move |_app, _node, _event| {
3260                        log.borrow_mut().push("node");
3261                        result.get()
3262                    })),
3263                );
3264            }
3265            {
3266                let log = Rc::clone(&log);
3267                scope.set_on_key_event(
3268                    &mut app,
3269                    Some(Rc::new(move |_app, _node, _event| {
3270                        log.borrow_mut().push("scope");
3271                        KeyEventResult::Ignored
3272                    })),
3273                );
3274            }
3275            {
3276                let log = Rc::clone(&log);
3277                root.set_on_key_event(
3278                    &mut app,
3279                    Some(Rc::new(move |_app, _node, _event| {
3280                        log.borrow_mut().push("root");
3281                        KeyEventResult::Ignored
3282                    })),
3283                );
3284            }
3285
3286            let keyboard = HardwareKeyboard::instance(&mut app);
3287            assert!(!keyboard.handle_key_event(&mut app, &key_a_down()));
3288            assert_eq!(*log.borrow(), vec!["node", "scope", "root"]);
3289
3290            log.borrow_mut().clear();
3291            result.set(KeyEventResult::Handled);
3292            assert!(keyboard.handle_key_event(&mut app, &key_a_down()));
3293            assert_eq!(*log.borrow(), vec!["node"]);
3294        });
3295    }
3296
3297    /// The host reports `state`, as Dart's test sends it on `flutter/lifecycle`.
3298    fn set_app_lifecycle_state(app: &mut App, state: AppLifecycleState) {
3299        ServicesBinding::instance(app).handle_lifecycle_message(app, state);
3300    }
3301
3302    /// The set-up the lifecycle tests share: a node in a scope under the root scope, with the
3303    /// primary focus.
3304    fn focused_node(tester: &mut WidgetTester) -> (Ref<FocusNode>, Ref<FocusAttachment>) {
3305        let context = pump_builder(tester);
3306        let (node, attachment) = {
3307            let mut app = tester.cell.borrow_mut();
3308            let root = FocusManager::instance(&mut app).root_scope(&app).handle();
3309            let scope = FocusScopeNode::new(&mut app);
3310            attach_under(&mut app, scope.as_node(), context, root.as_node());
3311            let node = FocusNode::new(&mut app);
3312            let attachment = attach_under(&mut app, node.as_node(), context, scope.as_node());
3313            node.request_focus(&mut app, None);
3314            app.drain_microtasks();
3315            assert!(node.has_primary_focus(&app));
3316            (node, attachment)
3317        };
3318        (node, attachment)
3319    }
3320
3321    #[test]
3322    fn focus_manager_ignores_app_lifecycle_changes_on_android_and_ios() {
3323        test_widgets_variant(
3324            TargetPlatformVariant::new([TargetPlatform::Android, TargetPlatform::IOS]),
3325            |tester| {
3326                let (node, _attachment) = focused_node(tester);
3327                let mut app = tester.cell.borrow_mut();
3328
3329                set_app_lifecycle_state(&mut app, AppLifecycleState::Paused);
3330                app.drain_microtasks();
3331                assert!(node.has_primary_focus(&app));
3332
3333                set_app_lifecycle_state(&mut app, AppLifecycleState::Resumed);
3334                app.drain_microtasks();
3335                assert!(node.has_primary_focus(&app));
3336            },
3337        );
3338    }
3339
3340    #[test]
3341    fn focus_manager_responds_to_app_lifecycle_changes() {
3342        test_widgets_variant(TargetPlatformVariant::desktop(), |tester| {
3343            let (node, _attachment) = focused_node(tester);
3344            let mut app = tester.cell.borrow_mut();
3345
3346            set_app_lifecycle_state(&mut app, AppLifecycleState::Paused);
3347            app.drain_microtasks();
3348            assert!(!node.has_primary_focus(&app));
3349
3350            set_app_lifecycle_state(&mut app, AppLifecycleState::Resumed);
3351            app.drain_microtasks();
3352            assert!(node.has_primary_focus(&app));
3353        });
3354    }
3355
3356    #[test]
3357    fn node_is_removed_completely_even_if_app_is_paused() {
3358        test_widgets(|tester| {
3359            let (node, attachment) = focused_node(tester);
3360            let mut app = tester.cell.borrow_mut();
3361
3362            set_app_lifecycle_state(&mut app, AppLifecycleState::Paused);
3363            app.drain_microtasks();
3364            attachment.detach(&mut app);
3365            assert!(!node.has_primary_focus(&app));
3366
3367            set_app_lifecycle_state(&mut app, AppLifecycleState::Resumed);
3368            app.drain_microtasks();
3369            assert!(!node.has_primary_focus(&app));
3370        });
3371    }
3372
3373    #[test]
3374    fn suspended_focus_is_not_restored_on_resume_when_another_node_claimed_focus() {
3375        test_widgets_variant(TargetPlatformVariant::desktop(), |tester| {
3376            let context = pump_builder(tester);
3377            let mut app = tester.cell.borrow_mut();
3378            let root = FocusManager::instance(&mut app).root_scope(&app).handle();
3379            let scope = FocusScopeNode::new(&mut app);
3380            attach_under(&mut app, scope.as_node(), context, root.as_node());
3381            let node_a = FocusNode::new(&mut app);
3382            attach_under(&mut app, node_a.as_node(), context, scope.as_node());
3383            let node_b = FocusNode::new(&mut app);
3384            attach_under(&mut app, node_b.as_node(), context, scope.as_node());
3385
3386            node_a.request_focus(&mut app, None);
3387            app.drain_microtasks();
3388            assert!(node_a.has_primary_focus(&app));
3389
3390            // App goes inactive: node A's focus is suspended and parked.
3391            set_app_lifecycle_state(&mut app, AppLifecycleState::Inactive);
3392            app.drain_microtasks();
3393            assert!(!node_a.has_primary_focus(&app));
3394
3395            // Another node requests focus before the app resumes (e.g. a different
3396            // window/view was activated).
3397            node_b.request_focus(&mut app, None);
3398
3399            // On resume, the suspended node A must not steal focus back from node B.
3400            set_app_lifecycle_state(&mut app, AppLifecycleState::Resumed);
3401            app.drain_microtasks();
3402            assert!(node_b.has_primary_focus(&app));
3403            assert!(!node_a.has_primary_focus(&app));
3404        });
3405    }
3406
3407    #[test]
3408    fn disposing_a_focused_node_moves_the_focus_to_its_scope() {
3409        test_widgets(|tester| {
3410            let context = pump_builder(tester);
3411            let mut app = tester.cell.borrow_mut();
3412            let manager = FocusManager::instance(&mut app);
3413            let root = manager.root_scope(&app).handle();
3414            let scope = FocusScopeNode::new(&mut app);
3415            attach_under(&mut app, scope.as_node(), context, root.as_node());
3416            let node = FocusNode::new(&mut app);
3417            attach_under(&mut app, node.as_node(), context, scope.as_node());
3418            node.request_focus(&mut app, None);
3419            app.drain_microtasks();
3420            assert_eq!(manager.primary_focus(&app), Some(node.as_node()));
3421
3422            node.dispose(&mut app);
3423            assert_eq!(manager.primary_focus(&app), None);
3424            assert_eq!(node.parent(&app), None);
3425
3426            app.drain_microtasks();
3427            assert_eq!(manager.primary_focus(&app), Some(scope.as_node()));
3428        });
3429    }
3430
3431    /// Dart's `Events change focus highlight mode.`, its key and tap steps, on Android.
3432    #[test]
3433    fn the_highlight_mode_follows_the_last_interaction() {
3434        test_widgets(|tester| {
3435            tester.pump_widget(SizedBox::shrink());
3436            let seen: Rc<RefCell<Vec<FocusHighlightMode>>> = Rc::default();
3437            tester.update(|app| {
3438                let manager = FocusManager::instance(app);
3439                let seen = Rc::clone(&seen);
3440                manager.add_highlight_mode_listener(
3441                    app,
3442                    Rc::new(move |_app, mode| seen.borrow_mut().push(mode)),
3443                );
3444                manager.set_highlight_strategy(app, FocusHighlightStrategy::Automatic);
3445            });
3446            let highlight_mode = |tester: &WidgetTester| {
3447                tester.update(|app| FocusManager::instance(app).highlight_mode(app))
3448            };
3449            // Android with no interaction yet.
3450            assert_eq!(highlight_mode(tester), FocusHighlightMode::Touch);
3451
3452            tester.send_key_event(
3453                PhysicalKeyboardKey::META_LEFT,
3454                LogicalKeyboardKey::META_LEFT,
3455            );
3456            assert_eq!(*seen.borrow(), vec![FocusHighlightMode::Traditional]);
3457            assert_eq!(highlight_mode(tester), FocusHighlightMode::Traditional);
3458
3459            tester.tap_at(Offset::ZERO, 1);
3460            assert_eq!(
3461                *seen.borrow(),
3462                vec![FocusHighlightMode::Traditional, FocusHighlightMode::Touch]
3463            );
3464            assert_eq!(highlight_mode(tester), FocusHighlightMode::Touch);
3465        });
3466    }
3467
3468    #[test]
3469    fn the_highlight_strategy_pins_the_mode() {
3470        test_widgets(|tester| {
3471            tester.pump_widget(SizedBox::shrink());
3472            let mut app = tester.cell.borrow_mut();
3473            let manager = FocusManager::instance(&mut app);
3474            manager.set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTouch);
3475            assert_eq!(
3476                manager.highlight_strategy(&app),
3477                FocusHighlightStrategy::AlwaysTouch
3478            );
3479            assert_eq!(manager.highlight_mode(&mut app), FocusHighlightMode::Touch);
3480
3481            HardwareKeyboard::instance(&mut app).handle_key_event(&mut app, &key_a_down());
3482            assert_eq!(manager.highlight_mode(&mut app), FocusHighlightMode::Touch);
3483        });
3484    }
3485
3486    #[test]
3487    fn combine_key_event_results_prefers_handled_then_skip() {
3488        assert_eq!(
3489            combine_key_event_results([KeyEventResult::Ignored, KeyEventResult::Ignored]),
3490            KeyEventResult::Ignored
3491        );
3492        assert_eq!(
3493            combine_key_event_results([
3494                KeyEventResult::Ignored,
3495                KeyEventResult::SkipRemainingHandlers
3496            ]),
3497            KeyEventResult::SkipRemainingHandlers
3498        );
3499        assert_eq!(
3500            combine_key_event_results([
3501                KeyEventResult::SkipRemainingHandlers,
3502                KeyEventResult::Handled
3503            ]),
3504            KeyEventResult::Handled
3505        );
3506    }
3507}
3508
3509#[cfg(test)]
3510mod diagnostics_tests {
3511    use waft_foundation::AppCell;
3512
3513    use super::*;
3514
3515    /// `focus_manager_test.dart`, "implements debugFillProperties": every property, hidden
3516    /// ones included, as that test maps them without filtering.
3517    fn described(node: AnyFocusNode, app: &mut App) -> Vec<String> {
3518        let mut properties = DiagnosticPropertiesBuilder::new();
3519        node.debug_fill_properties(app, &mut properties);
3520        properties
3521            .properties
3522            .iter()
3523            .map(|property| property.to_string_with(None, waft_foundation::DiagnosticLevel::Info))
3524            .collect()
3525    }
3526
3527    /// `focus_manager_test.dart`, "implements debugFillProperties" on a `FocusNode`.
3528    #[test]
3529    fn a_focus_node_describes_its_state() {
3530        let cell = AppCell::new();
3531        let mut app = cell.borrow_mut();
3532        let node = FocusNode::new(&mut app);
3533        assert_eq!(
3534            described(node.handle().as_node(), &mut app),
3535            [
3536                "context: null",
3537                "descendantsAreFocusable: true",
3538                "descendantsAreTraversable: true",
3539                "canRequestFocus: true",
3540                "hasFocus: false",
3541                "hasPrimaryFocus: false",
3542            ]
3543        );
3544    }
3545
3546    /// `focus_manager_test.dart`, "implements debugFillProperties" on a `FocusScopeNode`.
3547    #[test]
3548    fn a_focus_scope_node_describes_its_state() {
3549        let cell = AppCell::new();
3550        let mut app = cell.borrow_mut();
3551        let scope = FocusScopeNode::new(&mut app);
3552        assert_eq!(
3553            described(scope.handle().as_node(), &mut app),
3554            [
3555                "context: null",
3556                "descendantsAreFocusable: true",
3557                "descendantsAreTraversable: true",
3558                "canRequestFocus: true",
3559                "hasFocus: false",
3560                "hasPrimaryFocus: false",
3561            ]
3562        );
3563    }
3564}