Skip to main content

waft_winui/controls/
progress_ring.rs

1//! XAML `ProgressRing` (`controls/dev/ProgressRing/ProgressRing.xaml` and `ProgressRing.cpp`).
2//! The template is nothing but an `AnimatedVisualPlayer`, so the ring itself is transcribed from
3//! the two generated shape graphs the player is given: `AnimatedVisuals/ProgressRingDeterminate.cpp`
4//! and `AnimatedVisuals/ProgressRingIndeterminate.cpp`.
5
6use crate::{RangeBase, ThemeResources};
7use std::{f64::consts::TAU, time::Duration};
8use waft_animation::{Cubic, Curve};
9use waft_embedder::valo::{Cap, Point};
10use waft_embedder::{Canvas, Color, Paint, PaintStyle, PathBuilder, Size, Stroke};
11use waft_foundation::{App, Handle, OptionRetained, Ref};
12use waft_rendering::{BoxConstraints, CustomPainter};
13use waft_scheduler::{FrameCallback, Ticker};
14use waft_widgets::*;
15
16/// `c_durationTicks` of both generated visuals: twenty million ticks of 100 ns, so two seconds.
17pub const PROGRESS_RING_DURATION: Duration = Duration::from_secs(2);
18
19/// `ProgressRing.xaml`'s `Width` and `Height` setters.
20pub const PROGRESS_RING_SIZE: f64 = 32.0;
21
22/// `ProgressRing.xaml`'s `MinWidth` and `MinHeight` setters.
23pub const PROGRESS_RING_MIN_SIZE: f64 = 16.0;
24
25/// `ProgressRing.xaml`'s `Maximum` setter.
26pub const PROGRESS_RING_DEFAULT_MAXIMUM: f64 = 100.0;
27
28/// `ProgressRingDeterminate`'s ellipse of radius 8 under a scale of 1.77, as a fraction of the
29/// 32-unit visual it was generated at.
30const DETERMINATE_RADIUS: f64 = 8.0 * 1.77 / 32.0;
31
32/// `ProgressRingDeterminate`'s stroke of 1.5 under the same scale.
33const DETERMINATE_STROKE: f64 = 1.5 * 1.77 / 32.0;
34
35/// `ProgressRingIndeterminate`'s ellipse of radius 7 under a scale of 5, as a fraction of the
36/// 80-unit visual it was generated at.
37const INDETERMINATE_RADIUS: f64 = 7.0 * 5.0 / 80.0;
38
39/// `ProgressRingIndeterminate`'s stroke of 1.5 under the same scale.
40const INDETERMINATE_STROKE: f64 = 1.5 * 5.0 / 80.0;
41
42/// `CubicBezierEasingFunction_0`, shared by every eased segment of both visuals.
43fn lottie_ease() -> Cubic {
44    Cubic::new(0.167, 0.167, 0.833, 0.833)
45}
46
47/// How a generated animation eases the segment that ends at one of its key frames.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49enum Easing {
50    /// `CubicBezierEasingFunction_0`.
51    Eased,
52    /// A `StepEasingFunction`, which keeps the previous value until the key frame it lands on.
53    Held,
54}
55
56/// One `InsertKeyFrame` call: where it lands, the value it reaches and how it is approached.
57type KeyFrame = (f64, f64, Easing);
58
59/// Reads a generated `ScalarKeyFrameAnimation` at one point of its progress. Before the first
60/// key frame and after the last one the animation holds that key frame's value.
61fn key_frames(progress: f64, frames: &[KeyFrame]) -> f64 {
62    let (first, last) = (frames[0], frames[frames.len() - 1]);
63    if progress <= first.0 {
64        return first.1;
65    }
66    if progress >= last.0 {
67        return last.1;
68    }
69    let index = frames.iter().position(|frame| frame.0 > progress).unwrap();
70    let (from_progress, from_value, _) = frames[index - 1];
71    let (to_progress, to_value, easing) = frames[index];
72    match easing {
73        Easing::Held => from_value,
74        Easing::Eased => {
75            let span = (progress - from_progress) / (to_progress - from_progress);
76            from_value + (to_value - from_value) * lottie_ease().transform(span)
77        }
78    }
79}
80
81/// `TrimEndScalarAnimation_0_to_1` of `ProgressRingDeterminate`.
82fn determinate_trim_end(progress: f64) -> f64 {
83    key_frames(
84        progress,
85        &[
86            (0.0, 0.0001, Easing::Held),
87            (0.00833333377, 0.0001, Easing::Held),
88            (0.25, 0.25, Easing::Eased),
89            (0.5, 0.5, Easing::Eased),
90            (0.75, 0.75, Easing::Eased),
91            (0.983333349, 0.96666666, Easing::Eased),
92            (0.991666675, 1.0, Easing::Eased),
93        ],
94    )
95}
96
97/// `ShapeVisibilityAnimation` of `ProgressRingDeterminate`: the arc's container is scaled to
98/// nothing until the animation has begun.
99fn determinate_arc_is_shown(progress: f64) -> bool {
100    progress >= 0.00833333377
101}
102
103/// `RotationAngleInDegreesScalarAnimation_0_to_900` of `ProgressRingIndeterminate`, in turns.
104fn indeterminate_rotation(progress: f64) -> f64 {
105    key_frames(
106        progress,
107        &[
108            (0.0, 0.0, Easing::Held),
109            (0.5, 450.0, Easing::Eased),
110            (1.0, 900.0, Easing::Eased),
111        ],
112    ) / 360.0
113}
114
115/// `TrimEndScalarAnimation_0_to_0p5` of `ProgressRingIndeterminate`: the arc that grows through
116/// the first half of the loop.
117fn indeterminate_growing_arc(progress: f64) -> (f64, f64) {
118    let end = key_frames(
119        progress,
120        &[(0.0, 0.0001, Easing::Held), (0.5, 0.5, Easing::Eased)],
121    );
122    (0.0, end)
123}
124
125/// `TrimStartScalarAnimation_0_to_0p5` of `ProgressRingIndeterminate`: the arc whose start
126/// catches up with its fixed end through the second half of the loop.
127fn indeterminate_shrinking_arc(progress: f64) -> (f64, f64) {
128    let start = key_frames(
129        progress,
130        &[
131            (0.0, 0.0, Easing::Held),
132            (0.5, 0.0, Easing::Held),
133            (1.0, 0.5, Easing::Eased),
134        ],
135    );
136    (start, 0.5)
137}
138
139/// XAML `ProgressRing`: a ring that either fills to a value or turns while work continues.
140#[derive(Clone, Debug)]
141pub struct ProgressRing {
142    /// `Minimum` of the range the value is read against.
143    pub minimum: f64,
144
145    /// `Maximum`; the Fluent style sets it to 100.
146    pub maximum: f64,
147
148    /// `Value`, coerced into the range.
149    pub value: f64,
150
151    /// `IsActive`: whether the ring is shown at all.
152    pub is_active: bool,
153
154    /// `IsIndeterminate`: whether the ring turns instead of showing the value.
155    pub is_indeterminate: bool,
156
157    /// `Foreground`, in place of `ProgressRingForegroundThemeBrush`.
158    pub foreground: Option<Color>,
159
160    /// `Background`, the track behind the arc, in place of `ProgressRingBackgroundThemeBrush`.
161    pub background: Option<Color>,
162
163    /// Identity retained across parent rebuilds.
164    pub key: Option<KeyRef>,
165}
166
167impl Default for ProgressRing {
168    fn default() -> Self {
169        Self {
170            minimum: 0.0,
171            maximum: PROGRESS_RING_DEFAULT_MAXIMUM,
172            value: 0.0,
173            // `ProgressRing.idl` defaults both to true.
174            is_active: true,
175            is_indeterminate: true,
176            foreground: None,
177            background: None,
178            key: None,
179        }
180    }
181}
182
183impl ProgressRing {
184    /// Creates an active, indeterminate ring over the style's range.
185    pub fn new() -> Self {
186        Self::default()
187    }
188
189    /// Sets the XAML `Minimum`.
190    pub fn minimum(mut self, value: f64) -> Self {
191        self.minimum = value;
192        self
193    }
194
195    /// Sets the XAML `Maximum`.
196    pub fn maximum(mut self, value: f64) -> Self {
197        self.maximum = value;
198        self
199    }
200
201    /// Sets the XAML `Value`.
202    pub fn value(mut self, value: f64) -> Self {
203        self.value = value;
204        self
205    }
206
207    /// Sets the XAML `IsActive`.
208    pub fn is_active(mut self, value: bool) -> Self {
209        self.is_active = value;
210        self
211    }
212
213    /// Sets the XAML `IsIndeterminate`.
214    pub fn is_indeterminate(mut self, value: bool) -> Self {
215        self.is_indeterminate = value;
216        self
217    }
218
219    /// Sets the XAML `Foreground`.
220    pub fn foreground(mut self, value: Color) -> Self {
221        self.foreground = Some(value);
222        self
223    }
224
225    /// Sets the XAML `Background`.
226    pub fn background(mut self, value: Color) -> Self {
227        self.background = Some(value);
228        self
229    }
230
231    /// Sets the identity retained across rebuilds.
232    pub fn key(mut self, value: KeyRef) -> Self {
233        self.key = Some(value);
234        self
235    }
236
237    /// `UpdateLottieProgress`: where in the determinate animation the current value sits.
238    fn progress(&self) -> f64 {
239        let range = RangeBase::new(self.minimum, self.maximum, self.value).coerced();
240        let span = range.maximum - range.minimum;
241        if span == 0.0 {
242            0.0
243        } else {
244            (range.value - range.minimum) / span
245        }
246    }
247}
248
249/// Holds the clock the player runs on, and the segment a value change is playing through.
250pub struct ProgressRingState {
251    /// Framework widget state.
252    state: StateData<ProgressRing>,
253
254    /// Native TickerMode support.
255    single_ticker_provider: SingleTickerProviderStateMixinData,
256
257    /// The clock both generated visuals are driven by.
258    ticker: Option<Ref<Ticker>>,
259
260    /// Time since the current segment started playing.
261    elapsed: Duration,
262
263    /// `m_oldValue` as a progress: where `PlayAsync` started the current segment.
264    from: f64,
265
266    /// Where the current segment ends.
267    to: f64,
268}
269
270impl StatefulWidget for ProgressRing {
271    type State = ProgressRingState;
272
273    fn key(&self) -> Option<&KeyRef> {
274        self.key.as_ref()
275    }
276
277    fn create_state(&self) -> ProgressRingState {
278        let progress = self.progress();
279        ProgressRingState {
280            state: StateData::new(),
281            single_ticker_provider: Default::default(),
282            ticker: None,
283            elapsed: Duration::ZERO,
284            from: progress,
285            to: progress,
286        }
287    }
288}
289
290impl SingleTickerProviderStateMixin for ProgressRingState {
291    fn single_ticker_provider_data(
292        self: Handle<Self>,
293        app: &App,
294    ) -> &SingleTickerProviderStateMixinData {
295        &app.get(self).single_ticker_provider
296    }
297
298    fn single_ticker_provider_data_mut(
299        self: Handle<Self>,
300        app: &mut App,
301    ) -> &mut SingleTickerProviderStateMixinData {
302        &mut app.get_mut(self).single_ticker_provider
303    }
304}
305
306impl ProgressRingState {
307    /// Where the visual the player holds currently sits, between 0 and 1.
308    fn progress(self: Handle<Self>, app: &App) -> f64 {
309        let state = app.get(self);
310        let seconds = state.elapsed.as_secs_f64() / PROGRESS_RING_DURATION.as_secs_f64();
311        if self.widget(app).is_indeterminate {
312            // PlayAsync(0, 1, true) loops the whole visual.
313            seconds.fract()
314        } else {
315            // PlayAsync(fromProgress, toProgress, false) plays that segment at normal speed.
316            (state.from + seconds).min(state.to)
317        }
318    }
319
320    /// `ProgressRing::UpdateStates`: the player runs while the ring is active, and stops
321    /// otherwise.
322    fn update_states(self: Handle<Self>, app: &mut App) {
323        let ticker = app.get(self).ticker.clone().unwrap();
324        // AnimatedVisualPlayer replaces the previous playback before starting a segment.
325        ticker.stop(app, false);
326        app.get_mut(self).elapsed = Duration::ZERO;
327
328        let widget = self.widget(app);
329        if !widget.is_active {
330            // player.Stop() returns the visual to its first frame.
331            return;
332        }
333        if widget.is_indeterminate || app.get(self).from < app.get(self).to {
334            ticker.start(app);
335        }
336    }
337
338    /// `ProgressRing::UpdateLottieProgress`: a rising value plays forward from the old one, and
339    /// a falling value jumps.
340    fn update_progress(self: Handle<Self>, app: &mut App, old_progress: f64) {
341        let target = self.widget(app).progress();
342        let state = app.get_mut(self);
343        state.elapsed = Duration::ZERO;
344        if old_progress < target {
345            state.from = old_progress;
346        } else {
347            state.from = target;
348        }
349        state.to = target;
350        self.update_states(app);
351    }
352
353    /// Stops a finished determinate segment; the indeterminate visual keeps looping.
354    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
355        self.set_state(app, |state| state.elapsed = elapsed);
356        if !self.widget(app).is_indeterminate && self.progress(app) >= app.get(self).to {
357            app.get(self).ticker.handle().unwrap().stop(app, false);
358        }
359    }
360}
361
362impl State for ProgressRingState {
363    type Widget = ProgressRing;
364    waft_widgets::state_accessors!();
365
366    fn init_state(self: Handle<Self>, app: &mut App) {
367        let ticker = SingleTickerProviderStateMixin::create_ticker(
368            self,
369            app,
370            FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
371        );
372        app.get_mut(self).ticker = Some(ticker.clone());
373        self.update_states(app);
374    }
375
376    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ProgressRing) {
377        let widget = self.widget(app).clone();
378        let switched_kind = old.is_indeterminate != widget.is_indeterminate;
379        if switched_kind || (!widget.is_indeterminate && old.progress() != widget.progress()) {
380            self.update_progress(app, old.progress());
381        } else if old.is_active != widget.is_active {
382            // Reactivation reloads the visual and seeks to the last requested value.
383            if !widget.is_indeterminate {
384                app.get_mut(self).from = app.get(self).to;
385            }
386            self.update_states(app);
387        }
388    }
389
390    fn activate(self: Handle<Self>, app: &mut App) {
391        SingleTickerProviderStateMixin::activate(self, app);
392    }
393
394    fn dispose(self: Handle<Self>, app: &mut App) {
395        app.get(self).ticker.handle().unwrap().dispose(app);
396        SingleTickerProviderStateMixin::dispose(self, app);
397    }
398
399    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
400        let resources = ThemeResources::of(app, context);
401        let widget = self.widget(app).clone();
402        let painter = ProgressRingVisual {
403            progress: self.progress(app),
404            indeterminate: widget.is_indeterminate,
405            foreground: widget
406                .foreground
407                .unwrap_or(resources.progress_ring_foreground_theme_brush),
408            background: widget
409                .background
410                .unwrap_or(resources.progress_ring_background_theme_brush),
411        };
412        // The Inactive state sets LayoutRoot.Opacity to 0.
413        let opacity = if widget.is_active { 1.0 } else { 0.0 };
414        ConstrainedBox::new(BoxConstraints {
415            min_width: PROGRESS_RING_MIN_SIZE,
416            max_width: f64::INFINITY,
417            min_height: PROGRESS_RING_MIN_SIZE,
418            max_height: f64::INFINITY,
419        })
420        .child(
421            Opacity::new(opacity).child(
422                SizedBox::new()
423                    .width(PROGRESS_RING_SIZE)
424                    .height(PROGRESS_RING_SIZE)
425                    .child(IgnorePointer::new().child(CustomPaint::new().painter(painter))),
426            ),
427        )
428        .into_widget()
429    }
430}
431
432/// The shapes of `ProgressRingDeterminate` and `ProgressRingIndeterminate` at one point of
433/// their progress.
434#[derive(Clone, Copy, Debug, PartialEq)]
435struct ProgressRingVisual {
436    progress: f64,
437    indeterminate: bool,
438    foreground: Color,
439    background: Color,
440}
441
442impl ProgressRingVisual {
443    /// Strokes one trimmed part of the ellipse, as a sprite shape with round caps does.
444    fn arc(&self, canvas: &mut Canvas, size: Size, trim: (f64, f64), rotation: f64, color: Color) {
445        if color.a == 0.0 || trim.1 <= trim.0 {
446            return;
447        }
448        let (radius, width) = self.geometry(size);
449        let mut path = PathBuilder::new();
450        // Composition trims an ellipse from its start point, which is the top of the ring.
451        let start = (rotation + trim.0 - 0.25) * TAU;
452        path.arc(
453            center(size),
454            radius as f32,
455            start as f32,
456            ((trim.1 - trim.0) * TAU) as f32,
457        );
458        let mut paint = Paint::from_color(color.into());
459        paint.style = PaintStyle::Stroke(Stroke {
460            cap: Cap::Round,
461            ..Stroke::new(width as f32)
462        });
463        canvas.draw_path(&path.build(), Default::default(), &paint);
464    }
465
466    /// The ring's radius and stroke width in the space it was given.
467    fn geometry(&self, size: Size) -> (f64, f64) {
468        let side = size.width().min(size.height());
469        if self.indeterminate {
470            (INDETERMINATE_RADIUS * side, INDETERMINATE_STROKE * side)
471        } else {
472            (DETERMINATE_RADIUS * side, DETERMINATE_STROKE * side)
473        }
474    }
475}
476
477/// The centre both generated visuals place their ellipse at.
478fn center(size: Size) -> Point {
479    Point::new((size.width() / 2.0) as f32, (size.height() / 2.0) as f32)
480}
481
482impl CustomPainter for ProgressRingVisual {
483    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
484        if size.is_empty() {
485            return;
486        }
487
488        // AnimatedVisualPlayer uses Stretch.Fill, including the stroke and round caps.
489        canvas.save();
490        canvas.scale((size.width() / 32.0) as f32, (size.height() / 32.0) as f32);
491        let size = Size::new(32.0, 32.0);
492
493        // SpriteShape_0 of both visuals: the untrimmed track, in the Background colour.
494        self.arc(canvas, size, (0.0, 1.0), 0.0, self.background);
495        if self.indeterminate {
496            let rotation = indeterminate_rotation(self.progress);
497            // The two arcs cross-fade at the halfway step of their opacity animations.
498            if self.progress < 0.5 {
499                let trim = indeterminate_growing_arc(self.progress);
500                self.arc(canvas, size, trim, rotation, self.foreground);
501            } else {
502                let trim = indeterminate_shrinking_arc(self.progress);
503                self.arc(canvas, size, trim, rotation, self.foreground);
504            }
505        } else if determinate_arc_is_shown(self.progress) {
506            let trim = (0.0, determinate_trim_end(self.progress));
507            self.arc(canvas, size, trim, 0.0, self.foreground);
508        }
509        canvas.restore();
510    }
511
512    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
513        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
514    }
515
516    fn as_any(&self) -> &dyn std::any::Any {
517        self
518    }
519}