Skip to main content

gpui_material_components/
progress.rs

1use std::f32::consts::TAU;
2
3use gpui::{
4    App, Bounds, ContentMask, ElementId, Hsla, IntoElement, ParentElement, PathBuilder, PathStyle,
5    Pixels, Point, RenderOnce, SharedString, StrokeOptions, Styled, Window, canvas, point, px,
6    size,
7};
8use gpui_base::motion::Easing;
9use gpui_material_foundation::{animate, color, window_material_theme};
10use gpui_material_theme::{
11    ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, TokenValue, token,
12};
13use web_time::Instant;
14
15const STROKE_WIDTH: f32 = 4.;
16const TRACK_GAP: f32 = 4.;
17const STOP_SIZE: f32 = 4.;
18const LINEAR_AMPLITUDE: f32 = 3.;
19const CIRCULAR_AMPLITUDE: f32 = 1.6;
20const CIRCULAR_WAVELENGTH: f32 = 15.;
21const MAX_WAVES: f32 = 128.;
22
23/// Straight or Expressive wavy active progress indicator.
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum ProgressShape {
26    #[default]
27    Straight,
28    Wavy,
29}
30
31/// Shape at the ends of a progress stroke.
32#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
33pub enum ProgressCap {
34    #[default]
35    Round,
36    Butt,
37    Square,
38}
39
40/// Per-stroke appearance. The default width is 4 dp and the color comes from
41/// the window palette's active or track role.
42#[derive(Clone, Copy, Debug, Default, PartialEq)]
43pub struct ProgressStroke {
44    pub width: Option<Pixels>,
45    pub color: Option<Hsla>,
46    pub cap: ProgressCap,
47}
48
49/// Geometry and appearance passed to a linear determinate stop painter.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct ProgressStop {
52    pub bounds: Bounds<Pixels>,
53    pub color: Hsla,
54    pub cap: ProgressCap,
55    pub direction: Direction,
56}
57
58type StopPainter = dyn Fn(ProgressStop, &mut Window, &mut App);
59
60struct Progress {
61    id: ElementId,
62    name: SharedString,
63    value: Option<f32>,
64    shape: ProgressShape,
65    active: ProgressStroke,
66    track: ProgressStroke,
67    gap: f32,
68    stop_size: f32,
69    stop_painter: Option<Box<StopPainter>>,
70    amplitude: Option<Box<dyn Fn(f32) -> f32>>,
71    wavelength: Option<f32>,
72    wave_speed: Option<f32>,
73}
74
75impl Progress {
76    fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
77        Self {
78            id: id.into(),
79            name: name.into(),
80            value: None,
81            shape: ProgressShape::default(),
82            active: ProgressStroke::default(),
83            track: ProgressStroke::default(),
84            gap: TRACK_GAP,
85            stop_size: STOP_SIZE,
86            stop_painter: None,
87            amplitude: None,
88            wavelength: None,
89            wave_speed: None,
90        }
91    }
92
93    fn render(self, circular: bool, window: &mut Window, cx: &mut App) -> impl IntoElement {
94        let theme = window_material_theme(window, cx);
95        let active = Stroke::resolve(self.active, color(theme.colors.color(ColorRole::Primary)));
96        let track = Stroke::resolve(
97            self.track,
98            color(theme.colors.color(ColorRole::SecondaryContainer)),
99        );
100        let reduced = cx.reduce_motion();
101        let window_active = window.is_window_active();
102        let effects = theme.motion.spec(
103            MotionKind::Effects,
104            MotionSpeed::Default,
105            reduced || !window_active,
106        );
107        let spatial = theme.motion.spec(
108            MotionKind::Spatial,
109            MotionSpeed::Default,
110            reduced || !window_active,
111        );
112        let direction = theme.layout.direction;
113        let value = self
114            .value
115            .filter(|v| v.is_finite())
116            .map(|v| v.clamp(0., 1.));
117        let measured = value.is_some();
118        let motion = window.use_keyed_state((self.id.clone(), "progress-motion"), cx, |_, _| {
119            ProgressMotion {
120                last_measured: value.unwrap_or(0.4),
121                ..Default::default()
122            }
123        });
124        let target = motion.update(cx, |state, _| {
125            if let Some(value) = value {
126                state.last_measured = value;
127            }
128            state.last_measured
129        });
130        let mode = animate(
131            (self.id.clone(), "indeterminate-mix"),
132            f32::from(!measured),
133            effects,
134            window,
135            cx,
136        )
137        .clamp(0., 1.);
138        let measured_value = animate(
139            (self.id.clone(), "determinate-value"),
140            target,
141            spatial,
142            window,
143            cx,
144        )
145        .clamp(0., 1.);
146        let wavy = self.shape == ProgressShape::Wavy;
147        let amplitude = if wavy {
148            let endpoint = mode == 0. && (measured_value == 0. || measured_value == 1.);
149            let default_target = wave_amplitude(measured_value) * (1. - mode) + mode;
150            let target = self.amplitude.as_ref().map_or(default_target, |amplitude| {
151                normalized_amplitude(amplitude(if measured { measured_value } else { 0. }))
152            });
153            animate(
154                (self.id.clone(), "wave-amplitude"),
155                if endpoint { 0. } else { target },
156                if endpoint {
157                    MotionSpec::Instant
158                } else {
159                    effects
160                },
161                window,
162                cx,
163            )
164            .clamp(0., 1.)
165        } else {
166            0.
167        };
168        let wavelength = self.wavelength.unwrap_or(if circular {
169            CIRCULAR_WAVELENGTH
170        } else {
171            40. - 20. * mode
172        });
173        let hz = self
174            .wave_speed
175            .map_or(1., |speed| f64::from(speed) / f64::from(wavelength));
176        let motion_enabled = window_active && !reduced && active.width > 0.;
177        let animate_loop = motion_enabled && !measured;
178        let animate_wave =
179            motion_enabled && hz > 0. && amplitude > 0. && (mode > 0. || measured_value > 0.);
180        let now = cx.background_executor().now();
181        let (loop_time, phase) = motion.update(cx, |state, _| {
182            state.sample(
183                now,
184                animate_loop,
185                if animate_wave { hz } else { 0. },
186                reduced,
187                mode == 1.,
188            )
189        });
190        let motionless = reduced || !window_active && loop_time == 0.;
191        let (arc_start, arc_length) = if circular && mode > 0. && !motionless {
192            circular_indeterminate(loop_time)
193        } else {
194            (0., 0.25)
195        };
196        let arc_origin = motion.update(cx, |state, _| {
197            if mode == 0. || mode == 1. || motionless {
198                state.arc_origin = arc_start.round();
199            }
200            state.arc_origin
201        });
202        let arc = (
203            (arc_start - arc_origin) * mode,
204            measured_value + (arc_length - measured_value) * mode,
205        );
206        let [first, second] = if circular || mode == 0. || motionless {
207            [(0.25, 0.65), (0., 0.)]
208        } else {
209            linear_indeterminate(loop_time)
210        };
211        let mut lines = [
212            (
213                first.0 * mode,
214                measured_value + (first.1 - measured_value) * mode,
215            ),
216            (second.0, second.0 + (second.1 - second.0) * mode),
217        ];
218        lines.sort_by(|left, right| left.0.total_cmp(&right.0));
219
220        let wave_space = if wavy { 2. * LINEAR_AMPLITUDE } else { 0. };
221        let side = if circular {
222            if wavy { 48. } else { 40. }
223        } else {
224            STROKE_WIDTH
225                .max(active.width)
226                .max(track.width)
227                .max(self.stop_size)
228                + wave_space
229        };
230        let picture = canvas(
231            |_, _, _| (),
232            move |bounds, _, window, cx| {
233                let width = f32::from(bounds.size.width);
234                let height = f32::from(bounds.size.height);
235                if !width.is_finite() || !height.is_finite() || width <= 0. || height <= 0. {
236                    return;
237                }
238                window.with_content_mask(Some(ContentMask { bounds }), |window| {
239                    let paint = ProgressPaint {
240                        active,
241                        track,
242                        gap: self.gap,
243                        wavelength,
244                        amplitude,
245                        phase,
246                    };
247                    if circular {
248                        paint.circular(bounds, arc, wavy, window);
249                    } else {
250                        paint.linear(bounds, lines, direction, window);
251                        if measured && self.stop_size > 0. {
252                            let stop = ProgressStop {
253                                bounds: stop_bounds(bounds, self.stop_size, wavy, direction),
254                                color: active.color,
255                                cap: active.cap,
256                                direction,
257                            };
258                            paint_stop(stop, self.stop_painter.as_deref(), window, cx);
259                        }
260                    }
261                });
262                if animate_loop || animate_wave {
263                    window.request_animation_frame();
264                }
265            },
266        )
267        .size_full();
268        let mut element = gpui_base::Progress::new(self.id)
269            .value(value.unwrap_or_default() * 100.)
270            .indeterminate(!measured)
271            .accessibility_label(self.name)
272            .h(px(side))
273            .child(picture);
274        if circular {
275            element = element.w(px(side)).flex_none();
276        } else {
277            element = element.w_full();
278        }
279        element
280    }
281}
282
283#[derive(Default)]
284struct ProgressMotion {
285    last_measured: f32,
286    arc_origin: f32,
287    last_time: Option<Instant>,
288    loop_running: bool,
289    loop_ms: f64,
290    wave_hz: f64,
291    wave_phase: f64,
292}
293
294impl ProgressMotion {
295    fn sample(
296        &mut self,
297        now: Instant,
298        animate_loop: bool,
299        wave_hz: f64,
300        reduced: bool,
301        settled_loop: bool,
302    ) -> (f32, f32) {
303        if reduced {
304            self.last_time = None;
305            self.loop_ms = 0.;
306            self.wave_phase = 0.;
307        }
308        let elapsed = self
309            .last_time
310            .replace(now)
311            .map_or(0., |last| now.saturating_duration_since(last).as_secs_f64());
312        if animate_loop && self.loop_running {
313            self.loop_ms += elapsed * 1000.;
314        }
315        if settled_loop {
316            // 42 seconds is a multiple of both the linear and circular cycles.
317            self.loop_ms %= 42_000.;
318        }
319        if wave_hz > 0. && self.wave_hz > 0. {
320            self.wave_phase = (self.wave_phase + elapsed * self.wave_hz).fract();
321        }
322        self.loop_running = animate_loop;
323        self.wave_hz = wave_hz;
324        (self.loop_ms as f32, self.wave_phase as f32)
325    }
326}
327// The keyframe timings match ProgressIndicator.kt in Material 3 1.5.0-rc01.
328fn linear_indeterminate(elapsed_ms: f32) -> [(f32, f32); 2] {
329    let clock = elapsed_ms % 1750.;
330    let sample = |delay, duration| {
331        easing_sample(
332            "md.sys.motion.easing-emphasized-accelerate",
333            (clock - delay) / duration,
334        )
335    };
336    [
337        (sample(250., 1000.), sample(0., 1000.)),
338        (sample(900., 850.), sample(650., 850.)),
339    ]
340}
341
342fn circular_indeterminate(elapsed_ms: f32) -> (f32, f32) {
343    let clock = elapsed_ms % 6000.;
344    let step = (clock / 1500.).floor();
345    let turn = easing_sample(
346        "md.sys.motion.easing-emphasized-decelerate",
347        (clock % 1500.) / 300.,
348    );
349    let phase = clock / 3000.;
350    let length = if phase < 1. {
351        0.1 + (0.87 - 0.1) * phase
352    } else {
353        0.87 - (0.87 - 0.1) * easing_sample("md.sys.motion.easing-standard", phase - 1.)
354    };
355    // Keep the angle unwrapped during a mode change, then paint it periodically.
356    (
357        (elapsed_ms / 6000.) * 3. + (elapsed_ms / 6000.).floor() + (step + turn) / 4.,
358        length,
359    )
360}
361
362fn easing_sample(name: &str, progress: f32) -> f32 {
363    let progress = progress.clamp(0., 1.);
364    let TokenValue::Easing(curve) = token(name).expect("bundled progress easing") else {
365        unreachable!("progress easing token must contain a cubic Bézier");
366    };
367    let easing =
368        Easing::cubic_bezier(curve.x1, curve.y1, curve.x2, curve.y2).expect("valid Material curve");
369    easing.sample(progress)
370}
371
372#[derive(Clone, Copy)]
373struct Stroke {
374    width: f32,
375    color: Hsla,
376    cap: ProgressCap,
377}
378
379impl Stroke {
380    fn resolve(style: ProgressStroke, color: Hsla) -> Self {
381        Self {
382            width: style
383                .width
384                .and_then(nonnegative_length)
385                .unwrap_or(STROKE_WIDTH),
386            color: style.color.unwrap_or(color),
387            cap: style.cap,
388        }
389    }
390
391    fn fitted(self, max: f32) -> Self {
392        Self {
393            width: self.width.min(max),
394            ..self
395        }
396    }
397
398    fn cap_length(self) -> f32 {
399        if self.cap == ProgressCap::Butt {
400            0.
401        } else {
402            self.width / 2.
403        }
404    }
405
406    fn paint_flat(
407        self,
408        (start, end): (f32, f32),
409        sample: impl Fn(f32) -> Point<Pixels>,
410        window: &mut Window,
411    ) {
412        if self.width == 0. || self.color.a == 0. || end <= start {
413            return;
414        }
415        let first = sample(start);
416        let last = sample(end);
417        let extent = px(self.cap_length());
418        let half_width = px(self.width / 2.);
419        let bounds = Bounds::from_corners(
420            point(first.x.min(last.x) - extent, first.y - half_width),
421            point(first.x.max(last.x) + extent, first.y + half_width),
422        );
423        if bounds.size.width > px(0.) {
424            paint_marker(bounds, self.color, self.cap, window);
425        }
426    }
427
428    fn paint(
429        self,
430        range: (f32, f32),
431        samples_per_turn: f32,
432        closed: bool,
433        sample: impl Fn(f32) -> Point<Pixels>,
434        window: &mut Window,
435    ) {
436        let (start, end) = range;
437        if self.width == 0. || self.color.a == 0. || end <= start {
438            return;
439        }
440        let first = sample(start);
441        if !closed && first == sample(end) {
442            if self.cap != ProgressCap::Butt {
443                paint_marker(
444                    centered_square(first, self.width),
445                    self.color,
446                    self.cap,
447                    window,
448                );
449            }
450            return;
451        }
452        let steps = (((end - start) * samples_per_turn).ceil() as usize).max(1);
453        let last = sample(end);
454        let step = (end - start) / steps as f32;
455        let mut path = PathBuilder::default().with_style(PathStyle::Stroke(
456            StrokeOptions::default()
457                .with_line_width(self.width)
458                .with_miter_limit(1.),
459        ));
460        let square = !closed && self.cap == ProgressCap::Square;
461        path.move_to(if square {
462            extend_endpoint(first, sample(start + step), self.cap_length())
463        } else {
464            first
465        });
466        let last_step = if closed { steps - 1 } else { steps };
467        for index in 1..=last_step {
468            let point = if index == steps && square {
469                extend_endpoint(last, sample(end - step), self.cap_length())
470            } else {
471                sample(start + step * index as f32)
472            };
473            path.line_to(point);
474        }
475        if closed {
476            path.close();
477        }
478        if let Ok(path) = path.build() {
479            window.paint_path(path, self.color);
480        }
481        if !closed && self.cap == ProgressCap::Round {
482            for endpoint in [first, last] {
483                paint_marker(
484                    centered_square(endpoint, self.width),
485                    self.color,
486                    self.cap,
487                    window,
488                );
489            }
490        }
491    }
492}
493
494fn extend_endpoint(endpoint: Point<Pixels>, neighbor: Point<Pixels>, radius: f32) -> Point<Pixels> {
495    let difference = endpoint - neighbor;
496    let distance = f32::from(difference.x).hypot(f32::from(difference.y));
497    if distance > 0. {
498        endpoint + difference * (radius / distance)
499    } else {
500        endpoint
501    }
502}
503
504#[derive(Clone, Copy)]
505struct ProgressPaint {
506    active: Stroke,
507    track: Stroke,
508    gap: f32,
509    wavelength: f32,
510    amplitude: f32,
511    phase: f32,
512}
513
514impl ProgressPaint {
515    fn linear(
516        self,
517        bounds: Bounds<Pixels>,
518        segments: [(f32, f32); 2],
519        direction: Direction,
520        window: &mut Window,
521    ) {
522        let width = f32::from(bounds.size.width);
523        let height = f32::from(bounds.size.height);
524        let active = self.active.fitted(height.min(width));
525        let track = self.track.fitted(height.min(width));
526        let amplitude = self.amplitude * ((height - active.width) / 2.).min(LINEAR_AMPLITUDE);
527        let wavelength = self.wavelength.max(width / MAX_WAVES);
528        let axis = |x| logical_x(x, width, direction);
529        let mid = bounds.center().y;
530        let track_sample = |f| {
531            let offset = axis(linear_position(width, track.cap_length(), f));
532            point(bounds.left() + px(offset), mid)
533        };
534        let active_inset = if amplitude > 0. {
535            active.width / 2.
536        } else {
537            active.cap_length()
538        };
539        let active_sample = |f| {
540            let offset = linear_position(width, active_inset, f);
541            let wave = wave_offset(amplitude, offset / wavelength, self.phase);
542            point(bounds.left() + px(axis(offset)), mid + px(wave))
543        };
544        let gap = ((self.gap + active.cap_length() + track.cap_length()) / width).min(1.);
545        let samples = if amplitude > 0. {
546            (width / wavelength * 16.).max(100.)
547        } else {
548            1.
549        };
550        let mut cursor = 0.;
551        for (start, end) in segments {
552            if active.width > 0. && end > start {
553                track.paint_flat((cursor, start - gap), track_sample, window);
554                cursor = cursor.max(end + gap);
555            }
556        }
557        track.paint_flat((cursor, 1.), track_sample, window);
558        for segment in segments {
559            if amplitude > 0. {
560                active.paint(segment, samples, false, active_sample, window);
561            } else {
562                active.paint_flat(segment, active_sample, window);
563            }
564        }
565    }
566
567    fn circular(
568        self,
569        bounds: Bounds<Pixels>,
570        (start, extent): (f32, f32),
571        wavy: bool,
572        window: &mut Window,
573    ) {
574        let side = f32::from(bounds.size.width.min(bounds.size.height));
575        let margin = if wavy { 4.0_f32.min(side / 2.) } else { 0. };
576        let active = self.active.fitted((side - margin) / 2.);
577        let track = self.track.fitted((side - margin) / 2.);
578        let diameter = side
579            - margin
580            - active
581                .width
582                .max(track.width)
583                .max(STROKE_WIDTH.min(side / 2.));
584        let radius = diameter / 2.;
585        if radius <= 0. {
586            return;
587        }
588        let center = bounds.center();
589        let amplitude = self.amplitude * CIRCULAR_AMPLITUDE.min(margin / 2.);
590        let waves = circular_wave_count(radius, self.wavelength);
591        let sample = |fraction: f32, amplitude: f32| {
592            let arc = (fraction - 0.25) * TAU;
593            let wave = wave_offset(amplitude, fraction * waves, self.phase);
594            let radius = px(radius + wave);
595            center + point(radius * arc.cos(), radius * arc.sin())
596        };
597        let active_sample = |fraction| sample(fraction, amplitude);
598        let track_sample = |fraction| sample(fraction, 0.);
599        let samples = if amplitude > 0. {
600            (waves * 16.).max(100.)
601        } else {
602            100.
603        };
604        if active.width == 0. || extent <= 0. {
605            track.paint((0., 1.), 100., true, track_sample, window);
606        } else if extent >= 1. {
607            active.paint((0., 1.), samples, true, active_sample, window);
608        } else {
609            let gap =
610                ((self.gap + active.cap_length() + track.cap_length()) / (radius * TAU)).min(1.);
611            let end = start + extent;
612            track.paint(
613                (end + gap, start + 1. - gap),
614                100.,
615                false,
616                track_sample,
617                window,
618            );
619            active.paint((start, end), samples, false, active_sample, window);
620        }
621    }
622}
623
624fn linear_position(width: f32, inset: f32, fraction: f32) -> f32 {
625    let inset = inset.min(width / 2.);
626    (width * fraction).clamp(inset, width - inset)
627}
628
629fn logical_x(offset: f32, width: f32, direction: Direction) -> f32 {
630    if direction == Direction::Rtl {
631        width - offset
632    } else {
633        offset
634    }
635}
636
637fn circular_wave_count(radius: f32, wavelength: f32) -> f32 {
638    ((radius * TAU) / wavelength).round().clamp(1., MAX_WAVES)
639}
640
641fn wave_offset(amplitude: f32, cycles: f32, phase: f32) -> f32 {
642    amplitude * ((cycles.rem_euclid(1.) - phase) * TAU).sin()
643}
644
645fn nonnegative_length(value: Pixels) -> Option<f32> {
646    let length = f32::from(value);
647    (length.is_finite() && length >= 0.).then_some(length)
648}
649
650fn normalized_amplitude(amplitude: f32) -> f32 {
651    if amplitude.is_nan() {
652        0.
653    } else {
654        amplitude.clamp(0., 1.)
655    }
656}
657
658fn wave_amplitude(progress: f32) -> f32 {
659    // WavyProgressIndicatorDefaults.indicatorAmplitude suppresses waves at the
660    // beginning and end; only the change between these targets is animated.
661    f32::from(progress > 0.1 && progress < 0.95)
662}
663
664fn centered_square(center: Point<Pixels>, side: f32) -> Bounds<Pixels> {
665    let side = px(side);
666    Bounds::new(center - point(side / 2., side / 2.), size(side, side))
667}
668
669fn stop_bounds(
670    bounds: Bounds<Pixels>,
671    requested: f32,
672    wavy: bool,
673    direction: Direction,
674) -> Bounds<Pixels> {
675    let width = f32::from(bounds.size.width);
676    let side = requested.min(width).min(f32::from(bounds.size.height));
677    let inset = (side / 2. + if wavy { LINEAR_AMPLITUDE } else { 0. }).min(width / 2.);
678    let x = bounds.left() + px(logical_x(width - inset, width, direction));
679    centered_square(point(x, bounds.center().y), side)
680}
681
682fn paint_marker(bounds: Bounds<Pixels>, color: Hsla, cap: ProgressCap, window: &mut Window) {
683    let radius = if cap == ProgressCap::Round {
684        bounds.size.height / 2.
685    } else {
686        px(0.)
687    };
688    window.paint_quad(gpui::quad(
689        bounds,
690        radius,
691        color,
692        px(0.),
693        gpui::transparent_black(),
694        gpui::BorderStyle::Solid,
695    ));
696}
697
698fn paint_stop(
699    stop: ProgressStop,
700    painter: Option<&StopPainter>,
701    window: &mut Window,
702    cx: &mut App,
703) {
704    if let Some(painter) = painter {
705        window.with_content_mask(
706            Some(ContentMask {
707                bounds: stop.bounds,
708            }),
709            |window| {
710                painter(stop, window, cx);
711            },
712        );
713    } else {
714        paint_marker(stop.bounds, stop.color, stop.cap, window);
715    }
716}
717/// Horizontal progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
718#[derive(IntoElement)]
719pub struct LinearProgress(Progress);
720
721/// Circular progress. Supply a fraction from 0 to 1, or omit it for indeterminate progress.
722#[derive(IntoElement)]
723pub struct CircularProgress(Progress);
724
725impl LinearProgress {
726    /// Sets the determinate stop marker's size. Zero hides the marker.
727    pub fn stop_size(mut self, size: Pixels) -> Self {
728        self.0.stop_size = nonnegative_length(size).unwrap_or(STOP_SIZE);
729        self
730    }
731
732    /// Replaces the determinate stop marker's paint within its clipped bounds.
733    pub fn draw_stop_indicator(
734        mut self,
735        draw: impl Fn(ProgressStop, &mut Window, &mut App) + 'static,
736    ) -> Self {
737        self.0.stop_painter = Some(Box::new(draw));
738        self
739    }
740}
741
742macro_rules! progress_api {
743    ($name:ident, $circular:literal) => {
744        impl $name {
745            pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
746                Self(Progress::new(id, name))
747            }
748
749            pub fn value(mut self, value: f32) -> Self {
750                self.0.value = Some(value);
751                self
752            }
753
754            /// Clears the measured value and shows indeterminate progress.
755            pub fn indeterminate(mut self) -> Self {
756                self.0.value = None;
757                self
758            }
759
760            pub fn shape(mut self, shape: ProgressShape) -> Self {
761                self.0.shape = shape;
762                self
763            }
764
765            pub fn active_stroke(mut self, stroke: ProgressStroke) -> Self {
766                self.0.active = stroke;
767                self
768            }
769
770            pub fn track_stroke(mut self, stroke: ProgressStroke) -> Self {
771                self.0.track = stroke;
772                self
773            }
774
775            /// Sets the painted gap between the active stroke and the track.
776            pub fn gap(mut self, gap: Pixels) -> Self {
777                self.0.gap = nonnegative_length(gap).unwrap_or(TRACK_GAP);
778                self
779            }
780
781            /// Sets a fraction of the available height or radius for the wave.
782            pub fn wave_amplitude(self, fraction: f32) -> Self {
783                self.wave_amplitude_by(move |_| fraction)
784            }
785
786            /// Computes the wave amplitude from displayed progress. In
787            /// indeterminate mode the function receives zero.
788            pub fn wave_amplitude_by(mut self, amplitude: impl Fn(f32) -> f32 + 'static) -> Self {
789                self.0.amplitude = Some(Box::new(amplitude));
790                self
791            }
792
793            /// Sets crest spacing in logical pixels.
794            pub fn wavelength(mut self, length: Pixels) -> Self {
795                self.0.wavelength = nonnegative_length(length).filter(|length| *length > 0.);
796                self
797            }
798
799            /// Sets travel speed in logical pixels per second. Zero holds the phase.
800            pub fn wave_speed(mut self, length_per_second: Pixels) -> Self {
801                self.0.wave_speed = nonnegative_length(length_per_second);
802                self
803            }
804        }
805
806        impl RenderOnce for $name {
807            fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
808                self.0.render($circular, window, cx)
809            }
810        }
811    };
812}
813
814progress_api!(LinearProgress, false);
815progress_api!(CircularProgress, true);
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820
821    #[test]
822    fn rounded_progress_endpoints_and_stop_stay_inside_the_track() {
823        assert_eq!(linear_position(100., 2., 0.), 2.);
824        assert_eq!(linear_position(100., 2., 1.), 98.);
825        assert_eq!(linear_position(100., 2., 0.5), 50.);
826        assert_eq!(linear_position(1., 40., 0.), 0.5);
827        assert_eq!(linear_position(1., 40., 1.), 0.5);
828        for (width, height, wavy) in [(100., 4., false), (100., 10., true), (1., 2., false)] {
829            let track = Bounds::new(point(px(0.), px(0.)), size(px(width), px(height)));
830            let ltr = stop_bounds(track, 4., wavy, Direction::Ltr);
831            let rtl = stop_bounds(track, 4., wavy, Direction::Rtl);
832            assert_eq!(ltr.center().x + rtl.center().x, px(width));
833            assert!(ltr.right() <= px(width) && rtl.left() >= px(0.));
834            let oversized = stop_bounds(track, f32::MAX, wavy, Direction::Ltr);
835            assert!(oversized.right() <= px(width) && oversized.size.height <= px(height));
836        }
837    }
838
839    #[test]
840    fn determinate_wave_is_flat_at_both_ends_of_the_range() {
841        for value in [0., 0.05, 0.1, 0.95, 0.99, 1.] {
842            assert_eq!(wave_amplitude(value), 0.);
843        }
844        for value in [0.11, 0.5, 0.94] {
845            assert_eq!(wave_amplitude(value), 1.);
846        }
847    }
848
849    #[test]
850    fn indeterminate_keyframes_use_both_linear_segments_and_periodic_rotation() {
851        assert_eq!(linear_indeterminate(0.), [(0., 0.); 2]);
852        let [(start, end), (second_start, second_end)] = linear_indeterminate(800.);
853        assert!(0. < start && start < end && end < 1.);
854        assert_eq!(second_start, 0.);
855        assert!(second_end > 0.);
856        assert_eq!(linear_indeterminate(2550.), linear_indeterminate(800.));
857        assert_eq!(circular_indeterminate(0.), (0., 0.1));
858        assert_eq!(circular_indeterminate(6000.), (4., 0.1));
859        assert_eq!(circular_indeterminate(3000.).1, 0.87);
860    }
861
862    #[test]
863    fn circular_wavelengths_close_at_the_seam_and_bound_tessellation() {
864        assert_eq!(circular_wave_count(20., 15.), 8.);
865        assert_eq!(circular_wave_count(20., 23.), 5.);
866        assert_eq!(circular_wave_count(20., f32::MAX), 1.);
867        assert_eq!(circular_wave_count(20., f32::MIN_POSITIVE), MAX_WAVES);
868        for wavelength in [1., 6.4, 15., 23., 200.] {
869            let cycles = circular_wave_count(20., wavelength);
870            let start = wave_offset(1.6, 0., 0.75);
871            let end = wave_offset(1.6, cycles, 0.75);
872            assert_eq!(start, end);
873        }
874    }
875
876    #[test]
877    fn progress_motion_holds_phase_while_paused_and_resumes_without_elapsed_idle_time() {
878        use std::time::Duration;
879        let now = Instant::now();
880        let at = |millis| now + Duration::from_millis(millis);
881        let mut motion = ProgressMotion::default();
882        assert_eq!(motion.sample(at(0), true, 2., false, true), (0., 0.));
883        assert_eq!(motion.sample(at(125), true, 2., false, true), (125., 0.25));
884        assert_eq!(
885            motion.sample(at(125), false, 0., false, false),
886            (125., 0.25)
887        );
888        assert_eq!(motion.sample(at(1000), true, 1., false, true), (125., 0.25));
889        assert_eq!(motion.sample(at(1250), true, 1., false, true), (375., 0.5));
890        assert_eq!(motion.sample(at(1300), false, 0., true, false), (0., 0.));
891    }
892
893    #[test]
894    fn invalid_stroke_settings_keep_defaults_while_zero_disables_stroke() {
895        let default_color = gpui::white();
896        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.] {
897            let style = ProgressStroke {
898                width: Some(px(invalid)),
899                ..Default::default()
900            };
901            let stroke = Stroke::resolve(style, default_color);
902            assert_eq!(stroke.width, STROKE_WIDTH);
903            assert_eq!(stroke.color, default_color);
904            assert!(nonnegative_length(px(invalid)).is_none());
905        }
906        assert_eq!(nonnegative_length(px(0.)), Some(0.));
907        assert_eq!(normalized_amplitude(f32::NAN), 0.);
908        assert_eq!(normalized_amplitude(f32::NEG_INFINITY), 0.);
909        assert_eq!(normalized_amplitude(f32::INFINITY), 1.);
910    }
911}