Skip to main content

rust_glass/widgets/
progress.rs

1//! Progress bar, gauge and spinner.
2
3use std::f32::consts::TAU;
4
5use crate::accessibility::Role;
6use crate::animation::Tuning;
7use crate::color::Color;
8use crate::context::{Response, Sense};
9use crate::geometry::{Rect, Vec2, vec2};
10use crate::material::Corner;
11use crate::text::{TextStyle, Weight};
12use crate::ui::{Ui, Widget};
13
14/// A bar that fills from left to right: a flat capsule in one color on a
15/// quiet track, as on iOS. Progress bars are not glass.
16pub struct ProgressBar {
17    value: f32,
18    height: f32,
19    tint: Option<Color>,
20    track: Option<Color>,
21}
22
23impl ProgressBar {
24    /// Creates a bar filled to `value`, from 0 to 1.
25    pub fn new(value: f32) -> Self {
26        Self { value, height: 6.0, tint: None, track: None }
27    }
28    /// Sets the height in points. The default is 6.
29    pub fn height(mut self, height: f32) -> Self {
30        self.height = height;
31        self
32    }
33    /// Sets the fill color. The default is the theme accent.
34    pub fn tint(mut self, color: Color) -> Self {
35        self.tint = Some(color);
36        self
37    }
38    /// Sets the color of the unfilled track. The default is the strong fill
39    /// of the surface below.
40    pub fn track(mut self, color: Color) -> Self {
41        self.track = Some(color);
42        self
43    }
44}
45
46impl Widget for ProgressBar {
47    fn ui(self, ui: &mut Ui) -> Response {
48        let w = ui.available_width().clamp(60.0, 460.0);
49        let r = ui.allocate_response(vec2(w, self.height), Sense::Hover);
50        if let Some(n) = ui.access(r.id, Role::ProgressIndicator, r.rect) {
51            n.numeric(self.value.clamp(0.0, 1.0) as f64, 0.0, 1.0, None);
52        }
53        let v = ui.ctx.animate(r.id, self.value.clamp(0.0, 1.0), Tuning::new(0.5, 1.0));
54        let fill = self.tint.unwrap_or(ui.ctx.theme.accent);
55        let track = self.track.unwrap_or(ui.surface.strong_fill_color());
56        let mut p = ui.painter();
57        p.fill(r.rect, Corner::Capsule, track);
58        if v > 0.0005 {
59            // Below the height of the bar the fill shrinks into a dot rather
60            // than squashing its round ends.
61            let fw = r.rect.width() * v;
62            let h = self.height.min(fw.max(self.height * 0.5));
63            let bar =
64                Rect::from_min_size(vec2(r.rect.min.x, r.rect.center().y - h * 0.5), vec2(fw.max(h), h));
65            p.fill(bar, Corner::Capsule, fill);
66        }
67        r
68    }
69}
70
71/// A ring that fills clockwise, with a short label in the middle.
72///
73/// The label shrinks until it fits inside the ring with
74/// [`Gauge::label_padding`] to spare, so long words never touch it.
75pub struct Gauge<'a> {
76    value: f32,
77    size: f32,
78    label: &'a str,
79    tint: Color,
80    thickness: Option<f32>,
81    label_size: Option<f32>,
82    padding: Option<f32>,
83}
84
85impl<'a> Gauge<'a> {
86    /// Creates a ring filled to `value`, from 0 to 1.
87    pub fn new(value: f32, label: &'a str) -> Self {
88        Self {
89            value,
90            size: 64.0,
91            label,
92            tint: Color::GREEN,
93            thickness: None,
94            label_size: None,
95            padding: None,
96        }
97    }
98    /// Sets the diameter in points. The default is 64.
99    pub fn size(mut self, size: f32) -> Self {
100        self.size = size;
101        self
102    }
103    /// Sets the fill color. The default is green.
104    pub fn tint(mut self, color: Color) -> Self {
105        self.tint = color;
106        self
107    }
108    /// Sets the width of the ring in points. The default is 11 percent of
109    /// the diameter.
110    pub fn thickness(mut self, thickness: f32) -> Self {
111        self.thickness = Some(thickness);
112        self
113    }
114    /// Sets the largest font size of the label in points. The default is 22
115    /// percent of the diameter. Labels that do not fit are drawn smaller.
116    pub fn label_size(mut self, size: f32) -> Self {
117        self.label_size = Some(size);
118        self
119    }
120    /// Sets the space kept between the label and the inside of the ring, in
121    /// points. The default is 9 percent of the diameter.
122    pub fn label_padding(mut self, padding: f32) -> Self {
123        self.padding = Some(padding);
124        self
125    }
126}
127
128/// Smallest label size a gauge shrinks to, in points.
129const MIN_GAUGE_LABEL: f32 = 7.0;
130
131impl Widget for Gauge<'_> {
132    fn ui(self, ui: &mut Ui) -> Response {
133        let r = ui.allocate_response(Vec2::splat(self.size), Sense::Hover);
134        if let Some(n) = ui.access(r.id, Role::Meter, r.rect) {
135            n.label(self.label).numeric(self.value.clamp(0.0, 1.0) as f64, 0.0, 1.0, None);
136        }
137        let v = ui.ctx.animate(r.id, self.value.clamp(0.0, 1.0), Tuning::new(0.6, 0.85));
138        let radius = self.size * 0.5;
139        let w = self.thickness.unwrap_or(self.size * 0.11).clamp(1.0, radius * 0.6);
140        let pad = self.padding.unwrap_or(self.size * 0.09).max(0.0);
141        let room = (radius - w - pad).max(1.0);
142        let l = fit_label(ui, self.label, self.label_size.unwrap_or(self.size * 0.22), room);
143        let (track, tc) = (ui.surface.fill_color(), ui.surface.text_color());
144        let center = r.rect.center();
145        let mut p = ui.painter();
146        p.arc(center, radius, w, 0.0, TAU, track, track);
147        if v > 0.001 {
148            // The round caps stick out by half the width at both ends. Keep
149            // a small gap between them when the ring is nearly full.
150            let cap = w / (radius - w * 0.5);
151            let sweep = (v * TAU).min(TAU - cap * 0.35);
152            p.arc(center, radius, w, -TAU / 4.0, sweep, self.tint.lerp(Color::WHITE, 0.2), self.tint);
153        }
154        p.text_centered(r.rect, &l, tc, 1.0);
155        r
156    }
157}
158
159/// Lays out `text` at `size`, or smaller until its box fits in a circle of
160/// `room` points radius.
161fn fit_label(ui: &mut Ui, text: &str, size: f32, room: f32) -> std::rc::Rc<crate::text::TextLayout> {
162    let style = |s: f32| TextStyle::new(s).weight(Weight::Semibold);
163    let l = ui.layout_text(text, &style(size));
164    // Glyphs fill about three quarters of the line height.
165    let half = vec2(l.size.x, l.size.y * 0.74) * 0.5;
166    let k = room / half.length().max(0.01);
167    if k >= 1.0 {
168        return l;
169    }
170    // Text scales with its size. Round down to half points so the layout
171    // is not redone for every tiny change.
172    let fitted = ((size * k * 2.0).floor() * 0.5).max(MIN_GAUGE_LABEL);
173    ui.layout_text(text, &style(fitted))
174}
175
176/// An activity indicator for work of unknown length.
177pub struct Spinner {
178    size: f32,
179}
180
181impl Default for Spinner {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187impl Spinner {
188    /// Creates a spinner 24 points wide.
189    pub fn new() -> Self {
190        Self { size: 24.0 }
191    }
192    /// Sets the diameter in points.
193    pub fn size(mut self, size: f32) -> Self {
194        self.size = size;
195        self
196    }
197}
198
199impl Widget for Spinner {
200    fn ui(self, ui: &mut Ui) -> Response {
201        let r = ui.allocate_response(Vec2::splat(self.size), Sense::Hover);
202        let t = ui.ctx.time as f32;
203        let c = ui.surface.text_color();
204        let n = 8;
205        let head = (t * 1.1).fract() * n as f32;
206        let mut p = ui.painter();
207        for i in 0..n {
208            let a = i as f32 / n as f32 * TAU - TAU / 4.0;
209            let dir = vec2(a.cos(), a.sin());
210            let age = (head - i as f32).rem_euclid(n as f32) / n as f32;
211            let k = self.size * 0.5;
212            p.line(
213                r.rect.center() + dir * k * 0.46,
214                r.rect.center() + dir * k * 0.86,
215                self.size * 0.10,
216                c.alpha(0.12 + 0.62 * (1.0 - age).powf(1.8)),
217            );
218        }
219        ui.ctx.request_repaint();
220        r
221    }
222}
223
224impl Ui<'_> {
225    /// Adds a progress bar filled to `value`, from 0 to 1.
226    pub fn progress(&mut self, value: f32) -> Response {
227        self.add(ProgressBar::new(value))
228    }
229    /// Adds a spinner.
230    pub fn spinner(&mut self) -> Response {
231        self.add(Spinner::new())
232    }
233}