Skip to main content

waft_material/
magnifier.rs

1//! Flutter counterpart: `material/magnifier.dart`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use waft_embedder::{BlurStyle, Clip, Color, Offset, Radius, Size, TargetPlatform, clamp_double};
7use waft_foundation::{
8    App, Handle, Listenable, Listener, Ref, Timer, ValueListenable, ValueNotifier,
9};
10use waft_painting::{BorderRadius, BorderSide, BoxShadow, RoundedRectangleBorder};
11use waft_widgets::{
12    AnimatedPositioned, BuildContext, ColoredBox, IntoWidget, KeyRef, MagnifierBuilder,
13    MagnifierController, MagnifierDecoration, MagnifierInfo, MediaQuery, RawMagnifier, State,
14    StateData, StatefulWidget, StatelessWidget, TextMagnifierConfiguration, WidgetRef,
15};
16
17use waft_cupertino::CupertinoTextMagnifier;
18
19/// A [`Magnifier`] positioned by rules dictated by the native Android magnifier.
20///
21/// The positioning rules are based on [`magnifier_info`](Self::magnifier_info), as follows:
22///
23/// - The loupe tracks the gesture's _x_ coordinate, clamping to the beginning
24///   and end of the currently editing line.
25///
26/// - The focal point never contains anything out of the bounds of the text
27///   field or other widget being magnified (the [`MagnifierInfo::field_bounds`]).
28///
29/// - The focal point always remains aligned with the _y_ coordinate of the touch.
30///
31/// - The loupe always remains on the screen.
32///
33/// - When the line targeted by the touch's _y_ coordinate changes, the position
34///   is animated over [`JUMP_BETWEEN_LINES_ANIMATION_DURATION`](Self::JUMP_BETWEEN_LINES_ANIMATION_DURATION).
35///
36/// This behavior was based on the Android 12 source code, where possible, and
37/// on eyeballing a Pixel 6 running Android 12 otherwise.
38#[derive(Debug)]
39pub struct TextMagnifier {
40    pub key: Option<KeyRef>,
41    /// The current status of the user's touch.
42    ///
43    /// As the value of the [`magnifier_info`](Self::magnifier_info) changes, the position of the
44    /// loupe is adjusted automatically, according to the rules described in the
45    /// [`TextMagnifier`] class description.
46    pub magnifier_info: Ref<ValueNotifier<MagnifierInfo>>,
47}
48
49impl TextMagnifier {
50    /// Creates a [`TextMagnifier`].
51    ///
52    /// The `magnifier_info` must be provided, and must be updated with new values
53    /// as the user's touch changes.
54    pub fn new(magnifier_info: Ref<ValueNotifier<MagnifierInfo>>) -> TextMagnifier {
55        TextMagnifier {
56            key: None,
57            magnifier_info,
58        }
59    }
60
61    /// Dart `TextMagnifier(key:)`.
62    pub fn key(mut self, key: KeyRef) -> TextMagnifier {
63        self.key = Some(key);
64        self
65    }
66
67    /// Dart's `adaptiveMagnifierConfiguration`: a [`TextMagnifierConfiguration`] that returns a
68    /// [`CupertinoTextMagnifier`] on iOS, [`TextMagnifier`] on Android, and `None` on all other
69    /// platforms, and shows the editing handles only on iOS.
70    ///
71    /// Every call returns a configuration with the same builder, so two of them are the same
72    /// configuration to a widget that compares them.
73    pub fn adaptive_magnifier_configuration(app: &App) -> TextMagnifierConfiguration {
74        thread_local! {
75            static MAGNIFIER_BUILDER: MagnifierBuilder = Rc::new(
76                |app: &mut App,
77                 _context: BuildContext,
78                 controller: Ref<MagnifierController>,
79                 magnifier_info: Ref<ValueNotifier<MagnifierInfo>>| {
80                    match app.platform().target_platform() {
81                        TargetPlatform::IOS => Some(
82                            CupertinoTextMagnifier::new(controller, magnifier_info).into_widget(),
83                        ),
84                        TargetPlatform::Android => {
85                            Some(TextMagnifier::new(magnifier_info).into_widget())
86                        }
87                        TargetPlatform::Fuchsia
88                        | TargetPlatform::Linux
89                        | TargetPlatform::MacOS
90                        | TargetPlatform::Windows => None,
91                    }
92                },
93            );
94        }
95        TextMagnifierConfiguration::new()
96            .should_display_handles_in_magnifier(
97                app.platform().target_platform() == TargetPlatform::IOS,
98            )
99            .with_magnifier_builder(MAGNIFIER_BUILDER.with(MagnifierBuilder::clone))
100    }
101
102    /// The duration that the position is animated if [`TextMagnifier`] just switched
103    /// between lines.
104    pub const JUMP_BETWEEN_LINES_ANIMATION_DURATION: Duration = Duration::from_millis(70);
105}
106
107impl StatefulWidget for TextMagnifier {
108    type State = TextMagnifierState;
109
110    fn key(&self) -> Option<&KeyRef> {
111        self.key.as_ref()
112    }
113
114    fn create_state(&self) -> TextMagnifierState {
115        TextMagnifierState {
116            state: StateData::new(),
117            magnifier_position: None,
118            position_should_be_animated_timer: None,
119            extra_focal_point_offset: Offset::ZERO,
120        }
121    }
122}
123
124/// Dart's `_TextMagnifierState`.
125pub struct TextMagnifierState {
126    state: StateData<TextMagnifier>,
127    // Should _only_ be null on construction. This is because of the animation logic.
128    //
129    // Animations are added when `last_build_y != current_build_y`. This condition
130    // is true on the initial render, which would mean that the initial
131    // build would be animated - this is undesired. Thus, this is null for the
132    // first frame and the condition becomes `magnifier_position != null && last_build_y != this_build_y`.
133    magnifier_position: Option<Offset>,
134    // A timer that unsets itself after an animation duration.
135    // If the timer exists, then the magnifier animates its position -
136    // if this timer does not exist, the magnifier tracks the gesture (with respect
137    // to the positioning rules) directly.
138    position_should_be_animated_timer: Option<Timer>,
139    extra_focal_point_offset: Offset,
140}
141
142impl TextMagnifierState {
143    fn position_should_be_animated(self: Handle<Self>, app: &App) -> bool {
144        app.get(self).position_should_be_animated_timer.is_some()
145    }
146
147    fn determine_magnifier_position_and_focal_point(self: Handle<Self>, app: &mut App) {
148        let magnifier_info = self.widget(app).magnifier_info.clone();
149        let selection_info = *magnifier_info.value(app);
150        let context = self.context(app);
151        let screen_rect = Offset::ZERO & MediaQuery::size_of(app, context);
152
153        // Since by default we draw at the top left corner, this offset
154        // shifts the magnifier so we draw at the center, and then also includes
155        // the "above touch point" shift.
156        let basic_magnifier_offset = Offset::new(
157            Magnifier::K_DEFAULT_MAGNIFIER_SIZE.width() / 2.0,
158            Magnifier::K_DEFAULT_MAGNIFIER_SIZE.height()
159                + Magnifier::K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT,
160        );
161
162        // Since the magnifier should not go past the edges of the line,
163        // but must track the gesture otherwise, constrain the X of the magnifier
164        // to always stay between line start and end.
165        let magnifier_x = clamp_double(
166            selection_info.global_gesture_position.dx(),
167            selection_info.current_line_boundaries.left,
168            selection_info.current_line_boundaries.right,
169        );
170
171        // Place the magnifier at the previously calculated X, and the Y should be
172        // exactly at the center of the handle.
173        let unadjusted_magnifier_rect =
174            (Offset::new(magnifier_x, selection_info.caret_rect.center().dy())
175                - basic_magnifier_offset)
176                & Magnifier::K_DEFAULT_MAGNIFIER_SIZE;
177
178        // Shift the magnifier so that, if we are ever out of the screen, we become in bounds.
179        // This probably won't have much of an effect on the X, since it is already bound
180        // to the currentLineBoundaries, but will shift vertically if the magnifier is out of bounds.
181        let screen_bounds_adjusted_magnifier_rect =
182            MagnifierController::shift_within_bounds(unadjusted_magnifier_rect, screen_rect);
183
184        // Done with the magnifier position!
185        let final_magnifier_position = screen_bounds_adjusted_magnifier_rect.top_left();
186
187        // The insets, from either edge, that the focal point should not point
188        // past lest the magnifier displays something out of bounds.
189        let horizontal_max_focal_point_edge_insets =
190            (Magnifier::K_DEFAULT_MAGNIFIER_SIZE.width() / 2.0) / Magnifier::MAGNIFICATION;
191
192        // Adjust the focal point horizontally such that none of the magnifier
193        // ever points to anything out of bounds.
194        // If the text field is so narrow that we must show out of bounds,
195        // then settle for pointing to the center all the time.
196        let new_global_focal_point_x =
197            if selection_info.field_bounds.width() < horizontal_max_focal_point_edge_insets * 2.0 {
198                selection_info.field_bounds.center().dx()
199            } else {
200                // Otherwise, we can clamp the focal point to always point in bounds.
201                clamp_double(
202                    screen_bounds_adjusted_magnifier_rect.center().dx(),
203                    selection_info.field_bounds.left + horizontal_max_focal_point_edge_insets,
204                    selection_info.field_bounds.right - horizontal_max_focal_point_edge_insets,
205                )
206            };
207
208        // Since the previous value is now a global offset (i.e. `new_global_focal_point`
209        // is now a global offset), we must subtract the magnifier's global offset
210        // to obtain the relative shift in the focal point.
211        let new_relative_focal_point_x =
212            new_global_focal_point_x - screen_bounds_adjusted_magnifier_rect.center().dx();
213
214        // The Y component means that if we are pressed up against the top of the screen,
215        // then we should adjust the focal point such that it now points to how far we moved
216        // the magnifier. screen_bounds_adjusted_magnifier_rect.top == unadjusted_magnifier_rect.top for most cases,
217        // but when pressed up against the top of the screen, we adjust the focal point by
218        // the amount that we shifted from our "natural" position.
219        let focal_point_adjustment_for_screen_bounds_adjustment = Offset::new(
220            new_relative_focal_point_x,
221            unadjusted_magnifier_rect.top - screen_bounds_adjusted_magnifier_rect.top,
222        );
223
224        let mut position_should_be_animated = app.get(self).position_should_be_animated_timer;
225
226        if let Some(magnifier_position) = app.get(self).magnifier_position
227            && final_magnifier_position.dy() != magnifier_position.dy()
228        {
229            if let Some(timer) = position_should_be_animated
230                && timer.is_active(app)
231            {
232                timer.cancel(app);
233            }
234
235            // Create a timer that deletes itself when the timer is complete.
236            // This is `mounted` safe, since the timer is canceled in `dispose`.
237            position_should_be_animated = Some(Timer::new(
238                app,
239                TextMagnifier::JUMP_BETWEEN_LINES_ANIMATION_DURATION,
240                Listener::new(move |app| {
241                    self.set_state(app, |state| {
242                        state.position_should_be_animated_timer = None;
243                    });
244                }),
245            ));
246        }
247
248        self.set_state(app, |state| {
249            state.magnifier_position = Some(final_magnifier_position);
250            state.position_should_be_animated_timer = position_should_be_animated;
251            state.extra_focal_point_offset = focal_point_adjustment_for_screen_bounds_adjustment;
252        });
253    }
254}
255
256impl State for TextMagnifierState {
257    type Widget = TextMagnifier;
258    waft_widgets::state_accessors!();
259
260    fn init_state(self: Handle<Self>, app: &mut App) {
261        let magnifier_info = self.widget(app).magnifier_info.clone();
262        magnifier_info.add_listener(
263            app,
264            Listener::handle_method(self, Self::determine_magnifier_position_and_focal_point),
265        );
266    }
267
268    fn dispose(self: Handle<Self>, app: &mut App) {
269        let magnifier_info = self.widget(app).magnifier_info.clone();
270        magnifier_info.remove_listener(
271            app,
272            &Listener::handle_method(self, Self::determine_magnifier_position_and_focal_point),
273        );
274        if let Some(timer) = app.get(self).position_should_be_animated_timer {
275            timer.cancel(app);
276        }
277    }
278
279    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
280        self.determine_magnifier_position_and_focal_point(app);
281    }
282
283    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TextMagnifier) {
284        let magnifier_info = self.widget(app).magnifier_info.clone();
285        if old_widget.magnifier_info != magnifier_info {
286            old_widget.magnifier_info.remove_listener(
287                app,
288                &Listener::handle_method(self, Self::determine_magnifier_position_and_focal_point),
289            );
290            magnifier_info.add_listener(
291                app,
292                Listener::handle_method(self, Self::determine_magnifier_position_and_focal_point),
293            );
294        }
295    }
296
297    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
298        let magnifier_position = app.get(self).magnifier_position;
299        debug_assert!(
300            magnifier_position.is_some(),
301            "Magnifier position should only be null before the first build."
302        );
303        let magnifier_position = magnifier_position.expect("set in did_change_dependencies");
304        let extra_focal_point_offset = app.get(self).extra_focal_point_offset;
305        let duration = if self.position_should_be_animated(app) {
306            TextMagnifier::JUMP_BETWEEN_LINES_ANIMATION_DURATION
307        } else {
308            Duration::ZERO
309        };
310
311        AnimatedPositioned::new(
312            Magnifier::new().additional_focal_point_offset(extra_focal_point_offset),
313            // Material magnifier typically does not animate, unless we jump between lines,
314            // in which case we animate between lines.
315            duration,
316        )
317        .top(magnifier_position.dy())
318        .left(magnifier_position.dx())
319        .into_widget()
320    }
321}
322
323/// A Material-styled magnifying glass.
324///
325/// This widget focuses on mimicking the _style_ of the magnifier on material.
326/// For a widget that is focused on mimicking the _behavior_ of a material
327/// magnifier, see [`TextMagnifier`], which uses [`Magnifier`].
328///
329/// The styles implemented in this widget were based on the Android 12 source
330/// code, where possible, and on eyeballing a Pixel 6 running Android 12
331/// otherwise.
332#[derive(Debug)]
333pub struct Magnifier {
334    pub key: Option<KeyRef>,
335    /// Any additional offset the focal point requires to "point"
336    /// to the correct place.
337    ///
338    /// This value is added to [`K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT`](Self::K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT)
339    /// to obtain the actual offset.
340    ///
341    /// This is useful for instances where the magnifier is not pointing to
342    /// something directly below it.
343    pub additional_focal_point_offset: Offset,
344    /// The border radius for this magnifier.
345    ///
346    /// The magnifier's shape is a [`RoundedRectangleBorder`] with this radius.
347    pub border_radius: BorderRadius,
348    /// The color to tint the image in this [`Magnifier`].
349    ///
350    /// On native Android, there is a almost transparent gray tint to the
351    /// magnifier, in order to better distinguish the contents of the lens from
352    /// the background.
353    pub film_color: Color,
354    /// A list of shadows cast by the [`Magnifier`].
355    ///
356    /// If the shadows use a [`BlurStyle`] that paints inside the shape, or if they
357    /// are offset, then a [`clip_behavior`](Self::clip_behavior) that enables clipping (such as the
358    /// default [`Clip::HardEdge`]) is recommended, otherwise the shadow will occlude
359    /// the magnifier (the shadow is drawn above the magnifier so as to not be
360    /// included in the magnified image).
361    ///
362    /// By default, the shadows are offset vertically by two logical pixels, so
363    /// clipping is recommended.
364    ///
365    /// A shadow that uses [`BlurStyle::Outer`] and is not offset does not need
366    /// clipping; in that case, consider setting [`clip_behavior`](Self::clip_behavior) to [`Clip::None`].
367    pub shadows: Vec<BoxShadow>,
368    /// Whether and how to clip the [`shadows`](Self::shadows) that render inside the loupe.
369    ///
370    /// Defaults to [`Clip::HardEdge`].
371    ///
372    /// A value of [`Clip::None`] can be used if the shadow will not paint where the
373    /// magnified image appears, or if doing so is intentional (e.g. to blur the
374    /// edges of the magnified image).
375    ///
376    /// See the discussion at [`shadows`](Self::shadows).
377    pub clip_behavior: Clip,
378    /// The [`Size`] of this [`Magnifier`].
379    ///
380    /// The [`shadows`](Self::shadows) are drawn outside of the [`size`](Self::size).
381    pub size: Size,
382}
383
384impl Magnifier {
385    /// Creates a [`RawMagnifier`] in the Material style.
386    pub fn new() -> Magnifier {
387        Magnifier::default()
388    }
389
390    /// Dart `Magnifier(key:)`.
391    pub fn key(mut self, key: KeyRef) -> Magnifier {
392        self.key = Some(key);
393        self
394    }
395
396    /// Dart `Magnifier(additionalFocalPointOffset:)`.
397    pub fn additional_focal_point_offset(
398        mut self,
399        additional_focal_point_offset: Offset,
400    ) -> Magnifier {
401        self.additional_focal_point_offset = additional_focal_point_offset;
402        self
403    }
404
405    /// Dart `Magnifier(borderRadius:)`.
406    pub fn border_radius(mut self, border_radius: BorderRadius) -> Magnifier {
407        self.border_radius = border_radius;
408        self
409    }
410
411    /// Dart `Magnifier(filmColor:)`.
412    pub fn film_color(mut self, film_color: Color) -> Magnifier {
413        self.film_color = film_color;
414        self
415    }
416
417    /// Dart `Magnifier(shadows:)`.
418    pub fn shadows(mut self, shadows: Vec<BoxShadow>) -> Magnifier {
419        self.shadows = shadows;
420        self
421    }
422
423    /// Dart `Magnifier(clipBehavior:)`.
424    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Magnifier {
425        self.clip_behavior = clip_behavior;
426        self
427    }
428
429    /// Dart `Magnifier(size:)`.
430    pub fn size(mut self, size: Size) -> Magnifier {
431        self.size = size;
432        self
433    }
434
435    /// The default size of this [`Magnifier`].
436    ///
437    /// The size of the magnifier may be modified through the constructor;
438    /// [`K_DEFAULT_MAGNIFIER_SIZE`](Self::K_DEFAULT_MAGNIFIER_SIZE) is extracted from the default
439    /// parameter of [`Magnifier`]'s constructor so that positioners may depend on it.
440    pub const K_DEFAULT_MAGNIFIER_SIZE: Size = Size::new(77.37, 37.9);
441
442    /// The vertical distance that the magnifier should be above the focal point.
443    ///
444    /// The [`K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT`](Self::K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT)
445    /// value is a constant so that positioning of this [`Magnifier`] can be done with a guaranteed
446    /// size, as opposed to an estimate.
447    pub const K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT: f64 = 22.0;
448
449    const BORDER_RADIUS: f64 = 40.0;
450    const MAGNIFICATION: f64 = 1.25;
451}
452
453impl Default for Magnifier {
454    fn default() -> Magnifier {
455        Magnifier {
456            key: None,
457            additional_focal_point_offset: Offset::ZERO,
458            border_radius: BorderRadius::all(Radius::circular(Magnifier::BORDER_RADIUS)),
459            film_color: Color::from_argb(8, 158, 158, 158),
460            shadows: vec![BoxShadow::new(
461                Color::from_argb(25, 0, 0, 0),
462                Offset::new(0.0, 2.0),
463                1.5,
464                0.75,
465                BlurStyle::Normal,
466            )],
467            clip_behavior: Clip::HardEdge,
468            size: Magnifier::K_DEFAULT_MAGNIFIER_SIZE,
469        }
470    }
471}
472
473impl StatelessWidget for Magnifier {
474    fn key(&self) -> Option<&KeyRef> {
475        self.key.as_ref()
476    }
477
478    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
479        RawMagnifier::new(self.size)
480            .decoration(
481                MagnifierDecoration::new()
482                    .shape(RoundedRectangleBorder::new(
483                        BorderSide::NONE,
484                        self.border_radius.into(),
485                    ))
486                    .shadows(self.shadows.clone()),
487            )
488            .clip_behavior(self.clip_behavior)
489            .magnification_scale(Magnifier::MAGNIFICATION)
490            .focal_point_offset(
491                self.additional_focal_point_offset
492                    + Offset::new(
493                        0.0,
494                        Magnifier::K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT
495                            + Magnifier::K_DEFAULT_MAGNIFIER_SIZE.height() / 2.0,
496                    ),
497            )
498            .child(
499                // This couldn't be part of the decoration (even if the
500                // MagnifierDecoration supported specifying a color) because the
501                // decoration's shadows are offset and therefore we set a clipBehavior
502                // that clips the inner part of the decoration to avoid occluding the
503                // magnified image with the shadow.
504                ColoredBox::new(self.film_color),
505            )
506            .into_widget()
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use waft_embedder::{Rect, TargetPlatform};
513    use waft_widgets::{
514        GlobalKey, ImplicitlyAnimatedWidget, Positioned, SizedBox, downcast_widget,
515    };
516
517    use waft_widgets::testing::{WidgetTester, find, test_widgets};
518
519    use super::*;
520    use crate::app::MaterialApp;
521    use crate::theme_data::ThemeData;
522
523    const REASONABLE_TEXT_FIELD: Rect = Rect::from_ltrb(50.0, 100.0, 200.0, 100.0);
524    const BASIC_OFFSET: Offset = Offset::new(
525        Magnifier::K_DEFAULT_MAGNIFIER_SIZE.width() / 2.0,
526        Magnifier::K_STANDARD_VERTICAL_FOCAL_POINT_SHIFT
527            + Magnifier::K_DEFAULT_MAGNIFIER_SIZE.height(),
528    );
529
530    fn info(
531        line: Rect,
532        field: Rect,
533        caret: Rect,
534        global_gesture_position: Offset,
535    ) -> MagnifierInfo {
536        MagnifierInfo::new(global_gesture_position, caret, field, line)
537    }
538
539    /// An info whose line, field and caret are all `rect`, the gesture at `position`.
540    fn info_over(rect: Rect, position: Offset) -> MagnifierInfo {
541        info(rect, rect, rect, position)
542    }
543
544    /// Dart's `MaterialApp(home: Placeholder())`, whose home is a sized box under `key`.
545    fn pump_app(tester: &mut WidgetTester, key: &GlobalKey) {
546        let root = {
547            let app = tester.cell.borrow();
548            MaterialApp::new()
549                .theme(ThemeData::new(&app))
550                .home(SizedBox::new().key(key.clone().into()))
551                .into_widget()
552        };
553        tester.pump_widget(root);
554    }
555
556    fn app_context(tester: &mut WidgetTester) -> BuildContext {
557        let home = GlobalKey::new();
558        pump_app(tester, &home);
559        home.current_context(&tester.cell.borrow_mut())
560            .expect("mounted")
561    }
562
563    /// Dart's `showMagnifier`: shows a [`TextMagnifier`] over `magnifier_info` and settles.
564    fn show_magnifier(
565        tester: &mut WidgetTester,
566        context: BuildContext,
567        magnifier_info: MagnifierInfo,
568    ) -> (Ref<MagnifierController>, Ref<ValueNotifier<MagnifierInfo>>) {
569        let (controller, notifier) = {
570            let mut app = tester.cell.borrow_mut();
571            let notifier = app.create(ValueNotifier::new(magnifier_info));
572            let controller = MagnifierController::new(&mut app);
573            let shown = notifier.clone();
574            controller.show(
575                &mut app,
576                context,
577                Rc::new(move |_app: &mut App, _context: BuildContext| {
578                    TextMagnifier::new(shown.clone()).into_widget()
579                }),
580                None,
581            );
582            (controller, notifier)
583        };
584        tester.pump_and_settle();
585        (controller, notifier)
586    }
587
588    fn magnifier_position(tester: &WidgetTester) -> Offset {
589        let positioned = find::by_type::<Positioned>().evaluate(tester)[0];
590        tester.widget::<Positioned, _>(positioned, |positioned| {
591            Offset::new(
592                positioned.left.unwrap_or(0.0),
593                positioned.top.unwrap_or(0.0),
594            )
595        })
596    }
597
598    fn magnifier_additional_focal_point(tester: &WidgetTester) -> Offset {
599        let magnifier = find::by_type::<Magnifier>().evaluate(tester)[0];
600        tester.widget::<Magnifier, _>(magnifier, |magnifier| {
601            magnifier.additional_focal_point_offset
602        })
603    }
604
605    fn is_animated(tester: &WidgetTester) -> bool {
606        let positioned = find::by_type::<AnimatedPositioned>().evaluate(tester)[0];
607        tester.widget::<AnimatedPositioned, _>(positioned, |positioned| {
608            !positioned
609                .implicitly_animated_widget_data()
610                .duration
611                .is_zero()
612        })
613    }
614
615    /// What the configuration's builder builds on `platform`.
616    fn built_by_adaptive_configuration(platform: TargetPlatform) -> Option<WidgetRef> {
617        let mut tester = WidgetTester::on(platform);
618        let context = app_context(&mut tester);
619        let mut app = tester.cell.borrow_mut();
620        let notifier = app.create(ValueNotifier::new(MagnifierInfo::EMPTY));
621        let controller = MagnifierController::new(&mut app);
622        let builder = TextMagnifier::adaptive_magnifier_configuration(&app).magnifier_builder();
623        builder(&mut app, context, controller, notifier)
624    }
625
626    mod adaptive_magnifier_controller_builder {
627        use super::*;
628
629        #[test]
630        fn should_return_a_text_editing_magnifier_on_android() {
631            test_widgets(|_tester| {
632                let built = built_by_adaptive_configuration(TargetPlatform::Android)
633                    .expect("a magnifier on Android");
634                assert!(downcast_widget::<TextMagnifier>(&*built).is_some());
635            });
636        }
637
638        #[test]
639        fn should_return_a_cupertino_magnifier_on_ios() {
640            test_widgets(|_tester| {
641                let built = built_by_adaptive_configuration(TargetPlatform::IOS)
642                    .expect("a magnifier on iOS");
643                assert!(downcast_widget::<CupertinoTextMagnifier>(&*built).is_some());
644            });
645        }
646
647        #[test]
648        fn should_return_null_on_all_platforms_not_android_ios() {
649            test_widgets(|_tester| {
650                for platform in [
651                    TargetPlatform::Fuchsia,
652                    TargetPlatform::Linux,
653                    TargetPlatform::MacOS,
654                    TargetPlatform::Windows,
655                ] {
656                    assert!(
657                        built_by_adaptive_configuration(platform).is_none(),
658                        "{platform:?}"
659                    );
660                }
661            });
662        }
663
664        #[test]
665        fn shows_the_editing_handles_only_on_ios() {
666            test_widgets(|_tester| {
667                for platform in [
668                    TargetPlatform::Android,
669                    TargetPlatform::Fuchsia,
670                    TargetPlatform::IOS,
671                    TargetPlatform::Linux,
672                    TargetPlatform::MacOS,
673                    TargetPlatform::Windows,
674                ] {
675                    let tester = WidgetTester::on(platform);
676                    let configuration =
677                        TextMagnifier::adaptive_magnifier_configuration(&tester.cell.borrow());
678                    assert_eq!(
679                        configuration.should_display_handles_in_magnifier,
680                        platform == TargetPlatform::IOS,
681                        "{platform:?}"
682                    );
683                }
684            });
685        }
686
687        #[test]
688        fn keeps_one_builder_identity_across_calls() {
689            test_widgets(|tester| {
690                let app = tester.cell.borrow();
691                let first =
692                    TextMagnifier::adaptive_magnifier_configuration(&app).magnifier_builder();
693                let second =
694                    TextMagnifier::adaptive_magnifier_configuration(&app).magnifier_builder();
695                assert!(Rc::ptr_eq(&first, &second));
696            });
697        }
698    }
699
700    mod position {
701        use super::*;
702
703        #[test]
704        fn should_never_move_outside_the_right_bounds_of_the_editing_line() {
705            test_widgets(|tester| {
706                const GESTURE_OUTSIDE_LINE: f64 = 100.0;
707                let context = app_context(tester);
708
709                let (controller, _) = show_magnifier(
710                    tester,
711                    context,
712                    info(
713                        REASONABLE_TEXT_FIELD,
714                        // Inflate these two to make sure we're bounding on the
715                        // current line boundaries, not anything else.
716                        REASONABLE_TEXT_FIELD.inflate(GESTURE_OUTSIDE_LINE),
717                        REASONABLE_TEXT_FIELD.inflate(GESTURE_OUTSIDE_LINE),
718                        // The tap position is far out of the right side of the app.
719                        Offset::new(REASONABLE_TEXT_FIELD.right + GESTURE_OUTSIDE_LINE, 0.0),
720                    ),
721                );
722
723                // Should be less than the right edge, since we have padding.
724                assert!(magnifier_position(tester).dx() <= REASONABLE_TEXT_FIELD.right);
725                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
726            });
727        }
728
729        #[test]
730        fn should_never_move_outside_the_left_bounds_of_the_editing_line() {
731            test_widgets(|tester| {
732                const GESTURE_OUTSIDE_LINE: f64 = 100.0;
733                let context = app_context(tester);
734
735                let (controller, _) = show_magnifier(
736                    tester,
737                    context,
738                    info(
739                        REASONABLE_TEXT_FIELD,
740                        REASONABLE_TEXT_FIELD.inflate(GESTURE_OUTSIDE_LINE),
741                        REASONABLE_TEXT_FIELD.inflate(GESTURE_OUTSIDE_LINE),
742                        // The tap position is far out of the left side of the app.
743                        Offset::new(REASONABLE_TEXT_FIELD.left - GESTURE_OUTSIDE_LINE, 0.0),
744                    ),
745                );
746
747                assert!(
748                    magnifier_position(tester).dx() + BASIC_OFFSET.dx()
749                        >= REASONABLE_TEXT_FIELD.left
750                );
751                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
752            });
753        }
754
755        #[test]
756        fn should_position_vertically_at_the_center_of_the_line() {
757            test_widgets(|tester| {
758                let context = app_context(tester);
759
760                let (controller, _) = show_magnifier(
761                    tester,
762                    context,
763                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.center()),
764                );
765
766                assert_eq!(
767                    magnifier_position(tester).dy(),
768                    REASONABLE_TEXT_FIELD.center().dy() - BASIC_OFFSET.dy()
769                );
770                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
771            });
772        }
773
774        #[test]
775        fn should_reposition_vertically_if_mashed_against_the_ceiling() {
776            test_widgets(|tester| {
777                let top_of_screen_text_field =
778                    Rect::from_points(Offset::ZERO, Offset::new(200.0, 0.0));
779                let context = app_context(tester);
780
781                let (controller, _) = show_magnifier(
782                    tester,
783                    context,
784                    info_over(
785                        top_of_screen_text_field,
786                        top_of_screen_text_field.top_center(),
787                    ),
788                );
789
790                assert!(magnifier_position(tester).dy() >= 0.0);
791                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
792            });
793        }
794    }
795
796    mod focal_point {
797        use super::*;
798
799        #[test]
800        fn should_shift_focal_point_so_that_the_lens_sees_nothing_out_of_bounds() {
801            test_widgets(|tester| {
802                let context = app_context(tester);
803
804                let (controller, _) = show_magnifier(
805                    tester,
806                    context,
807                    // Gesture on the far right of the magnifier.
808                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.top_left()),
809                );
810
811                assert!(magnifier_additional_focal_point(tester).dx() < REASONABLE_TEXT_FIELD.left);
812                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
813            });
814        }
815
816        #[test]
817        fn focal_point_should_shift_if_mashed_against_the_top_to_always_point_to_text() {
818            test_widgets(|tester| {
819                let top_of_screen_text_field =
820                    Rect::from_points(Offset::ZERO, Offset::new(200.0, 0.0));
821                let context = app_context(tester);
822
823                let (controller, _) = show_magnifier(
824                    tester,
825                    context,
826                    info_over(
827                        top_of_screen_text_field,
828                        top_of_screen_text_field.top_center(),
829                    ),
830                );
831
832                assert!(magnifier_additional_focal_point(tester).dy() < 0.0);
833                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
834            });
835        }
836    }
837
838    mod animation_state {
839        use super::*;
840
841        const VERTICAL_SHIFT: Offset = Offset::new(0.0, 200.0);
842
843        /// The info of a gesture that went down a line from `REASONABLE_TEXT_FIELD`.
844        fn info_one_line_down() -> MagnifierInfo {
845            info(
846                REASONABLE_TEXT_FIELD.shift(VERTICAL_SHIFT),
847                Rect::from_points(
848                    REASONABLE_TEXT_FIELD.top_left(),
849                    REASONABLE_TEXT_FIELD.bottom_right() + VERTICAL_SHIFT,
850                ),
851                REASONABLE_TEXT_FIELD.shift(VERTICAL_SHIFT),
852                REASONABLE_TEXT_FIELD.center() + VERTICAL_SHIFT,
853            )
854        }
855
856        #[test]
857        fn should_not_be_animated_on_the_initial_state() {
858            test_widgets(|tester| {
859                let context = app_context(tester);
860
861                let (controller, _) = show_magnifier(
862                    tester,
863                    context,
864                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.center()),
865                );
866
867                assert!(!is_animated(tester));
868                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
869            });
870        }
871
872        #[test]
873        fn should_not_be_animated_on_horizontal_shifts() {
874            test_widgets(|tester| {
875                let context = app_context(tester);
876                let (controller, notifier) = show_magnifier(
877                    tester,
878                    context,
879                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.center()),
880                );
881
882                // New position has a horizontal shift.
883                notifier.set_value(
884                    &mut tester.cell.borrow_mut(),
885                    info_over(
886                        REASONABLE_TEXT_FIELD,
887                        REASONABLE_TEXT_FIELD.center() + Offset::new(200.0, 0.0),
888                    ),
889                );
890                tester.pump_and_settle();
891
892                assert!(!is_animated(tester));
893                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
894            });
895        }
896
897        #[test]
898        fn should_be_animated_on_vertical_shifts() {
899            test_widgets(|tester| {
900                let context = app_context(tester);
901                let (controller, notifier) = show_magnifier(
902                    tester,
903                    context,
904                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.center()),
905                );
906
907                // New position has a vertical shift.
908                notifier.set_value(&mut tester.cell.borrow_mut(), info_one_line_down());
909
910                tester.pump();
911                assert!(is_animated(tester));
912                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
913            });
914        }
915
916        #[test]
917        fn should_stop_being_animated_when_timer_is_up() {
918            test_widgets(|tester| {
919                let context = app_context(tester);
920                let (controller, notifier) = show_magnifier(
921                    tester,
922                    context,
923                    info_over(REASONABLE_TEXT_FIELD, REASONABLE_TEXT_FIELD.center()),
924                );
925
926                // New position has a vertical shift.
927                notifier.set_value(&mut tester.cell.borrow_mut(), info_one_line_down());
928
929                tester.pump();
930                assert!(is_animated(tester));
931                tester.pump_by(
932                    TextMagnifier::JUMP_BETWEEN_LINES_ANIMATION_DURATION + Duration::from_secs(2),
933                );
934                assert!(!is_animated(tester));
935                controller.remove_from_overlay(&mut tester.cell.borrow_mut());
936            });
937        }
938    }
939
940    mod material_magnifier {
941        use waft_widgets::RawMagnifier;
942
943        use super::*;
944
945        #[test]
946        fn builds_a_raw_magnifier_in_the_material_style_by_default() {
947            test_widgets(|tester| {
948                let _context = app_context(tester);
949                let root = {
950                    let app = tester.cell.borrow();
951                    MaterialApp::new()
952                        .theme(ThemeData::new(&app))
953                        .home(Magnifier::new())
954                        .into_widget()
955                };
956                tester.pump_widget(root);
957
958                let raw = find::by_type::<RawMagnifier>().evaluate(tester)[0];
959                tester.widget::<RawMagnifier, _>(raw, |raw| {
960                    assert_eq!(raw.size, Magnifier::K_DEFAULT_MAGNIFIER_SIZE);
961                    assert_eq!(raw.size, Size::new(77.37, 37.9));
962                    assert_eq!(raw.clip_behavior, Clip::HardEdge);
963                    assert_eq!(raw.magnification_scale, 1.25);
964                    assert_eq!(raw.focal_point_offset, Offset::new(0.0, 22.0 + 37.9 / 2.0));
965                    assert_eq!(
966                        raw.decoration.shadows,
967                        Some(vec![BoxShadow::new(
968                            Color::from_argb(25, 0, 0, 0),
969                            Offset::new(0.0, 2.0),
970                            1.5,
971                            0.75,
972                            BlurStyle::Normal,
973                        )])
974                    );
975                    let expected_shape = RoundedRectangleBorder::new(
976                        BorderSide::NONE,
977                        BorderRadius::all(Radius::circular(40.0)).into(),
978                    );
979                    assert!(raw.decoration.shape.eq_shape(&expected_shape));
980                });
981            });
982        }
983
984        #[test]
985        fn adds_the_additional_focal_point_offset_to_the_standard_shift() {
986            test_widgets(|tester| {
987                let _context = app_context(tester);
988                let root = {
989                    let app = tester.cell.borrow();
990                    MaterialApp::new()
991                        .theme(ThemeData::new(&app))
992                        .home(
993                            Magnifier::new().additional_focal_point_offset(Offset::new(5.0, -3.0)),
994                        )
995                        .into_widget()
996                };
997                tester.pump_widget(root);
998
999                let raw = find::by_type::<RawMagnifier>().evaluate(tester)[0];
1000                let focal_point_offset =
1001                    tester.widget::<RawMagnifier, _>(raw, |raw| raw.focal_point_offset);
1002                assert_eq!(
1003                    focal_point_offset,
1004                    Offset::new(5.0, 22.0 + 37.9 / 2.0 - 3.0)
1005                );
1006            });
1007        }
1008
1009        #[test]
1010        fn sizes_the_lens_to_zero_area_when_given_a_zero_size() {
1011            test_widgets(|tester| {
1012                let _context = app_context(tester);
1013                let root = {
1014                    let app = tester.cell.borrow();
1015                    MaterialApp::new()
1016                        .theme(ThemeData::new(&app))
1017                        .home(Magnifier::new().size(Size::ZERO))
1018                        .into_widget()
1019                };
1020                tester.pump_widget(root);
1021
1022                let raw = find::by_type::<RawMagnifier>().evaluate(tester)[0];
1023                assert_eq!(
1024                    tester.widget::<RawMagnifier, _>(raw, |raw| raw.size),
1025                    Size::ZERO
1026                );
1027            });
1028        }
1029    }
1030}