Skip to main content

waft_rendering/
animated_size.rs

1//! Flutter counterpart: `rendering/animated_size.dart`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use waft_animation::{
7    Animatable, Animation, AnimationBehavior, AnimationController, AnimationStatus,
8    AnimationStatusListener, Curve, CurvedAnimation, SizeTween,
9};
10use waft_embedder::{Clip, Offset, Size, TextBaseline, TextDirection};
11use waft_foundation::{App, Handle, Listener};
12use waft_painting::AlignmentGeometry;
13
14use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
15use crate::layer::{ClipRectLayer, LayerHandle};
16use crate::object::{
17    AnyRenderObject, Constraints, RenderHandle, RenderObject, RenderObjectBase, RenderObjectData,
18    RenderObjectWithChildData, RenderObjectWithChildMixin,
19};
20use crate::painting_context::PaintingContext;
21use crate::pipeline_owner::PipelineOwner;
22use crate::shifted_box::{
23    RenderAligningShiftedBox, RenderAligningShiftedBoxData, RenderShiftedBox,
24};
25use crate::sliver_persistent_header::TickerProviderRef;
26use waft_foundation::Ref;
27
28/// A [`RenderAnimatedSize`] can be in exactly one of these states.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum RenderAnimatedSizeState {
31    /// The initial state, when we do not yet know what the starting and target
32    /// sizes are to animate.
33    ///
34    /// The next state is [`Stable`](Self::Stable).
35    Start,
36    /// At this state the child's size is assumed to be stable and we are either
37    /// animating, or waiting for the child's size to change.
38    ///
39    /// If the child's size changes, the state will become [`Changed`](Self::Changed).
40    /// Otherwise, it remains [`Stable`](Self::Stable).
41    Stable,
42    /// At this state we know that the child has changed once after being assumed
43    /// [`Stable`](Self::Stable).
44    Changed,
45    /// At this state the child's size is assumed to be unstable (changing each
46    /// frame).
47    Unstable,
48}
49
50/// A render object that animates its size to its child's size over a given
51/// `duration` and with a given `curve`.
52pub struct RenderAnimatedSize {
53    render_object: RenderObjectData,
54    render_box: RenderBoxData,
55    child: RenderObjectWithChildData<AnyRenderBox>,
56    aligning: RenderAligningShiftedBoxData,
57    vsync: TickerProviderRef,
58    clip_behavior: Clip,
59    controller: Ref<AnimationController>,
60    animation: Ref<CurvedAnimation>,
61    size_tween: Ref<SizeTween>,
62    has_visual_overflow: bool,
63    last_value: Option<f64>,
64    state: RenderAnimatedSizeState,
65    current_size: Size,
66    on_end: Option<Listener>,
67    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
68}
69
70impl RenderAnimatedSize {
71    /// Creates a render object that animates its size to match its child.
72    #[allow(clippy::too_many_arguments)]
73    pub fn new(
74        app: &mut App,
75        vsync: TickerProviderRef,
76        duration: Duration,
77        reverse_duration: Option<Duration>,
78        curve: Rc<dyn Curve>,
79        alignment: AlignmentGeometry,
80        text_direction: Option<TextDirection>,
81        clip_behavior: Clip,
82        on_end: Option<Listener>,
83        child: Option<AnyRenderBox>,
84    ) -> RenderHandle<Self> {
85        let controller = AnimationController::new(
86            app,
87            None,
88            Some(duration),
89            reverse_duration,
90            0.0,
91            1.0,
92            AnimationBehavior::Normal,
93            vsync.clone(),
94        );
95        let animation = CurvedAnimation::new(app, controller.erase(), curve, None);
96        let size_tween = SizeTween::new(app, None, None);
97        let controller_handle = controller.handle();
98        let this = RenderHandle::new_box(
99            app,
100            RenderAnimatedSize {
101                render_object: RenderObjectData::new(),
102                render_box: RenderBoxData::new(),
103                child: RenderObjectWithChildData::new(),
104                aligning: RenderAligningShiftedBoxData::new(alignment, text_direction),
105                vsync,
106                clip_behavior,
107                controller,
108                animation,
109                size_tween,
110                has_visual_overflow: false,
111                last_value: None,
112                state: RenderAnimatedSizeState::Start,
113                current_size: Size::ZERO,
114                on_end,
115                clip_rect_layer: LayerHandle::new(),
116            },
117        );
118        controller_handle.add_listener(
119            app,
120            Listener::handle_method(this.handle(), on_controller_tick),
121        );
122        this.set_child(app, child);
123        this
124    }
125
126    /// The duration of the animation.
127    pub fn duration(self: RenderHandle<Self>, app: &App) -> Duration {
128        app.get(&self.get(app).controller)
129            .duration
130            .expect("duration")
131    }
132
133    /// Sets [`duration`](Self::duration).
134    pub fn set_duration(self: RenderHandle<Self>, app: &mut App, value: Duration) {
135        let controller = self.get(app).controller.handle();
136        if app.get(controller).duration == Some(value) {
137            return;
138        }
139        app.get_mut(controller).duration = Some(value);
140    }
141
142    /// The duration of the animation when running in reverse.
143    pub fn reverse_duration(self: RenderHandle<Self>, app: &App) -> Option<Duration> {
144        app.get(&self.get(app).controller).reverse_duration
145    }
146
147    /// Sets [`reverse_duration`](Self::reverse_duration).
148    pub fn set_reverse_duration(self: RenderHandle<Self>, app: &mut App, value: Option<Duration>) {
149        let controller = self.get(app).controller.handle();
150        if app.get(controller).reverse_duration == value {
151            return;
152        }
153        app.get_mut(controller).reverse_duration = value;
154    }
155
156    /// The curve of the animation.
157    pub fn curve(self: RenderHandle<Self>, app: &App) -> Rc<dyn Curve> {
158        app.get(&self.get(app).animation).curve.clone()
159    }
160
161    /// Sets [`curve`](Self::curve).
162    pub fn set_curve(self: RenderHandle<Self>, app: &mut App, value: Rc<dyn Curve>) {
163        let animation = self.get(app).animation.handle();
164        if Rc::ptr_eq(&app.get(animation).curve, &value) {
165            return;
166        }
167        app.get_mut(animation).curve = value;
168    }
169
170    /// {@macro flutter.material.Material.clipBehavior}
171    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
172        self.get(app).clip_behavior
173    }
174
175    /// Sets [`clip_behavior`](Self::clip_behavior).
176    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
177        if self.get(app).clip_behavior == value {
178            return;
179        }
180        self.get_mut(app).clip_behavior = value;
181        RenderBox::mark_needs_paint(self, app);
182    }
183
184    /// Whether the size is being currently animated towards the child's size.
185    pub fn is_animating(self: RenderHandle<Self>, app: &App) -> bool {
186        self.get(app).controller.as_animation().is_animating(app)
187    }
188
189    /// The [`TickerProvider`] for the [`AnimationController`] that runs the animation.
190    pub fn vsync(self: RenderHandle<Self>, app: &App) -> TickerProviderRef {
191        self.get(app).vsync.clone()
192    }
193
194    /// Sets [`vsync`](Self::vsync).
195    pub fn set_vsync(self: RenderHandle<Self>, app: &mut App, value: TickerProviderRef) {
196        if self.get(app).vsync == value {
197            return;
198        }
199        self.get_mut(app).vsync = value.clone();
200        let controller = self.get(app).controller.handle();
201        controller.resync(app, value);
202    }
203
204    /// Called every time an animation completes.
205    pub fn on_end(self: RenderHandle<Self>, app: &App) -> Option<Listener> {
206        self.get(app).on_end.clone()
207    }
208
209    /// Sets [`on_end`](Self::on_end).
210    pub fn set_on_end(self: RenderHandle<Self>, app: &mut App, value: Option<Listener>) {
211        self.get_mut(app).on_end = value;
212    }
213
214    /// The state this size animation is in.
215    pub fn state(self: RenderHandle<Self>, app: &App) -> RenderAnimatedSizeState {
216        self.get(app).state
217    }
218
219    fn animated_size(self: RenderHandle<Self>, app: &App) -> Option<Size> {
220        let this = self.get(app);
221        Animatable::evaluate(&this.size_tween, app, this.animation.as_animation())
222    }
223
224    fn restart_animation(self: RenderHandle<Self>, app: &mut App) {
225        self.get_mut(app).last_value = Some(0.0);
226        let controller = self.get(app).controller.handle();
227        controller.forward(app, Some(0.0));
228    }
229
230    fn layout_start(self: RenderHandle<Self>, app: &mut App) {
231        let child_size = self.child(app).expect("child").size(app);
232        let size_tween = self.get(app).size_tween.handle();
233        app.get_mut(size_tween).begin = Some(child_size);
234        app.get_mut(size_tween).end = Some(child_size);
235        self.get_mut(app).state = RenderAnimatedSizeState::Stable;
236    }
237
238    fn layout_stable(self: RenderHandle<Self>, app: &mut App) {
239        let child_size = self.child(app).expect("child").size(app);
240        let size_tween = self.get(app).size_tween.handle();
241        let end = app.get(size_tween).end;
242        if end != Some(child_size) {
243            let size = self.size(app);
244            app.get_mut(size_tween).begin = Some(size);
245            app.get_mut(size_tween).end = Some(child_size);
246            self.restart_animation(app);
247            self.get_mut(app).state = RenderAnimatedSizeState::Changed;
248        } else {
249            let controller = self.get(app).controller.handle();
250            let value = controller.value(app);
251            let upper = app.get(controller).upper_bound;
252            if value == upper {
253                app.get_mut(size_tween).begin = Some(child_size);
254                app.get_mut(size_tween).end = Some(child_size);
255            } else if !controller.is_animating(app) {
256                controller.forward(app, None);
257            }
258        }
259    }
260
261    fn layout_changed(self: RenderHandle<Self>, app: &mut App) {
262        let child_size = self.child(app).expect("child").size(app);
263        let size_tween = self.get(app).size_tween.handle();
264        if app.get(size_tween).end != Some(child_size) {
265            app.get_mut(size_tween).begin = Some(child_size);
266            app.get_mut(size_tween).end = Some(child_size);
267            self.restart_animation(app);
268            self.get_mut(app).state = RenderAnimatedSizeState::Unstable;
269        } else {
270            self.get_mut(app).state = RenderAnimatedSizeState::Stable;
271            let controller = self.get(app).controller.handle();
272            if !controller.is_animating(app) {
273                controller.forward(app, None);
274            }
275        }
276    }
277
278    fn layout_unstable(self: RenderHandle<Self>, app: &mut App) {
279        let child_size = self.child(app).expect("child").size(app);
280        let size_tween = self.get(app).size_tween.handle();
281        if app.get(size_tween).end != Some(child_size) {
282            app.get_mut(size_tween).begin = Some(child_size);
283            app.get_mut(size_tween).end = Some(child_size);
284            self.restart_animation(app);
285        } else {
286            let controller = self.get(app).controller.handle();
287            controller.stop(app, true);
288            self.get_mut(app).state = RenderAnimatedSizeState::Stable;
289        }
290    }
291}
292
293impl RenderObjectWithChildMixin for RenderAnimatedSize {
294    type ChildType = AnyRenderBox;
295
296    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
297        &self.get(app).child
298    }
299
300    fn child_data_mut(
301        self: RenderHandle<Self>,
302        app: &mut App,
303    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
304        &mut self.get_mut(app).child
305    }
306}
307
308impl RenderShiftedBox for RenderAnimatedSize {}
309
310impl RenderAligningShiftedBox for RenderAnimatedSize {
311    fn aligning_data(self: RenderHandle<Self>, app: &App) -> &RenderAligningShiftedBoxData {
312        &self.get(app).aligning
313    }
314
315    fn aligning_data_mut(
316        self: RenderHandle<Self>,
317        app: &mut App,
318    ) -> &mut RenderAligningShiftedBoxData {
319        &mut self.get_mut(app).aligning
320    }
321}
322
323impl RenderObject for RenderAnimatedSize {
324    crate::render_object_accessors!();
325
326    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
327        if let Some(child) = self.child(app) {
328            child.as_object().attach(app, owner);
329        }
330        match self.get(app).state {
331            RenderAnimatedSizeState::Start | RenderAnimatedSizeState::Stable => {}
332            RenderAnimatedSizeState::Changed | RenderAnimatedSizeState::Unstable => {
333                RenderBox::mark_needs_layout(self, app);
334            }
335        }
336        let controller = self.get(app).controller.handle();
337        controller.add_status_listener(
338            app,
339            AnimationStatusListener::handle_method(self.handle(), animation_status_listener),
340        );
341    }
342
343    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
344        let controller = self.get(app).controller.handle();
345        controller.stop(app, true);
346        controller.remove_status_listener(
347            app,
348            &AnimationStatusListener::handle_method(self.handle(), animation_status_listener),
349        );
350        if let Some(child) = self.child(app) {
351            child.as_object().detach(app);
352        }
353    }
354
355    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
356        let controller = self.get(app).controller.handle();
357        let value = controller.value(app);
358        self.get_mut(app).last_value = Some(value);
359        self.get_mut(app).has_visual_overflow = false;
360        let constraints = self.constraints(app);
361        if self.child(app).is_none() || constraints.is_tight() {
362            controller.stop(app, true);
363            let smallest = constraints.smallest();
364            let size_tween = self.get(app).size_tween.handle();
365            app.get_mut(size_tween).begin = Some(smallest);
366            app.get_mut(size_tween).end = Some(smallest);
367            self.set_size(app, smallest);
368            self.get_mut(app).current_size = smallest;
369            self.get_mut(app).state = RenderAnimatedSizeState::Start;
370            if let Some(child) = self.child(app) {
371                child.layout(app, constraints, false);
372            }
373            return;
374        }
375
376        let child = self.child(app).expect("child");
377        child.layout(app, constraints, true);
378
379        match self.get(app).state {
380            RenderAnimatedSizeState::Start => self.layout_start(app),
381            RenderAnimatedSizeState::Stable => self.layout_stable(app),
382            RenderAnimatedSizeState::Changed => self.layout_changed(app),
383            RenderAnimatedSizeState::Unstable => self.layout_unstable(app),
384        }
385
386        let animated = self.animated_size(app).expect("animated size");
387        let size = constraints.constrain(animated);
388        self.set_size(app, size);
389        self.get_mut(app).current_size = size;
390        self.align_child(app);
391
392        let end = app.get(&self.get(app).size_tween).end.expect("end");
393        if size.width() < end.width() || size.height() < end.height() {
394            self.get_mut(app).has_visual_overflow = true;
395        }
396    }
397
398    fn paint(
399        self: RenderHandle<Self>,
400        app: &mut App,
401        context: &mut PaintingContext,
402        offset: Offset,
403    ) {
404        if self.child(app).is_some()
405            && self.get(app).has_visual_overflow
406            && self.get(app).clip_behavior != Clip::None
407        {
408            let clip_rect = Offset::ZERO & self.size(app);
409            let clip_behavior = self.get(app).clip_behavior;
410            let old = self.get(app).clip_rect_layer.layer();
411            let layer = context.push_clip_rect(
412                app,
413                self.as_object().needs_compositing(app),
414                offset,
415                clip_rect,
416                |app, context, offset| RenderShiftedBox::paint(self, app, context, offset),
417                clip_behavior,
418                old,
419            );
420            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
421        } else {
422            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
423            RenderShiftedBox::paint(self, app, context, offset);
424        }
425    }
426
427    fn visit_children(
428        self: RenderHandle<Self>,
429        app: &App,
430        visitor: &mut dyn FnMut(AnyRenderObject),
431    ) {
432        if let Some(child) = self.child(app) {
433            visitor(child.as_object());
434        }
435    }
436
437    fn dispose(self: RenderHandle<Self>, app: &mut App) {
438        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
439        let controller = self.get(app).controller.handle();
440        let animation = self.get(app).animation.handle();
441        controller.dispose(app);
442        animation.dispose(app);
443        RenderObjectBase::dispose(self, app);
444    }
445}
446
447impl RenderBox for RenderAnimatedSize {
448    crate::render_box_accessors!();
449
450    fn hit_test_children(
451        self: RenderHandle<Self>,
452        app: &mut App,
453        result: &mut BoxHitTestResult<'_>,
454        position: Offset,
455    ) -> bool {
456        RenderShiftedBox::hit_test_children(self, app, result, position)
457    }
458
459    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
460        RenderShiftedBox::compute_min_intrinsic_width(self, app, height)
461    }
462
463    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
464        RenderShiftedBox::compute_max_intrinsic_width(self, app, height)
465    }
466
467    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
468        RenderShiftedBox::compute_min_intrinsic_height(self, app, width)
469    }
470
471    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
472        RenderShiftedBox::compute_max_intrinsic_height(self, app, width)
473    }
474
475    fn compute_distance_to_actual_baseline(
476        self: RenderHandle<Self>,
477        app: &mut App,
478        baseline: TextBaseline,
479    ) -> Option<f64> {
480        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
481    }
482
483    fn compute_dry_layout(
484        self: RenderHandle<Self>,
485        app: &mut App,
486        constraints: BoxConstraints,
487    ) -> Size {
488        let Some(child) = self.child(app) else {
489            return constraints.smallest();
490        };
491        if constraints.is_tight() {
492            return constraints.smallest();
493        }
494        let child_size = child.get_dry_layout(app, constraints);
495        match self.get(app).state {
496            RenderAnimatedSizeState::Start => return constraints.constrain(child_size),
497            RenderAnimatedSizeState::Stable => {
498                if app.get(&self.get(app).size_tween).end != Some(child_size) {
499                    return constraints.constrain(self.get(app).current_size);
500                }
501                let controller = self.get(app).controller.handle();
502                if controller.value(app) == app.get(controller).upper_bound {
503                    return constraints.constrain(child_size);
504                }
505            }
506            RenderAnimatedSizeState::Unstable | RenderAnimatedSizeState::Changed => {
507                if app.get(&self.get(app).size_tween).end != Some(child_size) {
508                    return constraints.constrain(child_size);
509                }
510            }
511        }
512        constraints.constrain(self.animated_size(app).expect("animated size"))
513    }
514
515    fn compute_dry_baseline(
516        self: RenderHandle<Self>,
517        app: &mut App,
518        constraints: BoxConstraints,
519        baseline: TextBaseline,
520    ) -> Option<f64> {
521        let child = self.child(app)?;
522        let result = child.get_dry_baseline(app, constraints, baseline)?;
523        let child_size = child.get_dry_layout(app, constraints);
524        let my_size = self.get_dry_layout(app, constraints);
525        let offset = self
526            .resolved_alignment(app)
527            .along_offset(my_size - child_size);
528        Some(result + offset.dy())
529    }
530}
531
532impl std::fmt::Debug for RenderAnimatedSize {
533    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
534        f.debug_struct("RenderAnimatedSize").finish_non_exhaustive()
535    }
536}
537
538fn on_controller_tick(this: Handle<RenderAnimatedSize>, app: &mut App) {
539    let this = RenderHandle::from_handle(this);
540    let value = this.get(app).controller.value(app);
541    if this.get(app).last_value != Some(value) {
542        RenderBox::mark_needs_layout(this, app);
543    }
544}
545
546fn animation_status_listener(
547    this: Handle<RenderAnimatedSize>,
548    app: &mut App,
549    status: AnimationStatus,
550) {
551    let this = RenderHandle::from_handle(this);
552    if status.is_completed()
553        && let Some(on_end) = this.get(app).on_end.clone()
554    {
555        on_end.call(app);
556    }
557}