use std::rc::Rc;
use std::time::Duration;
use waft_animation::{
Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef,
AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurvedAnimation, Curves, Drive,
Tween, TweenLerp,
};
use waft_embedder::{
Clip, Color, FilterQuality, Matrix4, Offset, Rect, TextAlign, TextHeightBehavior, compose,
decompose,
};
use waft_foundation::{App, Handle, Listener, OptionRetained};
use waft_painting::{
Alignment, AlignmentGeometry, AnyColor, Border, BorderRadius, BoxDecoration, BoxShape,
DecorationRef, EdgeInsets, EdgeInsetsGeometry, ShapeBorderRef, TextOverflow, TextStyle,
TextWidthBasis,
};
use waft_rendering::{AlignmentGeometryTween, BoxConstraints, Constraints};
use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::{
Align, Directionality, FractionallySizedBox, Padding, PhysicalModel, Positioned,
};
use crate::widgets::container::Container;
use crate::widgets::text::DefaultTextStyle;
use crate::widgets::ticker_provider::{
SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
};
use crate::widgets::transitions::{
FadeTransition, RotationTransition, ScaleTransition, SlideTransition,
};
use waft_foundation::Ref;
#[derive(Clone, Debug)]
pub struct BoxConstraintsTween {
pub begin: Option<BoxConstraints>,
pub end: Option<BoxConstraints>,
}
impl BoxConstraintsTween {
pub fn new(begin: Option<BoxConstraints>, end: Option<BoxConstraints>) -> BoxConstraintsTween {
BoxConstraintsTween { begin, end }
}
pub fn lerp(&self, t: f64) -> BoxConstraints {
BoxConstraints::lerp(self.begin, self.end, t)
.expect("BoxConstraintsTween.begin or end must be set before use")
}
}
impl Animatable<BoxConstraints> for BoxConstraintsTween {
fn transform(&self, _app: &App, t: f64) -> BoxConstraints {
if t == 0.0 {
return self.begin.expect("Tween.begin must be set before use");
}
if t == 1.0 {
return self.end.expect("Tween.end must be set before use");
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct DecorationTween {
pub begin: Option<DecorationRef>,
pub end: Option<DecorationRef>,
}
impl DecorationTween {
pub fn new(begin: Option<DecorationRef>, end: Option<DecorationRef>) -> DecorationTween {
DecorationTween { begin, end }
}
pub fn lerp(&self, t: f64) -> DecorationRef {
DecorationRef::lerp(self.begin.as_ref(), self.end.as_ref(), t)
.expect("DecorationTween.begin or end must be set before use")
}
}
impl Animatable<DecorationRef> for DecorationTween {
fn transform(&self, _app: &App, t: f64) -> DecorationRef {
if t == 0.0 {
return self
.begin
.as_ref()
.expect("Tween.begin must be set before use")
.clone();
}
if t == 1.0 {
return self
.end
.as_ref()
.expect("Tween.end must be set before use")
.clone();
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct EdgeInsetsTween {
pub begin: Option<EdgeInsets>,
pub end: Option<EdgeInsets>,
}
impl EdgeInsetsTween {
pub fn new(begin: Option<EdgeInsets>, end: Option<EdgeInsets>) -> EdgeInsetsTween {
EdgeInsetsTween { begin, end }
}
pub fn lerp(&self, t: f64) -> EdgeInsets {
EdgeInsets::lerp(self.begin, self.end, t)
.expect("EdgeInsetsTween.begin or end must be set before use")
}
}
impl Animatable<EdgeInsets> for EdgeInsetsTween {
fn transform(&self, _app: &App, t: f64) -> EdgeInsets {
if t == 0.0 {
return self.begin.expect("Tween.begin must be set before use");
}
if t == 1.0 {
return self.end.expect("Tween.end must be set before use");
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct EdgeInsetsGeometryTween {
pub begin: Option<EdgeInsetsGeometry>,
pub end: Option<EdgeInsetsGeometry>,
}
impl EdgeInsetsGeometryTween {
pub fn new(
begin: Option<EdgeInsetsGeometry>,
end: Option<EdgeInsetsGeometry>,
) -> EdgeInsetsGeometryTween {
EdgeInsetsGeometryTween { begin, end }
}
pub fn lerp(&self, t: f64) -> EdgeInsetsGeometry {
EdgeInsetsGeometry::lerp(self.begin, self.end, t)
.expect("EdgeInsetsGeometryTween.begin or end must be set before use")
}
}
impl Animatable<EdgeInsetsGeometry> for EdgeInsetsGeometryTween {
fn transform(&self, _app: &App, t: f64) -> EdgeInsetsGeometry {
if t == 0.0 {
return self.begin.expect("Tween.begin must be set before use");
}
if t == 1.0 {
return self.end.expect("Tween.end must be set before use");
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct BorderRadiusTween {
pub begin: Option<BorderRadius>,
pub end: Option<BorderRadius>,
}
impl BorderRadiusTween {
pub fn new(begin: Option<BorderRadius>, end: Option<BorderRadius>) -> BorderRadiusTween {
BorderRadiusTween { begin, end }
}
pub fn lerp(&self, t: f64) -> Option<BorderRadius> {
BorderRadius::lerp(self.begin, self.end, t)
}
}
impl Animatable<Option<BorderRadius>> for BorderRadiusTween {
fn transform(&self, _app: &App, t: f64) -> Option<BorderRadius> {
if t == 0.0 {
return self.begin;
}
if t == 1.0 {
return self.end;
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct BorderTween {
pub begin: Option<Border>,
pub end: Option<Border>,
}
impl BorderTween {
pub fn new(begin: Option<Border>, end: Option<Border>) -> BorderTween {
BorderTween { begin, end }
}
pub fn lerp(&self, t: f64) -> Option<Border> {
Border::lerp(self.begin, self.end, t)
}
}
impl Animatable<Option<Border>> for BorderTween {
fn transform(&self, _app: &App, t: f64) -> Option<Border> {
if t == 0.0 {
return self.begin;
}
if t == 1.0 {
return self.end;
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct Matrix4Tween {
pub begin: Option<Matrix4>,
pub end: Option<Matrix4>,
}
impl Matrix4Tween {
pub fn new(begin: Option<Matrix4>, end: Option<Matrix4>) -> Matrix4Tween {
Matrix4Tween { begin, end }
}
pub fn lerp(&self, t: f64) -> Matrix4 {
let begin = self
.begin
.expect("Matrix4Tween.begin must be set before use");
let end = self.end.expect("Matrix4Tween.end must be set before use");
let (begin_translation, begin_rotation, begin_scale) = decompose(begin);
let (end_translation, end_rotation, end_scale) = decompose(end);
let t = t as f32;
let lerp_translation = begin_translation * (1.0 - t) + end_translation * t;
let lerp_rotation = (begin_rotation.scaled(1.0 - t) + end_rotation.scaled(t)).normalized();
let lerp_scale = begin_scale * (1.0 - t) + end_scale * t;
compose(lerp_translation, lerp_rotation, lerp_scale)
}
}
impl Animatable<Matrix4> for Matrix4Tween {
fn transform(&self, _app: &App, t: f64) -> Matrix4 {
if t == 0.0 {
return self.begin.expect("Tween.begin must be set before use");
}
if t == 1.0 {
return self.end.expect("Tween.end must be set before use");
}
self.lerp(t)
}
}
#[derive(Clone, Debug)]
pub struct TextStyleTween {
pub begin: Option<TextStyle>,
pub end: Option<TextStyle>,
}
impl TextStyleTween {
pub fn new(begin: Option<TextStyle>, end: Option<TextStyle>) -> TextStyleTween {
TextStyleTween { begin, end }
}
pub fn lerp(&self, t: f64) -> TextStyle {
TextStyle::lerp(self.begin.as_ref(), self.end.as_ref(), t)
.expect("TextStyleTween.begin or end must be set before use")
}
}
impl Animatable<TextStyle> for TextStyleTween {
fn transform(&self, _app: &App, t: f64) -> TextStyle {
if t == 0.0 {
return self
.begin
.clone()
.expect("Tween.begin must be set before use");
}
if t == 1.0 {
return self.end.clone().expect("Tween.end must be set before use");
}
self.lerp(t)
}
}
#[derive(Debug)]
pub struct ImplicitlyAnimatedWidgetData {
pub key: Option<KeyRef>,
pub curve: Rc<dyn Curve>,
pub duration: Duration,
pub on_end: Option<Listener>,
}
impl ImplicitlyAnimatedWidgetData {
pub fn new(duration: Duration) -> ImplicitlyAnimatedWidgetData {
ImplicitlyAnimatedWidgetData {
key: None,
curve: Curves::linear(),
duration,
on_end: None,
}
}
}
#[macro_export]
macro_rules! implicitly_animated_widget_accessors {
() => {
fn implicitly_animated_widget_data(&self) -> &$crate::ImplicitlyAnimatedWidgetData {
&self.implicitly_animated_widget
}
fn implicitly_animated_widget_data_mut(
&mut self,
) -> &mut $crate::ImplicitlyAnimatedWidgetData {
&mut self.implicitly_animated_widget
}
};
}
#[macro_export]
macro_rules! implicitly_animated_widget_setters {
($name:ident) => {
pub fn key(mut self, key: $crate::KeyRef) -> $name {
self.implicitly_animated_widget.key = Some(key);
self
}
pub fn curve(mut self, curve: ::std::rc::Rc<dyn ::waft_animation::Curve>) -> $name {
self.implicitly_animated_widget.curve = curve;
self
}
pub fn on_end(mut self, on_end: ::waft_foundation::Listener) -> $name {
self.implicitly_animated_widget.on_end = Some(on_end);
self
}
};
}
pub trait ImplicitlyAnimatedWidget: StatefulWidget {
fn implicitly_animated_widget_data(&self) -> &ImplicitlyAnimatedWidgetData;
fn implicitly_animated_widget_data_mut(&mut self) -> &mut ImplicitlyAnimatedWidgetData;
}
pub trait TweenValue: 'static {
fn same(&self, other: &Self) -> bool;
}
impl<T: TweenValue> TweenValue for Rc<T> {
fn same(&self, other: &Rc<T>) -> bool {
T::same(self, other)
}
}
impl TweenValue for f64 {
fn same(&self, other: &f64) -> bool {
self == other
}
}
impl TweenValue for BoxConstraints {
fn same(&self, other: &BoxConstraints) -> bool {
self == other
}
}
impl TweenValue for EdgeInsets {
fn same(&self, other: &EdgeInsets) -> bool {
self == other
}
}
impl TweenValue for EdgeInsetsGeometry {
fn same(&self, other: &EdgeInsetsGeometry) -> bool {
self == other
}
}
impl TweenValue for Matrix4 {
fn same(&self, other: &Matrix4) -> bool {
self == other
}
}
impl TweenValue for Offset {
fn same(&self, other: &Offset) -> bool {
self == other
}
}
impl TweenValue for TextStyle {
fn same(&self, other: &TextStyle) -> bool {
self == other
}
}
impl TweenValue for Option<BorderRadius> {
fn same(&self, other: &Option<BorderRadius>) -> bool {
self == other
}
}
impl TweenValue for Option<Border> {
fn same(&self, other: &Option<Border>) -> bool {
self == other
}
}
impl TweenValue for Option<AlignmentGeometry> {
fn same(&self, other: &Option<AlignmentGeometry>) -> bool {
self == other
}
}
impl TweenValue for Option<Color> {
fn same(&self, other: &Option<Color>) -> bool {
self == other
}
}
impl TweenValue for DecorationRef {
fn same(&self, other: &DecorationRef) -> bool {
self == other
}
}
impl TweenValue for Option<ShapeBorderRef> {
fn same(&self, other: &Option<ShapeBorderRef>) -> bool {
self == other
}
}
pub trait TweenSlot: Animatable<<Self as TweenSlot>::Value> + Clone + 'static {
type Value: TweenValue;
fn begin(&self, app: &App) -> Option<Self::Value>;
fn set_begin(&mut self, app: &mut App, begin: Option<Self::Value>);
fn end(&self, app: &App) -> Option<Self::Value>;
fn set_end(&mut self, app: &mut App, end: Option<Self::Value>);
}
impl<T: TweenLerp + TweenValue> TweenSlot for Ref<Tween<T>> {
type Value = T;
fn begin(&self, app: &App) -> Option<T> {
Tween::begin(self.handle(), app).cloned()
}
fn set_begin(&mut self, app: &mut App, begin: Option<T>) {
Tween::set_begin(self.handle(), app, begin);
}
fn end(&self, app: &App) -> Option<T> {
Tween::end(self.handle(), app).cloned()
}
fn set_end(&mut self, app: &mut App, end: Option<T>) {
Tween::set_end(self.handle(), app, end);
}
}
macro_rules! tween_slot_for_value {
($tween:ty, $value:ty) => {
impl TweenSlot for $tween {
type Value = $value;
fn begin(&self, _app: &App) -> Option<$value> {
self.begin.clone()
}
fn set_begin(&mut self, _app: &mut App, begin: Option<$value>) {
self.begin = begin;
}
fn end(&self, _app: &App) -> Option<$value> {
self.end.clone()
}
fn set_end(&mut self, _app: &mut App, end: Option<$value>) {
self.end = end;
}
}
};
}
tween_slot_for_value!(BoxConstraintsTween, BoxConstraints);
tween_slot_for_value!(EdgeInsetsTween, EdgeInsets);
tween_slot_for_value!(EdgeInsetsGeometryTween, EdgeInsetsGeometry);
tween_slot_for_value!(Matrix4Tween, Matrix4);
tween_slot_for_value!(TextStyleTween, TextStyle);
macro_rules! tween_slot_for_nullable_value {
($tween:ty, $value:ty) => {
impl TweenSlot for $tween {
type Value = Option<$value>;
fn begin(&self, _app: &App) -> Option<Option<$value>> {
self.begin.map(Some)
}
fn set_begin(&mut self, _app: &mut App, begin: Option<Option<$value>>) {
self.begin = begin.flatten();
}
fn end(&self, _app: &App) -> Option<Option<$value>> {
self.end.map(Some)
}
fn set_end(&mut self, _app: &mut App, end: Option<Option<$value>>) {
self.end = end.flatten();
}
}
};
}
tween_slot_for_nullable_value!(BorderRadiusTween, BorderRadius);
impl TweenSlot for Ref<ColorTween> {
type Value = Option<Color>;
fn begin(&self, app: &App) -> Option<Option<Color>> {
ColorTween::begin(self.handle(), app).map(Some)
}
fn set_begin(&mut self, app: &mut App, begin: Option<Option<Color>>) {
ColorTween::set_begin(self.handle(), app, begin.flatten());
}
fn end(&self, app: &App) -> Option<Option<Color>> {
ColorTween::end(self.handle(), app).map(Some)
}
fn set_end(&mut self, app: &mut App, end: Option<Option<Color>>) {
ColorTween::set_end(self.handle(), app, end.flatten());
}
}
tween_slot_for_nullable_value!(BorderTween, Border);
tween_slot_for_nullable_value!(AlignmentGeometryTween, AlignmentGeometry);
impl TweenSlot for DecorationTween {
type Value = DecorationRef;
fn begin(&self, _app: &App) -> Option<DecorationRef> {
self.begin.clone()
}
fn set_begin(&mut self, _app: &mut App, begin: Option<DecorationRef>) {
self.begin = begin;
}
fn end(&self, _app: &App) -> Option<DecorationRef> {
self.end.clone()
}
fn set_end(&mut self, _app: &mut App, end: Option<DecorationRef>) {
self.end = end;
}
}
pub type TweenConstructor<W> = fn(&mut App, &<W as TweenSlot>::Value) -> W;
pub trait TweenVisitor {
fn visit<W: TweenSlot>(
&mut self,
app: &mut App,
tween: Option<W>,
target: Option<W::Value>,
constructor: TweenConstructor<W>,
) -> Option<W>;
}
struct ConstructTweens {
should_start_animation: bool,
}
impl TweenVisitor for ConstructTweens {
fn visit<W: TweenSlot>(
&mut self,
app: &mut App,
tween: Option<W>,
target: Option<W::Value>,
constructor: TweenConstructor<W>,
) -> Option<W> {
let target = target?;
let mut tween = match tween {
Some(tween) => tween,
None => constructor(app, &target),
};
let endpoint = tween.end(app).or_else(|| tween.begin(app));
if !endpoint.is_some_and(|endpoint| target.same(&endpoint)) {
self.should_start_animation = true;
} else if tween.end(app).is_none() {
let begin = tween.begin(app);
tween.set_end(app, begin);
}
Some(tween)
}
}
struct RetargetTweens {
animation: AnyAnimation<f64>,
}
impl TweenVisitor for RetargetTweens {
fn visit<W: TweenSlot>(
&mut self,
app: &mut App,
tween: Option<W>,
target: Option<W::Value>,
_constructor: TweenConstructor<W>,
) -> Option<W> {
let mut tween = tween?;
let begin = tween.evaluate(app, self.animation);
tween.set_begin(app, Some(begin));
tween.set_end(app, target);
Some(tween)
}
}
#[derive(Default)]
pub struct ImplicitlyAnimatedWidgetStateData {
controller: Option<Ref<AnimationController>>,
animation: Option<Ref<CurvedAnimation>>,
}
impl ImplicitlyAnimatedWidgetStateData {
pub fn new() -> ImplicitlyAnimatedWidgetStateData {
ImplicitlyAnimatedWidgetStateData::default()
}
}
#[macro_export]
macro_rules! implicitly_animated_widget_state_accessors {
() => {
fn implicitly_animated_widget_state_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::ImplicitlyAnimatedWidgetStateData {
&app.get(self).implicitly_animated_widget_state
}
fn implicitly_animated_widget_state_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::ImplicitlyAnimatedWidgetStateData {
&mut app.get_mut(self).implicitly_animated_widget_state
}
};
}
pub trait ImplicitlyAnimatedWidgetState:
State + SingleTickerProviderStateMixin + TickerProviderObject
where
Self::Widget: ImplicitlyAnimatedWidget,
{
fn implicitly_animated_widget_state_data(
self: Handle<Self>,
app: &App,
) -> &ImplicitlyAnimatedWidgetStateData;
fn implicitly_animated_widget_state_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut ImplicitlyAnimatedWidgetStateData;
fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
self.implicitly_animated_widget_state_data(app)
.controller
.handle()
.expect("created in init_state")
}
fn animation(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
curved_animation(self, app).as_animation()
}
fn init_state(self: Handle<Self>, app: &mut App) {
let duration = self.widget(app).implicitly_animated_widget_data().duration;
let controller = AnimationController::new(
app,
None,
Some(duration),
None,
0.0,
1.0,
AnimationBehavior::Normal,
self,
);
self.implicitly_animated_widget_state_data_mut(app)
.controller = Some(controller.clone());
controller.add_status_listener(
app,
AnimationStatusListener::new(move |status, app| {
if status.is_completed() {
let on_end = self
.widget(app)
.implicitly_animated_widget_data()
.on_end
.clone();
if let Some(on_end) = on_end {
on_end.call(app);
}
}
}),
);
let animation = create_curve(self, app);
self.implicitly_animated_widget_state_data_mut(app)
.animation = Some(animation);
construct_tweens(self, app);
self.did_update_tweens(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Self::Widget) {
let curve = Rc::clone(&self.widget(app).implicitly_animated_widget_data().curve);
if !Rc::ptr_eq(&curve, &old_widget.implicitly_animated_widget_data().curve) {
curved_animation(self, app).dispose(app);
let animation = create_curve(self, app);
self.implicitly_animated_widget_state_data_mut(app)
.animation = Some(animation);
}
let duration = self.widget(app).implicitly_animated_widget_data().duration;
let controller = self.controller(app);
app.get_mut(controller).duration = Some(duration);
if construct_tweens(self, app) {
let animation = self.animation(app);
self.for_each_tween(app, &mut RetargetTweens { animation });
controller.forward(app, Some(0.0));
self.did_update_tweens(app);
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
let animation = curved_animation(self, app);
animation.dispose(app);
let controller = self.controller(app);
controller.dispose(app);
SingleTickerProviderStateMixin::dispose(self, app);
}
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V);
fn did_update_tweens(self: Handle<Self>, app: &mut App) {
let _ = (self, app);
}
}
fn curved_animation<S>(this: Handle<S>, app: &App) -> Handle<CurvedAnimation>
where
S: ImplicitlyAnimatedWidgetState,
S::Widget: ImplicitlyAnimatedWidget,
{
this.implicitly_animated_widget_state_data(app)
.animation
.handle()
.expect("created in init_state")
}
fn create_curve<S>(this: Handle<S>, app: &mut App) -> Ref<CurvedAnimation>
where
S: ImplicitlyAnimatedWidgetState,
S::Widget: ImplicitlyAnimatedWidget,
{
let parent = this
.implicitly_animated_widget_state_data(app)
.controller
.as_ref()
.expect("created in init_state")
.erase();
let curve = Rc::clone(&this.widget(app).implicitly_animated_widget_data().curve);
CurvedAnimation::new(app, parent, curve, None)
}
fn construct_tweens<S>(this: Handle<S>, app: &mut App) -> bool
where
S: ImplicitlyAnimatedWidgetState,
S::Widget: ImplicitlyAnimatedWidget,
{
let mut visitor = ConstructTweens {
should_start_animation: false,
};
this.for_each_tween(app, &mut visitor);
visitor.should_start_animation
}
pub trait AnimatedWidgetBaseState: ImplicitlyAnimatedWidgetState
where
Self::Widget: ImplicitlyAnimatedWidget,
{
fn init_state(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::init_state(self, app);
let controller = self.controller(app);
controller.add_listener(
app,
Listener::handle_method(self, Self::handle_animation_changed),
);
}
fn handle_animation_changed(self: Handle<Self>, app: &mut App) {
self.set_state(app, |_state| {
});
}
}
#[derive(Debug)]
pub struct AnimatedContainer {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub alignment: Option<AlignmentGeometry>,
pub padding: Option<EdgeInsetsGeometry>,
color: Option<AnyColor>,
pub decoration: Option<DecorationRef>,
pub foreground_decoration: Option<DecorationRef>,
pub constraints: Option<BoxConstraints>,
given_constraints: Option<BoxConstraints>,
width: Option<f64>,
height: Option<f64>,
pub margin: Option<EdgeInsetsGeometry>,
pub transform: Option<Matrix4>,
pub transform_alignment: Option<AlignmentGeometry>,
pub child: Option<WidgetRef>,
pub clip_behavior: Clip,
}
impl AnimatedContainer {
pub fn new(duration: Duration) -> AnimatedContainer {
AnimatedContainer {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
alignment: None,
padding: None,
color: None,
decoration: None,
foreground_decoration: None,
constraints: None,
given_constraints: None,
width: None,
height: None,
margin: None,
transform: None,
transform_alignment: None,
child: None,
clip_behavior: Clip::None,
}
}
pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedContainer {
self.alignment = Some(alignment);
self
}
pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> AnimatedContainer {
let padding = padding.into();
debug_assert!(padding.is_non_negative());
self.padding = Some(padding);
self
}
pub fn color(mut self, color: impl Into<AnyColor>) -> AnimatedContainer {
let color = color.into();
debug_assert!(self.decoration.is_none(), "{CANNOT_PROVIDE_BOTH}");
self.color = Some(color.clone());
self.decoration = Some(DecorationRef::new(BoxDecoration::new().color(color)));
self
}
pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> AnimatedContainer {
debug_assert!(self.color.is_none(), "{CANNOT_PROVIDE_BOTH}");
let decoration = decoration.into();
debug_assert!(decoration.debug_assert_is_valid());
self.decoration = Some(decoration);
self
}
pub fn foreground_decoration(
mut self,
foreground_decoration: impl Into<DecorationRef>,
) -> AnimatedContainer {
self.foreground_decoration = Some(foreground_decoration.into());
self
}
pub fn width(mut self, width: f64) -> AnimatedContainer {
self.width = Some(width);
self.fold_constraints();
self
}
pub fn height(mut self, height: f64) -> AnimatedContainer {
self.height = Some(height);
self.fold_constraints();
self
}
pub fn constraints(mut self, constraints: BoxConstraints) -> AnimatedContainer {
debug_assert!(constraints.debug_assert_is_valid(false));
self.given_constraints = Some(constraints);
self.fold_constraints();
self
}
pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> AnimatedContainer {
let margin = margin.into();
debug_assert!(margin.is_non_negative());
self.margin = Some(margin);
self
}
pub fn transform(mut self, transform: Matrix4) -> AnimatedContainer {
self.transform = Some(transform);
self
}
pub fn transform_alignment(
mut self,
transform_alignment: AlignmentGeometry,
) -> AnimatedContainer {
self.transform_alignment = Some(transform_alignment);
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedContainer {
self.child = Some(child.into_widget());
self
}
pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedContainer {
self.clip_behavior = clip_behavior;
self
}
crate::implicitly_animated_widget_setters!(AnimatedContainer);
fn fold_constraints(&mut self) {
self.constraints = if self.width.is_some() || self.height.is_some() {
Some(match self.given_constraints {
Some(constraints) => constraints.tighten(self.width, self.height),
None => BoxConstraints::tight_for(self.width, self.height),
})
} else {
self.given_constraints
};
}
}
const CANNOT_PROVIDE_BOTH: &str = "Cannot provide both a color and a decoration\n\
The color argument is just a shorthand for \"decoration: BoxDecoration(color: color)\".";
impl ImplicitlyAnimatedWidget for AnimatedContainer {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedContainer {
type State = AnimatedContainerState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedContainerState {
AnimatedContainerState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
alignment: None,
padding: None,
decoration: None,
foreground_decoration: None,
constraints: None,
margin: None,
transform: None,
transform_alignment: None,
}
}
}
pub struct AnimatedContainerState {
state: StateData<AnimatedContainer>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
alignment: Option<AlignmentGeometryTween>,
padding: Option<EdgeInsetsGeometryTween>,
decoration: Option<DecorationTween>,
foreground_decoration: Option<DecorationTween>,
constraints: Option<BoxConstraintsTween>,
margin: Option<EdgeInsetsGeometryTween>,
transform: Option<Matrix4Tween>,
transform_alignment: Option<AlignmentGeometryTween>,
}
impl SingleTickerProviderStateMixin for AnimatedContainerState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedContainerState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedContainerState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).alignment.clone();
let target = self.widget(app).alignment.map(Some);
app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
AlignmentGeometryTween::new(*value, None)
});
let tween = app.get(self).padding.clone();
let target = self.widget(app).padding;
app.get_mut(self).padding = visitor.visit(app, tween, target, |_app, value| {
EdgeInsetsGeometryTween::new(Some(*value), None)
});
let tween = app.get(self).decoration.clone();
let target = self.widget(app).decoration.clone();
app.get_mut(self).decoration = visitor.visit(app, tween, target, |_app, value| {
DecorationTween::new(Some(value.clone()), None)
});
let tween = app.get(self).foreground_decoration.clone();
let target = self.widget(app).foreground_decoration.clone();
app.get_mut(self).foreground_decoration =
visitor.visit(app, tween, target, |_app, value| {
DecorationTween::new(Some(value.clone()), None)
});
let tween = app.get(self).constraints.clone();
let target = self.widget(app).constraints;
app.get_mut(self).constraints = visitor.visit(app, tween, target, |_app, value| {
BoxConstraintsTween::new(Some(*value), None)
});
let tween = app.get(self).margin.clone();
let target = self.widget(app).margin;
app.get_mut(self).margin = visitor.visit(app, tween, target, |_app, value| {
EdgeInsetsGeometryTween::new(Some(*value), None)
});
let tween = app.get(self).transform.clone();
let target = self.widget(app).transform;
app.get_mut(self).transform = visitor.visit(app, tween, target, |_app, value| {
Matrix4Tween::new(Some(*value), None)
});
let tween = app.get(self).transform_alignment.clone();
let target = self.widget(app).transform_alignment.map(Some);
app.get_mut(self).transform_alignment = visitor.visit(app, tween, target, |_app, value| {
AlignmentGeometryTween::new(*value, None)
});
}
}
impl AnimatedWidgetBaseState for AnimatedContainerState {}
impl State for AnimatedContainerState {
type Widget = AnimatedContainer;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedContainer) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let (alignment, padding) = (state.alignment.clone(), state.padding.clone());
let (decoration, foreground_decoration) = (
state.decoration.clone(),
state.foreground_decoration.clone(),
);
let (constraints, margin) = (state.constraints.clone(), state.margin.clone());
let (transform, transform_alignment) =
(state.transform.clone(), state.transform_alignment.clone());
let widget = self.widget(app);
let (clip_behavior, child) = (widget.clip_behavior, widget.child.clone());
let mut container = Container::new().clip_behavior(clip_behavior);
if let Some(alignment) = alignment.and_then(|tween| tween.evaluate(app, animation)) {
container = container.alignment(alignment);
}
if let Some(padding) = padding {
container = container.padding(padding.evaluate(app, animation));
}
if let Some(constraints) = constraints {
container = container.constraints(constraints.evaluate(app, animation));
}
if let Some(margin) = margin {
container = container.margin(margin.evaluate(app, animation));
}
if let Some(transform) = transform {
container = container.transform(transform.evaluate(app, animation));
}
if let Some(transform_alignment) =
transform_alignment.and_then(|tween| tween.evaluate(app, animation))
{
container = container.transform_alignment(transform_alignment);
}
if let Some(child) = child {
container = container.child(child);
}
if let Some(decoration) = decoration.map(|tween| tween.evaluate(app, animation)) {
container = container.decoration(decoration);
}
if let Some(foreground_decoration) =
foreground_decoration.map(|tween| tween.evaluate(app, animation))
{
container = container.foreground_decoration(foreground_decoration);
}
container.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedPadding {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub padding: EdgeInsetsGeometry,
pub child: Option<WidgetRef>,
}
impl AnimatedPadding {
pub fn new(padding: impl Into<EdgeInsetsGeometry>, duration: Duration) -> AnimatedPadding {
let padding = padding.into();
debug_assert!(padding.is_non_negative());
AnimatedPadding {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
padding,
child: None,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedPadding {
self.child = Some(child.into_widget());
self
}
crate::implicitly_animated_widget_setters!(AnimatedPadding);
}
impl ImplicitlyAnimatedWidget for AnimatedPadding {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedPadding {
type State = AnimatedPaddingState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedPaddingState {
AnimatedPaddingState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
padding: None,
}
}
}
pub struct AnimatedPaddingState {
state: StateData<AnimatedPadding>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
padding: Option<EdgeInsetsGeometryTween>,
}
impl SingleTickerProviderStateMixin for AnimatedPaddingState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedPaddingState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedPaddingState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).padding.clone();
let target = Some(self.widget(app).padding);
app.get_mut(self).padding = visitor.visit(app, tween, target, |_app, value| {
EdgeInsetsGeometryTween::new(Some(*value), None)
});
}
}
impl AnimatedWidgetBaseState for AnimatedPaddingState {}
impl State for AnimatedPaddingState {
type Widget = AnimatedPadding;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPadding) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let padding = app
.get(self)
.padding
.clone()
.expect("for_each_tween made the tween");
let child = self.widget(app).child.clone();
let padding = padding
.evaluate(app, animation)
.clamp(&EdgeInsetsGeometry::ZERO, &EdgeInsetsGeometry::INFINITY);
let mut widget = Padding::new(padding);
if let Some(child) = child {
widget = widget.child(child);
}
widget.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedAlign {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub alignment: AlignmentGeometry,
pub child: Option<WidgetRef>,
pub height_factor: Option<f64>,
pub width_factor: Option<f64>,
}
impl AnimatedAlign {
pub fn new(alignment: AlignmentGeometry, duration: Duration) -> AnimatedAlign {
AnimatedAlign {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
alignment,
child: None,
height_factor: None,
width_factor: None,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedAlign {
self.child = Some(child.into_widget());
self
}
pub fn height_factor(mut self, height_factor: f64) -> AnimatedAlign {
debug_assert!(height_factor >= 0.0);
self.height_factor = Some(height_factor);
self
}
pub fn width_factor(mut self, width_factor: f64) -> AnimatedAlign {
debug_assert!(width_factor >= 0.0);
self.width_factor = Some(width_factor);
self
}
crate::implicitly_animated_widget_setters!(AnimatedAlign);
}
impl ImplicitlyAnimatedWidget for AnimatedAlign {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedAlign {
type State = AnimatedAlignState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedAlignState {
AnimatedAlignState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
alignment: None,
height_factor_tween: None,
width_factor_tween: None,
}
}
}
pub struct AnimatedAlignState {
state: StateData<AnimatedAlign>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
alignment: Option<AlignmentGeometryTween>,
height_factor_tween: Option<Ref<Tween<f64>>>,
width_factor_tween: Option<Ref<Tween<f64>>>,
}
impl SingleTickerProviderStateMixin for AnimatedAlignState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedAlignState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedAlignState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).alignment.clone();
let target = Some(Some(self.widget(app).alignment));
app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
AlignmentGeometryTween::new(*value, None)
});
if self.widget(app).height_factor.is_some() {
let (tween, target) = (
app.get(self).height_factor_tween.clone(),
self.widget(app).height_factor,
);
app.get_mut(self).height_factor_tween = visitor.visit(app, tween, target, double_tween);
}
if self.widget(app).width_factor.is_some() {
let (tween, target) = (
app.get(self).width_factor_tween.clone(),
self.widget(app).width_factor,
);
app.get_mut(self).width_factor_tween = visitor.visit(app, tween, target, double_tween);
}
}
}
impl AnimatedWidgetBaseState for AnimatedAlignState {}
impl State for AnimatedAlignState {
type Widget = AnimatedAlign;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedAlign) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let alignment = state
.alignment
.clone()
.expect("for_each_tween made the tween");
let (height_factor_tween, width_factor_tween) = (
state.height_factor_tween.clone(),
state.width_factor_tween.clone(),
);
let child = self.widget(app).child.clone();
let alignment = alignment
.evaluate(app, animation)
.expect("the tween is built from the widget's alignment");
let mut align = Align::new().alignment(alignment);
if let Some(height_factor) = height_factor_tween {
align = align.height_factor(height_factor.evaluate(app, animation));
}
if let Some(width_factor) = width_factor_tween {
align = align.width_factor(width_factor.evaluate(app, animation));
}
if let Some(child) = child {
align = align.child(child);
}
align.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedPositioned {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: WidgetRef,
pub left: Option<f64>,
pub top: Option<f64>,
pub right: Option<f64>,
pub bottom: Option<f64>,
pub width: Option<f64>,
pub height: Option<f64>,
}
impl AnimatedPositioned {
pub fn new<K>(child: impl IntoWidget<K>, duration: Duration) -> AnimatedPositioned {
AnimatedPositioned {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: child.into_widget(),
left: None,
top: None,
right: None,
bottom: None,
width: None,
height: None,
}
}
pub fn from_rect<K>(
child: impl IntoWidget<K>,
rect: Rect,
duration: Duration,
) -> AnimatedPositioned {
AnimatedPositioned {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: child.into_widget(),
left: Some(rect.left),
top: Some(rect.top),
right: None,
bottom: None,
width: Some(rect.width()),
height: Some(rect.height()),
}
}
pub fn left(mut self, left: f64) -> AnimatedPositioned {
self.left = Some(left);
self.debug_check_axes();
self
}
pub fn top(mut self, top: f64) -> AnimatedPositioned {
self.top = Some(top);
self.debug_check_axes();
self
}
pub fn right(mut self, right: f64) -> AnimatedPositioned {
self.right = Some(right);
self.debug_check_axes();
self
}
pub fn bottom(mut self, bottom: f64) -> AnimatedPositioned {
self.bottom = Some(bottom);
self.debug_check_axes();
self
}
pub fn width(mut self, width: f64) -> AnimatedPositioned {
self.width = Some(width);
self.debug_check_axes();
self
}
pub fn height(mut self, height: f64) -> AnimatedPositioned {
self.height = Some(height);
self.debug_check_axes();
self
}
crate::implicitly_animated_widget_setters!(AnimatedPositioned);
fn debug_check_axes(&self) {
debug_assert!(
self.left.is_none() || self.right.is_none() || self.width.is_none(),
"Only two out of `left`, `right` and `width` can be set."
);
debug_assert!(
self.top.is_none() || self.bottom.is_none() || self.height.is_none(),
"Only two out of `top`, `bottom` and `height` can be set."
);
}
}
impl ImplicitlyAnimatedWidget for AnimatedPositioned {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedPositioned {
type State = AnimatedPositionedState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedPositionedState {
AnimatedPositionedState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
left: None,
top: None,
right: None,
bottom: None,
width: None,
height: None,
}
}
}
pub struct AnimatedPositionedState {
state: StateData<AnimatedPositioned>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
left: Option<Ref<Tween<f64>>>,
top: Option<Ref<Tween<f64>>>,
right: Option<Ref<Tween<f64>>>,
bottom: Option<Ref<Tween<f64>>>,
width: Option<Ref<Tween<f64>>>,
height: Option<Ref<Tween<f64>>>,
}
impl SingleTickerProviderStateMixin for AnimatedPositionedState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedPositionedState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedPositionedState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (app.get(self).left.clone(), self.widget(app).left);
app.get_mut(self).left = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).top.clone(), self.widget(app).top);
app.get_mut(self).top = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).right.clone(), self.widget(app).right);
app.get_mut(self).right = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).bottom.clone(), self.widget(app).bottom);
app.get_mut(self).bottom = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).width.clone(), self.widget(app).width);
app.get_mut(self).width = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).height.clone(), self.widget(app).height);
app.get_mut(self).height = visitor.visit(app, tween, target, double_tween);
}
}
impl AnimatedWidgetBaseState for AnimatedPositionedState {}
impl State for AnimatedPositionedState {
type Widget = AnimatedPositioned;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPositioned) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let (left, top, right) = (state.left.clone(), state.top.clone(), state.right.clone());
let (bottom, width, height) = (
state.bottom.clone(),
state.width.clone(),
state.height.clone(),
);
let mut positioned = Positioned::new(self.widget(app).child.clone());
if let Some(left) = left {
positioned = positioned.left(left.evaluate(app, animation));
}
if let Some(top) = top {
positioned = positioned.top(top.evaluate(app, animation));
}
if let Some(right) = right {
positioned = positioned.right(right.evaluate(app, animation));
}
if let Some(bottom) = bottom {
positioned = positioned.bottom(bottom.evaluate(app, animation));
}
if let Some(width) = width {
positioned = positioned.width(width.evaluate(app, animation));
}
if let Some(height) = height {
positioned = positioned.height(height.evaluate(app, animation));
}
positioned.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedPositionedDirectional {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: WidgetRef,
pub start: Option<f64>,
pub top: Option<f64>,
pub end: Option<f64>,
pub bottom: Option<f64>,
pub width: Option<f64>,
pub height: Option<f64>,
}
impl AnimatedPositionedDirectional {
pub fn new<K>(child: impl IntoWidget<K>, duration: Duration) -> AnimatedPositionedDirectional {
AnimatedPositionedDirectional {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: child.into_widget(),
start: None,
top: None,
end: None,
bottom: None,
width: None,
height: None,
}
}
pub fn start(mut self, start: f64) -> AnimatedPositionedDirectional {
self.start = Some(start);
self.debug_check_axes();
self
}
pub fn top(mut self, top: f64) -> AnimatedPositionedDirectional {
self.top = Some(top);
self.debug_check_axes();
self
}
pub fn end(mut self, end: f64) -> AnimatedPositionedDirectional {
self.end = Some(end);
self.debug_check_axes();
self
}
pub fn bottom(mut self, bottom: f64) -> AnimatedPositionedDirectional {
self.bottom = Some(bottom);
self.debug_check_axes();
self
}
pub fn width(mut self, width: f64) -> AnimatedPositionedDirectional {
self.width = Some(width);
self.debug_check_axes();
self
}
pub fn height(mut self, height: f64) -> AnimatedPositionedDirectional {
self.height = Some(height);
self.debug_check_axes();
self
}
crate::implicitly_animated_widget_setters!(AnimatedPositionedDirectional);
fn debug_check_axes(&self) {
debug_assert!(
self.start.is_none() || self.end.is_none() || self.width.is_none(),
"Only two out of `start`, `end` and `width` can be set."
);
debug_assert!(
self.top.is_none() || self.bottom.is_none() || self.height.is_none(),
"Only two out of `top`, `bottom` and `height` can be set."
);
}
}
impl ImplicitlyAnimatedWidget for AnimatedPositionedDirectional {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedPositionedDirectional {
type State = AnimatedPositionedDirectionalState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedPositionedDirectionalState {
AnimatedPositionedDirectionalState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
start: None,
top: None,
end: None,
bottom: None,
width: None,
height: None,
}
}
}
pub struct AnimatedPositionedDirectionalState {
state: StateData<AnimatedPositionedDirectional>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
start: Option<Ref<Tween<f64>>>,
top: Option<Ref<Tween<f64>>>,
end: Option<Ref<Tween<f64>>>,
bottom: Option<Ref<Tween<f64>>>,
width: Option<Ref<Tween<f64>>>,
height: Option<Ref<Tween<f64>>>,
}
impl SingleTickerProviderStateMixin for AnimatedPositionedDirectionalState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedPositionedDirectionalState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedPositionedDirectionalState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (app.get(self).start.clone(), self.widget(app).start);
app.get_mut(self).start = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).top.clone(), self.widget(app).top);
app.get_mut(self).top = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).end.clone(), self.widget(app).end);
app.get_mut(self).end = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).bottom.clone(), self.widget(app).bottom);
app.get_mut(self).bottom = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).width.clone(), self.widget(app).width);
app.get_mut(self).width = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).height.clone(), self.widget(app).height);
app.get_mut(self).height = visitor.visit(app, tween, target, double_tween);
}
}
impl AnimatedWidgetBaseState for AnimatedPositionedDirectionalState {}
impl State for AnimatedPositionedDirectionalState {
type Widget = AnimatedPositionedDirectional;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(
self: Handle<Self>,
app: &mut App,
old_widget: &AnimatedPositionedDirectional,
) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let (start, top, end) = (state.start.clone(), state.top.clone(), state.end.clone());
let (bottom, width, height) = (
state.bottom.clone(),
state.width.clone(),
state.height.clone(),
);
let text_direction = Directionality::of(app, context);
let start = start.map(|start| start.evaluate(app, animation));
let end = end.map(|end| end.evaluate(app, animation));
let mut positioned =
Positioned::directional(text_direction, start, end, self.widget(app).child.clone());
if let Some(top) = top {
positioned = positioned.top(top.evaluate(app, animation));
}
if let Some(bottom) = bottom {
positioned = positioned.bottom(bottom.evaluate(app, animation));
}
if let Some(width) = width {
positioned = positioned.width(width.evaluate(app, animation));
}
if let Some(height) = height {
positioned = positioned.height(height.evaluate(app, animation));
}
positioned.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedScale {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: Option<WidgetRef>,
pub scale: f64,
pub alignment: Alignment,
pub filter_quality: Option<FilterQuality>,
}
impl AnimatedScale {
pub fn new(scale: f64, duration: Duration) -> AnimatedScale {
AnimatedScale {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: None,
scale,
alignment: Alignment::CENTER,
filter_quality: None,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedScale {
self.child = Some(child.into_widget());
self
}
pub fn alignment(mut self, alignment: Alignment) -> AnimatedScale {
self.alignment = alignment;
self
}
pub fn filter_quality(mut self, filter_quality: FilterQuality) -> AnimatedScale {
self.filter_quality = Some(filter_quality);
self
}
crate::implicitly_animated_widget_setters!(AnimatedScale);
}
impl ImplicitlyAnimatedWidget for AnimatedScale {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedScale {
type State = AnimatedScaleState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedScaleState {
AnimatedScaleState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
scale: None,
scale_animation: None,
}
}
}
pub struct AnimatedScaleState {
state: StateData<AnimatedScale>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
scale: Option<Ref<Tween<f64>>>,
scale_animation: Option<AnimationRef<f64>>,
}
impl SingleTickerProviderStateMixin for AnimatedScaleState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedScaleState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedScaleState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (app.get(self).scale.clone(), Some(self.widget(app).scale));
app.get_mut(self).scale = visitor.visit(app, tween, target, double_tween);
}
fn did_update_tweens(self: Handle<Self>, app: &mut App) {
let scale = app
.get(self)
.scale
.clone()
.expect("for_each_tween made the tween");
let animation = self.animation(app).keep(app);
let scale_animation = animation.drive(app, scale);
app.get_mut(self).scale_animation = Some(scale_animation);
}
}
impl State for AnimatedScaleState {
type Widget = AnimatedScale;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedScale) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let scale = app
.get(self)
.scale_animation
.clone()
.expect("did_update_tweens drove the animation");
let widget = self.widget(app);
let (alignment, filter_quality, child) = (
widget.alignment,
widget.filter_quality,
widget.child.clone(),
);
let mut transition = ScaleTransition::new(scale).alignment(alignment);
transition.filter_quality = filter_quality;
if let Some(child) = child {
transition = transition.child(child);
}
transition.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedRotation {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: Option<WidgetRef>,
pub turns: f64,
pub alignment: Alignment,
pub filter_quality: Option<FilterQuality>,
}
impl AnimatedRotation {
pub fn new(turns: f64, duration: Duration) -> AnimatedRotation {
AnimatedRotation {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: None,
turns,
alignment: Alignment::CENTER,
filter_quality: None,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedRotation {
self.child = Some(child.into_widget());
self
}
pub fn alignment(mut self, alignment: Alignment) -> AnimatedRotation {
self.alignment = alignment;
self
}
pub fn filter_quality(mut self, filter_quality: FilterQuality) -> AnimatedRotation {
self.filter_quality = Some(filter_quality);
self
}
crate::implicitly_animated_widget_setters!(AnimatedRotation);
}
impl ImplicitlyAnimatedWidget for AnimatedRotation {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedRotation {
type State = AnimatedRotationState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedRotationState {
AnimatedRotationState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
turns: None,
turns_animation: None,
}
}
}
pub struct AnimatedRotationState {
state: StateData<AnimatedRotation>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
turns: Option<Ref<Tween<f64>>>,
turns_animation: Option<AnimationRef<f64>>,
}
impl SingleTickerProviderStateMixin for AnimatedRotationState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedRotationState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedRotationState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (app.get(self).turns.clone(), Some(self.widget(app).turns));
app.get_mut(self).turns = visitor.visit(app, tween, target, double_tween);
}
fn did_update_tweens(self: Handle<Self>, app: &mut App) {
let turns = app
.get(self)
.turns
.clone()
.expect("for_each_tween made the tween");
let animation = self.animation(app).keep(app);
let turns_animation = animation.drive(app, turns);
app.get_mut(self).turns_animation = Some(turns_animation);
}
}
impl State for AnimatedRotationState {
type Widget = AnimatedRotation;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedRotation) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let turns = app
.get(self)
.turns_animation
.clone()
.expect("did_update_tweens drove the animation");
let widget = self.widget(app);
let (alignment, filter_quality, child) = (
widget.alignment,
widget.filter_quality,
widget.child.clone(),
);
let mut transition = RotationTransition::new(turns).alignment(alignment);
transition.filter_quality = filter_quality;
if let Some(child) = child {
transition = transition.child(child);
}
transition.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedSlide {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: Option<WidgetRef>,
pub offset: Offset,
}
impl AnimatedSlide {
pub fn new(offset: Offset, duration: Duration) -> AnimatedSlide {
AnimatedSlide {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: None,
offset,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedSlide {
self.child = Some(child.into_widget());
self
}
crate::implicitly_animated_widget_setters!(AnimatedSlide);
}
impl ImplicitlyAnimatedWidget for AnimatedSlide {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedSlide {
type State = AnimatedSlideState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedSlideState {
AnimatedSlideState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
offset: None,
offset_animation: None,
}
}
}
pub struct AnimatedSlideState {
state: StateData<AnimatedSlide>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
offset: Option<Ref<Tween<Offset>>>,
offset_animation: Option<AnimationRef<Offset>>,
}
impl SingleTickerProviderStateMixin for AnimatedSlideState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedSlideState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedSlideState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (app.get(self).offset.clone(), Some(self.widget(app).offset));
app.get_mut(self).offset = visitor.visit(app, tween, target, offset_tween);
}
fn did_update_tweens(self: Handle<Self>, app: &mut App) {
let offset = app
.get(self)
.offset
.clone()
.expect("for_each_tween made the tween");
let animation = self.animation(app).keep(app);
let offset_animation = animation.drive(app, offset);
app.get_mut(self).offset_animation = Some(offset_animation);
}
}
impl State for AnimatedSlideState {
type Widget = AnimatedSlide;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedSlide) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let position = app
.get(self)
.offset_animation
.clone()
.expect("did_update_tweens drove the animation");
let child = self.widget(app).child.clone();
let mut transition = SlideTransition::new(position);
if let Some(child) = child {
transition = transition.child(child);
}
transition.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedOpacity {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: Option<WidgetRef>,
pub opacity: f64,
}
impl AnimatedOpacity {
pub fn new(opacity: f64, duration: Duration) -> AnimatedOpacity {
debug_assert!((0.0..=1.0).contains(&opacity));
AnimatedOpacity {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: None,
opacity,
}
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedOpacity {
self.child = Some(child.into_widget());
self
}
crate::implicitly_animated_widget_setters!(AnimatedOpacity);
}
impl ImplicitlyAnimatedWidget for AnimatedOpacity {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedOpacity {
type State = AnimatedOpacityState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedOpacityState {
AnimatedOpacityState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
opacity: None,
opacity_animation: None,
}
}
}
pub struct AnimatedOpacityState {
state: StateData<AnimatedOpacity>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
opacity: Option<Ref<Tween<f64>>>,
opacity_animation: Option<AnimationRef<f64>>,
}
impl SingleTickerProviderStateMixin for AnimatedOpacityState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedOpacityState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedOpacityState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let (tween, target) = (
app.get(self).opacity.clone(),
Some(self.widget(app).opacity),
);
app.get_mut(self).opacity = visitor.visit(app, tween, target, double_tween);
}
fn did_update_tweens(self: Handle<Self>, app: &mut App) {
let opacity = app
.get(self)
.opacity
.clone()
.expect("for_each_tween made the tween");
let animation = self.animation(app).keep(app);
let opacity_animation = animation.drive(app, opacity);
app.get_mut(self).opacity_animation = Some(opacity_animation);
}
}
impl State for AnimatedOpacityState {
type Widget = AnimatedOpacity;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedOpacity) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let opacity = app
.get(self)
.opacity_animation
.clone()
.expect("did_update_tweens drove the animation");
let child = self.widget(app).child.clone();
let mut transition = FadeTransition::new(opacity);
if let Some(child) = child {
transition = transition.child(child);
}
transition.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedDefaultTextStyle {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: WidgetRef,
pub style: TextStyle,
pub text_align: Option<TextAlign>,
pub soft_wrap: bool,
pub overflow: TextOverflow,
pub max_lines: Option<i32>,
pub text_width_basis: TextWidthBasis,
pub text_height_behavior: Option<TextHeightBehavior>,
}
impl AnimatedDefaultTextStyle {
pub fn new<K>(
child: impl IntoWidget<K>,
style: TextStyle,
duration: Duration,
) -> AnimatedDefaultTextStyle {
AnimatedDefaultTextStyle {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: child.into_widget(),
style,
text_align: None,
soft_wrap: true,
overflow: TextOverflow::Clip,
max_lines: None,
text_width_basis: TextWidthBasis::Parent,
text_height_behavior: None,
}
}
pub fn text_align(mut self, text_align: TextAlign) -> AnimatedDefaultTextStyle {
self.text_align = Some(text_align);
self
}
pub fn soft_wrap(mut self, soft_wrap: bool) -> AnimatedDefaultTextStyle {
self.soft_wrap = soft_wrap;
self
}
pub fn overflow(mut self, overflow: TextOverflow) -> AnimatedDefaultTextStyle {
self.overflow = overflow;
self
}
pub fn max_lines(mut self, max_lines: i32) -> AnimatedDefaultTextStyle {
debug_assert!(max_lines > 0);
self.max_lines = Some(max_lines);
self
}
pub fn text_width_basis(
mut self,
text_width_basis: TextWidthBasis,
) -> AnimatedDefaultTextStyle {
self.text_width_basis = text_width_basis;
self
}
pub fn text_height_behavior(
mut self,
text_height_behavior: TextHeightBehavior,
) -> AnimatedDefaultTextStyle {
self.text_height_behavior = Some(text_height_behavior);
self
}
crate::implicitly_animated_widget_setters!(AnimatedDefaultTextStyle);
}
impl ImplicitlyAnimatedWidget for AnimatedDefaultTextStyle {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedDefaultTextStyle {
type State = AnimatedDefaultTextStyleState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedDefaultTextStyleState {
AnimatedDefaultTextStyleState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
style: None,
}
}
}
pub struct AnimatedDefaultTextStyleState {
state: StateData<AnimatedDefaultTextStyle>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
style: Option<TextStyleTween>,
}
impl SingleTickerProviderStateMixin for AnimatedDefaultTextStyleState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedDefaultTextStyleState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedDefaultTextStyleState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).style.clone();
let target = self.widget(app).style.clone();
app.get_mut(self).style = visitor.visit(app, tween, Some(target), |_app, value| {
TextStyleTween::new(Some(value.clone()), None)
});
}
}
impl AnimatedWidgetBaseState for AnimatedDefaultTextStyleState {}
impl State for AnimatedDefaultTextStyleState {
type Widget = AnimatedDefaultTextStyle;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedDefaultTextStyle) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let style = app
.get(self)
.style
.clone()
.expect("for_each_tween made the tween");
let widget = self.widget(app);
let (text_align, soft_wrap, overflow) =
(widget.text_align, widget.soft_wrap, widget.overflow);
let (max_lines, text_width_basis) = (widget.max_lines, widget.text_width_basis);
let text_height_behavior = widget.text_height_behavior;
let child = widget.child.clone();
let mut default_text_style = DefaultTextStyle::new(style.evaluate(app, animation), child)
.soft_wrap(soft_wrap)
.overflow(overflow)
.text_width_basis(text_width_basis);
if let Some(text_align) = text_align {
default_text_style = default_text_style.text_align(text_align);
}
if let Some(max_lines) = max_lines {
default_text_style = default_text_style.max_lines(max_lines);
}
if let Some(text_height_behavior) = text_height_behavior {
default_text_style = default_text_style.text_height_behavior(text_height_behavior);
}
default_text_style.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedPhysicalModel {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: WidgetRef,
pub shape: BoxShape,
pub clip_behavior: Clip,
pub border_radius: Option<BorderRadius>,
pub elevation: f64,
pub color: AnyColor,
pub animate_color: bool,
pub shadow_color: AnyColor,
pub animate_shadow_color: bool,
}
impl AnimatedPhysicalModel {
pub fn new<K>(
child: impl IntoWidget<K>,
color: impl Into<AnyColor>,
shadow_color: impl Into<AnyColor>,
duration: Duration,
) -> AnimatedPhysicalModel {
AnimatedPhysicalModel {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: child.into_widget(),
shape: BoxShape::Rectangle,
clip_behavior: Clip::None,
border_radius: None,
elevation: 0.0,
color: color.into(),
animate_color: true,
shadow_color: shadow_color.into(),
animate_shadow_color: true,
}
}
pub fn shape(mut self, shape: BoxShape) -> AnimatedPhysicalModel {
self.shape = shape;
self
}
pub fn clip_behavior(mut self, clip_behavior: Clip) -> AnimatedPhysicalModel {
self.clip_behavior = clip_behavior;
self
}
pub fn border_radius(mut self, border_radius: BorderRadius) -> AnimatedPhysicalModel {
self.border_radius = Some(border_radius);
self
}
pub fn elevation(mut self, elevation: f64) -> AnimatedPhysicalModel {
debug_assert!(elevation >= 0.0);
self.elevation = elevation;
self
}
pub fn animate_color(mut self, animate_color: bool) -> AnimatedPhysicalModel {
self.animate_color = animate_color;
self
}
pub fn animate_shadow_color(mut self, animate_shadow_color: bool) -> AnimatedPhysicalModel {
self.animate_shadow_color = animate_shadow_color;
self
}
crate::implicitly_animated_widget_setters!(AnimatedPhysicalModel);
}
impl ImplicitlyAnimatedWidget for AnimatedPhysicalModel {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedPhysicalModel {
type State = AnimatedPhysicalModelState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedPhysicalModelState {
AnimatedPhysicalModelState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
border_radius: None,
elevation: None,
color: None,
shadow_color: None,
}
}
}
pub struct AnimatedPhysicalModelState {
state: StateData<AnimatedPhysicalModel>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
border_radius: Option<BorderRadiusTween>,
elevation: Option<Ref<Tween<f64>>>,
color: Option<Ref<ColorTween>>,
shadow_color: Option<Ref<ColorTween>>,
}
impl SingleTickerProviderStateMixin for AnimatedPhysicalModelState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedPhysicalModelState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedPhysicalModelState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).border_radius.clone();
let target = self.widget(app).border_radius.unwrap_or(BorderRadius::ZERO);
app.get_mut(self).border_radius =
visitor.visit(app, tween, Some(Some(target)), |_app, value| {
BorderRadiusTween::new(*value, None)
});
let (tween, target) = (
app.get(self).elevation.clone(),
Some(self.widget(app).elevation),
);
app.get_mut(self).elevation = visitor.visit(app, tween, target, double_tween);
let (tween, target) = (app.get(self).color.clone(), self.widget(app).color.color());
app.get_mut(self).color = visitor.visit(app, tween, Some(Some(target)), color_tween);
let (tween, target) = (
app.get(self).shadow_color.clone(),
self.widget(app).shadow_color.color(),
);
app.get_mut(self).shadow_color = visitor.visit(app, tween, Some(Some(target)), color_tween);
}
}
impl AnimatedWidgetBaseState for AnimatedPhysicalModelState {}
impl State for AnimatedPhysicalModelState {
type Widget = AnimatedPhysicalModel;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedPhysicalModel) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let border_radius = state
.border_radius
.clone()
.expect("for_each_tween made the tween");
let elevation = state
.elevation
.clone()
.expect("for_each_tween made the tween");
let color = state.color.clone().expect("for_each_tween made the tween");
let shadow_color = state
.shadow_color
.clone()
.expect("for_each_tween made the tween");
let widget = self.widget(app);
let (shape, clip_behavior, child) =
(widget.shape, widget.clip_behavior, widget.child.clone());
let (animate_color, widget_color) = (widget.animate_color, widget.color.clone());
let (animate_shadow_color, widget_shadow_color) =
(widget.animate_shadow_color, widget.shadow_color.clone());
let mut physical_model = PhysicalModel::new(if animate_color {
AnyColor::new(
color
.evaluate(app, animation)
.expect("a colour tween between colours"),
)
} else {
widget_color
})
.shape(shape)
.clip_behavior(clip_behavior)
.elevation(elevation.evaluate(app, animation))
.shadow_color(if animate_shadow_color {
AnyColor::new(
shadow_color
.evaluate(app, animation)
.expect("a colour tween between colours"),
)
} else {
widget_shadow_color
})
.child(child);
physical_model.border_radius = border_radius.evaluate(app, animation);
physical_model.into_widget()
}
}
#[derive(Debug)]
pub struct AnimatedFractionallySizedBox {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
pub child: Option<WidgetRef>,
pub height_factor: Option<f64>,
pub width_factor: Option<f64>,
pub alignment: AlignmentGeometry,
}
impl AnimatedFractionallySizedBox {
pub fn new(duration: Duration) -> AnimatedFractionallySizedBox {
AnimatedFractionallySizedBox {
implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
child: None,
height_factor: None,
width_factor: None,
alignment: AlignmentGeometry::CENTER,
}
}
pub fn alignment(mut self, alignment: AlignmentGeometry) -> AnimatedFractionallySizedBox {
self.alignment = alignment;
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> AnimatedFractionallySizedBox {
self.child = Some(child.into_widget());
self
}
pub fn height_factor(mut self, height_factor: f64) -> AnimatedFractionallySizedBox {
debug_assert!(height_factor >= 0.0);
self.height_factor = Some(height_factor);
self
}
pub fn width_factor(mut self, width_factor: f64) -> AnimatedFractionallySizedBox {
debug_assert!(width_factor >= 0.0);
self.width_factor = Some(width_factor);
self
}
crate::implicitly_animated_widget_setters!(AnimatedFractionallySizedBox);
}
impl ImplicitlyAnimatedWidget for AnimatedFractionallySizedBox {
crate::implicitly_animated_widget_accessors!();
}
impl StatefulWidget for AnimatedFractionallySizedBox {
type State = AnimatedFractionallySizedBoxState;
fn key(&self) -> Option<&KeyRef> {
self.implicitly_animated_widget.key.as_ref()
}
fn create_state(&self) -> AnimatedFractionallySizedBoxState {
AnimatedFractionallySizedBoxState {
state: StateData::new(),
single_ticker_provider: SingleTickerProviderStateMixinData::new(),
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
alignment: None,
height_factor_tween: None,
width_factor_tween: None,
}
}
}
pub struct AnimatedFractionallySizedBoxState {
state: StateData<AnimatedFractionallySizedBox>,
single_ticker_provider: SingleTickerProviderStateMixinData,
implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
alignment: Option<AlignmentGeometryTween>,
height_factor_tween: Option<Ref<Tween<f64>>>,
width_factor_tween: Option<Ref<Tween<f64>>>,
}
impl SingleTickerProviderStateMixin for AnimatedFractionallySizedBoxState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl TickerProviderObject for AnimatedFractionallySizedBoxState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl ImplicitlyAnimatedWidgetState for AnimatedFractionallySizedBoxState {
crate::implicitly_animated_widget_state_accessors!();
fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
let tween = app.get(self).alignment.clone();
let target = Some(Some(self.widget(app).alignment));
app.get_mut(self).alignment = visitor.visit(app, tween, target, |_app, value| {
AlignmentGeometryTween::new(*value, None)
});
if self.widget(app).height_factor.is_some() {
let (tween, target) = (
app.get(self).height_factor_tween.clone(),
self.widget(app).height_factor,
);
app.get_mut(self).height_factor_tween = visitor.visit(app, tween, target, double_tween);
}
if self.widget(app).width_factor.is_some() {
let (tween, target) = (
app.get(self).width_factor_tween.clone(),
self.widget(app).width_factor,
);
app.get_mut(self).width_factor_tween = visitor.visit(app, tween, target, double_tween);
}
}
}
impl AnimatedWidgetBaseState for AnimatedFractionallySizedBoxState {}
impl State for AnimatedFractionallySizedBoxState {
type Widget = AnimatedFractionallySizedBox;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AnimatedWidgetBaseState::init_state(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn did_update_widget(
self: Handle<Self>,
app: &mut App,
old_widget: &AnimatedFractionallySizedBox,
) {
ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ImplicitlyAnimatedWidgetState::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = self.animation(app);
let state = app.get(self);
let alignment = state
.alignment
.clone()
.expect("for_each_tween made the tween");
let (height_factor_tween, width_factor_tween) = (
state.height_factor_tween.clone(),
state.width_factor_tween.clone(),
);
let child = self.widget(app).child.clone();
let alignment = alignment
.evaluate(app, animation)
.expect("the tween is built from the widget's alignment");
let mut box_ = FractionallySizedBox::new().alignment(alignment);
if let Some(height_factor) = height_factor_tween {
box_ = box_.height_factor(height_factor.evaluate(app, animation));
}
if let Some(width_factor) = width_factor_tween {
box_ = box_.width_factor(width_factor.evaluate(app, animation));
}
if let Some(child) = child {
box_ = box_.child(child);
}
box_.into_widget()
}
}
fn double_tween(app: &mut App, value: &f64) -> Ref<Tween<f64>> {
Tween::new(app, Some(*value), None)
}
fn color_tween(app: &mut App, value: &Option<Color>) -> Ref<ColorTween> {
ColorTween::new(app, *value, None)
}
fn offset_tween(app: &mut App, value: &Offset) -> Ref<Tween<Offset>> {
Tween::new(app, Some(*value), None)
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use waft_foundation::AppCell;
use waft_painting::Decoration;
use waft_embedder::{Size, TextDirection};
use waft_rendering::{RenderAnimatedOpacity, RenderAnimatedOpacityMixin};
use super::*;
use crate::binding::WidgetsBinding;
use crate::framework::GlobalKey;
use crate::testing::{WidgetTester, find, test_widgets};
use crate::view::View;
use crate::widgets::basic::{Align, Builder, Directionality, SizedBox, Stack};
use crate::widgets::text::Text;
use waft_rendering::RenderHandle;
const DURATION: Duration = Duration::from_millis(100);
fn ms(milliseconds: u64) -> Duration {
Duration::from_millis(milliseconds)
}
fn positioned_tree(key: &GlobalKey, width: f64, on_end: Option<Listener>) -> WidgetRef {
let mut positioned = AnimatedPositioned::new(SizedBox::expand(), DURATION)
.key(key.clone().into())
.left(0.0)
.top(0.0)
.width(width)
.height(10.0);
if let Some(on_end) = on_end {
positioned = positioned.on_end(on_end);
}
Directionality::new(
TextDirection::Ltr,
Stack::new().children([positioned.into_widget()]),
)
.into_widget()
}
#[test]
fn an_animated_positioned_animates_its_box_and_calls_on_end_once() {
test_widgets(|tester| {
let key = GlobalKey::new();
let ends = Rc::new(Cell::new(0));
let counted = Rc::clone(&ends);
let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
tester.pump_widget(positioned_tree(&key, 20.0, Some(on_end.clone())));
assert_eq!(
tester.get_size(&key),
Size::new(20.0, 10.0),
"the first build does not animate"
);
tester.pump_widget(positioned_tree(&key, 40.0, Some(on_end)));
assert_eq!(
tester.get_size(&key).width(),
20.0,
"the frame that starts the animation still shows the old width"
);
tester.pump_by(ms(50));
let halfway = tester.get_size(&key).width();
assert!(
(halfway - 30.0).abs() < 0.001,
"halfway between 20 and 40, not {halfway}"
);
assert_eq!(ends.get(), 0, "the animation is still running");
tester.pump_by(ms(50));
assert_eq!(tester.get_size(&key).width(), 40.0);
assert_eq!(
ends.get(),
0,
"the controller completes on the first tick past the duration"
);
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1);
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1, "on_end fires once per animation");
});
}
fn opacity_tree(key: &GlobalKey, opacity: f64) -> WidgetRef {
AnimatedOpacity::new(opacity, DURATION)
.key(key.clone().into())
.child(SizedBox::square(Some(10.0)))
.into_widget()
}
fn opacity_of(tester: &WidgetTester, key: &GlobalKey) -> f64 {
let render_object = tester.render_object(key);
let app = tester.cell.borrow();
let render_object = render_object
.downcast::<RenderAnimatedOpacity>(&app)
.expect("a RenderAnimatedOpacity");
RenderAnimatedOpacityMixin::opacity(render_object, &app).value(&app)
}
#[test]
fn an_animated_opacity_reaches_its_target_after_the_duration() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(opacity_tree(&key, 1.0));
assert_eq!(opacity_of(tester, &key), 1.0);
tester.pump_widget(opacity_tree(&key, 0.0));
assert_eq!(opacity_of(tester, &key), 1.0);
tester.pump_by(ms(50));
let halfway = opacity_of(tester, &key);
assert!((halfway - 0.5).abs() < 0.001, "{halfway}");
tester.pump_by(ms(50));
assert_eq!(opacity_of(tester, &key), 0.0);
});
}
#[test]
fn a_new_target_mid_flight_retargets_from_the_value_on_screen() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(opacity_tree(&key, 0.0));
tester.pump_widget(opacity_tree(&key, 1.0));
tester.pump_by(ms(50));
let midpoint = opacity_of(tester, &key);
assert!((midpoint - 0.5).abs() < 0.001, "{midpoint}");
tester.pump_widget(opacity_tree(&key, 0.0));
assert!(
(opacity_of(tester, &key) - midpoint).abs() < 0.001,
"the restarted animation still shows the value on screen"
);
tester.pump_by(ms(50));
let quarter = opacity_of(tester, &key);
assert!(
(quarter - 0.25).abs() < 0.001,
"the new tween runs from the value on screen, not from 1.0: {quarter}"
);
tester.pump_by(ms(50));
assert_eq!(opacity_of(tester, &key), 0.0);
});
}
fn text_style_tree(font_size: f64, seen: &Rc<RefCell<Option<TextStyle>>>) -> WidgetRef {
let seen = Rc::clone(seen);
AnimatedDefaultTextStyle::new(
Builder::new(move |app, context| {
*seen.borrow_mut() = Some(DefaultTextStyle::of(app, context).style);
SizedBox::square(Some(10.0)).into_widget()
}),
TextStyle::new().font_size(font_size),
DURATION,
)
.into_widget()
}
#[test]
fn an_animated_default_text_style_interpolates_the_style() {
test_widgets(|tester| {
let seen: Rc<RefCell<Option<TextStyle>>> = Rc::new(RefCell::new(None));
let font_size = || {
seen.borrow()
.as_ref()
.expect("the builder ran")
.font_size
.expect("a font size")
};
tester.pump_widget(text_style_tree(10.0, &seen));
assert_eq!(font_size(), 10.0);
tester.pump_widget(text_style_tree(20.0, &seen));
assert_eq!(font_size(), 10.0);
tester.pump_by(ms(50));
let halfway = font_size();
assert!((halfway - 15.0).abs() < 0.001, "{halfway}");
tester.pump_by(ms(50));
assert_eq!(font_size(), 20.0);
});
}
#[test]
fn a_target_that_did_not_change_leaves_the_controller_dismissed() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(opacity_tree(&key, 0.5));
tester.pump_widget(opacity_tree(&key, 0.5));
tester.pump_by(ms(50));
{
let app = tester.cell.borrow();
let state = key
.current_state::<AnimatedOpacityState>(&app)
.expect("the widget is mounted");
assert!(
state.controller(&app).is_dismissed(&app),
"an unchanged target does not start the controller"
);
}
assert_eq!(opacity_of(tester, &key), 0.5);
});
}
#[test]
fn an_animated_positioned_directional_resolves_start_against_the_text_direction() {
test_widgets(|tester| {
let directional = |text_direction: TextDirection| {
Directionality::new(
text_direction,
Stack::new().children([AnimatedPositionedDirectional::new(
SizedBox::expand(),
DURATION,
)
.start(10.0)
.top(0.0)
.width(20.0)
.height(10.0)
.into_widget()]),
)
};
tester.pump_widget(directional(TextDirection::Ltr));
let positioned = |tester: &WidgetTester| {
tester.widget(find::by_type::<Positioned>(), |positioned: &Positioned| {
(positioned.left, positioned.right)
})
};
assert_eq!(positioned(tester), (Some(10.0), None));
tester.pump_widget(directional(TextDirection::Rtl));
assert_eq!(positioned(tester), (None, Some(10.0)));
});
}
#[test]
fn unmounting_frees_the_arena_tweens_the_constructors_made() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(opacity_tree(&key, 0.5));
let tween = {
let app = tester.cell.borrow();
let state = key
.current_state::<AnimatedOpacityState>(&app)
.expect("the widget is mounted");
let tween = app
.get(state)
.opacity
.handle()
.expect("for_each_tween made the tween");
assert!(app.contains(tween));
tween
};
tester.pump_widget(SizedBox::square(Some(10.0)));
tester.cell.checkpoint();
assert!(
!tester.cell.borrow().contains(tween),
"the last keeper of the arena tween is gone"
);
});
}
#[test]
fn a_text_style_tween_interpolates_the_style_fields() {
let tween = TextStyleTween::new(
Some(TextStyle::new().font_size(10.0)),
Some(TextStyle::new().font_size(20.0)),
);
assert_eq!(tween.lerp(0.5).font_size, Some(15.0));
let cell = AppCell::new();
let app = cell.borrow();
assert_eq!(tween.transform(&app, 0.0).font_size, Some(10.0));
assert_eq!(tween.transform(&app, 1.0).font_size, Some(20.0));
}
#[test]
fn a_box_constraints_tween_interpolates_the_constraints() {
let tween = BoxConstraintsTween::new(
Some(BoxConstraints::tight(Size::new(10.0, 10.0))),
Some(BoxConstraints::tight(Size::new(20.0, 30.0))),
);
let cell = AppCell::new();
let app = cell.borrow();
let halfway = tween.transform(&app, 0.5);
assert_eq!(halfway.max_width, 15.0);
assert_eq!(halfway.max_height, 20.0);
}
fn container_tree(key: &GlobalKey, width: f64, on_end: Option<Listener>) -> WidgetRef {
let mut container = AnimatedContainer::new(DURATION)
.key(key.clone().into())
.width(width)
.height(10.0);
if let Some(on_end) = on_end {
container = container.on_end(on_end);
}
crate::widgets::basic::Center::new()
.child(container)
.into_widget()
}
#[test]
fn an_animated_container_animates_its_width_and_calls_on_end_once() {
test_widgets(|tester| {
let key = GlobalKey::new();
let ends = Rc::new(Cell::new(0));
let counted = Rc::clone(&ends);
let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
tester.pump_widget(container_tree(&key, 20.0, Some(on_end.clone())));
assert_eq!(
tester.get_size(&key),
Size::new(20.0, 10.0),
"the first build does not animate"
);
tester.pump_widget(container_tree(&key, 40.0, Some(on_end)));
assert_eq!(
tester.get_size(&key).width(),
20.0,
"the frame that starts the animation still shows the old width"
);
tester.pump_by(ms(50));
let halfway = tester.get_size(&key).width();
assert!(
(halfway - 30.0).abs() < 0.001,
"halfway between 20 and 40, not {halfway}"
);
assert_eq!(ends.get(), 0, "the animation is still running");
tester.pump_by(ms(50));
assert_eq!(tester.get_size(&key).width(), 40.0);
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1);
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1, "on_end fires once per animation");
});
}
#[derive(Debug)]
struct IdentityDecoration;
impl Decoration for IdentityDecoration {
fn create_box_painter(
&self,
_on_changed: Option<waft_foundation::VoidCallback>,
) -> Box<dyn waft_painting::BoxPainter> {
Box::new(PaintsNothing)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
struct PaintsNothing;
impl waft_painting::BoxPainter for PaintsNothing {
fn paint(
&mut self,
_canvas: &mut waft_embedder::Canvas,
_offset: Offset,
_configuration: &waft_painting::ImageConfiguration,
) {
}
fn on_changed(&self) -> Option<&dyn Fn(&mut App)> {
None
}
}
#[test]
fn an_animated_container_given_its_own_decoration_again_does_not_animate() {
test_widgets(|tester| {
let decorated = |key: &GlobalKey, decoration: &DecorationRef| {
AnimatedContainer::new(DURATION)
.key(key.clone().into())
.decoration(decoration.clone())
.into_widget()
};
let key = GlobalKey::new();
let decoration = DecorationRef::new(IdentityDecoration);
tester.pump_widget(decorated(&key, &decoration));
let controller = |tester: &WidgetTester| {
let app = tester.cell.borrow();
key.current_state::<AnimatedContainerState>(&app)
.expect("the widget is mounted")
.controller(&app)
};
tester.pump_widget(decorated(&key, &decoration));
assert!(
controller(tester).is_dismissed(&tester.cell.borrow()),
"the same decoration is no new target"
);
let another = DecorationRef::new(IdentityDecoration);
tester.pump_widget(decorated(&key, &another));
let controller = controller(tester);
assert!(
controller.is_animating(&mut tester.cell.borrow_mut()),
"another decoration of the same type is, as Dart's identity `==` makes it"
);
});
}
fn padding_tree(key: &GlobalKey, text_direction: TextDirection, start: f64) -> WidgetRef {
Directionality::new(
text_direction,
AnimatedPadding::new(
EdgeInsetsGeometry::from_steb(start, 0.0, 0.0, 0.0),
DURATION,
)
.child(SizedBox::square(Some(10.0)).key(key.clone().into())),
)
.into_widget()
}
#[test]
fn an_animated_padding_interpolates_a_directional_inset() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(padding_tree(&key, TextDirection::Ltr, 0.0));
assert_eq!(tester.get_top_left(&key), Offset::ZERO);
tester.pump_widget(padding_tree(&key, TextDirection::Ltr, 40.0));
tester.pump_by(ms(50));
let halfway = tester.get_top_left(&key).dx();
assert!((halfway - 20.0).abs() < 0.001, "{halfway}");
tester.pump_by(ms(50));
assert_eq!(tester.get_top_left(&key).dx(), 40.0);
});
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(padding_tree(&key, TextDirection::Rtl, 40.0));
assert_eq!(
tester.get_top_left(&key),
Offset::ZERO,
"an rtl start is an inset on the right"
);
});
}
fn align_tree(key: &GlobalKey, alignment: AlignmentGeometry) -> WidgetRef {
AnimatedAlign::new(alignment, DURATION)
.child(SizedBox::square(Some(10.0)).key(key.clone().into()))
.into_widget()
}
#[test]
fn an_animated_align_interpolates_the_alignment() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(align_tree(&key, AlignmentGeometry::TOP_LEFT));
assert_eq!(tester.get_top_left(&key), Offset::ZERO);
tester.pump_widget(align_tree(&key, AlignmentGeometry::BOTTOM_RIGHT));
tester.pump_by(ms(50));
assert_eq!(tester.get_top_left(&key), Offset::new(395.0, 295.0));
tester.pump_by(ms(50));
assert_eq!(tester.get_top_left(&key), Offset::new(790.0, 590.0));
});
}
fn slide_tree(key: &GlobalKey, offset: Offset) -> WidgetRef {
Align::new()
.alignment(AlignmentGeometry::TOP_LEFT)
.child(
AnimatedSlide::new(offset, DURATION)
.child(SizedBox::square(Some(10.0)).key(key.clone().into())),
)
.into_widget()
}
#[test]
fn an_animated_slide_moves_the_child_by_a_fraction_of_its_size() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(slide_tree(&key, Offset::ZERO));
assert_eq!(tester.get_top_left(&key), Offset::ZERO);
tester.pump_widget(slide_tree(&key, Offset::new(2.0, 0.0)));
tester.pump_by(ms(50));
assert_eq!(tester.get_top_left(&key), Offset::new(10.0, 0.0));
tester.pump_by(ms(50));
assert_eq!(tester.get_top_left(&key), Offset::new(20.0, 0.0));
});
}
#[test]
fn a_matrix4_tween_round_trips_a_translation_and_a_scale() {
let begin = Matrix4::IDENTITY;
let end = Matrix4::translation(10.0, 20.0).then(&Matrix4::scale(3.0, 3.0));
let tween = Matrix4Tween::new(Some(begin), Some(end));
let cell = AppCell::new();
let app = cell.borrow();
assert_eq!(tween.transform(&app, 0.0), begin);
assert_eq!(tween.transform(&app, 1.0), end);
let (translation, _, scale) = decompose(tween.transform(&app, 0.5));
assert!((translation.x - 5.0).abs() < 1e-5, "{translation:?}");
assert!((translation.y - 10.0).abs() < 1e-5, "{translation:?}");
assert!((scale.x - 2.0).abs() < 1e-5, "{scale:?}");
assert!((scale.y - 2.0).abs() < 1e-5, "{scale:?}");
}
#[test]
fn an_edge_insets_geometry_tween_crosses_the_two_kinds() {
let tween = EdgeInsetsGeometryTween::new(
Some(EdgeInsetsGeometry::from_ltrb(10.0, 0.0, 0.0, 0.0)),
Some(EdgeInsetsGeometry::from_steb(20.0, 0.0, 0.0, 0.0)),
);
let cell = AppCell::new();
let app = cell.borrow();
let halfway = tween.transform(&app, 0.5);
assert_eq!(
halfway.resolve(Some(TextDirection::Ltr)),
EdgeInsets::from_ltrb(15.0, 0.0, 0.0, 0.0)
);
assert_eq!(
halfway.resolve(Some(TextDirection::Rtl)),
EdgeInsets::from_ltrb(5.0, 0.0, 10.0, 0.0)
);
}
#[test]
fn a_border_radius_tween_interpolates_the_radius() {
use waft_embedder::Radius;
let tween = BorderRadiusTween::new(
Some(BorderRadius::all(Radius::circular(0.0))),
Some(BorderRadius::all(Radius::circular(10.0))),
);
let cell = AppCell::new();
let app = cell.borrow();
let halfway = tween.transform(&app, 0.5).expect("both ends are set");
assert_eq!(halfway.top_left.x, 5.0);
}
#[test]
fn an_implicit_animation_moved_by_a_global_key_follows_its_view_and_ticker_mode() {
use waft_embedder::{TargetPlatform, ViewId};
use waft_test::TestPlatform;
use crate::view::ViewCollection;
use crate::widgets::ticker_provider::TickerMode;
let (first, second) = (ViewId(1), ViewId(2));
let platform = Rc::new(
TestPlatform::new()
.on(TargetPlatform::MacOS)
.with_views(&[first, second]),
);
let cell = AppCell::with_platform(platform.clone());
let key = GlobalKey::new();
let tree = |view: ViewId, enabled: bool, opacity: f64| -> WidgetRef {
let animated = TickerMode::new(
enabled,
AnimatedOpacity::new(opacity, DURATION).key(key.clone().into()),
)
.into_widget();
let (in_first, in_second) = if view == first {
(animated, SizedBox::new().into_widget())
} else {
(SizedBox::new().into_widget(), animated)
};
ViewCollection::new(vec![
View::new(platform.test_view(first), in_first).into_widget(),
View::new(platform.test_view(second), in_second).into_widget(),
])
.into_widget()
};
let pump = |app: &mut App, view: ViewId, ms: u64| {
crate::test_harness::binding_pump_view(app, view, Duration::from_millis(ms));
};
let attach = |app: &mut App, root: WidgetRef| {
WidgetsBinding::instance(app).attach_root_widget(app, root);
};
crate::binding::run_widget(&mut cell.borrow_mut(), tree(first, true, 1.0));
cell.elapse(Duration::ZERO);
let mut app = cell.borrow_mut();
let value = |app: &mut App| {
let state = key
.current_state::<AnimatedOpacityState>(app)
.expect("mounted");
ImplicitlyAnimatedWidgetState::controller(state, app).value(app)
};
attach(&mut app, tree(first, true, 0.0));
pump(&mut app, first, 16);
pump(&mut app, first, 32);
let before_move = value(&mut app);
assert!(before_move > 0.0, "it animates in the first view");
attach(&mut app, tree(second, true, 0.0));
pump(&mut app, second, 48);
assert_eq!(value(&mut app), before_move);
pump(&mut app, first, 64);
assert_eq!(
value(&mut app),
before_move,
"no tick at the first view's frame"
);
pump(&mut app, second, 64);
let moved = value(&mut app);
assert!(moved > before_move, "it ticks at the second view's frame");
attach(&mut app, tree(first, false, 0.0));
pump(&mut app, first, 80);
let muted = value(&mut app);
pump(&mut app, first, 96);
pump(&mut app, second, 96);
assert_eq!(value(&mut app), muted, "muted by its new TickerMode");
}
#[test]
fn an_animated_physical_model_defaults_to_a_physical_models_arguments() {
let color = Color::new(0x00000000);
let animated = AnimatedPhysicalModel::new(SizedBox::shrink(), color, color, Duration::ZERO);
let physical = PhysicalModel::new(color).shadow_color(color);
assert_eq!(animated.shape, physical.shape);
assert_eq!(animated.clip_behavior, physical.clip_behavior);
assert_eq!(animated.border_radius, physical.border_radius);
}
fn physical_model_tree(
key: &GlobalKey,
elevation: f64,
color: Color,
animate_color: bool,
) -> WidgetRef {
AnimatedPhysicalModel::new(
SizedBox::square(Some(10.0)),
color,
Color::new(0xFF000000),
DURATION,
)
.key(key.clone().into())
.elevation(elevation)
.animate_color(animate_color)
.into_widget()
}
fn physical_model_of(
tester: &WidgetTester,
key: &GlobalKey,
) -> RenderHandle<waft_rendering::RenderPhysicalModel> {
let render_object = tester.render_object(key);
render_object
.downcast::<waft_rendering::RenderPhysicalModel>(&tester.cell.borrow())
.expect("a RenderPhysicalModel")
}
#[test]
fn an_animated_physical_model_animates_its_elevation_and_colour() {
use waft_rendering::RenderPhysicalModelBase;
for animate_color in [true, false] {
test_widgets(|tester| {
let key = GlobalKey::new();
let red = Color::new(0xFFFF0000);
let blue = Color::new(0xFF0000FF);
tester.pump_widget(physical_model_tree(&key, 0.0, red, animate_color));
assert_eq!(
physical_model_of(tester, &key).elevation(&tester.cell.borrow()),
0.0
);
tester.pump_widget(physical_model_tree(&key, 8.0, blue, animate_color));
tester.pump_by(ms(50));
let model = physical_model_of(tester, &key);
let app = tester.cell.borrow();
let halfway = model.elevation(&app);
assert!((halfway - 4.0).abs() < 0.001, "{halfway}");
let color = model.color(&app);
if animate_color {
assert_eq!(
color,
Color::lerp(Some(red), Some(blue), 0.5).expect("two colours")
);
} else {
assert_eq!(color, blue);
}
drop(app);
tester.pump_by(ms(50));
let model = physical_model_of(tester, &key);
let app = tester.cell.borrow();
assert_eq!(model.elevation(&app), 8.0);
assert_eq!(model.color(&app), blue);
});
}
}
#[test]
fn an_animated_physical_model_calls_on_end_once_its_animation_ends() {
test_widgets(|tester| {
let key = GlobalKey::new();
let ends = Rc::new(Cell::new(0));
let counted = Rc::clone(&ends);
let on_end = Listener::new(move |_app| counted.set(counted.get() + 1));
let tree = |elevation: f64| {
AnimatedPhysicalModel::new(
SizedBox::square(Some(10.0)),
Color::new(0xFF0000FF),
Color::new(0xFF000000),
DURATION,
)
.key(key.clone().into())
.elevation(elevation)
.on_end(on_end.clone())
.into_widget()
};
tester.pump_widget(tree(0.0));
tester.pump_widget(tree(4.0));
tester.pump_by(ms(50));
assert_eq!(ends.get(), 0);
tester.pump_by(ms(50));
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1);
tester.pump_by(ms(50));
assert_eq!(ends.get(), 1);
});
}
#[test]
fn an_animated_physical_model_does_not_crash_at_zero_area() {
test_widgets(|tester| {
let physical_model_color = Color::new(0xFF009688);
let physical_model_shadow_color = Color::new(0xFF64FFDA);
tester.pump_widget(Directionality::new(
TextDirection::Ltr,
crate::widgets::basic::Center::new().child(SizedBox::shrink().child(
AnimatedPhysicalModel::new(
Text::new("X"),
physical_model_color,
physical_model_shadow_color,
Duration::from_millis(300),
),
)),
));
tester.pump_and_settle();
assert_eq!(
tester.get_size(find::by_type::<AnimatedPhysicalModel>()),
Size::ZERO
);
});
}
#[test]
fn a_shape_border_value_is_the_same_by_its_equality() {
use waft_painting::{BorderSide, CircleBorder, RoundedRectangleBorder};
let rounded = |radius: f64| -> Option<ShapeBorderRef> {
Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
BorderSide::NONE,
BorderRadius::circular(radius).into(),
)))
};
assert!(rounded(2.0).same(&rounded(2.0)));
assert!(!rounded(2.0).same(&rounded(4.0)));
assert!(
!rounded(2.0).same(&Some(ShapeBorderRef::new(CircleBorder::new(
BorderSide::NONE,
0.0
))))
);
assert!(!rounded(2.0).same(&None));
assert!(None::<ShapeBorderRef>.same(&None));
}
}