1use std::fmt;
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::{
11 Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef,
12 AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurvedAnimation, Curves, Drive,
13 Tween, TweenLerp,
14};
15use waft_embedder::{
16 Clip, Color, FilterQuality, Matrix4, Offset, Rect, TextAlign, TextHeightBehavior, compose,
17 decompose,
18};
19use waft_foundation::{
20 App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
21 FlagProperty, Handle, IntProperty, Listener, ObjectFlagProperty, OptionRetained,
22};
23use waft_painting::{
24 Alignment, AlignmentGeometry, AnyColor, Border, BorderRadius, BoxDecoration, BoxShape,
25 ColorProperty, DecorationRef, EdgeInsets, EdgeInsetsGeometry, ShapeBorderRef, TextOverflow,
26 TextStyle, TextWidthBasis,
27};
28use waft_rendering::{AlignmentGeometryTween, BoxConstraints, Constraints};
29use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
30
31use crate::framework::{
32 BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
33};
34use crate::widgets::basic::{
35 Align, Directionality, FractionallySizedBox, Padding, PhysicalModel, Positioned,
36};
37use crate::widgets::container::Container;
38use crate::widgets::text::DefaultTextStyle;
39use crate::widgets::ticker_provider::{
40 SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
41};
42use crate::widgets::transitions::{
43 FadeTransition, RotationTransition, ScaleTransition, SlideTransition,
44};
45use waft_foundation::Ref;
46
47fn display_option<T: fmt::Display>(value: &Option<T>) -> String {
49 value
50 .as_ref()
51 .map_or_else(|| "null".to_string(), |value| value.to_string())
52}
53
54fn display_option_debug<T: fmt::Debug>(value: &Option<T>) -> String {
56 value
57 .as_ref()
58 .map_or_else(|| "null".to_string(), |value| format!("{value:?}"))
59}
60
61fn describe_double_tween(tween: Option<&Ref<Tween<f64>>>, app: &App) -> Option<String> {
63 tween.map(|tween| {
64 let tween = app.get(tween);
65 format!(
66 "Tween<double>(begin: {}, end: {})",
67 display_option(&tween.begin),
68 display_option(&tween.end)
69 )
70 })
71}
72
73#[derive(Clone, Debug)]
85pub struct BoxConstraintsTween {
86 pub begin: Option<BoxConstraints>,
88
89 pub end: Option<BoxConstraints>,
91}
92
93impl BoxConstraintsTween {
94 pub fn new(begin: Option<BoxConstraints>, end: Option<BoxConstraints>) -> BoxConstraintsTween {
99 BoxConstraintsTween { begin, end }
100 }
101
102 pub fn lerp(&self, t: f64) -> BoxConstraints {
104 BoxConstraints::lerp(self.begin, self.end, t)
105 .expect("BoxConstraintsTween.begin or end must be set before use")
106 }
107}
108
109impl fmt::Display for BoxConstraintsTween {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(
113 f,
114 "BoxConstraintsTween(begin: {}, end: {})",
115 display_option(&self.begin),
116 display_option(&self.end),
117 )
118 }
119}
120
121impl Animatable<BoxConstraints> for BoxConstraintsTween {
122 fn transform(&self, _app: &App, t: f64) -> BoxConstraints {
123 if t == 0.0 {
124 return self.begin.expect("Tween.begin must be set before use");
125 }
126 if t == 1.0 {
127 return self.end.expect("Tween.end must be set before use");
128 }
129 self.lerp(t)
130 }
131}
132
133#[derive(Clone, Debug)]
145pub struct DecorationTween {
146 pub begin: Option<DecorationRef>,
148
149 pub end: Option<DecorationRef>,
151}
152
153impl DecorationTween {
154 pub fn new(begin: Option<DecorationRef>, end: Option<DecorationRef>) -> DecorationTween {
156 DecorationTween { begin, end }
157 }
158
159 pub fn lerp(&self, t: f64) -> DecorationRef {
161 DecorationRef::lerp(self.begin.as_ref(), self.end.as_ref(), t)
162 .expect("DecorationTween.begin or end must be set before use")
163 }
164}
165
166impl fmt::Display for DecorationTween {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 write!(
170 f,
171 "DecorationTween(begin: {}, end: {})",
172 display_option_debug(&self.begin),
173 display_option_debug(&self.end),
174 )
175 }
176}
177
178impl Animatable<DecorationRef> for DecorationTween {
179 fn transform(&self, _app: &App, t: f64) -> DecorationRef {
180 if t == 0.0 {
181 return self
182 .begin
183 .as_ref()
184 .expect("Tween.begin must be set before use")
185 .clone();
186 }
187 if t == 1.0 {
188 return self
189 .end
190 .as_ref()
191 .expect("Tween.end must be set before use")
192 .clone();
193 }
194 self.lerp(t)
195 }
196}
197
198#[derive(Clone, Debug)]
214pub struct EdgeInsetsTween {
215 pub begin: Option<EdgeInsets>,
217
218 pub end: Option<EdgeInsets>,
220}
221
222impl EdgeInsetsTween {
223 pub fn new(begin: Option<EdgeInsets>, end: Option<EdgeInsets>) -> EdgeInsetsTween {
228 EdgeInsetsTween { begin, end }
229 }
230
231 pub fn lerp(&self, t: f64) -> EdgeInsets {
233 EdgeInsets::lerp(self.begin, self.end, t)
234 .expect("EdgeInsetsTween.begin or end must be set before use")
235 }
236}
237
238impl Animatable<EdgeInsets> for EdgeInsetsTween {
239 fn transform(&self, _app: &App, t: f64) -> EdgeInsets {
240 if t == 0.0 {
241 return self.begin.expect("Tween.begin must be set before use");
242 }
243 if t == 1.0 {
244 return self.end.expect("Tween.end must be set before use");
245 }
246 self.lerp(t)
247 }
248}
249
250#[derive(Clone, Debug)]
263pub struct EdgeInsetsGeometryTween {
264 pub begin: Option<EdgeInsetsGeometry>,
266
267 pub end: Option<EdgeInsetsGeometry>,
269}
270
271impl EdgeInsetsGeometryTween {
272 pub fn new(
277 begin: Option<EdgeInsetsGeometry>,
278 end: Option<EdgeInsetsGeometry>,
279 ) -> EdgeInsetsGeometryTween {
280 EdgeInsetsGeometryTween { begin, end }
281 }
282
283 pub fn lerp(&self, t: f64) -> EdgeInsetsGeometry {
285 EdgeInsetsGeometry::lerp(self.begin, self.end, t)
286 .expect("EdgeInsetsGeometryTween.begin or end must be set before use")
287 }
288}
289
290impl fmt::Display for EdgeInsetsGeometryTween {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 write!(
294 f,
295 "EdgeInsetsGeometryTween(begin: {}, end: {})",
296 display_option(&self.begin),
297 display_option(&self.end),
298 )
299 }
300}
301
302impl Animatable<EdgeInsetsGeometry> for EdgeInsetsGeometryTween {
303 fn transform(&self, _app: &App, t: f64) -> EdgeInsetsGeometry {
304 if t == 0.0 {
305 return self.begin.expect("Tween.begin must be set before use");
306 }
307 if t == 1.0 {
308 return self.end.expect("Tween.end must be set before use");
309 }
310 self.lerp(t)
311 }
312}
313
314#[derive(Clone, Debug)]
323pub struct BorderRadiusTween {
324 pub begin: Option<BorderRadius>,
326
327 pub end: Option<BorderRadius>,
329}
330
331impl BorderRadiusTween {
332 pub fn new(begin: Option<BorderRadius>, end: Option<BorderRadius>) -> BorderRadiusTween {
337 BorderRadiusTween { begin, end }
338 }
339
340 pub fn lerp(&self, t: f64) -> Option<BorderRadius> {
342 BorderRadius::lerp(self.begin, self.end, t)
343 }
344}
345
346impl Animatable<Option<BorderRadius>> for BorderRadiusTween {
347 fn transform(&self, _app: &App, t: f64) -> Option<BorderRadius> {
348 if t == 0.0 {
349 return self.begin;
350 }
351 if t == 1.0 {
352 return self.end;
353 }
354 self.lerp(t)
355 }
356}
357
358#[derive(Clone, Debug)]
367pub struct BorderTween {
368 pub begin: Option<Border>,
370
371 pub end: Option<Border>,
373}
374
375impl BorderTween {
376 pub fn new(begin: Option<Border>, end: Option<Border>) -> BorderTween {
381 BorderTween { begin, end }
382 }
383
384 pub fn lerp(&self, t: f64) -> Option<Border> {
386 Border::lerp(self.begin, self.end, t)
387 }
388}
389
390impl Animatable<Option<Border>> for BorderTween {
391 fn transform(&self, _app: &App, t: f64) -> Option<Border> {
392 if t == 0.0 {
393 return self.begin;
394 }
395 if t == 1.0 {
396 return self.end;
397 }
398 self.lerp(t)
399 }
400}
401
402#[derive(Clone, Debug)]
413pub struct Matrix4Tween {
414 pub begin: Option<Matrix4>,
416
417 pub end: Option<Matrix4>,
419}
420
421impl Matrix4Tween {
422 pub fn new(begin: Option<Matrix4>, end: Option<Matrix4>) -> Matrix4Tween {
428 Matrix4Tween { begin, end }
429 }
430
431 pub fn lerp(&self, t: f64) -> Matrix4 {
433 let begin = self
434 .begin
435 .expect("Matrix4Tween.begin must be set before use");
436 let end = self.end.expect("Matrix4Tween.end must be set before use");
437 let (begin_translation, begin_rotation, begin_scale) = decompose(begin);
438 let (end_translation, end_rotation, end_scale) = decompose(end);
439 let t = t as f32;
440 let lerp_translation = begin_translation * (1.0 - t) + end_translation * t;
441 let lerp_rotation = (begin_rotation.scaled(1.0 - t) + end_rotation.scaled(t)).normalized();
443 let lerp_scale = begin_scale * (1.0 - t) + end_scale * t;
444 compose(lerp_translation, lerp_rotation, lerp_scale)
445 }
446}
447
448impl Animatable<Matrix4> for Matrix4Tween {
449 fn transform(&self, _app: &App, t: f64) -> Matrix4 {
450 if t == 0.0 {
451 return self.begin.expect("Tween.begin must be set before use");
452 }
453 if t == 1.0 {
454 return self.end.expect("Tween.end must be set before use");
455 }
456 self.lerp(t)
457 }
458}
459
460#[derive(Clone, Debug)]
471pub struct TextStyleTween {
472 pub begin: Option<TextStyle>,
474
475 pub end: Option<TextStyle>,
477}
478
479impl TextStyleTween {
480 pub fn new(begin: Option<TextStyle>, end: Option<TextStyle>) -> TextStyleTween {
482 TextStyleTween { begin, end }
483 }
484
485 pub fn lerp(&self, t: f64) -> TextStyle {
487 TextStyle::lerp(self.begin.as_ref(), self.end.as_ref(), t)
488 .expect("TextStyleTween.begin or end must be set before use")
489 }
490}
491
492impl Animatable<TextStyle> for TextStyleTween {
493 fn transform(&self, _app: &App, t: f64) -> TextStyle {
494 if t == 0.0 {
495 return self
496 .begin
497 .clone()
498 .expect("Tween.begin must be set before use");
499 }
500 if t == 1.0 {
501 return self.end.clone().expect("Tween.end must be set before use");
502 }
503 self.lerp(t)
504 }
505}
506
507#[derive(Debug)]
509pub struct ImplicitlyAnimatedWidgetData {
510 pub key: Option<KeyRef>,
512
513 pub curve: Rc<dyn Curve>,
515
516 pub duration: Duration,
518
519 pub on_end: Option<Listener>,
524}
525
526impl ImplicitlyAnimatedWidgetData {
527 pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
530 properties.add(IntProperty::new("duration", self.duration.as_millis() as i64).unit("ms"));
531 }
532
533 pub fn new(duration: Duration) -> ImplicitlyAnimatedWidgetData {
535 ImplicitlyAnimatedWidgetData {
536 key: None,
537 curve: Curves::linear(),
538 duration,
539 on_end: None,
540 }
541 }
542}
543
544#[macro_export]
547macro_rules! implicitly_animated_widget_accessors {
548 () => {
549 fn implicitly_animated_widget_data(&self) -> &$crate::ImplicitlyAnimatedWidgetData {
550 &self.implicitly_animated_widget
551 }
552
553 fn implicitly_animated_widget_data_mut(
554 &mut self,
555 ) -> &mut $crate::ImplicitlyAnimatedWidgetData {
556 &mut self.implicitly_animated_widget
557 }
558 };
559}
560
561#[macro_export]
564macro_rules! implicitly_animated_widget_setters {
565 ($name:ident) => {
566 pub fn key(mut self, key: $crate::KeyRef) -> $name {
568 self.implicitly_animated_widget.key = Some(key);
569 self
570 }
571
572 pub fn curve(mut self, curve: ::std::rc::Rc<dyn ::waft_animation::Curve>) -> $name {
574 self.implicitly_animated_widget.curve = curve;
575 self
576 }
577
578 pub fn on_end(mut self, on_end: ::waft_foundation::Listener) -> $name {
580 self.implicitly_animated_widget.on_end = Some(on_end);
581 self
582 }
583 };
584}
585
586pub trait ImplicitlyAnimatedWidget: StatefulWidget {
627 fn implicitly_animated_widget_data(&self) -> &ImplicitlyAnimatedWidgetData;
630
631 fn implicitly_animated_widget_data_mut(&mut self) -> &mut ImplicitlyAnimatedWidgetData;
633}
634
635pub trait TweenValue: 'static {
639 fn same(&self, other: &Self) -> bool;
641}
642
643impl<T: TweenValue> TweenValue for Rc<T> {
646 fn same(&self, other: &Rc<T>) -> bool {
647 T::same(self, other)
648 }
649}
650
651impl TweenValue for f64 {
652 fn same(&self, other: &f64) -> bool {
653 self == other
654 }
655}
656
657impl TweenValue for BoxConstraints {
658 fn same(&self, other: &BoxConstraints) -> bool {
659 self == other
660 }
661}
662
663impl TweenValue for EdgeInsets {
664 fn same(&self, other: &EdgeInsets) -> bool {
665 self == other
666 }
667}
668
669impl TweenValue for EdgeInsetsGeometry {
670 fn same(&self, other: &EdgeInsetsGeometry) -> bool {
671 self == other
672 }
673}
674
675impl TweenValue for Matrix4 {
676 fn same(&self, other: &Matrix4) -> bool {
677 self == other
678 }
679}
680
681impl TweenValue for Offset {
682 fn same(&self, other: &Offset) -> bool {
683 self == other
684 }
685}
686
687impl TweenValue for TextStyle {
688 fn same(&self, other: &TextStyle) -> bool {
689 self == other
690 }
691}
692
693impl TweenValue for Option<BorderRadius> {
694 fn same(&self, other: &Option<BorderRadius>) -> bool {
695 self == other
696 }
697}
698
699impl TweenValue for Option<Border> {
700 fn same(&self, other: &Option<Border>) -> bool {
701 self == other
702 }
703}
704
705impl TweenValue for Option<AlignmentGeometry> {
706 fn same(&self, other: &Option<AlignmentGeometry>) -> bool {
707 self == other
708 }
709}
710
711impl TweenValue for Option<Color> {
712 fn same(&self, other: &Option<Color>) -> bool {
713 self == other
714 }
715}
716
717impl TweenValue for DecorationRef {
718 fn same(&self, other: &DecorationRef) -> bool {
719 self == other
720 }
721}
722
723impl TweenValue for Option<ShapeBorderRef> {
725 fn same(&self, other: &Option<ShapeBorderRef>) -> bool {
726 self == other
727 }
728}
729
730pub trait TweenSlot: Animatable<<Self as TweenSlot>::Value> + Clone + 'static {
735 type Value: TweenValue;
737
738 fn begin(&self, app: &App) -> Option<Self::Value>;
740
741 fn set_begin(&mut self, app: &mut App, begin: Option<Self::Value>);
743
744 fn end(&self, app: &App) -> Option<Self::Value>;
746
747 fn set_end(&mut self, app: &mut App, end: Option<Self::Value>);
749}
750
751impl<T: TweenLerp + TweenValue> TweenSlot for Ref<Tween<T>> {
752 type Value = T;
753
754 fn begin(&self, app: &App) -> Option<T> {
755 Tween::begin(self.handle(), app).cloned()
756 }
757
758 fn set_begin(&mut self, app: &mut App, begin: Option<T>) {
759 Tween::set_begin(self.handle(), app, begin);
760 }
761
762 fn end(&self, app: &App) -> Option<T> {
763 Tween::end(self.handle(), app).cloned()
764 }
765
766 fn set_end(&mut self, app: &mut App, end: Option<T>) {
767 Tween::set_end(self.handle(), app, end);
768 }
769}
770
771macro_rules! tween_slot_for_value {
773 ($tween:ty, $value:ty) => {
774 impl TweenSlot for $tween {
775 type Value = $value;
776
777 fn begin(&self, _app: &App) -> Option<$value> {
778 self.begin.clone()
779 }
780
781 fn set_begin(&mut self, _app: &mut App, begin: Option<$value>) {
782 self.begin = begin;
783 }
784
785 fn end(&self, _app: &App) -> Option<$value> {
786 self.end.clone()
787 }
788
789 fn set_end(&mut self, _app: &mut App, end: Option<$value>) {
790 self.end = end;
791 }
792 }
793 };
794}
795
796tween_slot_for_value!(BoxConstraintsTween, BoxConstraints);
797tween_slot_for_value!(EdgeInsetsTween, EdgeInsets);
798tween_slot_for_value!(EdgeInsetsGeometryTween, EdgeInsetsGeometry);
799tween_slot_for_value!(Matrix4Tween, Matrix4);
800tween_slot_for_value!(TextStyleTween, TextStyle);
801
802macro_rules! tween_slot_for_nullable_value {
806 ($tween:ty, $value:ty) => {
807 impl TweenSlot for $tween {
808 type Value = Option<$value>;
809
810 fn begin(&self, _app: &App) -> Option<Option<$value>> {
811 self.begin.map(Some)
812 }
813
814 fn set_begin(&mut self, _app: &mut App, begin: Option<Option<$value>>) {
815 self.begin = begin.flatten();
816 }
817
818 fn end(&self, _app: &App) -> Option<Option<$value>> {
819 self.end.map(Some)
820 }
821
822 fn set_end(&mut self, _app: &mut App, end: Option<Option<$value>>) {
823 self.end = end.flatten();
824 }
825 }
826 };
827}
828
829tween_slot_for_nullable_value!(BorderRadiusTween, BorderRadius);
830
831impl TweenSlot for Ref<ColorTween> {
834 type Value = Option<Color>;
835
836 fn begin(&self, app: &App) -> Option<Option<Color>> {
837 ColorTween::begin(self.handle(), app).map(Some)
838 }
839
840 fn set_begin(&mut self, app: &mut App, begin: Option<Option<Color>>) {
841 ColorTween::set_begin(self.handle(), app, begin.flatten());
842 }
843
844 fn end(&self, app: &App) -> Option<Option<Color>> {
845 ColorTween::end(self.handle(), app).map(Some)
846 }
847
848 fn set_end(&mut self, app: &mut App, end: Option<Option<Color>>) {
849 ColorTween::set_end(self.handle(), app, end.flatten());
850 }
851}
852tween_slot_for_nullable_value!(BorderTween, Border);
853tween_slot_for_nullable_value!(AlignmentGeometryTween, AlignmentGeometry);
854
855impl TweenSlot for DecorationTween {
856 type Value = DecorationRef;
857
858 fn begin(&self, _app: &App) -> Option<DecorationRef> {
859 self.begin.clone()
860 }
861
862 fn set_begin(&mut self, _app: &mut App, begin: Option<DecorationRef>) {
863 self.begin = begin;
864 }
865
866 fn end(&self, _app: &App) -> Option<DecorationRef> {
867 self.end.clone()
868 }
869
870 fn set_end(&mut self, _app: &mut App, end: Option<DecorationRef>) {
871 self.end = end;
872 }
873}
874
875pub type TweenConstructor<W> = fn(&mut App, &<W as TweenSlot>::Value) -> W;
883
884pub trait TweenVisitor {
906 fn visit<W: TweenSlot>(
908 &mut self,
909 app: &mut App,
910 tween: Option<W>,
911 target: Option<W::Value>,
912 constructor: TweenConstructor<W>,
913 ) -> Option<W>;
914}
915
916struct ConstructTweens {
918 should_start_animation: bool,
919}
920
921impl TweenVisitor for ConstructTweens {
922 fn visit<W: TweenSlot>(
923 &mut self,
924 app: &mut App,
925 tween: Option<W>,
926 target: Option<W::Value>,
927 constructor: TweenConstructor<W>,
928 ) -> Option<W> {
929 let target = target?;
930 let mut tween = match tween {
931 Some(tween) => tween,
932 None => constructor(app, &target),
933 };
934 let endpoint = tween.end(app).or_else(|| tween.begin(app));
935 if !endpoint.is_some_and(|endpoint| target.same(&endpoint)) {
936 self.should_start_animation = true;
937 } else if tween.end(app).is_none() {
938 let begin = tween.begin(app);
939 tween.set_end(app, begin);
940 }
941 Some(tween)
942 }
943}
944
945struct RetargetTweens {
948 animation: AnyAnimation<f64>,
949}
950
951impl TweenVisitor for RetargetTweens {
952 fn visit<W: TweenSlot>(
953 &mut self,
954 app: &mut App,
955 tween: Option<W>,
956 target: Option<W::Value>,
957 _constructor: TweenConstructor<W>,
958 ) -> Option<W> {
959 let mut tween = tween?;
960 let begin = tween.evaluate(app, self.animation);
961 tween.set_begin(app, Some(begin));
962 tween.set_end(app, target);
963 Some(tween)
964 }
965}
966
967#[derive(Default)]
971pub struct ImplicitlyAnimatedWidgetStateData {
972 controller: Option<Ref<AnimationController>>,
973 animation: Option<Ref<CurvedAnimation>>,
974}
975
976impl ImplicitlyAnimatedWidgetStateData {
977 pub fn new() -> ImplicitlyAnimatedWidgetStateData {
979 ImplicitlyAnimatedWidgetStateData::default()
980 }
981}
982
983#[macro_export]
987macro_rules! implicitly_animated_widget_state_accessors {
988 () => {
989 fn implicitly_animated_widget_state_data(
990 self: ::waft_foundation::Handle<Self>,
991 app: &::waft_foundation::App,
992 ) -> &$crate::ImplicitlyAnimatedWidgetStateData {
993 &app.get(self).implicitly_animated_widget_state
994 }
995
996 fn implicitly_animated_widget_state_data_mut(
997 self: ::waft_foundation::Handle<Self>,
998 app: &mut ::waft_foundation::App,
999 ) -> &mut $crate::ImplicitlyAnimatedWidgetStateData {
1000 &mut app.get_mut(self).implicitly_animated_widget_state
1001 }
1002 };
1003}
1004
1005pub trait ImplicitlyAnimatedWidgetState:
1019 State + SingleTickerProviderStateMixin + TickerProviderObject
1020where
1021 Self::Widget: ImplicitlyAnimatedWidget,
1022{
1023 fn implicitly_animated_widget_state_data(
1026 self: Handle<Self>,
1027 app: &App,
1028 ) -> &ImplicitlyAnimatedWidgetStateData;
1029
1030 fn implicitly_animated_widget_state_data_mut(
1032 self: Handle<Self>,
1033 app: &mut App,
1034 ) -> &mut ImplicitlyAnimatedWidgetStateData;
1035
1036 fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1038 self.implicitly_animated_widget_state_data(app)
1039 .controller
1040 .handle()
1041 .expect("created in init_state")
1042 }
1043
1044 fn animation(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1046 curved_animation(self, app).as_animation()
1047 }
1048
1049 fn init_state(self: Handle<Self>, app: &mut App) {
1051 let duration = self.widget(app).implicitly_animated_widget_data().duration;
1052 let controller = AnimationController::new(
1053 app,
1054 None,
1055 Some(duration),
1056 None,
1057 0.0,
1058 1.0,
1059 AnimationBehavior::Normal,
1060 self,
1061 );
1062 self.implicitly_animated_widget_state_data_mut(app)
1063 .controller = Some(controller.clone());
1064 controller.add_status_listener(
1065 app,
1066 AnimationStatusListener::new(move |status, app| {
1067 if status.is_completed() {
1068 let on_end = self
1069 .widget(app)
1070 .implicitly_animated_widget_data()
1071 .on_end
1072 .clone();
1073 if let Some(on_end) = on_end {
1074 on_end.call(app);
1075 }
1076 }
1077 }),
1078 );
1079 let animation = create_curve(self, app);
1080 self.implicitly_animated_widget_state_data_mut(app)
1081 .animation = Some(animation);
1082 construct_tweens(self, app);
1083 self.did_update_tweens(app);
1084 }
1085
1086 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Self::Widget) {
1088 let curve = Rc::clone(&self.widget(app).implicitly_animated_widget_data().curve);
1089 if !Rc::ptr_eq(&curve, &old_widget.implicitly_animated_widget_data().curve) {
1090 curved_animation(self, app).dispose(app);
1091 let animation = create_curve(self, app);
1092 self.implicitly_animated_widget_state_data_mut(app)
1093 .animation = Some(animation);
1094 }
1095 let duration = self.widget(app).implicitly_animated_widget_data().duration;
1096 let controller = self.controller(app);
1097 app.get_mut(controller).duration = Some(duration);
1098 if construct_tweens(self, app) {
1099 let animation = self.animation(app);
1100 self.for_each_tween(app, &mut RetargetTweens { animation });
1101 controller.forward(app, Some(0.0));
1102 self.did_update_tweens(app);
1103 }
1104 }
1105
1106 fn dispose(self: Handle<Self>, app: &mut App) {
1108 let animation = curved_animation(self, app);
1109 animation.dispose(app);
1110 let controller = self.controller(app);
1111 controller.dispose(app);
1112 SingleTickerProviderStateMixin::dispose(self, app);
1113 }
1114
1115 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V);
1147
1148 fn did_update_tweens(self: Handle<Self>, app: &mut App) {
1171 let _ = (self, app);
1172 }
1173}
1174
1175fn curved_animation<S>(this: Handle<S>, app: &App) -> Handle<CurvedAnimation>
1177where
1178 S: ImplicitlyAnimatedWidgetState,
1179 S::Widget: ImplicitlyAnimatedWidget,
1180{
1181 this.implicitly_animated_widget_state_data(app)
1182 .animation
1183 .handle()
1184 .expect("created in init_state")
1185}
1186
1187fn create_curve<S>(this: Handle<S>, app: &mut App) -> Ref<CurvedAnimation>
1189where
1190 S: ImplicitlyAnimatedWidgetState,
1191 S::Widget: ImplicitlyAnimatedWidget,
1192{
1193 let parent = this
1194 .implicitly_animated_widget_state_data(app)
1195 .controller
1196 .as_ref()
1197 .expect("created in init_state")
1198 .erase();
1199 let curve = Rc::clone(&this.widget(app).implicitly_animated_widget_data().curve);
1200 CurvedAnimation::new(app, parent, curve, None)
1201}
1202
1203fn construct_tweens<S>(this: Handle<S>, app: &mut App) -> bool
1205where
1206 S: ImplicitlyAnimatedWidgetState,
1207 S::Widget: ImplicitlyAnimatedWidget,
1208{
1209 let mut visitor = ConstructTweens {
1210 should_start_animation: false,
1211 };
1212 this.for_each_tween(app, &mut visitor);
1213 visitor.should_start_animation
1214}
1215
1216pub trait AnimatedWidgetBaseState: ImplicitlyAnimatedWidgetState
1227where
1228 Self::Widget: ImplicitlyAnimatedWidget,
1229{
1230 fn init_state(self: Handle<Self>, app: &mut App) {
1232 ImplicitlyAnimatedWidgetState::init_state(self, app);
1233 let controller = self.controller(app);
1234 controller.add_listener(
1235 app,
1236 Listener::handle_method(self, Self::handle_animation_changed),
1237 );
1238 }
1239
1240 fn handle_animation_changed(self: Handle<Self>, app: &mut App) {
1242 self.set_state(app, |_state| {
1243 });
1245 }
1246}
1247
1248#[derive(Debug)]
1274pub struct AnimatedContainer {
1275 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
1276
1277 pub alignment: Option<AlignmentGeometry>,
1285
1286 pub padding: Option<EdgeInsetsGeometry>,
1289
1290 color: Option<AnyColor>,
1293
1294 pub decoration: Option<DecorationRef>,
1299
1300 pub foreground_decoration: Option<DecorationRef>,
1302
1303 pub constraints: Option<BoxConstraints>,
1310 given_constraints: Option<BoxConstraints>,
1311 width: Option<f64>,
1312 height: Option<f64>,
1313
1314 pub margin: Option<EdgeInsetsGeometry>,
1317
1318 pub transform: Option<Matrix4>,
1320
1321 pub transform_alignment: Option<AlignmentGeometry>,
1326
1327 pub child: Option<WidgetRef>,
1334
1335 pub clip_behavior: Clip,
1343}
1344
1345impl AnimatedContainer {
1346 pub fn new(duration: Duration) -> AnimatedContainer {
1348 AnimatedContainer {
1349 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
1350 alignment: None,
1351 padding: None,
1352 color: None,
1353 decoration: None,
1354 foreground_decoration: None,
1355 constraints: None,
1356 given_constraints: None,
1357 width: None,
1358 height: None,
1359 margin: None,
1360 transform: None,
1361 transform_alignment: None,
1362 child: None,
1363 clip_behavior: Clip::None,
1364 }
1365 }
1366
1367 pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedContainer {
1369 self.alignment = Some(alignment);
1370 self
1371 }
1372
1373 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> AnimatedContainer {
1375 let padding = padding.into();
1376 debug_assert!(padding.is_non_negative());
1377 self.padding = Some(padding);
1378 self
1379 }
1380
1381 pub fn color(mut self, color: impl Into<AnyColor>) -> AnimatedContainer {
1384 let color = color.into();
1385 debug_assert!(self.decoration.is_none(), "{CANNOT_PROVIDE_BOTH}");
1386 self.color = Some(color.clone());
1387 self.decoration = Some(DecorationRef::new(BoxDecoration::new().color(color)));
1388 self
1389 }
1390
1391 pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> AnimatedContainer {
1394 debug_assert!(self.color.is_none(), "{CANNOT_PROVIDE_BOTH}");
1395 let decoration = decoration.into();
1396 debug_assert!(decoration.debug_assert_is_valid());
1397 self.decoration = Some(decoration);
1398 self
1399 }
1400
1401 pub fn foreground_decoration(
1403 mut self,
1404 foreground_decoration: impl Into<DecorationRef>,
1405 ) -> AnimatedContainer {
1406 self.foreground_decoration = Some(foreground_decoration.into());
1407 self
1408 }
1409
1410 pub fn width(mut self, width: f64) -> AnimatedContainer {
1412 self.width = Some(width);
1413 self.fold_constraints();
1414 self
1415 }
1416
1417 pub fn height(mut self, height: f64) -> AnimatedContainer {
1419 self.height = Some(height);
1420 self.fold_constraints();
1421 self
1422 }
1423
1424 pub fn constraints(mut self, constraints: BoxConstraints) -> AnimatedContainer {
1426 debug_assert!(constraints.debug_assert_is_valid(false));
1427 self.given_constraints = Some(constraints);
1428 self.fold_constraints();
1429 self
1430 }
1431
1432 pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> AnimatedContainer {
1434 let margin = margin.into();
1435 debug_assert!(margin.is_non_negative());
1436 self.margin = Some(margin);
1437 self
1438 }
1439
1440 pub fn transform(mut self, transform: Matrix4) -> AnimatedContainer {
1442 self.transform = Some(transform);
1443 self
1444 }
1445
1446 pub fn transform_alignment(
1448 mut self,
1449 transform_alignment: AlignmentGeometry,
1450 ) -> AnimatedContainer {
1451 self.transform_alignment = Some(transform_alignment);
1452 self
1453 }
1454
1455 #[cfg_attr(debug_assertions, track_caller)]
1457 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedContainer {
1458 self.child = Some(child.into_widget());
1459 self
1460 }
1461
1462 pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedContainer {
1464 self.clip_behavior = clip_behavior;
1465 self
1466 }
1467
1468 crate::implicitly_animated_widget_setters!(AnimatedContainer);
1469
1470 fn fold_constraints(&mut self) {
1472 self.constraints = if self.width.is_some() || self.height.is_some() {
1473 Some(match self.given_constraints {
1474 Some(constraints) => constraints.tighten(self.width, self.height),
1475 None => BoxConstraints::tight_for(self.width, self.height),
1476 })
1477 } else {
1478 self.given_constraints
1479 };
1480 }
1481}
1482
1483const CANNOT_PROVIDE_BOTH: &str = "Cannot provide both a color and a decoration\n\
1485 The color argument is just a shorthand for \"decoration: BoxDecoration(color: color)\".";
1486
1487impl ImplicitlyAnimatedWidget for AnimatedContainer {
1488 crate::implicitly_animated_widget_accessors!();
1489}
1490
1491impl StatefulWidget for AnimatedContainer {
1492 type State = AnimatedContainerState;
1493
1494 fn key(&self) -> Option<&KeyRef> {
1495 self.implicitly_animated_widget.key.as_ref()
1496 }
1497
1498 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1499 ImplicitlyAnimatedWidgetData::debug_fill_properties(
1500 &self.implicitly_animated_widget,
1501 properties,
1502 );
1503 properties.add(
1504 DiagnosticsProperty::<AlignmentGeometry>::new("alignment", self.alignment)
1505 .with_show_name(false)
1506 .default_value(None),
1507 );
1508 properties.add(
1509 DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
1510 .default_value(None),
1511 );
1512 properties.add(
1513 DiagnosticsProperty::<String>::new(
1514 "bg",
1515 self.decoration
1516 .as_ref()
1517 .map(|decoration| format!("{decoration:?}")),
1518 )
1519 .default_value(None),
1520 );
1521 properties.add(
1522 DiagnosticsProperty::<String>::new(
1523 "fg",
1524 self.foreground_decoration
1525 .as_ref()
1526 .map(|decoration| format!("{decoration:?}")),
1527 )
1528 .default_value(None),
1529 );
1530 properties.add(
1531 DiagnosticsProperty::<BoxConstraints>::new("constraints", self.constraints)
1532 .with_show_name(false)
1533 .default_value(None),
1534 );
1535 properties.add(
1536 DiagnosticsProperty::<EdgeInsetsGeometry>::new("margin", self.margin)
1537 .default_value(None),
1538 );
1539 properties.add(ObjectFlagProperty::<String>::has(
1540 "transform",
1541 self.transform.as_ref().map(|_| String::new()),
1542 ));
1543 properties.add(
1544 DiagnosticsProperty::<AlignmentGeometry>::new(
1545 "transformAlignment",
1546 self.transform_alignment,
1547 )
1548 .default_value(None),
1549 );
1550 properties.add(DiagnosticsProperty::new("clipBehavior", self.clip_behavior));
1551 }
1552
1553 fn create_state(&self) -> AnimatedContainerState {
1554 AnimatedContainerState {
1555 state: StateData::new(),
1556 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1557 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
1558 alignment: None,
1559 padding: None,
1560 decoration: None,
1561 foreground_decoration: None,
1562 constraints: None,
1563 margin: None,
1564 transform: None,
1565 transform_alignment: None,
1566 }
1567 }
1568}
1569
1570pub struct AnimatedContainerState {
1572 state: StateData<AnimatedContainer>,
1573 single_ticker_provider: SingleTickerProviderStateMixinData,
1574 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
1575 alignment: Option<AlignmentGeometryTween>,
1576 padding: Option<EdgeInsetsGeometryTween>,
1577 decoration: Option<DecorationTween>,
1578 foreground_decoration: Option<DecorationTween>,
1579 constraints: Option<BoxConstraintsTween>,
1580 margin: Option<EdgeInsetsGeometryTween>,
1581 transform: Option<Matrix4Tween>,
1582 transform_alignment: Option<AlignmentGeometryTween>,
1583}
1584
1585impl SingleTickerProviderStateMixin for AnimatedContainerState {
1586 fn single_ticker_provider_data(
1587 self: Handle<Self>,
1588 app: &App,
1589 ) -> &SingleTickerProviderStateMixinData {
1590 &app.get(self).single_ticker_provider
1591 }
1592
1593 fn single_ticker_provider_data_mut(
1594 self: Handle<Self>,
1595 app: &mut App,
1596 ) -> &mut SingleTickerProviderStateMixinData {
1597 &mut app.get_mut(self).single_ticker_provider
1598 }
1599}
1600
1601impl TickerProviderObject for AnimatedContainerState {
1602 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1603 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1604 }
1605}
1606
1607impl ImplicitlyAnimatedWidgetState for AnimatedContainerState {
1608 crate::implicitly_animated_widget_state_accessors!();
1609
1610 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
1611 let tween = app.get(self).alignment.clone();
1612 let target = self.widget(app).alignment.map(Some);
1613 app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
1614 AlignmentGeometryTween::new(*value, None)
1615 });
1616 let tween = app.get(self).padding.clone();
1617 let target = self.widget(app).padding;
1618 app.get_mut(self).padding = visitor.visit(app, tween, target, |_app, value| {
1619 EdgeInsetsGeometryTween::new(Some(*value), None)
1620 });
1621 let tween = app.get(self).decoration.clone();
1622 let target = self.widget(app).decoration.clone();
1623 app.get_mut(self).decoration = visitor.visit(app, tween, target, |_app, value| {
1624 DecorationTween::new(Some(value.clone()), None)
1625 });
1626 let tween = app.get(self).foreground_decoration.clone();
1627 let target = self.widget(app).foreground_decoration.clone();
1628 app.get_mut(self).foreground_decoration =
1629 visitor.visit(app, tween, target, |_app, value| {
1630 DecorationTween::new(Some(value.clone()), None)
1631 });
1632 let tween = app.get(self).constraints.clone();
1633 let target = self.widget(app).constraints;
1634 app.get_mut(self).constraints = visitor.visit(app, tween, target, |_app, value| {
1635 BoxConstraintsTween::new(Some(*value), None)
1636 });
1637 let tween = app.get(self).margin.clone();
1638 let target = self.widget(app).margin;
1639 app.get_mut(self).margin = visitor.visit(app, tween, target, |_app, value| {
1640 EdgeInsetsGeometryTween::new(Some(*value), None)
1641 });
1642 let tween = app.get(self).transform.clone();
1643 let target = self.widget(app).transform;
1644 app.get_mut(self).transform = visitor.visit(app, tween, target, |_app, value| {
1645 Matrix4Tween::new(Some(*value), None)
1646 });
1647 let tween = app.get(self).transform_alignment.clone();
1648 let target = self.widget(app).transform_alignment.map(Some);
1649 app.get_mut(self).transform_alignment = visitor.visit(app, tween, target, |_app, value| {
1650 AlignmentGeometryTween::new(*value, None)
1651 });
1652 }
1653}
1654
1655impl AnimatedWidgetBaseState for AnimatedContainerState {}
1656
1657impl State for AnimatedContainerState {
1658 type Widget = AnimatedContainer;
1659 crate::state_accessors!();
1660
1661 fn debug_fill_properties(
1662 self: Handle<Self>,
1663 app: &App,
1664 properties: &mut DiagnosticPropertiesBuilder,
1665 ) {
1666 let state = app.get(self);
1667 properties.add(
1668 DiagnosticsProperty::<String>::new(
1669 "alignment",
1670 state.alignment.as_ref().map(|tween| tween.to_string()),
1671 )
1672 .with_show_name(false)
1673 .default_value(None),
1674 );
1675 properties.add(
1676 DiagnosticsProperty::<String>::new(
1677 "padding",
1678 state.padding.as_ref().map(|tween| tween.to_string()),
1679 )
1680 .default_value(None),
1681 );
1682 properties.add(
1683 DiagnosticsProperty::<String>::new(
1684 "bg",
1685 state.decoration.as_ref().map(|tween| tween.to_string()),
1686 )
1687 .default_value(None),
1688 );
1689 properties.add(
1690 DiagnosticsProperty::<String>::new(
1691 "fg",
1692 state
1693 .foreground_decoration
1694 .as_ref()
1695 .map(|tween| tween.to_string()),
1696 )
1697 .default_value(None),
1698 );
1699 properties.add(
1700 DiagnosticsProperty::<String>::new(
1701 "constraints",
1702 state.constraints.as_ref().map(|tween| tween.to_string()),
1703 )
1704 .with_show_name(false)
1705 .default_value(None),
1706 );
1707 properties.add(
1708 DiagnosticsProperty::<String>::new(
1709 "margin",
1710 state.margin.as_ref().map(|tween| tween.to_string()),
1711 )
1712 .default_value(None),
1713 );
1714 properties.add(ObjectFlagProperty::<String>::has(
1715 "transform",
1716 state.transform.as_ref().map(|_| String::new()),
1717 ));
1718 properties.add(
1719 DiagnosticsProperty::<String>::new(
1720 "transformAlignment",
1721 state
1722 .transform_alignment
1723 .as_ref()
1724 .map(|tween| tween.to_string()),
1725 )
1726 .default_value(None),
1727 );
1728 }
1729
1730 fn init_state(self: Handle<Self>, app: &mut App) {
1731 AnimatedWidgetBaseState::init_state(self, app);
1732 }
1733
1734 fn activate(self: Handle<Self>, app: &mut App) {
1735 SingleTickerProviderStateMixin::activate(self, app);
1736 }
1737
1738 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedContainer) {
1739 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
1740 }
1741
1742 fn dispose(self: Handle<Self>, app: &mut App) {
1743 ImplicitlyAnimatedWidgetState::dispose(self, app);
1744 }
1745
1746 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1747 let animation = self.animation(app);
1748 let state = app.get(self);
1749 let (alignment, padding) = (state.alignment.clone(), state.padding.clone());
1750 let (decoration, foreground_decoration) = (
1751 state.decoration.clone(),
1752 state.foreground_decoration.clone(),
1753 );
1754 let (constraints, margin) = (state.constraints.clone(), state.margin.clone());
1755 let (transform, transform_alignment) =
1756 (state.transform.clone(), state.transform_alignment.clone());
1757 let widget = self.widget(app);
1758 let (clip_behavior, child) = (widget.clip_behavior, widget.child.clone());
1759 let mut container = Container::new().clip_behavior(clip_behavior);
1760 if let Some(alignment) = alignment.and_then(|tween| tween.evaluate(app, animation)) {
1761 container = container.alignment(alignment);
1762 }
1763 if let Some(padding) = padding {
1764 container = container.padding(padding.evaluate(app, animation));
1765 }
1766 if let Some(constraints) = constraints {
1767 container = container.constraints(constraints.evaluate(app, animation));
1768 }
1769 if let Some(margin) = margin {
1770 container = container.margin(margin.evaluate(app, animation));
1771 }
1772 if let Some(transform) = transform {
1773 container = container.transform(transform.evaluate(app, animation));
1774 }
1775 if let Some(transform_alignment) =
1776 transform_alignment.and_then(|tween| tween.evaluate(app, animation))
1777 {
1778 container = container.transform_alignment(transform_alignment);
1779 }
1780 if let Some(child) = child {
1781 container = container.child(child);
1782 }
1783 if let Some(decoration) = decoration.map(|tween| tween.evaluate(app, animation)) {
1784 container = container.decoration(decoration);
1785 }
1786 if let Some(foreground_decoration) =
1787 foreground_decoration.map(|tween| tween.evaluate(app, animation))
1788 {
1789 container = container.foreground_decoration(foreground_decoration);
1790 }
1791 container.into_widget()
1792 }
1793}
1794
1795#[derive(Debug)]
1805pub struct AnimatedPadding {
1806 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
1807
1808 pub padding: EdgeInsetsGeometry,
1810
1811 pub child: Option<WidgetRef>,
1813}
1814
1815impl AnimatedPadding {
1816 pub fn new(padding: impl Into<EdgeInsetsGeometry>, duration: Duration) -> AnimatedPadding {
1819 let padding = padding.into();
1820 debug_assert!(padding.is_non_negative());
1821 AnimatedPadding {
1822 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
1823 padding,
1824 child: None,
1825 }
1826 }
1827
1828 #[cfg_attr(debug_assertions, track_caller)]
1830 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedPadding {
1831 self.child = Some(child.into_widget());
1832 self
1833 }
1834
1835 crate::implicitly_animated_widget_setters!(AnimatedPadding);
1836}
1837
1838impl ImplicitlyAnimatedWidget for AnimatedPadding {
1839 crate::implicitly_animated_widget_accessors!();
1840}
1841
1842impl StatefulWidget for AnimatedPadding {
1843 type State = AnimatedPaddingState;
1844
1845 fn key(&self) -> Option<&KeyRef> {
1846 self.implicitly_animated_widget.key.as_ref()
1847 }
1848
1849 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1850 ImplicitlyAnimatedWidgetData::debug_fill_properties(
1851 &self.implicitly_animated_widget,
1852 properties,
1853 );
1854 properties.add(DiagnosticsProperty::new("padding", self.padding));
1855 }
1856
1857 fn create_state(&self) -> AnimatedPaddingState {
1858 AnimatedPaddingState {
1859 state: StateData::new(),
1860 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1861 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
1862 padding: None,
1863 }
1864 }
1865}
1866
1867pub struct AnimatedPaddingState {
1869 state: StateData<AnimatedPadding>,
1870 single_ticker_provider: SingleTickerProviderStateMixinData,
1871 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
1872 padding: Option<EdgeInsetsGeometryTween>,
1873}
1874
1875impl SingleTickerProviderStateMixin for AnimatedPaddingState {
1876 fn single_ticker_provider_data(
1877 self: Handle<Self>,
1878 app: &App,
1879 ) -> &SingleTickerProviderStateMixinData {
1880 &app.get(self).single_ticker_provider
1881 }
1882
1883 fn single_ticker_provider_data_mut(
1884 self: Handle<Self>,
1885 app: &mut App,
1886 ) -> &mut SingleTickerProviderStateMixinData {
1887 &mut app.get_mut(self).single_ticker_provider
1888 }
1889}
1890
1891impl TickerProviderObject for AnimatedPaddingState {
1892 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1893 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1894 }
1895}
1896
1897impl ImplicitlyAnimatedWidgetState for AnimatedPaddingState {
1898 crate::implicitly_animated_widget_state_accessors!();
1899
1900 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
1901 let tween = app.get(self).padding.clone();
1902 let target = Some(self.widget(app).padding);
1903 app.get_mut(self).padding = visitor.visit(app, tween, target, |_app, value| {
1904 EdgeInsetsGeometryTween::new(Some(*value), None)
1905 });
1906 }
1907}
1908
1909impl AnimatedWidgetBaseState for AnimatedPaddingState {}
1910
1911impl State for AnimatedPaddingState {
1912 type Widget = AnimatedPadding;
1913 crate::state_accessors!();
1914
1915 fn debug_fill_properties(
1916 self: Handle<Self>,
1917 app: &App,
1918 properties: &mut DiagnosticPropertiesBuilder,
1919 ) {
1920 let state = app.get(self);
1921 properties.add(
1922 DiagnosticsProperty::<String>::new(
1923 "padding",
1924 state.padding.as_ref().map(|tween| tween.to_string()),
1925 )
1926 .default_value(None),
1927 );
1928 }
1929
1930 fn init_state(self: Handle<Self>, app: &mut App) {
1931 AnimatedWidgetBaseState::init_state(self, app);
1932 }
1933
1934 fn activate(self: Handle<Self>, app: &mut App) {
1935 SingleTickerProviderStateMixin::activate(self, app);
1936 }
1937
1938 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPadding) {
1939 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
1940 }
1941
1942 fn dispose(self: Handle<Self>, app: &mut App) {
1943 ImplicitlyAnimatedWidgetState::dispose(self, app);
1944 }
1945
1946 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1947 let animation = self.animation(app);
1948 let padding = app
1949 .get(self)
1950 .padding
1951 .clone()
1952 .expect("for_each_tween made the tween");
1953 let child = self.widget(app).child.clone();
1954 let padding = padding
1955 .evaluate(app, animation)
1956 .clamp(&EdgeInsetsGeometry::ZERO, &EdgeInsetsGeometry::INFINITY);
1957 let mut widget = Padding::new(padding);
1958 if let Some(child) = child {
1959 widget = widget.child(child);
1960 }
1961 widget.into_widget()
1962 }
1963}
1964
1965#[derive(Debug)]
1988pub struct AnimatedAlign {
1989 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
1990
1991 pub alignment: AlignmentGeometry,
2001
2002 pub child: Option<WidgetRef>,
2004
2005 pub height_factor: Option<f64>,
2009
2010 pub width_factor: Option<f64>,
2014}
2015
2016impl AnimatedAlign {
2017 pub fn new(alignment: AlignmentGeometry, duration: Duration) -> AnimatedAlign {
2020 AnimatedAlign {
2021 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
2022 alignment,
2023 child: None,
2024 height_factor: None,
2025 width_factor: None,
2026 }
2027 }
2028
2029 #[cfg_attr(debug_assertions, track_caller)]
2031 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedAlign {
2032 self.child = Some(child.into_widget());
2033 self
2034 }
2035
2036 pub fn height_factor(mut self, height_factor: f64) -> AnimatedAlign {
2038 debug_assert!(height_factor >= 0.0);
2039 self.height_factor = Some(height_factor);
2040 self
2041 }
2042
2043 pub fn width_factor(mut self, width_factor: f64) -> AnimatedAlign {
2045 debug_assert!(width_factor >= 0.0);
2046 self.width_factor = Some(width_factor);
2047 self
2048 }
2049
2050 crate::implicitly_animated_widget_setters!(AnimatedAlign);
2051}
2052
2053impl ImplicitlyAnimatedWidget for AnimatedAlign {
2054 crate::implicitly_animated_widget_accessors!();
2055}
2056
2057impl StatefulWidget for AnimatedAlign {
2058 type State = AnimatedAlignState;
2059
2060 fn key(&self) -> Option<&KeyRef> {
2061 self.implicitly_animated_widget.key.as_ref()
2062 }
2063
2064 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2065 ImplicitlyAnimatedWidgetData::debug_fill_properties(
2066 &self.implicitly_animated_widget,
2067 properties,
2068 );
2069 properties.add(DiagnosticsProperty::new("alignment", self.alignment));
2070 }
2071
2072 fn create_state(&self) -> AnimatedAlignState {
2073 AnimatedAlignState {
2074 state: StateData::new(),
2075 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
2076 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
2077 alignment: None,
2078 height_factor_tween: None,
2079 width_factor_tween: None,
2080 }
2081 }
2082}
2083
2084pub struct AnimatedAlignState {
2086 state: StateData<AnimatedAlign>,
2087 single_ticker_provider: SingleTickerProviderStateMixinData,
2088 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
2089 alignment: Option<AlignmentGeometryTween>,
2090 height_factor_tween: Option<Ref<Tween<f64>>>,
2091 width_factor_tween: Option<Ref<Tween<f64>>>,
2092}
2093
2094impl SingleTickerProviderStateMixin for AnimatedAlignState {
2095 fn single_ticker_provider_data(
2096 self: Handle<Self>,
2097 app: &App,
2098 ) -> &SingleTickerProviderStateMixinData {
2099 &app.get(self).single_ticker_provider
2100 }
2101
2102 fn single_ticker_provider_data_mut(
2103 self: Handle<Self>,
2104 app: &mut App,
2105 ) -> &mut SingleTickerProviderStateMixinData {
2106 &mut app.get_mut(self).single_ticker_provider
2107 }
2108}
2109
2110impl TickerProviderObject for AnimatedAlignState {
2111 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2112 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2113 }
2114}
2115
2116impl ImplicitlyAnimatedWidgetState for AnimatedAlignState {
2117 crate::implicitly_animated_widget_state_accessors!();
2118
2119 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
2120 let tween = app.get(self).alignment.clone();
2121 let target = Some(Some(self.widget(app).alignment));
2122 app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
2123 AlignmentGeometryTween::new(*value, None)
2124 });
2125 if self.widget(app).height_factor.is_some() {
2126 let (tween, target) = (
2127 app.get(self).height_factor_tween.clone(),
2128 self.widget(app).height_factor,
2129 );
2130 app.get_mut(self).height_factor_tween = visitor.visit(app, tween, target, double_tween);
2131 }
2132 if self.widget(app).width_factor.is_some() {
2133 let (tween, target) = (
2134 app.get(self).width_factor_tween.clone(),
2135 self.widget(app).width_factor,
2136 );
2137 app.get_mut(self).width_factor_tween = visitor.visit(app, tween, target, double_tween);
2138 }
2139 }
2140}
2141
2142impl AnimatedWidgetBaseState for AnimatedAlignState {}
2143
2144impl State for AnimatedAlignState {
2145 type Widget = AnimatedAlign;
2146 crate::state_accessors!();
2147
2148 fn debug_fill_properties(
2149 self: Handle<Self>,
2150 app: &App,
2151 properties: &mut DiagnosticPropertiesBuilder,
2152 ) {
2153 let state = app.get(self);
2154 properties.add(
2155 DiagnosticsProperty::<String>::new(
2156 "alignment",
2157 state.alignment.as_ref().map(|tween| tween.to_string()),
2158 )
2159 .default_value(None),
2160 );
2161 properties.add(
2162 DiagnosticsProperty::<String>::new(
2163 "widthFactor",
2164 describe_double_tween(state.width_factor_tween.as_ref(), app),
2165 )
2166 .default_value(None),
2167 );
2168 properties.add(
2169 DiagnosticsProperty::<String>::new(
2170 "heightFactor",
2171 describe_double_tween(state.height_factor_tween.as_ref(), app),
2172 )
2173 .default_value(None),
2174 );
2175 }
2176
2177 fn init_state(self: Handle<Self>, app: &mut App) {
2178 AnimatedWidgetBaseState::init_state(self, app);
2179 }
2180
2181 fn activate(self: Handle<Self>, app: &mut App) {
2182 SingleTickerProviderStateMixin::activate(self, app);
2183 }
2184
2185 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedAlign) {
2186 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
2187 }
2188
2189 fn dispose(self: Handle<Self>, app: &mut App) {
2190 ImplicitlyAnimatedWidgetState::dispose(self, app);
2191 }
2192
2193 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2194 let animation = self.animation(app);
2195 let state = app.get(self);
2196 let alignment = state
2197 .alignment
2198 .clone()
2199 .expect("for_each_tween made the tween");
2200 let (height_factor_tween, width_factor_tween) = (
2201 state.height_factor_tween.clone(),
2202 state.width_factor_tween.clone(),
2203 );
2204 let child = self.widget(app).child.clone();
2205 let alignment = alignment
2206 .evaluate(app, animation)
2207 .expect("the tween is built from the widget's alignment");
2208 let mut align = Align::new().alignment(alignment);
2209 if let Some(height_factor) = height_factor_tween {
2210 align = align.height_factor(height_factor.evaluate(app, animation));
2211 }
2212 if let Some(width_factor) = width_factor_tween {
2213 align = align.width_factor(width_factor.evaluate(app, animation));
2214 }
2215 if let Some(child) = child {
2216 align = align.child(child);
2217 }
2218 align.into_widget()
2219 }
2220}
2221
2222#[derive(Debug)]
2246pub struct AnimatedPositioned {
2247 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
2248
2249 pub child: WidgetRef,
2251
2252 pub left: Option<f64>,
2254
2255 pub top: Option<f64>,
2257
2258 pub right: Option<f64>,
2260
2261 pub bottom: Option<f64>,
2263
2264 pub width: Option<f64>,
2269
2270 pub height: Option<f64>,
2276}
2277
2278impl AnimatedPositioned {
2279 #[cfg_attr(debug_assertions, track_caller)]
2287 pub fn new<K>(child: impl IntoWidget<K>, duration: Duration) -> AnimatedPositioned {
2288 AnimatedPositioned {
2289 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
2290 child: child.into_widget(),
2291 left: None,
2292 top: None,
2293 right: None,
2294 bottom: None,
2295 width: None,
2296 height: None,
2297 }
2298 }
2299
2300 #[cfg_attr(debug_assertions, track_caller)]
2302 pub fn from_rect<K>(
2303 child: impl IntoWidget<K>,
2304 rect: Rect,
2305 duration: Duration,
2306 ) -> AnimatedPositioned {
2307 AnimatedPositioned {
2308 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
2309 child: child.into_widget(),
2310 left: Some(rect.left),
2311 top: Some(rect.top),
2312 right: None,
2313 bottom: None,
2314 width: Some(rect.width()),
2315 height: Some(rect.height()),
2316 }
2317 }
2318
2319 pub fn left(mut self, left: f64) -> AnimatedPositioned {
2321 self.left = Some(left);
2322 self.debug_check_axes();
2323 self
2324 }
2325
2326 pub fn top(mut self, top: f64) -> AnimatedPositioned {
2328 self.top = Some(top);
2329 self.debug_check_axes();
2330 self
2331 }
2332
2333 pub fn right(mut self, right: f64) -> AnimatedPositioned {
2335 self.right = Some(right);
2336 self.debug_check_axes();
2337 self
2338 }
2339
2340 pub fn bottom(mut self, bottom: f64) -> AnimatedPositioned {
2342 self.bottom = Some(bottom);
2343 self.debug_check_axes();
2344 self
2345 }
2346
2347 pub fn width(mut self, width: f64) -> AnimatedPositioned {
2349 self.width = Some(width);
2350 self.debug_check_axes();
2351 self
2352 }
2353
2354 pub fn height(mut self, height: f64) -> AnimatedPositioned {
2356 self.height = Some(height);
2357 self.debug_check_axes();
2358 self
2359 }
2360
2361 crate::implicitly_animated_widget_setters!(AnimatedPositioned);
2362
2363 fn debug_check_axes(&self) {
2365 debug_assert!(
2366 self.left.is_none() || self.right.is_none() || self.width.is_none(),
2367 "Only two out of `left`, `right` and `width` can be set."
2368 );
2369 debug_assert!(
2370 self.top.is_none() || self.bottom.is_none() || self.height.is_none(),
2371 "Only two out of `top`, `bottom` and `height` can be set."
2372 );
2373 }
2374}
2375
2376impl ImplicitlyAnimatedWidget for AnimatedPositioned {
2377 crate::implicitly_animated_widget_accessors!();
2378}
2379
2380impl StatefulWidget for AnimatedPositioned {
2381 type State = AnimatedPositionedState;
2382
2383 fn key(&self) -> Option<&KeyRef> {
2384 self.implicitly_animated_widget.key.as_ref()
2385 }
2386
2387 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2388 ImplicitlyAnimatedWidgetData::debug_fill_properties(
2389 &self.implicitly_animated_widget,
2390 properties,
2391 );
2392 properties.add(DoubleProperty::new("left", self.left).default_value(None));
2393 properties.add(DoubleProperty::new("top", self.top).default_value(None));
2394 properties.add(DoubleProperty::new("right", self.right).default_value(None));
2395 properties.add(DoubleProperty::new("bottom", self.bottom).default_value(None));
2396 properties.add(DoubleProperty::new("width", self.width).default_value(None));
2397 properties.add(DoubleProperty::new("height", self.height).default_value(None));
2398 }
2399
2400 fn create_state(&self) -> AnimatedPositionedState {
2401 AnimatedPositionedState {
2402 state: StateData::new(),
2403 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
2404 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
2405 left: None,
2406 top: None,
2407 right: None,
2408 bottom: None,
2409 width: None,
2410 height: None,
2411 }
2412 }
2413}
2414
2415pub struct AnimatedPositionedState {
2417 state: StateData<AnimatedPositioned>,
2418 single_ticker_provider: SingleTickerProviderStateMixinData,
2419 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
2420 left: Option<Ref<Tween<f64>>>,
2421 top: Option<Ref<Tween<f64>>>,
2422 right: Option<Ref<Tween<f64>>>,
2423 bottom: Option<Ref<Tween<f64>>>,
2424 width: Option<Ref<Tween<f64>>>,
2425 height: Option<Ref<Tween<f64>>>,
2426}
2427
2428impl SingleTickerProviderStateMixin for AnimatedPositionedState {
2429 fn single_ticker_provider_data(
2430 self: Handle<Self>,
2431 app: &App,
2432 ) -> &SingleTickerProviderStateMixinData {
2433 &app.get(self).single_ticker_provider
2434 }
2435
2436 fn single_ticker_provider_data_mut(
2437 self: Handle<Self>,
2438 app: &mut App,
2439 ) -> &mut SingleTickerProviderStateMixinData {
2440 &mut app.get_mut(self).single_ticker_provider
2441 }
2442}
2443
2444impl TickerProviderObject for AnimatedPositionedState {
2445 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2446 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2447 }
2448}
2449
2450impl ImplicitlyAnimatedWidgetState for AnimatedPositionedState {
2451 crate::implicitly_animated_widget_state_accessors!();
2452
2453 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
2454 let (tween, target) = (app.get(self).left.clone(), self.widget(app).left);
2455 app.get_mut(self).left = visitor.visit(app, tween, target, double_tween);
2456 let (tween, target) = (app.get(self).top.clone(), self.widget(app).top);
2457 app.get_mut(self).top = visitor.visit(app, tween, target, double_tween);
2458 let (tween, target) = (app.get(self).right.clone(), self.widget(app).right);
2459 app.get_mut(self).right = visitor.visit(app, tween, target, double_tween);
2460 let (tween, target) = (app.get(self).bottom.clone(), self.widget(app).bottom);
2461 app.get_mut(self).bottom = visitor.visit(app, tween, target, double_tween);
2462 let (tween, target) = (app.get(self).width.clone(), self.widget(app).width);
2463 app.get_mut(self).width = visitor.visit(app, tween, target, double_tween);
2464 let (tween, target) = (app.get(self).height.clone(), self.widget(app).height);
2465 app.get_mut(self).height = visitor.visit(app, tween, target, double_tween);
2466 }
2467}
2468
2469impl AnimatedWidgetBaseState for AnimatedPositionedState {}
2470
2471impl State for AnimatedPositionedState {
2472 type Widget = AnimatedPositioned;
2473 crate::state_accessors!();
2474
2475 fn debug_fill_properties(
2476 self: Handle<Self>,
2477 app: &App,
2478 properties: &mut DiagnosticPropertiesBuilder,
2479 ) {
2480 let state = app.get(self);
2481 properties.add(ObjectFlagProperty::<String>::has(
2482 "left",
2483 state.left.as_ref().map(|_| String::new()),
2484 ));
2485 properties.add(ObjectFlagProperty::<String>::has(
2486 "top",
2487 state.top.as_ref().map(|_| String::new()),
2488 ));
2489 properties.add(ObjectFlagProperty::<String>::has(
2490 "right",
2491 state.right.as_ref().map(|_| String::new()),
2492 ));
2493 properties.add(ObjectFlagProperty::<String>::has(
2494 "bottom",
2495 state.bottom.as_ref().map(|_| String::new()),
2496 ));
2497 properties.add(ObjectFlagProperty::<String>::has(
2498 "width",
2499 state.width.as_ref().map(|_| String::new()),
2500 ));
2501 properties.add(ObjectFlagProperty::<String>::has(
2502 "height",
2503 state.height.as_ref().map(|_| String::new()),
2504 ));
2505 }
2506
2507 fn init_state(self: Handle<Self>, app: &mut App) {
2508 AnimatedWidgetBaseState::init_state(self, app);
2509 }
2510
2511 fn activate(self: Handle<Self>, app: &mut App) {
2512 SingleTickerProviderStateMixin::activate(self, app);
2513 }
2514
2515 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPositioned) {
2516 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
2517 }
2518
2519 fn dispose(self: Handle<Self>, app: &mut App) {
2520 ImplicitlyAnimatedWidgetState::dispose(self, app);
2521 }
2522
2523 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2524 let animation = self.animation(app);
2525 let state = app.get(self);
2526 let (left, top, right) = (state.left.clone(), state.top.clone(), state.right.clone());
2527 let (bottom, width, height) = (
2528 state.bottom.clone(),
2529 state.width.clone(),
2530 state.height.clone(),
2531 );
2532 let mut positioned = Positioned::new(self.widget(app).child.clone());
2533 if let Some(left) = left {
2534 positioned = positioned.left(left.evaluate(app, animation));
2535 }
2536 if let Some(top) = top {
2537 positioned = positioned.top(top.evaluate(app, animation));
2538 }
2539 if let Some(right) = right {
2540 positioned = positioned.right(right.evaluate(app, animation));
2541 }
2542 if let Some(bottom) = bottom {
2543 positioned = positioned.bottom(bottom.evaluate(app, animation));
2544 }
2545 if let Some(width) = width {
2546 positioned = positioned.width(width.evaluate(app, animation));
2547 }
2548 if let Some(height) = height {
2549 positioned = positioned.height(height.evaluate(app, animation));
2550 }
2551 positioned.into_widget()
2552 }
2553}
2554
2555#[derive(Debug)]
2569pub struct AnimatedPositionedDirectional {
2570 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
2571
2572 pub child: WidgetRef,
2574
2575 pub start: Option<f64>,
2577
2578 pub top: Option<f64>,
2580
2581 pub end: Option<f64>,
2583
2584 pub bottom: Option<f64>,
2586
2587 pub width: Option<f64>,
2592
2593 pub height: Option<f64>,
2599}
2600
2601impl AnimatedPositionedDirectional {
2602 #[cfg_attr(debug_assertions, track_caller)]
2609 pub fn new<K>(child: impl IntoWidget<K>, duration: Duration) -> AnimatedPositionedDirectional {
2610 AnimatedPositionedDirectional {
2611 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
2612 child: child.into_widget(),
2613 start: None,
2614 top: None,
2615 end: None,
2616 bottom: None,
2617 width: None,
2618 height: None,
2619 }
2620 }
2621
2622 pub fn start(mut self, start: f64) -> AnimatedPositionedDirectional {
2624 self.start = Some(start);
2625 self.debug_check_axes();
2626 self
2627 }
2628
2629 pub fn top(mut self, top: f64) -> AnimatedPositionedDirectional {
2631 self.top = Some(top);
2632 self.debug_check_axes();
2633 self
2634 }
2635
2636 pub fn end(mut self, end: f64) -> AnimatedPositionedDirectional {
2638 self.end = Some(end);
2639 self.debug_check_axes();
2640 self
2641 }
2642
2643 pub fn bottom(mut self, bottom: f64) -> AnimatedPositionedDirectional {
2645 self.bottom = Some(bottom);
2646 self.debug_check_axes();
2647 self
2648 }
2649
2650 pub fn width(mut self, width: f64) -> AnimatedPositionedDirectional {
2652 self.width = Some(width);
2653 self.debug_check_axes();
2654 self
2655 }
2656
2657 pub fn height(mut self, height: f64) -> AnimatedPositionedDirectional {
2659 self.height = Some(height);
2660 self.debug_check_axes();
2661 self
2662 }
2663
2664 crate::implicitly_animated_widget_setters!(AnimatedPositionedDirectional);
2665
2666 fn debug_check_axes(&self) {
2668 debug_assert!(
2669 self.start.is_none() || self.end.is_none() || self.width.is_none(),
2670 "Only two out of `start`, `end` and `width` can be set."
2671 );
2672 debug_assert!(
2673 self.top.is_none() || self.bottom.is_none() || self.height.is_none(),
2674 "Only two out of `top`, `bottom` and `height` can be set."
2675 );
2676 }
2677}
2678
2679impl ImplicitlyAnimatedWidget for AnimatedPositionedDirectional {
2680 crate::implicitly_animated_widget_accessors!();
2681}
2682
2683impl StatefulWidget for AnimatedPositionedDirectional {
2684 type State = AnimatedPositionedDirectionalState;
2685
2686 fn key(&self) -> Option<&KeyRef> {
2687 self.implicitly_animated_widget.key.as_ref()
2688 }
2689
2690 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2691 ImplicitlyAnimatedWidgetData::debug_fill_properties(
2692 &self.implicitly_animated_widget,
2693 properties,
2694 );
2695 properties.add(DoubleProperty::new("start", self.start).default_value(None));
2696 properties.add(DoubleProperty::new("top", self.top).default_value(None));
2697 properties.add(DoubleProperty::new("end", self.end).default_value(None));
2698 properties.add(DoubleProperty::new("bottom", self.bottom).default_value(None));
2699 properties.add(DoubleProperty::new("width", self.width).default_value(None));
2700 properties.add(DoubleProperty::new("height", self.height).default_value(None));
2701 }
2702
2703 fn create_state(&self) -> AnimatedPositionedDirectionalState {
2704 AnimatedPositionedDirectionalState {
2705 state: StateData::new(),
2706 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
2707 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
2708 start: None,
2709 top: None,
2710 end: None,
2711 bottom: None,
2712 width: None,
2713 height: None,
2714 }
2715 }
2716}
2717
2718pub struct AnimatedPositionedDirectionalState {
2720 state: StateData<AnimatedPositionedDirectional>,
2721 single_ticker_provider: SingleTickerProviderStateMixinData,
2722 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
2723 start: Option<Ref<Tween<f64>>>,
2724 top: Option<Ref<Tween<f64>>>,
2725 end: Option<Ref<Tween<f64>>>,
2726 bottom: Option<Ref<Tween<f64>>>,
2727 width: Option<Ref<Tween<f64>>>,
2728 height: Option<Ref<Tween<f64>>>,
2729}
2730
2731impl SingleTickerProviderStateMixin for AnimatedPositionedDirectionalState {
2732 fn single_ticker_provider_data(
2733 self: Handle<Self>,
2734 app: &App,
2735 ) -> &SingleTickerProviderStateMixinData {
2736 &app.get(self).single_ticker_provider
2737 }
2738
2739 fn single_ticker_provider_data_mut(
2740 self: Handle<Self>,
2741 app: &mut App,
2742 ) -> &mut SingleTickerProviderStateMixinData {
2743 &mut app.get_mut(self).single_ticker_provider
2744 }
2745}
2746
2747impl TickerProviderObject for AnimatedPositionedDirectionalState {
2748 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2749 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2750 }
2751}
2752
2753impl ImplicitlyAnimatedWidgetState for AnimatedPositionedDirectionalState {
2754 crate::implicitly_animated_widget_state_accessors!();
2755
2756 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
2757 let (tween, target) = (app.get(self).start.clone(), self.widget(app).start);
2758 app.get_mut(self).start = visitor.visit(app, tween, target, double_tween);
2759 let (tween, target) = (app.get(self).top.clone(), self.widget(app).top);
2760 app.get_mut(self).top = visitor.visit(app, tween, target, double_tween);
2761 let (tween, target) = (app.get(self).end.clone(), self.widget(app).end);
2762 app.get_mut(self).end = visitor.visit(app, tween, target, double_tween);
2763 let (tween, target) = (app.get(self).bottom.clone(), self.widget(app).bottom);
2764 app.get_mut(self).bottom = visitor.visit(app, tween, target, double_tween);
2765 let (tween, target) = (app.get(self).width.clone(), self.widget(app).width);
2766 app.get_mut(self).width = visitor.visit(app, tween, target, double_tween);
2767 let (tween, target) = (app.get(self).height.clone(), self.widget(app).height);
2768 app.get_mut(self).height = visitor.visit(app, tween, target, double_tween);
2769 }
2770}
2771
2772impl AnimatedWidgetBaseState for AnimatedPositionedDirectionalState {}
2773
2774impl State for AnimatedPositionedDirectionalState {
2775 type Widget = AnimatedPositionedDirectional;
2776 crate::state_accessors!();
2777
2778 fn debug_fill_properties(
2779 self: Handle<Self>,
2780 app: &App,
2781 properties: &mut DiagnosticPropertiesBuilder,
2782 ) {
2783 let state = app.get(self);
2784 properties.add(ObjectFlagProperty::<String>::has(
2785 "start",
2786 state.start.as_ref().map(|_| String::new()),
2787 ));
2788 properties.add(ObjectFlagProperty::<String>::has(
2789 "top",
2790 state.top.as_ref().map(|_| String::new()),
2791 ));
2792 properties.add(ObjectFlagProperty::<String>::has(
2793 "end",
2794 state.end.as_ref().map(|_| String::new()),
2795 ));
2796 properties.add(ObjectFlagProperty::<String>::has(
2797 "bottom",
2798 state.bottom.as_ref().map(|_| String::new()),
2799 ));
2800 properties.add(ObjectFlagProperty::<String>::has(
2801 "width",
2802 state.width.as_ref().map(|_| String::new()),
2803 ));
2804 properties.add(ObjectFlagProperty::<String>::has(
2805 "height",
2806 state.height.as_ref().map(|_| String::new()),
2807 ));
2808 }
2809
2810 fn init_state(self: Handle<Self>, app: &mut App) {
2811 AnimatedWidgetBaseState::init_state(self, app);
2812 }
2813
2814 fn activate(self: Handle<Self>, app: &mut App) {
2815 SingleTickerProviderStateMixin::activate(self, app);
2816 }
2817
2818 fn did_update_widget(
2819 self: Handle<Self>,
2820 app: &mut App,
2821 old_widget: &AnimatedPositionedDirectional,
2822 ) {
2823 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
2824 }
2825
2826 fn dispose(self: Handle<Self>, app: &mut App) {
2827 ImplicitlyAnimatedWidgetState::dispose(self, app);
2828 }
2829
2830 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2831 let animation = self.animation(app);
2832 let state = app.get(self);
2833 let (start, top, end) = (state.start.clone(), state.top.clone(), state.end.clone());
2834 let (bottom, width, height) = (
2835 state.bottom.clone(),
2836 state.width.clone(),
2837 state.height.clone(),
2838 );
2839 let text_direction = Directionality::of(app, context);
2840 let start = start.map(|start| start.evaluate(app, animation));
2841 let end = end.map(|end| end.evaluate(app, animation));
2842 let mut positioned =
2843 Positioned::directional(text_direction, start, end, self.widget(app).child.clone());
2844 if let Some(top) = top {
2845 positioned = positioned.top(top.evaluate(app, animation));
2846 }
2847 if let Some(bottom) = bottom {
2848 positioned = positioned.bottom(bottom.evaluate(app, animation));
2849 }
2850 if let Some(width) = width {
2851 positioned = positioned.width(width.evaluate(app, animation));
2852 }
2853 if let Some(height) = height {
2854 positioned = positioned.height(height.evaluate(app, animation));
2855 }
2856 positioned.into_widget()
2857 }
2858}
2859
2860#[derive(Debug)]
2869pub struct AnimatedScale {
2870 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
2871
2872 pub child: Option<WidgetRef>,
2874
2875 pub scale: f64,
2877
2878 pub alignment: Alignment,
2884
2885 pub filter_quality: Option<FilterQuality>,
2891}
2892
2893impl AnimatedScale {
2894 pub fn new(scale: f64, duration: Duration) -> AnimatedScale {
2896 AnimatedScale {
2897 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
2898 child: None,
2899 scale,
2900 alignment: Alignment::CENTER,
2901 filter_quality: None,
2902 }
2903 }
2904
2905 #[cfg_attr(debug_assertions, track_caller)]
2907 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedScale {
2908 self.child = Some(child.into_widget());
2909 self
2910 }
2911
2912 pub fn alignment(mut self, alignment: Alignment) -> AnimatedScale {
2914 self.alignment = alignment;
2915 self
2916 }
2917
2918 pub fn filter_quality(mut self, filter_quality: FilterQuality) -> AnimatedScale {
2920 self.filter_quality = Some(filter_quality);
2921 self
2922 }
2923
2924 crate::implicitly_animated_widget_setters!(AnimatedScale);
2925}
2926
2927impl ImplicitlyAnimatedWidget for AnimatedScale {
2928 crate::implicitly_animated_widget_accessors!();
2929}
2930
2931impl StatefulWidget for AnimatedScale {
2932 type State = AnimatedScaleState;
2933
2934 fn key(&self) -> Option<&KeyRef> {
2935 self.implicitly_animated_widget.key.as_ref()
2936 }
2937
2938 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2939 ImplicitlyAnimatedWidgetData::debug_fill_properties(
2940 &self.implicitly_animated_widget,
2941 properties,
2942 );
2943 properties.add(DoubleProperty::new("scale", self.scale));
2944 properties.add(
2945 DiagnosticsProperty::<Alignment>::new("alignment", Some(self.alignment))
2946 .default_value(Some(Alignment::CENTER)),
2947 );
2948 properties.add(
2949 EnumProperty::<FilterQuality>::new("filterQuality", self.filter_quality)
2950 .default_value(None),
2951 );
2952 }
2953
2954 fn create_state(&self) -> AnimatedScaleState {
2955 AnimatedScaleState {
2956 state: StateData::new(),
2957 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
2958 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
2959 scale: None,
2960 scale_animation: None,
2961 }
2962 }
2963}
2964
2965pub struct AnimatedScaleState {
2967 state: StateData<AnimatedScale>,
2968 single_ticker_provider: SingleTickerProviderStateMixinData,
2969 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
2970 scale: Option<Ref<Tween<f64>>>,
2971 scale_animation: Option<AnimationRef<f64>>,
2972}
2973
2974impl SingleTickerProviderStateMixin for AnimatedScaleState {
2975 fn single_ticker_provider_data(
2976 self: Handle<Self>,
2977 app: &App,
2978 ) -> &SingleTickerProviderStateMixinData {
2979 &app.get(self).single_ticker_provider
2980 }
2981
2982 fn single_ticker_provider_data_mut(
2983 self: Handle<Self>,
2984 app: &mut App,
2985 ) -> &mut SingleTickerProviderStateMixinData {
2986 &mut app.get_mut(self).single_ticker_provider
2987 }
2988}
2989
2990impl TickerProviderObject for AnimatedScaleState {
2991 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2992 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2993 }
2994}
2995
2996impl ImplicitlyAnimatedWidgetState for AnimatedScaleState {
2997 crate::implicitly_animated_widget_state_accessors!();
2998
2999 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
3000 let (tween, target) = (app.get(self).scale.clone(), Some(self.widget(app).scale));
3001 app.get_mut(self).scale = visitor.visit(app, tween, target, double_tween);
3002 }
3003
3004 fn did_update_tweens(self: Handle<Self>, app: &mut App) {
3005 let scale = app
3006 .get(self)
3007 .scale
3008 .clone()
3009 .expect("for_each_tween made the tween");
3010 let animation = self.animation(app).keep(app);
3011 let scale_animation = animation.drive(app, scale);
3012 app.get_mut(self).scale_animation = Some(scale_animation);
3013 }
3014}
3015
3016impl State for AnimatedScaleState {
3017 type Widget = AnimatedScale;
3018 crate::state_accessors!();
3019
3020 fn init_state(self: Handle<Self>, app: &mut App) {
3021 ImplicitlyAnimatedWidgetState::init_state(self, app);
3022 }
3023
3024 fn activate(self: Handle<Self>, app: &mut App) {
3025 SingleTickerProviderStateMixin::activate(self, app);
3026 }
3027
3028 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedScale) {
3029 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
3030 }
3031
3032 fn dispose(self: Handle<Self>, app: &mut App) {
3033 ImplicitlyAnimatedWidgetState::dispose(self, app);
3034 }
3035
3036 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3037 let scale = app
3038 .get(self)
3039 .scale_animation
3040 .clone()
3041 .expect("did_update_tweens drove the animation");
3042 let widget = self.widget(app);
3043 let (alignment, filter_quality, child) = (
3044 widget.alignment,
3045 widget.filter_quality,
3046 widget.child.clone(),
3047 );
3048 let mut transition = ScaleTransition::new(scale).alignment(alignment);
3049 transition.filter_quality = filter_quality;
3050 if let Some(child) = child {
3051 transition = transition.child(child);
3052 }
3053 transition.into_widget()
3054 }
3055}
3056
3057#[derive(Debug)]
3066pub struct AnimatedRotation {
3067 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
3068
3069 pub child: Option<WidgetRef>,
3071
3072 pub turns: f64,
3077
3078 pub alignment: Alignment,
3084
3085 pub filter_quality: Option<FilterQuality>,
3091}
3092
3093impl AnimatedRotation {
3094 pub fn new(turns: f64, duration: Duration) -> AnimatedRotation {
3096 AnimatedRotation {
3097 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
3098 child: None,
3099 turns,
3100 alignment: Alignment::CENTER,
3101 filter_quality: None,
3102 }
3103 }
3104
3105 #[cfg_attr(debug_assertions, track_caller)]
3107 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedRotation {
3108 self.child = Some(child.into_widget());
3109 self
3110 }
3111
3112 pub fn alignment(mut self, alignment: Alignment) -> AnimatedRotation {
3114 self.alignment = alignment;
3115 self
3116 }
3117
3118 pub fn filter_quality(mut self, filter_quality: FilterQuality) -> AnimatedRotation {
3120 self.filter_quality = Some(filter_quality);
3121 self
3122 }
3123
3124 crate::implicitly_animated_widget_setters!(AnimatedRotation);
3125}
3126
3127impl ImplicitlyAnimatedWidget for AnimatedRotation {
3128 crate::implicitly_animated_widget_accessors!();
3129}
3130
3131impl StatefulWidget for AnimatedRotation {
3132 type State = AnimatedRotationState;
3133
3134 fn key(&self) -> Option<&KeyRef> {
3135 self.implicitly_animated_widget.key.as_ref()
3136 }
3137
3138 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3139 ImplicitlyAnimatedWidgetData::debug_fill_properties(
3140 &self.implicitly_animated_widget,
3141 properties,
3142 );
3143 properties.add(DoubleProperty::new("turns", self.turns));
3144 properties.add(
3145 DiagnosticsProperty::<Alignment>::new("alignment", Some(self.alignment))
3146 .default_value(Some(Alignment::CENTER)),
3147 );
3148 properties.add(
3149 EnumProperty::<FilterQuality>::new("filterQuality", self.filter_quality)
3150 .default_value(None),
3151 );
3152 }
3153
3154 fn create_state(&self) -> AnimatedRotationState {
3155 AnimatedRotationState {
3156 state: StateData::new(),
3157 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
3158 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
3159 turns: None,
3160 turns_animation: None,
3161 }
3162 }
3163}
3164
3165pub struct AnimatedRotationState {
3167 state: StateData<AnimatedRotation>,
3168 single_ticker_provider: SingleTickerProviderStateMixinData,
3169 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
3170 turns: Option<Ref<Tween<f64>>>,
3171 turns_animation: Option<AnimationRef<f64>>,
3172}
3173
3174impl SingleTickerProviderStateMixin for AnimatedRotationState {
3175 fn single_ticker_provider_data(
3176 self: Handle<Self>,
3177 app: &App,
3178 ) -> &SingleTickerProviderStateMixinData {
3179 &app.get(self).single_ticker_provider
3180 }
3181
3182 fn single_ticker_provider_data_mut(
3183 self: Handle<Self>,
3184 app: &mut App,
3185 ) -> &mut SingleTickerProviderStateMixinData {
3186 &mut app.get_mut(self).single_ticker_provider
3187 }
3188}
3189
3190impl TickerProviderObject for AnimatedRotationState {
3191 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3192 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
3193 }
3194}
3195
3196impl ImplicitlyAnimatedWidgetState for AnimatedRotationState {
3197 crate::implicitly_animated_widget_state_accessors!();
3198
3199 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
3200 let (tween, target) = (app.get(self).turns.clone(), Some(self.widget(app).turns));
3201 app.get_mut(self).turns = visitor.visit(app, tween, target, double_tween);
3202 }
3203
3204 fn did_update_tweens(self: Handle<Self>, app: &mut App) {
3205 let turns = app
3206 .get(self)
3207 .turns
3208 .clone()
3209 .expect("for_each_tween made the tween");
3210 let animation = self.animation(app).keep(app);
3211 let turns_animation = animation.drive(app, turns);
3212 app.get_mut(self).turns_animation = Some(turns_animation);
3213 }
3214}
3215
3216impl State for AnimatedRotationState {
3217 type Widget = AnimatedRotation;
3218 crate::state_accessors!();
3219
3220 fn init_state(self: Handle<Self>, app: &mut App) {
3221 ImplicitlyAnimatedWidgetState::init_state(self, app);
3222 }
3223
3224 fn activate(self: Handle<Self>, app: &mut App) {
3225 SingleTickerProviderStateMixin::activate(self, app);
3226 }
3227
3228 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedRotation) {
3229 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
3230 }
3231
3232 fn dispose(self: Handle<Self>, app: &mut App) {
3233 ImplicitlyAnimatedWidgetState::dispose(self, app);
3234 }
3235
3236 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3237 let turns = app
3238 .get(self)
3239 .turns_animation
3240 .clone()
3241 .expect("did_update_tweens drove the animation");
3242 let widget = self.widget(app);
3243 let (alignment, filter_quality, child) = (
3244 widget.alignment,
3245 widget.filter_quality,
3246 widget.child.clone(),
3247 );
3248 let mut transition = RotationTransition::new(turns).alignment(alignment);
3249 transition.filter_quality = filter_quality;
3250 if let Some(child) = child {
3251 transition = transition.child(child);
3252 }
3253 transition.into_widget()
3254 }
3255}
3256
3257#[derive(Debug)]
3273pub struct AnimatedSlide {
3274 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
3275
3276 pub child: Option<WidgetRef>,
3278
3279 pub offset: Offset,
3284}
3285
3286impl AnimatedSlide {
3287 pub fn new(offset: Offset, duration: Duration) -> AnimatedSlide {
3289 AnimatedSlide {
3290 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
3291 child: None,
3292 offset,
3293 }
3294 }
3295
3296 #[cfg_attr(debug_assertions, track_caller)]
3298 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedSlide {
3299 self.child = Some(child.into_widget());
3300 self
3301 }
3302
3303 crate::implicitly_animated_widget_setters!(AnimatedSlide);
3304}
3305
3306impl ImplicitlyAnimatedWidget for AnimatedSlide {
3307 crate::implicitly_animated_widget_accessors!();
3308}
3309
3310impl StatefulWidget for AnimatedSlide {
3311 type State = AnimatedSlideState;
3312
3313 fn key(&self) -> Option<&KeyRef> {
3314 self.implicitly_animated_widget.key.as_ref()
3315 }
3316
3317 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3318 ImplicitlyAnimatedWidgetData::debug_fill_properties(
3319 &self.implicitly_animated_widget,
3320 properties,
3321 );
3322 properties.add(DiagnosticsProperty::new("offset", self.offset));
3323 }
3324
3325 fn create_state(&self) -> AnimatedSlideState {
3326 AnimatedSlideState {
3327 state: StateData::new(),
3328 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
3329 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
3330 offset: None,
3331 offset_animation: None,
3332 }
3333 }
3334}
3335
3336pub struct AnimatedSlideState {
3338 state: StateData<AnimatedSlide>,
3339 single_ticker_provider: SingleTickerProviderStateMixinData,
3340 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
3341 offset: Option<Ref<Tween<Offset>>>,
3342 offset_animation: Option<AnimationRef<Offset>>,
3343}
3344
3345impl SingleTickerProviderStateMixin for AnimatedSlideState {
3346 fn single_ticker_provider_data(
3347 self: Handle<Self>,
3348 app: &App,
3349 ) -> &SingleTickerProviderStateMixinData {
3350 &app.get(self).single_ticker_provider
3351 }
3352
3353 fn single_ticker_provider_data_mut(
3354 self: Handle<Self>,
3355 app: &mut App,
3356 ) -> &mut SingleTickerProviderStateMixinData {
3357 &mut app.get_mut(self).single_ticker_provider
3358 }
3359}
3360
3361impl TickerProviderObject for AnimatedSlideState {
3362 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3363 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
3364 }
3365}
3366
3367impl ImplicitlyAnimatedWidgetState for AnimatedSlideState {
3368 crate::implicitly_animated_widget_state_accessors!();
3369
3370 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
3371 let (tween, target) = (app.get(self).offset.clone(), Some(self.widget(app).offset));
3372 app.get_mut(self).offset = visitor.visit(app, tween, target, offset_tween);
3373 }
3374
3375 fn did_update_tweens(self: Handle<Self>, app: &mut App) {
3376 let offset = app
3377 .get(self)
3378 .offset
3379 .clone()
3380 .expect("for_each_tween made the tween");
3381 let animation = self.animation(app).keep(app);
3382 let offset_animation = animation.drive(app, offset);
3383 app.get_mut(self).offset_animation = Some(offset_animation);
3384 }
3385}
3386
3387impl State for AnimatedSlideState {
3388 type Widget = AnimatedSlide;
3389 crate::state_accessors!();
3390
3391 fn init_state(self: Handle<Self>, app: &mut App) {
3392 ImplicitlyAnimatedWidgetState::init_state(self, app);
3393 }
3394
3395 fn activate(self: Handle<Self>, app: &mut App) {
3396 SingleTickerProviderStateMixin::activate(self, app);
3397 }
3398
3399 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedSlide) {
3400 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
3401 }
3402
3403 fn dispose(self: Handle<Self>, app: &mut App) {
3404 ImplicitlyAnimatedWidgetState::dispose(self, app);
3405 }
3406
3407 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3408 let position = app
3409 .get(self)
3410 .offset_animation
3411 .clone()
3412 .expect("did_update_tweens drove the animation");
3413 let child = self.widget(app).child.clone();
3414 let mut transition = SlideTransition::new(position);
3415 if let Some(child) = child {
3416 transition = transition.child(child);
3417 }
3418 transition.into_widget()
3419 }
3420}
3421
3422#[derive(Debug)]
3446pub struct AnimatedOpacity {
3447 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
3448
3449 pub child: Option<WidgetRef>,
3451
3452 pub opacity: f64,
3457}
3458
3459impl AnimatedOpacity {
3460 pub fn new(opacity: f64, duration: Duration) -> AnimatedOpacity {
3464 debug_assert!((0.0..=1.0).contains(&opacity));
3465 AnimatedOpacity {
3466 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
3467 child: None,
3468 opacity,
3469 }
3470 }
3471
3472 #[cfg_attr(debug_assertions, track_caller)]
3474 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedOpacity {
3475 self.child = Some(child.into_widget());
3476 self
3477 }
3478
3479 crate::implicitly_animated_widget_setters!(AnimatedOpacity);
3480}
3481
3482impl ImplicitlyAnimatedWidget for AnimatedOpacity {
3483 crate::implicitly_animated_widget_accessors!();
3484}
3485
3486impl StatefulWidget for AnimatedOpacity {
3487 type State = AnimatedOpacityState;
3488
3489 fn key(&self) -> Option<&KeyRef> {
3490 self.implicitly_animated_widget.key.as_ref()
3491 }
3492
3493 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3494 ImplicitlyAnimatedWidgetData::debug_fill_properties(
3495 &self.implicitly_animated_widget,
3496 properties,
3497 );
3498 properties.add(DoubleProperty::new("opacity", self.opacity));
3499 }
3500
3501 fn create_state(&self) -> AnimatedOpacityState {
3502 AnimatedOpacityState {
3503 state: StateData::new(),
3504 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
3505 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
3506 opacity: None,
3507 opacity_animation: None,
3508 }
3509 }
3510}
3511
3512pub struct AnimatedOpacityState {
3514 state: StateData<AnimatedOpacity>,
3515 single_ticker_provider: SingleTickerProviderStateMixinData,
3516 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
3517 opacity: Option<Ref<Tween<f64>>>,
3518 opacity_animation: Option<AnimationRef<f64>>,
3519}
3520
3521impl SingleTickerProviderStateMixin for AnimatedOpacityState {
3522 fn single_ticker_provider_data(
3523 self: Handle<Self>,
3524 app: &App,
3525 ) -> &SingleTickerProviderStateMixinData {
3526 &app.get(self).single_ticker_provider
3527 }
3528
3529 fn single_ticker_provider_data_mut(
3530 self: Handle<Self>,
3531 app: &mut App,
3532 ) -> &mut SingleTickerProviderStateMixinData {
3533 &mut app.get_mut(self).single_ticker_provider
3534 }
3535}
3536
3537impl TickerProviderObject for AnimatedOpacityState {
3538 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3539 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
3540 }
3541}
3542
3543impl ImplicitlyAnimatedWidgetState for AnimatedOpacityState {
3544 crate::implicitly_animated_widget_state_accessors!();
3545
3546 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
3547 let (tween, target) = (
3548 app.get(self).opacity.clone(),
3549 Some(self.widget(app).opacity),
3550 );
3551 app.get_mut(self).opacity = visitor.visit(app, tween, target, double_tween);
3552 }
3553
3554 fn did_update_tweens(self: Handle<Self>, app: &mut App) {
3555 let opacity = app
3556 .get(self)
3557 .opacity
3558 .clone()
3559 .expect("for_each_tween made the tween");
3560 let animation = self.animation(app).keep(app);
3561 let opacity_animation = animation.drive(app, opacity);
3562 app.get_mut(self).opacity_animation = Some(opacity_animation);
3563 }
3564}
3565
3566impl State for AnimatedOpacityState {
3567 type Widget = AnimatedOpacity;
3568 crate::state_accessors!();
3569
3570 fn init_state(self: Handle<Self>, app: &mut App) {
3571 ImplicitlyAnimatedWidgetState::init_state(self, app);
3572 }
3573
3574 fn activate(self: Handle<Self>, app: &mut App) {
3575 SingleTickerProviderStateMixin::activate(self, app);
3576 }
3577
3578 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedOpacity) {
3579 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
3580 }
3581
3582 fn dispose(self: Handle<Self>, app: &mut App) {
3583 ImplicitlyAnimatedWidgetState::dispose(self, app);
3584 }
3585
3586 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3587 let opacity = app
3588 .get(self)
3589 .opacity_animation
3590 .clone()
3591 .expect("did_update_tweens drove the animation");
3592 let child = self.widget(app).child.clone();
3593 let mut transition = FadeTransition::new(opacity);
3594 if let Some(child) = child {
3595 transition = transition.child(child);
3596 }
3597 transition.into_widget()
3598 }
3599}
3600
3601#[derive(Debug)]
3618pub struct AnimatedDefaultTextStyle {
3619 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
3620
3621 pub child: WidgetRef,
3623
3624 pub style: TextStyle,
3629
3630 pub text_align: Option<TextAlign>,
3634
3635 pub soft_wrap: bool,
3641
3642 pub overflow: TextOverflow,
3646
3647 pub max_lines: Option<i32>,
3653
3654 pub text_width_basis: TextWidthBasis,
3656
3657 pub text_height_behavior: Option<TextHeightBehavior>,
3659}
3660
3661impl AnimatedDefaultTextStyle {
3662 #[cfg_attr(debug_assertions, track_caller)]
3664 pub fn new<K>(
3665 child: impl IntoWidget<K>,
3666 style: TextStyle,
3667 duration: Duration,
3668 ) -> AnimatedDefaultTextStyle {
3669 AnimatedDefaultTextStyle {
3670 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
3671 child: child.into_widget(),
3672 style,
3673 text_align: None,
3674 soft_wrap: true,
3675 overflow: TextOverflow::Clip,
3676 max_lines: None,
3677 text_width_basis: TextWidthBasis::Parent,
3678 text_height_behavior: None,
3679 }
3680 }
3681
3682 pub fn text_align(mut self, text_align: TextAlign) -> AnimatedDefaultTextStyle {
3684 self.text_align = Some(text_align);
3685 self
3686 }
3687
3688 pub fn soft_wrap(mut self, soft_wrap: bool) -> AnimatedDefaultTextStyle {
3690 self.soft_wrap = soft_wrap;
3691 self
3692 }
3693
3694 pub fn overflow(mut self, overflow: TextOverflow) -> AnimatedDefaultTextStyle {
3696 self.overflow = overflow;
3697 self
3698 }
3699
3700 pub fn max_lines(mut self, max_lines: i32) -> AnimatedDefaultTextStyle {
3702 debug_assert!(max_lines > 0);
3703 self.max_lines = Some(max_lines);
3704 self
3705 }
3706
3707 pub fn text_width_basis(
3709 mut self,
3710 text_width_basis: TextWidthBasis,
3711 ) -> AnimatedDefaultTextStyle {
3712 self.text_width_basis = text_width_basis;
3713 self
3714 }
3715
3716 pub fn text_height_behavior(
3718 mut self,
3719 text_height_behavior: TextHeightBehavior,
3720 ) -> AnimatedDefaultTextStyle {
3721 self.text_height_behavior = Some(text_height_behavior);
3722 self
3723 }
3724
3725 crate::implicitly_animated_widget_setters!(AnimatedDefaultTextStyle);
3726}
3727
3728impl ImplicitlyAnimatedWidget for AnimatedDefaultTextStyle {
3729 crate::implicitly_animated_widget_accessors!();
3730}
3731
3732impl StatefulWidget for AnimatedDefaultTextStyle {
3733 type State = AnimatedDefaultTextStyleState;
3734
3735 fn key(&self) -> Option<&KeyRef> {
3736 self.implicitly_animated_widget.key.as_ref()
3737 }
3738
3739 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
3740 ImplicitlyAnimatedWidgetData::debug_fill_properties(
3741 &self.implicitly_animated_widget,
3742 properties,
3743 );
3744 waft_foundation::Diagnosticable::debug_fill_properties(&self.style, properties);
3745 properties
3746 .add(EnumProperty::<TextAlign>::new("textAlign", self.text_align).default_value(None));
3747 properties.add(
3748 FlagProperty::new("softWrap", Some(self.soft_wrap))
3749 .if_true("wrapping at box width")
3750 .if_false("no wrapping except at line break characters")
3751 .with_show_name(true),
3752 );
3753 properties.add(EnumProperty::new("overflow", self.overflow).default_value(None));
3754 properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).default_value(None));
3755 properties.add(
3756 EnumProperty::new("textWidthBasis", self.text_width_basis)
3757 .default_value(Some(TextWidthBasis::Parent)),
3758 );
3759 properties.add(
3760 DiagnosticsProperty::<String>::new(
3761 "textHeightBehavior",
3762 self.text_height_behavior
3763 .map(|behavior| behavior.to_string()),
3764 )
3765 .default_value(None),
3766 );
3767 }
3768
3769 fn create_state(&self) -> AnimatedDefaultTextStyleState {
3770 AnimatedDefaultTextStyleState {
3771 state: StateData::new(),
3772 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
3773 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
3774 style: None,
3775 }
3776 }
3777}
3778
3779pub struct AnimatedDefaultTextStyleState {
3781 state: StateData<AnimatedDefaultTextStyle>,
3782 single_ticker_provider: SingleTickerProviderStateMixinData,
3783 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
3784 style: Option<TextStyleTween>,
3785}
3786
3787impl SingleTickerProviderStateMixin for AnimatedDefaultTextStyleState {
3788 fn single_ticker_provider_data(
3789 self: Handle<Self>,
3790 app: &App,
3791 ) -> &SingleTickerProviderStateMixinData {
3792 &app.get(self).single_ticker_provider
3793 }
3794
3795 fn single_ticker_provider_data_mut(
3796 self: Handle<Self>,
3797 app: &mut App,
3798 ) -> &mut SingleTickerProviderStateMixinData {
3799 &mut app.get_mut(self).single_ticker_provider
3800 }
3801}
3802
3803impl TickerProviderObject for AnimatedDefaultTextStyleState {
3804 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3805 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
3806 }
3807}
3808
3809impl ImplicitlyAnimatedWidgetState for AnimatedDefaultTextStyleState {
3810 crate::implicitly_animated_widget_state_accessors!();
3811
3812 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
3813 let tween = app.get(self).style.clone();
3814 let target = self.widget(app).style.clone();
3815 app.get_mut(self).style = visitor.visit(app, tween, Some(target), |_app, value| {
3816 TextStyleTween::new(Some(value.clone()), None)
3817 });
3818 }
3819}
3820
3821impl AnimatedWidgetBaseState for AnimatedDefaultTextStyleState {}
3822
3823impl State for AnimatedDefaultTextStyleState {
3824 type Widget = AnimatedDefaultTextStyle;
3825 crate::state_accessors!();
3826
3827 fn init_state(self: Handle<Self>, app: &mut App) {
3828 AnimatedWidgetBaseState::init_state(self, app);
3829 }
3830
3831 fn activate(self: Handle<Self>, app: &mut App) {
3832 SingleTickerProviderStateMixin::activate(self, app);
3833 }
3834
3835 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedDefaultTextStyle) {
3836 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
3837 }
3838
3839 fn dispose(self: Handle<Self>, app: &mut App) {
3840 ImplicitlyAnimatedWidgetState::dispose(self, app);
3841 }
3842
3843 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3844 let animation = self.animation(app);
3845 let style = app
3846 .get(self)
3847 .style
3848 .clone()
3849 .expect("for_each_tween made the tween");
3850 let widget = self.widget(app);
3851 let (text_align, soft_wrap, overflow) =
3852 (widget.text_align, widget.soft_wrap, widget.overflow);
3853 let (max_lines, text_width_basis) = (widget.max_lines, widget.text_width_basis);
3854 let text_height_behavior = widget.text_height_behavior;
3855 let child = widget.child.clone();
3856 let mut default_text_style = DefaultTextStyle::new(style.evaluate(app, animation), child)
3857 .soft_wrap(soft_wrap)
3858 .overflow(overflow)
3859 .text_width_basis(text_width_basis);
3860 if let Some(text_align) = text_align {
3861 default_text_style = default_text_style.text_align(text_align);
3862 }
3863 if let Some(max_lines) = max_lines {
3864 default_text_style = default_text_style.max_lines(max_lines);
3865 }
3866 if let Some(text_height_behavior) = text_height_behavior {
3867 default_text_style = default_text_style.text_height_behavior(text_height_behavior);
3868 }
3869 default_text_style.into_widget()
3870 }
3871}
3872
3873#[derive(Debug)]
3888pub struct AnimatedPhysicalModel {
3889 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
3890
3891 pub child: WidgetRef,
3893
3894 pub shape: BoxShape,
3898
3899 pub clip_behavior: Clip,
3903
3904 pub border_radius: Option<BorderRadius>,
3906
3907 pub elevation: f64,
3912
3913 pub color: AnyColor,
3915
3916 pub animate_color: bool,
3918
3919 pub shadow_color: AnyColor,
3921
3922 pub animate_shadow_color: bool,
3924}
3925
3926impl AnimatedPhysicalModel {
3927 #[cfg_attr(debug_assertions, track_caller)]
3933 pub fn new<K>(
3934 child: impl IntoWidget<K>,
3935 color: impl Into<AnyColor>,
3936 shadow_color: impl Into<AnyColor>,
3937 duration: Duration,
3938 ) -> AnimatedPhysicalModel {
3939 AnimatedPhysicalModel {
3940 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
3941 child: child.into_widget(),
3942 shape: BoxShape::Rectangle,
3943 clip_behavior: Clip::None,
3944 border_radius: None,
3945 elevation: 0.0,
3946 color: color.into(),
3947 animate_color: true,
3948 shadow_color: shadow_color.into(),
3949 animate_shadow_color: true,
3950 }
3951 }
3952
3953 pub fn shape(mut self, shape: BoxShape) -> AnimatedPhysicalModel {
3955 self.shape = shape;
3956 self
3957 }
3958
3959 pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedPhysicalModel {
3961 self.clip_behavior = clip_behavior;
3962 self
3963 }
3964
3965 pub fn border_radius(mut self, border_radius: BorderRadius) -> AnimatedPhysicalModel {
3967 self.border_radius = Some(border_radius);
3968 self
3969 }
3970
3971 pub fn elevation(mut self, elevation: f64) -> AnimatedPhysicalModel {
3973 debug_assert!(elevation >= 0.0);
3974 self.elevation = elevation;
3975 self
3976 }
3977
3978 pub fn animate_color(mut self, animate_color: bool) -> AnimatedPhysicalModel {
3980 self.animate_color = animate_color;
3981 self
3982 }
3983
3984 pub fn animate_shadow_color(mut self, animate_shadow_color: bool) -> AnimatedPhysicalModel {
3986 self.animate_shadow_color = animate_shadow_color;
3987 self
3988 }
3989
3990 crate::implicitly_animated_widget_setters!(AnimatedPhysicalModel);
3991}
3992
3993impl ImplicitlyAnimatedWidget for AnimatedPhysicalModel {
3994 crate::implicitly_animated_widget_accessors!();
3995}
3996
3997impl StatefulWidget for AnimatedPhysicalModel {
3998 type State = AnimatedPhysicalModelState;
3999
4000 fn key(&self) -> Option<&KeyRef> {
4001 self.implicitly_animated_widget.key.as_ref()
4002 }
4003
4004 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4005 ImplicitlyAnimatedWidgetData::debug_fill_properties(
4006 &self.implicitly_animated_widget,
4007 properties,
4008 );
4009 properties.add(EnumProperty::new("shape", self.shape));
4010 properties.add(DiagnosticsProperty::<BorderRadius>::new(
4011 "borderRadius",
4012 self.border_radius,
4013 ));
4014 properties.add(DoubleProperty::new("elevation", self.elevation));
4015 properties.add(ColorProperty::new("color", self.color.color()));
4016 properties.add(DiagnosticsProperty::new("animateColor", self.animate_color));
4017 properties.add(ColorProperty::new("shadowColor", self.shadow_color.color()));
4018 properties.add(DiagnosticsProperty::new(
4019 "animateShadowColor",
4020 self.animate_shadow_color,
4021 ));
4022 }
4023
4024 fn create_state(&self) -> AnimatedPhysicalModelState {
4025 AnimatedPhysicalModelState {
4026 state: StateData::new(),
4027 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
4028 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
4029 border_radius: None,
4030 elevation: None,
4031 color: None,
4032 shadow_color: None,
4033 }
4034 }
4035}
4036
4037pub struct AnimatedPhysicalModelState {
4039 state: StateData<AnimatedPhysicalModel>,
4040 single_ticker_provider: SingleTickerProviderStateMixinData,
4041 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
4042 border_radius: Option<BorderRadiusTween>,
4043 elevation: Option<Ref<Tween<f64>>>,
4044 color: Option<Ref<ColorTween>>,
4045 shadow_color: Option<Ref<ColorTween>>,
4046}
4047
4048impl SingleTickerProviderStateMixin for AnimatedPhysicalModelState {
4049 fn single_ticker_provider_data(
4050 self: Handle<Self>,
4051 app: &App,
4052 ) -> &SingleTickerProviderStateMixinData {
4053 &app.get(self).single_ticker_provider
4054 }
4055
4056 fn single_ticker_provider_data_mut(
4057 self: Handle<Self>,
4058 app: &mut App,
4059 ) -> &mut SingleTickerProviderStateMixinData {
4060 &mut app.get_mut(self).single_ticker_provider
4061 }
4062}
4063
4064impl TickerProviderObject for AnimatedPhysicalModelState {
4065 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
4066 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
4067 }
4068}
4069
4070impl ImplicitlyAnimatedWidgetState for AnimatedPhysicalModelState {
4071 crate::implicitly_animated_widget_state_accessors!();
4072
4073 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
4074 let tween = app.get(self).border_radius.clone();
4075 let target = self.widget(app).border_radius.unwrap_or(BorderRadius::ZERO);
4076 app.get_mut(self).border_radius =
4077 visitor.visit(app, tween, Some(Some(target)), |_app, value| {
4078 BorderRadiusTween::new(*value, None)
4079 });
4080 let (tween, target) = (
4081 app.get(self).elevation.clone(),
4082 Some(self.widget(app).elevation),
4083 );
4084 app.get_mut(self).elevation = visitor.visit(app, tween, target, double_tween);
4085 let (tween, target) = (app.get(self).color.clone(), self.widget(app).color.color());
4086 app.get_mut(self).color = visitor.visit(app, tween, Some(Some(target)), color_tween);
4087 let (tween, target) = (
4088 app.get(self).shadow_color.clone(),
4089 self.widget(app).shadow_color.color(),
4090 );
4091 app.get_mut(self).shadow_color = visitor.visit(app, tween, Some(Some(target)), color_tween);
4092 }
4093}
4094
4095impl AnimatedWidgetBaseState for AnimatedPhysicalModelState {}
4096
4097impl State for AnimatedPhysicalModelState {
4098 type Widget = AnimatedPhysicalModel;
4099 crate::state_accessors!();
4100
4101 fn init_state(self: Handle<Self>, app: &mut App) {
4102 AnimatedWidgetBaseState::init_state(self, app);
4103 }
4104
4105 fn activate(self: Handle<Self>, app: &mut App) {
4106 SingleTickerProviderStateMixin::activate(self, app);
4107 }
4108
4109 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPhysicalModel) {
4110 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
4111 }
4112
4113 fn dispose(self: Handle<Self>, app: &mut App) {
4114 ImplicitlyAnimatedWidgetState::dispose(self, app);
4115 }
4116
4117 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
4118 let animation = self.animation(app);
4119 let state = app.get(self);
4120 let border_radius = state
4121 .border_radius
4122 .clone()
4123 .expect("for_each_tween made the tween");
4124 let elevation = state
4125 .elevation
4126 .clone()
4127 .expect("for_each_tween made the tween");
4128 let color = state.color.clone().expect("for_each_tween made the tween");
4129 let shadow_color = state
4130 .shadow_color
4131 .clone()
4132 .expect("for_each_tween made the tween");
4133 let widget = self.widget(app);
4134 let (shape, clip_behavior, child) =
4135 (widget.shape, widget.clip_behavior, widget.child.clone());
4136 let (animate_color, widget_color) = (widget.animate_color, widget.color.clone());
4137 let (animate_shadow_color, widget_shadow_color) =
4138 (widget.animate_shadow_color, widget.shadow_color.clone());
4139 let mut physical_model = PhysicalModel::new(if animate_color {
4140 AnyColor::new(
4141 color
4142 .evaluate(app, animation)
4143 .expect("a colour tween between colours"),
4144 )
4145 } else {
4146 widget_color
4147 })
4148 .shape(shape)
4149 .clip_behavior(clip_behavior)
4150 .elevation(elevation.evaluate(app, animation))
4151 .shadow_color(if animate_shadow_color {
4152 AnyColor::new(
4153 shadow_color
4154 .evaluate(app, animation)
4155 .expect("a colour tween between colours"),
4156 )
4157 } else {
4158 widget_shadow_color
4159 })
4160 .child(child);
4161 physical_model.border_radius = border_radius.evaluate(app, animation);
4162 physical_model.into_widget()
4163 }
4164}
4165
4166#[derive(Debug)]
4186pub struct AnimatedFractionallySizedBox {
4187 implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
4188
4189 pub child: Option<WidgetRef>,
4191
4192 pub height_factor: Option<f64>,
4194
4195 pub width_factor: Option<f64>,
4197
4198 pub alignment: AlignmentGeometry,
4200}
4201
4202impl AnimatedFractionallySizedBox {
4203 pub fn new(duration: Duration) -> AnimatedFractionallySizedBox {
4207 AnimatedFractionallySizedBox {
4208 implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
4209 child: None,
4210 height_factor: None,
4211 width_factor: None,
4212 alignment: AlignmentGeometry::CENTER,
4213 }
4214 }
4215
4216 pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedFractionallySizedBox {
4218 self.alignment = alignment;
4219 self
4220 }
4221
4222 #[cfg_attr(debug_assertions, track_caller)]
4224 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedFractionallySizedBox {
4225 self.child = Some(child.into_widget());
4226 self
4227 }
4228
4229 pub fn height_factor(mut self, height_factor: f64) -> AnimatedFractionallySizedBox {
4231 debug_assert!(height_factor >= 0.0);
4232 self.height_factor = Some(height_factor);
4233 self
4234 }
4235
4236 pub fn width_factor(mut self, width_factor: f64) -> AnimatedFractionallySizedBox {
4238 debug_assert!(width_factor >= 0.0);
4239 self.width_factor = Some(width_factor);
4240 self
4241 }
4242
4243 crate::implicitly_animated_widget_setters!(AnimatedFractionallySizedBox);
4244}
4245
4246impl ImplicitlyAnimatedWidget for AnimatedFractionallySizedBox {
4247 crate::implicitly_animated_widget_accessors!();
4248}
4249
4250impl StatefulWidget for AnimatedFractionallySizedBox {
4251 type State = AnimatedFractionallySizedBoxState;
4252
4253 fn key(&self) -> Option<&KeyRef> {
4254 self.implicitly_animated_widget.key.as_ref()
4255 }
4256
4257 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
4258 ImplicitlyAnimatedWidgetData::debug_fill_properties(
4259 &self.implicitly_animated_widget,
4260 properties,
4261 );
4262 properties.add(DiagnosticsProperty::new("alignment", self.alignment));
4263 properties.add(DiagnosticsProperty::<f64>::new(
4264 "widthFactor",
4265 self.width_factor,
4266 ));
4267 properties.add(DiagnosticsProperty::<f64>::new(
4268 "heightFactor",
4269 self.height_factor,
4270 ));
4271 }
4272
4273 fn create_state(&self) -> AnimatedFractionallySizedBoxState {
4274 AnimatedFractionallySizedBoxState {
4275 state: StateData::new(),
4276 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
4277 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
4278 alignment: None,
4279 height_factor_tween: None,
4280 width_factor_tween: None,
4281 }
4282 }
4283}
4284
4285pub struct AnimatedFractionallySizedBoxState {
4287 state: StateData<AnimatedFractionallySizedBox>,
4288 single_ticker_provider: SingleTickerProviderStateMixinData,
4289 implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
4290 alignment: Option<AlignmentGeometryTween>,
4291 height_factor_tween: Option<Ref<Tween<f64>>>,
4292 width_factor_tween: Option<Ref<Tween<f64>>>,
4293}
4294
4295impl SingleTickerProviderStateMixin for AnimatedFractionallySizedBoxState {
4296 fn single_ticker_provider_data(
4297 self: Handle<Self>,
4298 app: &App,
4299 ) -> &SingleTickerProviderStateMixinData {
4300 &app.get(self).single_ticker_provider
4301 }
4302
4303 fn single_ticker_provider_data_mut(
4304 self: Handle<Self>,
4305 app: &mut App,
4306 ) -> &mut SingleTickerProviderStateMixinData {
4307 &mut app.get_mut(self).single_ticker_provider
4308 }
4309}
4310
4311impl TickerProviderObject for AnimatedFractionallySizedBoxState {
4312 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
4313 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
4314 }
4315}
4316
4317impl ImplicitlyAnimatedWidgetState for AnimatedFractionallySizedBoxState {
4318 crate::implicitly_animated_widget_state_accessors!();
4319
4320 fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
4321 let tween = app.get(self).alignment.clone();
4322 let target = Some(Some(self.widget(app).alignment));
4323 app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
4324 AlignmentGeometryTween::new(*value, None)
4325 });
4326 if self.widget(app).height_factor.is_some() {
4327 let (tween, target) = (
4328 app.get(self).height_factor_tween.clone(),
4329 self.widget(app).height_factor,
4330 );
4331 app.get_mut(self).height_factor_tween = visitor.visit(app, tween, target, double_tween);
4332 }
4333 if self.widget(app).width_factor.is_some() {
4334 let (tween, target) = (
4335 app.get(self).width_factor_tween.clone(),
4336 self.widget(app).width_factor,
4337 );
4338 app.get_mut(self).width_factor_tween = visitor.visit(app, tween, target, double_tween);
4339 }
4340 }
4341}
4342
4343impl AnimatedWidgetBaseState for AnimatedFractionallySizedBoxState {}
4344
4345impl State for AnimatedFractionallySizedBoxState {
4346 type Widget = AnimatedFractionallySizedBox;
4347 crate::state_accessors!();
4348
4349 fn debug_fill_properties(
4350 self: Handle<Self>,
4351 app: &App,
4352 properties: &mut DiagnosticPropertiesBuilder,
4353 ) {
4354 let state = app.get(self);
4355 properties.add(
4356 DiagnosticsProperty::<String>::new(
4357 "alignment",
4358 state.alignment.as_ref().map(|tween| tween.to_string()),
4359 )
4360 .default_value(None),
4361 );
4362 properties.add(
4363 DiagnosticsProperty::<String>::new(
4364 "widthFactor",
4365 describe_double_tween(state.width_factor_tween.as_ref(), app),
4366 )
4367 .default_value(None),
4368 );
4369 properties.add(
4370 DiagnosticsProperty::<String>::new(
4371 "heightFactor",
4372 describe_double_tween(state.height_factor_tween.as_ref(), app),
4373 )
4374 .default_value(None),
4375 );
4376 }
4377
4378 fn init_state(self: Handle<Self>, app: &mut App) {
4379 AnimatedWidgetBaseState::init_state(self, app);
4380 }
4381
4382 fn activate(self: Handle<Self>, app: &mut App) {
4383 SingleTickerProviderStateMixin::activate(self, app);
4384 }
4385
4386 fn did_update_widget(
4387 self: Handle<Self>,
4388 app: &mut App,
4389 old_widget: &AnimatedFractionallySizedBox,
4390 ) {
4391 ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
4392 }
4393
4394 fn dispose(self: Handle<Self>, app: &mut App) {
4395 ImplicitlyAnimatedWidgetState::dispose(self, app);
4396 }
4397
4398 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
4399 let animation = self.animation(app);
4400 let state = app.get(self);
4401 let alignment = state
4402 .alignment
4403 .clone()
4404 .expect("for_each_tween made the tween");
4405 let (height_factor_tween, width_factor_tween) = (
4406 state.height_factor_tween.clone(),
4407 state.width_factor_tween.clone(),
4408 );
4409 let child = self.widget(app).child.clone();
4410 let alignment = alignment
4411 .evaluate(app, animation)
4412 .expect("the tween is built from the widget's alignment");
4413 let mut box_ = FractionallySizedBox::new().alignment(alignment);
4414 if let Some(height_factor) = height_factor_tween {
4415 box_ = box_.height_factor(height_factor.evaluate(app, animation));
4416 }
4417 if let Some(width_factor) = width_factor_tween {
4418 box_ = box_.width_factor(width_factor.evaluate(app, animation));
4419 }
4420 if let Some(child) = child {
4421 box_ = box_.child(child);
4422 }
4423 box_.into_widget()
4424 }
4425}
4426
4427fn double_tween(app: &mut App, value: &f64) -> Ref<Tween<f64>> {
4430 Tween::new(app, Some(*value), None)
4431}
4432
4433fn color_tween(app: &mut App, value: &Option<Color>) -> Ref<ColorTween> {
4435 ColorTween::new(app, *value, None)
4436}
4437
4438fn offset_tween(app: &mut App, value: &Offset) -> Ref<Tween<Offset>> {
4440 Tween::new(app, Some(*value), None)
4441}
4442
4443#[cfg(test)]
4444mod tests {
4445 use std::cell::{Cell, RefCell};
4446 use waft_foundation::AppCell;
4447 use waft_painting::Decoration;
4448
4449 use waft_embedder::{Size, TextDirection};
4450 use waft_rendering::{RenderAnimatedOpacity, RenderAnimatedOpacityMixin};
4451
4452 use super::*;
4453 use crate::binding::WidgetsBinding;
4454 use crate::framework::GlobalKey;
4455 use crate::testing::{WidgetTester, find, test_widgets};
4456 use crate::view::View;
4457 use crate::widgets::basic::{Align, Builder, Directionality, SizedBox, Stack};
4458 use crate::widgets::text::Text;
4459 use waft_rendering::RenderHandle;
4460
4461 const DURATION: Duration = Duration::from_millis(100);
4462
4463 fn ms(milliseconds: u64) -> Duration {
4464 Duration::from_millis(milliseconds)
4465 }
4466
4467 fn positioned_tree(key: &GlobalKey, width: f64, on_end: Option<Listener>) -> WidgetRef {
4468 let mut positioned = AnimatedPositioned::new(SizedBox::expand(), DURATION)
4469 .key(key.clone().into())
4470 .left(0.0)
4471 .top(0.0)
4472 .width(width)
4473 .height(10.0);
4474 if let Some(on_end) = on_end {
4475 positioned = positioned.on_end(on_end);
4476 }
4477 Directionality::new(
4478 TextDirection::Ltr,
4479 Stack::new().children([positioned.into_widget()]),
4480 )
4481 .into_widget()
4482 }
4483
4484 #[test]
4485 fn an_animated_positioned_animates_its_box_and_calls_on_end_once() {
4486 test_widgets(|tester| {
4487 let key = GlobalKey::new();
4488 let ends = Rc::new(Cell::new(0));
4489 let counted = Rc::clone(&ends);
4490 let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
4491 tester.pump_widget(positioned_tree(&key, 20.0, Some(on_end.clone())));
4492 assert_eq!(
4493 tester.get_size(&key),
4494 Size::new(20.0, 10.0),
4495 "the first build does not animate"
4496 );
4497
4498 tester.pump_widget(positioned_tree(&key, 40.0, Some(on_end)));
4499 assert_eq!(
4500 tester.get_size(&key).width(),
4501 20.0,
4502 "the frame that starts the animation still shows the old width"
4503 );
4504
4505 tester.pump_by(ms(50));
4506 let halfway = tester.get_size(&key).width();
4507 assert!(
4508 (halfway - 30.0).abs() < 0.001,
4509 "halfway between 20 and 40, not {halfway}"
4510 );
4511 assert_eq!(ends.get(), 0, "the animation is still running");
4512
4513 tester.pump_by(ms(50));
4514 assert_eq!(tester.get_size(&key).width(), 40.0);
4515 assert_eq!(
4516 ends.get(),
4517 0,
4518 "the controller completes on the first tick past the duration"
4519 );
4520
4521 tester.pump_by(ms(50));
4522 assert_eq!(ends.get(), 1);
4523
4524 tester.pump_by(ms(50));
4525 assert_eq!(ends.get(), 1, "on_end fires once per animation");
4526 });
4527 }
4528
4529 fn opacity_tree(key: &GlobalKey, opacity: f64) -> WidgetRef {
4530 AnimatedOpacity::new(opacity, DURATION)
4531 .key(key.clone().into())
4532 .child(SizedBox::square(Some(10.0)))
4533 .into_widget()
4534 }
4535
4536 fn opacity_of(tester: &WidgetTester, key: &GlobalKey) -> f64 {
4537 let render_object = tester.render_object(key);
4538 let app = tester.cell.borrow();
4539 let render_object = render_object
4540 .downcast::<RenderAnimatedOpacity>(&app)
4541 .expect("a RenderAnimatedOpacity");
4542 RenderAnimatedOpacityMixin::opacity(render_object, &app).value(&app)
4543 }
4544
4545 #[test]
4546 fn an_animated_opacity_reaches_its_target_after_the_duration() {
4547 test_widgets(|tester| {
4548 let key = GlobalKey::new();
4549 tester.pump_widget(opacity_tree(&key, 1.0));
4550 assert_eq!(opacity_of(tester, &key), 1.0);
4551
4552 tester.pump_widget(opacity_tree(&key, 0.0));
4553 assert_eq!(opacity_of(tester, &key), 1.0);
4554
4555 tester.pump_by(ms(50));
4556 let halfway = opacity_of(tester, &key);
4557 assert!((halfway - 0.5).abs() < 0.001, "{halfway}");
4558
4559 tester.pump_by(ms(50));
4560 assert_eq!(opacity_of(tester, &key), 0.0);
4561 });
4562 }
4563
4564 #[test]
4565 fn a_new_target_mid_flight_retargets_from_the_value_on_screen() {
4566 test_widgets(|tester| {
4567 let key = GlobalKey::new();
4568 tester.pump_widget(opacity_tree(&key, 0.0));
4569 tester.pump_widget(opacity_tree(&key, 1.0));
4570 tester.pump_by(ms(50));
4571 let midpoint = opacity_of(tester, &key);
4572 assert!((midpoint - 0.5).abs() < 0.001, "{midpoint}");
4573
4574 tester.pump_widget(opacity_tree(&key, 0.0));
4575 assert!(
4576 (opacity_of(tester, &key) - midpoint).abs() < 0.001,
4577 "the restarted animation still shows the value on screen"
4578 );
4579
4580 tester.pump_by(ms(50));
4581 let quarter = opacity_of(tester, &key);
4582 assert!(
4583 (quarter - 0.25).abs() < 0.001,
4584 "the new tween runs from the value on screen, not from 1.0: {quarter}"
4585 );
4586
4587 tester.pump_by(ms(50));
4588 assert_eq!(opacity_of(tester, &key), 0.0);
4589 });
4590 }
4591
4592 fn text_style_tree(font_size: f64, seen: &Rc<RefCell<Option<TextStyle>>>) -> WidgetRef {
4593 let seen = Rc::clone(seen);
4594 AnimatedDefaultTextStyle::new(
4595 Builder::new(move |app, context| {
4596 *seen.borrow_mut() = Some(DefaultTextStyle::of(app, context).style);
4597 SizedBox::square(Some(10.0)).into_widget()
4598 }),
4599 TextStyle::new().font_size(font_size),
4600 DURATION,
4601 )
4602 .into_widget()
4603 }
4604
4605 #[test]
4606 fn an_animated_default_text_style_interpolates_the_style() {
4607 test_widgets(|tester| {
4608 let seen: Rc<RefCell<Option<TextStyle>>> = Rc::new(RefCell::new(None));
4609 let font_size = || {
4610 seen.borrow()
4611 .as_ref()
4612 .expect("the builder ran")
4613 .font_size
4614 .expect("a font size")
4615 };
4616 tester.pump_widget(text_style_tree(10.0, &seen));
4617 assert_eq!(font_size(), 10.0);
4618
4619 tester.pump_widget(text_style_tree(20.0, &seen));
4620 assert_eq!(font_size(), 10.0);
4621
4622 tester.pump_by(ms(50));
4623 let halfway = font_size();
4624 assert!((halfway - 15.0).abs() < 0.001, "{halfway}");
4625
4626 tester.pump_by(ms(50));
4627 assert_eq!(font_size(), 20.0);
4628 });
4629 }
4630
4631 #[test]
4632 fn a_target_that_did_not_change_leaves_the_controller_dismissed() {
4633 test_widgets(|tester| {
4634 let key = GlobalKey::new();
4635 tester.pump_widget(opacity_tree(&key, 0.5));
4636 tester.pump_widget(opacity_tree(&key, 0.5));
4637 tester.pump_by(ms(50));
4638
4639 {
4640 let app = tester.cell.borrow();
4641 let state = key
4642 .current_state::<AnimatedOpacityState>(&app)
4643 .expect("the widget is mounted");
4644 assert!(
4645 state.controller(&app).is_dismissed(&app),
4646 "an unchanged target does not start the controller"
4647 );
4648 }
4649 assert_eq!(opacity_of(tester, &key), 0.5);
4650 });
4651 }
4652
4653 #[test]
4654 fn an_animated_positioned_directional_resolves_start_against_the_text_direction() {
4655 test_widgets(|tester| {
4656 let directional = |text_direction: TextDirection| {
4657 Directionality::new(
4658 text_direction,
4659 Stack::new().children([AnimatedPositionedDirectional::new(
4660 SizedBox::expand(),
4661 DURATION,
4662 )
4663 .start(10.0)
4664 .top(0.0)
4665 .width(20.0)
4666 .height(10.0)
4667 .into_widget()]),
4668 )
4669 };
4670 tester.pump_widget(directional(TextDirection::Ltr));
4671 let positioned = |tester: &WidgetTester| {
4672 tester.widget(find::by_type::<Positioned>(), |positioned: &Positioned| {
4673 (positioned.left, positioned.right)
4674 })
4675 };
4676 assert_eq!(positioned(tester), (Some(10.0), None));
4677
4678 tester.pump_widget(directional(TextDirection::Rtl));
4679 assert_eq!(positioned(tester), (None, Some(10.0)));
4680 });
4681 }
4682
4683 #[test]
4684 fn unmounting_frees_the_arena_tweens_the_constructors_made() {
4685 test_widgets(|tester| {
4686 let key = GlobalKey::new();
4687 tester.pump_widget(opacity_tree(&key, 0.5));
4688 let tween = {
4689 let app = tester.cell.borrow();
4690 let state = key
4691 .current_state::<AnimatedOpacityState>(&app)
4692 .expect("the widget is mounted");
4693 let tween = app
4694 .get(state)
4695 .opacity
4696 .handle()
4697 .expect("for_each_tween made the tween");
4698 assert!(app.contains(tween));
4699 tween
4700 };
4701
4702 tester.pump_widget(SizedBox::square(Some(10.0)));
4703 tester.cell.checkpoint();
4704 assert!(
4705 !tester.cell.borrow().contains(tween),
4706 "the last keeper of the arena tween is gone"
4707 );
4708 });
4709 }
4710
4711 #[test]
4712 fn a_text_style_tween_interpolates_the_style_fields() {
4713 let tween = TextStyleTween::new(
4714 Some(TextStyle::new().font_size(10.0)),
4715 Some(TextStyle::new().font_size(20.0)),
4716 );
4717 assert_eq!(tween.lerp(0.5).font_size, Some(15.0));
4718 let cell = AppCell::new();
4719 let app = cell.borrow();
4720 assert_eq!(tween.transform(&app, 0.0).font_size, Some(10.0));
4721 assert_eq!(tween.transform(&app, 1.0).font_size, Some(20.0));
4722 }
4723
4724 #[test]
4725 fn a_box_constraints_tween_interpolates_the_constraints() {
4726 let tween = BoxConstraintsTween::new(
4727 Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
4728 Some(BoxConstraints::tight(Size::new(20.0, 30.0))),
4729 );
4730 let cell = AppCell::new();
4731 let app = cell.borrow();
4732 let halfway = tween.transform(&app, 0.5);
4733 assert_eq!(halfway.max_width, 15.0);
4734 assert_eq!(halfway.max_height, 20.0);
4735 }
4736
4737 fn container_tree(key: &GlobalKey, width: f64, on_end: Option<Listener>) -> WidgetRef {
4739 let mut container = AnimatedContainer::new(DURATION)
4740 .key(key.clone().into())
4741 .width(width)
4742 .height(10.0);
4743 if let Some(on_end) = on_end {
4744 container = container.on_end(on_end);
4745 }
4746 crate::widgets::basic::Center::new()
4747 .child(container)
4748 .into_widget()
4749 }
4750
4751 #[test]
4752 fn an_animated_container_animates_its_width_and_calls_on_end_once() {
4753 test_widgets(|tester| {
4754 let key = GlobalKey::new();
4755 let ends = Rc::new(Cell::new(0));
4756 let counted = Rc::clone(&ends);
4757 let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
4758 tester.pump_widget(container_tree(&key, 20.0, Some(on_end.clone())));
4759 assert_eq!(
4760 tester.get_size(&key),
4761 Size::new(20.0, 10.0),
4762 "the first build does not animate"
4763 );
4764
4765 tester.pump_widget(container_tree(&key, 40.0, Some(on_end)));
4766 assert_eq!(
4767 tester.get_size(&key).width(),
4768 20.0,
4769 "the frame that starts the animation still shows the old width"
4770 );
4771
4772 tester.pump_by(ms(50));
4773 let halfway = tester.get_size(&key).width();
4774 assert!(
4775 (halfway - 30.0).abs() < 0.001,
4776 "halfway between 20 and 40, not {halfway}"
4777 );
4778 assert_eq!(ends.get(), 0, "the animation is still running");
4779
4780 tester.pump_by(ms(50));
4781 assert_eq!(tester.get_size(&key).width(), 40.0);
4782
4783 tester.pump_by(ms(50));
4784 assert_eq!(ends.get(), 1);
4785
4786 tester.pump_by(ms(50));
4787 assert_eq!(ends.get(), 1, "on_end fires once per animation");
4788 });
4789 }
4790
4791 #[derive(Debug)]
4793 struct IdentityDecoration;
4794
4795 impl Decoration for IdentityDecoration {
4796 fn create_box_painter(
4797 &self,
4798 _on_changed: Option<waft_foundation::VoidCallback>,
4799 ) -> Box<dyn waft_painting::BoxPainter> {
4800 Box::new(PaintsNothing)
4801 }
4802
4803 fn as_any(&self) -> &dyn std::any::Any {
4804 self
4805 }
4806 }
4807
4808 struct PaintsNothing;
4809
4810 impl waft_painting::BoxPainter for PaintsNothing {
4811 fn paint(
4812 &mut self,
4813 _canvas: &mut waft_embedder::Canvas,
4814 _offset: Offset,
4815 _configuration: &waft_painting::ImageConfiguration,
4816 ) {
4817 }
4818
4819 fn on_changed(&self) -> Option<&dyn Fn(&mut App)> {
4820 None
4821 }
4822 }
4823
4824 #[test]
4827 fn an_animated_container_given_its_own_decoration_again_does_not_animate() {
4828 test_widgets(|tester| {
4829 let decorated = |key: &GlobalKey, decoration: &DecorationRef| {
4830 AnimatedContainer::new(DURATION)
4831 .key(key.clone().into())
4832 .decoration(decoration.clone())
4833 .into_widget()
4834 };
4835 let key = GlobalKey::new();
4836 let decoration = DecorationRef::new(IdentityDecoration);
4837 tester.pump_widget(decorated(&key, &decoration));
4838 let controller = |tester: &WidgetTester| {
4839 let app = tester.cell.borrow();
4840 key.current_state::<AnimatedContainerState>(&app)
4841 .expect("the widget is mounted")
4842 .controller(&app)
4843 };
4844
4845 tester.pump_widget(decorated(&key, &decoration));
4846 assert!(
4847 controller(tester).is_dismissed(&tester.cell.borrow()),
4848 "the same decoration is no new target"
4849 );
4850
4851 let another = DecorationRef::new(IdentityDecoration);
4852 tester.pump_widget(decorated(&key, &another));
4853 let controller = controller(tester);
4854 assert!(
4855 controller.is_animating(&mut tester.cell.borrow_mut()),
4856 "another decoration of the same type is, as Dart's identity `==` makes it"
4857 );
4858 });
4859 }
4860
4861 fn padding_tree(key: &GlobalKey, text_direction: TextDirection, start: f64) -> WidgetRef {
4862 Directionality::new(
4863 text_direction,
4864 AnimatedPadding::new(
4865 EdgeInsetsGeometry::from_steb(start, 0.0, 0.0, 0.0),
4866 DURATION,
4867 )
4868 .child(SizedBox::square(Some(10.0)).key(key.clone().into())),
4869 )
4870 .into_widget()
4871 }
4872
4873 #[test]
4874 fn an_animated_padding_interpolates_a_directional_inset() {
4875 test_widgets(|tester| {
4876 let key = GlobalKey::new();
4877 tester.pump_widget(padding_tree(&key, TextDirection::Ltr, 0.0));
4878 assert_eq!(tester.get_top_left(&key), Offset::ZERO);
4879
4880 tester.pump_widget(padding_tree(&key, TextDirection::Ltr, 40.0));
4881 tester.pump_by(ms(50));
4882 let halfway = tester.get_top_left(&key).dx();
4883 assert!((halfway - 20.0).abs() < 0.001, "{halfway}");
4884
4885 tester.pump_by(ms(50));
4886 assert_eq!(tester.get_top_left(&key).dx(), 40.0);
4887 });
4888 test_widgets(|tester| {
4889 let key = GlobalKey::new();
4890 tester.pump_widget(padding_tree(&key, TextDirection::Rtl, 40.0));
4891 assert_eq!(
4892 tester.get_top_left(&key),
4893 Offset::ZERO,
4894 "an rtl start is an inset on the right"
4895 );
4896 });
4897 }
4898
4899 fn align_tree(key: &GlobalKey, alignment: AlignmentGeometry) -> WidgetRef {
4900 AnimatedAlign::new(alignment, DURATION)
4901 .child(SizedBox::square(Some(10.0)).key(key.clone().into()))
4902 .into_widget()
4903 }
4904
4905 #[test]
4906 fn an_animated_align_interpolates_the_alignment() {
4907 test_widgets(|tester| {
4908 let key = GlobalKey::new();
4909 tester.pump_widget(align_tree(&key, AlignmentGeometry::TOP_LEFT));
4910 assert_eq!(tester.get_top_left(&key), Offset::ZERO);
4911
4912 tester.pump_widget(align_tree(&key, AlignmentGeometry::BOTTOM_RIGHT));
4913 tester.pump_by(ms(50));
4914 assert_eq!(tester.get_top_left(&key), Offset::new(395.0, 295.0));
4915
4916 tester.pump_by(ms(50));
4917 assert_eq!(tester.get_top_left(&key), Offset::new(790.0, 590.0));
4918 });
4919 }
4920
4921 fn slide_tree(key: &GlobalKey, offset: Offset) -> WidgetRef {
4922 Align::new()
4923 .alignment(AlignmentGeometry::TOP_LEFT)
4924 .child(
4925 AnimatedSlide::new(offset, DURATION)
4926 .child(SizedBox::square(Some(10.0)).key(key.clone().into())),
4927 )
4928 .into_widget()
4929 }
4930
4931 #[test]
4932 fn an_animated_slide_moves_the_child_by_a_fraction_of_its_size() {
4933 test_widgets(|tester| {
4934 let key = GlobalKey::new();
4935 tester.pump_widget(slide_tree(&key, Offset::ZERO));
4936 assert_eq!(tester.get_top_left(&key), Offset::ZERO);
4937
4938 tester.pump_widget(slide_tree(&key, Offset::new(2.0, 0.0)));
4939 tester.pump_by(ms(50));
4940 assert_eq!(tester.get_top_left(&key), Offset::new(10.0, 0.0));
4941
4942 tester.pump_by(ms(50));
4943 assert_eq!(tester.get_top_left(&key), Offset::new(20.0, 0.0));
4944 });
4945 }
4946
4947 #[test]
4948 fn a_matrix4_tween_round_trips_a_translation_and_a_scale() {
4949 let begin = Matrix4::IDENTITY;
4950 let end = Matrix4::translation(10.0, 20.0).then(&Matrix4::scale(3.0, 3.0));
4951 let tween = Matrix4Tween::new(Some(begin), Some(end));
4952 let cell = AppCell::new();
4953 let app = cell.borrow();
4954 assert_eq!(tween.transform(&app, 0.0), begin);
4955 assert_eq!(tween.transform(&app, 1.0), end);
4956
4957 let (translation, _, scale) = decompose(tween.transform(&app, 0.5));
4958 assert!((translation.x - 5.0).abs() < 1e-5, "{translation:?}");
4959 assert!((translation.y - 10.0).abs() < 1e-5, "{translation:?}");
4960 assert!((scale.x - 2.0).abs() < 1e-5, "{scale:?}");
4961 assert!((scale.y - 2.0).abs() < 1e-5, "{scale:?}");
4962 }
4963
4964 #[test]
4965 fn an_edge_insets_geometry_tween_crosses_the_two_kinds() {
4966 let tween = EdgeInsetsGeometryTween::new(
4967 Some(EdgeInsetsGeometry::from_ltrb(10.0, 0.0, 0.0, 0.0)),
4968 Some(EdgeInsetsGeometry::from_steb(20.0, 0.0, 0.0, 0.0)),
4969 );
4970 let cell = AppCell::new();
4971 let app = cell.borrow();
4972 let halfway = tween.transform(&app, 0.5);
4973 assert_eq!(
4974 halfway.resolve(Some(TextDirection::Ltr)),
4975 EdgeInsets::from_ltrb(15.0, 0.0, 0.0, 0.0)
4976 );
4977 assert_eq!(
4978 halfway.resolve(Some(TextDirection::Rtl)),
4979 EdgeInsets::from_ltrb(5.0, 0.0, 10.0, 0.0)
4980 );
4981 }
4982
4983 #[test]
4984 fn a_border_radius_tween_interpolates_the_radius() {
4985 use waft_embedder::Radius;
4986 let tween = BorderRadiusTween::new(
4987 Some(BorderRadius::all(Radius::circular(0.0))),
4988 Some(BorderRadius::all(Radius::circular(10.0))),
4989 );
4990 let cell = AppCell::new();
4991 let app = cell.borrow();
4992 let halfway = tween.transform(&app, 0.5).expect("both ends are set");
4993 assert_eq!(halfway.top_left.x, 5.0);
4994 }
4995
4996 #[test]
4999 fn an_implicit_animation_moved_by_a_global_key_follows_its_view_and_ticker_mode() {
5000 use waft_embedder::{TargetPlatform, ViewId};
5001 use waft_test::TestPlatform;
5002
5003 use crate::view::ViewCollection;
5004 use crate::widgets::ticker_provider::TickerMode;
5005
5006 let (first, second) = (ViewId(1), ViewId(2));
5007 let platform = Rc::new(
5008 TestPlatform::new()
5009 .on(TargetPlatform::MacOS)
5010 .with_views(&[first, second]),
5011 );
5012 let cell = AppCell::with_platform(platform.clone());
5013 let key = GlobalKey::new();
5014 let tree = |view: ViewId, enabled: bool, opacity: f64| -> WidgetRef {
5015 let animated = TickerMode::new(
5016 enabled,
5017 AnimatedOpacity::new(opacity, DURATION).key(key.clone().into()),
5018 )
5019 .into_widget();
5020 let (in_first, in_second) = if view == first {
5021 (animated, SizedBox::new().into_widget())
5022 } else {
5023 (SizedBox::new().into_widget(), animated)
5024 };
5025 ViewCollection::new(vec![
5026 View::new(platform.test_view(first), in_first).into_widget(),
5027 View::new(platform.test_view(second), in_second).into_widget(),
5028 ])
5029 .into_widget()
5030 };
5031 let pump = |app: &mut App, view: ViewId, ms: u64| {
5032 crate::test_harness::binding_pump_view(app, view, Duration::from_millis(ms));
5033 };
5034 let attach = |app: &mut App, root: WidgetRef| {
5035 WidgetsBinding::instance(app).attach_root_widget(app, root);
5036 };
5037 crate::binding::run_widget(&mut cell.borrow_mut(), tree(first, true, 1.0));
5038 cell.elapse(Duration::ZERO);
5039 let mut app = cell.borrow_mut();
5040 let value = |app: &mut App| {
5041 let state = key
5042 .current_state::<AnimatedOpacityState>(app)
5043 .expect("mounted");
5044 ImplicitlyAnimatedWidgetState::controller(state, app).value(app)
5045 };
5046
5047 attach(&mut app, tree(first, true, 0.0));
5048 pump(&mut app, first, 16);
5049 pump(&mut app, first, 32);
5050 let before_move = value(&mut app);
5051 assert!(before_move > 0.0, "it animates in the first view");
5052
5053 attach(&mut app, tree(second, true, 0.0));
5055 pump(&mut app, second, 48);
5056 assert_eq!(value(&mut app), before_move);
5057 pump(&mut app, first, 64);
5058 assert_eq!(
5059 value(&mut app),
5060 before_move,
5061 "no tick at the first view's frame"
5062 );
5063 pump(&mut app, second, 64);
5064 let moved = value(&mut app);
5065 assert!(moved > before_move, "it ticks at the second view's frame");
5066
5067 attach(&mut app, tree(first, false, 0.0));
5068 pump(&mut app, first, 80);
5069 let muted = value(&mut app);
5070 pump(&mut app, first, 96);
5071 pump(&mut app, second, 96);
5072 assert_eq!(value(&mut app), muted, "muted by its new TickerMode");
5073 }
5074
5075 #[test]
5077 fn an_animated_physical_model_defaults_to_a_physical_models_arguments() {
5078 let color = Color::new(0x00000000);
5079 let animated = AnimatedPhysicalModel::new(SizedBox::shrink(), color, color, Duration::ZERO);
5080 let physical = PhysicalModel::new(color).shadow_color(color);
5081 assert_eq!(animated.shape, physical.shape);
5082 assert_eq!(animated.clip_behavior, physical.clip_behavior);
5083 assert_eq!(animated.border_radius, physical.border_radius);
5084 }
5085
5086 fn physical_model_tree(
5087 key: &GlobalKey,
5088 elevation: f64,
5089 color: Color,
5090 animate_color: bool,
5091 ) -> WidgetRef {
5092 AnimatedPhysicalModel::new(
5093 SizedBox::square(Some(10.0)),
5094 color,
5095 Color::new(0xFF000000),
5096 DURATION,
5097 )
5098 .key(key.clone().into())
5099 .elevation(elevation)
5100 .animate_color(animate_color)
5101 .into_widget()
5102 }
5103
5104 fn physical_model_of(
5105 tester: &WidgetTester,
5106 key: &GlobalKey,
5107 ) -> RenderHandle<waft_rendering::RenderPhysicalModel> {
5108 let render_object = tester.render_object(key);
5109 render_object
5110 .downcast::<waft_rendering::RenderPhysicalModel>(&tester.cell.borrow())
5111 .expect("a RenderPhysicalModel")
5112 }
5113
5114 #[test]
5117 fn an_animated_physical_model_animates_its_elevation_and_colour() {
5118 use waft_rendering::RenderPhysicalModelBase;
5119 for animate_color in [true, false] {
5120 test_widgets(|tester| {
5121 let key = GlobalKey::new();
5122 let red = Color::new(0xFFFF0000);
5123 let blue = Color::new(0xFF0000FF);
5124 tester.pump_widget(physical_model_tree(&key, 0.0, red, animate_color));
5125 assert_eq!(
5126 physical_model_of(tester, &key).elevation(&tester.cell.borrow()),
5127 0.0
5128 );
5129
5130 tester.pump_widget(physical_model_tree(&key, 8.0, blue, animate_color));
5131 tester.pump_by(ms(50));
5132 let model = physical_model_of(tester, &key);
5133 let app = tester.cell.borrow();
5134 let halfway = model.elevation(&app);
5135 assert!((halfway - 4.0).abs() < 0.001, "{halfway}");
5136 let color = model.color(&app);
5137 if animate_color {
5138 assert_eq!(
5139 color,
5140 Color::lerp(Some(red), Some(blue), 0.5).expect("two colours")
5141 );
5142 } else {
5143 assert_eq!(color, blue);
5144 }
5145 drop(app);
5146
5147 tester.pump_by(ms(50));
5148 let model = physical_model_of(tester, &key);
5149 let app = tester.cell.borrow();
5150 assert_eq!(model.elevation(&app), 8.0);
5151 assert_eq!(model.color(&app), blue);
5152 });
5153 }
5154 }
5155
5156 #[test]
5158 fn an_animated_physical_model_calls_on_end_once_its_animation_ends() {
5159 test_widgets(|tester| {
5160 let key = GlobalKey::new();
5161 let ends = Rc::new(Cell::new(0));
5162 let counted = Rc::clone(&ends);
5163 let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
5164 let tree = |elevation: f64| {
5165 AnimatedPhysicalModel::new(
5166 SizedBox::square(Some(10.0)),
5167 Color::new(0xFF0000FF),
5168 Color::new(0xFF000000),
5169 DURATION,
5170 )
5171 .key(key.clone().into())
5172 .elevation(elevation)
5173 .on_end(on_end.clone())
5174 .into_widget()
5175 };
5176 tester.pump_widget(tree(0.0));
5177 tester.pump_widget(tree(4.0));
5178 tester.pump_by(ms(50));
5179 assert_eq!(ends.get(), 0);
5180 tester.pump_by(ms(50));
5181 tester.pump_by(ms(50));
5182 assert_eq!(ends.get(), 1);
5183 tester.pump_by(ms(50));
5184 assert_eq!(ends.get(), 1);
5185 });
5186 }
5187
5188 #[test]
5190 fn an_animated_physical_model_does_not_crash_at_zero_area() {
5191 test_widgets(|tester| {
5192 let physical_model_color = Color::new(0xFF009688);
5193 let physical_model_shadow_color = Color::new(0xFF64FFDA);
5194 tester.pump_widget(Directionality::new(
5195 TextDirection::Ltr,
5196 crate::widgets::basic::Center::new().child(SizedBox::shrink().child(
5197 AnimatedPhysicalModel::new(
5198 Text::new("X"),
5199 physical_model_color,
5200 physical_model_shadow_color,
5201 Duration::from_millis(300),
5202 ),
5203 )),
5204 ));
5205 tester.pump_and_settle();
5206 assert_eq!(
5207 tester.get_size(find::by_type::<AnimatedPhysicalModel>()),
5208 Size::ZERO
5209 );
5210 });
5211 }
5212
5213 #[test]
5215 fn a_shape_border_value_is_the_same_by_its_equality() {
5216 use waft_painting::{BorderSide, CircleBorder, RoundedRectangleBorder};
5217 let rounded = |radius: f64| -> Option<ShapeBorderRef> {
5218 Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
5219 BorderSide::NONE,
5220 BorderRadius::circular(radius).into(),
5221 )))
5222 };
5223 assert!(rounded(2.0).same(&rounded(2.0)));
5224 assert!(!rounded(2.0).same(&rounded(4.0)));
5225 assert!(
5226 !rounded(2.0).same(&Some(ShapeBorderRef::new(CircleBorder::new(
5227 BorderSide::NONE,
5228 0.0
5229 ))))
5230 );
5231 assert!(!rounded(2.0).same(&None));
5232 assert!(None::<ShapeBorderRef>.same(&None));
5233 }
5234}
5235
5236#[cfg(test)]
5237mod diagnostics_tests {
5238 use super::*;
5239 use crate::testing::has_one_line_description;
5240
5241 #[test]
5243 fn an_animated_container_has_a_one_line_description() {
5244 let container = AnimatedContainer::new(Duration::from_millis(200))
5245 .constraints(BoxConstraints::tight_for(Some(17.0), Some(23.0)))
5246 .decoration(BoxDecoration::new().color(Color::new(0xFF00FF00)))
5247 .foreground_decoration(BoxDecoration::new().color(Color::new(0x7F0000FF)))
5248 .margin(EdgeInsets::all(10.0))
5249 .padding(EdgeInsets::all(7.0))
5250 .transform(Matrix4::translation(4.0, 3.0))
5251 .width(50.0)
5252 .height(75.0)
5253 .curve(Curves::ease());
5254 assert!(has_one_line_description(&container));
5255 }
5256
5257 #[test]
5259 fn an_animated_padding_has_a_one_line_description() {
5260 let padding = AnimatedPadding::new(EdgeInsets::all(10.0), Duration::from_millis(100));
5261 assert!(has_one_line_description(&padding));
5262 }
5263
5264 #[test]
5266 fn an_animated_align_has_a_one_line_description() {
5267 let align = AnimatedAlign::new(AlignmentGeometry::TOP_LEFT, Duration::from_millis(100));
5268 assert!(has_one_line_description(&align));
5269 }
5270}