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 crate::SemanticTone;
12use motion::{ProgressMotion, circular_indeterminate, linear_indeterminate};
13use paint::{ProgressPaint, Stroke, paint_stop, stop_bounds};
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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum ProgressShape {
26 #[default]
28 Straight,
29 Wavy,
31}
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
35pub enum ProgressCap {
36 #[default]
38 Round,
39 Butt,
41 Square,
43}
44
45#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct ProgressStroke {
49 pub width: Option<Pixels>,
51 pub color: Option<Hsla>,
53 pub cap: ProgressCap,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct ProgressStop {
60 pub bounds: Bounds<Pixels>,
62 pub color: Hsla,
64 pub cap: ProgressCap,
66 pub direction: Direction,
68}
69
70type StopPainter = dyn Fn(ProgressStop, &mut Window, &mut App);
71
72fn progress_tone_roles(tone: SemanticTone) -> (ColorRole, ColorRole) {
73 tone.roles().map_or(
74 (ColorRole::Primary, ColorRole::SecondaryContainer),
75 |(role, _, container, _)| (role, container),
76 )
77}
78
79struct Progress {
80 id: ElementId,
81 name: SharedString,
82 value: Option<f32>,
83 shape: ProgressShape,
84 tone: SemanticTone,
85 active: ProgressStroke,
86 track: ProgressStroke,
87 gap: f32,
88 stop_size: f32,
89 stop_painter: Option<Box<StopPainter>>,
90 amplitude: Option<Box<dyn Fn(f32) -> f32>>,
91 wavelength: Option<f32>,
92 wave_speed: Option<f32>,
93}
94
95impl Progress {
96 fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
97 Self {
98 id: id.into(),
99 name: name.into(),
100 value: None,
101 shape: ProgressShape::default(),
102 tone: SemanticTone::Default,
103 active: ProgressStroke::default(),
104 track: ProgressStroke::default(),
105 gap: TRACK_GAP,
106 stop_size: STOP_SIZE,
107 stop_painter: None,
108 amplitude: None,
109 wavelength: None,
110 wave_speed: None,
111 }
112 }
113
114 fn render(self, circular: bool, window: &mut Window, cx: &mut App) -> impl IntoElement {
115 let theme = current_material_theme(window, cx);
116 let (active_role, track_role) = progress_tone_roles(self.tone);
117 let active = Stroke::resolve(self.active, color(theme.colors.color(active_role)));
118 let track = Stroke::resolve(self.track, color(theme.colors.color(track_role)));
119 let reduced = cx.reduce_motion();
120 let window_active = window.is_window_active();
121 let effects = theme.motion.spec(
122 MotionKind::Effects,
123 MotionSpeed::Default,
124 reduced || !window_active,
125 );
126 let spatial = theme.motion.spec(
127 MotionKind::Spatial,
128 MotionSpeed::Default,
129 reduced || !window_active,
130 );
131 let direction = theme.layout.direction;
132 let value = self
133 .value
134 .filter(|v| v.is_finite())
135 .map(|v| v.clamp(0., 1.));
136 let measured = value.is_some();
137 let motion = window.use_keyed_state((self.id.clone(), "progress-motion"), cx, |_, _| {
138 ProgressMotion::new(value.unwrap_or(0.4))
139 });
140 let target = motion.update(cx, |state, _| {
141 if let Some(value) = value {
142 state.last_measured = value;
143 }
144 state.last_measured
145 });
146 let mode = animate(
147 (self.id.clone(), "indeterminate-mix"),
148 f32::from(!measured),
149 effects,
150 window,
151 cx,
152 )
153 .clamp(0., 1.);
154 let measured_value = animate(
155 (self.id.clone(), "determinate-value"),
156 target,
157 spatial,
158 window,
159 cx,
160 )
161 .clamp(0., 1.);
162 let wavy = self.shape == ProgressShape::Wavy;
163 let amplitude = if wavy {
164 let endpoint = mode == 0. && (measured_value == 0. || measured_value == 1.);
165 let default_target = wave_amplitude(measured_value) * (1. - mode) + mode;
166 let target = self.amplitude.as_ref().map_or(default_target, |amplitude| {
167 normalized_amplitude(amplitude(if measured { measured_value } else { 0. }))
168 });
169 animate(
170 (self.id.clone(), "wave-amplitude"),
171 if endpoint { 0. } else { target },
172 if endpoint {
173 MotionSpec::Instant
174 } else {
175 effects
176 },
177 window,
178 cx,
179 )
180 .clamp(0., 1.)
181 } else {
182 0.
183 };
184 let wavelength = self.wavelength.unwrap_or(if circular {
185 CIRCULAR_WAVELENGTH
186 } else {
187 40. - 20. * mode
188 });
189 let hz = self
190 .wave_speed
191 .map_or(1., |speed| f64::from(speed) / f64::from(wavelength));
192 let motion_enabled = window_active && window.is_visible() && !reduced && active.width > 0.;
193 let animate_loop = motion_enabled && !measured;
194 let animate_wave =
195 motion_enabled && hz > 0. && amplitude > 0. && (mode > 0. || measured_value > 0.);
196 let now = cx.background_executor().now();
197 let (loop_time, phase) = motion.update(cx, |state, _| {
198 let visible = state.visible;
199 state.sample(
200 now,
201 animate_loop && visible,
202 if animate_wave && visible { hz } else { 0. },
203 reduced,
204 mode == 1.,
205 )
206 });
207 let motionless = reduced || !window_active && loop_time == 0.;
208 let (arc_start, arc_length) = if circular && mode > 0. && !motionless {
209 circular_indeterminate(loop_time)
210 } else {
211 (0., 0.25)
212 };
213 let arc_origin = motion.update(cx, |state, _| {
214 if mode == 0. || mode == 1. || motionless {
215 state.arc_origin = arc_start.round();
216 }
217 state.arc_origin
218 });
219 let arc = (
220 (arc_start - arc_origin) * mode,
221 measured_value + (arc_length - measured_value) * mode,
222 );
223 let [first, second] = if circular || mode == 0. || motionless {
224 [(0.25, 0.65), (0., 0.)]
225 } else {
226 linear_indeterminate(loop_time)
227 };
228 let mut lines = [
229 (
230 first.0 * mode,
231 measured_value + (first.1 - measured_value) * mode,
232 ),
233 (second.0, second.0 + (second.1 - second.0) * mode),
234 ];
235 lines.sort_by(|left, right| left.0.total_cmp(&right.0));
236
237 let wave_space = if wavy { 2. * LINEAR_AMPLITUDE } else { 0. };
238 let side = if circular {
239 if wavy { 48. } else { 40. }
240 } else {
241 STROKE_WIDTH
242 .max(active.width)
243 .max(track.width)
244 .max(self.stop_size)
245 + wave_space
246 };
247 let picture = canvas(
248 |_, _, _| (),
249 move |bounds, _, window, cx| {
250 let width = f32::from(bounds.size.width);
251 let height = f32::from(bounds.size.height);
252 let visible = width.is_finite()
253 && height.is_finite()
254 && width > 0.
255 && height > 0.
256 && is_bounds_visible(bounds, window);
257 let now = cx.background_executor().now();
258 motion.update(cx, |state, _| state.set_visible(visible, now));
259 if !visible {
260 return;
261 }
262 window.with_content_mask(Some(ContentMask { bounds }), |window| {
263 let paint = ProgressPaint {
264 active,
265 track,
266 gap: self.gap,
267 wavelength,
268 amplitude,
269 phase,
270 };
271 if circular {
272 paint.circular(bounds, arc, wavy, window);
273 } else {
274 paint.linear(bounds, lines, direction, window);
275 if measured && self.stop_size > 0. {
276 let stop = ProgressStop {
277 bounds: stop_bounds(bounds, self.stop_size, wavy, direction),
278 color: active.color,
279 cap: active.cap,
280 direction,
281 };
282 paint_stop(stop, self.stop_painter.as_deref(), window, cx);
283 }
284 }
285 });
286 if animate_loop || animate_wave {
287 window.request_animation_frame();
288 }
289 },
290 )
291 .size_full();
292 let mut element = gpui_base::Progress::new(self.id)
293 .value(value.unwrap_or_default() * 100.)
294 .indeterminate(!measured)
295 .accessibility_label(self.name)
296 .h(px(side))
297 .child(picture);
298 if circular {
299 element = element.w(px(side)).flex_none();
300 } else {
301 element = element.w_full();
302 }
303 element
304 }
305}
306
307fn nonnegative_length(value: Pixels) -> Option<f32> {
308 let length = f32::from(value);
309 (length.is_finite() && length >= 0.).then_some(length)
310}
311
312fn normalized_amplitude(amplitude: f32) -> f32 {
313 if amplitude.is_nan() {
314 0.
315 } else {
316 amplitude.clamp(0., 1.)
317 }
318}
319
320fn wave_amplitude(progress: f32) -> f32 {
321 f32::from(progress > 0.1 && progress < 0.95)
324}
325
326#[derive(IntoElement)]
328pub struct LinearProgress(Progress);
329
330#[derive(IntoElement)]
332pub struct CircularProgress(Progress);
333
334impl LinearProgress {
335 pub fn stop_size(mut self, size: Pixels) -> Self {
337 self.0.stop_size = nonnegative_length(size).unwrap_or(STOP_SIZE);
338 self
339 }
340
341 pub fn draw_stop_indicator(
343 mut self,
344 draw: impl Fn(ProgressStop, &mut Window, &mut App) + 'static,
345 ) -> Self {
346 self.0.stop_painter = Some(Box::new(draw));
347 self
348 }
349}
350
351macro_rules! progress_api {
352 ($name:ident, $circular:literal) => {
353 impl $name {
354 pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
356 Self(Progress::new(id, name))
357 }
358
359 pub fn value(mut self, value: f32) -> Self {
361 self.0.value = Some(value);
362 self
363 }
364
365 pub fn indeterminate(mut self) -> Self {
367 self.0.value = None;
368 self
369 }
370
371 pub fn shape(mut self, shape: ProgressShape) -> Self {
373 self.0.shape = shape;
374 self
375 }
376
377 pub fn tone(mut self, tone: SemanticTone) -> Self {
380 self.0.tone = tone;
381 self
382 }
383
384 pub fn active_stroke(mut self, stroke: ProgressStroke) -> Self {
386 self.0.active = stroke;
387 self
388 }
389
390 pub fn track_stroke(mut self, stroke: ProgressStroke) -> Self {
392 self.0.track = stroke;
393 self
394 }
395
396 pub fn gap(mut self, gap: Pixels) -> Self {
398 self.0.gap = nonnegative_length(gap).unwrap_or(TRACK_GAP);
399 self
400 }
401
402 pub fn wave_amplitude(self, fraction: f32) -> Self {
404 self.wave_amplitude_by(move |_| fraction)
405 }
406
407 pub fn wave_amplitude_by(mut self, amplitude: impl Fn(f32) -> f32 + 'static) -> Self {
410 self.0.amplitude = Some(Box::new(amplitude));
411 self
412 }
413
414 pub fn wavelength(mut self, length: Pixels) -> Self {
416 self.0.wavelength = nonnegative_length(length).filter(|length| *length > 0.);
417 self
418 }
419
420 pub fn wave_speed(mut self, length_per_second: Pixels) -> Self {
422 self.0.wave_speed = nonnegative_length(length_per_second);
423 self
424 }
425 }
426
427 impl RenderOnce for $name {
428 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
429 self.0.render($circular, window, cx)
430 }
431 }
432 };
433}
434
435progress_api!(LinearProgress, false);
436progress_api!(CircularProgress, true);
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn progress_tone_roles_map_semantic_tones() {
444 use ColorRole::*;
445 assert_eq!(
446 progress_tone_roles(SemanticTone::Default),
447 (Primary, SecondaryContainer)
448 );
449 assert_eq!(
450 progress_tone_roles(SemanticTone::Danger),
451 (Error, ErrorContainer)
452 );
453 assert_eq!(
454 progress_tone_roles(SemanticTone::Success),
455 (Success, SuccessContainer)
456 );
457 assert_eq!(
458 progress_tone_roles(SemanticTone::Warning),
459 (Warning, WarningContainer)
460 );
461 assert_eq!(
462 progress_tone_roles(SemanticTone::Info),
463 (Info, InfoContainer)
464 );
465 }
466}