1#![allow(deprecated)]
10
11use std::any::Any;
12use std::f64::consts::PI;
13use std::rc::Rc;
14use std::time::Duration;
15
16use waft_animation::{
17 Animatable, AnimationBehavior, AnimationController, AnimationRef, AnyAnimation, Cubic, Curve,
18 Curves, Interval, SawTooth, TweenSequence, TweenSequenceItem, ValueCurveTween, ValueTween,
19};
20use waft_cupertino::CupertinoActivityIndicator;
21use waft_embedder::StrokeCap;
22use waft_embedder::{
23 Canvas, Color, FillRule, Offset, Paint, PaintStyle, PathBuilder, Rect, SemanticsRole, Size,
24 Stroke, TargetPlatform, TextDirection, clamp_double,
25};
26use waft_foundation::{App, DiagnosticPropertiesBuilder, Handle, PercentProperty, Ref};
27use waft_painting::{BorderRadiusGeometry, EdgeInsets, EdgeInsetsGeometry, draw_arc, draw_rrect};
28use waft_rendering::{BoxConstraints, CustomPainter};
29use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
30use waft_widgets::{
31 AnimatedBuilder, BuildContext, Builder, ClipRRect, ConstrainedBox, CustomPaint, Directionality,
32 IntoWidget, KeyRef, Opacity, Padding, Semantics, SingleTickerProviderStateMixin,
33 SingleTickerProviderStateMixinData, SizedBox, State, StateData, StatefulWidget, Transform,
34 WidgetRef,
35};
36
37use crate::generated::progress_indicator_defaults_m3::{
38 CircularProgressIndicatorDefaultsM3, LinearProgressIndicatorDefaultsM3,
39};
40use crate::material::{Material, MaterialType};
41use crate::progress_indicator_theme::{
42 ProgressIndicatorTheme, ProgressIndicatorThemeData, ProgressIndicatorThemeDataGetters,
43};
44use crate::theme::Theme;
45use crate::theme_data_getters::DefaultsContext;
46
47const K_INDETERMINATE_LINEAR_DURATION: u64 = 1800;
50const K_INDETERMINATE_CIRCULAR_DURATION: u64 = 1333 * 2222;
53
54const K_TRACK_GAP_RAMP_DOWN_THRESHOLD: f64 = 0.01;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59enum ActivityIndicatorType {
60 Material,
61 Adaptive,
62}
63
64const K_VALUE_CONTROLLER_ASSERTION: &str = "A progress indicator cannot have both a value and a controller.\n\
65The \"value\" property is for a determinate indicator with a specific progress, \
66while the \"controller\" is for controlling the animation of an indeterminate indicator.\n\
67To resolve this, provide only one of the two properties.";
68
69#[derive(Clone, Debug, Default)]
80pub struct ProgressIndicatorData {
81 pub key: Option<KeyRef>,
82
83 pub value: Option<f64>,
92
93 pub background_color: Option<Color>,
98
99 pub color: Option<Color>,
107
108 pub value_color: Option<AnimationRef<Option<Color>>>,
114
115 pub semantics_label: Option<String>,
121
122 pub semantics_value: Option<String>,
133}
134
135impl ProgressIndicatorData {
136 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
138 properties.add(
139 PercentProperty::new("value", self.value)
140 .with_show_name(false)
141 .if_null("<indeterminate>"),
142 );
143 }
144
145 fn effective_value(&self) -> Option<f64> {
146 self.value.map(|value| clamp_double(value, 0.0, 1.0))
147 }
148
149 #[cfg_attr(debug_assertions, track_caller)]
151 fn build_semantics_wrapper<K>(
152 &self,
153 _context: BuildContext,
154 child: impl IntoWidget<K>,
155 ) -> WidgetRef {
156 let mut is_progress_bar = false;
157 let mut expanded_semantics_value = self.semantics_value.clone();
158 if let Some(effective_value) = self.effective_value() {
159 expanded_semantics_value
160 .get_or_insert_with(|| format!("{}", (effective_value * 100.0).round() as i64));
161 is_progress_bar = true;
162 }
163 let mut semantics = Semantics::new().role(if is_progress_bar {
164 SemanticsRole::ProgressBar
165 } else {
166 SemanticsRole::LoadingSpinner
167 });
168 if let Some(semantics_label) = &self.semantics_label {
169 semantics = semantics.label(semantics_label.clone());
170 }
171 if is_progress_bar {
172 semantics = semantics.min_value("0").max_value("100");
173 }
174 if let Some(expanded_semantics_value) = expanded_semantics_value {
175 semantics = semantics.value(expanded_semantics_value);
176 }
177 semantics.child(child).into_widget()
178 }
179
180 fn get_value_color(
183 &self,
184 app: &mut App,
185 context: BuildContext,
186 color: Option<Color>,
187 default_color: Option<Color>,
188 ) -> Color {
189 if let Some(color) = self
190 .clone()
191 .value_color
192 .and_then(|value_color| value_color.value(app))
193 .or(color)
194 {
195 return color;
196 }
197 if let Some(color) = ProgressIndicatorTheme::of(app, context)
198 .color
199 .or(default_color)
200 {
201 return color;
202 }
203 Theme::of(app, context).color_scheme.primary()
204 }
205}
206
207pub trait ProgressIndicator: 'static {
214 fn progress_indicator_data(&self) -> &ProgressIndicatorData;
216}
217
218macro_rules! progress_indicator_setters {
221 ($name:ident, $($bag:ident).+) => {
222 #[doc = concat!("Dart `", stringify!($name), "(key:)`.")]
223 pub fn key(mut self, key: KeyRef) -> $name {
224 self.$($bag).+.key = Some(key);
225 self
226 }
227
228 #[doc = concat!("Dart `", stringify!($name), "(backgroundColor:)`.")]
229 pub fn background_color(mut self, background_color: Color) -> $name {
230 self.$($bag).+.background_color = Some(background_color);
231 self
232 }
233
234 #[doc = concat!("Dart `", stringify!($name), "(color:)`.")]
235 pub fn color(mut self, color: Color) -> $name {
236 self.$($bag).+.color = Some(color);
237 self
238 }
239
240 #[doc = concat!("Dart `", stringify!($name), "(valueColor:)`.")]
241 pub fn value_color(mut self, value_color: AnimationRef<Option<Color>>) -> $name {
242 self.$($bag).+.value_color = Some(value_color);
243 self
244 }
245
246 #[doc = concat!("Dart `", stringify!($name), "(semanticsLabel:)`.")]
247 pub fn semantics_label(mut self, semantics_label: impl Into<String>) -> $name {
248 self.$($bag).+.semantics_label = Some(semantics_label.into());
249 self
250 }
251
252 #[doc = concat!("Dart `", stringify!($name), "(semanticsValue:)`.")]
253 pub fn semantics_value(mut self, semantics_value: impl Into<String>) -> $name {
254 self.$($bag).+.semantics_value = Some(semantics_value.into());
255 self
256 }
257 };
258}
259
260#[derive(Debug)]
262struct LinearProgressIndicatorPainter {
263 track_color: Color,
264 value_color: Color,
265 value: Option<f64>,
266 animation_value: f64,
267 text_direction: TextDirection,
268 indicator_border_radius: Option<BorderRadiusGeometry>,
269 stop_indicator_color: Option<Color>,
270 stop_indicator_radius: Option<f64>,
271 track_gap: Option<f64>,
272}
273
274impl LinearProgressIndicatorPainter {
275 fn line1_head() -> Interval {
278 Interval::new(
279 0.0,
280 750.0 / K_INDETERMINATE_LINEAR_DURATION as f64,
281 Rc::new(Cubic::new(0.2, 0.0, 0.8, 1.0)),
282 )
283 }
284
285 fn line1_tail() -> Interval {
286 Interval::new(
287 333.0 / K_INDETERMINATE_LINEAR_DURATION as f64,
288 (333.0 + 750.0) / K_INDETERMINATE_LINEAR_DURATION as f64,
289 Rc::new(Cubic::new(0.4, 0.0, 1.0, 1.0)),
290 )
291 }
292
293 fn line2_head() -> Interval {
294 Interval::new(
295 1000.0 / K_INDETERMINATE_LINEAR_DURATION as f64,
296 (1000.0 + 567.0) / K_INDETERMINATE_LINEAR_DURATION as f64,
297 Rc::new(Cubic::new(0.0, 0.0, 0.65, 1.0)),
298 )
299 }
300
301 fn line2_tail() -> Interval {
302 Interval::new(
303 1267.0 / K_INDETERMINATE_LINEAR_DURATION as f64,
304 (1267.0 + 533.0) / K_INDETERMINATE_LINEAR_DURATION as f64,
305 Rc::new(Cubic::new(0.10, 0.0, 0.45, 1.0)),
306 )
307 }
308
309 fn draw_linear_indicator(
310 &self,
311 canvas: &mut Canvas,
312 size: Size,
313 start_fraction: f64,
314 end_fraction: f64,
315 color: Color,
316 ) {
317 if end_fraction - start_fraction <= 0.0 {
318 return;
319 }
320
321 let is_ltr = self.text_direction == TextDirection::Ltr;
322 let left = (if is_ltr {
323 start_fraction
324 } else {
325 1.0 - end_fraction
326 }) * size.width();
327 let right = (if is_ltr {
328 end_fraction
329 } else {
330 1.0 - start_fraction
331 }) * size.width();
332
333 let rect = Rect::from_ltrb(left, 0.0, right, size.height());
334 let paint = Paint::from_color(color.into());
335
336 match self.indicator_border_radius {
337 Some(indicator_border_radius) => {
338 let rrect = indicator_border_radius
339 .resolve(Some(self.text_direction))
340 .to_rrect(rect);
341 draw_rrect(canvas, rrect, &paint);
342 }
343 None => canvas.draw_rect(rect, &paint),
344 }
345 }
346
347 fn draw_stop_indicator(&self, canvas: &mut Canvas, size: Size) {
348 let max_radius = size.height() / 2.0;
350 let radius = self
351 .stop_indicator_radius
352 .expect("drawn only with a radius")
353 .min(max_radius);
354 let indicator_paint = Paint::from_color(
355 self.stop_indicator_color
356 .expect("drawn only with a colour")
357 .into(),
358 );
359 let position = match self.text_direction {
360 TextDirection::Rtl => Offset::new(max_radius, max_radius),
361 TextDirection::Ltr => Offset::new(size.width() - max_radius, max_radius),
362 };
363 canvas.draw_circle(position, radius as f32, &indicator_paint);
364 }
365
366 fn get_effective_track_gap_fraction(current_value: f64, track_gap_fraction: f64) -> f64 {
373 track_gap_fraction * clamp_double(current_value, 0.0, K_TRACK_GAP_RAMP_DOWN_THRESHOLD)
374 / K_TRACK_GAP_RAMP_DOWN_THRESHOLD
375 }
376
377 fn paint_determinate(
378 &self,
379 canvas: &mut Canvas,
380 size: Size,
381 effective_value: f64,
382 track_gap_fraction: f64,
383 ) {
384 let track_start_fraction = if track_gap_fraction > 0.0 {
385 effective_value
386 + LinearProgressIndicatorPainter::get_effective_track_gap_fraction(
387 effective_value,
388 track_gap_fraction,
389 )
390 } else {
391 0.0
392 };
393
394 if track_start_fraction < 1.0 {
396 self.draw_linear_indicator(canvas, size, track_start_fraction, 1.0, self.track_color);
397 }
398
399 if self
401 .stop_indicator_radius
402 .is_some_and(|stop_indicator_radius| stop_indicator_radius > 0.0)
403 {
404 self.draw_stop_indicator(canvas, size);
405 }
406
407 if effective_value > 0.0 {
409 self.draw_linear_indicator(canvas, size, 0.0, effective_value, self.value_color);
410 }
411 }
412
413 fn paint_indeterminate(&self, canvas: &mut Canvas, size: Size, track_gap_fraction: f64) {
414 let first_line_head =
417 LinearProgressIndicatorPainter::line1_head().transform(self.animation_value);
418 let first_line_tail =
419 LinearProgressIndicatorPainter::line1_tail().transform(self.animation_value);
420 let second_line_head =
421 LinearProgressIndicatorPainter::line2_head().transform(self.animation_value);
422 let second_line_tail =
423 LinearProgressIndicatorPainter::line2_tail().transform(self.animation_value);
424 let gap = LinearProgressIndicatorPainter::get_effective_track_gap_fraction;
425
426 if first_line_head < 1.0 - track_gap_fraction {
429 let track_start_fraction = if first_line_head > 0.0 {
430 first_line_head + gap(first_line_head, track_gap_fraction)
431 } else {
432 0.0
433 };
434 self.draw_linear_indicator(canvas, size, track_start_fraction, 1.0, self.track_color);
435 }
436
437 if first_line_head - first_line_tail > 0.0 {
439 self.draw_linear_indicator(
440 canvas,
441 size,
442 first_line_tail,
443 first_line_head,
444 self.value_color,
445 );
446 }
447
448 if first_line_tail > track_gap_fraction {
452 let track_start_fraction = if second_line_head > 0.0 {
453 second_line_head + gap(second_line_head, track_gap_fraction)
454 } else {
455 0.0
456 };
457 let track_end_fraction = if first_line_tail < 1.0 {
458 first_line_tail - gap(1.0 - first_line_tail, track_gap_fraction)
459 } else {
460 1.0
461 };
462 self.draw_linear_indicator(
463 canvas,
464 size,
465 track_start_fraction,
466 track_end_fraction,
467 self.track_color,
468 );
469 }
470
471 if second_line_head - second_line_tail > 0.0 {
473 self.draw_linear_indicator(
474 canvas,
475 size,
476 second_line_tail,
477 second_line_head,
478 self.value_color,
479 );
480 }
481
482 if second_line_tail > track_gap_fraction {
485 let track_end_fraction = if second_line_tail < 1.0 {
486 second_line_tail - gap(1.0 - second_line_tail, track_gap_fraction)
487 } else {
488 1.0
489 };
490 self.draw_linear_indicator(canvas, size, 0.0, track_end_fraction, self.track_color);
491 }
492 }
493}
494
495impl CustomPainter for LinearProgressIndicatorPainter {
496 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
497 let effective_track_gap = self.track_gap.unwrap_or(0.0);
498 let track_gap_fraction = effective_track_gap / size.width();
499 let effective_value = self.value.map(|value| clamp_double(value, 0.0, 1.0));
500
501 match effective_value {
502 Some(effective_value) => {
503 self.paint_determinate(canvas, size, effective_value, track_gap_fraction);
504 }
505 None => self.paint_indeterminate(canvas, size, track_gap_fraction),
506 }
507 }
508
509 fn should_repaint(&self, _app: &App, old_painter: &dyn CustomPainter) -> bool {
510 let old_painter = old_painter
511 .as_any()
512 .downcast_ref::<LinearProgressIndicatorPainter>()
513 .expect("Dart's covariant parameter");
514 old_painter.track_color != self.track_color
515 || old_painter.value_color != self.value_color
516 || old_painter.value != self.value
517 || old_painter.animation_value != self.animation_value
518 || old_painter.text_direction != self.text_direction
519 || old_painter.indicator_border_radius != self.indicator_border_radius
520 || old_painter.stop_indicator_color != self.stop_indicator_color
521 || old_painter.stop_indicator_radius != self.stop_indicator_radius
522 || old_painter.track_gap != self.track_gap
523 }
524
525 fn as_any(&self) -> &dyn Any {
526 self
527 }
528}
529
530#[derive(Clone, Debug, Default)]
575pub struct LinearProgressIndicator {
576 pub progress_indicator: ProgressIndicatorData,
583
584 pub min_height: Option<f64>,
590
591 pub border_radius: Option<BorderRadiusGeometry>,
599
600 pub stop_indicator_color: Option<Color>,
608
609 pub stop_indicator_radius: Option<f64>,
620
621 pub track_gap: Option<f64>,
631
632 #[deprecated(
643 note = "Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. This feature was deprecated after v3.27.0-0.1.pre."
644 )]
645 pub year2023: Option<bool>,
646
647 pub controller: Option<Ref<AnimationController>>,
666}
667
668impl LinearProgressIndicator {
669 pub const DEFAULT_ANIMATION_DURATION: Duration =
675 Duration::from_millis(K_INDETERMINATE_LINEAR_DURATION);
676
677 pub fn new() -> LinearProgressIndicator {
683 LinearProgressIndicator::default()
684 }
685
686 progress_indicator_setters!(LinearProgressIndicator, progress_indicator);
687
688 pub fn value(mut self, value: f64) -> LinearProgressIndicator {
690 debug_assert!(self.controller.is_none(), "{K_VALUE_CONTROLLER_ASSERTION}");
691 self.progress_indicator.value = Some(value);
692 self
693 }
694
695 pub fn min_height(mut self, min_height: f64) -> LinearProgressIndicator {
697 debug_assert!(min_height > 0.0);
698 self.min_height = Some(min_height);
699 self
700 }
701
702 pub fn border_radius(
704 mut self,
705 border_radius: impl Into<BorderRadiusGeometry>,
706 ) -> LinearProgressIndicator {
707 self.border_radius = Some(border_radius.into());
708 self
709 }
710
711 pub fn stop_indicator_color(mut self, stop_indicator_color: Color) -> LinearProgressIndicator {
713 self.stop_indicator_color = Some(stop_indicator_color);
714 self
715 }
716
717 pub fn stop_indicator_radius(mut self, stop_indicator_radius: f64) -> LinearProgressIndicator {
719 self.stop_indicator_radius = Some(stop_indicator_radius);
720 self
721 }
722
723 pub fn track_gap(mut self, track_gap: f64) -> LinearProgressIndicator {
725 self.track_gap = Some(track_gap);
726 self
727 }
728
729 #[deprecated(
731 note = "Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. This feature was deprecated after v3.26.0-0.1.pre."
732 )]
733 pub fn year2023(mut self, year2023: bool) -> LinearProgressIndicator {
734 self.year2023 = Some(year2023);
735 self
736 }
737
738 pub fn controller(mut self, controller: Ref<AnimationController>) -> LinearProgressIndicator {
740 debug_assert!(
741 self.progress_indicator.value.is_none(),
742 "{K_VALUE_CONTROLLER_ASSERTION}"
743 );
744 self.controller = Some(controller);
745 self
746 }
747}
748
749impl ProgressIndicator for LinearProgressIndicator {
750 fn progress_indicator_data(&self) -> &ProgressIndicatorData {
751 &self.progress_indicator
752 }
753}
754
755impl StatefulWidget for LinearProgressIndicator {
756 type State = LinearProgressIndicatorState;
757
758 fn key(&self) -> Option<&KeyRef> {
759 self.progress_indicator.key.as_ref()
760 }
761
762 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
763 self.progress_indicator_data()
764 .debug_fill_properties(properties);
765 }
766
767 fn create_state(&self) -> LinearProgressIndicatorState {
768 LinearProgressIndicatorState {
769 state: StateData::new(),
770 single_ticker_provider: SingleTickerProviderStateMixinData::default(),
771 internal_controller: None,
772 }
773 }
774}
775
776pub struct LinearProgressIndicatorState {
778 state: StateData<LinearProgressIndicator>,
779 single_ticker_provider: SingleTickerProviderStateMixinData,
780 internal_controller: Option<Ref<AnimationController>>,
781}
782
783impl LinearProgressIndicatorState {
784 fn internal_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
785 app.get(self)
786 .internal_controller
787 .as_ref()
788 .expect("created in init_state")
789 }
790
791 fn controller(self: Handle<Self>, app: &App) -> Ref<AnimationController> {
792 let context = self.context(app);
793 self.widget(app)
794 .controller
795 .clone()
796 .or_else(|| {
797 context
798 .get_inherited_widget_of_exact_type::<ProgressIndicatorTheme>(app)
799 .and_then(|theme| theme.data.controller.clone())
800 })
801 .or_else(|| {
802 context
803 .find_ancestor_widget_of_exact_type::<Theme>(app)
804 .and_then(|theme| theme.data.progress_indicator_theme.controller.clone())
805 })
806 .unwrap_or_else(|| self.internal_controller(app).clone())
807 }
808
809 fn update_controller_animating_status(self: Handle<Self>, app: &mut App) {
810 let effective_value = self.widget(app).progress_indicator.effective_value();
811 let internal_controller = self.internal_controller(app).handle();
812 if effective_value.is_none() && !internal_controller.is_animating(app) {
813 internal_controller.repeat(app, None, None, false, None, None);
814 } else if effective_value.is_some() && internal_controller.is_animating(app) {
815 internal_controller.stop(app, true);
816 }
817 }
818
819 fn build_indicator(
820 self: Handle<Self>,
821 app: &mut App,
822 context: BuildContext,
823 animation_value: f64,
824 text_direction: TextDirection,
825 ) -> WidgetRef {
826 let indicator_theme = ProgressIndicatorTheme::of(app, context);
827 let widget = self.widget(app);
828 let year2023 = widget.year2023.or(indicator_theme.year2023).unwrap_or(true);
829 let defaults: Box<dyn ProgressIndicatorThemeDataGetters> =
830 if Theme::of(app, context).use_material3 {
831 if year2023 {
832 Box::new(LinearProgressIndicatorDefaultsM3Year2023::new(context))
833 } else {
834 Box::new(LinearProgressIndicatorDefaultsM3::new(context))
835 }
836 } else {
837 Box::new(LinearProgressIndicatorDefaultsM2::new(context))
838 };
839 let widget = self.widget(app).clone();
840 let track_color = widget
841 .progress_indicator
842 .background_color
843 .or(indicator_theme.linear_track_color)
844 .or_else(|| defaults.linear_track_color(app))
845 .expect("the defaults give a track colour");
846 let min_height = widget
847 .min_height
848 .or(indicator_theme.linear_min_height)
849 .or_else(|| defaults.linear_min_height(app))
850 .expect("the defaults give a minimum height");
851 let border_radius = widget
852 .border_radius
853 .or(indicator_theme.border_radius)
854 .or_else(|| defaults.border_radius(app));
855 let stop_indicator_color = if !year2023 {
856 widget
857 .stop_indicator_color
858 .or(indicator_theme.stop_indicator_color)
859 .or_else(|| defaults.stop_indicator_color(app))
860 } else {
861 None
862 };
863 let stop_indicator_radius = if !year2023 {
864 widget
865 .stop_indicator_radius
866 .or(indicator_theme.stop_indicator_radius)
867 .or_else(|| defaults.stop_indicator_radius(app))
868 } else {
869 None
870 };
871 let track_gap = if !year2023 {
872 widget
873 .track_gap
874 .or(indicator_theme.track_gap)
875 .or_else(|| defaults.track_gap(app))
876 } else {
877 None
878 };
879 let progress_indicator = widget.progress_indicator.clone();
880 let effective_value = progress_indicator.effective_value();
881 let default_color = defaults.color(app);
882
883 let mut result = ConstrainedBox::new(
884 BoxConstraints::new()
885 .min_width(f64::INFINITY)
886 .min_height(min_height),
887 )
888 .child(CustomPaint::new().painter(LinearProgressIndicatorPainter {
889 track_color,
890 value_color: progress_indicator.get_value_color(
891 app,
892 context,
893 progress_indicator.color,
894 default_color,
895 ),
896 value: effective_value, animation_value, text_direction,
899 indicator_border_radius: border_radius,
900 stop_indicator_color,
901 stop_indicator_radius,
902 track_gap,
903 }))
904 .into_widget();
905
906 if let Some(border_radius) = border_radius
908 && effective_value.is_none()
909 {
910 result = ClipRRect::new()
911 .border_radius(border_radius)
912 .child(result)
913 .into_widget();
914 }
915
916 progress_indicator.build_semantics_wrapper(context, result)
917 }
918}
919
920impl SingleTickerProviderStateMixin for LinearProgressIndicatorState {
921 fn single_ticker_provider_data(
922 self: Handle<Self>,
923 app: &App,
924 ) -> &SingleTickerProviderStateMixinData {
925 &app.get(self).single_ticker_provider
926 }
927
928 fn single_ticker_provider_data_mut(
929 self: Handle<Self>,
930 app: &mut App,
931 ) -> &mut SingleTickerProviderStateMixinData {
932 &mut app.get_mut(self).single_ticker_provider
933 }
934}
935
936impl TickerProviderObject for LinearProgressIndicatorState {
938 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
939 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
940 }
941}
942
943impl State for LinearProgressIndicatorState {
944 type Widget = LinearProgressIndicator;
945 waft_widgets::state_accessors!();
946
947 fn init_state(self: Handle<Self>, app: &mut App) {
948 let internal_controller = AnimationController::new(
949 app,
950 None,
951 Some(LinearProgressIndicator::DEFAULT_ANIMATION_DURATION),
952 None,
953 0.0,
954 1.0,
955 AnimationBehavior::Normal,
956 self,
957 );
958 app.get_mut(self).internal_controller = Some(internal_controller.clone());
959 self.update_controller_animating_status(app);
960 }
961
962 fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &LinearProgressIndicator) {
963 self.update_controller_animating_status(app);
964 }
965
966 fn activate(self: Handle<Self>, app: &mut App) {
967 SingleTickerProviderStateMixin::activate(self, app);
968 }
969
970 fn dispose(self: Handle<Self>, app: &mut App) {
971 let internal_controller = self.internal_controller(app).handle();
972 internal_controller.dispose(app);
973 SingleTickerProviderStateMixin::dispose(self, app);
974 }
975
976 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
977 let text_direction = Directionality::of(app, context);
978
979 if self
980 .widget(app)
981 .progress_indicator
982 .effective_value()
983 .is_some()
984 {
985 let animation_value = self.controller(app).value(app);
986 return self.build_indicator(app, context, animation_value, text_direction);
987 }
988
989 AnimatedBuilder::new(
990 Rc::new(self.controller(app).erase::<AnyAnimation<f64>>()),
991 move |app, context, _child| {
992 let animation_value = self.controller(app).value(app);
993 self.build_indicator(app, context, animation_value, text_direction)
994 },
995 )
996 .into_widget()
997 }
998}
999
1000fn stroke_paint(color: Color, stroke_width: f64, cap: StrokeCap) -> Paint {
1002 let mut paint = Paint::from_color(color.into());
1003 paint.style = PaintStyle::Stroke(Stroke {
1004 cap,
1005 ..Stroke::new(stroke_width as f32)
1006 });
1007 paint
1008}
1009
1010#[derive(Debug)]
1012struct CircularProgressIndicatorPainter {
1013 track_color: Option<Color>,
1014 value_color: Color,
1015 value: Option<f64>,
1016 head_value: f64,
1017 tail_value: f64,
1018 offset_value: f64,
1019 rotation_value: f64,
1020 stroke_width: f64,
1021 stroke_align: f64,
1022 arc_start: f64,
1023 arc_sweep: f64,
1024 stroke_cap: Option<StrokeCap>,
1025 track_gap: Option<f64>,
1026 year2023: bool,
1027}
1028
1029impl CircularProgressIndicatorPainter {
1030 const TWO_PI: f64 = PI * 2.0;
1031 const EPSILON: f64 = 0.001;
1032 const SWEEP: f64 =
1034 CircularProgressIndicatorPainter::TWO_PI - CircularProgressIndicatorPainter::EPSILON;
1035 const START_ANGLE: f64 = -PI / 2.0;
1036
1037 #[allow(clippy::too_many_arguments)]
1038 fn new(
1039 track_color: Option<Color>,
1040 value_color: Color,
1041 value: Option<f64>,
1042 head_value: f64,
1043 tail_value: f64,
1044 offset_value: f64,
1045 rotation_value: f64,
1046 stroke_width: f64,
1047 stroke_align: f64,
1048 stroke_cap: Option<StrokeCap>,
1049 track_gap: Option<f64>,
1050 year2023: bool,
1051 ) -> CircularProgressIndicatorPainter {
1052 let arc_start = match value {
1053 Some(_) => CircularProgressIndicatorPainter::START_ANGLE,
1054 None => {
1055 CircularProgressIndicatorPainter::START_ANGLE
1056 + tail_value * 3.0 / 2.0 * PI
1057 + rotation_value * PI * 2.0
1058 + offset_value * 0.5 * PI
1059 }
1060 };
1061 let arc_sweep = match value {
1062 Some(value) => clamp_double(value, 0.0, 1.0) * CircularProgressIndicatorPainter::SWEEP,
1063 None => (head_value * 3.0 / 2.0 * PI - tail_value * 3.0 / 2.0 * PI)
1064 .max(CircularProgressIndicatorPainter::EPSILON),
1065 };
1066 CircularProgressIndicatorPainter {
1067 track_color,
1068 value_color,
1069 value,
1070 head_value,
1071 tail_value,
1072 offset_value,
1073 rotation_value,
1074 stroke_width,
1075 stroke_align,
1076 arc_start,
1077 arc_sweep,
1078 stroke_cap,
1079 track_gap,
1080 year2023,
1081 }
1082 }
1083
1084 fn paint_track(&self, canvas: &mut Canvas, size: Size, track_color: Color, arc_rect: Rect) {
1085 let has_gap = self.track_gap.is_some_and(|track_gap| track_gap > 0.0);
1086 let background_paint = stroke_paint(
1087 track_color,
1088 self.stroke_width,
1089 self.stroke_cap.unwrap_or(StrokeCap::Round),
1090 );
1091 match self.value {
1093 Some(value) if has_gap && value > CircularProgressIndicatorPainter::EPSILON => {
1094 let arc_radius = arc_rect.shortest_side() / 2.0;
1095 let stroke_radius = self.stroke_width / arc_radius;
1096 let gap_radius = self.track_gap.expect("has_gap") / arc_radius;
1097 let start_gap = stroke_radius + gap_radius;
1098 let end_gap = if value < CircularProgressIndicatorPainter::EPSILON {
1099 start_gap
1100 } else {
1101 start_gap * 2.0
1102 };
1103 let start_sweep = (-PI / 2.0) + start_gap;
1104 let end_sweep = (CircularProgressIndicatorPainter::TWO_PI
1105 - clamp_double(value, 0.0, 1.0) * CircularProgressIndicatorPainter::TWO_PI
1106 - end_gap)
1107 .max(0.0);
1108 canvas.save();
1110 canvas.scale(-1.0, 1.0);
1111 canvas.translate(-size.width() as f32, 0.0);
1112 draw_arc(
1113 canvas,
1114 arc_rect,
1115 start_sweep,
1116 end_sweep,
1117 false,
1118 &background_paint,
1119 );
1120 canvas.restore();
1122 }
1123 _ => draw_arc(
1124 canvas,
1125 arc_rect,
1126 0.0,
1127 CircularProgressIndicatorPainter::SWEEP,
1128 false,
1129 &background_paint,
1130 ),
1131 }
1132 }
1133
1134 fn active_stroke_cap(&self) -> StrokeCap {
1135 if self.year2023 {
1136 if self.value.is_none() && self.stroke_cap.is_none() {
1137 StrokeCap::Square
1139 } else {
1140 self.stroke_cap.unwrap_or(StrokeCap::Butt)
1142 }
1143 } else {
1144 self.stroke_cap.unwrap_or(StrokeCap::Round)
1145 }
1146 }
1147}
1148
1149impl CustomPainter for CircularProgressIndicatorPainter {
1150 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1151 let stroke_offset = self.stroke_width / 2.0 * -self.stroke_align;
1154 let arc_base_offset = Offset::new(stroke_offset, stroke_offset);
1155 let arc_actual_size = Size::new(
1156 size.width() - stroke_offset * 2.0,
1157 size.height() - stroke_offset * 2.0,
1158 );
1159 let arc_rect = arc_base_offset & arc_actual_size;
1160
1161 if let Some(track_color) = self.track_color {
1162 self.paint_track(canvas, size, track_color, arc_rect);
1163 }
1164
1165 let paint = stroke_paint(
1166 self.value_color,
1167 self.stroke_width,
1168 self.active_stroke_cap(),
1169 );
1170 draw_arc(
1171 canvas,
1172 arc_rect,
1173 self.arc_start,
1174 self.arc_sweep,
1175 false,
1176 &paint,
1177 );
1178 }
1179
1180 fn should_repaint(&self, _app: &App, old_painter: &dyn CustomPainter) -> bool {
1181 let old_painter = old_painter
1182 .as_any()
1183 .downcast_ref::<CircularProgressIndicatorPainter>()
1184 .expect("Dart's covariant parameter");
1185 old_painter.track_color != self.track_color
1186 || old_painter.value_color != self.value_color
1187 || old_painter.value != self.value
1188 || old_painter.head_value != self.head_value
1189 || old_painter.tail_value != self.tail_value
1190 || old_painter.offset_value != self.offset_value
1191 || old_painter.rotation_value != self.rotation_value
1192 || old_painter.stroke_width != self.stroke_width
1193 || old_painter.stroke_align != self.stroke_align
1194 || old_painter.stroke_cap != self.stroke_cap
1195 || old_painter.track_gap != self.track_gap
1196 || old_painter.year2023 != self.year2023
1197 }
1198
1199 fn as_any(&self) -> &dyn Any {
1200 self
1201 }
1202}
1203
1204#[derive(Clone, Debug)]
1232pub struct CircularProgressIndicator {
1233 pub progress_indicator: ProgressIndicatorData,
1240
1241 indicator_type: ActivityIndicatorType,
1242
1243 pub stroke_width: Option<f64>,
1245
1246 pub stroke_align: Option<f64>,
1258
1259 pub stroke_cap: Option<StrokeCap>,
1279
1280 pub constraints: Option<BoxConstraints>,
1285
1286 pub track_gap: Option<f64>,
1296
1297 #[deprecated(
1308 note = "Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. This feature was deprecated after v3.27.0-0.2.pre."
1309 )]
1310 pub year2023: Option<bool>,
1311
1312 pub padding: Option<EdgeInsetsGeometry>,
1318
1319 pub controller: Option<Ref<AnimationController>>,
1327}
1328
1329impl CircularProgressIndicator {
1330 pub const STROKE_ALIGN_INSIDE: f64 = -1.0;
1334
1335 pub const STROKE_ALIGN_CENTER: f64 = 0.0;
1343
1344 pub const STROKE_ALIGN_OUTSIDE: f64 = 1.0;
1348
1349 pub const DEFAULT_ANIMATION_DURATION: Duration =
1357 Duration::from_millis(K_INDETERMINATE_CIRCULAR_DURATION);
1358
1359 pub fn new() -> CircularProgressIndicator {
1365 CircularProgressIndicator::with_type(ActivityIndicatorType::Material)
1366 }
1367
1368 pub fn adaptive() -> CircularProgressIndicator {
1381 CircularProgressIndicator::with_type(ActivityIndicatorType::Adaptive)
1382 }
1383
1384 fn with_type(indicator_type: ActivityIndicatorType) -> CircularProgressIndicator {
1385 CircularProgressIndicator {
1386 progress_indicator: ProgressIndicatorData::default(),
1387 indicator_type,
1388 stroke_width: None,
1389 stroke_align: None,
1390 stroke_cap: None,
1391 constraints: None,
1392 track_gap: None,
1393 year2023: None,
1394 padding: None,
1395 controller: None,
1396 }
1397 }
1398
1399 progress_indicator_setters!(CircularProgressIndicator, progress_indicator);
1400
1401 pub fn value(mut self, value: f64) -> CircularProgressIndicator {
1403 debug_assert!(self.controller.is_none(), "{K_VALUE_CONTROLLER_ASSERTION}");
1404 self.progress_indicator.value = Some(value);
1405 self
1406 }
1407
1408 pub fn stroke_width(mut self, stroke_width: f64) -> CircularProgressIndicator {
1410 self.stroke_width = Some(stroke_width);
1411 self
1412 }
1413
1414 pub fn stroke_align(mut self, stroke_align: f64) -> CircularProgressIndicator {
1416 self.stroke_align = Some(stroke_align);
1417 self
1418 }
1419
1420 pub fn stroke_cap(mut self, stroke_cap: StrokeCap) -> CircularProgressIndicator {
1422 self.stroke_cap = Some(stroke_cap);
1423 self
1424 }
1425
1426 pub fn constraints(mut self, constraints: BoxConstraints) -> CircularProgressIndicator {
1428 self.constraints = Some(constraints);
1429 self
1430 }
1431
1432 pub fn track_gap(mut self, track_gap: f64) -> CircularProgressIndicator {
1434 self.track_gap = Some(track_gap);
1435 self
1436 }
1437
1438 #[deprecated(
1440 note = "Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. This feature was deprecated after v3.27.0-0.1.pre."
1441 )]
1442 pub fn year2023(mut self, year2023: bool) -> CircularProgressIndicator {
1443 self.year2023 = Some(year2023);
1444 self
1445 }
1446
1447 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> CircularProgressIndicator {
1449 self.padding = Some(padding.into());
1450 self
1451 }
1452
1453 pub fn controller(mut self, controller: Ref<AnimationController>) -> CircularProgressIndicator {
1455 debug_assert!(
1456 self.progress_indicator.value.is_none(),
1457 "{K_VALUE_CONTROLLER_ASSERTION}"
1458 );
1459 self.controller = Some(controller);
1460 self
1461 }
1462
1463 pub fn effective_color(&self) -> Option<Color> {
1466 match self.indicator_type {
1467 ActivityIndicatorType::Material => self.progress_indicator.color,
1468 ActivityIndicatorType::Adaptive => None,
1469 }
1470 }
1471}
1472
1473impl Default for CircularProgressIndicator {
1474 fn default() -> CircularProgressIndicator {
1475 CircularProgressIndicator::new()
1476 }
1477}
1478
1479impl ProgressIndicator for CircularProgressIndicator {
1480 fn progress_indicator_data(&self) -> &ProgressIndicatorData {
1481 &self.progress_indicator
1482 }
1483}
1484
1485impl StatefulWidget for CircularProgressIndicator {
1486 type State = CircularProgressIndicatorState;
1487
1488 fn key(&self) -> Option<&KeyRef> {
1489 self.progress_indicator.key.as_ref()
1490 }
1491
1492 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1493 self.progress_indicator_data()
1494 .debug_fill_properties(properties);
1495 }
1496
1497 fn create_state(&self) -> CircularProgressIndicatorState {
1498 CircularProgressIndicatorState {
1499 state: StateData::new(),
1500 single_ticker_provider: SingleTickerProviderStateMixinData::default(),
1501 circular_state: CircularProgressIndicatorStateData::default(),
1502 }
1503 }
1504}
1505
1506const PATH_COUNT: i64 = (K_INDETERMINATE_CIRCULAR_DURATION / 1333) as i64;
1507const ROTATION_COUNT: i64 = (K_INDETERMINATE_CIRCULAR_DURATION / 2222) as i64;
1508
1509fn stroke_head_tween() -> impl Animatable<f64> {
1511 ValueCurveTween::new(Rc::new(Interval::new(0.0, 0.5, Curves::fast_out_slow_in())))
1512 .chain(ValueCurveTween::new(Rc::new(SawTooth::new(PATH_COUNT))))
1513}
1514
1515fn stroke_tail_tween() -> impl Animatable<f64> {
1517 ValueCurveTween::new(Rc::new(Interval::new(0.5, 1.0, Curves::fast_out_slow_in())))
1518 .chain(ValueCurveTween::new(Rc::new(SawTooth::new(PATH_COUNT))))
1519}
1520
1521fn offset_tween() -> impl Animatable<f64> {
1523 ValueCurveTween::new(Rc::new(SawTooth::new(PATH_COUNT)))
1524}
1525
1526fn rotation_tween() -> impl Animatable<f64> {
1528 ValueCurveTween::new(Rc::new(SawTooth::new(ROTATION_COUNT)))
1529}
1530
1531#[derive(Debug, Default)]
1534struct CircularProgressIndicatorStateData {
1535 internal_controller: Option<Ref<AnimationController>>,
1536}
1537
1538trait CircularProgressIndicatorStateBase:
1542 State + SingleTickerProviderStateMixin + TickerProviderObject
1543{
1544 fn circular_state_data(self: Handle<Self>, app: &App) -> &CircularProgressIndicatorStateData;
1545
1546 fn circular_state_data_mut(
1547 self: Handle<Self>,
1548 app: &mut App,
1549 ) -> &mut CircularProgressIndicatorStateData;
1550
1551 fn circular_widget(self: Handle<Self>, app: &App) -> &CircularProgressIndicator;
1553
1554 fn init_state(self: Handle<Self>, app: &mut App) {
1555 let internal_controller = AnimationController::new(
1556 app,
1557 None,
1558 Some(CircularProgressIndicator::DEFAULT_ANIMATION_DURATION),
1559 None,
1560 0.0,
1561 1.0,
1562 AnimationBehavior::Normal,
1563 self,
1564 );
1565 self.circular_state_data_mut(app).internal_controller = Some(internal_controller.clone());
1566 self.update_controller_animating_status(app);
1567 }
1568
1569 fn did_update_widget(self: Handle<Self>, app: &mut App) {
1570 self.update_controller_animating_status(app);
1571 }
1572
1573 fn dispose(self: Handle<Self>, app: &mut App) {
1574 let internal_controller = self.internal_controller(app).handle();
1575 internal_controller.dispose(app);
1576 SingleTickerProviderStateMixin::dispose(self, app);
1577 }
1578
1579 fn internal_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
1580 self.circular_state_data(app)
1581 .internal_controller
1582 .as_ref()
1583 .expect("created in init_state")
1584 }
1585
1586 fn controller(self: Handle<Self>, app: &App) -> Ref<AnimationController> {
1587 let context = self.context(app);
1588 self.circular_widget(app)
1589 .controller
1590 .clone()
1591 .or_else(|| {
1592 context
1593 .get_inherited_widget_of_exact_type::<ProgressIndicatorTheme>(app)
1594 .and_then(|theme| theme.data.controller.clone())
1595 })
1596 .or_else(|| {
1597 context
1598 .find_ancestor_widget_of_exact_type::<Theme>(app)
1599 .and_then(|theme| theme.data.progress_indicator_theme.controller.clone())
1600 })
1601 .unwrap_or_else(|| self.internal_controller(app).clone())
1602 }
1603
1604 fn update_controller_animating_status(self: Handle<Self>, app: &mut App) {
1605 let effective_value = self
1606 .circular_widget(app)
1607 .progress_indicator
1608 .effective_value();
1609 let internal_controller = self.internal_controller(app).handle();
1610 if effective_value.is_none() && !internal_controller.is_animating(app) {
1611 internal_controller.repeat(app, None, None, false, None, None);
1612 } else if effective_value.is_some() && internal_controller.is_animating(app) {
1613 internal_controller.stop(app, true);
1614 }
1615 }
1616
1617 fn build_cupertino_indicator(self: Handle<Self>, app: &mut App) -> WidgetRef {
1618 let progress_indicator = &self.circular_widget(app).progress_indicator;
1619 let tick_color = progress_indicator.background_color;
1620 let value = progress_indicator.effective_value();
1621 let indicator = match value {
1622 None => CupertinoActivityIndicator::new(),
1623 Some(value) => CupertinoActivityIndicator::partially_revealed().progress(value),
1624 };
1625 let indicator = match progress_indicator.key.clone() {
1626 Some(key) => indicator.key(key),
1627 None => indicator,
1628 };
1629 match tick_color {
1630 Some(tick_color) => indicator.color(tick_color),
1631 None => indicator,
1632 }
1633 .into_widget()
1634 }
1635
1636 fn build_material_indicator(
1637 self: Handle<Self>,
1638 app: &mut App,
1639 context: BuildContext,
1640 head_value: f64,
1641 tail_value: f64,
1642 offset_value: f64,
1643 rotation_value: f64,
1644 ) -> WidgetRef {
1645 let indicator_theme = ProgressIndicatorTheme::of(app, context);
1646 let year2023 = self
1647 .circular_widget(app)
1648 .year2023
1649 .or(indicator_theme.year2023)
1650 .unwrap_or(true);
1651 let indeterminate = self
1652 .circular_widget(app)
1653 .progress_indicator
1654 .effective_value()
1655 .is_none();
1656 let defaults: Box<dyn ProgressIndicatorThemeDataGetters> =
1657 if Theme::of(app, context).use_material3 {
1658 if year2023 {
1659 Box::new(CircularProgressIndicatorDefaultsM3Year2023::new(
1660 context,
1661 indeterminate,
1662 ))
1663 } else {
1664 Box::new(CircularProgressIndicatorDefaultsM3::new(
1665 context,
1666 indeterminate,
1667 ))
1668 }
1669 } else {
1670 Box::new(CircularProgressIndicatorDefaultsM2::new(
1671 context,
1672 indeterminate,
1673 ))
1674 };
1675 let widget = self.circular_widget(app).clone();
1676 let track_color = widget
1677 .progress_indicator
1678 .background_color
1679 .or(indicator_theme.circular_track_color)
1680 .or_else(|| defaults.circular_track_color(app));
1681 let stroke_width = widget
1682 .stroke_width
1683 .or(indicator_theme.stroke_width)
1684 .or_else(|| defaults.stroke_width(app))
1685 .expect("the defaults give a stroke width");
1686 let stroke_align = widget
1687 .stroke_align
1688 .or(indicator_theme.stroke_align)
1689 .or_else(|| defaults.stroke_align(app))
1690 .expect("the defaults give a stroke alignment");
1691 let stroke_cap = widget.stroke_cap.or(indicator_theme.stroke_cap);
1692 let constraints = widget
1693 .constraints
1694 .or(indicator_theme.constraints)
1695 .or_else(|| defaults.constraints(app))
1696 .expect("the defaults give constraints");
1697 let track_gap = if year2023 {
1698 None
1699 } else {
1700 widget
1701 .track_gap
1702 .or(indicator_theme.track_gap)
1703 .or_else(|| defaults.track_gap(app))
1704 };
1705 let effective_padding = widget
1706 .padding
1707 .or(indicator_theme.circular_track_padding)
1708 .or_else(|| defaults.circular_track_padding(app));
1709 let progress_indicator = widget.progress_indicator.clone();
1710 let color = widget.effective_color();
1711 let default_color = defaults.color(app);
1712
1713 let result = ConstrainedBox::new(constraints).child(CustomPaint::new().painter(
1714 CircularProgressIndicatorPainter::new(
1715 track_color,
1716 progress_indicator.get_value_color(app, context, color, default_color),
1717 progress_indicator.effective_value(), head_value, tail_value,
1720 offset_value,
1721 rotation_value,
1722 stroke_width,
1723 stroke_align,
1724 stroke_cap,
1725 track_gap,
1726 year2023,
1727 ),
1728 ));
1729
1730 let result = match effective_padding {
1731 Some(effective_padding) => Padding::new(effective_padding).child(result).into_widget(),
1732 None => result.into_widget(),
1733 };
1734
1735 progress_indicator.build_semantics_wrapper(context, result)
1736 }
1737
1738 fn build_animation(self: Handle<Self>, app: &mut App) -> WidgetRef {
1739 AnimatedBuilder::new(
1740 Rc::new(self.controller(app).erase::<AnyAnimation<f64>>()),
1741 move |app, context, _child| {
1742 let value = self.controller(app).value(app);
1743 self.build_material_indicator(
1744 app,
1745 context,
1746 stroke_head_tween().transform(app, value),
1747 stroke_tail_tween().transform(app, value),
1748 offset_tween().transform(app, value),
1749 rotation_tween().transform(app, value),
1750 )
1751 },
1752 )
1753 .into_widget()
1754 }
1755
1756 fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
1757 Builder::new(move |app, context| {
1758 let widget = self.circular_widget(app);
1759 let determinate = widget.progress_indicator.effective_value().is_some();
1760 match widget.indicator_type {
1761 ActivityIndicatorType::Material => {
1762 if determinate {
1763 return self.build_material_indicator(app, context, 0.0, 0.0, 0.0, 0.0);
1764 }
1765 self.build_animation(app)
1766 }
1767 ActivityIndicatorType::Adaptive => {
1768 let theme = Theme::of(app, context);
1769 match theme.platform {
1770 TargetPlatform::IOS | TargetPlatform::MacOS => {
1771 self.build_cupertino_indicator(app)
1772 }
1773 TargetPlatform::Android
1774 | TargetPlatform::Fuchsia
1775 | TargetPlatform::Linux
1776 | TargetPlatform::Windows => {
1777 if determinate {
1778 return self
1779 .build_material_indicator(app, context, 0.0, 0.0, 0.0, 0.0);
1780 }
1781 self.build_animation(app)
1782 }
1783 }
1784 }
1785 }
1786 })
1787 .into_widget()
1788 }
1789}
1790
1791pub struct CircularProgressIndicatorState {
1793 state: StateData<CircularProgressIndicator>,
1794 single_ticker_provider: SingleTickerProviderStateMixinData,
1795 circular_state: CircularProgressIndicatorStateData,
1796}
1797
1798impl CircularProgressIndicatorStateBase for CircularProgressIndicatorState {
1799 fn circular_state_data(self: Handle<Self>, app: &App) -> &CircularProgressIndicatorStateData {
1800 &app.get(self).circular_state
1801 }
1802
1803 fn circular_state_data_mut(
1804 self: Handle<Self>,
1805 app: &mut App,
1806 ) -> &mut CircularProgressIndicatorStateData {
1807 &mut app.get_mut(self).circular_state
1808 }
1809
1810 fn circular_widget(self: Handle<Self>, app: &App) -> &CircularProgressIndicator {
1811 self.widget(app)
1812 }
1813}
1814
1815impl SingleTickerProviderStateMixin for CircularProgressIndicatorState {
1816 fn single_ticker_provider_data(
1817 self: Handle<Self>,
1818 app: &App,
1819 ) -> &SingleTickerProviderStateMixinData {
1820 &app.get(self).single_ticker_provider
1821 }
1822
1823 fn single_ticker_provider_data_mut(
1824 self: Handle<Self>,
1825 app: &mut App,
1826 ) -> &mut SingleTickerProviderStateMixinData {
1827 &mut app.get_mut(self).single_ticker_provider
1828 }
1829}
1830
1831impl TickerProviderObject for CircularProgressIndicatorState {
1833 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1834 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1835 }
1836}
1837
1838impl State for CircularProgressIndicatorState {
1839 type Widget = CircularProgressIndicator;
1840 waft_widgets::state_accessors!();
1841
1842 fn init_state(self: Handle<Self>, app: &mut App) {
1843 CircularProgressIndicatorStateBase::init_state(self, app);
1844 }
1845
1846 fn did_update_widget(
1847 self: Handle<Self>,
1848 app: &mut App,
1849 _old_widget: &CircularProgressIndicator,
1850 ) {
1851 CircularProgressIndicatorStateBase::did_update_widget(self, app);
1852 }
1853
1854 fn activate(self: Handle<Self>, app: &mut App) {
1855 SingleTickerProviderStateMixin::activate(self, app);
1856 }
1857
1858 fn dispose(self: Handle<Self>, app: &mut App) {
1859 CircularProgressIndicatorStateBase::dispose(self, app);
1860 }
1861
1862 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1863 CircularProgressIndicatorStateBase::build(self, app, context)
1864 }
1865}
1866
1867#[derive(Debug)]
1869struct RefreshProgressIndicatorPainter {
1870 circular: CircularProgressIndicatorPainter,
1871 arrowhead_scale: f64,
1872}
1873
1874impl RefreshProgressIndicatorPainter {
1875 fn paint_arrowhead(&self, canvas: &mut Canvas, size: Size) {
1876 let circular = &self.circular;
1877 let arc_end = circular.arc_start + circular.arc_sweep;
1880 let ux = arc_end.cos();
1881 let uy = arc_end.sin();
1882
1883 debug_assert_eq!(size.width(), size.height());
1884 let radius = size.width() / 2.0;
1885 let arrowhead_point_x =
1886 radius + ux * radius + -uy * circular.stroke_width * 2.0 * self.arrowhead_scale;
1887 let arrowhead_point_y =
1888 radius + uy * radius + ux * circular.stroke_width * 2.0 * self.arrowhead_scale;
1889 let arrowhead_radius = circular.stroke_width * 2.0 * self.arrowhead_scale;
1890 let inner_radius = radius - arrowhead_radius;
1891 let outer_radius = radius + arrowhead_radius;
1892
1893 let mut path = PathBuilder::new();
1894 path.move_to((
1895 (radius + ux * inner_radius) as f32,
1896 (radius + uy * inner_radius) as f32,
1897 ))
1898 .line_to((
1899 (radius + ux * outer_radius) as f32,
1900 (radius + uy * outer_radius) as f32,
1901 ))
1902 .line_to((arrowhead_point_x as f32, arrowhead_point_y as f32))
1903 .close();
1904
1905 let paint = Paint::from_color(circular.value_color.into());
1906 canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
1907 }
1908}
1909
1910impl CustomPainter for RefreshProgressIndicatorPainter {
1911 fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1912 self.circular.paint(app, canvas, size);
1913 if self.arrowhead_scale > 0.0 {
1914 self.paint_arrowhead(canvas, size);
1915 }
1916 }
1917
1918 fn should_repaint(&self, app: &App, old_painter: &dyn CustomPainter) -> bool {
1919 let old_painter = old_painter
1920 .as_any()
1921 .downcast_ref::<RefreshProgressIndicatorPainter>()
1922 .expect("Dart's covariant parameter");
1923 self.circular.should_repaint(app, &old_painter.circular)
1924 }
1925
1926 fn as_any(&self) -> &dyn Any {
1927 self
1928 }
1929}
1930
1931#[derive(Debug)]
1945pub struct RefreshProgressIndicator {
1946 pub circular_progress_indicator: CircularProgressIndicator,
1953
1954 pub elevation: f64,
1956
1957 pub indicator_margin: EdgeInsetsGeometry,
1960
1961 pub indicator_padding: EdgeInsetsGeometry,
1963}
1964
1965impl RefreshProgressIndicator {
1966 pub const DEFAULT_STROKE_WIDTH: f64 = 2.5;
1968
1969 pub fn new() -> RefreshProgressIndicator {
1978 RefreshProgressIndicator {
1979 circular_progress_indicator: CircularProgressIndicator::new()
1981 .stroke_width(RefreshProgressIndicator::DEFAULT_STROKE_WIDTH),
1982 elevation: 2.0,
1983 indicator_margin: EdgeInsets::all(4.0).into(),
1984 indicator_padding: EdgeInsets::all(12.0).into(),
1985 }
1986 }
1987
1988 progress_indicator_setters!(
1989 RefreshProgressIndicator,
1990 circular_progress_indicator.progress_indicator
1991 );
1992
1993 pub fn value(mut self, value: f64) -> RefreshProgressIndicator {
1995 self.circular_progress_indicator = self.circular_progress_indicator.value(value);
1996 self
1997 }
1998
1999 pub fn stroke_width(mut self, stroke_width: f64) -> RefreshProgressIndicator {
2001 self.circular_progress_indicator =
2002 self.circular_progress_indicator.stroke_width(stroke_width);
2003 self
2004 }
2005
2006 pub fn stroke_align(mut self, stroke_align: f64) -> RefreshProgressIndicator {
2008 self.circular_progress_indicator =
2009 self.circular_progress_indicator.stroke_align(stroke_align);
2010 self
2011 }
2012
2013 pub fn stroke_cap(mut self, stroke_cap: StrokeCap) -> RefreshProgressIndicator {
2015 self.circular_progress_indicator = self.circular_progress_indicator.stroke_cap(stroke_cap);
2016 self
2017 }
2018
2019 pub fn elevation(mut self, elevation: f64) -> RefreshProgressIndicator {
2021 self.elevation = elevation;
2022 self
2023 }
2024
2025 pub fn indicator_margin(
2027 mut self,
2028 indicator_margin: impl Into<EdgeInsetsGeometry>,
2029 ) -> RefreshProgressIndicator {
2030 self.indicator_margin = indicator_margin.into();
2031 self
2032 }
2033
2034 pub fn indicator_padding(
2036 mut self,
2037 indicator_padding: impl Into<EdgeInsetsGeometry>,
2038 ) -> RefreshProgressIndicator {
2039 self.indicator_padding = indicator_padding.into();
2040 self
2041 }
2042}
2043
2044impl Default for RefreshProgressIndicator {
2045 fn default() -> RefreshProgressIndicator {
2046 RefreshProgressIndicator::new()
2047 }
2048}
2049
2050impl ProgressIndicator for RefreshProgressIndicator {
2051 fn progress_indicator_data(&self) -> &ProgressIndicatorData {
2052 &self.circular_progress_indicator.progress_indicator
2053 }
2054}
2055
2056impl StatefulWidget for RefreshProgressIndicator {
2057 type State = RefreshProgressIndicatorState;
2058
2059 fn key(&self) -> Option<&KeyRef> {
2060 self.circular_progress_indicator
2061 .progress_indicator
2062 .key
2063 .as_ref()
2064 }
2065
2066 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2067 self.progress_indicator_data()
2068 .debug_fill_properties(properties);
2069 }
2070
2071 fn create_state(&self) -> RefreshProgressIndicatorState {
2072 RefreshProgressIndicatorState {
2073 state: StateData::new(),
2074 single_ticker_provider: SingleTickerProviderStateMixinData::default(),
2075 circular_state: CircularProgressIndicatorStateData::default(),
2076 convert_tween: ValueCurveTween::new(Rc::new(Interval::new(
2077 0.1,
2078 RefreshProgressIndicatorState::STROKE_HEAD_INTERVAL,
2079 Curves::linear(),
2080 ))),
2081 additional_rotation_tween: TweenSequence::new(vec![
2082 TweenSequenceItem::new(
2084 Rc::new(ValueTween::new(-0.1, -0.2)),
2085 RefreshProgressIndicatorState::STROKE_HEAD_INTERVAL,
2086 ),
2087 TweenSequenceItem::new(
2089 Rc::new(ValueTween::new(-0.2, 1.35)),
2090 1.0 - RefreshProgressIndicatorState::STROKE_HEAD_INTERVAL,
2091 ),
2092 ]),
2093 last_value: None,
2094 }
2095 }
2096}
2097
2098pub struct RefreshProgressIndicatorState {
2101 state: StateData<RefreshProgressIndicator>,
2102 single_ticker_provider: SingleTickerProviderStateMixinData,
2103 circular_state: CircularProgressIndicatorStateData,
2104 convert_tween: ValueCurveTween,
2105 additional_rotation_tween: TweenSequence<f64>,
2106 last_value: Option<f64>,
2108}
2109
2110impl RefreshProgressIndicatorState {
2111 const INDICATOR_SIZE: f64 = 41.0;
2112
2113 const STROKE_HEAD_INTERVAL: f64 = 0.33;
2115}
2116
2117impl CircularProgressIndicatorStateBase for RefreshProgressIndicatorState {
2118 fn circular_state_data(self: Handle<Self>, app: &App) -> &CircularProgressIndicatorStateData {
2119 &app.get(self).circular_state
2120 }
2121
2122 fn circular_state_data_mut(
2123 self: Handle<Self>,
2124 app: &mut App,
2125 ) -> &mut CircularProgressIndicatorStateData {
2126 &mut app.get_mut(self).circular_state
2127 }
2128
2129 fn circular_widget(self: Handle<Self>, app: &App) -> &CircularProgressIndicator {
2130 &self.widget(app).circular_progress_indicator
2131 }
2132
2133 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2140 let value = self
2141 .circular_widget(app)
2142 .progress_indicator
2143 .effective_value();
2144 if let Some(value) = value {
2145 app.get_mut(self).last_value = Some(value);
2146 let converted = app.get(self).convert_tween.transform(app, value);
2147 self.controller(app).set_value(
2148 app,
2149 converted * (1333.0 / 2.0 / K_INDETERMINATE_CIRCULAR_DURATION as f64),
2150 );
2151 }
2152 CircularProgressIndicatorStateBase::build_animation(self, app)
2153 }
2154
2155 fn build_animation(self: Handle<Self>, app: &mut App) -> WidgetRef {
2156 AnimatedBuilder::new(
2157 Rc::new(self.controller(app).erase::<AnyAnimation<f64>>()),
2158 move |app, context, _child| {
2159 let value = self.controller(app).value(app);
2160 self.build_material_indicator(
2161 app,
2162 context,
2163 1.05 * stroke_head_tween().transform(app, value),
2165 stroke_tail_tween().transform(app, value),
2166 offset_tween().transform(app, value),
2167 rotation_tween().transform(app, value),
2168 )
2169 },
2170 )
2171 .into_widget()
2172 }
2173
2174 fn build_material_indicator(
2175 self: Handle<Self>,
2176 app: &mut App,
2177 context: BuildContext,
2178 head_value: f64,
2179 tail_value: f64,
2180 offset_value: f64,
2181 rotation_value: f64,
2182 ) -> WidgetRef {
2183 let value = self
2184 .circular_widget(app)
2185 .progress_indicator
2186 .effective_value();
2187 let arrowhead_scale = match value {
2188 None => 0.0,
2189 Some(value) => Interval::new(
2190 0.1,
2191 RefreshProgressIndicatorState::STROKE_HEAD_INTERVAL,
2192 Curves::linear(),
2193 )
2194 .transform(value),
2195 };
2196 let last_value = app.get(self).last_value;
2197 let rotation = if value.is_none() && last_value.is_none() {
2198 0.0
2199 } else {
2200 PI * app.get(self).additional_rotation_tween.transform(
2201 app,
2202 value.unwrap_or_else(|| last_value.expect("checked above")),
2203 )
2204 };
2205
2206 let widget = self.circular_widget(app);
2207 let color = widget.effective_color();
2208 let progress_indicator = widget.progress_indicator.clone();
2209 let value_color = progress_indicator.get_value_color(app, context, color, None);
2210 let opacity = value_color.opacity();
2211 let value_color = value_color.with_opacity(1.0);
2212
2213 let defaults: Box<dyn ProgressIndicatorThemeDataGetters> =
2214 if Theme::of(app, context).use_material3 {
2215 Box::new(CircularProgressIndicatorDefaultsM3Year2023::new(
2216 context,
2217 value.is_none(),
2218 ))
2219 } else {
2220 Box::new(CircularProgressIndicatorDefaultsM2::new(
2221 context,
2222 value.is_none(),
2223 ))
2224 };
2225 let indicator_theme = ProgressIndicatorTheme::of(app, context);
2226 let background_color = match progress_indicator
2227 .background_color
2228 .or(indicator_theme.refresh_background_color)
2229 {
2230 Some(background_color) => background_color,
2231 None => Theme::of(app, context).canvas_color,
2232 };
2233 let circular = self.circular_widget(app).clone();
2234 let stroke_width = circular
2235 .stroke_width
2236 .or(indicator_theme.stroke_width)
2237 .or_else(|| defaults.stroke_width(app))
2238 .expect("the defaults give a stroke width");
2239 let stroke_align = circular
2240 .stroke_align
2241 .or(indicator_theme.stroke_align)
2242 .or_else(|| defaults.stroke_align(app))
2243 .expect("the defaults give a stroke alignment");
2244 let stroke_cap = circular.stroke_cap.or(indicator_theme.stroke_cap);
2245 let widget = self.widget(app);
2246
2247 progress_indicator.build_semantics_wrapper(
2248 context,
2249 Padding::new(widget.indicator_margin).child(
2250 SizedBox::from_size(Some(Size::square(
2251 RefreshProgressIndicatorState::INDICATOR_SIZE,
2252 )))
2253 .child(
2254 Material::new()
2255 .r#type(MaterialType::Circle)
2256 .color(background_color)
2257 .elevation(widget.elevation)
2258 .child(Padding::new(widget.indicator_padding).child(
2259 Opacity::new(opacity).child(Transform::rotate(rotation).child(
2260 CustomPaint::new().painter(RefreshProgressIndicatorPainter {
2261 circular: CircularProgressIndicatorPainter::new(
2262 None,
2263 value_color,
2264 None,
2266 head_value,
2267 tail_value,
2268 offset_value,
2269 rotation_value,
2270 stroke_width,
2271 stroke_align,
2272 stroke_cap,
2273 None,
2274 true,
2275 ),
2276 arrowhead_scale,
2277 }),
2278 )),
2279 )),
2280 ),
2281 ),
2282 )
2283 }
2284}
2285
2286impl SingleTickerProviderStateMixin for RefreshProgressIndicatorState {
2287 fn single_ticker_provider_data(
2288 self: Handle<Self>,
2289 app: &App,
2290 ) -> &SingleTickerProviderStateMixinData {
2291 &app.get(self).single_ticker_provider
2292 }
2293
2294 fn single_ticker_provider_data_mut(
2295 self: Handle<Self>,
2296 app: &mut App,
2297 ) -> &mut SingleTickerProviderStateMixinData {
2298 &mut app.get_mut(self).single_ticker_provider
2299 }
2300}
2301
2302impl TickerProviderObject for RefreshProgressIndicatorState {
2304 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2305 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2306 }
2307}
2308
2309impl State for RefreshProgressIndicatorState {
2310 type Widget = RefreshProgressIndicator;
2311 waft_widgets::state_accessors!();
2312
2313 fn init_state(self: Handle<Self>, app: &mut App) {
2314 CircularProgressIndicatorStateBase::init_state(self, app);
2315 }
2316
2317 fn did_update_widget(
2318 self: Handle<Self>,
2319 app: &mut App,
2320 _old_widget: &RefreshProgressIndicator,
2321 ) {
2322 CircularProgressIndicatorStateBase::did_update_widget(self, app);
2323 }
2324
2325 fn activate(self: Handle<Self>, app: &mut App) {
2326 SingleTickerProviderStateMixin::activate(self, app);
2327 }
2328
2329 fn dispose(self: Handle<Self>, app: &mut App) {
2330 CircularProgressIndicatorStateBase::dispose(self, app);
2331 }
2332
2333 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2334 CircularProgressIndicatorStateBase::build(self, app, context)
2335 }
2336}
2337
2338struct CircularProgressIndicatorDefaultsM2 {
2341 progress_indicator_theme_data: ProgressIndicatorThemeData,
2343 context: DefaultsContext,
2344 #[expect(
2346 dead_code,
2347 reason = "Dart's constructor argument, which no getter of this class reads"
2348 )]
2349 indeterminate: bool,
2350}
2351
2352impl CircularProgressIndicatorDefaultsM2 {
2353 fn new(context: BuildContext, indeterminate: bool) -> CircularProgressIndicatorDefaultsM2 {
2354 CircularProgressIndicatorDefaultsM2 {
2355 progress_indicator_theme_data: ProgressIndicatorThemeData::new(),
2356 context: DefaultsContext::new(context),
2357 indeterminate,
2358 }
2359 }
2360}
2361
2362impl ProgressIndicatorThemeDataGetters for CircularProgressIndicatorDefaultsM2 {
2363 fn progress_indicator_theme_data(&self) -> &ProgressIndicatorThemeData {
2364 &self.progress_indicator_theme_data
2365 }
2366
2367 fn color(&self, app: &mut App) -> Option<Color> {
2368 Some(self.context.colors(app).primary())
2369 }
2370
2371 fn stroke_width(&self, _app: &mut App) -> Option<f64> {
2372 Some(4.0)
2373 }
2374
2375 fn stroke_align(&self, _app: &mut App) -> Option<f64> {
2376 Some(CircularProgressIndicator::STROKE_ALIGN_CENTER)
2377 }
2378
2379 fn constraints(&self, _app: &mut App) -> Option<BoxConstraints> {
2380 Some(BoxConstraints::new().min_width(36.0).min_height(36.0))
2381 }
2382}
2383
2384struct LinearProgressIndicatorDefaultsM2 {
2386 progress_indicator_theme_data: ProgressIndicatorThemeData,
2388 context: DefaultsContext,
2389}
2390
2391impl LinearProgressIndicatorDefaultsM2 {
2392 fn new(context: BuildContext) -> LinearProgressIndicatorDefaultsM2 {
2393 LinearProgressIndicatorDefaultsM2 {
2394 progress_indicator_theme_data: ProgressIndicatorThemeData::new(),
2395 context: DefaultsContext::new(context),
2396 }
2397 }
2398}
2399
2400impl ProgressIndicatorThemeDataGetters for LinearProgressIndicatorDefaultsM2 {
2401 fn progress_indicator_theme_data(&self) -> &ProgressIndicatorThemeData {
2402 &self.progress_indicator_theme_data
2403 }
2404
2405 fn color(&self, app: &mut App) -> Option<Color> {
2406 Some(self.context.colors(app).primary())
2407 }
2408
2409 fn linear_track_color(&self, app: &mut App) -> Option<Color> {
2410 Some(self.context.colors(app).background())
2411 }
2412
2413 fn linear_min_height(&self, _app: &mut App) -> Option<f64> {
2414 Some(4.0)
2415 }
2416}
2417
2418struct CircularProgressIndicatorDefaultsM3Year2023 {
2420 progress_indicator_theme_data: ProgressIndicatorThemeData,
2422 context: DefaultsContext,
2423 #[expect(
2425 dead_code,
2426 reason = "Dart's constructor argument, which no getter of this class reads"
2427 )]
2428 indeterminate: bool,
2429}
2430
2431impl CircularProgressIndicatorDefaultsM3Year2023 {
2432 fn new(
2433 context: BuildContext,
2434 indeterminate: bool,
2435 ) -> CircularProgressIndicatorDefaultsM3Year2023 {
2436 CircularProgressIndicatorDefaultsM3Year2023 {
2437 progress_indicator_theme_data: ProgressIndicatorThemeData::new(),
2438 context: DefaultsContext::new(context),
2439 indeterminate,
2440 }
2441 }
2442}
2443
2444impl ProgressIndicatorThemeDataGetters for CircularProgressIndicatorDefaultsM3Year2023 {
2445 fn progress_indicator_theme_data(&self) -> &ProgressIndicatorThemeData {
2446 &self.progress_indicator_theme_data
2447 }
2448
2449 fn color(&self, app: &mut App) -> Option<Color> {
2450 Some(self.context.colors(app).primary())
2451 }
2452
2453 fn stroke_width(&self, _app: &mut App) -> Option<f64> {
2454 Some(4.0)
2455 }
2456
2457 fn stroke_align(&self, _app: &mut App) -> Option<f64> {
2458 Some(CircularProgressIndicator::STROKE_ALIGN_CENTER)
2459 }
2460
2461 fn constraints(&self, _app: &mut App) -> Option<BoxConstraints> {
2462 Some(BoxConstraints::new().min_width(36.0).min_height(36.0))
2463 }
2464}
2465
2466struct LinearProgressIndicatorDefaultsM3Year2023 {
2468 progress_indicator_theme_data: ProgressIndicatorThemeData,
2470 context: DefaultsContext,
2471}
2472
2473impl LinearProgressIndicatorDefaultsM3Year2023 {
2474 fn new(context: BuildContext) -> LinearProgressIndicatorDefaultsM3Year2023 {
2475 LinearProgressIndicatorDefaultsM3Year2023 {
2476 progress_indicator_theme_data: ProgressIndicatorThemeData::new(),
2477 context: DefaultsContext::new(context),
2478 }
2479 }
2480}
2481
2482impl ProgressIndicatorThemeDataGetters for LinearProgressIndicatorDefaultsM3Year2023 {
2483 fn progress_indicator_theme_data(&self) -> &ProgressIndicatorThemeData {
2484 &self.progress_indicator_theme_data
2485 }
2486
2487 fn color(&self, app: &mut App) -> Option<Color> {
2488 Some(self.context.colors(app).primary())
2489 }
2490
2491 fn linear_track_color(&self, app: &mut App) -> Option<Color> {
2492 Some(self.context.colors(app).secondary_container())
2493 }
2494
2495 fn linear_min_height(&self, _app: &mut App) -> Option<f64> {
2496 Some(4.0)
2497 }
2498}
2499
2500#[cfg(test)]
2501pub(crate) mod tests {
2502 use waft_animation::AlwaysStoppedAnimation;
2505 use waft_embedder::valo::{self, Op};
2506 use waft_embedder::{RRect, Radius};
2507 use waft_painting::BorderRadius;
2508 use waft_rendering::{
2509 AnyRenderObject, RenderBox, RenderCustomPaint, RenderHandle, RenderObject,
2510 };
2511 use waft_scheduler::SchedulerBinding;
2512 use waft_widgets::{AnyElement, Center, InheritedTheme, TickerMode, downcast_widget};
2513
2514 use waft_widgets::testing::{
2515 TargetPlatformVariant, WidgetTester, expect, find, finds_one_widget, test_widgets,
2516 test_widgets_variant,
2517 };
2518
2519 use super::*;
2520 use crate::app::MaterialApp;
2521 use crate::color_scheme::ColorScheme;
2522 use crate::colors::Colors;
2523 use crate::scaffold::Scaffold;
2524 use crate::theme_data::ThemeData;
2525 use waft_widgets::testing::TestVSync;
2526
2527 pub(crate) fn pump_with(tester: &mut WidgetTester, build: impl FnOnce(&mut App) -> WidgetRef) {
2529 let root = build(&mut tester.cell.borrow_mut());
2530 tester.pump_widget(root);
2531 }
2532
2533 pub(crate) fn theme(app: &App) -> ThemeData {
2535 ThemeData::new(app)
2536 }
2537
2538 pub(crate) fn theme_with(app: &App, data: ProgressIndicatorThemeData) -> ThemeData {
2540 ThemeData::builder()
2541 .progress_indicator_theme(data)
2542 .build(app)
2543 }
2544
2545 pub(crate) fn themed<K>(theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
2546 Theme::new(theme, child).into_widget()
2547 }
2548
2549 pub(crate) fn directional<K>(direction: TextDirection, child: impl IntoWidget<K>) -> WidgetRef {
2550 Directionality::new(direction, child).into_widget()
2551 }
2552
2553 pub(crate) fn centered_width<K>(width: f64, child: impl IntoWidget<K>) -> WidgetRef {
2555 Center::new()
2556 .child(SizedBox::new().width(width).child(child))
2557 .into_widget()
2558 }
2559
2560 pub(crate) fn scaffold_app<K>(theme: Option<ThemeData>, body: impl IntoWidget<K>) -> WidgetRef {
2562 let app = MaterialApp::new().home(Scaffold::new().body(body));
2563 match theme {
2564 Some(theme) => app.theme(theme),
2565 None => app,
2566 }
2567 .into_widget()
2568 }
2569
2570 fn transient_callback_count(tester: &WidgetTester) -> usize {
2571 SchedulerBinding::transient_callback_count(&mut tester.cell.borrow_mut())
2572 }
2573
2574 fn find_render<T: RenderObject>(
2576 app: &App,
2577 node: AnyRenderObject,
2578 accept: &dyn Fn(RenderHandle<T>) -> bool,
2579 ) -> Option<RenderHandle<T>> {
2580 if let Some(found) = node.downcast::<T>(app)
2581 && accept(found)
2582 {
2583 return Some(found);
2584 }
2585 let mut found = None;
2586 node.visit_children(app, &mut |child| {
2587 if found.is_none() {
2588 found = find_render(app, child, accept);
2589 }
2590 });
2591 found
2592 }
2593
2594 pub(crate) fn first<W: 'static>(tester: &WidgetTester) -> AnyElement {
2596 *find::by_type::<W>()
2597 .evaluate(tester)
2598 .first()
2599 .expect("a widget of that type")
2600 }
2601
2602 pub(crate) fn painter_under<W: 'static>(
2604 tester: &WidgetTester,
2605 ) -> (Rc<dyn CustomPainter>, Size) {
2606 let element = first::<W>(tester);
2607 let app = tester.cell.borrow();
2608 let root = element
2609 .find_render_object(&app)
2610 .expect("the widget has a render object");
2611 let custom = find_render(&app, root, &|custom: RenderHandle<RenderCustomPaint>| {
2612 custom.painter(&app).is_some()
2613 })
2614 .expect("a CustomPaint with a painter under it");
2615 (custom.painter(&app).expect("a painter"), custom.size(&app))
2616 }
2617
2618 pub(crate) fn painted_by<W: 'static>(tester: &WidgetTester) -> Vec<Op> {
2621 let (painter, size) = painter_under::<W>(tester);
2622 let mut canvas = Canvas::new();
2623 painter.paint(&mut tester.cell.borrow_mut(), &mut canvas, size);
2624 canvas.build().ops().to_vec()
2625 }
2626
2627 pub(crate) fn active_arc_of<W: 'static>(tester: &WidgetTester) -> (f64, f64) {
2630 let (painter, _) = painter_under::<W>(tester);
2631 let painter = painter.as_any();
2632 let circular = painter
2633 .downcast_ref::<CircularProgressIndicatorPainter>()
2634 .or_else(|| {
2635 painter
2636 .downcast_ref::<RefreshProgressIndicatorPainter>()
2637 .map(|refresh| &refresh.circular)
2638 })
2639 .expect("a circular indicator's painter");
2640 (circular.arc_start, circular.arc_sweep)
2641 }
2642
2643 pub(crate) fn arc_count(ops: &[Op]) -> usize {
2645 ops.iter()
2646 .filter(|op| {
2647 matches!(op, Op::DrawPath { paint, .. } if matches!(paint.style, PaintStyle::Stroke(_)))
2648 })
2649 .count()
2650 }
2651
2652 #[derive(Clone, Copy, Debug, Default, PartialEq)]
2653 enum Kind {
2654 #[default]
2655 Rect,
2656 RRect,
2657 Circle,
2658 Arc,
2659 }
2660
2661 #[derive(Clone, Copy, Debug, Default)]
2663 pub(crate) struct Expect {
2664 kind: Kind,
2665 rect: Option<Rect>,
2666 rrect: Option<RRect>,
2667 center: Option<Offset>,
2668 radius: Option<f64>,
2669 color: Option<Color>,
2670 stroke_width: Option<f64>,
2671 stroke_cap: Option<StrokeCap>,
2672 }
2673
2674 pub(crate) fn rect(rect: Rect) -> Expect {
2676 Expect {
2677 kind: Kind::Rect,
2678 rect: Some(rect),
2679 ..Expect::default()
2680 }
2681 }
2682
2683 pub(crate) fn rrect(rrect: RRect) -> Expect {
2685 Expect {
2686 kind: Kind::RRect,
2687 rrect: Some(rrect),
2688 ..Expect::default()
2689 }
2690 }
2691
2692 pub(crate) fn circle() -> Expect {
2694 Expect {
2695 kind: Kind::Circle,
2696 ..Expect::default()
2697 }
2698 }
2699
2700 pub(crate) fn arc() -> Expect {
2702 Expect {
2703 kind: Kind::Arc,
2704 ..Expect::default()
2705 }
2706 }
2707
2708 impl Expect {
2709 pub(crate) fn color(mut self, color: Color) -> Expect {
2710 self.color = Some(color);
2711 self
2712 }
2713
2714 pub(crate) fn at(mut self, x: f64, y: f64) -> Expect {
2716 self.center = Some(Offset::new(x, y));
2717 self
2718 }
2719
2720 pub(crate) fn radius(mut self, radius: f64) -> Expect {
2722 self.radius = Some(radius);
2723 self
2724 }
2725
2726 pub(crate) fn in_rect(mut self, rect: Rect) -> Expect {
2728 self.rect = Some(rect);
2729 self
2730 }
2731
2732 pub(crate) fn stroke_width(mut self, stroke_width: f64) -> Expect {
2733 self.stroke_width = Some(stroke_width);
2734 self
2735 }
2736
2737 pub(crate) fn stroke_cap(mut self, stroke_cap: StrokeCap) -> Expect {
2738 self.stroke_cap = Some(stroke_cap);
2739 self
2740 }
2741
2742 fn matches(&self, op: &Op) -> bool {
2743 let paint = match op {
2744 Op::DrawRect { paint, .. } | Op::DrawPath { paint, .. } => paint,
2745 _ => return false,
2746 };
2747 if self
2748 .color
2749 .is_some_and(|color| paint.color != valo::Color::from(color))
2750 {
2751 return false;
2752 }
2753 match self.kind {
2754 Kind::Rect => matches!(
2755 op,
2756 Op::DrawRect { rect, .. }
2757 if Some(*rect) == self.rect.map(valo::Rect::from)
2758 ),
2759 Kind::RRect => same_geometry(op, &rrect_op(self.rrect.expect("an rrect"))),
2760 Kind::Circle => self.matches_circle(op),
2761 Kind::Arc => self.matches_arc(op),
2762 }
2763 }
2764
2765 fn matches_circle(&self, op: &Op) -> bool {
2766 let Op::DrawPath { path, .. } = op else {
2767 return false;
2768 };
2769 let Some(oval) = path.as_oval() else {
2770 return false;
2771 };
2772 let radius = f64::from(oval.width) / 2.0;
2773 let center = Offset::new(
2774 f64::from(oval.x) + radius,
2775 f64::from(oval.y) + f64::from(oval.height) / 2.0,
2776 );
2777 self.center.is_none_or(|expected| {
2778 close(center.dx(), expected.dx()) && close(center.dy(), expected.dy())
2779 }) && self.radius.is_none_or(|expected| close(radius, expected))
2780 }
2781
2782 fn matches_arc(&self, op: &Op) -> bool {
2783 let Op::DrawPath { path, paint, .. } = op else {
2784 return false;
2785 };
2786 let PaintStyle::Stroke(stroke) = &paint.style else {
2787 return false;
2788 };
2789 self.stroke_width
2790 .is_none_or(|width| stroke.width == width as f32)
2791 && self.stroke_cap.is_none_or(|cap| stroke.cap == cap)
2792 && self.rect.is_none_or(|rect| on_oval_of(path, rect))
2793 }
2794 }
2795
2796 fn close(a: f64, b: f64) -> bool {
2797 (a - b).abs() < 1e-4
2798 }
2799
2800 fn rrect_op(rrect: RRect) -> Op {
2802 let mut canvas = Canvas::new();
2803 draw_rrect(&mut canvas, rrect, &Paint::default());
2804 canvas.build().ops()[0].clone()
2805 }
2806
2807 fn same_geometry(a: &Op, b: &Op) -> bool {
2808 match (a, b) {
2809 (Op::DrawRect { rect: a, .. }, Op::DrawRect { rect: b, .. }) => a == b,
2810 (Op::DrawPath { path: a, .. }, Op::DrawPath { path: b, .. }) => **a == **b,
2811 _ => false,
2812 }
2813 }
2814
2815 fn on_oval_of(path: &valo::Path, rect: Rect) -> bool {
2818 let center = rect.center();
2819 let (radius_x, radius_y) = (rect.width() / 2.0, rect.height() / 2.0);
2820 let contours = path.measure(0.01);
2821 !contours.is_empty()
2822 && contours.iter().all(|contour| {
2823 (0..=10).all(|step| {
2824 let point = contour
2825 .sample(contour.length() * step as f32 / 10.0)
2826 .position;
2827 let x = (f64::from(point.x) - center.dx()) / radius_x;
2828 let y = (f64::from(point.y) - center.dy()) / radius_y;
2829 (x * x + y * y - 1.0).abs() < 1e-3
2830 })
2831 })
2832 }
2833
2834 pub(crate) fn paints(ops: &[Op], expected: &[Expect]) -> bool {
2836 let mut ops = ops.iter();
2837 expected
2838 .iter()
2839 .all(|expect| ops.any(|op| expect.matches(op)))
2840 }
2841
2842 pub(crate) fn descendants<W: 'static, D: 'static>(tester: &WidgetTester) -> Vec<AnyElement> {
2845 let of = first::<W>(tester);
2846 find::by_type::<D>()
2847 .evaluate(tester)
2848 .into_iter()
2849 .filter(|element| tester.ancestors(*element).contains(&of))
2850 .collect()
2851 }
2852
2853 pub(crate) fn controller_at(tester: &WidgetTester, value: f64) -> Ref<AnimationController> {
2854 AnimationController::new(
2855 &mut tester.cell.borrow_mut(),
2856 Some(value),
2857 None,
2858 None,
2859 0.0,
2860 1.0,
2861 AnimationBehavior::Normal,
2862 TestVSync,
2863 )
2864 }
2865
2866 fn always(app: &mut App, color: Option<Color>) -> AnimationRef<Option<Color>> {
2867 app.create(AlwaysStoppedAnimation::new(color))
2868 .into_erased::<AnyAnimation<Option<Color>>>()
2869 }
2870
2871 #[test]
2872 fn linear_progress_indicator_custom_min_height() {
2873 test_widgets(|tester| {
2874 pump_with(tester, |app| {
2875 themed(
2876 theme(app),
2877 directional(
2878 TextDirection::Ltr,
2879 centered_width(
2880 200.0,
2881 LinearProgressIndicator::new().value(0.25).min_height(2.0),
2882 ),
2883 ),
2884 )
2885 });
2886 let expected = [
2887 rect(Rect::from_ltrb(0.0, 0.0, 200.0, 2.0)),
2888 rect(Rect::from_ltrb(0.0, 0.0, 50.0, 2.0)),
2889 ];
2890 assert!(paints(
2891 &painted_by::<LinearProgressIndicator>(tester),
2892 &expected
2893 ));
2894
2895 pump_with(tester, |app| {
2897 themed(
2898 theme_with(
2899 app,
2900 ProgressIndicatorThemeData::new().linear_min_height(2.0),
2901 ),
2902 directional(
2903 TextDirection::Ltr,
2904 centered_width(200.0, LinearProgressIndicator::new().value(0.25)),
2905 ),
2906 )
2907 });
2908 assert!(paints(
2909 &painted_by::<LinearProgressIndicator>(tester),
2910 &expected
2911 ));
2912 });
2913 }
2914
2915 fn pump_linear(
2916 tester: &mut WidgetTester,
2917 direction: TextDirection,
2918 indicator: LinearProgressIndicator,
2919 ) {
2920 pump_with(tester, |app| {
2921 themed(
2922 theme(app),
2923 directional(direction, centered_width(200.0, indicator)),
2924 )
2925 });
2926 }
2927
2928 #[test]
2929 fn linear_progress_indicator_paint_ltr() {
2930 test_widgets(|tester| {
2931 pump_linear(
2932 tester,
2933 TextDirection::Ltr,
2934 LinearProgressIndicator::new().value(0.25),
2935 );
2936 assert!(paints(
2937 &painted_by::<LinearProgressIndicator>(tester),
2938 &[
2939 rect(Rect::from_ltrb(0.0, 0.0, 200.0, 4.0)),
2940 rect(Rect::from_ltrb(0.0, 0.0, 50.0, 4.0)),
2941 ]
2942 ));
2943 assert_eq!(transient_callback_count(tester), 0);
2944 });
2945 }
2946
2947 #[test]
2948 fn linear_progress_indicator_paint_rtl() {
2949 test_widgets(|tester| {
2950 pump_linear(
2951 tester,
2952 TextDirection::Rtl,
2953 LinearProgressIndicator::new().value(0.25),
2954 );
2955 assert!(paints(
2956 &painted_by::<LinearProgressIndicator>(tester),
2957 &[
2958 rect(Rect::from_ltrb(0.0, 0.0, 200.0, 4.0)),
2959 rect(Rect::from_ltrb(150.0, 0.0, 200.0, 4.0)),
2960 ]
2961 ));
2962 assert_eq!(transient_callback_count(tester), 0);
2963 });
2964 }
2965
2966 fn line1_head_at_300ms() -> f64 {
2967 Interval::new(0.0, 750.0 / 1800.0, Rc::new(Cubic::new(0.2, 0.0, 0.8, 1.0)))
2968 .transform(300.0 / 1800.0)
2969 }
2970
2971 #[test]
2972 fn linear_progress_indicator_indeterminate_ltr() {
2973 test_widgets(|tester| {
2974 pump_linear(tester, TextDirection::Ltr, LinearProgressIndicator::new());
2975 tester.pump_by(Duration::from_millis(300));
2976 let animation_value = line1_head_at_300ms();
2977 assert!(paints(
2978 &painted_by::<LinearProgressIndicator>(tester),
2979 &[
2980 rect(Rect::from_ltrb(animation_value * 200.0, 0.0, 200.0, 4.0)),
2982 rect(Rect::from_ltrb(0.0, 0.0, animation_value * 200.0, 4.0)),
2984 ]
2985 ));
2986 assert_eq!(transient_callback_count(tester), 1);
2987 });
2988 }
2989
2990 #[test]
2991 fn linear_progress_indicator_indeterminate_rtl() {
2992 test_widgets(|tester| {
2993 pump_linear(tester, TextDirection::Rtl, LinearProgressIndicator::new());
2994 tester.pump_by(Duration::from_millis(300));
2995 let animation_value = line1_head_at_300ms();
2996 assert!(paints(
2997 &painted_by::<LinearProgressIndicator>(tester),
2998 &[
2999 rect(Rect::from_ltrb(
3000 0.0,
3001 0.0,
3002 200.0 - animation_value * 200.0,
3003 4.0
3004 )),
3005 rect(Rect::from_ltrb(
3006 200.0 - animation_value * 200.0,
3007 0.0,
3008 200.0,
3009 4.0
3010 )),
3011 ]
3012 ));
3013 assert_eq!(transient_callback_count(tester), 1);
3014 });
3015 }
3016
3017 #[test]
3018 fn linear_progress_indicator_with_colors() {
3019 test_widgets(|tester| {
3020 let default_theme = theme(&tester.cell.borrow());
3021 let track = Rect::from_ltrb(0.0, 0.0, 200.0, 4.0);
3022 let active = Rect::from_ltrb(0.0, 0.0, 50.0, 4.0);
3023 pump_with(tester, |_app| {
3024 MaterialApp::new()
3025 .home(centered_width(
3026 200.0,
3027 LinearProgressIndicator::new().value(0.25),
3028 ))
3029 .into_widget()
3030 });
3031
3032 assert!(paints(
3034 &painted_by::<LinearProgressIndicator>(tester),
3035 &[
3036 rect(track).color(default_theme.color_scheme.secondary_container()),
3037 rect(active).color(default_theme.color_scheme.primary()),
3038 ]
3039 ));
3040
3041 pump_with(tester, |app| {
3043 let value_color = always(app, Some(Colors::WHITE));
3044 themed(
3045 theme(app),
3046 directional(
3047 TextDirection::Ltr,
3048 centered_width(
3049 200.0,
3050 LinearProgressIndicator::new()
3051 .value(0.25)
3052 .background_color(Colors::BLACK)
3053 .color(Colors::BLUE.primary())
3054 .value_color(value_color.clone()),
3055 ),
3056 ),
3057 )
3058 });
3059
3060 assert!(paints(
3062 &painted_by::<LinearProgressIndicator>(tester),
3063 &[rect(track), rect(active).color(Colors::WHITE)]
3064 ));
3065
3066 pump_with(tester, |app| {
3068 themed(
3069 theme(app),
3070 directional(
3071 TextDirection::Ltr,
3072 centered_width(
3073 200.0,
3074 LinearProgressIndicator::new()
3075 .value(0.25)
3076 .background_color(Colors::BLACK)
3077 .color(Colors::WHITE12),
3078 ),
3079 ),
3080 )
3081 });
3082
3083 assert!(paints(
3085 &painted_by::<LinearProgressIndicator>(tester),
3086 &[rect(track), rect(active).color(Colors::WHITE12)]
3087 ));
3088
3089 let primary_color = Color::new(0xff008800);
3091 pump_with(tester, |app| {
3092 let color_scheme = ColorScheme::from_swatch()
3093 .build()
3094 .copy_with()
3095 .with_primary(primary_color);
3096 themed(
3097 theme(app).copy_with().color_scheme(color_scheme).build(),
3098 directional(
3099 TextDirection::Ltr,
3100 centered_width(
3101 200.0,
3102 LinearProgressIndicator::new()
3103 .value(0.25)
3104 .background_color(Colors::BLACK),
3105 ),
3106 ),
3107 )
3108 });
3109
3110 assert!(paints(
3112 &painted_by::<LinearProgressIndicator>(tester),
3113 &[rect(track), rect(active).color(primary_color)]
3114 ));
3115
3116 let indicator_color = Color::new(0xff0000ff);
3118 pump_with(tester, |app| {
3119 themed(
3120 theme_with(
3121 app,
3122 ProgressIndicatorThemeData::new()
3123 .color(indicator_color)
3124 .linear_track_color(Colors::BLACK),
3125 ),
3126 directional(
3127 TextDirection::Ltr,
3128 centered_width(200.0, LinearProgressIndicator::new().value(0.25)),
3129 ),
3130 )
3131 });
3132
3133 assert!(paints(
3135 &painted_by::<LinearProgressIndicator>(tester),
3136 &[rect(track), rect(active).color(indicator_color)]
3137 ));
3138 });
3139 }
3140
3141 #[test]
3142 fn linear_progress_indicator_with_animation_with_null_colors() {
3143 test_widgets(|tester| {
3144 pump_with(tester, |app| {
3145 let value_color = always(app, None);
3146 themed(
3147 theme(app),
3148 directional(
3149 TextDirection::Ltr,
3150 centered_width(
3151 200.0,
3152 LinearProgressIndicator::new()
3153 .value(0.25)
3154 .value_color(value_color.clone())
3155 .background_color(Colors::BLACK),
3156 ),
3157 ),
3158 )
3159 });
3160 assert!(paints(
3161 &painted_by::<LinearProgressIndicator>(tester),
3162 &[
3163 rect(Rect::from_ltrb(0.0, 0.0, 200.0, 4.0)),
3164 rect(Rect::from_ltrb(0.0, 0.0, 50.0, 4.0)),
3165 ]
3166 ));
3167 });
3168 }
3169
3170 #[test]
3171 fn circular_progress_indicator_stroke_width() {
3172 test_widgets(|tester| {
3173 pump_with(tester, |app| {
3174 themed(theme(app), CircularProgressIndicator::new())
3175 });
3176 assert!(paints(
3177 &painted_by::<CircularProgressIndicator>(tester),
3178 &[arc().stroke_width(4.0)]
3179 ));
3180
3181 pump_with(tester, |app| {
3182 themed(
3183 theme(app),
3184 CircularProgressIndicator::new().stroke_width(16.0),
3185 )
3186 });
3187 assert!(paints(
3188 &painted_by::<CircularProgressIndicator>(tester),
3189 &[arc().stroke_width(16.0)]
3190 ));
3191 });
3192 }
3193
3194 #[test]
3195 fn circular_progress_indicator_adaptive_stroke_width() {
3196 test_widgets(|tester| {
3197 tester.pump_widget(CircularProgressIndicator::adaptive().into_widget());
3198
3199 assert!(paints(
3201 &painted_by::<CircularProgressIndicator>(tester),
3202 &[arc().stroke_width(4.0)]
3203 ));
3204
3205 let theme_data =
3206 |app: &App| theme_with(app, ProgressIndicatorThemeData::new().stroke_width(10.0));
3207 pump_with(tester, |app| {
3208 themed(theme_data(app), CircularProgressIndicator::adaptive())
3209 });
3210
3211 assert!(paints(
3213 &painted_by::<CircularProgressIndicator>(tester),
3214 &[arc().stroke_width(10.0)]
3215 ));
3216
3217 pump_with(tester, |app| {
3218 themed(
3219 theme_data(app),
3220 CircularProgressIndicator::adaptive().stroke_width(16.0),
3221 )
3222 });
3223
3224 assert!(paints(
3226 &painted_by::<CircularProgressIndicator>(tester),
3227 &[arc().stroke_width(16.0)]
3228 ));
3229 });
3230 }
3231
3232 #[test]
3233 fn circular_progress_indicator_stroke_align() {
3234 test_widgets(|tester| {
3235 let cases = [
3236 (None, Offset::ZERO & Size::new(800.0, 600.0)),
3237 (
3238 Some(CircularProgressIndicator::STROKE_ALIGN_INSIDE),
3239 Offset::new(2.0, 2.0) & Size::new(796.0, 596.0),
3240 ),
3241 (
3242 Some(CircularProgressIndicator::STROKE_ALIGN_OUTSIDE),
3243 Offset::new(-2.0, -2.0) & Size::new(804.0, 604.0),
3244 ),
3245 (Some(2.0), Offset::new(-4.0, -4.0) & Size::new(808.0, 608.0)),
3247 ];
3248 for (stroke_align, expected) in cases {
3249 pump_with(tester, |app| {
3250 let indicator = CircularProgressIndicator::new();
3251 let indicator = match stroke_align {
3252 Some(stroke_align) => indicator.stroke_align(stroke_align),
3253 None => indicator,
3254 };
3255 themed(theme(app), indicator)
3256 });
3257 assert!(paints(
3258 &painted_by::<CircularProgressIndicator>(tester),
3259 &[arc().in_rect(expected)]
3260 ));
3261 }
3262 });
3263 }
3264
3265 #[test]
3266 fn circular_progress_indicator_with_stroke_cap() {
3267 test_widgets(|tester| {
3268 tester.pump_widget(CircularProgressIndicator::new().into_widget());
3269 assert!(
3270 paints(
3271 &painted_by::<CircularProgressIndicator>(tester),
3272 &[arc().stroke_cap(StrokeCap::Square)]
3273 ),
3274 "Default indeterminate strokeCap is StrokeCap.square."
3275 );
3276
3277 tester.pump_widget(directional(
3278 TextDirection::Ltr,
3279 CircularProgressIndicator::new().value(0.5),
3280 ));
3281 assert!(
3282 paints(
3283 &painted_by::<CircularProgressIndicator>(tester),
3284 &[arc().stroke_cap(StrokeCap::Butt)]
3285 ),
3286 "Default determinate strokeCap is StrokeCap.butt."
3287 );
3288
3289 tester.pump_widget(
3290 CircularProgressIndicator::new()
3291 .stroke_cap(StrokeCap::Butt)
3292 .into_widget(),
3293 );
3294 assert!(
3295 paints(
3296 &painted_by::<CircularProgressIndicator>(tester),
3297 &[arc().stroke_cap(StrokeCap::Butt)]
3298 ),
3299 "strokeCap can be set to StrokeCap.butt, and will not be overridden."
3300 );
3301
3302 tester.pump_widget(
3303 CircularProgressIndicator::new()
3304 .stroke_cap(StrokeCap::Round)
3305 .into_widget(),
3306 );
3307 assert!(paints(
3308 &painted_by::<CircularProgressIndicator>(tester),
3309 &[arc().stroke_cap(StrokeCap::Round)]
3310 ));
3311 });
3312 }
3313
3314 #[test]
3315 fn linear_progress_indicator_with_indicator_border_radius() {
3316 test_widgets(|tester| {
3317 pump_with(tester, |app| {
3318 themed(
3319 theme(app),
3320 directional(
3321 TextDirection::Ltr,
3322 Center::new().child(
3323 SizedBox::new().width(100.0).height(4.0).child(
3324 LinearProgressIndicator::new()
3325 .value(0.25)
3326 .border_radius(BorderRadius::all(Radius::circular(10.0))),
3327 ),
3328 ),
3329 ),
3330 )
3331 });
3332 assert!(paints(
3333 &painted_by::<LinearProgressIndicator>(tester),
3334 &[
3335 rrect(RRect::from_ltrbr(
3336 0.0,
3337 0.0,
3338 100.0,
3339 4.0,
3340 Radius::circular(10.0)
3341 )),
3342 rrect(RRect::from_rect_and_radius(
3343 Rect::from_ltrb(0.0, 0.0, 25.0, 4.0),
3344 Radius::circular(10.0),
3345 )),
3346 ]
3347 ));
3348 assert_eq!(transient_callback_count(tester), 0);
3349 });
3350 }
3351
3352 #[test]
3353 fn linear_progress_indicator_reflects_controller_value() {
3354 test_widgets(|tester| {
3355 let controller = controller_at(tester, 0.5);
3356 pump_with(tester, |_app| {
3357 MaterialApp::new()
3358 .home(Material::new().child(centered_width(
3359 200.0,
3360 LinearProgressIndicator::new().controller(controller.clone()),
3361 )))
3362 .into_widget()
3363 });
3364 assert!(paints(
3365 &painted_by::<LinearProgressIndicator>(tester),
3366 &[rect(Rect::from_ltrb(127.79541015625, 0.0, 200.0, 4.0))]
3367 ));
3368 controller.dispose(&mut tester.cell.borrow_mut());
3369 });
3370 }
3371
3372 #[test]
3373 fn circular_progress_indicator_paint_colors() {
3374 test_widgets(|tester| {
3375 let green = Color::new(0xFF00FF00);
3376 let blue = Color::new(0xFF0000FF);
3377 let red = Color::new(0xFFFF0000);
3378
3379 pump_with(tester, |app| {
3381 let value_color = always(app, Some(blue));
3382 themed(
3383 theme(app),
3384 CircularProgressIndicator::new()
3385 .color(red)
3386 .value_color(value_color.clone()),
3387 )
3388 });
3389 let ops = painted_by::<CircularProgressIndicator>(tester);
3390 assert_eq!(arc_count(&ops), 1);
3391 assert!(paints(&ops, &[arc().color(blue)]));
3392
3393 pump_with(tester, |app| {
3395 themed(theme(app), CircularProgressIndicator::new().color(red))
3396 });
3397 let ops = painted_by::<CircularProgressIndicator>(tester);
3398 assert_eq!(arc_count(&ops), 1);
3399 assert!(paints(&ops, &[arc().color(red)]));
3400
3401 pump_with(tester, |app| {
3403 let color_scheme = ColorScheme::from_swatch()
3404 .build()
3405 .copy_with()
3406 .with_primary(green);
3407 themed(
3408 theme(app).copy_with().color_scheme(color_scheme).build(),
3409 CircularProgressIndicator::new(),
3410 )
3411 });
3412 let ops = painted_by::<CircularProgressIndicator>(tester);
3413 assert_eq!(arc_count(&ops), 1);
3414 assert!(paints(&ops, &[arc().color(green)]));
3415
3416 pump_with(tester, |app| {
3418 themed(
3419 theme(app),
3420 CircularProgressIndicator::new()
3421 .background_color(green)
3422 .color(blue),
3423 )
3424 });
3425 let ops = painted_by::<CircularProgressIndicator>(tester);
3426 assert_eq!(arc_count(&ops), 2);
3427 assert!(paints(&ops, &[arc().color(green), arc().color(blue)]));
3428
3429 pump_with(tester, |app| {
3431 themed(
3432 theme_with(
3433 app,
3434 ProgressIndicatorThemeData::new()
3435 .color(green)
3436 .circular_track_color(blue),
3437 ),
3438 CircularProgressIndicator::new(),
3439 )
3440 });
3441 let ops = painted_by::<CircularProgressIndicator>(tester);
3442 assert_eq!(arc_count(&ops), 2);
3443 assert!(paints(&ops, &[arc().color(blue), arc().color(green)]));
3444 });
3445 }
3446
3447 fn refresh_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
3449 let material = descendants::<RefreshProgressIndicator, Material>(tester)[0];
3450 tester.widget(material, read)
3451 }
3452
3453 #[test]
3454 fn refresh_progress_indicator_paint_colors() {
3455 test_widgets(|tester| {
3456 let green = Color::new(0xFF00FF00);
3457 let blue = Color::new(0xFF0000FF);
3458 let red = Color::new(0xFFFF0000);
3459
3460 pump_with(tester, |app| {
3462 let value_color = always(app, Some(blue));
3463 themed(
3464 theme(app),
3465 RefreshProgressIndicator::new()
3466 .color(red)
3467 .value_color(value_color.clone()),
3468 )
3469 });
3470 let ops = painted_by::<RefreshProgressIndicator>(tester);
3471 assert_eq!(arc_count(&ops), 1);
3472 assert!(paints(&ops, &[arc().color(blue)]));
3473
3474 pump_with(tester, |app| {
3476 themed(theme(app), RefreshProgressIndicator::new().color(red))
3477 });
3478 let ops = painted_by::<RefreshProgressIndicator>(tester);
3479 assert_eq!(arc_count(&ops), 1);
3480 assert!(paints(&ops, &[arc().color(red)]));
3481
3482 pump_with(tester, |app| {
3484 let color_scheme = ColorScheme::from_swatch()
3485 .build()
3486 .copy_with()
3487 .with_primary(green);
3488 themed(
3489 theme(app).copy_with().color_scheme(color_scheme).build(),
3490 RefreshProgressIndicator::new(),
3491 )
3492 });
3493 let ops = painted_by::<RefreshProgressIndicator>(tester);
3494 assert_eq!(arc_count(&ops), 1);
3495 assert!(paints(&ops, &[arc().color(green)]));
3496
3497 pump_with(tester, |app| {
3499 themed(
3500 theme(app),
3501 RefreshProgressIndicator::new()
3502 .color(blue)
3503 .background_color(green),
3504 )
3505 });
3506 let ops = painted_by::<RefreshProgressIndicator>(tester);
3507 assert_eq!(arc_count(&ops), 1);
3508 assert!(paints(&ops, &[arc().color(blue)]));
3509 refresh_material(tester, |material| {
3510 assert_eq!(material.r#type, MaterialType::Circle);
3511 assert_eq!(material.color, Some(green));
3512 });
3513
3514 pump_with(tester, |app| {
3516 themed(
3517 theme_with(
3518 app,
3519 ProgressIndicatorThemeData::new()
3520 .color(green)
3521 .refresh_background_color(blue),
3522 ),
3523 RefreshProgressIndicator::new(),
3524 )
3525 });
3526 let ops = painted_by::<RefreshProgressIndicator>(tester);
3527 assert_eq!(arc_count(&ops), 1);
3528 assert!(paints(&ops, &[arc().color(green)]));
3529 refresh_material(tester, |material| {
3530 assert_eq!(material.r#type, MaterialType::Circle);
3531 assert_eq!(material.color, Some(blue));
3532 });
3533 });
3534 }
3535
3536 #[test]
3537 fn refresh_progress_indicator_with_a_round_indicator() {
3538 test_widgets(|tester| {
3539 tester.pump_widget(RefreshProgressIndicator::new().into_widget());
3540 assert!(
3541 paints(
3542 &painted_by::<RefreshProgressIndicator>(tester),
3543 &[arc().stroke_cap(StrokeCap::Square)]
3544 ),
3545 "Default indeterminate strokeCap is StrokeCap.square"
3546 );
3547
3548 pump_with(tester, |app| {
3549 themed(
3550 theme(app),
3551 directional(
3552 TextDirection::Ltr,
3553 centered_width(
3554 200.0,
3555 RefreshProgressIndicator::new().stroke_cap(StrokeCap::Round),
3556 ),
3557 ),
3558 )
3559 });
3560 assert!(paints(
3561 &painted_by::<RefreshProgressIndicator>(tester),
3562 &[arc().stroke_cap(StrokeCap::Round)]
3563 ));
3564 });
3565 }
3566
3567 #[test]
3568 fn indeterminate_refresh_progress_indicator_keeps_spinning_until_end_of_time_approximate() {
3569 test_widgets(|tester| {
3571 pump_with(tester, |app| {
3572 themed(
3573 theme(app),
3574 directional(
3575 TextDirection::Ltr,
3576 centered_width(200.0, RefreshProgressIndicator::new()),
3577 ),
3578 )
3579 });
3580 assert!(transient_callback_count(tester) > 0);
3581
3582 tester.pump_by(Duration::from_secs(5));
3583 assert!(transient_callback_count(tester) > 0);
3584
3585 tester.pump_by(Duration::from_millis(1));
3586 assert!(transient_callback_count(tester) > 0);
3587
3588 tester.pump_by(Duration::from_secs(9999 * 24 * 60 * 60));
3589 assert!(transient_callback_count(tester) > 0);
3590 });
3591 }
3592
3593 #[test]
3594 fn determinate_circular_progress_indicator_stops_the_animator() {
3595 test_widgets(|tester| {
3596 let pump_value = |tester: &mut WidgetTester, progress_value: Option<f64>| {
3597 pump_with(tester, |app| {
3598 let indicator = CircularProgressIndicator::new();
3599 let indicator = match progress_value {
3600 Some(value) => indicator.value(value),
3601 None => indicator,
3602 };
3603 themed(
3604 theme(app),
3605 directional(TextDirection::Ltr, Center::new().child(indicator)),
3606 )
3607 });
3608 };
3609 pump_value(tester, None);
3610 assert!(transient_callback_count(tester) > 0);
3611
3612 pump_value(tester, Some(1.0));
3613 tester.pump_by(Duration::from_millis(1));
3614 assert_eq!(transient_callback_count(tester), 0);
3615
3616 pump_value(tester, None);
3617 tester.pump_by(Duration::from_millis(1));
3618 assert!(transient_callback_count(tester) > 0);
3619 });
3620 }
3621
3622 #[test]
3623 fn an_indeterminate_indicator_stops_ticking_while_its_ticker_mode_is_off() {
3624 test_widgets(|tester| {
3625 let pump_enabled = |tester: &mut WidgetTester, enabled: bool| {
3626 pump_with(tester, |app| {
3627 themed(
3628 theme(app),
3629 TickerMode::new(
3630 enabled,
3631 Center::new().child(CircularProgressIndicator::new()),
3632 ),
3633 )
3634 });
3635 };
3636 pump_enabled(tester, false);
3637 assert_eq!(transient_callback_count(tester), 0);
3638 let before = active_arc_of::<CircularProgressIndicator>(tester);
3639 tester.pump_by(Duration::from_millis(500));
3640 assert_eq!(active_arc_of::<CircularProgressIndicator>(tester), before);
3641
3642 pump_enabled(tester, true);
3643 assert_eq!(transient_callback_count(tester), 1);
3644 });
3645 }
3646
3647 #[test]
3648 fn linear_progress_indicator_with_height_12_0() {
3649 test_widgets(|tester| {
3650 for (height, painted) in [(12.0, 12.0), (3.0, 3.0), (4.0, 4.0)] {
3651 pump_with(tester, |app| {
3652 themed(
3653 theme(app),
3654 directional(
3655 TextDirection::Ltr,
3656 Center::new().child(
3657 SizedBox::new()
3658 .width(100.0)
3659 .height(height)
3660 .child(LinearProgressIndicator::new().value(0.25)),
3661 ),
3662 ),
3663 )
3664 });
3665 assert!(paints(
3666 &painted_by::<LinearProgressIndicator>(tester),
3667 &[
3668 rect(Rect::from_ltrb(0.0, 0.0, 100.0, painted)),
3669 rect(Rect::from_ltrb(0.0, 0.0, 25.0, painted)),
3670 ]
3671 ));
3672 assert_eq!(transient_callback_count(tester), 0);
3673 }
3674 });
3675 }
3676
3677 fn pump_adaptive(tester: &mut WidgetTester, indicator: CircularProgressIndicator) {
3678 pump_with(tester, |app| {
3679 scaffold_app(Some(theme(app)), Material::new().child(indicator))
3680 });
3681 }
3682
3683 const APPLE: [TargetPlatform; 2] = [TargetPlatform::IOS, TargetPlatform::MacOS];
3684
3685 #[test]
3686 fn adaptive_circular_progress_indicator_displays_cupertino_activity_indicator_in_ios() {
3687 test_widgets(|_| {
3688 for platform in APPLE {
3689 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3690 pump_adaptive(tester, CircularProgressIndicator::adaptive());
3691 expect(
3692 tester,
3693 &find::by_type::<CupertinoActivityIndicator>(),
3694 finds_one_widget(),
3695 );
3696 });
3697 }
3698 });
3699 }
3700
3701 #[test]
3702 fn adaptive_circular_progress_indicator_displays_cupertino_activity_indicator_in_ios_macos() {
3703 test_widgets(|_| {
3704 for platform in APPLE {
3705 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3706 pump_adaptive(tester, CircularProgressIndicator::adaptive().value(0.5));
3707 let indicators = find::by_type::<CupertinoActivityIndicator>().evaluate(tester);
3708 assert_eq!(indicators.len(), 1);
3709 let actual_progress = tester
3710 .widget(indicators[0], |indicator: &CupertinoActivityIndicator| {
3711 indicator.progress
3712 });
3713 assert_eq!(actual_progress, 0.5);
3714 });
3715 }
3716 });
3717 }
3718
3719 #[test]
3720 fn adaptive_circular_progress_indicator_can_use_background_color_to_change_tick_color_for_ios()
3721 {
3722 test_widgets(|_| {
3723 for platform in APPLE {
3724 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3725 let color = Color::new(0xFF5D3FD3);
3726 pump_adaptive(
3727 tester,
3728 CircularProgressIndicator::adaptive().background_color(color),
3729 );
3730 assert!(paints(
3731 &painted_by::<CupertinoActivityIndicator>(tester),
3732 &[
3733 rrect(RRect::from_ltrbxy(-1.0, -10.0 / 3.0, 1.0, -10.0, 1.0, 1.0))
3734 .color(color.with_alpha(47))
3737 ]
3738 ));
3739 });
3740 }
3741 });
3742 }
3743
3744 #[test]
3745 fn adaptive_circular_progress_indicator_does_not_display_cupertino_activity_indicator_in_non_ios()
3746 {
3747 test_widgets(|_| {
3748 for platform in [
3749 TargetPlatform::Android,
3750 TargetPlatform::Fuchsia,
3751 TargetPlatform::Windows,
3752 TargetPlatform::Linux,
3753 ] {
3754 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
3755 pump_adaptive(tester, CircularProgressIndicator::adaptive());
3756 assert!(
3757 find::by_type::<CupertinoActivityIndicator>()
3758 .evaluate(tester)
3759 .is_empty()
3760 );
3761 });
3762 }
3763 });
3764 }
3765
3766 #[test]
3767 fn progress_indicator_theme_wrap_always_creates_a_new_progress_indicator_theme() {
3768 test_widgets(|tester| {
3769 let theme_data = ProgressIndicatorThemeData::new()
3770 .color(Color::new(0xFFFF0000))
3771 .linear_track_color(Color::new(0xFF00FF00));
3772 let builder_context = Rc::new(std::cell::Cell::new(None));
3773 pump_with(tester, |app| {
3774 let builder_context = Rc::clone(&builder_context);
3775 MaterialApp::new()
3776 .home(themed(
3777 theme(app),
3778 ProgressIndicatorTheme::new(
3779 theme_data.clone(),
3780 Builder::new(move |_app, context| {
3781 builder_context.set(Some(context));
3782 LinearProgressIndicator::new().value(0.5).into_widget()
3783 }),
3784 ),
3785 ))
3786 .into_widget()
3787 });
3788 let progress_theme = first::<ProgressIndicatorTheme>(tester);
3789 let wrapped_theme = {
3790 let mut app = tester.cell.borrow_mut();
3791 let widget = progress_theme.widget(&app).clone();
3792 let progress_theme =
3793 downcast_widget::<ProgressIndicatorTheme>(&*widget).expect("found by type");
3794 progress_theme.wrap(
3795 &mut app,
3796 builder_context.get().expect("the builder ran"),
3797 SizedBox::new().into_widget(),
3798 )
3799 };
3800
3801 let app = tester.cell.borrow();
3804 assert!(!Rc::ptr_eq(&wrapped_theme, progress_theme.widget(&app)));
3805 let wrapped = downcast_widget::<ProgressIndicatorTheme>(&*wrapped_theme)
3806 .expect("a ProgressIndicatorTheme");
3807 assert_eq!(wrapped.data, theme_data);
3808 });
3809 }
3810
3811 #[test]
3812 fn material3_default_size_of_circular_progress_indicator() {
3813 test_widgets(|tester| {
3814 pump_with(tester, |_app| {
3815 scaffold_app(
3816 None,
3817 Material::new().child(CircularProgressIndicator::new()),
3818 )
3819 });
3820 let indicator = first::<CircularProgressIndicator>(tester);
3821 assert_eq!(tester.get_size(indicator), Size::new(36.0, 36.0));
3822 });
3823 }
3824
3825 #[test]
3826 fn material3_default_size_of_circular_progress_indicator_when_year2023_is_false() {
3827 test_widgets(|tester| {
3828 pump_with(tester, |_app| {
3829 scaffold_app(
3830 None,
3831 Material::new().child(CircularProgressIndicator::new().year2023(false)),
3832 )
3833 });
3834 let indicator = first::<CircularProgressIndicator>(tester);
3835 assert_eq!(tester.get_size(indicator), Size::new(48.0, 48.0));
3836 });
3837 }
3838
3839 #[test]
3840 fn refresh_progress_indicator_using_fields_correctly() {
3841 test_widgets(|tester| {
3842 let fields = |tester: &WidgetTester| {
3843 let material = descendants::<RefreshProgressIndicator, Material>(tester)[0];
3844 let elevation = tester.widget(material, |material: &Material| material.elevation);
3845 let padding = descendants::<RefreshProgressIndicator, Padding>(tester)[0];
3846 let padding = tester.widget(padding, |padding: &Padding| padding.padding);
3847 let inner_padding = *descendants::<Material, Padding>(tester)
3848 .last()
3849 .expect("a Padding in the Material");
3850 let inner_padding =
3851 tester.widget(inner_padding, |padding: &Padding| padding.padding);
3852 (elevation, padding, inner_padding)
3853 };
3854
3855 pump_with(tester, |app| {
3857 themed(theme(app), RefreshProgressIndicator::new())
3858 });
3859 assert_eq!(
3860 fields(tester),
3861 (
3862 2.0,
3863 EdgeInsets::all(4.0).into(),
3864 EdgeInsets::all(12.0).into()
3865 )
3866 );
3867
3868 let test_elevation = 1.0;
3870 let test_indicator_margin: EdgeInsetsGeometry = EdgeInsets::all(6.0).into();
3871 let test_indicator_padding: EdgeInsetsGeometry = EdgeInsets::all(10.0).into();
3872 pump_with(tester, |app| {
3873 themed(
3874 theme(app),
3875 RefreshProgressIndicator::new()
3876 .elevation(test_elevation)
3877 .indicator_margin(test_indicator_margin)
3878 .indicator_padding(test_indicator_padding),
3879 )
3880 });
3881 assert_eq!(
3882 fields(tester),
3883 (
3884 test_elevation,
3885 test_indicator_margin,
3886 test_indicator_padding
3887 )
3888 );
3889 });
3890 }
3891
3892 fn pump_linear_2024(
3893 tester: &mut WidgetTester,
3894 direction: TextDirection,
3895 indicator: LinearProgressIndicator,
3896 ) {
3897 tester.pump_widget(directional(
3898 direction,
3899 centered_width(200.0, indicator.year2023(false)),
3900 ));
3901 }
3902
3903 #[test]
3904 fn linear_progress_indicator_default_stop_indicator_when_year2023_is_false() {
3905 test_widgets(|tester| {
3906 let primary = theme(&tester.cell.borrow()).color_scheme.primary();
3907 pump_linear_2024(
3908 tester,
3909 TextDirection::Ltr,
3910 LinearProgressIndicator::new().value(0.5),
3911 );
3912 assert!(paints(
3913 &painted_by::<LinearProgressIndicator>(tester),
3914 &[circle().at(198.0, 2.0).radius(2.0).color(primary)]
3915 ));
3916
3917 pump_linear_2024(
3918 tester,
3919 TextDirection::Rtl,
3920 LinearProgressIndicator::new().value(0.5),
3921 );
3922 assert!(paints(
3923 &painted_by::<LinearProgressIndicator>(tester),
3924 &[circle().at(2.0, 2.0).radius(2.0).color(primary)]
3925 ));
3926 });
3927 }
3928
3929 #[test]
3930 fn indeterminate_linear_progress_indicator_does_not_paint_stop_indicator() {
3931 test_widgets(|tester| {
3932 let primary = theme(&tester.cell.borrow()).color_scheme.primary();
3933 let stop_indicator = [circle().at(198.0, 2.0).radius(2.0).color(primary)];
3934
3935 pump_linear_2024(
3937 tester,
3938 TextDirection::Ltr,
3939 LinearProgressIndicator::new().value(0.5),
3940 );
3941 assert!(paints(
3942 &painted_by::<LinearProgressIndicator>(tester),
3943 &stop_indicator
3944 ));
3945
3946 pump_linear_2024(tester, TextDirection::Ltr, LinearProgressIndicator::new());
3948 assert!(!paints(
3949 &painted_by::<LinearProgressIndicator>(tester),
3950 &stop_indicator
3951 ));
3952 });
3953 }
3954
3955 #[test]
3956 fn can_customise_linear_progress_indicator_stop_indicator_when_year2023_is_false() {
3957 test_widgets(|tester| {
3958 let stop_indicator_color = Color::new(0xFF00FF00);
3959 let stop_indicator_radius = 5.0;
3960 let indicator = || LinearProgressIndicator::new().min_height(20.0).value(0.5);
3961
3962 pump_linear_2024(
3964 tester,
3965 TextDirection::Ltr,
3966 indicator()
3967 .stop_indicator_color(stop_indicator_color)
3968 .stop_indicator_radius(stop_indicator_radius),
3969 );
3970 assert!(paints(
3971 &painted_by::<LinearProgressIndicator>(tester),
3972 &[circle()
3973 .at(190.0, 10.0)
3974 .radius(stop_indicator_radius)
3975 .color(stop_indicator_color)]
3976 ));
3977
3978 pump_linear_2024(
3980 tester,
3981 TextDirection::Ltr,
3982 indicator().stop_indicator_radius(0.0),
3983 );
3984 assert!(!paints(
3985 &painted_by::<LinearProgressIndicator>(tester),
3986 &[circle().color(stop_indicator_color)]
3987 ));
3988
3989 pump_linear_2024(
3991 tester,
3992 TextDirection::Ltr,
3993 indicator().stop_indicator_color(Color::new(0x00000000)),
3994 );
3995 let (painter, _) = painter_under::<LinearProgressIndicator>(tester);
3998 let painter = painter
3999 .as_any()
4000 .downcast_ref::<LinearProgressIndicatorPainter>()
4001 .expect("a linear indicator's painter");
4002 assert_eq!(painter.stop_indicator_color, Some(Color::new(0x00000000)));
4003 assert!(
4004 painter
4005 .stop_indicator_radius
4006 .is_some_and(|stop_indicator_radius| stop_indicator_radius > 0.0)
4007 );
4008 assert!(!paints(
4009 &painted_by::<LinearProgressIndicator>(tester),
4010 &[circle()]
4011 ));
4012 });
4013 }
4014
4015 #[test]
4016 fn stop_indicator_size_cannot_be_larger_than_the_progress_indicator() {
4017 test_widgets(|tester| {
4018 let primary = theme(&tester.cell.borrow()).color_scheme.primary();
4019 for stop_indicator_radius in [10.0, 30.0] {
4022 pump_linear_2024(
4023 tester,
4024 TextDirection::Ltr,
4025 LinearProgressIndicator::new()
4026 .stop_indicator_radius(stop_indicator_radius)
4027 .min_height(20.0)
4028 .value(0.5),
4029 );
4030 assert!(paints(
4031 &painted_by::<LinearProgressIndicator>(tester),
4032 &[circle().at(190.0, 10.0).radius(10.0).color(primary)]
4033 ));
4034 }
4035 });
4036 }
4037
4038 #[test]
4039 fn linear_progress_indicator_default_track_gap_when_year2023_is_false() {
4040 test_widgets(|tester| {
4041 let colors = theme(&tester.cell.borrow()).color_scheme;
4042 let default_track_gap = 4.0;
4043 let radius = Radius::circular(2.0);
4044
4045 pump_linear_2024(
4047 tester,
4048 TextDirection::Ltr,
4049 LinearProgressIndicator::new().value(0.5),
4050 );
4051 assert!(paints(
4052 &painted_by::<LinearProgressIndicator>(tester),
4053 &[
4054 rrect(RRect::from_ltrbr(
4056 100.0 + default_track_gap,
4057 0.0,
4058 200.0,
4059 4.0,
4060 radius
4061 ))
4062 .color(colors.secondary_container()),
4063 rrect(RRect::from_ltrbr(0.0, 0.0, 100.0, 4.0, radius)).color(colors.primary()),
4065 ]
4066 ));
4067
4068 pump_linear_2024(
4070 tester,
4071 TextDirection::Rtl,
4072 LinearProgressIndicator::new().value(0.5),
4073 );
4074 assert!(paints(
4075 &painted_by::<LinearProgressIndicator>(tester),
4076 &[
4077 rrect(RRect::from_ltrbr(
4079 0.0,
4080 0.0,
4081 100.0 - default_track_gap,
4082 4.0,
4083 radius
4084 ))
4085 .color(colors.secondary_container()),
4086 rrect(RRect::from_ltrbr(100.0, 0.0, 200.0, 4.0, radius))
4088 .color(colors.primary()),
4089 ]
4090 ));
4091 });
4092 }
4093
4094 #[test]
4095 fn can_customise_linear_progress_indicator_track_gap_when_year2023_is_false() {
4096 test_widgets(|tester| {
4097 let colors = theme(&tester.cell.borrow()).color_scheme;
4098 let radius = Radius::circular(2.0);
4099 for (track_gap, track_left) in [(12.0, 100.0 + 12.0), (0.0, 0.0)] {
4100 pump_linear_2024(
4101 tester,
4102 TextDirection::Ltr,
4103 LinearProgressIndicator::new()
4104 .track_gap(track_gap)
4105 .value(0.5),
4106 );
4107 assert!(paints(
4108 &painted_by::<LinearProgressIndicator>(tester),
4109 &[
4110 rrect(RRect::from_ltrbr(track_left, 0.0, 200.0, 4.0, radius))
4112 .color(colors.secondary_container()),
4113 circle(),
4115 rrect(RRect::from_ltrbr(0.0, 0.0, 100.0, 4.0, radius))
4117 .color(colors.primary()),
4118 ]
4119 ));
4120 }
4121 });
4122 }
4123
4124 pub(crate) fn circular_sizes(tester: &WidgetTester) -> (Size, Size) {
4127 let indicator = first::<CircularProgressIndicator>(tester);
4128 let constrained_box = descendants::<CircularProgressIndicator, ConstrainedBox>(tester)[0];
4129 (tester.get_size(indicator), tester.get_size(constrained_box))
4130 }
4131
4132 pub(crate) fn padded(size: Size, padding: EdgeInsetsGeometry) -> Size {
4133 Size::new(
4134 size.width() + padding.horizontal(),
4135 size.height() + padding.vertical(),
4136 )
4137 }
4138
4139 #[test]
4140 fn default_determinate_circular_progress_indicator_when_year2023_is_false() {
4141 test_widgets(|tester| {
4142 let padding: EdgeInsetsGeometry = EdgeInsets::all(4.0).into();
4143 pump_with(tester, |app| {
4144 crate::test_support::material_app(
4145 theme(app),
4146 Center::new()
4147 .child(CircularProgressIndicator::new().year2023(false).value(0.5))
4148 .into_widget(),
4149 )
4150 });
4151 let colors = theme(&tester.cell.borrow()).color_scheme;
4152 let (indicator, indicator_box) = circular_sizes(tester);
4153 assert_eq!(indicator, padded(indicator_box, padding));
4154 let arc_rect = Rect::from_ltrb(2.0, 2.0, 38.0, 38.0);
4155 assert!(paints(
4156 &painted_by::<CircularProgressIndicator>(tester),
4157 &[
4158 arc()
4160 .in_rect(arc_rect)
4161 .color(colors.secondary_container())
4162 .stroke_width(4.0)
4163 .stroke_cap(StrokeCap::Round),
4164 arc()
4166 .in_rect(arc_rect)
4167 .color(colors.primary())
4168 .stroke_width(4.0)
4169 .stroke_cap(StrokeCap::Round),
4170 ]
4171 ));
4172 });
4173 }
4174
4175 #[test]
4176 fn default_indeterminate_circular_progress_indicator_when_year2023_is_false() {
4177 test_widgets(|tester| {
4178 let padding: EdgeInsetsGeometry = EdgeInsets::all(4.0).into();
4179 pump_with(tester, |app| {
4180 crate::test_support::material_app(
4181 theme(app),
4182 Center::new()
4183 .child(CircularProgressIndicator::new().year2023(false))
4184 .into_widget(),
4185 )
4186 });
4187
4188 tester.pump_by(Duration::from_millis(200));
4190
4191 let colors = theme(&tester.cell.borrow()).color_scheme;
4192 let (indicator, indicator_box) = circular_sizes(tester);
4193 assert_eq!(indicator, padded(indicator_box, padding));
4194 assert!(paints(
4195 &painted_by::<CircularProgressIndicator>(tester),
4196 &[
4197 arc()
4199 .in_rect(Rect::from_ltrb(2.0, 2.0, 38.0, 38.0))
4200 .color(colors.primary())
4201 .stroke_width(4.0)
4202 .stroke_cap(StrokeCap::Round),
4203 ]
4204 ));
4205 });
4206 }
4207
4208 #[test]
4209 fn can_override_circular_progress_indicator_stroke_cap_when_year2023_is_false() {
4210 test_widgets(|tester| {
4211 pump_with(tester, |_app| {
4212 MaterialApp::new()
4213 .home(
4214 Center::new().child(
4215 CircularProgressIndicator::new()
4216 .year2023(false)
4217 .stroke_cap(StrokeCap::Square)
4218 .value(0.5),
4219 ),
4220 )
4221 .into_widget()
4222 });
4223 assert!(paints(
4224 &painted_by::<CircularProgressIndicator>(tester),
4225 &[
4226 arc().stroke_cap(StrokeCap::Square),
4228 arc().stroke_cap(StrokeCap::Square),
4230 ]
4231 ));
4232 });
4233 }
4234
4235 #[test]
4236 fn circular_progress_indicator_constraints_can_override_default_size() {
4237 test_widgets(|tester| {
4238 let size = Size::new(64.0, 64.0);
4239 pump_with(tester, |_app| {
4240 MaterialApp::new()
4241 .home(
4242 Center::new().child(
4243 CircularProgressIndicator::new()
4244 .constraints(
4245 BoxConstraints::new()
4246 .min_width(size.width())
4247 .min_height(size.height()),
4248 )
4249 .value(0.5),
4250 ),
4251 )
4252 .into_widget()
4253 });
4254 let indicator = first::<CircularProgressIndicator>(tester);
4255 assert_eq!(tester.get_size(indicator), size);
4256 });
4257 }
4258
4259 #[test]
4260 fn circular_progress_indicator_padding_can_be_customized() {
4261 test_widgets(|tester| {
4262 let padding: EdgeInsetsGeometry = EdgeInsets::all(12.0).into();
4263 pump_with(tester, |_app| {
4264 MaterialApp::new()
4265 .home(
4266 Center::new().child(
4267 CircularProgressIndicator::new()
4268 .padding(padding)
4269 .year2023(false)
4270 .value(0.5),
4271 ),
4272 )
4273 .into_widget()
4274 });
4275 let (indicator, indicator_box) = circular_sizes(tester);
4276 assert_eq!(indicator, padded(indicator_box, padding));
4277 });
4278 }
4279
4280 #[test]
4281 fn circular_progress_indicator_reflects_controller_value() {
4282 test_widgets(|tester| {
4283 let controller = controller_at(tester, 0.5);
4284 pump_with(tester, |_app| {
4285 MaterialApp::new()
4286 .home(Material::new().child(Center::new().child(
4287 SizedBox::square(Some(200.0)).child(AnimatedBuilder::new(
4288 Rc::new(controller.erase::<AnyAnimation<f64>>()),
4289 {
4290 let controller = controller.clone();
4291 move |_app, _context, _child| {
4292 CircularProgressIndicator::new()
4293 .controller(controller.clone())
4294 .into_widget()
4295 }
4296 },
4297 )),
4298 )))
4299 .into_widget()
4300 });
4301 assert_eq!(
4302 active_arc_of::<CircularProgressIndicator>(tester),
4303 (std::f64::consts::FRAC_PI_2, 0.001)
4304 );
4305 controller.dispose(&mut tester.cell.borrow_mut());
4306 });
4307 }
4308
4309 #[test]
4310 fn indicators_do_not_crash_at_zero_area() {
4311 fn pump_shrunk(tester: &mut WidgetTester, indicator: WidgetRef) {
4312 pump_with(tester, |_app| {
4313 MaterialApp::new()
4314 .home(Center::new().child(SizedBox::shrink().child(indicator)))
4315 .into_widget()
4316 });
4317 }
4318 test_widgets(|tester| {
4319 pump_shrunk(tester, RefreshProgressIndicator::new().into_widget());
4320 let indicator = first::<RefreshProgressIndicator>(tester);
4321 assert_eq!(tester.get_size(indicator), Size::ZERO);
4322
4323 pump_shrunk(tester, CircularProgressIndicator::new().into_widget());
4324 let indicator = first::<CircularProgressIndicator>(tester);
4325 assert_eq!(tester.get_size(indicator), Size::ZERO);
4326
4327 pump_shrunk(tester, LinearProgressIndicator::new().into_widget());
4328 let indicator = first::<LinearProgressIndicator>(tester);
4329 assert_eq!(tester.get_size(indicator), Size::ZERO);
4330 });
4331 }
4332}