use std::f64::consts::PI;
use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_animation::{Animatable, AnyAnimation};
use waft_embedder::{Matrix4, Offset, Rect, Size, TextAlign, TextDirection};
use waft_foundation::{App, Handle, Listenable, Listener};
use waft_painting::{Alignment, AlignmentGeometry, Axis, Decoration, TextOverflow, TextStyle};
use waft_rendering::{
AnyRenderObject, DecorationPosition, RelativeRect, RenderAnimatedOpacity,
RenderAnimatedOpacityMixin, RenderBox, RenderHandle,
};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
StateData, Stateful, StatefulWidget, WidgetRef, downcast_widget,
};
use crate::widgets::basic::{Align, ClipRect, FractionalTranslation, Positioned, Transform};
use crate::widgets::container::DecoratedBox;
use crate::widgets::text::DefaultTextStyle;
pub trait AnimatedWidget: Debug + 'static {
fn key(&self) -> Option<&KeyRef> {
None
}
fn listenable(&self) -> Rc<dyn Listenable>;
fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
}
pub struct AnimatedKind;
pub struct Animated<W: AnimatedWidget>(pub W);
impl<W: AnimatedWidget> IntoWidget<AnimatedKind> for W {
fn into_widget(self) -> WidgetRef {
Rc::new(Stateful(Animated(self)))
}
}
impl<W: AnimatedWidget> StatefulWidget for Animated<W> {
type State = AnimatedState<W>;
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_state(&self) -> AnimatedState<W> {
AnimatedState {
state: StateData::new(),
}
}
}
impl<W: AnimatedWidget> Debug for Animated<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub struct AnimatedState<W: AnimatedWidget> {
state: StateData<Animated<W>>,
}
impl<W: AnimatedWidget> State for AnimatedState<W> {
type Widget = Animated<W>;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let listenable = self.widget(app).0.listenable();
listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Animated<W>) {
let listenable = self.widget(app).0.listenable();
let old_listenable = old_widget.0.listenable();
if !Rc::ptr_eq(&listenable, &old_listenable) {
old_listenable
.remove_listener(app, &Listener::handle_method(self, Self::handle_change));
listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
let listenable = self.widget(app).0.listenable();
listenable.remove_listener(app, &Listener::handle_method(self, Self::handle_change));
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let widget = context.widget(app).clone();
downcast_widget::<Animated<W>>(&*widget)
.expect("an AnimatedState builds its AnimatedWidget")
.0
.build(app, context)
}
}
impl<W: AnimatedWidget> AnimatedState<W> {
fn handle_change(self: Handle<Self>, app: &mut App) {
if !self.mounted(app) {
return;
}
self.set_state(app, |_state| {
});
}
}
pub type DelegatedTransitionBuilder = Rc<
dyn Fn(
&mut App,
BuildContext,
AnyAnimation<f64>,
AnyAnimation<f64>,
bool,
Option<&WidgetRef>,
) -> Option<WidgetRef>,
>;
#[derive(Debug)]
pub struct SlideTransition {
pub key: Option<KeyRef>,
pub position: AnyAnimation<Offset>,
pub text_direction: Option<TextDirection>,
pub transform_hit_tests: bool,
pub child: Option<WidgetRef>,
}
impl SlideTransition {
pub fn new(position: AnyAnimation<Offset>) -> SlideTransition {
SlideTransition {
key: None,
position,
text_direction: None,
transform_hit_tests: true,
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> SlideTransition {
self.key = Some(key);
self
}
pub fn text_direction(mut self, text_direction: TextDirection) -> SlideTransition {
self.text_direction = Some(text_direction);
self
}
pub fn transform_hit_tests(mut self, transform_hit_tests: bool) -> SlideTransition {
self.transform_hit_tests = transform_hit_tests;
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SlideTransition {
self.child = Some(child.into_widget());
self
}
}
impl AnimatedWidget for SlideTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.position)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let mut offset = self.position.value(app);
if self.text_direction == Some(TextDirection::Rtl) {
offset = Offset::new(-offset.dx(), offset.dy());
}
let mut translation =
FractionalTranslation::new(offset).transform_hit_tests(self.transform_hit_tests);
if let Some(child) = &self.child {
translation = translation.child(child.clone());
}
translation.into_widget()
}
}
pub type TransformCallback = Rc<dyn Fn(f64) -> Matrix4>;
pub struct MatrixTransition {
pub key: Option<KeyRef>,
pub on_transform: TransformCallback,
pub animation: AnyAnimation<f64>,
pub alignment: Alignment,
pub child: Option<WidgetRef>,
}
impl MatrixTransition {
pub fn new(
animation: AnyAnimation<f64>,
on_transform: impl Fn(f64) -> Matrix4 + 'static,
) -> MatrixTransition {
MatrixTransition {
key: None,
on_transform: Rc::new(on_transform),
animation,
alignment: Alignment::CENTER,
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> MatrixTransition {
self.key = Some(key);
self
}
pub fn alignment(mut self, alignment: Alignment) -> MatrixTransition {
self.alignment = alignment;
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MatrixTransition {
self.child = Some(child.into_widget());
self
}
fn build_transform(
transform: Matrix4,
alignment: Alignment,
child: Option<&WidgetRef>,
) -> WidgetRef {
let mut transform =
Transform::new(transform).alignment(AlignmentGeometry::Alignment(alignment));
if let Some(child) = child {
transform = transform.child(child.clone());
}
transform.into_widget()
}
}
impl Debug for MatrixTransition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MatrixTransition")
.field("animation", &self.animation)
.field("alignment", &self.alignment)
.field("child", &self.child)
.finish_non_exhaustive()
}
}
impl AnimatedWidget for MatrixTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.animation)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let transform = (self.on_transform)(self.animation.value(app));
MatrixTransition::build_transform(transform, self.alignment, self.child.as_ref())
}
}
#[derive(Debug)]
pub struct ScaleTransition {
pub key: Option<KeyRef>,
pub animation: AnyAnimation<f64>,
pub alignment: Alignment,
pub child: Option<WidgetRef>,
}
impl ScaleTransition {
pub fn new(scale: AnyAnimation<f64>) -> ScaleTransition {
ScaleTransition {
key: None,
animation: scale,
alignment: Alignment::CENTER,
child: None,
}
}
pub fn scale(&self) -> AnyAnimation<f64> {
self.animation
}
pub fn key(mut self, key: KeyRef) -> ScaleTransition {
self.key = Some(key);
self
}
pub fn alignment(mut self, alignment: Alignment) -> ScaleTransition {
self.alignment = alignment;
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ScaleTransition {
self.child = Some(child.into_widget());
self
}
fn handle_scale_matrix(value: f64) -> Matrix4 {
Matrix4::scale(value as f32, value as f32)
}
}
impl AnimatedWidget for ScaleTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.animation)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let transform = ScaleTransition::handle_scale_matrix(self.animation.value(app));
MatrixTransition::build_transform(transform, self.alignment, self.child.as_ref())
}
}
#[derive(Debug)]
pub struct RotationTransition {
pub key: Option<KeyRef>,
pub animation: AnyAnimation<f64>,
pub alignment: Alignment,
pub child: Option<WidgetRef>,
}
impl RotationTransition {
pub fn new(turns: AnyAnimation<f64>) -> RotationTransition {
RotationTransition {
key: None,
animation: turns,
alignment: Alignment::CENTER,
child: None,
}
}
pub fn turns(&self) -> AnyAnimation<f64> {
self.animation
}
pub fn key(mut self, key: KeyRef) -> RotationTransition {
self.key = Some(key);
self
}
pub fn alignment(mut self, alignment: Alignment) -> RotationTransition {
self.alignment = alignment;
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RotationTransition {
self.child = Some(child.into_widget());
self
}
fn handle_turns_matrix(value: f64) -> Matrix4 {
Matrix4::rotation((value * PI * 2.0) as f32)
}
}
impl AnimatedWidget for RotationTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.animation)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let transform = RotationTransition::handle_turns_matrix(self.animation.value(app));
MatrixTransition::build_transform(transform, self.alignment, self.child.as_ref())
}
}
#[derive(Debug)]
pub struct SizeTransition {
pub key: Option<KeyRef>,
pub axis: Axis,
pub size_factor: AnyAnimation<f64>,
#[deprecated(
note = "Use alignment instead. This property provides full control over both axes, \
which is an improvement over the old axisAlignment. This feature was \
deprecated after v3.41.0-1.0.pre."
)]
pub axis_alignment: Option<f64>,
pub alignment: Option<AlignmentGeometry>,
pub fixed_cross_axis_size_factor: Option<f64>,
pub child: Option<WidgetRef>,
}
impl SizeTransition {
#[allow(deprecated)]
pub fn new(size_factor: AnyAnimation<f64>) -> SizeTransition {
SizeTransition {
key: None,
axis: Axis::Vertical,
size_factor,
axis_alignment: None,
alignment: None,
fixed_cross_axis_size_factor: None,
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> SizeTransition {
self.key = Some(key);
self
}
pub fn axis(mut self, axis: Axis) -> SizeTransition {
self.axis = axis;
self
}
#[deprecated(
note = "Use alignment instead. This property provides full control over both axes, \
which is an improvement over the old axisAlignment. This feature was \
deprecated after v3.41.0-1.0.pre."
)]
#[allow(deprecated)]
pub fn axis_alignment(mut self, axis_alignment: f64) -> SizeTransition {
debug_assert!(
self.alignment.is_none(),
"Cannot provide both axisAlignment and alignment as axisAlignment has been \
deprecated and superseded by alignment."
);
self.axis_alignment = Some(axis_alignment);
self
}
#[allow(deprecated)]
pub fn alignment(mut self, alignment: AlignmentGeometry) -> SizeTransition {
debug_assert!(
self.axis_alignment.is_none(),
"Cannot provide both axisAlignment and alignment as axisAlignment has been \
deprecated and superseded by alignment."
);
self.alignment = Some(alignment);
self
}
pub fn fixed_cross_axis_size_factor(
mut self,
fixed_cross_axis_size_factor: f64,
) -> SizeTransition {
debug_assert!(fixed_cross_axis_size_factor >= 0.0);
self.fixed_cross_axis_size_factor = Some(fixed_cross_axis_size_factor);
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SizeTransition {
self.child = Some(child.into_widget());
self
}
}
impl AnimatedWidget for SizeTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.size_factor)
}
#[allow(deprecated)]
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let axis_alignment = self.axis_alignment.unwrap_or(0.0);
let alignment = self.alignment.unwrap_or(match self.axis {
Axis::Horizontal => AlignmentGeometry::directional(axis_alignment, -1.0),
Axis::Vertical => AlignmentGeometry::directional(-1.0, axis_alignment),
});
let size_factor = self.size_factor.value(app).max(0.0);
let (height_factor, width_factor) = match self.axis {
Axis::Vertical => (Some(size_factor), self.fixed_cross_axis_size_factor),
Axis::Horizontal => (self.fixed_cross_axis_size_factor, Some(size_factor)),
};
let mut align = Align::new().alignment(alignment);
if let Some(height_factor) = height_factor {
align = align.height_factor(height_factor);
}
if let Some(width_factor) = width_factor {
align = align.width_factor(width_factor);
}
if let Some(child) = &self.child {
align = align.child(child.clone());
}
ClipRect::new().child(align).into_widget()
}
}
#[derive(Debug)]
pub struct FadeTransition {
pub key: Option<KeyRef>,
pub opacity: AnyAnimation<f64>,
pub child: Option<WidgetRef>,
}
impl FadeTransition {
pub fn new(opacity: AnyAnimation<f64>) -> FadeTransition {
FadeTransition {
key: None,
opacity,
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> FadeTransition {
self.key = Some(key);
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FadeTransition {
self.child = Some(child.into_widget());
self
}
}
impl RenderObjectWidget for FadeTransition {
type RenderObject = RenderAnimatedOpacity;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
RenderAnimatedOpacity::new(app, self.opacity, None).as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderAnimatedOpacity>,
) {
render_object.set_opacity(app, self.opacity);
}
}
impl SingleChildRenderObjectWidget for FadeTransition {
fn child(&self) -> Option<&WidgetRef> {
self.child.as_ref()
}
}
#[derive(Clone, Debug)]
pub struct RelativeRectTween {
pub begin: Option<RelativeRect>,
pub end: Option<RelativeRect>,
}
impl RelativeRectTween {
pub fn new(begin: Option<RelativeRect>, end: Option<RelativeRect>) -> RelativeRectTween {
RelativeRectTween { begin, end }
}
pub fn lerp(&self, t: f64) -> RelativeRect {
RelativeRect::lerp(self.begin, self.end, t)
.expect("RelativeRectTween.begin or end must be set before use")
}
}
impl Animatable<RelativeRect> for RelativeRectTween {
fn transform(&self, _app: &App, t: f64) -> RelativeRect {
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(Debug)]
pub struct PositionedTransition {
pub key: Option<KeyRef>,
pub rect: AnyAnimation<RelativeRect>,
pub child: WidgetRef,
}
impl PositionedTransition {
pub fn new<K>(
rect: AnyAnimation<RelativeRect>,
child: impl IntoWidget<K>,
) -> PositionedTransition {
PositionedTransition {
key: None,
rect,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> PositionedTransition {
self.key = Some(key);
self
}
}
impl AnimatedWidget for PositionedTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.rect)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
Positioned::from_relative_rect(self.rect.value(app), self.child.clone()).into_widget()
}
}
#[derive(Debug)]
pub struct RelativePositionedTransition {
pub key: Option<KeyRef>,
pub rect: AnyAnimation<Option<Rect>>,
pub size: Size,
pub child: WidgetRef,
}
impl RelativePositionedTransition {
pub fn new<K>(
rect: AnyAnimation<Option<Rect>>,
size: Size,
child: impl IntoWidget<K>,
) -> RelativePositionedTransition {
RelativePositionedTransition {
key: None,
rect,
size,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> RelativePositionedTransition {
self.key = Some(key);
self
}
}
impl AnimatedWidget for RelativePositionedTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.rect)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let offsets =
RelativeRect::from_size(self.rect.value(app).unwrap_or(Rect::ZERO), self.size);
Positioned::new(self.child.clone())
.top(offsets.top)
.right(offsets.right)
.bottom(offsets.bottom)
.left(offsets.left)
.into_widget()
}
}
#[derive(Debug)]
pub struct DecoratedBoxTransition {
pub key: Option<KeyRef>,
pub decoration: AnyAnimation<Box<dyn Decoration>>,
pub position: DecorationPosition,
pub child: WidgetRef,
}
impl DecoratedBoxTransition {
pub fn new<K>(
decoration: AnyAnimation<Box<dyn Decoration>>,
child: impl IntoWidget<K>,
) -> DecoratedBoxTransition {
DecoratedBoxTransition {
key: None,
decoration,
position: DecorationPosition::Background,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> DecoratedBoxTransition {
self.key = Some(key);
self
}
pub fn position(mut self, position: DecorationPosition) -> DecoratedBoxTransition {
self.position = position;
self
}
}
impl AnimatedWidget for DecoratedBoxTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.decoration)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
DecoratedBox {
key: None,
decoration: self.decoration.value(app),
position: self.position,
child: Some(self.child.clone()),
}
.into_widget()
}
}
#[derive(Debug)]
pub struct AlignTransition {
pub key: Option<KeyRef>,
pub alignment: AnyAnimation<AlignmentGeometry>,
pub width_factor: Option<f64>,
pub height_factor: Option<f64>,
pub child: WidgetRef,
}
impl AlignTransition {
pub fn new<K>(
alignment: AnyAnimation<AlignmentGeometry>,
child: impl IntoWidget<K>,
) -> AlignTransition {
AlignTransition {
key: None,
alignment,
width_factor: None,
height_factor: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> AlignTransition {
self.key = Some(key);
self
}
pub fn width_factor(mut self, width_factor: f64) -> AlignTransition {
self.width_factor = Some(width_factor);
self
}
pub fn height_factor(mut self, height_factor: f64) -> AlignTransition {
self.height_factor = Some(height_factor);
self
}
}
impl AnimatedWidget for AlignTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.alignment)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let mut align = Align::new().alignment(self.alignment.value(app));
if let Some(width_factor) = self.width_factor {
align = align.width_factor(width_factor);
}
if let Some(height_factor) = self.height_factor {
align = align.height_factor(height_factor);
}
align.child(self.child.clone()).into_widget()
}
}
#[derive(Debug)]
pub struct DefaultTextStyleTransition {
pub key: Option<KeyRef>,
pub style: AnyAnimation<TextStyle>,
pub text_align: Option<TextAlign>,
pub soft_wrap: bool,
pub overflow: TextOverflow,
pub max_lines: Option<i32>,
pub child: WidgetRef,
}
impl DefaultTextStyleTransition {
pub fn new<K>(
style: AnyAnimation<TextStyle>,
child: impl IntoWidget<K>,
) -> DefaultTextStyleTransition {
DefaultTextStyleTransition {
key: None,
style,
text_align: None,
soft_wrap: true,
overflow: TextOverflow::Clip,
max_lines: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> DefaultTextStyleTransition {
self.key = Some(key);
self
}
pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleTransition {
self.text_align = Some(text_align);
self
}
pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleTransition {
self.soft_wrap = soft_wrap;
self
}
pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleTransition {
self.overflow = overflow;
self
}
pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleTransition {
self.max_lines = Some(max_lines);
self
}
}
impl AnimatedWidget for DefaultTextStyleTransition {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.style)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
let mut default_text_style =
DefaultTextStyle::new(self.style.value(app), self.child.clone())
.soft_wrap(self.soft_wrap)
.overflow(self.overflow);
if let Some(text_align) = self.text_align {
default_text_style = default_text_style.text_align(text_align);
}
if let Some(max_lines) = self.max_lines {
default_text_style = default_text_style.max_lines(max_lines);
}
default_text_style.into_widget()
}
}
pub type TransitionBuilder = Rc<dyn Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef>;
pub struct ListenableBuilder {
pub key: Option<KeyRef>,
pub listenable: Rc<dyn Listenable>,
pub builder: TransitionBuilder,
pub child: Option<WidgetRef>,
}
pub type AnimatedBuilder = ListenableBuilder;
impl ListenableBuilder {
pub fn new(
listenable: Rc<dyn Listenable>,
builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
) -> ListenableBuilder {
ListenableBuilder {
key: None,
listenable,
builder: Rc::new(builder),
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> ListenableBuilder {
self.key = Some(key);
self
}
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ListenableBuilder {
self.child = Some(child.into_widget());
self
}
pub fn animation(&self) -> Rc<dyn Listenable> {
Rc::clone(&self.listenable)
}
}
impl Debug for ListenableBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ListenableBuilder")
.field("child", &self.child)
.finish_non_exhaustive()
}
}
impl AnimatedWidget for ListenableBuilder {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::clone(&self.listenable)
}
fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
(self.builder)(app, context, self.child.as_ref())
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::time::Duration;
use waft_foundation::AppCell;
use waft_animation::{AnimationBehavior, AnimationController, CallbackAnimatable};
use waft_embedder::Color;
use waft_foundation::{ChangeNotifier, ValueNotifier};
use waft_painting::{AnyColor, BoxDecoration};
use waft_rendering::{
BoxConstraints, ContainerRenderObjectMixin, RenderAligningShiftedBox, RenderConstrainedBox,
RenderFractionalTranslation, RenderObjectWithChildMixin, RenderTransform,
};
use waft_scheduler::{Ticker, TickerCallback, TickerProvider};
use super::*;
use crate::framework::LeafRenderObjectWidget;
use crate::test_harness::Harness;
use crate::widgets::basic::{Builder, Directionality, SizedBox, Stack};
struct TestVSync;
impl TickerProvider for TestVSync {
fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Handle<Ticker> {
Ticker::new(app, on_tick, None)
}
}
#[derive(Debug)]
struct Sized {
size: Size,
}
impl RenderObjectWidget for Sized {
type RenderObject = RenderConstrainedBox;
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderConstrainedBox>,
) {
render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
}
}
impl LeafRenderObjectWidget for Sized {}
fn new_controller(app: &mut App) -> Handle<AnimationController> {
AnimationController::create(
app,
None,
Some(Duration::from_millis(100)),
None,
0.0,
1.0,
AnimationBehavior::Normal,
TestVSync,
)
}
fn fade(opacity: AnyAnimation<f64>) -> WidgetRef {
FadeTransition::new(opacity)
.child(Sized {
size: Size::new(10.0, 10.0),
})
.into_widget()
}
fn fade_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderAnimatedOpacity> {
harness
.render_root(app)
.child(app)
.expect("a child")
.as_object()
.downcast::<RenderAnimatedOpacity>(app)
.expect("a RenderAnimatedOpacity")
}
fn root_child_size(harness: &Harness, app: &App) -> Size {
harness
.render_root(app)
.child(app)
.expect("a child")
.size(app)
}
fn under_root<T: waft_rendering::RenderObject>(
harness: &Harness,
app: &App,
) -> RenderHandle<T> {
harness
.render_root(app)
.child(app)
.expect("a child")
.as_object()
.downcast::<T>(app)
.expect("the expected render object")
}
fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
Directionality::new(TextDirection::Ltr, child).into_widget()
}
fn ten_by_ten() -> Sized {
Sized {
size: Size::new(10.0, 10.0),
}
}
fn assert_close(actual: Offset, expected: Offset) {
assert!(
(actual.dx() - expected.dx()).abs() < 1e-4
&& (actual.dy() - expected.dy()).abs() < 1e-4,
"{actual:?} is not {expected:?}"
);
}
#[test]
fn a_slide_transition_translates_by_the_animation_and_flips_in_rtl() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let position = controller.drive(
&mut app,
CallbackAnimatable::from_callback(|t| Offset::new(t, t * 2.0)),
);
let slide = |text_direction: Option<TextDirection>| {
let mut transition = SlideTransition::new(position)
.transform_hit_tests(false)
.child(ten_by_ten());
if let Some(text_direction) = text_direction {
transition = transition.text_direction(text_direction);
}
transition.into_widget()
};
let harness = Harness::mount(&mut app, slide(None));
harness.pump(&mut app);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let translation: RenderHandle<RenderFractionalTranslation> = under_root(&harness, &app);
assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
assert!(!translation.transform_hit_tests(&app));
harness.set_child(&mut app, slide(Some(TextDirection::Rtl)));
harness.pump(&mut app);
assert_eq!(translation.translation(&app), Offset::new(-0.5, 1.0));
harness.set_child(&mut app, slide(Some(TextDirection::Ltr)));
harness.pump(&mut app);
assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
controller.dispose(&mut app);
}
#[test]
fn a_matrix_transition_paints_the_matrix_its_callback_returns() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let widget = MatrixTransition::new(controller.view(), |value| {
Matrix4::translation(value as f32 * 100.0, 0.0)
})
.alignment(Alignment::TOP_LEFT)
.child(ten_by_ten())
.into_widget();
let harness = Harness::mount(&mut app, widget);
harness.pump(&mut app);
let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
assert_eq!(
transform.alignment(&app),
Some(AlignmentGeometry::Alignment(Alignment::TOP_LEFT))
);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let child = transform.child(&app).expect("the sized child");
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(50.0, 0.0),
);
controller.dispose(&mut app);
}
#[test]
fn a_scale_transition_scales_about_its_alignment() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let widget = ScaleTransition::new(controller.view())
.child(ten_by_ten())
.into_widget();
let harness = Harness::mount(&mut app, widget);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
assert_eq!(
transform.alignment(&app),
Some(AlignmentGeometry::Alignment(Alignment::CENTER))
);
let child = transform.child(&app).expect("the sized child");
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(2.5, 2.5),
);
controller.set_value(&mut app, 1.0);
harness.pump(&mut app);
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::ZERO,
);
controller.dispose(&mut app);
}
#[test]
fn a_rotation_transition_turns_a_full_circle_per_unit() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let widget = RotationTransition::new(controller.view())
.child(ten_by_ten())
.into_widget();
let harness = Harness::mount(&mut app, widget);
controller.set_value(&mut app, 0.25);
harness.pump(&mut app);
let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
let child = transform.child(&app).expect("the sized child");
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(10.0, 0.0),
);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(10.0, 10.0),
);
controller.dispose(&mut app);
}
#[test]
fn a_size_transition_clips_its_child_to_the_size_factor() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let widget = SizeTransition::new(controller.view())
.child(ten_by_ten())
.into_widget();
let harness = Harness::mount(&mut app, ltr(widget));
harness.pump(&mut app);
let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
assert_eq!(clip.size(&app).height(), 0.0);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
assert_eq!(clip.size(&app).height(), 5.0);
assert_eq!(
clip.size(&app).width(),
crate::test_harness::VIEW_WIDTH,
"the cross axis is as large as the parent"
);
controller.set_value(&mut app, 1.0);
harness.pump(&mut app);
assert_eq!(clip.size(&app).height(), 10.0);
controller.dispose(&mut app);
}
#[test]
fn a_horizontal_size_transition_fixes_its_cross_axis_factor() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let widget = SizeTransition::new(controller.view())
.axis(Axis::Horizontal)
.fixed_cross_axis_size_factor(1.0)
.child(ten_by_ten())
.into_widget();
let harness = Harness::mount(&mut app, ltr(widget));
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
assert_eq!(clip.size(&app), Size::new(5.0, 10.0));
controller.dispose(&mut app);
}
#[test]
fn a_positioned_transition_places_its_child_by_the_relative_rect() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let tween = RelativeRectTween::new(
Some(RelativeRect::from_ltrb(0.0, 0.0, 200.0, 100.0)),
Some(RelativeRect::from_ltrb(100.0, 50.0, 0.0, 0.0)),
);
let rect = controller.drive(&mut app, tween);
let widget = Stack::new()
.children([PositionedTransition::new(rect, ten_by_ten()).into_widget()])
.into_widget();
let harness = Harness::mount(&mut app, ltr(widget));
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
let child = stack.first_child(&app).expect("the positioned child");
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(50.0, 25.0),
);
assert_eq!(child.size(&app), Size::new(150.0, 125.0));
controller.dispose(&mut app);
}
#[test]
fn a_relative_positioned_transition_places_its_child_inside_the_given_size() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let rect = controller.drive(
&mut app,
CallbackAnimatable::from_callback(|t| {
Some(Rect::from_ltwh(t * 40.0, t * 20.0, 30.0, 15.0))
}),
);
let widget = Stack::new()
.children([RelativePositionedTransition::new(
rect,
Size::new(100.0, 100.0),
ten_by_ten(),
)
.into_widget()])
.into_widget();
let harness = Harness::mount(&mut app, ltr(widget));
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
let child = stack.first_child(&app).expect("the positioned child");
assert_close(
child.local_to_global(&app, Offset::ZERO, None),
Offset::new(20.0, 10.0),
);
assert_eq!(
child.size(&app),
Size::new(
crate::test_harness::VIEW_WIDTH - 20.0 - 50.0,
crate::test_harness::VIEW_HEIGHT - 10.0 - 75.0,
)
);
controller.dispose(&mut app);
}
#[derive(Clone)]
struct FadingBlack;
impl Animatable<Box<dyn Decoration>> for FadingBlack {
fn transform(&self, _app: &App, t: f64) -> Box<dyn Decoration> {
Box::new(BoxDecoration::new().color(Color::from_argb(
(t * 255.0).round() as i32,
0,
0,
0,
)))
}
}
#[test]
fn a_decorated_box_transition_hands_the_animated_decoration_to_its_render_object() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let decoration = controller.drive(&mut app, FadingBlack);
let widget = DecoratedBoxTransition::new(decoration, ten_by_ten())
.position(DecorationPosition::Foreground)
.into_widget();
let harness = Harness::mount(&mut app, widget);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let decorated: RenderHandle<waft_rendering::RenderDecoratedBox> =
under_root(&harness, &app);
assert_eq!(decorated.position(&app), DecorationPosition::Foreground);
let painted = (decorated.decoration(&app) as &dyn std::any::Any)
.downcast_ref::<BoxDecoration>()
.expect("a BoxDecoration");
assert_eq!(
painted.color.as_ref().map(AnyColor::color),
Some(Color::from_argb(128, 0, 0, 0))
);
controller.dispose(&mut app);
}
#[test]
fn an_align_transition_hands_the_animated_alignment_to_its_render_object() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let alignment = controller.drive(
&mut app,
CallbackAnimatable::from_callback(|t| AlignmentGeometry::xy(t, -t)),
);
let widget = AlignTransition::new(alignment, ten_by_ten())
.width_factor(2.0)
.height_factor(3.0)
.into_widget();
let harness = Harness::mount(&mut app, widget);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
let positioned: RenderHandle<waft_rendering::RenderPositionedBox> =
under_root(&harness, &app);
assert_eq!(
RenderAligningShiftedBox::alignment(positioned, &app),
AlignmentGeometry::xy(0.5, -0.5)
);
assert_eq!(positioned.width_factor(&app), Some(2.0));
assert_eq!(positioned.height_factor(&app), Some(3.0));
assert_eq!(positioned.size(&app), Size::new(20.0, 30.0));
controller.dispose(&mut app);
}
#[test]
fn a_default_text_style_transition_publishes_the_animated_style() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let style = controller.drive(
&mut app,
CallbackAnimatable::from_callback(|t| TextStyle::new().font_size(10.0 + t * 10.0)),
);
let seen: Rc<Cell<f64>> = Rc::new(Cell::new(0.0));
let child = Builder {
key: None,
builder: Rc::new({
let seen = Rc::clone(&seen);
move |app, context| {
let default = DefaultTextStyle::of(app, context);
seen.set(default.style.font_size.expect("a font size"));
ten_by_ten().into_widget()
}
}),
};
let widget = DefaultTextStyleTransition::new(style, child)
.max_lines(3)
.overflow(TextOverflow::Ellipsis)
.soft_wrap(false)
.into_widget();
let harness = Harness::mount(&mut app, widget);
controller.set_value(&mut app, 0.5);
harness.pump(&mut app);
assert_eq!(seen.get(), 15.0);
controller.set_value(&mut app, 1.0);
harness.pump(&mut app);
assert_eq!(seen.get(), 20.0);
controller.dispose(&mut app);
}
#[test]
fn a_fade_transition_hands_its_animation_to_the_render_object() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = new_controller(&mut app);
let harness = Harness::mount(&mut app, fade(controller.view()));
harness.pump(&mut app);
let render_object = fade_under_root(&harness, &app);
assert_eq!(render_object.opacity(&app), controller.view());
assert_eq!(render_object.opacity(&app).value(&app), 0.0);
assert!(
!render_object.as_object().is_repaint_boundary(&app),
"fully transparent"
);
for value in [0.25, 0.5, 0.75, 1.0] {
controller.set_value(&mut app, value);
harness.pump(&mut app);
assert_eq!(render_object.opacity(&app).value(&app), value);
}
assert!(
render_object.as_object().is_repaint_boundary(&app),
"the render object heard the controller"
);
let other = new_controller(&mut app);
harness.set_child(&mut app, fade(other.view()));
harness.pump(&mut app);
assert_eq!(
fade_under_root(&harness, &app),
render_object,
"reconfigured in place"
);
assert_eq!(render_object.opacity(&app), other.view());
controller.dispose(&mut app);
other.dispose(&mut app);
}
#[derive(Debug)]
struct Grower {
notifier: Handle<ValueNotifier<f64>>,
builds: Rc<Cell<u32>>,
}
impl AnimatedWidget for Grower {
fn listenable(&self) -> Rc<dyn Listenable> {
Rc::new(self.notifier)
}
fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
self.builds.set(self.builds.get() + 1);
let width = *app.get(self.notifier).value();
Sized {
size: Size::new(width, 10.0),
}
.into_widget()
}
}
fn has_listeners(app: &App, notifier: Handle<ValueNotifier<f64>>) -> bool {
app.get(notifier).change_notifier_data().has_listeners()
}
#[test]
fn an_animated_widget_rebuilds_when_its_listenable_notifies() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let notifier = app.create(ValueNotifier::new(10.0));
let builds = Rc::new(Cell::new(0));
let harness = Harness::mount(
&mut app,
Grower {
notifier,
builds: Rc::clone(&builds),
}
.into_widget(),
);
harness.pump(&mut app);
assert_eq!(builds.get(), 1);
assert!(has_listeners(&app, notifier));
assert_eq!(root_child_size(&harness, &app), Size::new(10.0, 10.0));
notifier.set_value(&mut app, 20.0);
assert_eq!(builds.get(), 1, "rebuilt at the next frame, not inline");
harness.pump(&mut app);
assert_eq!(builds.get(), 2);
assert_eq!(root_child_size(&harness, &app), Size::new(20.0, 10.0));
}
#[test]
fn an_animated_widget_follows_a_new_listenable_and_unsubscribes_on_unmount() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let first = app.create(ValueNotifier::new(10.0));
let second = app.create(ValueNotifier::new(30.0));
let builds = Rc::new(Cell::new(0));
let grower = |notifier| {
Grower {
notifier,
builds: Rc::clone(&builds),
}
.into_widget()
};
let harness = Harness::mount(&mut app, grower(first));
harness.pump(&mut app);
harness.set_child(&mut app, grower(second));
harness.pump(&mut app);
assert!(
!has_listeners(&app, first),
"did_update_widget left the old listenable"
);
assert!(has_listeners(&app, second));
assert_eq!(root_child_size(&harness, &app), Size::new(30.0, 10.0));
harness.set_child(
&mut app,
Sized {
size: Size::new(5.0, 5.0),
}
.into_widget(),
);
harness.pump(&mut app);
assert!(!has_listeners(&app, second), "dispose removed the listener");
let builds_before = builds.get();
second.set_value(&mut app, 40.0);
harness.pump(&mut app);
assert_eq!(
builds.get(),
builds_before,
"a disposed state never builds again"
);
}
#[test]
fn a_listenable_builder_rebuilds_on_notify_and_hands_back_its_child() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let notifier = app.create(ValueNotifier::new(0i32));
let builds = Rc::new(Cell::new(0));
let child: WidgetRef = SizedBox::square(Some(4.0)).into_widget();
let same_child = Rc::new(Cell::new(true));
let widget = AnimatedBuilder::new(Rc::new(notifier), {
let builds = Rc::clone(&builds);
let same_child = Rc::clone(&same_child);
let child = child.clone();
move |_app, _context, passed| {
builds.set(builds.get() + 1);
same_child.set(passed.is_some_and(|passed| Rc::ptr_eq(passed, &child)));
passed.expect("the child is passed back").clone()
}
})
.child(child.clone());
let harness = Harness::mount(&mut app, widget.into_widget());
harness.pump(&mut app);
assert_eq!(builds.get(), 1);
assert!(same_child.get());
notifier.set_value(&mut app, 1);
harness.pump(&mut app);
assert_eq!(builds.get(), 2);
}
}