1use crate::{RangeBase, ThemeResources};
7use std::{f64::consts::TAU, time::Duration};
8use waft_animation::{Cubic, Curve};
9use waft_embedder::valo::{Cap, Point};
10use waft_embedder::{Canvas, Color, Paint, PaintStyle, PathBuilder, Size, Stroke};
11use waft_foundation::{App, Handle, OptionRetained, Ref};
12use waft_rendering::{BoxConstraints, CustomPainter};
13use waft_scheduler::{FrameCallback, Ticker};
14use waft_widgets::*;
15
16pub const PROGRESS_RING_DURATION: Duration = Duration::from_secs(2);
18
19pub const PROGRESS_RING_SIZE: f64 = 32.0;
21
22pub const PROGRESS_RING_MIN_SIZE: f64 = 16.0;
24
25pub const PROGRESS_RING_DEFAULT_MAXIMUM: f64 = 100.0;
27
28const DETERMINATE_RADIUS: f64 = 8.0 * 1.77 / 32.0;
31
32const DETERMINATE_STROKE: f64 = 1.5 * 1.77 / 32.0;
34
35const INDETERMINATE_RADIUS: f64 = 7.0 * 5.0 / 80.0;
38
39const INDETERMINATE_STROKE: f64 = 1.5 * 5.0 / 80.0;
41
42fn lottie_ease() -> Cubic {
44 Cubic::new(0.167, 0.167, 0.833, 0.833)
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49enum Easing {
50 Eased,
52 Held,
54}
55
56type KeyFrame = (f64, f64, Easing);
58
59fn key_frames(progress: f64, frames: &[KeyFrame]) -> f64 {
62 let (first, last) = (frames[0], frames[frames.len() - 1]);
63 if progress <= first.0 {
64 return first.1;
65 }
66 if progress >= last.0 {
67 return last.1;
68 }
69 let index = frames.iter().position(|frame| frame.0 > progress).unwrap();
70 let (from_progress, from_value, _) = frames[index - 1];
71 let (to_progress, to_value, easing) = frames[index];
72 match easing {
73 Easing::Held => from_value,
74 Easing::Eased => {
75 let span = (progress - from_progress) / (to_progress - from_progress);
76 from_value + (to_value - from_value) * lottie_ease().transform(span)
77 }
78 }
79}
80
81fn determinate_trim_end(progress: f64) -> f64 {
83 key_frames(
84 progress,
85 &[
86 (0.0, 0.0001, Easing::Held),
87 (0.00833333377, 0.0001, Easing::Held),
88 (0.25, 0.25, Easing::Eased),
89 (0.5, 0.5, Easing::Eased),
90 (0.75, 0.75, Easing::Eased),
91 (0.983333349, 0.96666666, Easing::Eased),
92 (0.991666675, 1.0, Easing::Eased),
93 ],
94 )
95}
96
97fn determinate_arc_is_shown(progress: f64) -> bool {
100 progress >= 0.00833333377
101}
102
103fn indeterminate_rotation(progress: f64) -> f64 {
105 key_frames(
106 progress,
107 &[
108 (0.0, 0.0, Easing::Held),
109 (0.5, 450.0, Easing::Eased),
110 (1.0, 900.0, Easing::Eased),
111 ],
112 ) / 360.0
113}
114
115fn indeterminate_growing_arc(progress: f64) -> (f64, f64) {
118 let end = key_frames(
119 progress,
120 &[(0.0, 0.0001, Easing::Held), (0.5, 0.5, Easing::Eased)],
121 );
122 (0.0, end)
123}
124
125fn indeterminate_shrinking_arc(progress: f64) -> (f64, f64) {
128 let start = key_frames(
129 progress,
130 &[
131 (0.0, 0.0, Easing::Held),
132 (0.5, 0.0, Easing::Held),
133 (1.0, 0.5, Easing::Eased),
134 ],
135 );
136 (start, 0.5)
137}
138
139#[derive(Clone, Debug)]
141pub struct ProgressRing {
142 pub minimum: f64,
144
145 pub maximum: f64,
147
148 pub value: f64,
150
151 pub is_active: bool,
153
154 pub is_indeterminate: bool,
156
157 pub foreground: Option<Color>,
159
160 pub background: Option<Color>,
162
163 pub key: Option<KeyRef>,
165}
166
167impl Default for ProgressRing {
168 fn default() -> Self {
169 Self {
170 minimum: 0.0,
171 maximum: PROGRESS_RING_DEFAULT_MAXIMUM,
172 value: 0.0,
173 is_active: true,
175 is_indeterminate: true,
176 foreground: None,
177 background: None,
178 key: None,
179 }
180 }
181}
182
183impl ProgressRing {
184 pub fn new() -> Self {
186 Self::default()
187 }
188
189 pub fn minimum(mut self, value: f64) -> Self {
191 self.minimum = value;
192 self
193 }
194
195 pub fn maximum(mut self, value: f64) -> Self {
197 self.maximum = value;
198 self
199 }
200
201 pub fn value(mut self, value: f64) -> Self {
203 self.value = value;
204 self
205 }
206
207 pub fn is_active(mut self, value: bool) -> Self {
209 self.is_active = value;
210 self
211 }
212
213 pub fn is_indeterminate(mut self, value: bool) -> Self {
215 self.is_indeterminate = value;
216 self
217 }
218
219 pub fn foreground(mut self, value: Color) -> Self {
221 self.foreground = Some(value);
222 self
223 }
224
225 pub fn background(mut self, value: Color) -> Self {
227 self.background = Some(value);
228 self
229 }
230
231 pub fn key(mut self, value: KeyRef) -> Self {
233 self.key = Some(value);
234 self
235 }
236
237 fn progress(&self) -> f64 {
239 let range = RangeBase::new(self.minimum, self.maximum, self.value).coerced();
240 let span = range.maximum - range.minimum;
241 if span == 0.0 {
242 0.0
243 } else {
244 (range.value - range.minimum) / span
245 }
246 }
247}
248
249pub struct ProgressRingState {
251 state: StateData<ProgressRing>,
253
254 single_ticker_provider: SingleTickerProviderStateMixinData,
256
257 ticker: Option<Ref<Ticker>>,
259
260 elapsed: Duration,
262
263 from: f64,
265
266 to: f64,
268}
269
270impl StatefulWidget for ProgressRing {
271 type State = ProgressRingState;
272
273 fn key(&self) -> Option<&KeyRef> {
274 self.key.as_ref()
275 }
276
277 fn create_state(&self) -> ProgressRingState {
278 let progress = self.progress();
279 ProgressRingState {
280 state: StateData::new(),
281 single_ticker_provider: Default::default(),
282 ticker: None,
283 elapsed: Duration::ZERO,
284 from: progress,
285 to: progress,
286 }
287 }
288}
289
290impl SingleTickerProviderStateMixin for ProgressRingState {
291 fn single_ticker_provider_data(
292 self: Handle<Self>,
293 app: &App,
294 ) -> &SingleTickerProviderStateMixinData {
295 &app.get(self).single_ticker_provider
296 }
297
298 fn single_ticker_provider_data_mut(
299 self: Handle<Self>,
300 app: &mut App,
301 ) -> &mut SingleTickerProviderStateMixinData {
302 &mut app.get_mut(self).single_ticker_provider
303 }
304}
305
306impl ProgressRingState {
307 fn progress(self: Handle<Self>, app: &App) -> f64 {
309 let state = app.get(self);
310 let seconds = state.elapsed.as_secs_f64() / PROGRESS_RING_DURATION.as_secs_f64();
311 if self.widget(app).is_indeterminate {
312 seconds.fract()
314 } else {
315 (state.from + seconds).min(state.to)
317 }
318 }
319
320 fn update_states(self: Handle<Self>, app: &mut App) {
323 let ticker = app.get(self).ticker.clone().unwrap();
324 ticker.stop(app, false);
326 app.get_mut(self).elapsed = Duration::ZERO;
327
328 let widget = self.widget(app);
329 if !widget.is_active {
330 return;
332 }
333 if widget.is_indeterminate || app.get(self).from < app.get(self).to {
334 ticker.start(app);
335 }
336 }
337
338 fn update_progress(self: Handle<Self>, app: &mut App, old_progress: f64) {
341 let target = self.widget(app).progress();
342 let state = app.get_mut(self);
343 state.elapsed = Duration::ZERO;
344 if old_progress < target {
345 state.from = old_progress;
346 } else {
347 state.from = target;
348 }
349 state.to = target;
350 self.update_states(app);
351 }
352
353 fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
355 self.set_state(app, |state| state.elapsed = elapsed);
356 if !self.widget(app).is_indeterminate && self.progress(app) >= app.get(self).to {
357 app.get(self).ticker.handle().unwrap().stop(app, false);
358 }
359 }
360}
361
362impl State for ProgressRingState {
363 type Widget = ProgressRing;
364 waft_widgets::state_accessors!();
365
366 fn init_state(self: Handle<Self>, app: &mut App) {
367 let ticker = SingleTickerProviderStateMixin::create_ticker(
368 self,
369 app,
370 FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
371 );
372 app.get_mut(self).ticker = Some(ticker.clone());
373 self.update_states(app);
374 }
375
376 fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ProgressRing) {
377 let widget = self.widget(app).clone();
378 let switched_kind = old.is_indeterminate != widget.is_indeterminate;
379 if switched_kind || (!widget.is_indeterminate && old.progress() != widget.progress()) {
380 self.update_progress(app, old.progress());
381 } else if old.is_active != widget.is_active {
382 if !widget.is_indeterminate {
384 app.get_mut(self).from = app.get(self).to;
385 }
386 self.update_states(app);
387 }
388 }
389
390 fn activate(self: Handle<Self>, app: &mut App) {
391 SingleTickerProviderStateMixin::activate(self, app);
392 }
393
394 fn dispose(self: Handle<Self>, app: &mut App) {
395 app.get(self).ticker.handle().unwrap().dispose(app);
396 SingleTickerProviderStateMixin::dispose(self, app);
397 }
398
399 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
400 let resources = ThemeResources::of(app, context);
401 let widget = self.widget(app).clone();
402 let painter = ProgressRingVisual {
403 progress: self.progress(app),
404 indeterminate: widget.is_indeterminate,
405 foreground: widget
406 .foreground
407 .unwrap_or(resources.progress_ring_foreground_theme_brush),
408 background: widget
409 .background
410 .unwrap_or(resources.progress_ring_background_theme_brush),
411 };
412 let opacity = if widget.is_active { 1.0 } else { 0.0 };
414 ConstrainedBox::new(BoxConstraints {
415 min_width: PROGRESS_RING_MIN_SIZE,
416 max_width: f64::INFINITY,
417 min_height: PROGRESS_RING_MIN_SIZE,
418 max_height: f64::INFINITY,
419 })
420 .child(
421 Opacity::new(opacity).child(
422 SizedBox::new()
423 .width(PROGRESS_RING_SIZE)
424 .height(PROGRESS_RING_SIZE)
425 .child(IgnorePointer::new().child(CustomPaint::new().painter(painter))),
426 ),
427 )
428 .into_widget()
429 }
430}
431
432#[derive(Clone, Copy, Debug, PartialEq)]
435struct ProgressRingVisual {
436 progress: f64,
437 indeterminate: bool,
438 foreground: Color,
439 background: Color,
440}
441
442impl ProgressRingVisual {
443 fn arc(&self, canvas: &mut Canvas, size: Size, trim: (f64, f64), rotation: f64, color: Color) {
445 if color.a == 0.0 || trim.1 <= trim.0 {
446 return;
447 }
448 let (radius, width) = self.geometry(size);
449 let mut path = PathBuilder::new();
450 let start = (rotation + trim.0 - 0.25) * TAU;
452 path.arc(
453 center(size),
454 radius as f32,
455 start as f32,
456 ((trim.1 - trim.0) * TAU) as f32,
457 );
458 let mut paint = Paint::from_color(color.into());
459 paint.style = PaintStyle::Stroke(Stroke {
460 cap: Cap::Round,
461 ..Stroke::new(width as f32)
462 });
463 canvas.draw_path(&path.build(), Default::default(), &paint);
464 }
465
466 fn geometry(&self, size: Size) -> (f64, f64) {
468 let side = size.width().min(size.height());
469 if self.indeterminate {
470 (INDETERMINATE_RADIUS * side, INDETERMINATE_STROKE * side)
471 } else {
472 (DETERMINATE_RADIUS * side, DETERMINATE_STROKE * side)
473 }
474 }
475}
476
477fn center(size: Size) -> Point {
479 Point::new((size.width() / 2.0) as f32, (size.height() / 2.0) as f32)
480}
481
482impl CustomPainter for ProgressRingVisual {
483 fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
484 if size.is_empty() {
485 return;
486 }
487
488 canvas.save();
490 canvas.scale((size.width() / 32.0) as f32, (size.height() / 32.0) as f32);
491 let size = Size::new(32.0, 32.0);
492
493 self.arc(canvas, size, (0.0, 1.0), 0.0, self.background);
495 if self.indeterminate {
496 let rotation = indeterminate_rotation(self.progress);
497 if self.progress < 0.5 {
499 let trim = indeterminate_growing_arc(self.progress);
500 self.arc(canvas, size, trim, rotation, self.foreground);
501 } else {
502 let trim = indeterminate_shrinking_arc(self.progress);
503 self.arc(canvas, size, trim, rotation, self.foreground);
504 }
505 } else if determinate_arc_is_shown(self.progress) {
506 let trim = (0.0, determinate_trim_end(self.progress));
507 self.arc(canvas, size, trim, 0.0, self.foreground);
508 }
509 canvas.restore();
510 }
511
512 fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
513 old_delegate.as_any().downcast_ref::<Self>() != Some(self)
514 }
515
516 fn as_any(&self) -> &dyn std::any::Any {
517 self
518 }
519}