Skip to main content

waft_widgets/widgets/
raw_tooltip.rs

1//! Flutter counterpart: `widgets/raw_tooltip.dart`.
2
3use std::any::Any;
4use std::collections::HashSet;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{
10    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
11    AnimationStatusListener, AnimationStyle, Curve, CurvedAnimation, Curves,
12};
13use waft_embedder::{Matrix4, Offset, PointerDeviceKind, Size, TextBaseline};
14use waft_foundation::{
15    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle, Listener,
16    OptionRetained, StringProperty, Timer,
17};
18use waft_gestures::{
19    GestureBinding, LongPressGestureRecognizer, PointerDownEvent, PointerEnterEvent,
20    PointerEnterEventListener, PointerEvent, PointerExitEvent, PointerExitEventListener,
21    PointerRoute, PrimaryPointerLeafData, TapGestureRecognizer,
22};
23use waft_painting::{position_dependent_box, transform_point};
24use waft_rendering::{
25    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestEntry, BoxHitTestResult,
26    HitTestBehavior, PaintingContext, PipelineOwner, RenderBox, RenderBoxData, RenderHandle,
27    RenderMouseRegionBase, RenderMouseRegionData, RenderObject, RenderObjectData,
28    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
29    RenderProxyBoxWithHitTestBehavior, SingleChildLayoutDelegate,
30};
31use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
32use waft_services::MouseTrackerAnnotation;
33
34use crate::framework::{
35    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
36    StateData, StatefulWidget, WidgetRef,
37};
38use crate::widgets::basic::{
39    CustomSingleChildLayout, IgnorePointer, Listener as PointerListener, MouseRegion, Positioned,
40    Semantics, SizedBox,
41};
42use crate::widgets::debug::debug_check_has_overlay;
43use crate::widgets::feedback::Feedback;
44use crate::widgets::media_query::MediaQuery;
45use crate::widgets::overlay::{OverlayChildLayoutInfo, OverlayPortal, OverlayPortalController};
46use crate::widgets::selection_container::SelectionContainer;
47use crate::widgets::ticker_provider::{
48    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
49};
50use waft_foundation::Ref;
51
52/// Dart's `Duration.toString`, which a tooltip's dump prints (`0:00:01.500000`).
53fn describe_duration(duration: Duration) -> String {
54    let micros = duration.as_micros();
55    let hours = micros / 3_600_000_000;
56    let minutes = (micros / 60_000_000) % 60;
57    let seconds = (micros / 1_000_000) % 60;
58    let micros = micros % 1_000_000;
59    format!("{hours}:{minutes:02}:{seconds:02}.{micros:06}")
60}
61
62/// Dart's `Diagnosticable.toString` for an animation style, which a tooltip's dump prints.
63fn describe_animation_style(style: &AnimationStyle) -> String {
64    format!(
65        "AnimationStyle(curve: {:?}, duration: {}, reverseCurve: {:?}, reverseDuration: {})",
66        style.curve,
67        style
68            .duration
69            .map_or_else(|| "null".to_string(), describe_duration),
70        style.reverse_curve,
71        style
72            .reverse_duration
73            .map_or_else(|| "null".to_string(), describe_duration),
74    )
75}
76
77/// Dart's `_kDefaultAnimationStyle`; a function so its curve is the one shared
78/// `Curves::fast_out_slow_in()`, which `AnimationStyle`'s `==` compares by identity.
79fn default_animation_style() -> AnimationStyle {
80    AnimationStyle::new(
81        Some(Curves::fast_out_slow_in()),
82        Some(Duration::from_millis(150)),
83        None,
84        Some(Duration::from_millis(75)),
85    )
86}
87
88/// Signature for building the tooltip overlay child.
89///
90/// The animation property exposes the underlying tooltip overlay child show
91/// and hide animation. This can be used to drive animations that sync up with
92/// the tooltip overlay child show/hide animation, for example to fade the
93/// tooltip in and out.
94pub type TooltipComponentBuilder =
95    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;
96
97/// Signature for computing the position of a tooltip.
98///
99/// The [`TooltipPositionContext`] contains all the necessary information for
100/// positioning the tooltip, including the target location, sizes, offset, and
101/// positioning preference.
102///
103/// Returns the offset from the top left of the overlay to the top left of the tooltip.
104///
105/// See also:
106///
107///  * [`TooltipPositionContext`], which contains the positioning parameters.
108pub type TooltipPositionDelegate = Rc<dyn Fn(TooltipPositionContext) -> Offset>;
109
110/// Contextual information for positioning a tooltip.
111///
112/// This immutable data class contains all the necessary information for computing
113/// the position of a tooltip relative to its target widget.
114///
115/// See also:
116///
117///  * [`TooltipPositionDelegate`], which uses this context to compute tooltip positions.
118// TODO(victorsanni): Consider removing preferBelow and verticalOffset since
119// they are already available in the context of RawTooltip.
120#[derive(Clone, Copy, Debug, PartialEq)]
121pub struct TooltipPositionContext {
122    /// The center point of the target widget in the global coordinate system.
123    pub target: Offset,
124
125    /// The size of the target widget that triggers the tooltip.
126    pub target_size: Size,
127
128    /// The size of the tooltip itself.
129    pub tooltip_size: Size,
130
131    /// The configured vertical offset.
132    pub vertical_offset: f64,
133
134    /// Whether the tooltip prefers to be positioned below the target.
135    pub prefer_below: bool,
136
137    /// The size of the overlay within which the tooltip is displayed.
138    pub overlay_size: Size,
139}
140
141impl TooltipPositionContext {
142    /// Creates a tooltip position context.
143    pub fn new(
144        target: Offset,
145        target_size: Size,
146        tooltip_size: Size,
147        vertical_offset: f64,
148    ) -> TooltipPositionContext {
149        TooltipPositionContext {
150            target,
151            target_size,
152            tooltip_size,
153            vertical_offset,
154            prefer_below: true,
155            overlay_size: Size::INFINITE,
156        }
157    }
158
159    /// Dart `TooltipPositionContext(preferBelow:)`.
160    pub fn prefer_below(mut self, prefer_below: bool) -> TooltipPositionContext {
161        self.prefer_below = prefer_below;
162        self
163    }
164
165    /// Dart `TooltipPositionContext(overlaySize:)`.
166    pub fn overlay_size(mut self, overlay_size: Size) -> TooltipPositionContext {
167        self.overlay_size = overlay_size;
168        self
169    }
170}
171
172/// How touch events should trigger a tooltip.
173///
174/// When using a pointer device like a mouse, a tooltip is shown as soon as
175/// a pointer hovers over the widget, regardless of the value of
176/// [`RawTooltip::trigger_mode`].
177///
178/// A tooltip might also be triggered through other means regardless of this
179/// option, such as by calling `ensure_tooltip_visible`.
180///
181/// See also:
182///
183///  * [`RawTooltip::trigger_mode`], which uses this enum.
184///
185/// See also:
186///
187///   * [`RawTooltip::hover_delay`], which defines the length of time that
188///     a pointer must hover over a tooltip's widget before the tooltip
189///     will be shown.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum TooltipTriggerMode {
192    /// Tooltip will not be triggered by touch events.
193    Manual,
194
195    /// Tooltip will be shown after a long press.
196    ///
197    /// See also:
198    ///
199    ///   * `GestureDetector.on_long_press`, the event that is used for trigger.
200    ///   * [`Feedback::for_long_press`], the feedback method called when feedback is enabled.
201    LongPress,
202
203    /// Tooltip will be shown after a single tap.
204    ///
205    /// See also:
206    ///
207    ///   * `GestureDetector.on_tap`, the event that is used for trigger.
208    ///   * [`Feedback::for_tap`], the feedback method called when feedback is enabled.
209    Tap,
210}
211
212/// Signature for when a tooltip is triggered.
213pub type TooltipTriggeredCallback = Listener;
214
215/// A special [`MouseRegion`] that when nested, only the first [`ExclusiveMouseRegion`]
216/// to be hit in hit-testing order will be added to the [`BoxHitTestResult`] (i.e.,
217/// child over parent, last sibling over first sibling).
218///
219/// The `on_enter` method will be called when a mouse pointer enters this
220/// [`MouseRegion`], and there is no other [`ExclusiveMouseRegion`]s obstructing
221/// this [`ExclusiveMouseRegion`] from receiving the events. This includes the
222/// case where the mouse cursor stays within the paint bounds of an outer
223/// [`ExclusiveMouseRegion`], but moves outside of the bounds of the inner
224/// [`ExclusiveMouseRegion`] that was initially blocking the outer widget.
225///
226/// Likewise, `on_exit` is called when the a mouse pointer moves out of the paint
227/// bounds of this widget, or moves into another [`ExclusiveMouseRegion`] that
228/// overlaps this widget in hit-testing order.
229///
230/// This widget doesn't affect [`MouseRegion`]s that aren't [`ExclusiveMouseRegion`]s,
231/// or other `HitTestTarget`s in the tree.
232///
233/// Dart's `_ExclusiveMouseRegion extends MouseRegion`: the inherited fields are the
234/// [`MouseRegion`] it holds.
235#[derive(Debug)]
236struct ExclusiveMouseRegion {
237    mouse_region: MouseRegion,
238}
239
240impl ExclusiveMouseRegion {
241    #[cfg_attr(debug_assertions, track_caller)]
242    fn new<K>(
243        on_enter: PointerEnterEventListener,
244        on_exit: PointerExitEventListener,
245        child: impl IntoWidget<K>,
246    ) -> ExclusiveMouseRegion {
247        ExclusiveMouseRegion {
248            mouse_region: MouseRegion::new()
249                .on_enter(on_enter)
250                .on_exit(on_exit)
251                .child(child),
252        }
253    }
254}
255
256impl RenderObjectWidget for ExclusiveMouseRegion {
257    type RenderObject = RenderExclusiveMouseRegion;
258
259    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
260        let render_object = RenderExclusiveMouseRegion::new(app);
261        render_object.set_on_enter(app, self.mouse_region.on_enter.clone());
262        render_object.set_on_exit(app, self.mouse_region.on_exit.clone());
263        render_object.as_object()
264    }
265
266    fn update_render_object(
267        &self,
268        app: &mut App,
269        _context: BuildContext,
270        render_object: RenderHandle<RenderExclusiveMouseRegion>,
271    ) {
272        self.mouse_region.apply_configuration(app, render_object);
273    }
274}
275
276impl SingleChildRenderObjectWidget for ExclusiveMouseRegion {
277    fn child(&self) -> Option<&WidgetRef> {
278        self.mouse_region.child.as_ref()
279    }
280}
281
282/// Dart's statics `_RenderExclusiveMouseRegion.isOutermostMouseRegion` and
283/// `foundInnermostMouseRegion`, kept per [`App`].
284struct ExclusiveMouseRegionHitTest {
285    is_outermost_mouse_region: bool,
286    found_innermost_mouse_region: bool,
287}
288
289impl Default for ExclusiveMouseRegionHitTest {
290    fn default() -> ExclusiveMouseRegionHitTest {
291        ExclusiveMouseRegionHitTest {
292            is_outermost_mouse_region: true,
293            found_innermost_mouse_region: false,
294        }
295    }
296}
297
298/// Dart's `_RenderExclusiveMouseRegion extends RenderMouseRegion`: a
299/// [`RenderMouseRegionBase`] leaf that overrides only `hit_test`.
300struct RenderExclusiveMouseRegion {
301    render_object: RenderObjectData,
302    render_box: RenderBoxData,
303    child: RenderObjectWithChildData<AnyRenderBox>,
304    mouse_region: RenderMouseRegionData,
305}
306
307impl RenderExclusiveMouseRegion {
308    fn new(app: &mut App) -> RenderHandle<RenderExclusiveMouseRegion> {
309        RenderHandle::new_box(
310            app,
311            RenderExclusiveMouseRegion {
312                render_object: RenderObjectData::new(),
313                render_box: RenderBoxData::new(),
314                child: RenderObjectWithChildData::new(),
315                mouse_region: RenderMouseRegionData::new(true),
316            },
317        )
318    }
319}
320
321impl RenderMouseRegionBase for RenderExclusiveMouseRegion {
322    fn mouse_region_data(self: RenderHandle<Self>, app: &App) -> &RenderMouseRegionData {
323        &self.get(app).mouse_region
324    }
325
326    fn mouse_region_data_mut(
327        self: RenderHandle<Self>,
328        app: &mut App,
329    ) -> &mut RenderMouseRegionData {
330        &mut self.get_mut(app).mouse_region
331    }
332}
333
334impl RenderObjectWithChildMixin for RenderExclusiveMouseRegion {
335    type ChildType = AnyRenderBox;
336
337    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
338        &self.get(app).child
339    }
340
341    fn child_data_mut(
342        self: RenderHandle<Self>,
343        app: &mut App,
344    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
345        &mut self.get_mut(app).child
346    }
347}
348
349impl RenderProxyBoxMixin for RenderExclusiveMouseRegion {
350    fn compute_size_for_no_child(
351        self: RenderHandle<Self>,
352        _app: &App,
353        constraints: BoxConstraints,
354    ) -> Size {
355        constraints.biggest()
356    }
357}
358
359impl RenderProxyBoxWithHitTestBehavior for RenderExclusiveMouseRegion {
360    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
361        self.mouse_region_data(app).behavior()
362    }
363}
364
365impl RenderObject for RenderExclusiveMouseRegion {
366    waft_rendering::render_object_accessors!();
367
368    fn debug_fill_properties(
369        self: RenderHandle<Self>,
370        app: &App,
371        properties: &mut DiagnosticPropertiesBuilder,
372    ) {
373        RenderMouseRegionBase::debug_fill_properties(self, app, properties);
374    }
375
376    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
377        RenderMouseRegionBase::did_attach(self, app, owner);
378    }
379
380    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
381        RenderMouseRegionBase::did_detach(self, app);
382    }
383
384    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
385        RenderProxyBoxMixin::perform_layout(self, app);
386    }
387
388    fn mouse_tracker_annotation(
389        self: RenderHandle<Self>,
390        app: &App,
391    ) -> Option<MouseTrackerAnnotation> {
392        RenderMouseRegionBase::mouse_tracker_annotation(self, app)
393    }
394
395    fn paint(
396        self: RenderHandle<Self>,
397        app: &mut App,
398        context: &mut PaintingContext,
399        offset: Offset,
400    ) {
401        RenderProxyBoxMixin::paint(self, app, context, offset);
402    }
403
404    fn visit_children(
405        self: RenderHandle<Self>,
406        app: &App,
407        visitor: &mut dyn FnMut(AnyRenderObject),
408    ) {
409        if let Some(child) = self.child(app) {
410            visitor(child.as_object());
411        }
412    }
413}
414
415impl RenderBox for RenderExclusiveMouseRegion {
416    waft_rendering::render_box_accessors!();
417
418    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
419        RenderProxyBoxMixin::setup_parent_data(self, app, child);
420    }
421
422    fn apply_paint_transform(
423        self: RenderHandle<Self>,
424        app: &App,
425        child: AnyRenderObject,
426        transform: &mut Matrix4,
427    ) {
428        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
429    }
430
431    fn hit_test(
432        self: RenderHandle<Self>,
433        app: &mut App,
434        result: &mut BoxHitTestResult<'_>,
435        position: Offset,
436    ) -> bool {
437        let statics = app.singleton::<ExclusiveMouseRegionHitTest>();
438        let mut is_hit = false;
439        let outermost = app.get(statics).is_outermost_mouse_region;
440        app.get_mut(statics).is_outermost_mouse_region = false;
441        if self.size(app).contains(position) {
442            is_hit = RenderBox::hit_test_children(self, app, result, position)
443                || RenderBox::hit_test_self(self, app, position);
444            if (is_hit || self.behavior(app) == HitTestBehavior::Translucent)
445                && !app.get(statics).found_innermost_mouse_region
446            {
447                app.get_mut(statics).found_innermost_mouse_region = true;
448                result.add(BoxHitTestEntry::new(self.as_box(), position).into());
449            }
450        }
451
452        if outermost {
453            // The outermost region resets the global states.
454            let statics = app.get_mut(statics);
455            statics.is_outermost_mouse_region = true;
456            statics.found_innermost_mouse_region = false;
457        }
458        is_hit
459    }
460
461    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
462        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
463    }
464
465    fn hit_test_children(
466        self: RenderHandle<Self>,
467        app: &mut App,
468        result: &mut BoxHitTestResult<'_>,
469        position: Offset,
470    ) -> bool {
471        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
472    }
473
474    fn handle_event(
475        self: RenderHandle<Self>,
476        app: &mut App,
477        event: &PointerEvent,
478        _entry: &BoxHitTestEntry,
479    ) {
480        RenderMouseRegionBase::handle_event(self, app, event);
481    }
482
483    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
484        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
485    }
486
487    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
488        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
489    }
490
491    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
492        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
493    }
494
495    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
496        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
497    }
498
499    fn compute_distance_to_actual_baseline(
500        self: RenderHandle<Self>,
501        app: &mut App,
502        baseline: TextBaseline,
503    ) -> Option<f64> {
504        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
505    }
506
507    fn compute_dry_baseline(
508        self: RenderHandle<Self>,
509        app: &mut App,
510        constraints: BoxConstraints,
511        baseline: TextBaseline,
512    ) -> Option<f64> {
513        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
514    }
515
516    fn compute_dry_layout(
517        self: RenderHandle<Self>,
518        app: &mut App,
519        constraints: BoxConstraints,
520    ) -> Size {
521        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
522    }
523}
524
525/// A widget that wraps a child to display an informative overlay in response to
526/// user interactions, such as hovering or long-pressing.
527///
528/// Tooltips provide essential context by displaying text labels or brief
529/// descriptions that explain the function of a button or other user interface
530/// elements.
531///
532/// The tooltip can be triggered in several ways:
533///
534///  * By hovering a mouse pointer over the widget.
535///  * By touch interactions, such as a long press or a tap, depending on the
536///    configuration of [`trigger_mode`](Self::trigger_mode).
537///  * Manually, by calling [`RawTooltipState::ensure_tooltip_visible`].
538///
539/// See also:
540///
541///   * `Tooltip`, a Material-themed [`RawTooltip`].
542pub struct RawTooltip {
543    pub key: Option<KeyRef>,
544
545    /// The text to display in the tooltip's semantics announcement.
546    ///
547    /// This string is used by assistive technologies, most notably screen readers
548    /// like TalkBack and VoiceOver, to describe the tooltip's purpose.
549    ///
550    /// Providing a non-empty string adds a `Semantics` tooltip string for
551    /// assistive technologies. If the tooltip should not have a semantic
552    /// description, this property must be explicitly set to `None`.
553    pub semantics_tooltip: Option<String>,
554
555    /// Builds the widget that will be displayed in the tooltip's overlay.
556    ///
557    /// The `animation` parameter is an [`Animation`] that maps to the tooltip's
558    /// show and hide animation. Its value goes from 0.0 to 1.0 when the tooltip
559    /// is shown, and from 1.0 to 0.0 when it is hidden.
560    ///
561    /// This animation can be used to create custom transitions for the tooltip,
562    /// such as fading or scaling, by wrapping the tooltip's content in a
563    /// `FadeTransition` or `ScaleTransition` and using the provided `animation`.
564    ///
565    /// The characteristics of the animation, such as its duration and curve, can
566    /// be customized using the [`animation_style`](Self::animation_style) property.
567    pub tooltip_builder: TooltipComponentBuilder,
568
569    /// The length of time that a pointer must hover over a tooltip's widget
570    /// before the tooltip will be shown.
571    ///
572    /// Defaults to 0 milliseconds (the tooltip is shown immediately upon hover).
573    pub hover_delay: Duration,
574
575    /// The length of time that the tooltip will be shown after a long press is
576    /// released (if trigger_mode is [`TooltipTriggerMode::LongPress`]) or a tap is
577    /// released (if trigger_mode is [`TooltipTriggerMode::Tap`]).
578    ///
579    /// This property does not affect mouse pointer devices.
580    ///
581    /// Defaults to 1.5 seconds (the tooltip is shown 1.5 seconds after a tap or
582    /// long press is released).
583    ///
584    /// See also:
585    ///
586    ///  * [`dismiss_delay`](Self::dismiss_delay), which allows configuring the time until a
587    ///    pointer disappears when hovering.
588    pub touch_delay: Duration,
589
590    /// The length of time that a pointer must have stopped hovering over a
591    /// tooltip's widget before the tooltip will be hidden.
592    ///
593    /// Defaults to 100 milliseconds.
594    ///
595    /// See also:
596    ///
597    ///  * [`touch_delay`](Self::touch_delay), which allows configuring the length of time that
598    ///    a tooltip will be visible after touch events are released.
599    pub dismiss_delay: Duration,
600
601    /// Whether the tooltip can be dismissed by tap.
602    ///
603    /// The default value is true.
604    pub enable_tap_to_dismiss: bool,
605
606    /// The [`TooltipTriggerMode`] that will show the tooltip.
607    ///
608    /// This property does not affect mouse devices. Setting [`trigger_mode`](Self::trigger_mode)
609    /// to [`TooltipTriggerMode::Manual`] will not prevent the tooltip from showing when
610    /// the mouse cursor hovers over it.
611    pub trigger_mode: TooltipTriggerMode,
612
613    /// Whether the tooltip should provide acoustic and/or haptic feedback.
614    ///
615    /// For example, on Android a tap will produce a clicking sound and a
616    /// long-press will produce a short vibration, when feedback is enabled.
617    ///
618    /// When null, the default value is true.
619    ///
620    /// See also:
621    ///
622    ///  * [`Feedback`], for providing platform-specific feedback to certain
623    ///    actions.
624    pub enable_feedback: bool,
625
626    /// Called when the [`RawTooltip`] is triggered programmatically, on tap, or on
627    /// long press.
628    ///
629    /// The tooltip is triggered after a tap when [`trigger_mode`](Self::trigger_mode) is
630    /// [`TooltipTriggerMode::Tap`] or after a long press when
631    /// [`trigger_mode`](Self::trigger_mode) is [`TooltipTriggerMode::LongPress`].
632    ///
633    /// Hovering over the tooltip with a mouse pointer does not trigger this
634    /// callback.
635    ///
636    /// See also:
637    ///
638    /// * [`TooltipTriggerMode`], which defines the different ways a tooltip can be
639    ///   triggered.
640    pub on_triggered: Option<TooltipTriggeredCallback>,
641
642    /// Used to override the curve and duration of the animation that shows and
643    /// hides the tooltip.
644    ///
645    /// If [`AnimationStyle::duration`] is provided, it will be used to override
646    /// the show tooltip animation duration. If it is null, defaults to 150ms.
647    ///
648    /// If [`AnimationStyle::curve`] is provided, it will be used to override
649    /// the show tooltip animation curve. If it is null, defaults to
650    /// `Curves::fast_out_slow_in`.
651    ///
652    /// If [`AnimationStyle::reverse_duration`] is provided, it will be used to
653    /// override the hide tooltip animation duration. If it is null, defaults to
654    /// 75ms.
655    ///
656    /// If [`AnimationStyle::reverse_curve`] is provided, it will be used to
657    /// override the hide tooltip animation curve. If it is null, the same curve will be
658    /// used as for the show tooltip animation. The reverse curve only takes
659    /// effect when the tooltip starts hiding from the fully shown state; a
660    /// tooltip dismissed while it is still animating in continues to use the
661    /// show curve, to avoid a visual discontinuity. See
662    /// [`CurvedAnimation::reverse_curve`].
663    ///
664    /// To disable the tooltip show/hide animation, use
665    /// [`AnimationStyle::NO_ANIMATION`].
666    // TODO(victorsanni): Add an example of chaining a physics-based animation to
667    // the tooltip's underlying animation.
668    pub animation_style: AnimationStyle,
669
670    /// A custom position delegate function for computing where the tooltip should
671    /// be positioned.
672    ///
673    /// If provided, this function will be called with a [`TooltipPositionContext`]
674    /// containing all the necessary information for positioning the tooltip. The
675    /// function should return an [`Offset`] indicating where to place the tooltip
676    /// in the closest [`Overlay`](crate::widgets::overlay::Overlay).
677    ///
678    /// This allows for custom positioning such as left/right positioning, or any
679    /// other arbitrary positioning logic.
680    ///
681    /// For example, if the `Overlay` takes up the entire screen, returning
682    /// [`Offset::ZERO`] will position the tooltip at the top-left corner of the
683    /// screen.
684    ///
685    /// The [`TooltipPositionContext`] provides information that can be used to
686    /// position the tooltip relative to the target/child.
687    ///
688    /// If null, defaults to positioning the tooltip center-aligned and below the
689    /// target using [`position_dependent_box`].
690    ///
691    /// See also:
692    ///
693    ///  * [`TooltipPositionContext`], which contains the positioning parameters.
694    ///  * [`TooltipPositionDelegate`], the function signature for custom
695    ///    positioning.
696    pub position_delegate: Option<TooltipPositionDelegate>,
697
698    /// Whether the tooltip should be invisible to hit testing.
699    ///
700    /// Defaults to false.
701    ///
702    /// See also:
703    ///
704    /// * [`IgnorePointer`], for more information about how pointer events are
705    ///   handled or ignored.
706    pub ignore_pointer: bool,
707
708    /// The widget below this widget in the tree.
709    ///
710    /// The widget returned in [`tooltip_builder`](Self::tooltip_builder) will be shown when
711    /// the user hovers over this child widget.
712    pub child: WidgetRef,
713}
714
715/// Dart's static `RawTooltip._openedTooltips`, kept per [`App`].
716#[derive(Default)]
717struct OpenedTooltips {
718    opened_tooltips: Vec<Handle<RawTooltipState>>,
719}
720
721impl OpenedTooltips {
722    fn instance(app: &mut App) -> Handle<OpenedTooltips> {
723        app.singleton::<OpenedTooltips>()
724    }
725
726    fn add(app: &mut App, tooltip: Handle<RawTooltipState>) {
727        let this = OpenedTooltips::instance(app);
728        app.get_mut(this).opened_tooltips.push(tooltip);
729    }
730
731    /// Dart's `List.remove`: the first occurrence only.
732    fn remove(app: &mut App, tooltip: Handle<RawTooltipState>) {
733        let this = OpenedTooltips::instance(app);
734        let opened_tooltips = &mut app.get_mut(this).opened_tooltips;
735        if let Some(index) = opened_tooltips.iter().position(|opened| *opened == tooltip) {
736            opened_tooltips.remove(index);
737        }
738    }
739
740    fn to_list(app: &mut App) -> Vec<Handle<RawTooltipState>> {
741        let this = OpenedTooltips::instance(app);
742        app.get(this).opened_tooltips.clone()
743    }
744}
745
746impl RawTooltip {
747    /// Creates a raw tooltip.
748    ///
749    /// The `semantics_tooltip`, `tooltip_builder`, and `child` arguments are
750    /// required.
751    #[cfg_attr(debug_assertions, track_caller)]
752    pub fn new<K>(
753        semantics_tooltip: Option<String>,
754        tooltip_builder: impl Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef + 'static,
755        child: impl IntoWidget<K>,
756    ) -> RawTooltip {
757        RawTooltip {
758            key: None,
759            semantics_tooltip,
760            tooltip_builder: Rc::new(tooltip_builder),
761            hover_delay: Duration::ZERO,
762            touch_delay: Duration::from_millis(1500),
763            dismiss_delay: Duration::from_millis(100),
764            enable_tap_to_dismiss: true,
765            trigger_mode: TooltipTriggerMode::LongPress,
766            enable_feedback: true,
767            on_triggered: None,
768            animation_style: default_animation_style(),
769            position_delegate: None,
770            ignore_pointer: false,
771            child: child.into_widget(),
772        }
773    }
774
775    /// Dart `RawTooltip(key:)`.
776    pub fn key(mut self, key: KeyRef) -> RawTooltip {
777        self.key = Some(key);
778        self
779    }
780
781    /// Dart `RawTooltip(hoverDelay:)`.
782    pub fn hover_delay(mut self, hover_delay: Duration) -> RawTooltip {
783        self.hover_delay = hover_delay;
784        self
785    }
786
787    /// Dart `RawTooltip(touchDelay:)`.
788    pub fn touch_delay(mut self, touch_delay: Duration) -> RawTooltip {
789        self.touch_delay = touch_delay;
790        self
791    }
792
793    /// Dart `RawTooltip(dismissDelay:)`.
794    pub fn dismiss_delay(mut self, dismiss_delay: Duration) -> RawTooltip {
795        self.dismiss_delay = dismiss_delay;
796        self
797    }
798
799    /// Dart `RawTooltip(enableTapToDismiss:)`.
800    pub fn enable_tap_to_dismiss(mut self, enable_tap_to_dismiss: bool) -> RawTooltip {
801        self.enable_tap_to_dismiss = enable_tap_to_dismiss;
802        self
803    }
804
805    /// Dart `RawTooltip(triggerMode:)`.
806    pub fn trigger_mode(mut self, trigger_mode: TooltipTriggerMode) -> RawTooltip {
807        self.trigger_mode = trigger_mode;
808        self
809    }
810
811    /// Dart `RawTooltip(enableFeedback:)`.
812    pub fn enable_feedback(mut self, enable_feedback: bool) -> RawTooltip {
813        self.enable_feedback = enable_feedback;
814        self
815    }
816
817    /// Dart `RawTooltip(onTriggered:)`.
818    pub fn on_triggered(mut self, on_triggered: TooltipTriggeredCallback) -> RawTooltip {
819        self.on_triggered = Some(on_triggered);
820        self
821    }
822
823    /// Dart `RawTooltip(animationStyle:)`.
824    pub fn animation_style(mut self, animation_style: AnimationStyle) -> RawTooltip {
825        self.animation_style = animation_style;
826        self
827    }
828
829    /// Dart `RawTooltip(positionDelegate:)`.
830    pub fn position_delegate(mut self, position_delegate: TooltipPositionDelegate) -> RawTooltip {
831        self.position_delegate = Some(position_delegate);
832        self
833    }
834
835    /// Dart `RawTooltip(ignorePointer:)`.
836    pub fn ignore_pointer(mut self, ignore_pointer: bool) -> RawTooltip {
837        self.ignore_pointer = ignore_pointer;
838        self
839    }
840
841    /// Dismiss all of the tooltips that are currently shown on the screen,
842    /// including those with mouse cursors currently hovering over them.
843    ///
844    /// This method returns true if it successfully dismisses at least one tooltip
845    /// and returns false if there is no tooltip currently displayed.
846    pub fn dismiss_all_tool_tips(app: &mut App) -> bool {
847        // Avoid concurrent modification.
848        let opened_tooltips = OpenedTooltips::to_list(app);
849        if opened_tooltips.is_empty() {
850            return false;
851        }
852        for state in opened_tooltips {
853            debug_assert!(state.mounted(app));
854            state.schedule_dismiss_tooltip(app, Duration::ZERO);
855        }
856        true
857    }
858}
859
860impl Debug for RawTooltip {
861    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
862        f.debug_struct("RawTooltip")
863            .field("key", &self.key)
864            .field("semantics", &self.semantics_tooltip)
865            .field("hover delay", &self.hover_delay)
866            .field("touch delay", &self.touch_delay)
867            .field("dismiss delay", &self.dismiss_delay)
868            .field("triggerMode", &self.trigger_mode)
869            .field("enableFeedback", &self.enable_feedback)
870            .field("positionDelegate", &self.position_delegate.is_some())
871            .field("animationStyle", &self.animation_style)
872            .finish_non_exhaustive()
873    }
874}
875
876impl StatefulWidget for RawTooltip {
877    type State = RawTooltipState;
878
879    fn key(&self) -> Option<&KeyRef> {
880        self.key.as_ref()
881    }
882
883    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
884        let empty = self
885            .semantics_tooltip
886            .as_deref()
887            .is_none_or(|tooltip| tooltip.is_empty());
888        let mut semantics =
889            StringProperty::new("semantics", self.semantics_tooltip.clone()).with_show_name(empty);
890        if empty {
891            semantics = semantics.default_value(None);
892        }
893        properties.add(semantics);
894        properties.add(
895            DiagnosticsProperty::<String>::new(
896                "hover delay",
897                Some(describe_duration(self.hover_delay)),
898            )
899            .default_value(None),
900        );
901        properties.add(
902            DiagnosticsProperty::<String>::new(
903                "touch delay",
904                Some(describe_duration(self.touch_delay)),
905            )
906            .default_value(None),
907        );
908        properties.add(
909            DiagnosticsProperty::<String>::new(
910                "dismiss delay",
911                Some(describe_duration(self.dismiss_delay)),
912            )
913            .default_value(None),
914        );
915        properties.add(
916            DiagnosticsProperty::<waft_foundation::DartEnum<TooltipTriggerMode>>::new(
917                "triggerMode",
918                Some(waft_foundation::DartEnum(self.trigger_mode)),
919            )
920            .default_value(None),
921        );
922        properties.add(
923            FlagProperty::new("enableFeedback", Some(self.enable_feedback))
924                .if_true("true")
925                .with_show_name(true),
926        );
927        properties.add(
928            DiagnosticsProperty::<String>::new(
929                "positionDelegate",
930                self.position_delegate
931                    .as_ref()
932                    .map(|_| "Instance of 'TooltipPositionDelegate'".to_string()),
933            )
934            .default_value(None),
935        );
936        if self.animation_style != default_animation_style() {
937            properties.add(DiagnosticsProperty::<String>::new(
938                "animationStyle",
939                Some(describe_animation_style(&self.animation_style)),
940            ));
941        }
942    }
943
944    fn create_state(&self) -> RawTooltipState {
945        RawTooltipState {
946            state: StateData::new(),
947            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
948            overlay_controller: None,
949            timer: None,
950            backing_controller: None,
951            backing_overlay_animation: None,
952            long_press_recognizer: None,
953            tap_recognizer: None,
954            active_hovering_pointer_devices: HashSet::new(),
955            animation_status: AnimationStatus::Dismissed,
956        }
957    }
958}
959
960/// Contains the state for a [`RawTooltip`].
961///
962/// This class can be used to programmatically show the [`RawTooltip`]. See the
963/// [`ensure_tooltip_visible`](Self::ensure_tooltip_visible) method.
964pub struct RawTooltipState {
965    state: StateData<RawTooltip>,
966    single_ticker_provider: SingleTickerProviderStateMixinData,
967    /// Created in `init_state`, because a state is created without the [`App`].
968    overlay_controller: Option<Ref<OverlayPortalController>>,
969
970    timer: Option<Timer>,
971    backing_controller: Option<Ref<AnimationController>>,
972    backing_overlay_animation: Option<Ref<CurvedAnimation>>,
973
974    long_press_recognizer: Option<Ref<LongPressGestureRecognizer>>,
975    tap_recognizer: Option<Ref<TapGestureRecognizer>>,
976
977    // The ids of mouse devices that are keeping the tooltip from being dismissed.
978    //
979    // Device ids are added to this set in handle_mouse_enter, and removed in
980    // handle_mouse_exit. The set is cleared in handle_tap_to_dismiss, typically when
981    // a PointerDown event interacts with some other UI component.
982    active_hovering_pointer_devices: HashSet<i64>,
983
984    animation_status: AnimationStatus,
985}
986
987impl RawTooltipState {
988    fn overlay_controller(self: Handle<Self>, app: &App) -> Handle<OverlayPortalController> {
989        app.get(self)
990            .overlay_controller
991            .handle()
992            .expect("created in init_state")
993    }
994
995    fn show_duration(self: Handle<Self>, app: &App) -> Duration {
996        self.widget(app)
997            .animation_style
998            .duration
999            .or(default_animation_style().duration)
1000            .expect("the default style has a duration")
1001    }
1002
1003    fn hide_duration(self: Handle<Self>, app: &App) -> Duration {
1004        self.widget(app)
1005            .animation_style
1006            .reverse_duration
1007            .or(default_animation_style().reverse_duration)
1008            .expect("the default style has a reverse duration")
1009    }
1010
1011    fn show_curve(self: Handle<Self>, app: &App) -> Rc<dyn Curve> {
1012        self.widget(app)
1013            .animation_style
1014            .curve
1015            .clone()
1016            .or(default_animation_style().curve)
1017            .expect("the default style has a curve")
1018    }
1019
1020    fn hide_curve(self: Handle<Self>, app: &App) -> Option<Rc<dyn Curve>> {
1021        self.widget(app).animation_style.reverse_curve.clone()
1022    }
1023
1024    fn controller(self: Handle<Self>, app: &mut App) -> Handle<AnimationController> {
1025        if let Some(controller) = app.get(self).backing_controller.handle() {
1026            return controller;
1027        }
1028        let show_duration = self.show_duration(app);
1029        let hide_duration = self.hide_duration(app);
1030        let controller = AnimationController::new(
1031            app,
1032            None,
1033            Some(show_duration),
1034            Some(hide_duration),
1035            0.0,
1036            1.0,
1037            AnimationBehavior::Normal,
1038            self,
1039        );
1040        controller.add_status_listener(
1041            app,
1042            AnimationStatusListener::handle_method(self, Self::handle_status_changed),
1043        );
1044        let handle = controller.handle();
1045        app.get_mut(self).backing_controller = Some(controller);
1046        handle
1047    }
1048
1049    fn overlay_animation(self: Handle<Self>, app: &mut App) -> Handle<CurvedAnimation> {
1050        if let Some(overlay_animation) = app.get(self).backing_overlay_animation.handle() {
1051            return overlay_animation;
1052        }
1053        self.controller(app);
1054        let parent: AnimationRef<f64> = app
1055            .get(self)
1056            .backing_controller
1057            .as_ref()
1058            .expect("made above")
1059            .erase();
1060        let show_curve = self.show_curve(app);
1061        let hide_curve = self.hide_curve(app);
1062        let overlay_animation = CurvedAnimation::new(app, parent, show_curve, hide_curve);
1063        let handle = overlay_animation.handle();
1064        app.get_mut(self).backing_overlay_animation = Some(overlay_animation);
1065        handle
1066    }
1067
1068    fn handle_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
1069        debug_assert!(self.mounted(app));
1070        match (
1071            app.get(self).animation_status.is_dismissed(),
1072            status.is_dismissed(),
1073        ) {
1074            (false, true) => {
1075                OpenedTooltips::remove(app, self);
1076                self.overlay_controller(app).hide(app);
1077            }
1078            (true, false) => {
1079                self.overlay_controller(app).show(app);
1080                OpenedTooltips::add(app, self);
1081            }
1082            (true, true) | (false, false) => {}
1083        }
1084        app.get_mut(self).animation_status = status;
1085    }
1086
1087    fn schedule_show_tooltip(
1088        self: Handle<Self>,
1089        app: &mut App,
1090        with_delay: Duration,
1091        touch_delay: Option<Duration>,
1092    ) {
1093        debug_assert!(self.mounted(app));
1094        fn show(this: Handle<RawTooltipState>, app: &mut App, touch_delay: Option<Duration>) {
1095            debug_assert!(this.mounted(app));
1096
1097            this.controller(app).forward(app, None);
1098            let controller = app
1099                .get(this)
1100                .backing_controller
1101                .clone()
1102                .expect("made above");
1103            if let Some(timer) = app.get(this).timer {
1104                timer.cancel(app);
1105            }
1106            let timer = touch_delay.map(|touch_delay| {
1107                Timer::new(
1108                    app,
1109                    touch_delay,
1110                    Listener::new(move |app| {
1111                        controller.reverse(app, None);
1112                    }),
1113                )
1114            });
1115            app.get_mut(this).timer = timer;
1116        }
1117
1118        debug_assert!(
1119            !app.get(self)
1120                .timer
1121                .is_some_and(|timer| timer.is_active(app))
1122                || app
1123                    .get(self)
1124                    .backing_controller
1125                    .as_ref()
1126                    .is_none_or(|controller| controller.status(app) != AnimationStatus::Reverse),
1127            "timer must not be active when the tooltip is animating out"
1128        );
1129        let controller = self.controller(app);
1130        if controller.is_dismissed(app) && !with_delay.is_zero() {
1131            if let Some(timer) = app.get(self).timer {
1132                timer.cancel(app);
1133            }
1134            let timer = Timer::new(
1135                app,
1136                with_delay,
1137                Listener::new(move |app| show(self, app, touch_delay)),
1138            );
1139            app.get_mut(self).timer = Some(timer);
1140        } else {
1141            // If the tooltip is already animating in or fully visible, skip
1142            // the animation and show the tooltip immediately.
1143            show(self, app, touch_delay);
1144        }
1145    }
1146
1147    fn schedule_dismiss_tooltip(self: Handle<Self>, app: &mut App, with_delay: Duration) {
1148        debug_assert!(self.mounted(app));
1149        debug_assert!(
1150            !app.get(self)
1151                .timer
1152                .is_some_and(|timer| timer.is_active(app))
1153                || app
1154                    .get(self)
1155                    .backing_controller
1156                    .as_ref()
1157                    .is_none_or(|controller| controller.status(app) != AnimationStatus::Reverse),
1158            "timer must not be active when the tooltip is animating out"
1159        );
1160
1161        if let Some(timer) = app.get_mut(self).timer.take() {
1162            timer.cancel(app);
1163        }
1164        // Use backing_controller instead of controller to prevent the lazy getter
1165        // from instantiating an AnimationController unnecessarily.
1166        if app
1167            .get(self)
1168            .backing_controller
1169            .as_ref()
1170            .is_some_and(|controller| controller.is_forward_or_completed(app))
1171        {
1172            let controller = self.controller(app);
1173            // Dismiss when the tooltip is animating in: if there's a dismiss delay
1174            // we'll allow the animation to continue until the delay timer fires.
1175            if !with_delay.is_zero() {
1176                let timer = Timer::new(
1177                    app,
1178                    with_delay,
1179                    Listener::new(move |app| {
1180                        controller.reverse(app, None);
1181                    }),
1182                );
1183                app.get_mut(self).timer = Some(timer);
1184            } else {
1185                controller.reverse(app, None);
1186            }
1187        }
1188    }
1189
1190    fn handle_pointer_down(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
1191        // PointerDeviceKinds that don't support hovering.
1192        let trigger_mode_device_kinds = [
1193            PointerDeviceKind::InvertedStylus,
1194            PointerDeviceKind::Stylus,
1195            PointerDeviceKind::Touch,
1196            PointerDeviceKind::Unknown,
1197            // MouseRegion only tracks PointerDeviceKind == mouse.
1198            PointerDeviceKind::Trackpad,
1199        ];
1200        match self.widget(app).trigger_mode {
1201            TooltipTriggerMode::LongPress => {
1202                let recognizer = match app.get(self).long_press_recognizer.handle() {
1203                    Some(recognizer) => recognizer,
1204                    None => {
1205                        let recognizer = LongPressGestureRecognizer::new(app)
1206                            .supported_devices(app, trigger_mode_device_kinds);
1207                        let handle = recognizer.handle();
1208                        app.get_mut(self).long_press_recognizer = Some(recognizer);
1209                        handle
1210                    }
1211                };
1212                recognizer.set_on_long_press_cancel(
1213                    app,
1214                    Some(Listener::handle_method(self, Self::handle_tap_to_dismiss)),
1215                );
1216                recognizer.set_on_long_press(
1217                    app,
1218                    Some(Listener::handle_method(self, Self::handle_long_press)),
1219                );
1220                recognizer.set_on_long_press_up(
1221                    app,
1222                    Some(Listener::handle_method(self, Self::handle_press_up)),
1223                );
1224                recognizer.add_pointer(app, event);
1225            }
1226            TooltipTriggerMode::Tap => {
1227                let recognizer = match app.get(self).tap_recognizer.handle() {
1228                    Some(recognizer) => recognizer,
1229                    None => {
1230                        let recognizer = TapGestureRecognizer::new(app)
1231                            .supported_devices(app, trigger_mode_device_kinds);
1232                        let handle = recognizer.handle();
1233                        app.get_mut(self).tap_recognizer = Some(recognizer);
1234                        handle
1235                    }
1236                };
1237                recognizer.set_on_tap_cancel(
1238                    app,
1239                    Some(Listener::handle_method(self, Self::handle_tap_to_dismiss)),
1240                );
1241                recognizer.set_on_tap(app, Some(Listener::handle_method(self, Self::handle_tap)));
1242                recognizer.add_pointer(app, event);
1243            }
1244            TooltipTriggerMode::Manual => {}
1245        }
1246    }
1247
1248    // For PointerDownEvents, this method will be called after handle_pointer_down.
1249    fn handle_global_pointer_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
1250        debug_assert!(self.mounted(app));
1251        let pointer = Some(event.pointer());
1252        let tap_primary_pointer = app
1253            .get(self)
1254            .tap_recognizer
1255            .as_ref()
1256            .and_then(|recognizer| app.get(recognizer).primary().primary_pointer());
1257        let long_press_primary_pointer = app
1258            .get(self)
1259            .long_press_recognizer
1260            .as_ref()
1261            .and_then(|recognizer| app.get(recognizer).primary().primary_pointer());
1262        if tap_primary_pointer == pointer || long_press_primary_pointer == pointer {
1263            // This is a pointer of interest specified by the trigger mode, since it's
1264            // picked up by the recognizer.
1265            //
1266            // The recognizer will later determine if this is indeed a "trigger"
1267            // gesture and dismiss the tooltip if that's not the case. However there's
1268            // still a chance that the PointerEvent was cancelled before the gesture
1269            // recognizer gets to emit a tap/longPress down, in which case the onCancel
1270            // callback (handle_tap_to_dismiss) will not be called.
1271            return;
1272        }
1273        if (app.get(self).timer.is_none() && self.controller(app).is_dismissed(app))
1274            || !matches!(event, PointerEvent::Down(_))
1275        {
1276            return;
1277        }
1278        self.handle_tap_to_dismiss(app);
1279    }
1280
1281    // The primary pointer is not part of a "trigger" gesture so the tooltip
1282    // should be dismissed.
1283    fn handle_tap_to_dismiss(self: Handle<Self>, app: &mut App) {
1284        if !self.widget(app).enable_tap_to_dismiss {
1285            return;
1286        }
1287        self.schedule_dismiss_tooltip(app, Duration::ZERO);
1288        app.get_mut(self).active_hovering_pointer_devices.clear();
1289    }
1290
1291    fn handle_tap(self: Handle<Self>, app: &mut App) {
1292        let tooltip_created = self.controller(app).is_dismissed(app);
1293        if tooltip_created && self.widget(app).enable_feedback {
1294            debug_assert!(self.widget(app).trigger_mode == TooltipTriggerMode::Tap);
1295            Feedback::for_tap(app, self.context(app));
1296        }
1297        if let Some(on_triggered) = self.widget(app).on_triggered.clone() {
1298            on_triggered.call(app);
1299        }
1300        let touch_delay = if app.get(self).active_hovering_pointer_devices.is_empty() {
1301            Some(self.widget(app).touch_delay)
1302        } else {
1303            // active_hovering_pointer_devices keep the tooltip visible.
1304            None
1305        };
1306        self.schedule_show_tooltip(app, Duration::ZERO, touch_delay);
1307    }
1308
1309    // When a "trigger" gesture is recognized and the pointer down even is a part
1310    // of it.
1311    fn handle_long_press(self: Handle<Self>, app: &mut App) {
1312        let tooltip_created = self.controller(app).is_dismissed(app);
1313        if tooltip_created && self.widget(app).enable_feedback {
1314            debug_assert!(self.widget(app).trigger_mode == TooltipTriggerMode::LongPress);
1315            Feedback::for_long_press(app, self.context(app));
1316        }
1317        if let Some(on_triggered) = self.widget(app).on_triggered.clone() {
1318            on_triggered.call(app);
1319        }
1320        self.schedule_show_tooltip(app, Duration::ZERO, None);
1321    }
1322
1323    fn handle_press_up(self: Handle<Self>, app: &mut App) {
1324        if !app.get(self).active_hovering_pointer_devices.is_empty() {
1325            return;
1326        }
1327        let touch_delay = self.widget(app).touch_delay;
1328        self.schedule_dismiss_tooltip(app, touch_delay);
1329    }
1330
1331    // # Current Hovering Behavior:
1332    // 1. Hovered tooltips don't show more than one at a time, for each mouse
1333    //    device. For example, a chip with a delete icon typically shouldn't show
1334    //    both the delete icon tooltip and the chip tooltip at the same time.
1335    // 2. Hovered tooltips are dismissed when:
1336    //    i. [dismiss_all_tool_tips] is called, even these tooltips are still hovered
1337    //    ii. a unrecognized PointerDownEvent occurred within the application
1338    //    (even these tooltips are still hovered),
1339    //    iii. The last hovering device leaves the tooltip.
1340    fn handle_mouse_enter(self: Handle<Self>, app: &mut App, event: PointerEnterEvent) {
1341        // handle_mouse_enter is only called when the mouse starts to hover over this
1342        // tooltip (including the actual tooltip it shows on the overlay), and this
1343        // tooltip is the first to be hit in the widget tree's hit testing order.
1344        // See also ExclusiveMouseRegion for the exact behavior.
1345        app.get_mut(self)
1346            .active_hovering_pointer_devices
1347            .insert(event.device);
1348        // Dismiss other open tooltips unless they're kept visible by other mice.
1349        // The mouse tracker implementation always dispatches all `onExit` events
1350        // before dispatching any `onEnter` events, so `event.device` must have
1351        // already been removed from active_hovering_pointer_devices of the tooltips
1352        // that are no longer being hovered over.
1353        let tooltips_to_dismiss: Vec<Handle<RawTooltipState>> = OpenedTooltips::to_list(app)
1354            .into_iter()
1355            .filter(|tooltip| app.get(*tooltip).active_hovering_pointer_devices.is_empty())
1356            .collect();
1357        for tooltip in &tooltips_to_dismiss {
1358            debug_assert!(tooltip.mounted(app));
1359            tooltip.schedule_dismiss_tooltip(app, Duration::ZERO);
1360        }
1361        let with_delay = if tooltips_to_dismiss.is_empty() {
1362            self.widget(app).hover_delay
1363        } else {
1364            Duration::ZERO
1365        };
1366        self.schedule_show_tooltip(app, with_delay, None);
1367    }
1368
1369    fn handle_mouse_exit(self: Handle<Self>, app: &mut App, event: PointerExitEvent) {
1370        if app.get(self).active_hovering_pointer_devices.is_empty() {
1371            return;
1372        }
1373        app.get_mut(self)
1374            .active_hovering_pointer_devices
1375            .remove(&event.device);
1376        if app.get(self).active_hovering_pointer_devices.is_empty() {
1377            let dismiss_delay = self.widget(app).dismiss_delay;
1378            self.schedule_dismiss_tooltip(app, dismiss_delay);
1379        }
1380    }
1381
1382    /// Shows the tooltip if it is not already visible.
1383    ///
1384    /// After made visible by this method, the tooltip does not automatically
1385    /// dismiss after [`RawTooltip::hover_delay`] until the user dismisses/re-triggers it, or
1386    /// [`RawTooltip::dismiss_all_tool_tips`] is called.
1387    ///
1388    /// Returns `false` when the tooltip shouldn't be shown or when the tooltip
1389    /// was already visible.
1390    pub fn ensure_tooltip_visible(self: Handle<Self>, app: &mut App) -> bool {
1391        if let Some(timer) = app.get_mut(self).timer.take() {
1392            timer.cancel(app);
1393        }
1394        if self.controller(app).is_forward_or_completed(app) {
1395            return false;
1396        }
1397        self.schedule_show_tooltip(app, Duration::ZERO, None);
1398        true
1399    }
1400
1401    fn build_tooltip_overlay(
1402        self: Handle<Self>,
1403        app: &mut App,
1404        context: BuildContext,
1405        layout_info: OverlayChildLayoutInfo,
1406    ) -> WidgetRef {
1407        if layout_info.child_paint_transform().determinant() == 0.0 {
1408            // The child is not visible.
1409            return SizedBox::shrink().into_widget();
1410        }
1411        let target = transform_point(
1412            &layout_info.child_paint_transform(),
1413            layout_info.child_size().center(Offset::ZERO),
1414        );
1415
1416        // Keep the tooltip visible while the overlay child is hovered.
1417        let tooltip_builder = Rc::clone(&self.widget(app).tooltip_builder);
1418        self.overlay_animation(app);
1419        let overlay_animation: AnimationRef<f64> = app
1420            .get(self)
1421            .backing_overlay_animation
1422            .as_ref()
1423            .expect("made above")
1424            .erase();
1425        let tooltip = IgnorePointer::new()
1426            .ignoring(self.widget(app).ignore_pointer)
1427            .child(ExclusiveMouseRegion::new(
1428                Rc::new(move |app, event| self.handle_mouse_enter(app, event)),
1429                Rc::new(move |app, event| self.handle_mouse_exit(app, event)),
1430                tooltip_builder(app, context, overlay_animation),
1431            ));
1432
1433        let bottom =
1434            MediaQuery::maybe_view_insets_of(app, context).map_or(0.0, |insets| insets.bottom);
1435        let overlay_child = Positioned::fill(
1436            CustomSingleChildLayout::new(Rc::new(TooltipPositionLayoutDelegate {
1437                target,
1438                target_size: layout_info.child_size(),
1439                position_delegate: self.widget(app).position_delegate.clone(),
1440            }))
1441            .child(tooltip),
1442        )
1443        .bottom(bottom)
1444        .into_widget();
1445
1446        if SelectionContainer::maybe_of(app, context).is_none() {
1447            overlay_child
1448        } else {
1449            SelectionContainer::disabled(overlay_child).into_widget()
1450        }
1451    }
1452}
1453
1454impl SingleTickerProviderStateMixin for RawTooltipState {
1455    fn single_ticker_provider_data(
1456        self: Handle<Self>,
1457        app: &App,
1458    ) -> &SingleTickerProviderStateMixinData {
1459        &app.get(self).single_ticker_provider
1460    }
1461
1462    fn single_ticker_provider_data_mut(
1463        self: Handle<Self>,
1464        app: &mut App,
1465    ) -> &mut SingleTickerProviderStateMixinData {
1466        &mut app.get_mut(self).single_ticker_provider
1467    }
1468}
1469
1470/// Dart's `vsync: this`.
1471impl TickerProviderObject for RawTooltipState {
1472    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1473        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1474    }
1475}
1476
1477impl State for RawTooltipState {
1478    type Widget = RawTooltip;
1479    crate::state_accessors!();
1480
1481    fn init_state(self: Handle<Self>, app: &mut App) {
1482        app.get_mut(self).overlay_controller = Some(OverlayPortalController::new(app, None));
1483        // Listen to global pointer events so that we can hide a tooltip immediately
1484        // if some other control is clicked on. Pointer events are dispatched to
1485        // global routes **after** other routes.
1486        let router = GestureBinding::instance(app).pointer_router(app);
1487        router.add_global_route(
1488            app,
1489            PointerRoute::handle_method(self, Self::handle_global_pointer_event),
1490            None,
1491        );
1492    }
1493
1494    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RawTooltip) {
1495        if self.widget(app).animation_style != old_widget.animation_style {
1496            if let Some(controller) = app.get(self).backing_controller.handle() {
1497                let show_duration = self.show_duration(app);
1498                let hide_duration = self.hide_duration(app);
1499                let controller = app.get_mut(controller);
1500                controller.duration = Some(show_duration);
1501                controller.reverse_duration = Some(hide_duration);
1502            }
1503            if let Some(overlay_animation) = app.get(self).backing_overlay_animation.handle() {
1504                let show_curve = self.show_curve(app);
1505                let hide_curve = self.hide_curve(app);
1506                let overlay_animation = app.get_mut(overlay_animation);
1507                overlay_animation.curve = show_curve;
1508                overlay_animation.reverse_curve = hide_curve;
1509            }
1510        }
1511    }
1512
1513    fn activate(self: Handle<Self>, app: &mut App) {
1514        SingleTickerProviderStateMixin::activate(self, app);
1515    }
1516
1517    fn dispose(self: Handle<Self>, app: &mut App) {
1518        let router = GestureBinding::instance(app).pointer_router(app);
1519        router.remove_global_route(
1520            app,
1521            &PointerRoute::handle_method(self, Self::handle_global_pointer_event),
1522        );
1523        OpenedTooltips::remove(app, self);
1524        // long_press_recognizer.dispose() and tap_recognizer.dispose() may call
1525        // their registered on_cancel callbacks if there's a gesture in progress.
1526        // Remove the on_cancel callbacks to prevent the registered callbacks from
1527        // triggering unnecessary side effects (such as animations).
1528        if let Some(recognizer) = app.get_mut(self).long_press_recognizer.take() {
1529            recognizer.set_on_long_press_cancel(app, None);
1530            recognizer.dispose(app);
1531        }
1532        if let Some(recognizer) = app.get_mut(self).tap_recognizer.take() {
1533            recognizer.set_on_tap_cancel(app, None);
1534            recognizer.dispose(app);
1535        }
1536        if let Some(timer) = app.get_mut(self).timer.take() {
1537            timer.cancel(app);
1538        }
1539        if let Some(controller) = app.get(self).backing_controller.handle() {
1540            controller.dispose(app);
1541        }
1542        if let Some(overlay_animation) = app.get(self).backing_overlay_animation.handle() {
1543            overlay_animation.dispose(app);
1544        }
1545        SingleTickerProviderStateMixin::dispose(self, app);
1546    }
1547
1548    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1549        // If message is empty then no need to create a tooltip overlay to show
1550        // the empty black container so just return the wrapped child as is or
1551        // empty container if child is not specified.
1552        if self
1553            .widget(app)
1554            .semantics_tooltip
1555            .as_ref()
1556            .is_some_and(|semantics_tooltip| semantics_tooltip.is_empty())
1557        {
1558            return self.widget(app).child.clone();
1559        }
1560        debug_assert!(debug_check_has_overlay(app, context));
1561        let semantics_tooltip = self.widget(app).semantics_tooltip.clone();
1562        let exclude_from_semantics = semantics_tooltip
1563            .as_ref()
1564            .is_none_or(|semantics_tooltip| semantics_tooltip.is_empty());
1565        let mut semantics = Semantics::new();
1566        if !exclude_from_semantics && let Some(semantics_tooltip) = semantics_tooltip {
1567            semantics = semantics.tooltip(semantics_tooltip);
1568        }
1569        let result = semantics.child(self.widget(app).child.clone());
1570
1571        // Only check for gestures if tooltip should be visible.
1572        let result = ExclusiveMouseRegion::new(
1573            Rc::new(move |app, event| self.handle_mouse_enter(app, event)),
1574            Rc::new(move |app, event| self.handle_mouse_exit(app, event)),
1575            PointerListener::new()
1576                .on_pointer_down(Rc::new(move |app, event| {
1577                    self.handle_pointer_down(app, event)
1578                }))
1579                .behavior(HitTestBehavior::Opaque)
1580                .child(result),
1581        );
1582
1583        OverlayPortal::overlay_child_layout_builder(
1584            app.get(self)
1585                .overlay_controller
1586                .clone()
1587                .expect("created in init_state"),
1588            move |app, context, layout_info| self.build_tooltip_overlay(app, context, layout_info),
1589        )
1590        .child(result)
1591        .into_widget()
1592    }
1593}
1594
1595/// A delegate for computing the layout of a tooltip to be displayed above or
1596/// below a target specified in the global coordinate system.
1597///
1598/// Dart's private `_TooltipPositionDelegate`, renamed because Rust has one namespace for it
1599/// and the public [`TooltipPositionDelegate`].
1600struct TooltipPositionLayoutDelegate {
1601    /// The offset of the target the tooltip is positioned near in the global
1602    /// coordinate system.
1603    target: Offset,
1604
1605    /// The size of the target widget that triggers the tooltip.
1606    target_size: Size,
1607
1608    /// A custom position delegate function for computing where the tooltip should be positioned.
1609    ///
1610    /// If provided, this function will be called with a [`TooltipPositionContext`] instead
1611    /// of the default positioning logic.
1612    position_delegate: Option<TooltipPositionDelegate>,
1613}
1614
1615impl Debug for TooltipPositionLayoutDelegate {
1616    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1617        f.debug_struct("TooltipPositionLayoutDelegate")
1618            .field("target", &self.target)
1619            .field("target_size", &self.target_size)
1620            .field("position_delegate", &self.position_delegate.is_some())
1621            .finish()
1622    }
1623}
1624
1625impl SingleChildLayoutDelegate for TooltipPositionLayoutDelegate {
1626    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
1627        constraints.loosen()
1628    }
1629
1630    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
1631        if let Some(position_delegate) = &self.position_delegate {
1632            return position_delegate(
1633                TooltipPositionContext::new(self.target, self.target_size, child_size, 0.0)
1634                    .overlay_size(size),
1635            );
1636        }
1637        position_dependent_box(size, child_size, self.target, true, 0.0, 10.0)
1638    }
1639
1640    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
1641        old_delegate
1642            .as_any()
1643            .downcast_ref::<TooltipPositionLayoutDelegate>()
1644            .is_none_or(|old_delegate| {
1645                self.target != old_delegate.target
1646                    || self.target_size != old_delegate.target_size
1647                    || !same_position_delegate(
1648                        self.position_delegate.as_ref(),
1649                        old_delegate.position_delegate.as_ref(),
1650                    )
1651            })
1652    }
1653
1654    fn as_any(&self) -> &dyn Any {
1655        self
1656    }
1657}
1658
1659/// Dart's `positionDelegate != oldDelegate.positionDelegate` on two function values: the same
1660/// closure.
1661fn same_position_delegate(
1662    a: Option<&TooltipPositionDelegate>,
1663    b: Option<&TooltipPositionDelegate>,
1664) -> bool {
1665    match (a, b) {
1666        (None, None) => true,
1667        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1668        _ => false,
1669    }
1670}
1671
1672#[cfg(test)]
1673mod tests {
1674    use std::cell::{Cell, RefCell};
1675    use waft_foundation::Ref;
1676
1677    use waft_embedder::{Color, PointerChange, TextDirection};
1678    use waft_gestures::{K_LONG_PRESS_TIMEOUT, K_PRESS_TIMEOUT, K_PRIMARY_BUTTON};
1679    use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry};
1680    use waft_rendering::RenderParagraph;
1681    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
1682    use waft_test::TestPlatform;
1683
1684    use super::*;
1685    use crate::framework::GlobalKey;
1686    use crate::testing::{
1687        Finder, TestPointer, TestWidgetsApp, WidgetTester, assert_more_or_less_equals, expect,
1688        find, finds_nothing, finds_one_widget, test_widgets,
1689    };
1690    use crate::widgets::app::WidgetsApp;
1691    use crate::widgets::basic::{
1692        Align, Builder, Center, ColoredBox, Column, Directionality, Padding, Spacer, Stack,
1693    };
1694    use crate::widgets::gesture_detector::GestureDetector;
1695    use crate::widgets::overlay::{Overlay, OverlayEntry};
1696    use crate::widgets::text::Text;
1697    use crate::widgets::transitions::FadeTransition;
1698
1699    const MOUSE_DEVICE: i64 = 1;
1700    const ETERNITY: Duration = Duration::from_secs(9999 * 24 * 60 * 60);
1701    const ONE_DAY: Duration = Duration::from_secs(24 * 60 * 60);
1702
1703    /// A case's [`WidgetTester`] with what Dart's cases add to it: the overlay entry
1704    /// `tester.pumpWidget(WidgetsApp(builder: (_, _) => Overlay(initialEntries: [entry])))`
1705    /// pumps the case's tree into, and the case's mouse `TestGesture`.
1706    struct Tester<'t> {
1707        tester: &'t mut WidgetTester,
1708        /// What the overlay's one entry builds: the tree `pump_widget` was last given.
1709        home: Rc<RefCell<Rc<dyn Fn() -> WidgetRef>>>,
1710        /// The entry `pump_widget` mounted, until `pump_root` replaces the tree.
1711        entry: Option<Ref<OverlayEntry>>,
1712        mouse: TestPointer,
1713        /// Whether the mouse's primary button is held: Dart's mouse `TestGesture` after `down`.
1714        mouse_is_down: bool,
1715    }
1716
1717    impl std::ops::Deref for Tester<'_> {
1718        type Target = WidgetTester;
1719
1720        fn deref(&self) -> &WidgetTester {
1721            self.tester
1722        }
1723    }
1724
1725    impl std::ops::DerefMut for Tester<'_> {
1726        fn deref_mut(&mut self) -> &mut WidgetTester {
1727            self.tester
1728        }
1729    }
1730
1731    impl<'t> Tester<'t> {
1732        fn new(tester: &'t mut WidgetTester) -> Tester<'t> {
1733            Tester {
1734                tester,
1735                home: Rc::new(RefCell::new(Rc::new(|| SizedBox::shrink().into_widget()))),
1736                entry: None,
1737                mouse: TestPointer::mouse(MOUSE_DEVICE, K_PRIMARY_BUTTON),
1738                mouse_is_down: false,
1739            }
1740        }
1741
1742        /// Dart's `tester.pumpWidget(WidgetsApp(builder: (_, _) => Overlay(initialEntries:
1743        /// [entry])))`, with `child` as the one entry's widget: the first call mounts the tree,
1744        /// a later one rebuilds the entry with the new `child`, as `pumpWidget` updates the
1745        /// tree in place.
1746        fn pump_widget(&mut self, child: impl Fn() -> WidgetRef + 'static) {
1747            *self.home.borrow_mut() = Rc::new(child);
1748            if let Some(entry) = &self.entry {
1749                entry.mark_needs_build(&mut self.tester.cell.borrow_mut());
1750                self.tester.pump();
1751                return;
1752            }
1753            let home = Rc::clone(&self.home);
1754            let entry = OverlayEntry::new(
1755                &mut self.tester.cell.borrow_mut(),
1756                Rc::new(move |_app, _context| {
1757                    let build = Rc::clone(&home.borrow());
1758                    build()
1759                }),
1760                false,
1761                false,
1762                false,
1763            );
1764            self.pump_root(
1765                Directionality::new(
1766                    TextDirection::Ltr,
1767                    Overlay::new().initial_entries([entry.clone()]),
1768                )
1769                .into_widget(),
1770            );
1771            self.entry = Some(entry);
1772        }
1773
1774        /// Dart's `tester.pumpWidget(widget)` with a tree of another shape: `widget` replaces
1775        /// the whole tree under the view.
1776        fn pump_root(&mut self, widget: WidgetRef) {
1777            self.entry = None;
1778            self.tester.pump_widget(widget);
1779        }
1780
1781        /// Dart's `WidgetsApp(color: Color(0x00000000), pageRouteBuilder: .., home: home)`.
1782        fn pump_app(&mut self, home: WidgetRef) {
1783            self.entry = None;
1784            self.tester.pump_widget(
1785                WidgetsApp::new(Color::new(0x00000000))
1786                    .page_route_builder(TestWidgetsApp::default_page_route_builder)
1787                    .home(home),
1788            );
1789        }
1790
1791        /// Dart's `tester.startGesture(position)`: a touch pointer down.
1792        fn start_gesture(&mut self, position: Offset) -> TestPointer {
1793            let mut pointer = TestPointer::touch(self.tester.next_pointer());
1794            self.tester.down(&mut pointer, position);
1795            pointer
1796        }
1797
1798        /// Dart's `tester.tap(finder)`, at the center of what it found.
1799        fn tap(&mut self, position: Offset) {
1800            let pointer = self.tester.next_pointer();
1801            self.tester.tap_at(position, pointer);
1802        }
1803
1804        /// Dart's `tester.longPress(finder)`.
1805        fn long_press(&mut self, position: Offset) {
1806            let pointer = self.tester.next_pointer();
1807            self.tester.long_press_at(position, pointer);
1808        }
1809
1810        /// Dart's `_testGestureTap`.
1811        fn test_gesture_tap(&mut self, position: Offset) {
1812            self.tap(position);
1813            self.tester.pump_by(Duration::from_millis(10));
1814        }
1815
1816        /// Dart's `_testGestureLongPress`.
1817        fn test_gesture_long_press(&mut self, position: Offset) {
1818            let pointer = self.start_gesture(position);
1819            self.tester.pump();
1820            self.tester.pump_by(K_LONG_PRESS_TIMEOUT);
1821            self.tester.up(&pointer);
1822            self.tester.pump();
1823        }
1824
1825        /// Dart's `mouseGesture.moveTo(position)`: a hover, or a move while the button is held.
1826        fn mouse_move_to(&mut self, position: Offset) {
1827            let down = self.mouse_is_down;
1828            self.tester.move_to(&mut self.mouse, position, down);
1829        }
1830
1831        /// Dart's `mouseGesture.addPointer(location: position)`.
1832        fn mouse_add_pointer(&mut self, position: Offset) {
1833            self.tester.add_pointer(&mut self.mouse, position);
1834        }
1835
1836        /// Dart's `mouseGesture.removePointer()`.
1837        fn mouse_remove_pointer(&mut self) {
1838            let mouse = self.mouse;
1839            self.tester.send(&mouse, PointerChange::Remove);
1840        }
1841
1842        /// Dart's `tester.startGesture(position, kind: PointerDeviceKind.mouse)`: the primary
1843        /// button down.
1844        fn mouse_down(&mut self, position: Offset) {
1845            self.mouse_is_down = true;
1846            self.tester.down(&mut self.mouse, position);
1847        }
1848
1849        /// Dart's `mouseGesture.up()`.
1850        fn mouse_up(&mut self) {
1851            self.mouse_is_down = false;
1852            let mouse = self.mouse;
1853            self.tester.up(&mouse);
1854        }
1855
1856        fn state(&self, key: &GlobalKey) -> Handle<RawTooltipState> {
1857            key.current_state::<RawTooltipState>(&self.tester.cell.borrow())
1858                .expect("the tooltip is mounted")
1859        }
1860    }
1861
1862    fn sized_box(width: f64, height: f64) -> SizedBox {
1863        SizedBox::new().width(width).height(height)
1864    }
1865
1866    /// Dart's `Text(tooltipText)` as a tooltip, keyed so a test can find it.
1867    fn tip(key: &GlobalKey) -> WidgetRef {
1868        Text::new("TIP").key(key.clone().into()).into_widget()
1869    }
1870
1871    /// The `positionDelegate` of `setWidgetForTooltipMode`.
1872    fn below_with_vertical_offset_24() -> TooltipPositionDelegate {
1873        Rc::new(|context: TooltipPositionContext| {
1874            position_dependent_box(
1875                context.overlay_size,
1876                context.tooltip_size,
1877                context.target,
1878                context.prefer_below,
1879                24.0,
1880                10.0,
1881            )
1882        })
1883    }
1884
1885    fn prefer_above() -> TooltipPositionDelegate {
1886        Rc::new(|context: TooltipPositionContext| {
1887            position_dependent_box(
1888                context.overlay_size,
1889                context.tooltip_size,
1890                context.target,
1891                false,
1892                0.0,
1893                10.0,
1894            )
1895        })
1896    }
1897
1898    const CENTER: Offset = Offset::new(400.0, 300.0);
1899
1900    /// Dart's `setWidgetForTooltipMode`.
1901    fn set_widget_for_tooltip_mode(
1902        tester: &mut Tester,
1903        trigger_mode: TooltipTriggerMode,
1904        touch_delay: Option<Duration>,
1905        enable_tap_to_dismiss: Option<bool>,
1906        on_triggered: Option<Listener>,
1907    ) -> GlobalKey {
1908        let tip_key = GlobalKey::new();
1909        let key = tip_key.clone();
1910        tester.pump_widget(move || {
1911            let key = key.clone();
1912            let mut tooltip = RawTooltip::new(
1913                Some("TIP".into()),
1914                move |_app, _context, _animation| tip(&key),
1915                sized_box(100.0, 100.0),
1916            )
1917            .trigger_mode(trigger_mode)
1918            .touch_delay(touch_delay.unwrap_or(Duration::from_millis(1500)))
1919            .enable_tap_to_dismiss(enable_tap_to_dismiss.unwrap_or(true))
1920            .position_delegate(below_with_vertical_offset_24());
1921            if let Some(on_triggered) = on_triggered.clone() {
1922                tooltip = tooltip.on_triggered(on_triggered);
1923            }
1924            Center::new().child(tooltip).into_widget()
1925        });
1926        tip_key
1927    }
1928
1929    /// The tree of Dart's positioning cases: a tooltip at `(left, top)` of a `Stack`, shown
1930    /// by `ensureTooltipVisible` and given two seconds to fade in.
1931    fn position_case(
1932        tester: &mut WidgetTester,
1933        left: f64,
1934        top: f64,
1935        tip: impl Fn() -> WidgetRef + 'static,
1936        position_delegate: Option<TooltipPositionDelegate>,
1937    ) -> Tester<'_> {
1938        let mut tester = Tester::new(tester);
1939        let tooltip_key = GlobalKey::new();
1940        let key = tooltip_key.clone();
1941        let tip = Rc::new(tip);
1942        tester.pump_widget(move || {
1943            let tip = Rc::clone(&tip);
1944            let mut tooltip = RawTooltip::new(
1945                Some("TIP".into()),
1946                move |_app, _context, _animation| tip(),
1947                SizedBox::shrink(),
1948            )
1949            .key(key.clone().into());
1950            if let Some(position_delegate) = position_delegate.clone() {
1951                tooltip = tooltip.position_delegate(position_delegate);
1952            }
1953            Stack::new()
1954                .children([Positioned::new(tooltip).left(left).top(top).into_widget()])
1955                .into_widget()
1956        });
1957        let state = tester.state(&tooltip_key);
1958        state.ensure_tooltip_visible(&mut tester.cell.borrow_mut());
1959        tester.pump_by(Duration::from_secs(2)); // faded in, show timer started (and at 0.0)
1960        tester
1961    }
1962
1963    #[test]
1964    fn does_tooltip_end_up_in_the_right_place_center() {
1965        test_widgets(|tester| {
1966            let tip_key = GlobalKey::new();
1967            let key = tip_key.clone();
1968            let tester = position_case(tester, 300.0, 0.0, move || tip(&key), None);
1969            let tip = tester.get_rect(&tip_key);
1970            assert_eq!(tip.top_center().dx(), 300.0);
1971            assert_eq!(tip.top_center().dy(), 0.0);
1972        });
1973    }
1974
1975    #[test]
1976    fn does_tooltip_end_up_in_the_right_place_top_left() {
1977        test_widgets(|tester| {
1978            let tip_key = GlobalKey::new();
1979            let key = tip_key.clone();
1980            let tester = position_case(
1981                tester,
1982                0.0,
1983                0.0,
1984                move || {
1985                    Padding::new(EdgeInsetsGeometry::symmetric(5.0, 0.0))
1986                        .key(key.clone().into())
1987                        .child(sized_box(42.0, 20.0))
1988                        .into_widget()
1989                },
1990                None,
1991            );
1992            let tip = tester.get_rect(&tip_key);
1993            assert_eq!(tip.height(), 30.0); // 20.0 height + 5.0 padding * 2 (top, bottom)
1994            assert_eq!(tip.top_left(), Offset::new(10.0, 0.0));
1995        });
1996    }
1997
1998    #[test]
1999    fn does_tooltip_end_up_in_the_right_place_center_prefer_above_fits() {
2000        test_widgets(|tester| {
2001            let tip_key = GlobalKey::new();
2002            let key = tip_key.clone();
2003            let tester = position_case(
2004                tester,
2005                400.0,
2006                300.0,
2007                move || sized_box(42.0, 100.0).key(key.clone().into()).into_widget(),
2008                Some(prefer_above()),
2009            );
2010            let tip = tester.get_rect(&tip_key);
2011            assert_eq!(tip.height(), 100.0);
2012            assert_eq!(tip.top, 200.0);
2013            assert_eq!(tip.bottom, 300.0);
2014        });
2015    }
2016
2017    #[test]
2018    fn does_tooltip_end_up_in_the_right_place_center_prefer_above_does_not_fit() {
2019        test_widgets(|tester| {
2020            let tip_key = GlobalKey::new();
2021            let key = tip_key.clone();
2022            let tester = position_case(
2023                tester,
2024                400.0,
2025                299.0,
2026                move || sized_box(42.0, 190.0).key(key.clone().into()).into_widget(),
2027                Some(prefer_above()),
2028            );
2029            let tip = tester.get_rect(&tip_key);
2030            assert_eq!(tip.height(), 190.0);
2031            assert_eq!(tip.top, 109.0);
2032            assert_eq!(tip.bottom, 299.0);
2033        });
2034    }
2035
2036    #[test]
2037    fn does_tooltip_end_up_in_the_right_place_center_prefer_below_fits() {
2038        test_widgets(|tester| {
2039            let tip_key = GlobalKey::new();
2040            let key = tip_key.clone();
2041            let tester = position_case(
2042                tester,
2043                400.0,
2044                300.0,
2045                move || sized_box(42.0, 190.0).key(key.clone().into()).into_widget(),
2046                None,
2047            );
2048            let tip = tester.get_rect(&tip_key);
2049            assert_eq!(tip.height(), 190.0);
2050            assert_eq!(tip.top, 300.0);
2051            assert_eq!(tip.bottom, 490.0);
2052        });
2053    }
2054
2055    fn padded_ten_high(key: &GlobalKey) -> WidgetRef {
2056        Padding::new(EdgeInsetsGeometry::only(0.0, 0.0, 0.0, 10.0))
2057            .key(key.clone().into())
2058            .child(sized_box(42.0, 10.0))
2059            .into_widget()
2060    }
2061
2062    #[test]
2063    fn does_tooltip_end_up_in_the_right_place_way_off_to_the_right() {
2064        test_widgets(|tester| {
2065            let tip_key = GlobalKey::new();
2066            let key = tip_key.clone();
2067            let tester = position_case(tester, 1600.0, 300.0, move || padded_ten_high(&key), None);
2068            let tip = tester.get_rect(&tip_key);
2069            assert_eq!(tip.height(), 20.0);
2070            assert_eq!(tip.top, 300.0);
2071            assert_eq!(tip.right, 790.0);
2072            assert_eq!(tip.bottom, 320.0);
2073        });
2074    }
2075
2076    #[test]
2077    fn does_tooltip_end_up_in_the_right_place_near_the_edge() {
2078        test_widgets(|tester| {
2079            let tip_key = GlobalKey::new();
2080            let key = tip_key.clone();
2081            let tester = position_case(tester, 780.0, 300.0, move || padded_ten_high(&key), None);
2082            let tip = tester.get_rect(&tip_key);
2083            assert_eq!(tip.height(), 20.0);
2084            assert_eq!(tip.top, 300.0);
2085            assert_eq!(tip.right, 790.0);
2086            assert_eq!(tip.bottom, 320.0);
2087        });
2088    }
2089
2090    #[test]
2091    fn custom_tooltip_positioning_with_the_position_delegate() {
2092        test_widgets(|tester| {
2093            let mut tester = Tester::new(tester);
2094            let tip_key = GlobalKey::new();
2095            let key = tip_key.clone();
2096            let target_key = GlobalKey::new();
2097            let target = target_key.clone();
2098            tester.pump_widget(move || {
2099                let key = key.clone();
2100                Center::new()
2101                    .child(
2102                        RawTooltip::new(
2103                            Some("TIP".into()),
2104                            move |_app, _context, _animation| tip(&key),
2105                            sized_box(50.0, 50.0).key(target.clone().into()),
2106                        )
2107                        .position_delegate(Rc::new(
2108                            |context: TooltipPositionContext| {
2109                                // Align on top right of box with bottom left of tooltip.
2110                                Offset::new(
2111                                    context.target.dx() + (context.target_size.width() / 2.0),
2112                                    context.target.dy()
2113                                        - (context.target_size.height() / 2.0)
2114                                        - context.tooltip_size.height(),
2115                                )
2116                            },
2117                        )),
2118                    )
2119                    .into_widget()
2120            });
2121            tester.long_press(CENTER);
2122            tester.pump_by(Duration::from_secs(1));
2123            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2124
2125            let target_center = tester.get_center(&target_key);
2126            let tooltip_position = tester.get_top_left(&tip_key);
2127            // The tooltip should be positioned at target + (25, -25-14).
2128            assert!((tooltip_position.dx() - (target_center.dx() + 25.0)).abs() <= 5.0);
2129            assert!((tooltip_position.dy() - (target_center.dy() - 25.0 - 14.0)).abs() <= 5.0);
2130        });
2131    }
2132
2133    #[test]
2134    fn raw_tooltip_stays_after_long_press() {
2135        test_widgets(|tester| {
2136            let mut tester = Tester::new(tester);
2137            let tip_key = set_widget_for_tooltip_mode(
2138                &mut tester,
2139                TooltipTriggerMode::LongPress,
2140                None,
2141                None,
2142                None,
2143            );
2144
2145            // long press reveals tooltip
2146            let pointer = tester.start_gesture(CENTER);
2147            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2148            tester.pump_by(Duration::from_millis(10));
2149            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2150            tester.up(&pointer);
2151
2152            // tap (down, up) gesture hides tooltip, since its not
2153            // a long press
2154            tester.tap(CENTER);
2155            tester.pump();
2156            tester.pump_and_settle();
2157            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2158
2159            // long press once more
2160            let pointer = tester.start_gesture(CENTER);
2161            tester.pump();
2162            tester.pump_by(Duration::from_millis(300));
2163            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2164
2165            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2166            tester.pump_by(Duration::from_millis(10));
2167            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2168
2169            // keep holding the long press, should still show tooltip
2170            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2171            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2172            tester.up(&pointer);
2173        });
2174    }
2175
2176    #[test]
2177    fn raw_tooltip_dismiss_countdown_begins_on_long_press_release() {
2178        test_widgets(|tester| {
2179            let touch_delay = Duration::from_secs(1);
2180            let mut tester = Tester::new(tester);
2181            let tip_key = set_widget_for_tooltip_mode(
2182                &mut tester,
2183                TooltipTriggerMode::LongPress,
2184                Some(touch_delay),
2185                None,
2186                None,
2187            );
2188
2189            let pointer = tester.start_gesture(CENTER);
2190            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2191            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2192            // Keep holding to prevent the tooltip from dismissing.
2193            tester.pump_by(ETERNITY);
2194            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2195            tester.pump();
2196            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2197
2198            tester.up(&pointer);
2199            tester.pump();
2200            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2201
2202            tester.pump_by(touch_delay);
2203            tester.pump_by(Duration::from_millis(500));
2204            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2205        });
2206    }
2207
2208    #[test]
2209    fn raw_tooltip_is_dismissed_after_a_long_press_and_touch_delay_expired() {
2210        test_widgets(|tester| {
2211            let touch_delay = Duration::from_secs(3);
2212            let mut tester = Tester::new(tester);
2213            let tip_key = set_widget_for_tooltip_mode(
2214                &mut tester,
2215                TooltipTriggerMode::LongPress,
2216                Some(touch_delay),
2217                None,
2218                None,
2219            );
2220
2221            // Long press reveals tooltip
2222            let pointer = tester.start_gesture(CENTER);
2223            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2224            tester.pump_by(Duration::from_millis(10));
2225            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2226            tester.up(&pointer);
2227
2228            // Tooltip is dismissed after touchDelay expired
2229            tester.pump_by(touch_delay);
2230            tester.pump_by(Duration::from_millis(10));
2231            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2232        });
2233    }
2234
2235    #[test]
2236    fn raw_tooltip_is_dismissed_after_a_tap_and_touch_delay_expired() {
2237        test_widgets(|tester| {
2238            let touch_delay = Duration::from_secs(3);
2239            let mut tester = Tester::new(tester);
2240            let tip_key = set_widget_for_tooltip_mode(
2241                &mut tester,
2242                TooltipTriggerMode::Tap,
2243                Some(touch_delay),
2244                None,
2245                None,
2246            );
2247            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2248
2249            tester.test_gesture_tap(CENTER);
2250            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2251
2252            // Tooltip is dismissed after touchDelay expired
2253            tester.pump_by(touch_delay);
2254            tester.pump_by(Duration::from_millis(10));
2255            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2256        });
2257    }
2258
2259    #[test]
2260    fn raw_tooltip_is_dismissed_after_tap_to_dismiss_immediately() {
2261        test_widgets(|tester| {
2262            let mut tester = Tester::new(tester);
2263            let tip_key =
2264                set_widget_for_tooltip_mode(&mut tester, TooltipTriggerMode::Tap, None, None, None);
2265            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2266
2267            // Tap to trigger the tooltip.
2268            tester.test_gesture_tap(CENTER);
2269            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2270
2271            // Tap to dismiss the tooltip. Tooltip is dismissed immediately.
2272            let tip = tester.get_center(&tip_key);
2273            tester.test_gesture_tap(tip);
2274            tester.pump_by(Duration::from_millis(10));
2275            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2276        });
2277    }
2278
2279    #[test]
2280    fn tooltip_is_not_dismissed_after_tap_if_enable_tap_to_dismiss_is_false() {
2281        test_widgets(|tester| {
2282            let mut tester = Tester::new(tester);
2283            let tip_key = set_widget_for_tooltip_mode(
2284                &mut tester,
2285                TooltipTriggerMode::Tap,
2286                None,
2287                Some(false),
2288                None,
2289            );
2290            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2291
2292            // Tap to trigger the tooltip.
2293            tester.test_gesture_tap(CENTER);
2294            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2295
2296            // Tap the tooltip. The tooltip is not dismissed.
2297            let tip = tester.get_center(&tip_key);
2298            tester.test_gesture_tap(tip);
2299            tester.pump_by(Duration::from_millis(10));
2300            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2301        });
2302    }
2303
2304    #[test]
2305    fn tooltip_triggers_on_tap_when_trigger_mode_is_tap() {
2306        test_widgets(|tester| {
2307            let mut tester = Tester::new(tester);
2308            let tip_key =
2309                set_widget_for_tooltip_mode(&mut tester, TooltipTriggerMode::Tap, None, None, None);
2310            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2311
2312            tester.test_gesture_tap(CENTER);
2313            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2314        });
2315    }
2316
2317    #[test]
2318    fn tooltip_triggers_on_long_press_when_mode_is_long_press() {
2319        test_widgets(|tester| {
2320            let mut tester = Tester::new(tester);
2321            let tip_key = set_widget_for_tooltip_mode(
2322                &mut tester,
2323                TooltipTriggerMode::LongPress,
2324                None,
2325                None,
2326                None,
2327            );
2328            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2329
2330            tester.test_gesture_tap(CENTER);
2331            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2332
2333            tester.test_gesture_long_press(CENTER);
2334            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2335        });
2336    }
2337
2338    #[test]
2339    fn tooltip_does_not_trigger_when_trigger_mode_is_manual() {
2340        test_widgets(|tester| {
2341            let mut tester = Tester::new(tester);
2342            let tip_key = set_widget_for_tooltip_mode(
2343                &mut tester,
2344                TooltipTriggerMode::Manual,
2345                None,
2346                None,
2347                None,
2348            );
2349            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2350
2351            tester.test_gesture_tap(CENTER);
2352            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2353
2354            tester.test_gesture_long_press(CENTER);
2355            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2356        });
2357    }
2358
2359    #[test]
2360    fn tooltip_on_triggered_is_called_when_tooltip_triggers() {
2361        test_widgets(|tester| {
2362            let on_triggered_called = Rc::new(Cell::new(false));
2363            let called = Rc::clone(&on_triggered_called);
2364            let on_triggered = Listener::new(move |_app| called.set(true));
2365
2366            let mut tester = Tester::new(tester);
2367            set_widget_for_tooltip_mode(
2368                &mut tester,
2369                TooltipTriggerMode::LongPress,
2370                None,
2371                None,
2372                Some(on_triggered.clone()),
2373            );
2374            tester.test_gesture_long_press(CENTER);
2375            assert!(on_triggered_called.get());
2376
2377            on_triggered_called.set(false);
2378            set_widget_for_tooltip_mode(
2379                &mut tester,
2380                TooltipTriggerMode::Tap,
2381                None,
2382                None,
2383                Some(on_triggered),
2384            );
2385            tester.test_gesture_tap(CENTER);
2386            assert!(on_triggered_called.get());
2387        });
2388    }
2389
2390    /// The `Center(child: RawTooltip(child: SizedBox(100x100)))` the hover cases mount.
2391    fn hover_case(
2392        tester: &mut Tester,
2393        configure: impl Fn(RawTooltip) -> RawTooltip + 'static,
2394    ) -> GlobalKey {
2395        let tip_key = GlobalKey::new();
2396        let key = tip_key.clone();
2397        tester.pump_widget(move || {
2398            let key = key.clone();
2399            Center::new()
2400                .child(configure(RawTooltip::new(
2401                    Some("TIP".into()),
2402                    move |_app, _context, _animation| tip(&key),
2403                    sized_box(100.0, 100.0),
2404                )))
2405                .into_widget()
2406        });
2407        tip_key
2408    }
2409
2410    #[test]
2411    fn tooltip_on_triggered_is_not_called_when_tooltip_is_hovered() {
2412        test_widgets(|tester| {
2413            let on_triggered_called = Rc::new(Cell::new(false));
2414            let called = Rc::clone(&on_triggered_called);
2415            let mut tester = Tester::new(tester);
2416            tester.mouse_move_to(Offset::ZERO);
2417            hover_case(&mut tester, move |tooltip| {
2418                let called = Rc::clone(&called);
2419                tooltip.on_triggered(Listener::new(move |_app| called.set(true)))
2420            });
2421
2422            tester.mouse_move_to(CENTER);
2423            tester.pump();
2424            // Wait for it to appear.
2425            tester.pump();
2426            assert!(!on_triggered_called.get());
2427        });
2428    }
2429
2430    #[test]
2431    fn tooltip_shows_and_hides_when_hovered() {
2432        test_widgets(|tester| {
2433            let mut tester = Tester::new(tester);
2434            tester.mouse_move_to(Offset::new(1.0, 1.0));
2435            tester.mouse_move_to(Offset::ZERO);
2436            let tip_key = hover_case(&mut tester, |tooltip| tooltip);
2437
2438            tester.mouse_move_to(Offset::ZERO);
2439            tester.pump();
2440            tester.mouse_move_to(CENTER);
2441            tester.pump();
2442            // Wait for it to appear.
2443            tester.pump();
2444            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2445
2446            // Wait a looong time to make sure that it doesn't go away if the mouse is
2447            // still over the widget.
2448            tester.pump_by(ONE_DAY);
2449            tester.pump_and_settle();
2450            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2451
2452            tester.mouse_move_to(Offset::ZERO);
2453            tester.pump();
2454
2455            // Wait for it to disappear.
2456            tester.pump_and_settle();
2457            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2458        });
2459    }
2460
2461    #[test]
2462    fn tooltip_text_is_also_hoverable() {
2463        test_widgets(|tester| {
2464            let mut tester = Tester::new(tester);
2465            tester.mouse_move_to(Offset::new(1.0, 1.0));
2466            tester.mouse_move_to(Offset::ZERO);
2467            let tip_key = hover_case(&mut tester, |tooltip| tooltip);
2468
2469            tester.mouse_move_to(Offset::ZERO);
2470            tester.pump();
2471            tester.mouse_move_to(CENTER);
2472            tester.pump();
2473            // Wait for it to appear.
2474            tester.pump();
2475            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2476
2477            // Wait a looong time to make sure that it doesn't go away if the mouse is
2478            // still over the widget.
2479            tester.pump_by(ONE_DAY);
2480            tester.pump_and_settle();
2481            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2482
2483            // Hover to the tooltip text and verify the tooltip doesn't go away.
2484            let tip = tester.get_top_left(&tip_key);
2485            tester.mouse_move_to(tip);
2486            tester.pump_by(ONE_DAY);
2487            tester.pump_and_settle();
2488            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2489
2490            tester.mouse_move_to(Offset::ZERO);
2491            tester.pump();
2492
2493            // Wait for it to disappear.
2494            tester.pump_and_settle();
2495            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2496        });
2497    }
2498
2499    #[test]
2500    fn tooltip_shows_without_delay_when_the_mouse_moves_from_another_tooltip() {
2501        test_widgets(|tester| {
2502            let hover_delay = Duration::from_millis(700);
2503            let mut tester = Tester::new(tester);
2504            tester.mouse_move_to(Offset::new(1.0, 1.0));
2505            tester.mouse_move_to(Offset::ZERO);
2506            let (first_key, last_key) = (GlobalKey::new(), GlobalKey::new());
2507            let (first, last) = (first_key.clone(), last_key.clone());
2508            tester.pump_widget(move || {
2509                let (first, last) = (first.clone(), last.clone());
2510                Column::new()
2511                    .children([
2512                        RawTooltip::new(
2513                            Some("first tooltip".into()),
2514                            move |_app, _context, _animation| tip(&first),
2515                            sized_box(100.0, 100.0),
2516                        )
2517                        .hover_delay(hover_delay)
2518                        .into_widget(),
2519                        RawTooltip::new(
2520                            Some("last tooltip".into()),
2521                            move |_app, _context, _animation| tip(&last),
2522                            sized_box(100.0, 100.0),
2523                        )
2524                        .hover_delay(hover_delay)
2525                        .into_widget(),
2526                    ])
2527                    .into_widget()
2528            });
2529
2530            tester.mouse_move_to(Offset::ZERO);
2531            tester.pump();
2532            tester.mouse_move_to(Offset::new(400.0, 50.0));
2533            tester.pump();
2534            // Wait for the first tooltip to appear.
2535            tester.pump_by(hover_delay);
2536            expect(
2537                &tester,
2538                &find::by_global_key(&first_key),
2539                finds_one_widget(),
2540            );
2541            expect(&tester, &find::by_global_key(&last_key), finds_nothing());
2542
2543            // Move to the second tooltip and expect it to show up immediately.
2544            tester.mouse_move_to(Offset::new(400.0, 150.0));
2545            tester.pump();
2546            expect(&tester, &find::by_global_key(&first_key), finds_nothing());
2547            expect(&tester, &find::by_global_key(&last_key), finds_one_widget());
2548        });
2549    }
2550
2551    #[test]
2552    fn tooltip_should_not_show_more_than_one_tooltip_when_hovered() {
2553        test_widgets(|tester| {
2554            let hover_delay = Duration::from_millis(500);
2555            let mut tester = Tester::new(tester);
2556            let (outer_tip, inner_tip) = (GlobalKey::new(), GlobalKey::new());
2557            let (outer, inner) = (outer_tip.clone(), inner_tip.clone());
2558            tester.pump_widget(move || {
2559                let (outer, inner) = (outer.clone(), inner.clone());
2560                Center::new()
2561                    .child(RawTooltip::new(
2562                        Some("Outer".into()),
2563                        move |_app, _context, _animation| tip(&outer),
2564                        sized_box(100.0, 100.0).child(
2565                            Align::new()
2566                                .alignment(AlignmentGeometry::CENTER_RIGHT)
2567                                .child(RawTooltip::new(
2568                                    Some("Inner".into()),
2569                                    move |_app, _context, _animation| tip(&inner),
2570                                    sized_box(25.0, 100.0),
2571                                )),
2572                        ),
2573                    ))
2574                    .into_widget()
2575            });
2576            let outer_center = CENTER;
2577            let inner_center = Offset::new(437.5, 300.0);
2578
2579            // Both the inner and outer containers have tooltips associated with them, but only
2580            // the currently hovered one should appear, even though the pointer is inside both.
2581            tester.mouse_move_to(Offset::ZERO);
2582            tester.pump();
2583            tester.mouse_move_to(outer_center);
2584            tester.pump();
2585            tester.mouse_move_to(inner_center);
2586            tester.pump();
2587
2588            // Wait for it to appear.
2589            tester.pump_by(hover_delay);
2590
2591            expect(&tester, &find::by_global_key(&outer_tip), finds_nothing());
2592            expect(
2593                &tester,
2594                &find::by_global_key(&inner_tip),
2595                finds_one_widget(),
2596            );
2597            tester.mouse_move_to(outer_center);
2598            tester.pump();
2599            // Wait for it to switch.
2600            tester.pump_and_settle();
2601            expect(
2602                &tester,
2603                &find::by_global_key(&outer_tip),
2604                finds_one_widget(),
2605            );
2606            expect(&tester, &find::by_global_key(&inner_tip), finds_nothing());
2607
2608            tester.mouse_move_to(Offset::ZERO);
2609
2610            // Wait for all tooltips to disappear.
2611            tester.pump_and_settle();
2612            expect(&tester, &find::by_global_key(&outer_tip), finds_nothing());
2613            expect(&tester, &find::by_global_key(&inner_tip), finds_nothing());
2614        });
2615    }
2616
2617    #[test]
2618    fn dismiss_all_tool_tips_dismisses_hovered_tooltips() {
2619        test_widgets(|tester| {
2620            let mut tester = Tester::new(tester);
2621            tester.mouse_move_to(Offset::ZERO);
2622            let tip_key = hover_case(&mut tester, |tooltip| {
2623                tooltip.position_delegate(below_with_vertical_offset_24())
2624            });
2625
2626            tester.mouse_move_to(CENTER);
2627            tester.pump();
2628            // Wait for it to appear.
2629            tester.pump();
2630            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2631            tester.pump_by(ONE_DAY);
2632            tester.pump_and_settle();
2633            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2634
2635            assert!(RawTooltip::dismiss_all_tool_tips(
2636                &mut tester.cell.borrow_mut()
2637            ));
2638            tester.pump_and_settle();
2639            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2640        });
2641    }
2642
2643    #[test]
2644    fn tooltip_can_be_dismissed_by_escape_key() {
2645        test_widgets(|tester| {
2646            let hover_delay = Duration::ZERO;
2647            let mut tester = Tester::new(tester);
2648            tester.mouse_move_to(Offset::new(1.0, 1.0));
2649            tester.pump();
2650            tester.mouse_move_to(Offset::ZERO);
2651
2652            let colored_box = GlobalKey::new();
2653            let key = colored_box.clone();
2654            tester.pump_app(
2655                Center::new()
2656                    .child(RawTooltip::new(
2657                        Some("TIP".into()),
2658                        move |_app, _context, _animation| {
2659                            ColoredBox::new(Color::new(0xff0000ff))
2660                                .key(key.clone().into())
2661                                .into_widget()
2662                        },
2663                        Text::new("I am tool tip"),
2664                    ))
2665                    .into_widget(),
2666            );
2667
2668            tester.mouse_move_to(Offset::ZERO);
2669            tester.pump();
2670            tester.mouse_move_to(CENTER);
2671            tester.pump();
2672            // Wait for it to appear.
2673            tester.pump_by(hover_delay);
2674            expect(
2675                &tester,
2676                &find::by_global_key(&colored_box),
2677                finds_one_widget(),
2678            );
2679
2680            // Try to dismiss the tooltip with the shortcut key.
2681            tester.send_key_event(PhysicalKeyboardKey::ESCAPE, LogicalKeyboardKey::ESCAPE);
2682            tester.pump_and_settle();
2683            expect(&tester, &find::by_global_key(&colored_box), finds_nothing());
2684
2685            tester.mouse_move_to(Offset::ZERO);
2686            tester.pump_and_settle();
2687        });
2688    }
2689
2690    #[test]
2691    fn multiple_tooltips_are_dismissed_by_escape_key() {
2692        test_widgets(|tester| {
2693            let hover_delay = Duration::ZERO;
2694            let mut tester = Tester::new(tester);
2695            let (tooltip1, tooltip2) = (GlobalKey::new(), GlobalKey::new());
2696            let (message1, message2) = (GlobalKey::new(), GlobalKey::new());
2697            let message = |key: &GlobalKey, text: &'static str| {
2698                let key = key.clone();
2699                move |_app: &mut App, _context: BuildContext, _animation: AnimationRef<f64>| {
2700                    Text::new(text).key(key.clone().into()).into_widget()
2701                }
2702            };
2703            tester.pump_app(
2704                Center::new()
2705                    .child(
2706                        Column::new().children([
2707                            RawTooltip::new(
2708                                Some("tooltip1".into()),
2709                                message(&message1, "message1"),
2710                                Text::new("tooltip1"),
2711                            )
2712                            .key(tooltip1.clone().into())
2713                            .touch_delay(ONE_DAY)
2714                            .into_widget(),
2715                            Spacer::new().flex(2).into_widget(),
2716                            RawTooltip::new(
2717                                Some("tooltip2".into()),
2718                                message(&message2, "message2"),
2719                                Text::new("tooltip2"),
2720                            )
2721                            .key(tooltip2.clone().into())
2722                            .touch_delay(ONE_DAY)
2723                            .into_widget(),
2724                        ]),
2725                    )
2726                    .into_widget(),
2727            );
2728
2729            let (state1, state2) = (tester.state(&tooltip1), tester.state(&tooltip2));
2730            state1.ensure_tooltip_visible(&mut tester.cell.borrow_mut());
2731            state2.ensure_tooltip_visible(&mut tester.cell.borrow_mut());
2732            tester.pump();
2733            tester.pump_by(hover_delay);
2734            // Make sure both messages are on the screen.
2735            expect(&tester, &find::by_global_key(&message1), finds_one_widget());
2736            expect(&tester, &find::by_global_key(&message2), finds_one_widget());
2737
2738            // Try to dismiss the tooltip with the shortcut key
2739            tester.send_key_event(PhysicalKeyboardKey::ESCAPE, LogicalKeyboardKey::ESCAPE);
2740            tester.pump_and_settle();
2741            expect(&tester, &find::by_global_key(&message1), finds_nothing());
2742            expect(&tester, &find::by_global_key(&message2), finds_nothing());
2743        });
2744    }
2745
2746    #[test]
2747    fn hovered_tooltips_do_not_dismiss_after_touch_delay() {
2748        test_widgets(|tester| {
2749            let mut tester = Tester::new(tester);
2750            tester.mouse_move_to(Offset::ZERO);
2751            let tip_key = hover_case(&mut tester, |tooltip| tooltip);
2752
2753            tester.mouse_move_to(CENTER);
2754            tester.pump();
2755            // Wait for it to appear.
2756            tester.pump();
2757            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2758            tester.pump_by(ONE_DAY);
2759            tester.pump_and_settle();
2760            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2761
2762            tester.long_press(CENTER);
2763            tester.pump_by(ONE_DAY);
2764            tester.pump_and_settle();
2765            // Still visible.
2766            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2767
2768            // Still visible.
2769            tester.pump_by(ONE_DAY);
2770            tester.pump_and_settle();
2771
2772            // The tooltip is no longer hovered and becomes invisible.
2773            tester.mouse_move_to(Offset::ZERO);
2774            tester.pump_by(ONE_DAY);
2775            tester.pump_and_settle();
2776            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2777        });
2778    }
2779
2780    /// The `Center(SizedBox.square(10, RawTooltip(child: SizedBox.expand())))` of the
2781    /// dismiss-delay cases.
2782    fn small_hover_case(tester: &mut Tester, dismiss_delay: Option<Duration>) -> GlobalKey {
2783        let tip_key = GlobalKey::new();
2784        let key = tip_key.clone();
2785        tester.pump_widget(move || {
2786            let key = key.clone();
2787            let mut tooltip = RawTooltip::new(
2788                Some("TIP".into()),
2789                move |_app, _context, _animation| tip(&key),
2790                SizedBox::expand(),
2791            );
2792            if let Some(dismiss_delay) = dismiss_delay {
2793                tooltip = tooltip.dismiss_delay(dismiss_delay);
2794            }
2795            Center::new()
2796                .child(sized_box(10.0, 10.0).child(tooltip))
2797                .into_widget()
2798        });
2799        tip_key
2800    }
2801
2802    #[test]
2803    fn hovered_tooltips_hide_after_stopping_the_hover() {
2804        test_widgets(|tester| {
2805            let mut tester = Tester::new(tester);
2806            let tip_key = small_hover_case(&mut tester, None);
2807
2808            tester.mouse_move_to(CENTER);
2809            tester.pump_by(Duration::from_secs(1));
2810            // Tooltip should be visible when hovered.
2811            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2812
2813            tester.mouse_move_to(Offset::ZERO);
2814            tester.pump_by(Duration::from_millis(100));
2815            tester.pump_and_settle();
2816            // Tooltip should be hidden when no longer hovered.
2817            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2818        });
2819    }
2820
2821    #[test]
2822    fn hovered_tooltips_hide_after_stopping_the_hover_and_dismiss_delay_expires() {
2823        test_widgets(|tester| {
2824            let dismiss_delay = Duration::from_secs(1);
2825            let mut tester = Tester::new(tester);
2826            let tip_key = small_hover_case(&mut tester, Some(dismiss_delay));
2827
2828            tester.mouse_move_to(CENTER);
2829            tester.pump_by(Duration::from_secs(1));
2830            // Tooltip should be visible when hovered.
2831            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2832
2833            tester.mouse_move_to(Offset::ZERO);
2834            tester.pump_by(Duration::from_millis(100));
2835            tester.pump_and_settle();
2836            // Tooltip should wait until dismissDelay expires before being hidden
2837            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2838
2839            tester.pump_by(Duration::from_secs(1));
2840            tester.pump_and_settle();
2841            // Tooltip should be hidden when no longer hovered.
2842            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2843        });
2844    }
2845
2846    #[test]
2847    fn raw_tooltip_ignores_pointer_events_when_ignore_pointer_is_true() {
2848        test_widgets(|tester| {
2849            let mut tester = Tester::new(tester);
2850            tester.mouse_move_to(Offset::ZERO);
2851            let tip_key = GlobalKey::new();
2852            let key = tip_key.clone();
2853            tester.pump_widget(move || {
2854                let key = key.clone();
2855                Center::new()
2856                    .child(
2857                        RawTooltip::new(
2858                            Some("TIP".into()),
2859                            move |_app, _context, _animation| tip(&key),
2860                            Text::new("Hover me"),
2861                        )
2862                        .ignore_pointer(true),
2863                    )
2864                    .into_widget()
2865            });
2866
2867            // Hover over the target widget.
2868            tester.mouse_move_to(CENTER);
2869            tester.pump();
2870
2871            // Wait for the tooltip to actually appear.
2872            tester.pump_by(Duration::from_millis(100));
2873            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
2874
2875            // Move the mouse to the tooltip overlay.
2876            let tip = tester.get_center(&tip_key);
2877            tester.mouse_move_to(tip);
2878            tester.pump_and_settle();
2879
2880            // Verify the tooltip overlay is no longer displayed.
2881            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2882        });
2883    }
2884
2885    #[test]
2886    fn a_tooltip_with_an_empty_semantics_tooltip_builds_only_its_child() {
2887        test_widgets(|tester| {
2888            let mut tester = Tester::new(tester);
2889            let (tip_key, child_key) = (GlobalKey::new(), GlobalKey::new());
2890            let (key, child) = (tip_key.clone(), child_key.clone());
2891            tester.pump_widget(move || {
2892                let key = key.clone();
2893                RawTooltip::new(
2894                    Some(String::new()),
2895                    move |_app, _context, _animation| tip(&key),
2896                    SizedBox::shrink().key(child.clone().into()),
2897                )
2898                .into_widget()
2899            });
2900            expect(
2901                &tester,
2902                &find::by_global_key(&child_key),
2903                finds_one_widget(),
2904            );
2905            let state = child_key
2906                .current_context(&tester.cell.borrow_mut())
2907                .expect("mounted");
2908            let app = tester.cell.borrow();
2909            assert!(
2910                state
2911                    .find_ancestor_state_of_type::<RawTooltipState>(&app)
2912                    .is_some(),
2913                "the tooltip is still in the tree"
2914            );
2915            drop(app);
2916            tester.long_press(Offset::ZERO);
2917            tester.pump_by(Duration::from_secs(1));
2918            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
2919        });
2920    }
2921
2922    /// The text direction of the paragraph `key` is on.
2923    fn text_direction_of(tester: &Tester, key: &GlobalKey) -> TextDirection {
2924        let app = tester.cell.borrow();
2925        key.current_context(&app)
2926            .expect("mounted")
2927            .find_render_object(&app)
2928            .and_then(|render_object| render_object.downcast::<RenderParagraph>(&app))
2929            .expect("a paragraph")
2930            .text_direction(&app)
2931    }
2932
2933    #[test]
2934    fn raw_tooltip_overlay_respects_ambient_directionality() {
2935        test_widgets(|tester| {
2936            // Regression test for https://github.com/flutter/flutter/issues/40702.
2937            let mut tester = Tester::new(tester);
2938            let (tooltip_key, text_key) = (GlobalKey::new(), GlobalKey::new());
2939            let build_app = |text_direction: TextDirection| {
2940                let (tooltip_key, text_key) = (tooltip_key.clone(), text_key.clone());
2941                move || {
2942                    let text_key = text_key.clone();
2943                    Directionality::new(
2944                        text_direction,
2945                        Center::new().child(
2946                            RawTooltip::new(
2947                                Some("TIP".into()),
2948                                move |_app, _context, _animation| {
2949                                    Text::new("TIP").key(text_key.clone().into()).into_widget()
2950                                },
2951                                sized_box(100.0, 100.0)
2952                                    .child(ColoredBox::new(Color::new(0xff00ff00))),
2953                            )
2954                            .key(tooltip_key.clone().into()),
2955                        ),
2956                    )
2957                    .into_widget()
2958                }
2959            };
2960
2961            tester.pump_widget(build_app(TextDirection::Rtl));
2962            let center = tester.get_center(&tooltip_key);
2963            tester.long_press(center);
2964            expect(&tester, &find::by_global_key(&text_key), finds_one_widget());
2965            assert_eq!(text_direction_of(&tester, &text_key), TextDirection::Rtl);
2966
2967            tester.pump_by(Duration::from_secs(10));
2968            tester.pump_and_settle();
2969            tester.pump();
2970
2971            tester.pump_widget(build_app(TextDirection::Ltr));
2972            tester.long_press(center);
2973            expect(&tester, &find::by_global_key(&text_key), finds_one_widget());
2974            assert_eq!(text_direction_of(&tester, &text_key), TextDirection::Ltr);
2975        });
2976    }
2977
2978    #[test]
2979    fn tooltip_is_dismissed_after_a_tap_and_touch_delay_expired_when_competing_with_a_gesture_detector()
2980     {
2981        test_widgets(|tester| {
2982            // Regression test for https://github.com/flutter/flutter/issues/98854
2983            let touch_delay = Duration::from_secs(3);
2984            let mut tester = Tester::new(tester);
2985            let (tooltip_key, tip_key) = (GlobalKey::new(), GlobalKey::new());
2986            let (tooltip, key) = (tooltip_key.clone(), tip_key.clone());
2987            tester.pump_widget(move || {
2988                let key = key.clone();
2989                GestureDetector::new()
2990                    .on_vertical_drag_start(Rc::new(|_app, _details| {
2991                        // Do nothing
2992                    }))
2993                    .child(
2994                        RawTooltip::new(
2995                            Some("TIP".into()),
2996                            move |_app, _context, _animation| tip(&key),
2997                            sized_box(100.0, 100.0),
2998                        )
2999                        .key(tooltip.clone().into())
3000                        .trigger_mode(TooltipTriggerMode::Tap)
3001                        .touch_delay(touch_delay),
3002                    )
3003                    .into_widget()
3004            });
3005            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3006
3007            let center = tester.get_center(&tooltip_key);
3008            tester.tap(center);
3009            // Wait for GestureArena disambiguation, delay is kPressTimeout to disambiguate
3010            // between onTap and onVerticalDragStart
3011            tester.pump_by(K_PRESS_TIMEOUT);
3012            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3013
3014            // Tooltip is dismissed after touchDelay expired
3015            tester.pump_by(touch_delay);
3016            tester.pump_by(Duration::from_millis(10));
3017            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3018        });
3019    }
3020
3021    #[test]
3022    fn dispatch_the_mouse_events_before_tip_overlay_detached() {
3023        test_widgets(|tester| {
3024            // Regression test for https://github.com/flutter/flutter/issues/96890
3025            let hover_delay = Duration::ZERO;
3026            let mut tester = Tester::new(tester);
3027            tester.mouse_add_pointer(Offset::ZERO);
3028            tester.mouse_move_to(Offset::new(1.0, 1.0));
3029            tester.pump();
3030            tester.mouse_move_to(Offset::ZERO);
3031
3032            let tip_key = hover_case(&mut tester, |tooltip| tooltip);
3033
3034            // Trigger the tip overlay.
3035            tester.mouse_move_to(CENTER);
3036            tester.pump();
3037            // Wait for it to appear.
3038            tester.pump_by(hover_delay);
3039            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3040
3041            // Remove the `Tooltip` widget.
3042            tester.pump_root(Center::new().child(SizedBox::shrink()).into_widget());
3043
3044            // The tooltip should be removed, including the overlay child.
3045            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3046        });
3047    }
3048
3049    #[test]
3050    fn calling_ensure_tooltip_visible_on_an_unmounted_raw_tooltip_state_returns_false() {
3051        test_widgets(|tester| {
3052            // Regression test for https://github.com/flutter/flutter/issues/95851
3053            let mut tester = Tester::new(tester);
3054            let tooltip_key = GlobalKey::new();
3055            let key = tooltip_key.clone();
3056            tester.pump_widget(move || {
3057                Center::new()
3058                    .child(
3059                        RawTooltip::new(
3060                            Some("TIP".into()),
3061                            |_app, _context, _animation| sized_box(42.0, 14.0).into_widget(),
3062                            sized_box(100.0, 100.0),
3063                        )
3064                        .key(key.clone().into()),
3065                    )
3066                    .into_widget()
3067            });
3068
3069            let tooltip_state = tester.state(&tooltip_key);
3070            assert!(tooltip_state.ensure_tooltip_visible(&mut tester.cell.borrow_mut()));
3071
3072            // Remove the tooltip.
3073            tester.pump_root(Center::new().child(SizedBox::shrink()).into_widget());
3074
3075            // The recorded divergence: Dart's `?? false` through the key, as Material's `TooltipState`
3076            // reaches it; the stale handle itself is gone.
3077            let state = tooltip_key.current_state::<RawTooltipState>(&tester.cell.borrow_mut());
3078            let visible = state
3079                .is_some_and(|state| state.ensure_tooltip_visible(&mut tester.cell.borrow_mut()));
3080            assert!(!visible);
3081            assert!(!tester.cell.borrow().contains(tooltip_state));
3082        });
3083    }
3084
3085    #[test]
3086    fn tooltip_shows_and_hides_when_the_mouse_hovers_and_then_exits_and_re_enters_in_quick_succession()
3087     {
3088        test_widgets(|tester| {
3089            let hover_delay = Duration::from_millis(700);
3090            let mut tester = Tester::new(tester);
3091            tester.mouse_add_pointer(Offset::ZERO);
3092            tester.mouse_move_to(Offset::new(1.0, 1.0));
3093            let tip_key = hover_case(&mut tester, move |tooltip| {
3094                tooltip.hover_delay(hover_delay).dismiss_delay(hover_delay)
3095            });
3096
3097            let mouse_enter_and_wait_until_visible = |tester: &mut Tester| {
3098                tester.mouse_move_to(CENTER);
3099                tester.pump();
3100                tester.pump_by(hover_delay);
3101                tester.pump_and_settle();
3102                expect(tester, &find::by_global_key(&tip_key), finds_one_widget());
3103            };
3104            let mouse_exit = |tester: &mut Tester| {
3105                tester.mouse_move_to(Offset::ZERO);
3106                tester.pump();
3107            };
3108            let wait_for_reset = |tester: &mut Tester| {
3109                mouse_exit(tester);
3110                tester.pump_by(Duration::from_secs(60 * 60));
3111                tester.pump_and_settle();
3112                expect(tester, &find::by_global_key(&tip_key), finds_nothing());
3113            };
3114
3115            mouse_enter_and_wait_until_visible(&mut tester);
3116            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3117
3118            wait_for_reset(&mut tester);
3119
3120            mouse_enter_and_wait_until_visible(&mut tester);
3121            mouse_exit(&mut tester);
3122            mouse_enter_and_wait_until_visible(&mut tester);
3123            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3124
3125            wait_for_reset(&mut tester);
3126
3127            mouse_enter_and_wait_until_visible(&mut tester);
3128            mouse_exit(&mut tester);
3129            mouse_enter_and_wait_until_visible(&mut tester);
3130            mouse_exit(&mut tester);
3131            mouse_enter_and_wait_until_visible(&mut tester);
3132            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3133
3134            wait_for_reset(&mut tester);
3135        });
3136    }
3137
3138    #[test]
3139    fn tooltip_does_not_attempt_to_show_after_unmount() {
3140        test_widgets(|tester| {
3141            // Regression test for https://github.com/flutter/flutter/issues/54096.
3142            let hover_delay = Duration::from_secs(1);
3143            let mut tester = Tester::new(tester);
3144            tester.mouse_add_pointer(Offset::ZERO);
3145            tester.mouse_move_to(Offset::new(1.0, 1.0));
3146            tester.pump();
3147            tester.mouse_move_to(Offset::ZERO);
3148
3149            hover_case(&mut tester, move |tooltip| tooltip.hover_delay(hover_delay));
3150
3151            tester.mouse_move_to(Offset::ZERO);
3152            tester.pump();
3153            tester.mouse_move_to(CENTER);
3154            tester.pump();
3155
3156            // Pump another random widget to unmount the Tooltip widget.
3157            tester.pump_root(Center::new().child(SizedBox::new()).into_widget());
3158
3159            // If the issue regresses, a panic will be raised while we are waiting.
3160            tester.pump_by(hover_delay);
3161        });
3162    }
3163
3164    /// Dart's `FeedbackTester.hapticCount`: the `HapticFeedback.vibrate` messages, which carry
3165    /// every feedback kind.
3166    #[derive(Default)]
3167    struct CountingHaptics {
3168        haptic_count: Cell<usize>,
3169    }
3170
3171    impl waft_embedder::Haptics for CountingHaptics {
3172        fn feedback(&self, _kind: waft_embedder::HapticFeedbackType) {
3173            self.haptic_count.set(self.haptic_count.get() + 1);
3174        }
3175    }
3176
3177    #[test]
3178    fn haptic_feedback() {
3179        let feedback = Rc::new(CountingHaptics::default());
3180        // Flutter's tests run on Android, where a long press vibrates.
3181        let tester =
3182            &mut WidgetTester::with_platform(TestPlatform::new().with_haptics(feedback.clone()));
3183        let mut tester = Tester::new(tester);
3184        hover_case(&mut tester, |tooltip| tooltip);
3185
3186        tester.long_press(CENTER);
3187        tester.pump_by(Duration::from_secs(1));
3188        tester.pump_and_settle();
3189        assert_eq!(feedback.haptic_count.get(), 1);
3190    }
3191
3192    #[test]
3193    fn tooltip_does_not_trigger_on_tap_when_trigger_mode_is_long_press() {
3194        test_widgets(|tester| {
3195            let mut tester = Tester::new(tester);
3196            let tip_key = set_widget_for_tooltip_mode(
3197                &mut tester,
3198                TooltipTriggerMode::LongPress,
3199                None,
3200                None,
3201                None,
3202            );
3203            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3204
3205            tester.test_gesture_tap(CENTER);
3206            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3207        });
3208    }
3209
3210    #[test]
3211    fn hovered_tooltips_with_touch_delay_set_do_dismiss_when_hovering_elsewhere() {
3212        test_widgets(|tester| {
3213            let touch_delay = Duration::from_secs(1);
3214            let mut tester = Tester::new(tester);
3215            let tip_key = hover_case(&mut tester, move |tooltip| tooltip.touch_delay(touch_delay));
3216
3217            tester.mouse_move_to(CENTER);
3218            tester.pump_by(Duration::from_secs(1));
3219            // Tooltip should be visible when hovered.
3220            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3221
3222            tester.mouse_move_to(Offset::ZERO);
3223            // Set a duration equal to the default exit
3224            tester.pump_by(Duration::from_millis(100));
3225            tester.pump_and_settle();
3226            // Tooltip should not wait for touchDelay before it hides itself.
3227            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3228        });
3229    }
3230
3231    #[test]
3232    fn tooltip_should_not_be_shown_with_empty_message_with_child() {
3233        test_widgets(|tester| {
3234            let mut tester = Tester::new(tester);
3235            let (tip_key, child_key) = (GlobalKey::new(), GlobalKey::new());
3236            let (key, child) = (tip_key.clone(), child_key.clone());
3237            tester.pump_widget(move || {
3238                let key = key.clone();
3239                RawTooltip::new(
3240                    Some("TIP".into()),
3241                    move |_app, _context, _animation| tip(&key),
3242                    tip(&child),
3243                )
3244                .into_widget()
3245            });
3246            expect(
3247                &tester,
3248                &find::by_global_key(&child_key),
3249                finds_one_widget(),
3250            );
3251            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3252        });
3253    }
3254
3255    #[test]
3256    fn tooltip_should_not_be_shown_with_empty_message_without_child() {
3257        test_widgets(|tester| {
3258            let mut tester = Tester::new(tester);
3259            let tip_key = GlobalKey::new();
3260            let key = tip_key.clone();
3261            tester.pump_widget(move || {
3262                let key = key.clone();
3263                RawTooltip::new(
3264                    Some("TIP".into()),
3265                    move |_app, _context, _animation| tip(&key),
3266                    SizedBox::shrink(),
3267                )
3268                .into_widget()
3269            });
3270            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3271        });
3272    }
3273
3274    /// `home: RawTooltip(child: SizedBox.expand())`, filling the view.
3275    fn expanded_case(tester: &mut Tester) -> GlobalKey {
3276        let tip_key = GlobalKey::new();
3277        let key = tip_key.clone();
3278        tester.pump_widget(move || {
3279            let key = key.clone();
3280            RawTooltip::new(
3281                Some("TIP".into()),
3282                move |_app, _context, _animation| tip(&key),
3283                SizedBox::expand(),
3284            )
3285            .into_widget()
3286        });
3287        tip_key
3288    }
3289
3290    #[test]
3291    fn tooltip_trigger_mode_ignores_mouse_events() {
3292        test_widgets(|tester| {
3293            let mut tester = Tester::new(tester);
3294            let tip_key = expanded_case(&mut tester);
3295
3296            tester.mouse_down(CENTER);
3297            tester.pump_by(K_LONG_PRESS_TIMEOUT + K_PRESS_TIMEOUT);
3298            tester.mouse_up();
3299
3300            tester.pump();
3301            tester.pump_and_settle();
3302            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3303
3304            let touch_gesture = tester.start_gesture(CENTER);
3305            tester.pump_by(K_LONG_PRESS_TIMEOUT + K_PRESS_TIMEOUT);
3306            tester.up(&touch_gesture);
3307
3308            tester.pump();
3309            tester.pump_and_settle();
3310            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3311        });
3312    }
3313
3314    #[test]
3315    fn tooltip_does_not_block_other_mouse_regions() {
3316        test_widgets(|tester| {
3317            let entered = Rc::new(Cell::new(false));
3318            let mut tester = Tester::new(tester);
3319            let sink = Rc::clone(&entered);
3320            tester.pump_widget(move || {
3321                let sink = Rc::clone(&sink);
3322                MouseRegion::new()
3323                    .on_enter(Rc::new(move |_app, _event| sink.set(true)))
3324                    .child(RawTooltip::new(
3325                        Some("TIP".into()),
3326                        |_app, _context, _animation| sized_box(42.0, 14.0).into_widget(),
3327                        SizedBox::expand(),
3328                    ))
3329                    .into_widget()
3330            });
3331
3332            assert!(!entered.get());
3333
3334            tester.mouse_add_pointer(Offset::ZERO);
3335            tester.mouse_move_to(CENTER);
3336            tester.mouse_remove_pointer();
3337
3338            assert!(entered.get());
3339        });
3340    }
3341
3342    #[test]
3343    fn does_not_rebuild_on_mouse_connect_and_disconnect() {
3344        test_widgets(|tester| {
3345            // Regression test for https://github.com/flutter/flutter/issues/117627
3346            let build_count = Rc::new(Cell::new(0));
3347            let mut tester = Tester::new(tester);
3348            let count = Rc::clone(&build_count);
3349            tester.pump_widget(move || {
3350                let count = Rc::clone(&count);
3351                RawTooltip::new(
3352                    Some("TIP".into()),
3353                    |_app, _context, _animation| sized_box(42.0, 14.0).into_widget(),
3354                    Builder::new(move |_app, _context| {
3355                        count.set(count.get() + 1);
3356                        SizedBox::expand().into_widget()
3357                    }),
3358                )
3359                .into_widget()
3360            });
3361            assert_eq!(build_count.get(), 1);
3362
3363            tester.mouse_add_pointer(Offset::ZERO);
3364            tester.pump();
3365            tester.mouse_remove_pointer();
3366            tester.pump();
3367
3368            assert_eq!(build_count.get(), 1);
3369        });
3370    }
3371
3372    /// `Center(SizedBox.square(10, RawTooltip(hoverDelay: 1s, child: SizedBox.expand())))`.
3373    fn square_hover_case(
3374        tester: &mut Tester,
3375        configure: impl Fn(RawTooltip) -> RawTooltip + 'static,
3376    ) -> (GlobalKey, GlobalKey) {
3377        let (tooltip_key, tip_key) = (GlobalKey::new(), GlobalKey::new());
3378        let (tooltip, key) = (tooltip_key.clone(), tip_key.clone());
3379        tester.pump_widget(move || {
3380            let key = key.clone();
3381            Center::new()
3382                .child(
3383                    sized_box(10.0, 10.0).child(configure(
3384                        RawTooltip::new(
3385                            Some("TIP".into()),
3386                            move |_app, _context, _animation| tip(&key),
3387                            SizedBox::expand(),
3388                        )
3389                        .key(tooltip.clone().into())
3390                        .hover_delay(Duration::from_secs(1)),
3391                    )),
3392                )
3393                .into_widget()
3394        });
3395        (tooltip_key, tip_key)
3396    }
3397
3398    #[test]
3399    fn hold_mouse_button_down_and_hover_over_the_tooltip_widget() {
3400        test_widgets(|tester| {
3401            let mut tester = Tester::new(tester);
3402            let (_, tip_key) = square_hover_case(&mut tester, |tooltip| tooltip);
3403
3404            tester.mouse_down(Offset::ZERO);
3405            tester.mouse_move_to(CENTER);
3406            tester.pump_by(Duration::from_secs(1));
3407            // Tooltip should be visible when hovered.
3408            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3409
3410            tester.mouse_up();
3411            tester.pump_by(Duration::from_secs(10 * 24 * 60 * 60));
3412            tester.pump_and_settle();
3413            // Tooltip should be visible even when there is a PointerUp when hovered.
3414            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3415
3416            tester.mouse_move_to(Offset::ZERO);
3417            tester.pump_by(Duration::from_secs(1));
3418            tester.pump_and_settle();
3419            // Tooltip should be dismissed with no hovering mouse cursor.
3420            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3421        });
3422    }
3423
3424    #[test]
3425    fn hovered_text_should_dismiss_when_clicked_outside() {
3426        test_widgets(|tester| {
3427            let mut tester = Tester::new(tester);
3428            let (_, tip_key) = square_hover_case(&mut tester, |tooltip| {
3429                tooltip.position_delegate(below_with_vertical_offset_24())
3430            });
3431
3432            // Avoid using startGesture here to avoid the PointDown event from also being
3433            // interpreted as a PointHover event by the Tooltip.
3434            tester.mouse_move_to(CENTER);
3435            tester.pump_by(Duration::from_secs(1));
3436            // Tooltip should be visible when hovered.
3437            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3438
3439            // Tapping on the Tooltip widget should dismiss the tooltip, since the
3440            // trigger mode is longPress.
3441            tester.tap(CENTER);
3442            tester.pump();
3443            tester.pump_and_settle();
3444            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3445            tester.mouse_remove_pointer();
3446
3447            tester.mouse_move_to(CENTER);
3448            tester.pump_by(Duration::from_secs(1));
3449            // Tooltip should be visible when hovered.
3450            expect(&tester, &find::by_global_key(&tip_key), finds_one_widget());
3451
3452            tester.tap(Offset::ZERO);
3453            tester.pump();
3454            tester.pump_and_settle();
3455            // Tapping outside of the Tooltip widget should dismiss the tooltip.
3456            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3457        });
3458    }
3459
3460    #[test]
3461    fn mouse_tap_and_hover_over_the_tooltip_widget() {
3462        test_widgets(|tester| {
3463            // Regression test for https://github.com/flutter/flutter/issues/127575 .
3464            let mut tester = Tester::new(tester);
3465            let (_, tip_key) = square_hover_case(&mut tester, |tooltip| tooltip);
3466
3467            // The PointDown event is also interpreted as a PointHover event by the
3468            // Tooltip. This should be pretty rare but since it's more of a tap event
3469            // than a hover event, the tooltip shouldn't show unless the triggerMode
3470            // is set to tap.
3471            tester.mouse_down(CENTER);
3472            tester.pump_by(Duration::from_secs(1));
3473            // Tooltip should NOT be visible when hovered and tapped, when trigger mode is not tap
3474            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3475            tester.mouse_up();
3476            tester.mouse_remove_pointer();
3477            tester.pump_by(Duration::from_secs(10 * 24 * 60 * 60));
3478            tester.pump_and_settle();
3479
3480            let (_, tip_key) = square_hover_case(&mut tester, |tooltip| {
3481                tooltip.trigger_mode(TooltipTriggerMode::Tap)
3482            });
3483
3484            tester.mouse_down(CENTER);
3485            // The tap should be ignored, since Tooltip does not track "trigger gestures"
3486            // for mouse devices.
3487            tester.pump_by(Duration::from_millis(100));
3488            tester.mouse_up();
3489            tester.pump_by(Duration::from_secs(1));
3490            // Tooltip should NOT be visible when hovered and tapped, when trigger mode is tap
3491            expect(&tester, &find::by_global_key(&tip_key), finds_nothing());
3492        });
3493    }
3494
3495    #[test]
3496    fn tooltip_does_not_rebuild_for_show_and_hide_animation() {
3497        test_widgets(|tester| {
3498            let mut tester = Tester::new(tester);
3499            let tooltip_key = GlobalKey::new();
3500            let key = tooltip_key.clone();
3501            tester.pump_widget(move || {
3502                Center::new()
3503                    .child(
3504                        sized_box(10.0, 10.0).child(
3505                            RawTooltip::new(
3506                                Some("TIP".into()),
3507                                |_app, _context, animation| {
3508                                    FadeTransition::new(animation)
3509                                        .child(sized_box(42.0, 14.0))
3510                                        .into_widget()
3511                                },
3512                                SizedBox::expand(),
3513                            )
3514                            .key(key.clone().into())
3515                            .hover_delay(Duration::from_secs(1)),
3516                        ),
3517                    )
3518                    .into_widget()
3519            });
3520            let tooltip_state = tester.state(&tooltip_key);
3521            let element = tooltip_state.context(&tester.cell.borrow());
3522            let dirty = |tester: &Tester| element.dirty(&tester.cell.borrow());
3523            // The Tooltip widget itself is almost stateless thus doesn't need
3524            // rebuilding.
3525            assert!(!dirty(&tester));
3526
3527            assert!(tooltip_state.ensure_tooltip_visible(&mut tester.cell.borrow_mut()));
3528            assert!(!dirty(&tester));
3529            tester.pump_by(Duration::from_secs(1));
3530            assert!(!dirty(&tester));
3531
3532            assert!(RawTooltip::dismiss_all_tool_tips(
3533                &mut tester.cell.borrow_mut()
3534            ));
3535            assert!(!dirty(&tester));
3536            tester.pump_by(Duration::from_secs(1));
3537            assert!(!dirty(&tester));
3538        });
3539    }
3540
3541    /// `Center(RawTooltip(hoverDelay: 1s, child: SizedBox.square(50)))`.
3542    fn disposal_case(tester: &mut Tester) -> GlobalKey {
3543        let tooltip_key = GlobalKey::new();
3544        let key = tooltip_key.clone();
3545        tester.pump_widget(move || {
3546            Center::new()
3547                .child(
3548                    RawTooltip::new(
3549                        Some("TIP".into()),
3550                        |_app, _context, _animation| sized_box(42.0, 14.0).into_widget(),
3551                        sized_box(50.0, 50.0),
3552                    )
3553                    .key(key.clone().into())
3554                    .hover_delay(Duration::from_secs(1)),
3555                )
3556                .into_widget()
3557        });
3558        tooltip_key
3559    }
3560
3561    #[test]
3562    fn tooltip_does_not_initialize_animation_controller_in_dispose_process() {
3563        test_widgets(|tester| {
3564            let mut tester = Tester::new(tester);
3565            disposal_case(&mut tester);
3566
3567            let gesture = tester.start_gesture(CENTER);
3568            tester.pump_root(SizedBox::new().into_widget());
3569
3570            // Finish gesture to release resources.
3571            tester.up(&gesture);
3572            tester.pump_and_settle();
3573        });
3574    }
3575
3576    #[test]
3577    fn tooltip_does_not_crash_when_showing_the_tooltip_but_the_overlay_portal_is_unmounted_during_dispose()
3578     {
3579        test_widgets(|tester| {
3580            let mut tester = Tester::new(tester);
3581            let tooltip_key = disposal_case(&mut tester);
3582
3583            let tooltip_state = tester.state(&tooltip_key);
3584            let gesture = tester.start_gesture(CENTER);
3585            tooltip_state.ensure_tooltip_visible(&mut tester.cell.borrow_mut());
3586            tester.pump_root(SizedBox::new().into_widget());
3587
3588            // Finish gesture to release resources.
3589            tester.up(&gesture);
3590            tester.pump_and_settle();
3591        });
3592    }
3593
3594    #[test]
3595    fn raw_tooltip_does_not_crash_at_zero_area() {
3596        test_widgets(|tester| {
3597            tester.view().set_physical_size(Size::ZERO);
3598            let mut tester = Tester::new(tester);
3599            let tooltip_key = GlobalKey::new();
3600            let key = tooltip_key.clone();
3601            tester.pump_widget(move || {
3602                Center::new()
3603                    .child(
3604                        RawTooltip::new(
3605                            Some("TIP".into()),
3606                            |_app, _context, _animation| Text::new("Y").into_widget(),
3607                            Text::new("X"),
3608                        )
3609                        .key(key.clone().into()),
3610                    )
3611                    .into_widget()
3612            });
3613            assert_eq!(tester.get_size(&tooltip_key), Size::ZERO);
3614        });
3615    }
3616
3617    /// The tree of the `AnimationStyle` cases: `Center(RawTooltip(key:, animationStyle:,
3618    /// child: SizedBox(100x100)))`, whose tooltip builder keeps the animation it is given.
3619    struct AnimationStyleCase<'t> {
3620        tester: Tester<'t>,
3621        tooltip_key: GlobalKey,
3622        tip_key: GlobalKey,
3623        tooltip_animation: Rc<RefCell<Option<AnimationRef<f64>>>>,
3624    }
3625
3626    impl<'t> AnimationStyleCase<'t> {
3627        fn new(
3628            tester: &'t mut WidgetTester,
3629            animation_style: AnimationStyle,
3630        ) -> AnimationStyleCase<'t> {
3631            let mut this = AnimationStyleCase {
3632                tester: Tester::new(tester),
3633                tooltip_key: GlobalKey::new(),
3634                tip_key: GlobalKey::new(),
3635                tooltip_animation: Rc::default(),
3636            };
3637            this.pump_widget(animation_style);
3638            this
3639        }
3640
3641        /// Dart's `tester.pumpWidget(buildApp(animationStyle))`.
3642        fn pump_widget(&mut self, animation_style: AnimationStyle) {
3643            let (tooltip_key, tip_key) = (self.tooltip_key.clone(), self.tip_key.clone());
3644            let tooltip_animation = Rc::clone(&self.tooltip_animation);
3645            self.tester.pump_widget(move || {
3646                let (tip_key, tooltip_animation) = (tip_key.clone(), Rc::clone(&tooltip_animation));
3647                Center::new()
3648                    .child(
3649                        RawTooltip::new(
3650                            Some("TIP".into()),
3651                            move |_app, _context, animation| {
3652                                *tooltip_animation.borrow_mut() = Some(animation);
3653                                tip(&tip_key)
3654                            },
3655                            sized_box(100.0, 100.0),
3656                        )
3657                        .key(tooltip_key.clone().into())
3658                        .animation_style(animation_style.clone()),
3659                    )
3660                    .into_widget()
3661            });
3662        }
3663
3664        fn ensure_tooltip_visible(&mut self) {
3665            let state = self.tester.state(&self.tooltip_key);
3666            state.ensure_tooltip_visible(&mut self.tester.cell.borrow_mut());
3667        }
3668
3669        fn dismiss_all_tool_tips(&mut self) {
3670            RawTooltip::dismiss_all_tool_tips(&mut self.tester.cell.borrow_mut());
3671        }
3672
3673        /// `tooltipAnimation.value`.
3674        fn value(&self) -> f64 {
3675            let animation = self
3676                .tooltip_animation
3677                .borrow()
3678                .clone()
3679                .expect("the tooltip was built");
3680            animation.value(&self.tester.cell.borrow())
3681        }
3682
3683        /// Dart's `find.text(tooltipText)`: the tip, keyed.
3684        fn tip(&self) -> Finder {
3685            find::by_global_key(&self.tip_key)
3686        }
3687    }
3688
3689    fn style(
3690        curve: Rc<dyn Curve>,
3691        duration: Option<Duration>,
3692        reverse_curve: Option<Rc<dyn Curve>>,
3693        reverse_duration: Option<Duration>,
3694    ) -> AnimationStyle {
3695        AnimationStyle::new(Some(curve), duration, reverse_curve, reverse_duration)
3696    }
3697
3698    const MS_100: Option<Duration> = Some(Duration::from_millis(100));
3699
3700    #[test]
3701    fn animation_style_reverse_curve_is_used_for_the_hide_animation() {
3702        test_widgets(|tester| {
3703            let mut case = AnimationStyleCase::new(
3704                tester,
3705                style(
3706                    Curves::linear(),
3707                    MS_100,
3708                    Some(Curves::ease_in_expo()),
3709                    MS_100,
3710                ),
3711            );
3712
3713            case.ensure_tooltip_visible();
3714            case.tester.pump();
3715            case.tester.pump_by(Duration::from_millis(50));
3716
3717            // Halfway through the show animation, the forward curve applies.
3718            assert_more_or_less_equals(case.value(), 0.5);
3719            // CurvedAnimation only switches to the reverse curve when the direction
3720            // changes from a completed state.
3721            case.tester.pump_and_settle();
3722            assert_eq!(case.value(), 1.0);
3723
3724            case.dismiss_all_tool_tips();
3725            case.tester.pump();
3726            case.tester.pump_by(Duration::from_millis(50));
3727
3728            // Halfway through the hide animation, the reverse curve applies.
3729            assert_more_or_less_equals(case.value(), Curves::ease_in_expo().transform(0.5));
3730            case.tester.pump_and_settle();
3731            expect(&case.tester, &case.tip(), finds_nothing());
3732        });
3733    }
3734
3735    #[test]
3736    fn hide_animation_uses_the_forward_curve_when_animation_style_reverse_curve_is_null() {
3737        test_widgets(|tester| {
3738            let mut case = AnimationStyleCase::new(
3739                tester,
3740                style(Curves::ease_in_expo(), MS_100, None, MS_100),
3741            );
3742
3743            case.ensure_tooltip_visible();
3744            case.tester.pump();
3745            case.tester.pump_and_settle();
3746
3747            case.dismiss_all_tool_tips();
3748            case.tester.pump();
3749            case.tester.pump_by(Duration::from_millis(50));
3750
3751            // The hide animation follows the forward curve when no reverse curve is
3752            // provided.
3753            assert_more_or_less_equals(case.value(), Curves::ease_in_expo().transform(0.5));
3754            case.tester.pump_and_settle();
3755            expect(&case.tester, &case.tip(), finds_nothing());
3756        });
3757    }
3758
3759    #[test]
3760    fn animation_style_duration_changes_take_effect_after_the_first_show() {
3761        test_widgets(|tester| {
3762            let mut case =
3763                AnimationStyleCase::new(tester, style(Curves::linear(), MS_100, None, MS_100));
3764
3765            // Show once to instantiate the lazily-created animation controller.
3766            case.ensure_tooltip_visible();
3767            case.tester.pump_and_settle();
3768            case.dismiss_all_tool_tips();
3769            case.tester.pump_and_settle();
3770            expect(&case.tester, &case.tip(), finds_nothing());
3771
3772            case.pump_widget(style(
3773                Curves::linear(),
3774                Some(Duration::from_millis(300)),
3775                None,
3776                MS_100,
3777            ));
3778
3779            case.ensure_tooltip_visible();
3780            case.tester.pump();
3781            case.tester.pump_by(Duration::from_millis(150));
3782
3783            // Halfway through the updated 300ms show duration, not the original 100ms
3784            // duration which would have already completed the animation.
3785            assert_more_or_less_equals(case.value(), 0.5);
3786            case.tester.pump_by(Duration::from_millis(150));
3787            assert_eq!(case.value(), 1.0);
3788
3789            case.dismiss_all_tool_tips();
3790            case.tester.pump_and_settle();
3791            expect(&case.tester, &case.tip(), finds_nothing());
3792        });
3793    }
3794
3795    #[test]
3796    fn null_animation_style_durations_fall_back_to_the_documented_defaults() {
3797        test_widgets(|tester| {
3798            let mut case =
3799                AnimationStyleCase::new(tester, style(Curves::linear(), None, None, None));
3800
3801            case.ensure_tooltip_visible();
3802            case.tester.pump();
3803            case.tester.pump_by(Duration::from_millis(75));
3804
3805            // Halfway through the default 150ms show duration.
3806            assert_more_or_less_equals(case.value(), 0.5);
3807            case.tester.pump_by(Duration::from_millis(75));
3808            assert_eq!(case.value(), 1.0);
3809
3810            case.dismiss_all_tool_tips();
3811            case.tester.pump();
3812            case.tester.pump_by(Duration::from_micros(37500));
3813
3814            // Halfway through the default 75ms hide duration.
3815            assert_more_or_less_equals(case.value(), 0.5);
3816            case.tester.pump_and_settle();
3817            expect(&case.tester, &case.tip(), finds_nothing());
3818        });
3819    }
3820
3821    #[test]
3822    fn hide_animation_defaults_to_75ms_even_when_animation_style_duration_is_set() {
3823        test_widgets(|tester| {
3824            let mut case = AnimationStyleCase::new(
3825                tester,
3826                style(
3827                    Curves::linear(),
3828                    Some(Duration::from_millis(400)),
3829                    None,
3830                    None,
3831                ),
3832            );
3833
3834            case.ensure_tooltip_visible();
3835            case.tester.pump_and_settle();
3836            assert_eq!(case.value(), 1.0);
3837
3838            case.dismiss_all_tool_tips();
3839            case.tester.pump();
3840            case.tester.pump_by(Duration::from_micros(37500));
3841            // Halfway through the default 75ms hide duration, not the 400ms duration.
3842            assert_more_or_less_equals(case.value(), 0.5);
3843            case.tester.pump_and_settle();
3844            expect(&case.tester, &case.tip(), finds_nothing());
3845        });
3846    }
3847
3848    #[test]
3849    fn animation_style_curve_changes_take_effect_after_the_first_show() {
3850        test_widgets(|tester| {
3851            let mut case =
3852                AnimationStyleCase::new(tester, style(Curves::linear(), MS_100, None, MS_100));
3853
3854            // Show once to instantiate the lazily-created animation objects.
3855            case.ensure_tooltip_visible();
3856            case.tester.pump_and_settle();
3857            case.dismiss_all_tool_tips();
3858            case.tester.pump_and_settle();
3859
3860            case.pump_widget(style(
3861                Curves::ease_in_expo(),
3862                MS_100,
3863                Some(Curves::bounce_out()),
3864                MS_100,
3865            ));
3866
3867            case.ensure_tooltip_visible();
3868            case.tester.pump();
3869            case.tester.pump_by(Duration::from_millis(50));
3870
3871            // Halfway through the show animation, the updated forward curve applies.
3872            assert_more_or_less_equals(case.value(), Curves::ease_in_expo().transform(0.5));
3873            case.tester.pump_and_settle();
3874
3875            case.dismiss_all_tool_tips();
3876            case.tester.pump();
3877            case.tester.pump_by(Duration::from_millis(50));
3878
3879            // Halfway through the hide animation, the updated reverse curve applies.
3880            assert_more_or_less_equals(case.value(), Curves::bounce_out().transform(0.5));
3881            case.tester.pump_and_settle();
3882            expect(&case.tester, &case.tip(), finds_nothing());
3883        });
3884    }
3885
3886    #[test]
3887    fn animation_style_changes_while_the_tooltip_is_shown_apply_to_the_next_animation() {
3888        test_widgets(|tester| {
3889            let mut case =
3890                AnimationStyleCase::new(tester, style(Curves::linear(), MS_100, None, MS_100));
3891
3892            case.ensure_tooltip_visible();
3893            case.tester.pump_and_settle();
3894            assert_eq!(case.value(), 1.0);
3895
3896            // Update the style while the tooltip is fully shown.
3897            case.pump_widget(style(
3898                Curves::linear(),
3899                MS_100,
3900                Some(Curves::ease_in_expo()),
3901                Some(Duration::from_millis(200)),
3902            ));
3903            expect(&case.tester, &case.tip(), finds_one_widget());
3904
3905            case.dismiss_all_tool_tips();
3906            case.tester.pump();
3907            case.tester.pump_by(Duration::from_millis(100));
3908
3909            // Halfway through the updated 200ms hide duration, following the updated
3910            // reverse curve.
3911            assert_more_or_less_equals(case.value(), Curves::ease_in_expo().transform(0.5));
3912            case.tester.pump_and_settle();
3913            expect(&case.tester, &case.tip(), finds_nothing());
3914        });
3915    }
3916
3917    #[test]
3918    fn changing_animation_style_while_the_tooltip_is_animating_in_does_not_crash() {
3919        test_widgets(|tester| {
3920            let mut case =
3921                AnimationStyleCase::new(tester, style(Curves::linear(), MS_100, None, MS_100));
3922
3923            case.ensure_tooltip_visible();
3924            case.tester.pump();
3925            case.tester.pump_by(Duration::from_millis(25));
3926
3927            // Update the style while the show animation is running.
3928            case.pump_widget(style(
3929                Curves::ease_in_expo(),
3930                Some(Duration::from_millis(300)),
3931                None,
3932                MS_100,
3933            ));
3934
3935            // The running show animation completes on its original 100ms timeline, of
3936            // which 25ms have already elapsed. Duration changes take effect the next
3937            // time an animation starts.
3938            case.tester.pump_by(Duration::from_millis(75));
3939            assert_eq!(case.value(), 1.0);
3940            expect(&case.tester, &case.tip(), finds_one_widget());
3941
3942            case.dismiss_all_tool_tips();
3943            case.tester.pump_and_settle();
3944            expect(&case.tester, &case.tip(), finds_nothing());
3945        });
3946    }
3947
3948    #[test]
3949    fn zero_show_duration_shows_instantly_and_hides_with_the_default_75ms() {
3950        test_widgets(|tester| {
3951            let mut case = AnimationStyleCase::new(
3952                tester,
3953                style(Curves::linear(), Some(Duration::ZERO), None, None),
3954            );
3955
3956            case.ensure_tooltip_visible();
3957            case.tester.pump();
3958            assert_eq!(case.value(), 1.0);
3959            expect(&case.tester, &case.tip(), finds_one_widget());
3960
3961            case.dismiss_all_tool_tips();
3962            case.tester.pump();
3963            case.tester.pump_by(Duration::from_micros(37500));
3964
3965            // The hide animation uses the default 75ms reverse duration.
3966            assert_more_or_less_equals(case.value(), 0.5);
3967            case.tester.pump_and_settle();
3968            expect(&case.tester, &case.tip(), finds_nothing());
3969        });
3970    }
3971}
3972
3973#[cfg(test)]
3974mod diagnostics_tests {
3975    use super::*;
3976    use crate::testing::describe_properties;
3977    use crate::widgets::basic::SizedBox;
3978
3979    fn tooltip() -> RawTooltip {
3980        RawTooltip::new(
3981            Some("message".to_string()),
3982            |_app, _context, _animation| SizedBox::shrink().into_widget(),
3983            SizedBox::shrink(),
3984        )
3985    }
3986
3987    /// `raw_tooltip_test.dart`, "default RawTooltip debugFillProperties".
3988    #[test]
3989    fn a_default_tooltip_describes_its_delays_and_trigger() {
3990        let cell = waft_foundation::AppCell::new();
3991        let app = cell.borrow();
3992        assert_eq!(
3993            describe_properties(|properties| tooltip().debug_fill_properties(&app, properties)),
3994            [
3995                "\"message\"",
3996                "hover delay: 0:00:00.000000",
3997                "touch delay: 0:00:01.500000",
3998                "dismiss delay: 0:00:00.100000",
3999                "triggerMode: TooltipTriggerMode.longPress",
4000                "enableFeedback: true",
4001            ]
4002        );
4003    }
4004
4005    /// `raw_tooltip_test.dart`, "RawTooltip implements debugFillProperties".
4006    #[test]
4007    fn a_tooltip_describes_the_values_it_is_given() {
4008        let tooltip = tooltip()
4009            .hover_delay(Duration::from_secs(1))
4010            .touch_delay(Duration::from_secs(2))
4011            .trigger_mode(TooltipTriggerMode::Manual);
4012        let cell = waft_foundation::AppCell::new();
4013        let app = cell.borrow();
4014        assert_eq!(
4015            describe_properties(|properties| tooltip.debug_fill_properties(&app, properties)),
4016            [
4017                "\"message\"",
4018                "hover delay: 0:00:01.000000",
4019                "touch delay: 0:00:02.000000",
4020                "dismiss delay: 0:00:00.100000",
4021                "triggerMode: TooltipTriggerMode.manual",
4022                "enableFeedback: true",
4023            ]
4024        );
4025    }
4026}