Skip to main content

waft_winui/controls/
progress_bar.rs

1//! WinUI ProgressBar.xaml and ProgressBar.cpp: range sizing and CommonStates storyboards.
2
3use crate::*;
4use std::{any::Any, time::Duration};
5use waft_animation::{Cubic, Curve};
6use waft_embedder::{Color, Rect, Size};
7use waft_foundation::{App, Handle, OptionRetained, Ref};
8use waft_painting::EdgeInsetsGeometry;
9use waft_rendering::CustomClipper;
10use waft_scheduler::{FrameCallback, Ticker};
11use waft_widgets::*;
12
13/// A horizontal progress indicator with the Fluent determinate, paused, error and indeterminate states.
14#[derive(Clone, Debug)]
15pub struct ProgressBar {
16    /// Lower bound of the progress range.
17    pub minimum: f64,
18
19    /// Upper bound of the range; the Fluent style sets it to 100.
20    pub maximum: f64,
21
22    /// Progress value, coerced to the range.
23    pub value: f64,
24
25    /// Whether the two moving indicators replace the determinate indicator.
26    pub is_indeterminate: bool,
27
28    /// Whether progress is paused; error takes precedence.
29    pub show_paused: bool,
30
31    /// Whether the error visual state is active.
32    pub show_error: bool,
33
34    /// Whether the control is visible and its indeterminate animation runs.
35    pub is_visible: bool,
36
37    /// Height of the indicator grid, as bound by the source template; the theme's `ProgressBarMinHeight` when `None`.
38    pub min_height: Option<f64>,
39
40    /// Padding in left, top, right, bottom order.
41    pub padding: [f64; 4],
42
43    /// Border widths in left, top, right, bottom order; the theme's `ProgressBarBorderThemeThickness` when `None`.
44    pub border_thickness: Option<[f64; 4]>,
45
46    /// Radius of the indicator rectangles; the theme's `ProgressBarCornerRadius` when `None`.
47    pub corner_radius: Option<f64>,
48
49    /// Optional normal indicator color.
50    pub foreground: Option<Color>,
51
52    /// Optional track color.
53    pub background: Option<Color>,
54
55    /// Optional outer border color.
56    pub border_brush: Option<Color>,
57
58    /// Widget identity across rebuilds.
59    pub key: Option<KeyRef>,
60}
61
62impl ProgressBar {
63    /// Creates the source default ProgressBar.
64    pub fn new() -> Self {
65        Self {
66            minimum: 0.0,
67            maximum: 100.0,
68            value: 0.0,
69            is_indeterminate: false,
70            show_paused: false,
71            show_error: false,
72            is_visible: true,
73            min_height: None,
74            padding: [0.0; 4],
75            border_thickness: None,
76            corner_radius: None,
77            foreground: None,
78            background: None,
79            border_brush: None,
80            key: None,
81        }
82    }
83
84    /// Sets Minimum.
85    pub fn minimum(mut self, value: f64) -> Self {
86        self.minimum = value;
87        self
88    }
89
90    /// Sets Maximum.
91    pub fn maximum(mut self, value: f64) -> Self {
92        self.maximum = value;
93        self
94    }
95
96    /// Sets Value.
97    pub fn value(mut self, value: f64) -> Self {
98        self.value = value;
99        self
100    }
101
102    /// Sets IsIndeterminate.
103    pub fn is_indeterminate(mut self, value: bool) -> Self {
104        self.is_indeterminate = value;
105        self
106    }
107
108    /// Sets ShowPaused.
109    pub fn show_paused(mut self, value: bool) -> Self {
110        self.show_paused = value;
111        self
112    }
113
114    /// Sets ShowError.
115    pub fn show_error(mut self, value: bool) -> Self {
116        self.show_error = value;
117        self
118    }
119
120    /// Sets IsVisible.
121    pub fn is_visible(mut self, value: bool) -> Self {
122        self.is_visible = value;
123        self
124    }
125
126    /// Sets MinHeight.
127    pub fn min_height(mut self, value: f64) -> Self {
128        self.min_height = Some(value);
129        self
130    }
131
132    /// Sets Padding.
133    pub fn padding(mut self, value: [f64; 4]) -> Self {
134        self.padding = value;
135        self
136    }
137
138    /// Sets BorderThickness.
139    pub fn border_thickness(mut self, value: [f64; 4]) -> Self {
140        self.border_thickness = Some(value);
141        self
142    }
143
144    /// Sets CornerRadius.
145    pub fn corner_radius(mut self, value: f64) -> Self {
146        self.corner_radius = Some(value);
147        self
148    }
149
150    /// Sets Foreground.
151    pub fn foreground(mut self, value: Color) -> Self {
152        self.foreground = Some(value);
153        self
154    }
155
156    /// Sets Background.
157    pub fn background(mut self, value: Color) -> Self {
158        self.background = Some(value);
159        self
160    }
161
162    /// Sets BorderBrush.
163    pub fn border_brush(mut self, value: Color) -> Self {
164        self.border_brush = Some(value);
165        self
166    }
167
168    /// Sets Key.
169    pub fn key(mut self, value: KeyRef) -> Self {
170        self.key = Some(value);
171        self
172    }
173
174    /// Chooses CommonStates using ProgressBar::UpdateStates precedence.
175    fn visual_state(&self) -> ProgressState {
176        match (
177            self.is_indeterminate && self.is_visible,
178            self.show_error,
179            self.show_paused,
180        ) {
181            (true, true, _) => ProgressState::IndeterminateError,
182            (true, false, true) => ProgressState::IndeterminatePaused,
183            (true, false, false) => ProgressState::Indeterminate,
184            (false, true, _) => ProgressState::Error,
185            (false, false, true) => ProgressState::Paused,
186            _ => ProgressState::Determinate,
187        }
188    }
189
190    /// Resolves the target fill of the active state.
191    fn indicator_color(&self, resources: &ThemeResources) -> Color {
192        if self.show_error {
193            resources.progress_bar_error_foreground_color
194        } else if self.show_paused {
195            resources.progress_bar_paused_foreground_color
196        } else {
197            self.foreground.unwrap_or(resources.progress_bar_foreground)
198        }
199    }
200}
201
202impl Default for ProgressBar {
203    fn default() -> Self {
204        Self::new()
205    }
206}
207
208/// Stable states of ProgressBar.xaml's CommonStates group.
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210enum ProgressState {
211    Determinate,
212    Updating,
213    UpdatingError,
214    Paused,
215    Error,
216    Indeterminate,
217    IndeterminatePaused,
218    IndeterminateError,
219}
220
221impl ProgressState {
222    /// Whether the second indicator is filling the track after a pause or error.
223    fn suspended(self) -> bool {
224        matches!(self, Self::IndeterminatePaused | Self::IndeterminateError)
225    }
226}
227
228/// A sampled source storyboard, with translation expressed as a multiple of LayoutRoot width.
229#[derive(Clone, Copy, Debug)]
230struct ProgressVisuals {
231    /// Opacity of the determinate track.
232    track_opacity: f64,
233
234    /// Translation of the track.
235    track_translation: f64,
236
237    /// Translation of the first 40-percent indicator, absent when collapsed.
238    first: Option<f64>,
239
240    /// Translation of the second indicator, absent when collapsed.
241    second: Option<f64>,
242}
243
244/// Evaluates the explicit spline keys; Windows theme animations are documented separately.
245fn progress_visuals(
246    state: ProgressState,
247    from: ProgressState,
248    elapsed: f64,
249    initial_second: f64,
250) -> ProgressVisuals {
251    let mut result = ProgressVisuals {
252        track_opacity: 1.0,
253        track_translation: 0.0,
254        first: None,
255        second: None,
256    };
257
258    if state == ProgressState::Indeterminate {
259        if from.suspended() && elapsed < 0.5 {
260            let curve = Cubic::new(1.0, 0.0, 1.0, 1.0);
261            result.second = Some(
262                initial_second
263                    + (1.2 - initial_second) * curve.transform((elapsed / 0.333).min(1.0)),
264            );
265            result.track_opacity = 0.0;
266            result.track_translation = 1.2 * curve.transform((elapsed / 0.5).min(1.0));
267            return result;
268        }
269
270        let time = (elapsed - if from.suspended() { 0.5 } else { 0.0 }).max(0.0) % 2.0;
271        let curve = Cubic::new(0.4, 0.0, 0.6, 1.0);
272        result.track_opacity = 0.0;
273        result.first = Some(-0.4 + 1.6 * curve.transform((time / 1.5).min(1.0)));
274        result.second =
275            Some(-0.9 + 1.896 * curve.transform(((time - 0.75) / 1.25).clamp(0.0, 1.0)));
276    } else if state.suspended() {
277        result.track_opacity = 0.0;
278        // The two keys at 167 ms first reach the end and then jump to the start.
279        result.second = Some(if elapsed < 0.167 {
280            initial_second
281                + (0.996 - initial_second)
282                    * Cubic::new(1.0, 1.0, 0.0, 1.0).transform(elapsed / 0.167)
283        } else {
284            -0.9 + 0.9
285                * Cubic::new(0.0, 0.0, 0.0, 1.0).transform(((elapsed - 0.167) / 0.583).min(1.0))
286        });
287        result.track_translation =
288            -0.9 + 0.9 * Cubic::new(0.0, 0.0, 0.0, 1.0).transform((elapsed / 0.75).min(1.0));
289    }
290
291    result
292}
293
294/// Owns the source storyboard clock and the color captured when a state changes.
295pub struct ProgressBarState {
296    /// Framework widget state.
297    state: StateData<ProgressBar>,
298
299    /// Native TickerMode support.
300    single_ticker_provider: SingleTickerProviderStateMixinData,
301
302    /// Clock shared by the source tracks.
303    ticker: Option<Ref<Ticker>>,
304
305    /// State whose visual values were captured at transition start.
306    from: ProgressState,
307
308    /// Elapsed time in the active storyboard.
309    elapsed: Duration,
310
311    /// Second indicator position when a transition interrupted it.
312    initial_second: f64,
313
314    /// Initial fill for the source's 167 ms color animation.
315    from_color: Option<Color>,
316
317    /// Last LayoutRoot size whose SizeChanged callback updated the source state.
318    layout_size: Option<Size>,
319}
320
321impl StatefulWidget for ProgressBar {
322    type State = ProgressBarState;
323
324    /// Returns the identity used to retain this control across owner rebuilds.
325    fn key(&self) -> Option<&KeyRef> {
326        self.key.as_ref()
327    }
328
329    /// Initializes template state from the first widget description.
330    fn create_state(&self) -> ProgressBarState {
331        ProgressBarState {
332            state: StateData::new(),
333            single_ticker_provider: Default::default(),
334            ticker: None,
335            from: self.visual_state(),
336            elapsed: Duration::ZERO,
337            initial_second: 0.0,
338            from_color: None,
339            layout_size: None,
340        }
341    }
342}
343
344impl SingleTickerProviderStateMixin for ProgressBarState {
345    fn single_ticker_provider_data(
346        self: Handle<Self>,
347        app: &App,
348    ) -> &SingleTickerProviderStateMixinData {
349        &app.get(self).single_ticker_provider
350    }
351
352    fn single_ticker_provider_data_mut(
353        self: Handle<Self>,
354        app: &mut App,
355    ) -> &mut SingleTickerProviderStateMixinData {
356        &mut app.get_mut(self).single_ticker_provider
357    }
358}
359
360impl ProgressBarState {
361    /// SetProgressBarIndicatorWidth visits Updating before returning to the target state.
362    fn update_indicator_width(self: Handle<Self>, app: &mut App) {
363        let resources = ThemeResources::of(app, self.context(app));
364        let widget = self.widget(app);
365        let from = if widget.show_error {
366            ProgressState::UpdatingError
367        } else {
368            ProgressState::Updating
369        };
370        let color = if widget.show_error && !widget.is_indeterminate {
371            resources.progress_bar_error_foreground_color
372        } else {
373            widget
374                .foreground
375                .unwrap_or(resources.progress_bar_foreground)
376        };
377        self.start_state(app, from, color, 0.0);
378    }
379
380    /// Starts the selected source storyboard after leaving the previous visual state.
381    fn start_state(
382        self: Handle<Self>,
383        app: &mut App,
384        from: ProgressState,
385        color: Color,
386        second: f64,
387    ) {
388        let ticker = app.get(self).ticker.clone().unwrap();
389        ticker.stop(app, false);
390        let state = app.get_mut(self);
391        state.from = from;
392        state.from_color = Some(color);
393        state.initial_second = second;
394        state.elapsed = Duration::ZERO;
395
396        if self.widget(app).is_visible {
397            ticker.start(app);
398        }
399    }
400
401    /// Advances finite tracks to their final key and keeps indeterminate tracks repeating.
402    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
403        self.set_state(app, |state| state.elapsed = elapsed);
404        let target = self.widget(app).visual_state();
405        if target != ProgressState::Indeterminate && elapsed >= Duration::from_millis(750) {
406            app.get(self).ticker.handle().unwrap().stop(app, false);
407        }
408    }
409
410    /// Current animated fill, including an interrupted color transition.
411    fn color(
412        self: Handle<Self>,
413        app: &App,
414        widget: &ProgressBar,
415        resources: &ThemeResources,
416    ) -> Color {
417        let target = widget.indicator_color(resources);
418        let state = app.get(self);
419        Color::lerp(
420            state.from_color,
421            Some(target),
422            (state.elapsed.as_secs_f64() / 0.167).min(1.0),
423        )
424        .unwrap_or(target)
425    }
426}
427
428impl State for ProgressBarState {
429    type Widget = ProgressBar;
430    waft_widgets::state_accessors!();
431
432    /// Creates the native clock for the source storyboards.
433    fn init_state(self: Handle<Self>, app: &mut App) {
434        let ticker = SingleTickerProviderStateMixin::create_ticker(
435            self,
436            app,
437            FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
438        );
439        app.get_mut(self).ticker = Some(ticker.clone());
440        if self.widget(app).is_indeterminate && self.widget(app).is_visible {
441            ticker.start(app);
442        }
443    }
444
445    /// Applies source property-change behavior when the owner supplies new values.
446    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ProgressBar) {
447        let widget = self.widget(app);
448        let width_component_changed = old.value != widget.value
449            || old.minimum != widget.minimum
450            || old.maximum != widget.maximum
451            || old.padding != widget.padding
452            || old.is_indeterminate != widget.is_indeterminate
453            || old.show_paused != widget.show_paused
454            || old.show_error != widget.show_error;
455        if width_component_changed {
456            self.update_indicator_width(app);
457        } else if old.visual_state() != widget.visual_state() {
458            let resources = ThemeResources::of(app, self.context(app));
459            let color = self.color(app, old, &resources);
460            let previous = progress_visuals(
461                old.visual_state(),
462                app.get(self).from,
463                app.get(self).elapsed.as_secs_f64(),
464                app.get(self).initial_second,
465            );
466            self.start_state(
467                app,
468                old.visual_state(),
469                color,
470                previous.second.unwrap_or(0.0),
471            );
472        }
473    }
474
475    fn activate(self: Handle<Self>, app: &mut App) {
476        SingleTickerProviderStateMixin::activate(self, app);
477    }
478
479    /// Releases the storyboard clock before disposing its ticker provider.
480    fn dispose(self: Handle<Self>, app: &mut App) {
481        app.get(self).ticker.handle().unwrap().dispose(app);
482        SingleTickerProviderStateMixin::dispose(self, app);
483    }
484
485    /// Builds the named template parts from the current visual state.
486    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
487        let widget = self.widget(app).clone();
488        let resources = ThemeResources::of(app, context);
489        let state = widget.visual_state();
490        let scale = MediaQuery::device_pixel_ratio_of(app, context);
491        let border = widget
492            .border_thickness
493            .unwrap_or(resources.progress_bar_border_theme_thickness)
494            .map(|side| (side * scale).round() / scale);
495        let range = RangeBase::new(widget.minimum, widget.maximum, widget.value).coerced();
496
497        let body = LayoutBuilder::new(move |app, _, constraints| {
498            let width = if constraints.max_width.is_finite() {
499                constraints.max_width
500            } else {
501                constraints.min_width
502            };
503            let inset = widget.padding[0] + widget.padding[2] + border[0] + border[2];
504            let available = (width - inset).max(0.0);
505            let height = widget
506                .min_height
507                .unwrap_or(resources.progress_bar_min_height);
508            let root_size = constraints.constrain(Size::new(
509                width,
510                height + widget.padding[1] + widget.padding[3] + border[1] + border[3],
511            ));
512            if app.get(self).layout_size != Some(root_size) {
513                app.get_mut(self).layout_size = Some(root_size);
514                // OnSizeChanged calls SetProgressBarIndicatorWidth before updating the template settings.
515                self.update_indicator_width(app);
516            }
517            let foreground = self.color(app, &widget, &resources);
518            let visuals = progress_visuals(
519                state,
520                app.get(self).from,
521                app.get(self).elapsed.as_secs_f64(),
522                app.get(self).initial_second,
523            );
524            let mut parts = Vec::new();
525
526            // ProgressBarTrack.
527            if visuals.track_opacity > 0.0 {
528                parts.push(
529                    Positioned::new(progress_rectangle(
530                        available,
531                        resources.progress_bar_track_height,
532                        resources.progress_bar_track_corner_radius[0],
533                        widget
534                            .background
535                            .unwrap_or(resources.progress_bar_background),
536                    ))
537                    .left(visuals.track_translation * width)
538                    .top((height - resources.progress_bar_track_height) / 2.0)
539                    .into_widget(),
540                );
541            }
542
543            // DeterminateProgressBarIndicator.
544            if !widget.is_indeterminate {
545                parts.push(
546                    Positioned::new(progress_rectangle(
547                        if (range.maximum - range.minimum).abs() > f64::EPSILON {
548                            available * range.fraction_of(range.value)
549                        } else {
550                            0.0
551                        },
552                        height,
553                        widget
554                            .corner_radius
555                            .unwrap_or(resources.progress_bar_corner_radius[0]),
556                        foreground,
557                    ))
558                    .left(0.0)
559                    .top(0.0)
560                    .into_widget(),
561                );
562            }
563
564            // IndeterminateProgressBarIndicator and IndeterminateProgressBarIndicator2.
565            if let Some(position) = visuals.first {
566                parts.push(
567                    Positioned::new(progress_rectangle(
568                        available * 0.4,
569                        height,
570                        widget
571                            .corner_radius
572                            .unwrap_or(resources.progress_bar_corner_radius[0]),
573                        foreground,
574                    ))
575                    .left(position * width)
576                    .top(0.0)
577                    .into_widget(),
578                );
579            }
580            if let Some(position) = visuals.second {
581                parts.push(
582                    Positioned::new(progress_rectangle(
583                        available * if state.suspended() { 1.0 } else { 0.6 },
584                        height,
585                        widget
586                            .corner_radius
587                            .unwrap_or(resources.progress_bar_corner_radius[0]),
588                        foreground,
589                    ))
590                    .left(position * width)
591                    .top(0.0)
592                    .into_widget(),
593                );
594            }
595
596            SizedBox::new()
597                .width(width)
598                .child(
599                    ControlBorder::new(
600                        Brush::Solid(Color::from_argb(0, 0, 0, 0)),
601                        Brush::Solid(
602                            widget
603                                .border_brush
604                                .unwrap_or(resources.progress_bar_border_brush),
605                        ),
606                    )
607                    .border_thickness_ltrb(border)
608                    .corner_radius(
609                        widget
610                            .corner_radius
611                            .unwrap_or(resources.progress_bar_corner_radius[0]),
612                    )
613                    .child(
614                        Padding::new(EdgeInsetsGeometry::from_ltrb(
615                            widget.padding[0],
616                            widget.padding[1],
617                            widget.padding[2],
618                            widget.padding[3],
619                        ))
620                        .child(
621                            ClipRect::new()
622                                .clipper(ProgressClipper(Rect::from_ltwh(
623                                    widget.padding[0],
624                                    widget.padding[1],
625                                    (width - widget.padding[0] - widget.padding[2]).max(0.0),
626                                    (root_size.height() - widget.padding[1] - widget.padding[3])
627                                        .max(0.0),
628                                )))
629                                .child(
630                                    Align::new().height_factor(1.0).child(
631                                        SizedBox::new().height(height).child(
632                                            Stack::new()
633                                                .clip_behavior(waft_embedder::Clip::None)
634                                                .children(parts),
635                                        ),
636                                    ),
637                                ),
638                        ),
639                    ),
640                )
641                .into_widget()
642        });
643
644        Offstage::new()
645            .child(body.into_widget())
646            .offstage(!self.widget(app).is_visible)
647            .into_widget()
648    }
649}
650
651/// A source Rectangle with equal horizontal and vertical radii.
652fn progress_rectangle(width: f64, height: f64, radius: f64, color: Color) -> WidgetRef {
653    SizedBox::new()
654        .width(width)
655        .height(height)
656        .child(
657            ControlBorder::new(
658                Brush::Solid(color),
659                Brush::Solid(Color::from_argb(0, 0, 0, 0)),
660            )
661            .border_thickness(0.0)
662            .corner_radius(radius),
663        )
664        .into_widget()
665}
666
667/// TemplateSettings.ClipRect is expressed in LayoutRoot coordinates, including its padding offset.
668#[derive(Debug)]
669struct ProgressClipper(Rect);
670
671impl CustomClipper<Rect> for ProgressClipper {
672    fn get_clip(&self, _app: &App, _: Size) -> Rect {
673        self.0
674    }
675
676    fn should_reclip(&self, _app: &App, old: &dyn CustomClipper<Rect>) -> bool {
677        old.as_any()
678            .downcast_ref::<Self>()
679            .is_none_or(|old| old.0 != self.0)
680    }
681
682    fn as_any(&self) -> &dyn Any {
683        self
684    }
685}
686
687#[cfg(test)]
688mod tests {
689    use super::*;
690
691    #[test]
692    fn error_precedes_pause_and_hidden_indeterminate_uses_determinate_states() {
693        let bar = ProgressBar::new()
694            .is_indeterminate(true)
695            .show_paused(true)
696            .show_error(true);
697        assert_eq!(bar.visual_state(), ProgressState::IndeterminateError);
698        assert_eq!(bar.is_visible(false).visual_state(), ProgressState::Error);
699    }
700
701    #[test]
702    fn indeterminate_segments_follow_the_staggered_two_second_loop() {
703        let sample = |time| {
704            progress_visuals(
705                ProgressState::Indeterminate,
706                ProgressState::Determinate,
707                time,
708                0.0,
709            )
710        };
711        assert_eq!(sample(0.0).first, Some(-0.4));
712        assert_eq!(sample(0.75).second, Some(-0.9));
713        assert!((sample(1.5).first.unwrap() - 1.2).abs() < 1e-12);
714        assert_eq!(sample(2.0).first, Some(-0.4));
715        assert_eq!(sample(2.0).second, Some(-0.9));
716    }
717
718    #[test]
719    fn suspension_fills_the_track_and_resume_finishes_before_the_loop() {
720        let pause = progress_visuals(
721            ProgressState::IndeterminatePaused,
722            ProgressState::Indeterminate,
723            0.75,
724            0.2,
725        );
726        assert_eq!(pause.first, None);
727        assert_eq!(pause.second, Some(0.0));
728        let resume = |time| {
729            progress_visuals(
730                ProgressState::Indeterminate,
731                ProgressState::IndeterminatePaused,
732                time,
733                0.0,
734            )
735        };
736        assert_eq!(resume(0.333).first, None);
737        assert!((resume(0.333).second.unwrap() - 1.2).abs() < 1e-12);
738        assert_eq!(resume(0.5).first, Some(-0.4));
739    }
740}