use crate::{RangeBase, ThemeResources};
use std::{f64::consts::TAU, time::Duration};
use waft_animation::{Cubic, Curve};
use waft_embedder::valo::{Cap, Point};
use waft_embedder::{Canvas, Color, Paint, PaintStyle, PathBuilder, Size, Stroke};
use waft_foundation::{App, Handle};
use waft_rendering::{BoxConstraints, CustomPainter};
use waft_scheduler::{FrameCallback, Ticker};
use waft_widgets::*;
pub const PROGRESS_RING_DURATION: Duration = Duration::from_secs(2);
pub const PROGRESS_RING_SIZE: f64 = 32.0;
pub const PROGRESS_RING_MIN_SIZE: f64 = 16.0;
pub const PROGRESS_RING_DEFAULT_MAXIMUM: f64 = 100.0;
const DETERMINATE_RADIUS: f64 = 8.0 * 1.77 / 32.0;
const DETERMINATE_STROKE: f64 = 1.5 * 1.77 / 32.0;
const INDETERMINATE_RADIUS: f64 = 7.0 * 5.0 / 80.0;
const INDETERMINATE_STROKE: f64 = 1.5 * 5.0 / 80.0;
fn lottie_ease() -> Cubic {
Cubic::new(0.167, 0.167, 0.833, 0.833)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Easing {
Eased,
Held,
}
type KeyFrame = (f64, f64, Easing);
fn key_frames(progress: f64, frames: &[KeyFrame]) -> f64 {
let (first, last) = (frames[0], frames[frames.len() - 1]);
if progress <= first.0 {
return first.1;
}
if progress >= last.0 {
return last.1;
}
let index = frames.iter().position(|frame| frame.0 > progress).unwrap();
let (from_progress, from_value, _) = frames[index - 1];
let (to_progress, to_value, easing) = frames[index];
match easing {
Easing::Held => from_value,
Easing::Eased => {
let span = (progress - from_progress) / (to_progress - from_progress);
from_value + (to_value - from_value) * lottie_ease().transform(span)
}
}
}
fn determinate_trim_end(progress: f64) -> f64 {
key_frames(
progress,
&[
(0.0, 0.0001, Easing::Held),
(0.00833333377, 0.0001, Easing::Held),
(0.25, 0.25, Easing::Eased),
(0.5, 0.5, Easing::Eased),
(0.75, 0.75, Easing::Eased),
(0.983333349, 0.96666666, Easing::Eased),
(0.991666675, 1.0, Easing::Eased),
],
)
}
fn determinate_arc_is_shown(progress: f64) -> bool {
progress >= 0.00833333377
}
fn indeterminate_rotation(progress: f64) -> f64 {
key_frames(
progress,
&[
(0.0, 0.0, Easing::Held),
(0.5, 450.0, Easing::Eased),
(1.0, 900.0, Easing::Eased),
],
) / 360.0
}
fn indeterminate_growing_arc(progress: f64) -> (f64, f64) {
let end = key_frames(
progress,
&[(0.0, 0.0001, Easing::Held), (0.5, 0.5, Easing::Eased)],
);
(0.0, end)
}
fn indeterminate_shrinking_arc(progress: f64) -> (f64, f64) {
let start = key_frames(
progress,
&[
(0.0, 0.0, Easing::Held),
(0.5, 0.0, Easing::Held),
(1.0, 0.5, Easing::Eased),
],
);
(start, 0.5)
}
#[derive(Clone, Debug)]
pub struct ProgressRing {
pub minimum: f64,
pub maximum: f64,
pub value: f64,
pub is_active: bool,
pub is_indeterminate: bool,
pub foreground: Option<Color>,
pub background: Option<Color>,
pub key: Option<KeyRef>,
}
impl Default for ProgressRing {
fn default() -> Self {
Self {
minimum: 0.0,
maximum: PROGRESS_RING_DEFAULT_MAXIMUM,
value: 0.0,
is_active: true,
is_indeterminate: true,
foreground: None,
background: None,
key: None,
}
}
}
impl ProgressRing {
pub fn new() -> Self {
Self::default()
}
pub fn minimum(mut self, value: f64) -> Self {
self.minimum = value;
self
}
pub fn maximum(mut self, value: f64) -> Self {
self.maximum = value;
self
}
pub fn value(mut self, value: f64) -> Self {
self.value = value;
self
}
pub fn is_active(mut self, value: bool) -> Self {
self.is_active = value;
self
}
pub fn is_indeterminate(mut self, value: bool) -> Self {
self.is_indeterminate = value;
self
}
pub fn foreground(mut self, value: Color) -> Self {
self.foreground = Some(value);
self
}
pub fn background(mut self, value: Color) -> Self {
self.background = Some(value);
self
}
pub fn key(mut self, value: KeyRef) -> Self {
self.key = Some(value);
self
}
fn progress(&self) -> f64 {
let range = RangeBase::new(self.minimum, self.maximum, self.value).coerced();
let span = range.maximum - range.minimum;
if span == 0.0 {
0.0
} else {
(range.value - range.minimum) / span
}
}
}
pub struct ProgressRingState {
state: StateData<ProgressRing>,
single_ticker_provider: SingleTickerProviderStateMixinData,
ticker: Option<Handle<Ticker>>,
elapsed: Duration,
from: f64,
to: f64,
}
impl StatefulWidget for ProgressRing {
type State = ProgressRingState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ProgressRingState {
let progress = self.progress();
ProgressRingState {
state: StateData::new(),
single_ticker_provider: Default::default(),
ticker: None,
elapsed: Duration::ZERO,
from: progress,
to: progress,
}
}
}
impl SingleTickerProviderStateMixin for ProgressRingState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl ProgressRingState {
fn progress(self: Handle<Self>, app: &App) -> f64 {
let state = app.get(self);
let seconds = state.elapsed.as_secs_f64() / PROGRESS_RING_DURATION.as_secs_f64();
if self.widget(app).is_indeterminate {
seconds.fract()
} else {
(state.from + seconds).min(state.to)
}
}
fn update_states(self: Handle<Self>, app: &mut App) {
let ticker = app.get(self).ticker.unwrap();
ticker.stop(app, false);
app.get_mut(self).elapsed = Duration::ZERO;
let widget = self.widget(app);
if !widget.is_active {
return;
}
if widget.is_indeterminate || app.get(self).from < app.get(self).to {
ticker.start(app);
}
}
fn update_progress(self: Handle<Self>, app: &mut App, old_progress: f64) {
let target = self.widget(app).progress();
let state = app.get_mut(self);
state.elapsed = Duration::ZERO;
if old_progress < target {
state.from = old_progress;
} else {
state.from = target;
}
state.to = target;
self.update_states(app);
}
fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
self.set_state(app, |state| state.elapsed = elapsed);
if !self.widget(app).is_indeterminate && self.progress(app) >= app.get(self).to {
app.get(self).ticker.unwrap().stop(app, false);
}
}
}
impl State for ProgressRingState {
type Widget = ProgressRing;
waft_widgets::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let ticker = SingleTickerProviderStateMixin::create_ticker(
self,
app,
FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
);
app.get_mut(self).ticker = Some(ticker);
self.update_states(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ProgressRing) {
let widget = self.widget(app).clone();
let switched_kind = old.is_indeterminate != widget.is_indeterminate;
if switched_kind || (!widget.is_indeterminate && old.progress() != widget.progress()) {
self.update_progress(app, old.progress());
} else if old.is_active != widget.is_active {
if !widget.is_indeterminate {
app.get_mut(self).from = app.get(self).to;
}
self.update_states(app);
}
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
app.get(self).ticker.unwrap().dispose(app);
SingleTickerProviderStateMixin::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let resources = ThemeResources::of(app, context);
let widget = self.widget(app).clone();
let painter = ProgressRingVisual {
progress: self.progress(app),
indeterminate: widget.is_indeterminate,
foreground: widget
.foreground
.unwrap_or(resources.progress_ring_foreground_theme_brush),
background: widget
.background
.unwrap_or(resources.progress_ring_background_theme_brush),
};
let opacity = if widget.is_active { 1.0 } else { 0.0 };
ConstrainedBox::new(BoxConstraints {
min_width: PROGRESS_RING_MIN_SIZE,
max_width: f64::INFINITY,
min_height: PROGRESS_RING_MIN_SIZE,
max_height: f64::INFINITY,
})
.child(
Opacity::new(opacity).child(
SizedBox::new()
.width(PROGRESS_RING_SIZE)
.height(PROGRESS_RING_SIZE)
.child(IgnorePointer::new().child(CustomPaint::new().painter(painter))),
),
)
.into_widget()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct ProgressRingVisual {
progress: f64,
indeterminate: bool,
foreground: Color,
background: Color,
}
impl ProgressRingVisual {
fn arc(&self, canvas: &mut Canvas, size: Size, trim: (f64, f64), rotation: f64, color: Color) {
if color.a == 0.0 || trim.1 <= trim.0 {
return;
}
let (radius, width) = self.geometry(size);
let mut path = PathBuilder::new();
let start = (rotation + trim.0 - 0.25) * TAU;
path.arc(
center(size),
radius as f32,
start as f32,
((trim.1 - trim.0) * TAU) as f32,
);
let mut paint = Paint::from_color(color.into());
paint.style = PaintStyle::Stroke(Stroke {
cap: Cap::Round,
..Stroke::new(width as f32)
});
canvas.draw_path(&path.build(), Default::default(), &paint);
}
fn geometry(&self, size: Size) -> (f64, f64) {
let side = size.width().min(size.height());
if self.indeterminate {
(INDETERMINATE_RADIUS * side, INDETERMINATE_STROKE * side)
} else {
(DETERMINATE_RADIUS * side, DETERMINATE_STROKE * side)
}
}
}
fn center(size: Size) -> Point {
Point::new((size.width() / 2.0) as f32, (size.height() / 2.0) as f32)
}
impl CustomPainter for ProgressRingVisual {
fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
if size.is_empty() {
return;
}
canvas.save();
canvas.scale((size.width() / 32.0) as f32, (size.height() / 32.0) as f32);
let size = Size::new(32.0, 32.0);
self.arc(canvas, size, (0.0, 1.0), 0.0, self.background);
if self.indeterminate {
let rotation = indeterminate_rotation(self.progress);
if self.progress < 0.5 {
let trim = indeterminate_growing_arc(self.progress);
self.arc(canvas, size, trim, rotation, self.foreground);
} else {
let trim = indeterminate_shrinking_arc(self.progress);
self.arc(canvas, size, trim, rotation, self.foreground);
}
} else if determinate_arc_is_shown(self.progress) {
let trim = (0.0, determinate_trim_end(self.progress));
self.arc(canvas, size, trim, 0.0, self.foreground);
}
canvas.restore();
}
fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
old_delegate.as_any().downcast_ref::<Self>() != Some(self)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}