Skip to main content

waft_widgets/widgets/
magnifier.rs

1//! Flutter counterpart: `widgets/magnifier.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6
7use waft_animation::AnimationController;
8use waft_embedder::{
9    Clip, FilterQuality, ImageFilter, Matrix4, Offset, Path, PathBuilder, PathFillType, Rect, Size,
10    TextBaseline,
11};
12use waft_foundation::{App, Handle, Listener, OptionRetained, ValueNotifier};
13use waft_painting::{
14    Alignment, AlignmentGeometry, BoxShadow, RoundedRectangleBorder, ShapeBorderRef,
15    ShapeDecoration,
16};
17use waft_rendering::{
18    AnyRenderBox, AnyRenderObject, BackdropFilterLayer, BoxConstraints, BoxHitTestResult,
19    ContainerLayer, CustomClipper, PaintingContext, RenderBox, RenderBoxData, RenderHandle,
20    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
21    RenderProxyBoxMixin,
22};
23use waft_scheduler::TickerFuture;
24
25use crate::framework::{
26    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
27    StatelessWidget, WidgetRef,
28};
29use crate::widgets::basic::{ClipPath, IgnorePointer, Opacity, SizedBox, Stack, WidgetBuilder};
30use crate::widgets::container::DecoratedBox;
31use crate::widgets::inherited_theme::InheritedTheme;
32use crate::widgets::navigator::Navigator;
33use crate::widgets::overlay::{Overlay, OverlayEntry};
34use waft_foundation::Ref;
35
36/// Signature for a builder that builds a [`WidgetRef`] with a [`MagnifierController`].
37///
38/// The builder is called exactly once per magnifier.
39///
40/// If the `controller` parameter's [`MagnifierController::animation_controller`]
41/// field is set (by the builder) to an [`AnimationController`], the
42/// [`MagnifierController`] will drive the animation during entry and exit.
43///
44/// The `magnifier_info` parameter is updated with new [`MagnifierInfo`] instances
45/// during the lifetime of the built magnifier, e.g. as the user moves their
46/// finger around the text field.
47pub type MagnifierBuilder = Rc<
48    dyn Fn(
49        &mut App,
50        BuildContext,
51        Ref<MagnifierController>,
52        Ref<ValueNotifier<MagnifierInfo>>,
53    ) -> Option<WidgetRef>,
54>;
55
56/// A data class that contains the geometry information of text layouts
57/// and selection gestures, used to position magnifiers.
58#[derive(Clone, Copy, PartialEq)]
59pub struct MagnifierInfo {
60    /// The offset of the gesture position that the magnifier should be shown at.
61    pub global_gesture_position: Offset,
62    /// The rect of the current line the magnifier should be shown at, without
63    /// taking into account any padding of the field; only the position of the
64    /// first and last character.
65    pub current_line_boundaries: Rect,
66    /// The rect of the handle that the magnifier should follow.
67    pub caret_rect: Rect,
68    /// The bounds of the entire text field that the magnifier is bound to.
69    pub field_bounds: Rect,
70}
71
72impl MagnifierInfo {
73    /// Constructs a [`MagnifierInfo`] from provided geometry values.
74    pub const fn new(
75        global_gesture_position: Offset,
76        caret_rect: Rect,
77        field_bounds: Rect,
78        current_line_boundaries: Rect,
79    ) -> MagnifierInfo {
80        MagnifierInfo {
81            global_gesture_position,
82            caret_rect,
83            field_bounds,
84            current_line_boundaries,
85        }
86    }
87
88    /// Const [`MagnifierInfo`] with all values set to 0.
89    pub const EMPTY: MagnifierInfo = MagnifierInfo {
90        global_gesture_position: Offset::ZERO,
91        caret_rect: Rect::ZERO,
92        current_line_boundaries: Rect::ZERO,
93        field_bounds: Rect::ZERO,
94    };
95}
96
97impl Debug for MagnifierInfo {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(
100            f,
101            "MagnifierInfo(position: {:?}, line: {:?}, caret: {:?}, field: {:?})",
102            self.global_gesture_position,
103            self.current_line_boundaries,
104            self.caret_rect,
105            self.field_bounds
106        )
107    }
108}
109
110/// A configuration object for a magnifier (e.g. in a text field).
111///
112/// In general, most features of the magnifier can be configured by controlling
113/// the widgets built by the [`magnifier_builder`](Self::magnifier_builder).
114#[derive(Clone)]
115pub struct TextMagnifierConfiguration {
116    magnifier_builder: Option<MagnifierBuilder>,
117    /// Whether a magnifier should show the text editing handles or not.
118    ///
119    /// This flag is used by `SelectionOverlay.showMagnifier` to control the order
120    /// of layers in the rendering; specifically, whether to place the layer
121    /// containing the handles above or below the layer containing the magnifier
122    /// in the [`Overlay`].
123    pub should_display_handles_in_magnifier: bool,
124}
125
126impl TextMagnifierConfiguration {
127    /// Constructs a [`TextMagnifierConfiguration`] from parts.
128    ///
129    /// If [`magnifier_builder`](Self::magnifier_builder) is not set, a default
130    /// [`MagnifierBuilder`] will be used that does not build a magnifier.
131    pub const fn new() -> TextMagnifierConfiguration {
132        TextMagnifierConfiguration {
133            magnifier_builder: None,
134            should_display_handles_in_magnifier: true,
135        }
136    }
137
138    /// The builder callback that creates the widget that renders the magnifier.
139    pub fn magnifier_builder(&self) -> MagnifierBuilder {
140        self.magnifier_builder
141            .clone()
142            .unwrap_or_else(|| Rc::new(none))
143    }
144
145    /// Dart `TextMagnifierConfiguration(magnifierBuilder:)`.
146    pub fn with_magnifier_builder(
147        mut self,
148        magnifier_builder: MagnifierBuilder,
149    ) -> TextMagnifierConfiguration {
150        self.magnifier_builder = Some(magnifier_builder);
151        self
152    }
153
154    /// Dart `TextMagnifierConfiguration(shouldDisplayHandlesInMagnifier:)`.
155    pub fn should_display_handles_in_magnifier(
156        mut self,
157        should_display_handles_in_magnifier: bool,
158    ) -> TextMagnifierConfiguration {
159        self.should_display_handles_in_magnifier = should_display_handles_in_magnifier;
160        self
161    }
162
163    pub(crate) fn same_configuration(&self, other: &TextMagnifierConfiguration) -> bool {
164        self.should_display_handles_in_magnifier == other.should_display_handles_in_magnifier
165            && match (&self.magnifier_builder, &other.magnifier_builder) {
166                (None, None) => true,
167                (Some(a), Some(b)) => Rc::ptr_eq(a, b),
168                _ => false,
169            }
170    }
171
172    /// A constant for a [`TextMagnifierConfiguration`] that is disabled, meaning it
173    /// never builds anything, regardless of platform.
174    pub const DISABLED: TextMagnifierConfiguration = TextMagnifierConfiguration::new();
175}
176
177impl Default for TextMagnifierConfiguration {
178    fn default() -> TextMagnifierConfiguration {
179        TextMagnifierConfiguration::new()
180    }
181}
182
183fn none(
184    _app: &mut App,
185    _context: BuildContext,
186    _controller: Ref<MagnifierController>,
187    _magnifier_info: Ref<ValueNotifier<MagnifierInfo>>,
188) -> Option<WidgetRef> {
189    None
190}
191
192/// A controller for a magnifier.
193///
194/// [`MagnifierController`]'s main benefit over holding a raw [`OverlayEntry`] is that
195/// [`MagnifierController`] will handle logic around waiting for a magnifier to animate in or out.
196///
197/// If a magnifier chooses to have an entry / exit animation, it should provide the animation
198/// controller to [`MagnifierController::animation_controller`]. [`MagnifierController`] will then drive
199/// the [`AnimationController`] and wait for it to be complete before removing it from the
200/// [`Overlay`].
201///
202/// To check the status of the magnifier, see [`MagnifierController::shown`].
203pub struct MagnifierController {
204    /// The controller that will be driven in / out when show / hide is triggered,
205    /// respectively.
206    pub animation_controller: Option<Ref<AnimationController>>,
207    overlay_entry: Option<Ref<OverlayEntry>>,
208}
209
210impl MagnifierController {
211    /// If there is no in / out animation for the magnifier, [`animation_controller`](Self::animation_controller)
212    /// should be left unset.
213    pub fn new(app: &mut App) -> Ref<MagnifierController> {
214        app.create(MagnifierController {
215            animation_controller: None,
216            overlay_entry: None,
217        })
218    }
219
220    /// Dart `MagnifierController(animationController:)`.
221    pub fn animation_controller(
222        self: Ref<Self>,
223        app: &mut App,
224        animation_controller: Ref<AnimationController>,
225    ) -> Ref<Self> {
226        animation_controller.set_value(app, 0.0);
227        app.get_mut(&self).animation_controller = Some(animation_controller);
228        self
229    }
230
231    /// The magnifier's [`OverlayEntry`], if currently in the overlay.
232    ///
233    /// This is exposed so that other overlay entries can be positioned above or
234    /// below this [`overlay_entry`](Self::overlay_entry). Anything in the paint order after the
235    /// `RawMagnifier` in this [`OverlayEntry`] will not be displayed in the
236    /// magnifier; if it is desired for an overlay entry to be displayed in the
237    /// magnifier, it *must* be positioned below the magnifier.
238    ///
239    /// To check if a magnifier is in the overlay, use [`shown`](Self::shown). The
240    /// [`overlay_entry`](Self::overlay_entry) field may be non-null even when the magnifier is
241    /// not visible.
242    pub fn overlay_entry(self: Handle<Self>, app: &App) -> Option<Handle<OverlayEntry>> {
243        app.get(self).overlay_entry.handle()
244    }
245
246    /// Whether the magnifier is currently being shown.
247    ///
248    /// This is false when nothing is in the overlay, when the
249    /// [`animation_controller`](Self::animation_controller) is in the
250    /// [`waft_animation::AnimationStatus::Dismissed`] state, or when
251    /// the [`animation_controller`](Self::animation_controller) is animating out (i.e. in the
252    /// [`waft_animation::AnimationStatus::Reverse`] state).
253    ///
254    /// It is true in the opposite cases, i.e. when the overlay is not empty, and
255    /// either the [`animation_controller`](Self::animation_controller) is `None`, in the
256    /// [`waft_animation::AnimationStatus::Completed`] state, or in the
257    /// [`waft_animation::AnimationStatus::Forward`]
258    /// state.
259    pub fn shown(self: Handle<Self>, app: &App) -> bool {
260        app.get(self).overlay_entry.is_some()
261            && app
262                .get(self)
263                .animation_controller
264                .as_ref()
265                .is_none_or(|controller| controller.status(app).is_forward_or_completed())
266    }
267
268    /// Displays the magnifier.
269    ///
270    /// Returns a future that completes when the magnifier is fully shown, i.e. done
271    /// with its entry animation.
272    ///
273    /// To control what overlays are shown in the magnifier, use `below`. See
274    /// [`overlay_entry`](Self::overlay_entry) for more details on how to utilize `below`.
275    ///
276    /// If the magnifier already exists (i.e. [`overlay_entry`](Self::overlay_entry) is `Some`),
277    /// then [`show`](Self::show) will replace the old overlay without playing an exit
278    /// animation. Consider awaiting [`hide`](Self::hide) first, to animate from the old
279    /// magnifier to the new one.
280    pub fn show(
281        self: Handle<Self>,
282        app: &mut App,
283        context: BuildContext,
284        builder: WidgetBuilder,
285        below: Option<Handle<OverlayEntry>>,
286    ) -> TickerFuture {
287        if let Some(entry) = app.get(self).overlay_entry.handle() {
288            entry.remove(app);
289            entry.dispose(app);
290        }
291
292        let overlay_state = Overlay::of(app, context, true);
293
294        let to = Navigator::maybe_of(app, context, false).map(|navigator| navigator.context(app));
295        let captured_themes = <dyn InheritedTheme>::capture(app, context, to);
296
297        let overlay_entry = OverlayEntry::new(
298            app,
299            Rc::new(move |app: &mut App, context: BuildContext| {
300                captured_themes.wrap(builder(app, context))
301            }),
302            false,
303            false,
304            false,
305        );
306        app.get_mut(self).overlay_entry = Some(overlay_entry.clone());
307        overlay_state.insert(app, overlay_entry, below, None);
308
309        if let Some(controller) = app.get(self).animation_controller.handle() {
310            controller.forward(app, None)
311        } else {
312            TickerFuture::complete()
313        }
314    }
315
316    /// Schedules a hide of the magnifier.
317    ///
318    /// If this [`MagnifierController`] has an [`animation_controller`](Self::animation_controller),
319    /// then [`hide`](Self::hide) reverses the animation controller and waits
320    /// for the animation to complete. Then, if `remove_from_overlay`
321    /// is true, remove the magnifier from the overlay.
322    ///
323    /// In general, `remove_from_overlay` should be true, unless
324    /// the magnifier needs to preserve states between shows / hides.
325    ///
326    /// See also:
327    ///
328    ///  * [`remove_from_overlay`](Self::remove_from_overlay) which removes the [`OverlayEntry`] from the [`Overlay`]
329    ///    synchronously.
330    pub fn hide(self: Handle<Self>, app: &mut App, remove_from_overlay: bool) -> TickerFuture {
331        if app.get(self).overlay_entry.is_none() {
332            return TickerFuture::complete();
333        }
334
335        if let Some(controller) = app.get(self).animation_controller.handle() {
336            let future = controller.reverse(app, None);
337            if remove_from_overlay {
338                future.when_complete(
339                    app,
340                    Listener::handle_method(self, MagnifierController::remove_from_overlay),
341                );
342            }
343            return future;
344        }
345
346        if remove_from_overlay {
347            self.remove_from_overlay(app);
348        }
349        TickerFuture::complete()
350    }
351
352    /// Remove the [`OverlayEntry`] from the [`Overlay`].
353    ///
354    /// This method removes the [`OverlayEntry`] synchronously,
355    /// regardless of exit animation: this leads to abrupt removals
356    /// of [`OverlayEntry`]s with animations.
357    ///
358    /// To allow the [`OverlayEntry`] to play its exit animation, consider calling
359    /// [`hide`](Self::hide) instead, with `remove_from_overlay` set to true, and optionally await
360    /// the returned future.
361    pub fn remove_from_overlay(self: Handle<Self>, app: &mut App) {
362        if let Some(entry) = app.get(self).overlay_entry.handle() {
363            entry.remove(app);
364            entry.dispose(app);
365        }
366        app.get_mut(self).overlay_entry = None;
367    }
368
369    /// A utility for calculating a new [`Rect`] from `rect` such that
370    /// `rect` is fully constrained within `bounds`.
371    ///
372    /// Any point in the output rect is guaranteed to also be a point contained in `bounds`.
373    ///
374    /// It is a runtime error for `rect`.width to be greater than `bounds`.width,
375    /// and it is also an error for `rect`.height to be greater than `bounds`.height.
376    ///
377    /// This algorithm translates `rect` the shortest distance such that it is entirely within
378    /// `bounds`.
379    ///
380    /// If `rect` is already within `bounds`, no shift will be applied to `rect` and
381    /// `rect` will be returned as-is.
382    ///
383    /// It is perfectly valid for the output rect to have a point along the edge of the
384    /// `bounds`. If the desired output rect requires that no edges are parallel to edges
385    /// of `bounds`, see [`Rect::deflate`] by 1 on `bounds` to achieve this effect.
386    pub fn shift_within_bounds(rect: Rect, bounds: Rect) -> Rect {
387        debug_assert!(
388            rect.width() <= bounds.width(),
389            "attempted to shift {rect:?} within {bounds:?}, but the rect has a greater width.",
390        );
391        debug_assert!(
392            rect.height() <= bounds.height(),
393            "attempted to shift {rect:?} within {bounds:?}, but the rect has a greater height.",
394        );
395
396        let mut rect_shift = Offset::ZERO;
397        if rect.left < bounds.left {
398            rect_shift = rect_shift + Offset::new(bounds.left - rect.left, 0.0);
399        } else if rect.right > bounds.right {
400            rect_shift = rect_shift + Offset::new(bounds.right - rect.right, 0.0);
401        }
402
403        if rect.top < bounds.top {
404            rect_shift = rect_shift + Offset::new(0.0, bounds.top - rect.top);
405        } else if rect.bottom > bounds.bottom {
406            rect_shift = rect_shift + Offset::new(0.0, bounds.bottom - rect.bottom);
407        }
408
409        rect.shift(rect_shift)
410    }
411}
412
413/// The decorations to put around the loupe in a [`RawMagnifier`].
414///
415/// See also:
416///
417///  * `Decoration`, a more general solution for [`DecoratedBox`].
418#[derive(Clone, Debug)]
419pub struct MagnifierDecoration {
420    // TODO(ianh): deprecate [opacity] (moving it to [RawMagnifier]), and then
421    // once [opacity] can be removed, replace [MagnifierDecoration] with a
422    // `typedef` to [ShapeDecoration] and make anywhere that accepts a
423    // [MagnifierDecoration] accept a [ShapeDecoration] instead. This would allow
424    // magnifiers that don't offset the shadows to use the decoration to paint
425    // over the loupe rather than having to have a Stack of widgets to do so.
426    /// The opacity of the magnifier and decorations around the magnifier.
427    ///
428    /// When this is 1.0, the magnified image shows in the [`shape`](Self::shape) of the
429    /// magnifier. When this is less than 1.0, the magnified image is transparent
430    /// and shows through the unmagnified background.
431    ///
432    /// Generally this is only useful for animating the magnifier in and out, as a
433    /// transparent magnifier looks quite confusing.
434    pub opacity: f64,
435    /// A list of shadows cast by the [`shape`](Self::shape).
436    ///
437    /// If the shadows are offset, consider setting [`RawMagnifier::clip_behavior`] to
438    /// [`Clip::HardEdge`] (or similar) to ensure the shadow does not occlude the
439    /// magnifier (the shadow is drawn above the magnifier).
440    ///
441    /// If the shadows are _not_ offset, consider using `BlurStyle::Outer` in the
442    /// shadows instead, to avoid having to introduce a clip.
443    ///
444    /// In the event that [`shape`](Self::shape) consists of a stack of borders, the shadow
445    /// is drawn using the bounds of the last one.
446    ///
447    /// See also:
448    ///
449    ///  * `kElevationToShadow`, which defines some shadows for Material design.
450    ///    Those shadows use `BlurStyle::Normal` and may need to be converted to
451    ///    `BlurStyle::Outer` for use with [`MagnifierDecoration`].
452    pub shadows: Option<Vec<BoxShadow>>,
453    /// The shape of the magnifier and the outline (border) around it.
454    ///
455    /// Shapes can be stacked (using `plus`). In that case, the magnifier and shadow are
456    /// drawn according to the outside edge of the last shape, with the borders painted on
457    /// top.
458    pub shape: ShapeBorderRef,
459}
460
461impl MagnifierDecoration {
462    /// Constructs a [`MagnifierDecoration`].
463    ///
464    /// By default, [`MagnifierDecoration`] is a rectangular magnifier with no
465    /// shadows, and fully opaque.
466    pub fn new() -> MagnifierDecoration {
467        MagnifierDecoration::default()
468    }
469
470    /// Dart `MagnifierDecoration(opacity:)`.
471    pub fn opacity(mut self, opacity: f64) -> MagnifierDecoration {
472        self.opacity = opacity;
473        self
474    }
475
476    /// Dart `MagnifierDecoration(shadows:)`.
477    pub fn shadows(mut self, shadows: Vec<BoxShadow>) -> MagnifierDecoration {
478        self.shadows = Some(shadows);
479        self
480    }
481
482    /// Dart `MagnifierDecoration(shape:)`.
483    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> MagnifierDecoration {
484        self.shape = shape.into();
485        self
486    }
487}
488
489impl Default for MagnifierDecoration {
490    fn default() -> MagnifierDecoration {
491        MagnifierDecoration {
492            opacity: 1.0,
493            shadows: None,
494            shape: ShapeBorderRef::new(RoundedRectangleBorder::default()),
495        }
496    }
497}
498
499impl PartialEq for MagnifierDecoration {
500    fn eq(&self, other: &MagnifierDecoration) -> bool {
501        self.opacity == other.opacity && self.shadows == other.shadows && self.shape == other.shape
502    }
503}
504
505/// A common base class for magnifiers.
506///
507/// This magnifying glass is useful for scenarios on mobile devices where
508/// the user's finger may be covering part of the screen where a granular
509/// action is being performed, such as navigating a small cursor with a drag
510/// gesture, on an image or text.
511///
512/// A magnifier can be conveniently managed by [`MagnifierController`], which handles
513/// showing and hiding the magnifier, with an optional entry / exit animation.
514///
515/// See:
516/// * [`MagnifierController`], a controller to handle magnifiers in an overlay.
517#[derive(Debug)]
518pub struct RawMagnifier {
519    pub key: Option<KeyRef>,
520    /// An optional widget to position inside the len of the [`RawMagnifier`].
521    ///
522    /// This is positioned over the [`RawMagnifier`] - it may be useful for tinting the
523    /// [`RawMagnifier`], or drawing a crosshair-like UI.
524    pub child: Option<WidgetRef>,
525    /// This magnifier's decoration.
526    ///
527    /// This sets the shape of the loupe, plus any borders and shadows that it
528    /// casts. The default has no border and no shadow; combined with the default
529    /// [`magnification_scale`](Self::magnification_scale) of 1.0, this results in the
530    /// magnifier having no visible effect.
531    ///
532    /// If the [`decoration`](Self::decoration) has a [`MagnifierDecoration::shadows`] that
533    /// uses offset shadows or uses a `BlurStyle` that would obscure the magnified image,
534    /// consider setting [`clip_behavior`](Self::clip_behavior) to [`Clip::HardEdge`] (or
535    /// similar) to ensure the magnified image is visible.
536    pub decoration: MagnifierDecoration,
537    /// Whether and how to clip the parts of [`decoration`](Self::decoration) that render
538    /// inside the loupe.
539    ///
540    /// Defaults to [`Clip::None`].
541    ///
542    /// See the discussion at [`decoration`](Self::decoration).
543    pub clip_behavior: Clip,
544    /// The offset of the magnifier from [`RawMagnifier`]'s center.
545    ///
546    /// For example, if [`RawMagnifier`] is globally positioned at Offset(100, 100),
547    /// and [`focal_point_offset`](Self::focal_point_offset) is Offset(-20, -20), then
548    /// [`RawMagnifier`] will see the content at global offset (80, 80).
549    ///
550    /// If left as [`Offset::ZERO`], the [`RawMagnifier`] will show the content that
551    /// is directly below it.
552    pub focal_point_offset: Offset,
553    /// How "zoomed in" the magnification subject is in the lens.
554    ///
555    /// The default is 1.0, which is no magnification.
556    pub magnification_scale: f64,
557    /// The size of the magnifier.
558    ///
559    /// This does not include the border from the [`decoration`](Self::decoration); it only
560    /// includes the size of the magnifier.
561    pub size: Size,
562}
563
564impl RawMagnifier {
565    /// Constructs a [`RawMagnifier`].
566    ///
567    /// By default, this magnifier uses the default [`MagnifierDecoration`] (which
568    /// draws nothing), the focal point is directly under the magnifier, and there
569    /// is no magnification; this means that a default magnifier will be entirely
570    /// invisible to the naked eye, painting exactly what is under it, exactly
571    /// where it was painted originally.
572    pub fn new(size: Size) -> RawMagnifier {
573        RawMagnifier {
574            key: None,
575            child: None,
576            decoration: MagnifierDecoration::new(),
577            clip_behavior: Clip::None,
578            focal_point_offset: Offset::ZERO,
579            magnification_scale: 1.0,
580            size,
581        }
582    }
583
584    /// Dart `RawMagnifier(key:)`.
585    pub fn key(mut self, key: KeyRef) -> RawMagnifier {
586        self.key = Some(key);
587        self
588    }
589
590    /// Dart `RawMagnifier(child:)`.
591    #[cfg_attr(debug_assertions, track_caller)]
592    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RawMagnifier {
593        self.child = Some(child.into_widget());
594        self
595    }
596
597    /// Dart `RawMagnifier(decoration:)`.
598    pub fn decoration(mut self, decoration: MagnifierDecoration) -> RawMagnifier {
599        self.decoration = decoration;
600        self
601    }
602
603    /// Dart `RawMagnifier(clipBehavior:)`.
604    pub fn clip_behavior(mut self, clip_behavior: Clip) -> RawMagnifier {
605        self.clip_behavior = clip_behavior;
606        self
607    }
608
609    /// Dart `RawMagnifier(focalPointOffset:)`.
610    pub fn focal_point_offset(mut self, focal_point_offset: Offset) -> RawMagnifier {
611        self.focal_point_offset = focal_point_offset;
612        self
613    }
614
615    /// Dart `RawMagnifier(magnificationScale:)`.
616    pub fn magnification_scale(mut self, magnification_scale: f64) -> RawMagnifier {
617        debug_assert!(
618            magnification_scale != 0.0,
619            "Magnification scale of 0 results in undefined behavior."
620        );
621        self.magnification_scale = magnification_scale;
622        self
623    }
624}
625
626impl StatelessWidget for RawMagnifier {
627    fn key(&self) -> Option<&KeyRef> {
628        self.key.as_ref()
629    }
630
631    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
632        let mut lens = SizedBox::from_size(Some(self.size));
633        lens.child = self.child.clone();
634        let mut decoration = ShapeDecoration::new(self.decoration.shape.clone());
635        decoration.shadows = self.decoration.shadows.clone();
636        Stack::new()
637            .clip_behavior(Clip::None)
638            .alignment(AlignmentGeometry::CENTER)
639            .children([
640                // The magnified image is clipped to the outer path of the shape.
641                ClipPath::shape(self.decoration.shape.clone())
642                    .child(
643                        Opacity::new(self.decoration.opacity).child(
644                            Magnifier::new()
645                                .focal_point_offset(self.focal_point_offset)
646                                .magnification_scale(self.magnification_scale)
647                                .child(lens),
648                        ),
649                    )
650                    .into_widget(),
651                // Because `BackdropFilter` will filter any widgets before it, we apply
652                // these styles after (i.e. in a younger sibling) to avoid the magnifier
653                // from seeing its own styling.
654                IgnorePointer::new()
655                    .child(
656                        Opacity::new(self.decoration.opacity).child(
657                            ClipPath::new()
658                                .clip_behavior(self.clip_behavior)
659                                .clipper(Rc::new(NegativeClip::new(self.decoration.shape.clone())))
660                                .child(
661                                    DecoratedBox::new(decoration)
662                                        .child(SizedBox::from_size(Some(self.size))),
663                                ),
664                        ),
665                    )
666                    .into_widget(),
667            ])
668            .into_widget()
669    }
670}
671
672/// A clip that renders everything except the inside of a shape.
673struct NegativeClip {
674    shape: ShapeBorderRef,
675}
676
677impl NegativeClip {
678    fn new(shape: ShapeBorderRef) -> NegativeClip {
679        NegativeClip { shape }
680    }
681}
682
683impl CustomClipper<Path> for NegativeClip {
684    fn get_clip(&self, _app: &App, size: Size) -> Path {
685        let mut path = PathBuilder::new();
686        path.rect(Rect::LARGEST.into());
687        path.append(
688            self.shape
689                .get_inner_path(Offset::ZERO & size, None)
690                .as_valo(),
691            &Matrix4::IDENTITY,
692        );
693        let mut path = Path::new(path.build());
694        path.fill_type = PathFillType::EvenOdd;
695        path
696    }
697
698    fn should_reclip(&self, _app: &App, old_clipper: &dyn CustomClipper<Path>) -> bool {
699        let Some(old_clipper) = old_clipper.as_any().downcast_ref::<NegativeClip>() else {
700            return true;
701        };
702        old_clipper.shape != self.shape
703    }
704
705    fn as_any(&self) -> &dyn Any {
706        self
707    }
708}
709
710/// Dart's `_Magnifier`: the render object widget of the lens.
711#[derive(Debug)]
712struct Magnifier {
713    /// The Offset that the center of the [`Magnifier`] points to, relative
714    /// to the center of the magnifier.
715    focal_point_offset: Offset,
716    /// The enlarge multiplier of the magnification.
717    ///
718    /// If equal to 1.0, the content in the magnifier is true to its real size.
719    /// If greater than 1.0, the content appears bigger in the magnifier.
720    magnification_scale: f64,
721    child: Option<WidgetRef>,
722}
723
724impl Magnifier {
725    fn new() -> Magnifier {
726        Magnifier {
727            focal_point_offset: Offset::ZERO,
728            magnification_scale: 1.0,
729            child: None,
730        }
731    }
732
733    fn focal_point_offset(mut self, focal_point_offset: Offset) -> Magnifier {
734        self.focal_point_offset = focal_point_offset;
735        self
736    }
737
738    fn magnification_scale(mut self, magnification_scale: f64) -> Magnifier {
739        self.magnification_scale = magnification_scale;
740        self
741    }
742
743    #[cfg_attr(debug_assertions, track_caller)]
744    fn child<K>(mut self, child: impl IntoWidget<K>) -> Magnifier {
745        self.child = Some(child.into_widget());
746        self
747    }
748}
749
750impl RenderObjectWidget for Magnifier {
751    type RenderObject = RenderMagnification;
752
753    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
754        RenderMagnification::new(app, self.focal_point_offset, self.magnification_scale, None)
755            .as_object()
756    }
757
758    fn update_render_object(
759        &self,
760        app: &mut App,
761        _context: BuildContext,
762        render_object: RenderHandle<RenderMagnification>,
763    ) {
764        render_object.set_focal_point_offset(app, self.focal_point_offset);
765        render_object.set_magnification_scale(app, self.magnification_scale);
766    }
767}
768
769impl SingleChildRenderObjectWidget for Magnifier {
770    fn child(&self) -> Option<&WidgetRef> {
771        self.child.as_ref()
772    }
773}
774
775/// Dart's `_RenderMagnification`: a proxy box that shows, under its child, what was painted
776/// before it, moved and scaled by [`magnification_matrix`](Self::magnification_matrix).
777struct RenderMagnification {
778    render_object: RenderObjectData,
779    render_box: RenderBoxData,
780    child: RenderObjectWithChildData<AnyRenderBox>,
781    focal_point_offset: Offset,
782    magnification_scale: f64,
783}
784
785impl RenderMagnification {
786    fn new(
787        app: &mut App,
788        focal_point_offset: Offset,
789        magnification_scale: f64,
790        child: Option<AnyRenderBox>,
791    ) -> RenderHandle<RenderMagnification> {
792        let this = RenderHandle::new_box(
793            app,
794            RenderMagnification {
795                render_object: RenderObjectData::new(),
796                render_box: RenderBoxData::new(),
797                child: RenderObjectWithChildData::new(),
798                focal_point_offset,
799                magnification_scale,
800            },
801        );
802        this.set_child(app, child);
803        this
804    }
805
806    fn focal_point_offset(self: RenderHandle<Self>, app: &App) -> Offset {
807        self.get(app).focal_point_offset
808    }
809
810    fn set_focal_point_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
811        if self.focal_point_offset(app) == value {
812            return;
813        }
814        self.get_mut(app).focal_point_offset = value;
815        self.mark_needs_paint(app);
816    }
817
818    fn magnification_scale(self: RenderHandle<Self>, app: &App) -> f64 {
819        self.get(app).magnification_scale
820    }
821
822    fn set_magnification_scale(self: RenderHandle<Self>, app: &mut App, value: f64) {
823        if self.magnification_scale(app) == value {
824            return;
825        }
826        self.get_mut(app).magnification_scale = value;
827        self.mark_needs_paint(app);
828    }
829
830    /// The transform Dart's `paint` hands `ImageFilter.matrix` for the backdrop painted at
831    /// `offset`: a scale by [`magnification_scale`](Self::magnification_scale) about this
832    /// box's center, which brings the focal point under the center.
833    fn magnification_matrix(self: RenderHandle<Self>, app: &App, offset: Offset) -> Matrix4 {
834        let this_center = Alignment::CENTER.along_size(self.size(app)) + offset;
835        let magnification_scale = self.magnification_scale(app);
836        let focal_point_offset = self.focal_point_offset(app);
837        let scale = magnification_scale as f32;
838        Matrix4::translation(
839            (magnification_scale * (-focal_point_offset.dx() - this_center.dx()) + this_center.dx())
840                as f32,
841            (magnification_scale * (-focal_point_offset.dy() - this_center.dy()) + this_center.dy())
842                as f32,
843        )
844        .then(&Matrix4::from_flutter_array(&[
845            scale, 0.0, 0.0, 0.0, //
846            0.0, scale, 0.0, 0.0, //
847            0.0, 0.0, scale, 0.0, //
848            0.0, 0.0, 0.0, 1.0,
849        ]))
850    }
851}
852
853impl RenderObjectWithChildMixin for RenderMagnification {
854    type ChildType = AnyRenderBox;
855
856    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
857        &self.get(app).child
858    }
859
860    fn child_data_mut(
861        self: RenderHandle<Self>,
862        app: &mut App,
863    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
864        &mut self.get_mut(app).child
865    }
866}
867
868impl RenderProxyBoxMixin for RenderMagnification {}
869
870impl RenderObject for RenderMagnification {
871    waft_rendering::render_object_accessors!();
872
873    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
874        true
875    }
876
877    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
878        RenderProxyBoxMixin::perform_layout(self, app);
879    }
880
881    fn paint(
882        self: RenderHandle<Self>,
883        app: &mut App,
884        context: &mut PaintingContext,
885        offset: Offset,
886    ) {
887        let filter =
888            ImageFilter::matrix(self.magnification_matrix(app, offset), FilterQuality::High);
889
890        let layer = match self.as_object().layer_as::<BackdropFilterLayer>(app) {
891            Some(layer) => layer,
892            None => {
893                let layer = BackdropFilterLayer::new(app);
894                self.as_object()
895                    .set_layer(app, Some(layer.as_container_layer()));
896                layer
897            }
898        };
899        layer.set_filter(app, Some(filter));
900
901        context.push_layer(
902            app,
903            layer.as_container_layer(),
904            |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
905            offset,
906            None,
907        );
908    }
909
910    fn visit_children(
911        self: RenderHandle<Self>,
912        app: &App,
913        visitor: &mut dyn FnMut(AnyRenderObject),
914    ) {
915        if let Some(child) = self.child(app) {
916            visitor(child.as_object());
917        }
918    }
919}
920
921impl RenderBox for RenderMagnification {
922    waft_rendering::render_box_accessors!();
923
924    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
925        RenderProxyBoxMixin::setup_parent_data(self, app, child);
926    }
927
928    fn apply_paint_transform(
929        self: RenderHandle<Self>,
930        app: &App,
931        child: AnyRenderObject,
932        transform: &mut Matrix4,
933    ) {
934        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
935    }
936
937    fn hit_test_children(
938        self: RenderHandle<Self>,
939        app: &mut App,
940        result: &mut BoxHitTestResult<'_>,
941        position: Offset,
942    ) -> bool {
943        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
944    }
945
946    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
947        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
948    }
949
950    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
951        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
952    }
953
954    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
955        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
956    }
957
958    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
959        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
960    }
961
962    fn compute_distance_to_actual_baseline(
963        self: RenderHandle<Self>,
964        app: &mut App,
965        baseline: TextBaseline,
966    ) -> Option<f64> {
967        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
968    }
969
970    fn compute_dry_baseline(
971        self: RenderHandle<Self>,
972        app: &mut App,
973        constraints: BoxConstraints,
974        baseline: TextBaseline,
975    ) -> Option<f64> {
976        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
977    }
978
979    fn compute_dry_layout(
980        self: RenderHandle<Self>,
981        app: &mut App,
982        constraints: BoxConstraints,
983    ) -> Size {
984        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use std::time::Duration;
991
992    use waft_animation::{AnimationBehavior, AnimationStatus};
993    use waft_embedder::{BlurStyle, Color, Radius, TextDirection};
994    use waft_foundation::UniqueKey;
995    use waft_painting::{BorderRadius, BorderSide, BorderStyle, CircleBorder};
996    use waft_rendering::{
997        RenderClipPath, RenderCustomClip, RenderDecoratedBox, RenderOpacity, RenderStack,
998    };
999    use waft_scheduler::{FrameTarget, SchedulerBinding};
1000
1001    use super::*;
1002    use crate::binding::WidgetsBinding;
1003    use crate::framework::{AnyElement, GlobalKey};
1004    use crate::testing::{TestVSync, WidgetTester, test_widgets};
1005    use crate::widgets::basic::{Center, Directionality, Positioned};
1006    use crate::widgets::text::Text;
1007
1008    fn elements(app: &mut App) -> Vec<AnyElement> {
1009        fn visit(app: &App, element: AnyElement, found: &mut Vec<AnyElement>) {
1010            found.push(element);
1011            for child in element.children(app) {
1012                visit(app, child, found);
1013            }
1014        }
1015        let mut found = Vec::new();
1016        let root = WidgetsBinding::instance(app)
1017            .root_element(app)
1018            .expect("a mounted tree");
1019        visit(app, root, &mut found);
1020        found
1021    }
1022
1023    /// The render objects of the mounted tree that are an `R`, in tree order.
1024    fn render_objects<R: RenderObject>(app: &mut App) -> Vec<RenderHandle<R>> {
1025        fn visit<R: RenderObject>(
1026            app: &App,
1027            node: AnyRenderObject,
1028            found: &mut Vec<RenderHandle<R>>,
1029        ) {
1030            if let Some(handle) = node.downcast::<R>(app) {
1031                found.push(handle);
1032            }
1033            node.visit_children(app, &mut |child| visit(app, child, found));
1034        }
1035        let root = WidgetsBinding::instance(app)
1036            .root_element(app)
1037            .and_then(|root| root.find_render_object(app))
1038            .expect("a laid out tree");
1039        let mut found = Vec::new();
1040        visit(app, root, &mut found);
1041        found
1042    }
1043
1044    /// The render box of the first element whose widget `matches`.
1045    fn render_box_where(app: &mut App, matches: impl Fn(&WidgetRef) -> bool) -> AnyRenderBox {
1046        elements(app)
1047            .into_iter()
1048            .find(|element| matches(element.widget(app)))
1049            .and_then(|element| element.find_render_object(app))
1050            .and_then(|render_object| render_object.as_box())
1051            .expect("a mounted render box")
1052    }
1053
1054    fn has_key(widget: &WidgetRef, key: &KeyRef) -> bool {
1055        widget.key() == Some(key)
1056    }
1057
1058    /// Dart's `TestWidgetsApp(home: Placeholder())`: an overlay around a box whose context the
1059    /// magnifier is shown from.
1060    fn app_with_overlay(tester: &mut WidgetTester, home: GlobalKey) {
1061        tester.pump_widget(Directionality::new(
1062            TextDirection::Ltr,
1063            Overlay::wrap(SizedBox::new().key(home.into())),
1064        ));
1065    }
1066
1067    /// Dart's `WidgetsBinding.instance.scheduleFrame()`, then `tester.pump()`.
1068    fn schedule_frame_and_pump(tester: &mut WidgetTester) {
1069        tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
1070        tester.pump();
1071    }
1072
1073    fn raw_magnifier_builder(magnifier_key: KeyRef) -> WidgetBuilder {
1074        Rc::new(move |_app: &mut App, _context: BuildContext| {
1075            RawMagnifier::new(Size::new(100.0, 100.0))
1076                .key(magnifier_key.clone())
1077                .into_widget()
1078        })
1079    }
1080
1081    #[test]
1082    fn a_raw_magnifier_is_as_large_as_its_size() {
1083        test_widgets(|tester| {
1084            tester.pump_widget(
1085                Directionality::new(
1086                    TextDirection::Ltr,
1087                    Center::new().child(RawMagnifier::new(Size::new(100.0, 80.0))),
1088                )
1089                .into_widget(),
1090            );
1091            let mut app = tester.cell.borrow_mut();
1092            let magnifier =
1093                render_box_where(&mut app, |widget| widget.as_any().is::<RawMagnifier>());
1094            assert_eq!(magnifier.size(&app), Size::new(100.0, 80.0));
1095            let lens = render_objects::<RenderMagnification>(&mut app);
1096            assert_eq!(lens.len(), 1);
1097            assert_eq!(lens[0].size(&app), Size::new(100.0, 80.0));
1098        });
1099    }
1100
1101    #[test]
1102    fn a_raw_magnifier_does_not_crash_at_zero_area() {
1103        test_widgets(|tester| {
1104            tester.pump_widget(
1105                Directionality::new(
1106                    TextDirection::Ltr,
1107                    Center::new().child(
1108                        SizedBox::shrink()
1109                            .child(RawMagnifier::new(Size::square(2.0)).child(Text::new("X"))),
1110                    ),
1111                )
1112                .into_widget(),
1113            );
1114            let mut app = tester.cell.borrow_mut();
1115            let magnifier =
1116                render_box_where(&mut app, |widget| widget.as_any().is::<RawMagnifier>());
1117            assert_eq!(magnifier.size(&app), Size::ZERO);
1118        });
1119    }
1120
1121    #[test]
1122    fn the_lens_takes_the_focal_point_and_the_magnification_scale_of_the_magnifier() {
1123        test_widgets(|tester| {
1124            let magnifier = |focal_point_offset: Offset, magnification_scale: f64| {
1125                Directionality::new(
1126                    TextDirection::Ltr,
1127                    Center::new().child(
1128                        RawMagnifier::new(Size::new(100.0, 100.0))
1129                            .focal_point_offset(focal_point_offset)
1130                            .magnification_scale(magnification_scale),
1131                    ),
1132                )
1133                .into_widget()
1134            };
1135            tester.pump_widget(magnifier(Offset::new(50.0, 50.0), 2.0));
1136            let mut app = tester.cell.borrow_mut();
1137            let lens = render_objects::<RenderMagnification>(&mut app)[0];
1138            assert_eq!(lens.focal_point_offset(&app), Offset::new(50.0, 50.0));
1139            assert_eq!(lens.magnification_scale(&app), 2.0);
1140            assert!(lens.as_object().needs_compositing(&app));
1141
1142            drop(app);
1143            tester.pump_widget(magnifier(Offset::new(-20.0, 10.0), 3.0));
1144            let app = tester.cell.borrow();
1145            assert_eq!(lens.focal_point_offset(&app), Offset::new(-20.0, 10.0));
1146            assert_eq!(lens.magnification_scale(&app), 3.0);
1147        });
1148    }
1149
1150    #[test]
1151    fn the_magnification_matrix_scales_the_focal_point_into_the_center_of_the_lens() {
1152        test_widgets(|tester| {
1153            // Dart's 'should render with correct focal point and decoration' setup: a lens of
1154            // 100 x 100 at (200, 200) that looks 50 right and 50 down, at twice the size.
1155            tester.pump_widget(
1156                Directionality::new(
1157                    TextDirection::Ltr,
1158                    Center::new().child(
1159                        RawMagnifier::new(Size::new(100.0, 100.0))
1160                            .focal_point_offset(Offset::new(50.0, 50.0))
1161                            .magnification_scale(2.0),
1162                    ),
1163                )
1164                .into_widget(),
1165            );
1166            let mut app = tester.cell.borrow_mut();
1167            let lens = render_objects::<RenderMagnification>(&mut app)[0];
1168            let matrix = lens.magnification_matrix(&app, Offset::new(200.0, 200.0));
1169
1170            let center = waft_embedder::valo::Point::new(250.0, 250.0);
1171            let focal_point = waft_embedder::valo::Point::new(300.0, 300.0);
1172            assert_eq!(matrix.map_point(focal_point), center);
1173            let one_right_of_focal_point = waft_embedder::valo::Point::new(301.0, 300.0);
1174            assert_eq!(
1175                matrix.map_point(one_right_of_focal_point),
1176                waft_embedder::valo::Point::new(252.0, 250.0)
1177            );
1178            assert_eq!(
1179                matrix.to_flutter_array(),
1180                [
1181                    2.0, 0.0, 0.0, 0.0, //
1182                    0.0, 2.0, 0.0, 0.0, //
1183                    0.0, 0.0, 2.0, 0.0, //
1184                    -350.0, -350.0, 0.0, 1.0,
1185                ]
1186            );
1187        });
1188    }
1189
1190    #[test]
1191    fn the_lens_filters_the_backdrop_through_its_magnification_matrix() {
1192        test_widgets(|tester| {
1193            tester.pump_widget(
1194                Directionality::new(
1195                    TextDirection::Ltr,
1196                    Center::new().child(
1197                        RawMagnifier::new(Size::new(100.0, 100.0))
1198                            .focal_point_offset(Offset::new(50.0, 50.0))
1199                            .magnification_scale(2.0),
1200                    ),
1201                )
1202                .into_widget(),
1203            );
1204            let mut app = tester.cell.borrow_mut();
1205            let lens = render_objects::<RenderMagnification>(&mut app)[0];
1206            // The lens paints at the origin of the opacity layer `RawMagnifier` fades it in, as
1207            // `PaintingContext.pushOpacity` paints its child at `Offset.zero`.
1208            let offset = Offset::ZERO;
1209            let layer = lens
1210                .as_object()
1211                .layer_as::<BackdropFilterLayer>(&app)
1212                .expect("the lens pushes a backdrop filter layer");
1213            assert_eq!(
1214                layer.filter(&app),
1215                Some(&ImageFilter::matrix(
1216                    lens.magnification_matrix(&app, offset),
1217                    FilterQuality::High
1218                ))
1219            );
1220        });
1221    }
1222
1223    #[test]
1224    fn the_decoration_is_painted_over_the_lens_through_a_negative_clip() {
1225        test_widgets(|tester| {
1226            let shadow = BoxShadow::new(
1227                Color::new(0xFFFFFF00),
1228                Offset::new(5.0, 5.0),
1229                10.0,
1230                10.0,
1231                BlurStyle::Normal,
1232            );
1233            let shape = RoundedRectangleBorder::new(
1234                BorderSide::new(Color::new(0xFF000000), 2.0, BorderStyle::Solid, -1.0),
1235                BorderRadius::all(Radius::circular(10.0)).into(),
1236            );
1237            tester.pump_widget(
1238                Directionality::new(
1239                    TextDirection::Ltr,
1240                    Center::new().child(
1241                        RawMagnifier::new(Size::new(100.0, 100.0))
1242                            .clip_behavior(Clip::HardEdge)
1243                            .decoration(
1244                                MagnifierDecoration::new()
1245                                    .shadows(vec![shadow])
1246                                    .opacity(0.5)
1247                                    .shape(shape),
1248                            ),
1249                    ),
1250                )
1251                .into_widget(),
1252            );
1253            let mut app = tester.cell.borrow_mut();
1254
1255            let opacities = render_objects::<RenderOpacity>(&mut app);
1256            assert_eq!(opacities.len(), 2, "the lens and the decoration both fade");
1257            assert!(opacities.iter().all(|opacity| opacity.opacity(&app) == 0.5));
1258
1259            let decorated = render_objects::<RenderDecoratedBox>(&mut app);
1260            assert_eq!(decorated.len(), 1);
1261            let decoration = decorated[0]
1262                .decoration(&app)
1263                .as_any()
1264                .downcast_ref::<ShapeDecoration>()
1265                .expect("a ShapeDecoration");
1266            assert_eq!(decoration.shadows, Some(vec![shadow]));
1267            assert!(decoration.shape.eq_shape(&shape));
1268            assert_eq!(decorated[0].size(&app), Size::new(100.0, 100.0));
1269
1270            let clips = render_objects::<RenderClipPath>(&mut app);
1271            assert_eq!(clips.len(), 2);
1272            let (lens_clip, decoration_clip) = (clips[0], clips[1]);
1273            assert_eq!(lens_clip.clip_behavior(&app), Clip::AntiAlias);
1274            assert_eq!(decoration_clip.clip_behavior(&app), Clip::HardEdge);
1275            let negative = decoration_clip
1276                .clipper(&app)
1277                .expect("the negative clip")
1278                .get_clip(&app, Size::new(100.0, 100.0));
1279            assert!(negative.contains(Offset::new(-50.0, -50.0)));
1280            assert!(negative.contains(Offset::new(150.0, 50.0)));
1281            assert!(!negative.contains(Offset::new(50.0, 50.0)));
1282
1283            let stack = render_objects::<RenderStack>(&mut app);
1284            assert_eq!(stack[0].size(&app), Size::new(100.0, 100.0));
1285        });
1286    }
1287
1288    #[test]
1289    fn the_negative_clip_cuts_out_the_inside_of_a_shape() {
1290        let cell = waft_foundation::AppCell::new();
1291        let app = cell.borrow();
1292        let size = Size::new(100.0, 60.0);
1293        for shape in [
1294            ShapeBorderRef::new(RoundedRectangleBorder::default()),
1295            ShapeBorderRef::new(RoundedRectangleBorder::new(
1296                BorderSide::NONE,
1297                BorderRadius::all(Radius::elliptical(60.0, 50.0)).into(),
1298            )),
1299            ShapeBorderRef::new(CircleBorder::default()),
1300        ] {
1301            let clip = NegativeClip::new(shape.clone()).get_clip(&app, size);
1302            assert_eq!(clip.fill_type, PathFillType::EvenOdd);
1303            let hole = shape.get_inner_path(Offset::ZERO & size, None);
1304            for (x, y) in [(50.0, 30.0), (40.0, 25.0), (60.0, 35.0)] {
1305                let point = Offset::new(x, y);
1306                assert_eq!(
1307                    clip.contains(point),
1308                    !hole.contains(point),
1309                    "{shape:?} at {point:?}"
1310                );
1311            }
1312            for (x, y) in [(-1.0e6, -1.0e6), (1.0e6, 30.0), (50.0, 61.0)] {
1313                let point = Offset::new(x, y);
1314                assert!(clip.contains(point), "{shape:?} at {point:?}");
1315            }
1316        }
1317    }
1318
1319    #[test]
1320    fn the_negative_clip_reclips_only_for_another_shape() {
1321        let cell = waft_foundation::AppCell::new();
1322        let app = cell.borrow();
1323        let square = NegativeClip::new(ShapeBorderRef::new(RoundedRectangleBorder::default()));
1324        let same = NegativeClip::new(ShapeBorderRef::new(RoundedRectangleBorder::default()));
1325        let round = NegativeClip::new(ShapeBorderRef::new(CircleBorder::default()));
1326        assert!(!same.should_reclip(&app, &square));
1327        assert!(round.should_reclip(&app, &square));
1328    }
1329
1330    #[test]
1331    fn magnifier_decorations_with_the_same_fields_are_equal() {
1332        assert_eq!(MagnifierDecoration::new(), MagnifierDecoration::default());
1333        assert_eq!(MagnifierDecoration::new().opacity, 1.0);
1334        assert_eq!(MagnifierDecoration::new().shadows, None);
1335        assert_ne!(
1336            MagnifierDecoration::new(),
1337            MagnifierDecoration::new().opacity(0.5)
1338        );
1339        assert_ne!(
1340            MagnifierDecoration::new(),
1341            MagnifierDecoration::new().shape(CircleBorder::default())
1342        );
1343        assert_ne!(
1344            MagnifierDecoration::new(),
1345            MagnifierDecoration::new().shadows(Vec::new())
1346        );
1347    }
1348
1349    #[test]
1350    fn should_immediately_remove_from_overlay_on_no_animation_controller() {
1351        test_widgets(|tester| {
1352            let home = GlobalKey::new();
1353            app_with_overlay(tester, home.clone());
1354            let mut app = tester.cell.borrow_mut();
1355            let context = home.current_context(&app).expect("mounted");
1356            let magnifier_controller = MagnifierController::new(&mut app);
1357
1358            magnifier_controller.show(
1359                &mut app,
1360                context,
1361                raw_magnifier_builder(UniqueKey::new().into()),
1362                None,
1363            );
1364            drop(app);
1365            schedule_frame_and_pump(tester);
1366            let mut app = tester.cell.borrow_mut();
1367            assert!(magnifier_controller.overlay_entry(&app).is_some());
1368
1369            magnifier_controller.hide(&mut app, true);
1370            drop(app);
1371            schedule_frame_and_pump(tester);
1372            let app = tester.cell.borrow();
1373            assert!(magnifier_controller.overlay_entry(&app).is_none());
1374        });
1375    }
1376
1377    #[test]
1378    fn should_update_shown_based_on_animation_status() {
1379        test_widgets(|tester| {
1380            let home = GlobalKey::new();
1381            app_with_overlay(tester, home.clone());
1382            let mut app = tester.cell.borrow_mut();
1383            let context = home.current_context(&app).expect("mounted");
1384            let duration = Duration::from_secs(120);
1385            let animation_controller = AnimationController::new(
1386                &mut app,
1387                None,
1388                Some(duration),
1389                None,
1390                0.0,
1391                1.0,
1392                AnimationBehavior::Normal,
1393                TestVSync,
1394            );
1395            let magnifier_controller = MagnifierController::new(&mut app)
1396                .animation_controller(&mut app, animation_controller.clone());
1397
1398            magnifier_controller.show(
1399                &mut app,
1400                context,
1401                raw_magnifier_builder(UniqueKey::new().into()),
1402                None,
1403            );
1404            drop(app);
1405            schedule_frame_and_pump(tester);
1406            let app = tester.cell.borrow();
1407
1408            // No time has passed, so the animation controller has not completed.
1409            assert_eq!(animation_controller.status(&app), AnimationStatus::Forward);
1410            assert!(magnifier_controller.shown(&app));
1411
1412            // Dart's `async.elapse(duration)` moves the case's own `FakeAsync`, which no frame
1413            // reads; the frames `pumpAndSettle` runs drive the controller.
1414            drop(app);
1415            tester.pump_and_settle();
1416            let mut app = tester.cell.borrow_mut();
1417            assert_eq!(
1418                animation_controller.status(&app),
1419                AnimationStatus::Completed
1420            );
1421            assert!(magnifier_controller.shown(&app));
1422
1423            magnifier_controller.hide(&mut app, true);
1424            drop(app);
1425            schedule_frame_and_pump(tester);
1426            let app = tester.cell.borrow();
1427            assert_eq!(animation_controller.status(&app), AnimationStatus::Reverse);
1428            assert!(!magnifier_controller.shown(&app));
1429
1430            drop(app);
1431            tester.pump_and_settle();
1432            let app = tester.cell.borrow();
1433            assert_eq!(
1434                animation_controller.status(&app),
1435                AnimationStatus::Dismissed
1436            );
1437            assert!(!magnifier_controller.shown(&app));
1438        });
1439    }
1440
1441    #[test]
1442    fn should_insert_below_below_widget() {
1443        test_widgets(|tester| {
1444            let home = GlobalKey::new();
1445            app_with_overlay(tester, home.clone());
1446            let mut app = tester.cell.borrow_mut();
1447            let context = home.current_context(&app).expect("mounted");
1448            let magnifier_controller = MagnifierController::new(&mut app);
1449            let fake_magnifier: KeyRef = UniqueKey::new().into();
1450            let fake_before: KeyRef = UniqueKey::new().into();
1451
1452            let before_key = fake_before.clone();
1453            let fake_before_overlay_entry = OverlayEntry::new(
1454                &mut app,
1455                Rc::new(move |_app: &mut App, _context: BuildContext| {
1456                    SizedBox::new().key(before_key.clone()).into_widget()
1457                }),
1458                false,
1459                false,
1460                false,
1461            );
1462            Overlay::of(&mut app, context, false).insert(
1463                &mut app,
1464                fake_before_overlay_entry.clone(),
1465                None,
1466                None,
1467            );
1468            let magnifier_key = fake_magnifier.clone();
1469            magnifier_controller.show(
1470                &mut app,
1471                context,
1472                Rc::new(move |_app: &mut App, _context: BuildContext| {
1473                    SizedBox::new().key(magnifier_key.clone()).into_widget()
1474                }),
1475                Some(fake_before_overlay_entry.handle()),
1476            );
1477            SchedulerBinding::schedule_frame(&mut app, FrameTarget::EveryView);
1478            drop(app);
1479            tester.pump_and_settle();
1480            let mut app = tester.cell.borrow_mut();
1481
1482            let keyed: Vec<KeyRef> = elements(&mut app)
1483                .into_iter()
1484                .filter_map(|element| element.widget(&app).key().cloned())
1485                .filter(|key| key == &fake_magnifier || key == &fake_before)
1486                .collect();
1487            // Expect the magnifier to be the first child, even though it was inserted
1488            // after the fakeBefore.
1489            assert_eq!(keyed, vec![fake_magnifier, fake_before]);
1490
1491            magnifier_controller.remove_from_overlay(&mut app);
1492            fake_before_overlay_entry.remove(&mut app);
1493            fake_before_overlay_entry.dispose(&mut app);
1494        });
1495    }
1496
1497    #[test]
1498    fn should_insert_newly_built_widget_without_animating_out_if_overlay_is_not_none() {
1499        test_widgets(|tester| {
1500            let home = GlobalKey::new();
1501            app_with_overlay(tester, home.clone());
1502            let mut app = tester.cell.borrow_mut();
1503            let context = home.current_context(&app).expect("mounted");
1504            let magnifier_controller = MagnifierController::new(&mut app);
1505            let first: KeyRef = UniqueKey::new().into();
1506            let second: KeyRef = UniqueKey::new().into();
1507
1508            magnifier_controller.show(
1509                &mut app,
1510                context,
1511                raw_magnifier_builder(first.clone()),
1512                None,
1513            );
1514            drop(app);
1515            schedule_frame_and_pump(tester);
1516            let app = tester.cell.borrow();
1517            drop(app);
1518            tester.pump_and_settle();
1519            let mut app = tester.cell.borrow_mut();
1520
1521            magnifier_controller.show(
1522                &mut app,
1523                context,
1524                raw_magnifier_builder(second.clone()),
1525                None,
1526            );
1527            drop(app);
1528            schedule_frame_and_pump(tester);
1529            let mut app = tester.cell.borrow_mut();
1530
1531            let count = |app: &mut App, key: &KeyRef| {
1532                elements(app)
1533                    .into_iter()
1534                    .filter(|element| has_key(element.widget(app), key))
1535                    .count()
1536            };
1537            assert_eq!(count(&mut app, &second), 1);
1538            assert_eq!(count(&mut app, &first), 0);
1539            magnifier_controller.remove_from_overlay(&mut app);
1540        });
1541    }
1542
1543    #[test]
1544    fn shift_within_bounds_moves_a_rect_the_shortest_way_into_the_bounds() {
1545        let bounds = Rect::from_ltrb(0.0, 0.0, 100.0, 100.0);
1546        for (input, output) in [
1547            (
1548                Rect::from_ltrb(-100.0, -100.0, -80.0, -80.0),
1549                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
1550            ),
1551            (
1552                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
1553                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
1554            ),
1555            (
1556                Rect::from_ltrb(110.0, 0.0, 120.0, 10.0),
1557                Rect::from_ltrb(90.0, 0.0, 100.0, 10.0),
1558            ),
1559            (
1560                Rect::from_ltrb(110.0, 110.0, 120.0, 120.0),
1561                Rect::from_ltrb(90.0, 90.0, 100.0, 100.0),
1562            ),
1563        ] {
1564            assert_eq!(
1565                MagnifierController::shift_within_bounds(input, bounds),
1566                output,
1567                "should shift {input:?} to {output:?} for bounds {bounds:?}"
1568            );
1569        }
1570    }
1571
1572    #[test]
1573    fn raw_magnifier_sits_where_it_is_positioned() {
1574        test_widgets(|tester| {
1575            let key: KeyRef = UniqueKey::new().into();
1576            tester.pump_widget(
1577                Directionality::new(
1578                    TextDirection::Ltr,
1579                    Stack::new().children([Positioned::new(
1580                        RawMagnifier::new(Size::new(40.0, 40.0)).key(key.clone()),
1581                    )
1582                    .left(20.0)
1583                    .top(30.0)
1584                    .into_widget()]),
1585                )
1586                .into_widget(),
1587            );
1588            let mut app = tester.cell.borrow_mut();
1589            let magnifier = render_box_where(&mut app, |widget| has_key(widget, &key));
1590            assert_eq!(
1591                magnifier.local_to_global(&app, Offset::ZERO, None),
1592                Offset::new(20.0, 30.0)
1593            );
1594        });
1595    }
1596}