1mod motion;
2mod paint;
3
4use gpui::{
5 App, Bounds, ContentMask, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce,
6 SharedString, Styled, Window, canvas, px,
7};
8use gpui_material_foundation::{animate, color, current_material_theme, is_bounds_visible};
9use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed};
10
11use motion::{ProgressMotion, circular_indeterminate, linear_indeterminate};
12use paint::{ProgressPaint, Stroke, paint_stop, stop_bounds};
13
14const STROKE_WIDTH: f32 = 4.;
15const TRACK_GAP: f32 = 4.;
16const STOP_SIZE: f32 = 4.;
17const LINEAR_AMPLITUDE: f32 = 3.;
18const CIRCULAR_AMPLITUDE: f32 = 1.6;
19const CIRCULAR_WAVELENGTH: f32 = 15.;
20const MAX_WAVES: f32 = 128.;
21
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum ProgressShape {
25 #[default]
26 Straight,
27 Wavy,
28}
29
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub enum ProgressCap {
33 #[default]
34 Round,
35 Butt,
36 Square,
37}
38
39#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct ProgressStroke {
43 pub width: Option<Pixels>,
44 pub color: Option<Hsla>,
45 pub cap: ProgressCap,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct ProgressStop {
51 pub bounds: Bounds<Pixels>,
52 pub color: Hsla,
53 pub cap: ProgressCap,
54 pub direction: Direction,
55}
56
57type StopPainter = dyn Fn(ProgressStop, &mut Window, &mut App);
58
59struct Progress {
60 id: ElementId,
61 name: SharedString,
62 value: Option<f32>,
63 shape: ProgressShape,
64 active: ProgressStroke,
65 track: ProgressStroke,
66 gap: f32,
67 stop_size: f32,
68 stop_painter: Option<Box<StopPainter>>,
69 amplitude: Option<Box<dyn Fn(f32) -> f32>>,
70 wavelength: Option<f32>,
71 wave_speed: Option<f32>,
72}
73
74impl Progress {
75 fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
76 Self {
77 id: id.into(),
78 name: name.into(),
79 value: None,
80 shape: ProgressShape::default(),
81 active: ProgressStroke::default(),
82 track: ProgressStroke::default(),
83 gap: TRACK_GAP,
84 stop_size: STOP_SIZE,
85 stop_painter: None,
86 amplitude: None,
87 wavelength: None,
88 wave_speed: None,
89 }
90 }
91
92 fn render(self, circular: bool, window: &mut Window, cx: &mut App) -> impl IntoElement {
93 let theme = current_material_theme(window, cx);
94 let active = Stroke::resolve(self.active, color(theme.colors.color(ColorRole::Primary)));
95 let track = Stroke::resolve(
96 self.track,
97 color(theme.colors.color(ColorRole::SecondaryContainer)),
98 );
99 let reduced = cx.reduce_motion();
100 let window_active = window.is_window_active();
101 let effects = theme.motion.spec(
102 MotionKind::Effects,
103 MotionSpeed::Default,
104 reduced || !window_active,
105 );
106 let spatial = theme.motion.spec(
107 MotionKind::Spatial,
108 MotionSpeed::Default,
109 reduced || !window_active,
110 );
111 let direction = theme.layout.direction;
112 let value = self
113 .value
114 .filter(|v| v.is_finite())
115 .map(|v| v.clamp(0., 1.));
116 let measured = value.is_some();
117 let motion = window.use_keyed_state((self.id.clone(), "progress-motion"), cx, |_, _| {
118 ProgressMotion::new(value.unwrap_or(0.4))
119 });
120 let target = motion.update(cx, |state, _| {
121 if let Some(value) = value {
122 state.last_measured = value;
123 }
124 state.last_measured
125 });
126 let mode = animate(
127 (self.id.clone(), "indeterminate-mix"),
128 f32::from(!measured),
129 effects,
130 window,
131 cx,
132 )
133 .clamp(0., 1.);
134 let measured_value = animate(
135 (self.id.clone(), "determinate-value"),
136 target,
137 spatial,
138 window,
139 cx,
140 )
141 .clamp(0., 1.);
142 let wavy = self.shape == ProgressShape::Wavy;
143 let amplitude = if wavy {
144 let endpoint = mode == 0. && (measured_value == 0. || measured_value == 1.);
145 let default_target = wave_amplitude(measured_value) * (1. - mode) + mode;
146 let target = self.amplitude.as_ref().map_or(default_target, |amplitude| {
147 normalized_amplitude(amplitude(if measured { measured_value } else { 0. }))
148 });
149 animate(
150 (self.id.clone(), "wave-amplitude"),
151 if endpoint { 0. } else { target },
152 if endpoint {
153 MotionSpec::Instant
154 } else {
155 effects
156 },
157 window,
158 cx,
159 )
160 .clamp(0., 1.)
161 } else {
162 0.
163 };
164 let wavelength = self.wavelength.unwrap_or(if circular {
165 CIRCULAR_WAVELENGTH
166 } else {
167 40. - 20. * mode
168 });
169 let hz = self
170 .wave_speed
171 .map_or(1., |speed| f64::from(speed) / f64::from(wavelength));
172 let motion_enabled = window_active && window.is_visible() && !reduced && active.width > 0.;
173 let animate_loop = motion_enabled && !measured;
174 let animate_wave =
175 motion_enabled && hz > 0. && amplitude > 0. && (mode > 0. || measured_value > 0.);
176 let now = cx.background_executor().now();
177 let (loop_time, phase) = motion.update(cx, |state, _| {
178 let visible = state.visible;
179 state.sample(
180 now,
181 animate_loop && visible,
182 if animate_wave && visible { hz } else { 0. },
183 reduced,
184 mode == 1.,
185 )
186 });
187 let motionless = reduced || !window_active && loop_time == 0.;
188 let (arc_start, arc_length) = if circular && mode > 0. && !motionless {
189 circular_indeterminate(loop_time)
190 } else {
191 (0., 0.25)
192 };
193 let arc_origin = motion.update(cx, |state, _| {
194 if mode == 0. || mode == 1. || motionless {
195 state.arc_origin = arc_start.round();
196 }
197 state.arc_origin
198 });
199 let arc = (
200 (arc_start - arc_origin) * mode,
201 measured_value + (arc_length - measured_value) * mode,
202 );
203 let [first, second] = if circular || mode == 0. || motionless {
204 [(0.25, 0.65), (0., 0.)]
205 } else {
206 linear_indeterminate(loop_time)
207 };
208 let mut lines = [
209 (
210 first.0 * mode,
211 measured_value + (first.1 - measured_value) * mode,
212 ),
213 (second.0, second.0 + (second.1 - second.0) * mode),
214 ];
215 lines.sort_by(|left, right| left.0.total_cmp(&right.0));
216
217 let wave_space = if wavy { 2. * LINEAR_AMPLITUDE } else { 0. };
218 let side = if circular {
219 if wavy { 48. } else { 40. }
220 } else {
221 STROKE_WIDTH
222 .max(active.width)
223 .max(track.width)
224 .max(self.stop_size)
225 + wave_space
226 };
227 let picture = canvas(
228 |_, _, _| (),
229 move |bounds, _, window, cx| {
230 let width = f32::from(bounds.size.width);
231 let height = f32::from(bounds.size.height);
232 let visible = width.is_finite()
233 && height.is_finite()
234 && width > 0.
235 && height > 0.
236 && is_bounds_visible(bounds, window);
237 let now = cx.background_executor().now();
238 motion.update(cx, |state, _| state.set_visible(visible, now));
239 if !visible {
240 return;
241 }
242 window.with_content_mask(Some(ContentMask { bounds }), |window| {
243 let paint = ProgressPaint {
244 active,
245 track,
246 gap: self.gap,
247 wavelength,
248 amplitude,
249 phase,
250 };
251 if circular {
252 paint.circular(bounds, arc, wavy, window);
253 } else {
254 paint.linear(bounds, lines, direction, window);
255 if measured && self.stop_size > 0. {
256 let stop = ProgressStop {
257 bounds: stop_bounds(bounds, self.stop_size, wavy, direction),
258 color: active.color,
259 cap: active.cap,
260 direction,
261 };
262 paint_stop(stop, self.stop_painter.as_deref(), window, cx);
263 }
264 }
265 });
266 if animate_loop || animate_wave {
267 window.request_animation_frame();
268 }
269 },
270 )
271 .size_full();
272 let mut element = gpui_base::Progress::new(self.id)
273 .value(value.unwrap_or_default() * 100.)
274 .indeterminate(!measured)
275 .accessibility_label(self.name)
276 .h(px(side))
277 .child(picture);
278 if circular {
279 element = element.w(px(side)).flex_none();
280 } else {
281 element = element.w_full();
282 }
283 element
284 }
285}
286
287fn nonnegative_length(value: Pixels) -> Option<f32> {
288 let length = f32::from(value);
289 (length.is_finite() && length >= 0.).then_some(length)
290}
291
292fn normalized_amplitude(amplitude: f32) -> f32 {
293 if amplitude.is_nan() {
294 0.
295 } else {
296 amplitude.clamp(0., 1.)
297 }
298}
299
300fn wave_amplitude(progress: f32) -> f32 {
301 f32::from(progress > 0.1 && progress < 0.95)
304}
305
306#[derive(IntoElement)]
308pub struct LinearProgress(Progress);
309
310#[derive(IntoElement)]
312pub struct CircularProgress(Progress);
313
314impl LinearProgress {
315 pub fn stop_size(mut self, size: Pixels) -> Self {
317 self.0.stop_size = nonnegative_length(size).unwrap_or(STOP_SIZE);
318 self
319 }
320
321 pub fn draw_stop_indicator(
323 mut self,
324 draw: impl Fn(ProgressStop, &mut Window, &mut App) + 'static,
325 ) -> Self {
326 self.0.stop_painter = Some(Box::new(draw));
327 self
328 }
329}
330
331macro_rules! progress_api {
332 ($name:ident, $circular:literal) => {
333 impl $name {
334 pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
335 Self(Progress::new(id, name))
336 }
337
338 pub fn value(mut self, value: f32) -> Self {
339 self.0.value = Some(value);
340 self
341 }
342
343 pub fn indeterminate(mut self) -> Self {
345 self.0.value = None;
346 self
347 }
348
349 pub fn shape(mut self, shape: ProgressShape) -> Self {
350 self.0.shape = shape;
351 self
352 }
353
354 pub fn active_stroke(mut self, stroke: ProgressStroke) -> Self {
355 self.0.active = stroke;
356 self
357 }
358
359 pub fn track_stroke(mut self, stroke: ProgressStroke) -> Self {
360 self.0.track = stroke;
361 self
362 }
363
364 pub fn gap(mut self, gap: Pixels) -> Self {
366 self.0.gap = nonnegative_length(gap).unwrap_or(TRACK_GAP);
367 self
368 }
369
370 pub fn wave_amplitude(self, fraction: f32) -> Self {
372 self.wave_amplitude_by(move |_| fraction)
373 }
374
375 pub fn wave_amplitude_by(mut self, amplitude: impl Fn(f32) -> f32 + 'static) -> Self {
378 self.0.amplitude = Some(Box::new(amplitude));
379 self
380 }
381
382 pub fn wavelength(mut self, length: Pixels) -> Self {
384 self.0.wavelength = nonnegative_length(length).filter(|length| *length > 0.);
385 self
386 }
387
388 pub fn wave_speed(mut self, length_per_second: Pixels) -> Self {
390 self.0.wave_speed = nonnegative_length(length_per_second);
391 self
392 }
393 }
394
395 impl RenderOnce for $name {
396 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
397 self.0.render($circular, window, cx)
398 }
399 }
400 };
401}
402
403progress_api!(LinearProgress, false);
404progress_api!(CircularProgress, true);