Skip to main content

egui_pop_core/
progress.rs

1//! Progress and waiting: a bar (determinate or indeterminate, with tones
2//! and stacked sections), a ring, a meter and a spinner with a label and
3//! a delay, drawn by the kit (`progress-bar`, `progress-line`,
4//! `progress-fill`, `progress-caption`, `meter`, `meter-tick`,
5//! `progress-ring`, `spinner`; docs/kit.md) on the motion clock
6//! (`motion`): frozen in tests, still under reduced motion.
7//!
8//! <div class="warning">Experimental: may change in any release
9//! (docs/stability.md).</div>
10//!
11//! Each is an AccessKit `ProgressIndicator` (the meter a `Meter`) with
12//! a name, and, when determinate, a numeric value and its range (0 to
13//! the total, or 0 to 100) and a value text ("12 of 340"); an
14//! indeterminate one has no value.
15//!
16//! ```
17//! use egui_pop_core::progress::{ProgressBar, Ring, Spinner, Tone};
18//!
19//! fn ui(ui: &mut egui::Ui) {
20//!     ui.add(ProgressBar::new(Some(0.42)).label("Export"));
21//!     ui.add(
22//!         ProgressBar::counts(340, 1204)
23//!             .label("Import")
24//!             .section(0.05, Tone::Danger, "failed")
25//!             .text("340 of 1,204, 61 failed"),
26//!     );
27//!     ui.add(ProgressBar::new(None).label("Scanning"));
28//!     ui.add(Ring::new(Some(0.75)).label("Render"));
29//!     ui.add(Spinner::new().label("Loading previews"));
30//! }
31//! ```
32
33use std::f32::consts::TAU;
34
35use egui::accesskit::Role;
36use egui::{
37    Color32, Context, FontId, Id, Painter, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, Widget,
38    WidgetInfo, pos2, vec2,
39};
40
41pub use crate::kit::Tone;
42use crate::kit::{Kit, KitCx, Part, State};
43use crate::motion::{self, Busy};
44use crate::theme::Tokens;
45
46impl Tone {
47    /// Its colour as a progress fill (`progress-fill`, in this tone).
48    pub fn color(self, ctx: &Context) -> Color32 {
49        Kit::of(ctx)
50            .progress_fill
51            .style_toned(self, State::REST)
52            .fill
53    }
54}
55
56/// The installed kit's progress values, for a widget drawing progress of
57/// its own (read from `progress-bar`, `progress-fill`, `progress-line`
58/// and `progress-ring`).
59#[derive(Clone, Debug, PartialEq)]
60pub struct ProgressTokens {
61    /// The track under the fill (`progress-bar.rest.fill`).
62    pub track: Color32,
63    /// The fill (`progress-fill.rest.fill`).
64    pub fill: Color32,
65    /// A bar's thickness (`progress-bar.height`).
66    pub height: f32,
67    /// A thin line's (`progress-line.height`).
68    pub line: f32,
69    /// A ring's and a spinner's diameter (`progress-ring.width`).
70    pub ring: f32,
71}
72
73impl ProgressTokens {
74    pub fn of(ctx: &Context) -> ProgressTokens {
75        let kit = Kit::of(ctx);
76        ProgressTokens {
77            track: kit.progress_bar.style(State::REST).fill,
78            fill: kit.progress_fill.style(State::REST).fill,
79            height: kit.progress_bar.data.height.max(1.0),
80            line: kit.progress_line.data.height.max(1.0),
81            ring: kit.progress_ring.data.width.max(8.0),
82        }
83    }
84}
85
86/// A stacked section of a bar: done, failed, skipped.
87#[derive(Clone, Debug, PartialEq)]
88pub struct Section {
89    /// Its share of the whole bar (0 to 1).
90    pub fraction: f32,
91    pub tone: Tone,
92    pub label: String,
93}
94
95/// How thick a bar is.
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub enum BarSize {
98    /// A bar (`progress.height`).
99    #[default]
100    Standard,
101    /// A thin line under a title or along a viewport's top
102    /// (`progress.line`).
103    Line,
104}
105
106/// The value AccessKit gets: a number within a range, as text.
107#[derive(Clone, Debug, PartialEq)]
108struct Value {
109    value: f64,
110    min: f64,
111    max: f64,
112}
113
114fn percent(fraction: f32) -> String {
115    format!("{:.0}%", f64::from(fraction.clamp(0.0, 1.0)) * 100.0)
116}
117
118/// Writes a progress node: its name, and its value and range when
119/// determinate (none when indeterminate).
120fn access(
121    ui: &Ui,
122    response: &Response,
123    role: Option<Role>,
124    label: &str,
125    value: Option<&Value>,
126    text: Option<&str>,
127) {
128    let enabled = ui.is_enabled();
129    let name = label.to_string();
130    response.widget_info(|| WidgetInfo::labeled(Role::ProgressIndicator, enabled, &name));
131    let (value, text) = (value.cloned(), text.map(String::from));
132    ui.ctx().accesskit_node_builder(response.id, |node| {
133        if let Some(role) = role {
134            node.set_role(role);
135        }
136        match &value {
137            Some(v) => {
138                node.set_numeric_value(v.value);
139                node.set_min_numeric_value(v.min);
140                node.set_max_numeric_value(v.max);
141            }
142            None => {
143                node.clear_numeric_value();
144                node.clear_min_numeric_value();
145                node.clear_max_numeric_value();
146            }
147        }
148        match text {
149            Some(t) => node.set_value(t),
150            None => node.clear_value(),
151        }
152    });
153}
154
155/// Paints a stretch of a track (`progress-fill`) in a tone: `room` is
156/// the track, the stretch's ends rounded where they meet its ends.
157fn paint_fill(kit: &Kit, cx: &KitCx<'_>, rect: Rect, room: Rect, tone: Tone) {
158    kit.progress_fill.paint(
159        cx,
160        &Part {
161            rect,
162            room,
163            state: State::REST.toned(tone),
164            label: None,
165        },
166    );
167}
168
169/// A progress bar.
170///
171/// Need (state): a progress bar.
172#[derive(Clone, Debug)]
173#[must_use = "add it with `ui.add`"]
174pub struct ProgressBar {
175    fraction: Option<f32>,
176    sections: Vec<Section>,
177    tone: Tone,
178    size: BarSize,
179    label: String,
180    text: Option<String>,
181    counts: Option<(u64, u64)>,
182    width: Option<f32>,
183    caption: bool,
184}
185
186impl ProgressBar {
187    /// A bar at `fraction` (0 to 1); none: indeterminate (a segment
188    /// travelling along the track).
189    pub fn new(fraction: Option<f32>) -> Self {
190        Self {
191            fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
192            sections: Vec::new(),
193            tone: Tone::Accent,
194            size: BarSize::Standard,
195            label: String::new(),
196            text: None,
197            counts: None,
198            width: None,
199            caption: false,
200        }
201    }
202
203    /// An indeterminate bar.
204    pub fn indeterminate() -> Self {
205        Self::new(None)
206    }
207
208    /// `done` of `total` items: AccessKit's range is 0 to `total`, the
209    /// value text "done of total".
210    pub fn counts(done: u64, total: u64) -> Self {
211        let fraction = if total == 0 {
212            0.0
213        } else {
214            (done as f64 / total as f64) as f32
215        };
216        let mut bar = Self::new(Some(fraction));
217        bar.counts = Some((done, total));
218        bar
219    }
220
221    /// Its accessible name ("Exporting 340 images").
222    pub fn label(mut self, label: impl Into<String>) -> Self {
223        self.label = label.into();
224        self
225    }
226
227    /// Its value as text ("12 of 340, about 2 minutes left"), for
228    /// screen readers and, with [`ProgressBar::caption`], on screen.
229    pub fn text(mut self, text: impl Into<String>) -> Self {
230        self.text = Some(text.into());
231        self
232    }
233
234    pub fn tone(mut self, tone: Tone) -> Self {
235        self.tone = tone;
236        self
237    }
238
239    /// Adds a stacked section after the fill (failed, skipped): the
240    /// fill keeps its fraction, the sections follow it.
241    pub fn section(mut self, fraction: f32, tone: Tone, label: impl Into<String>) -> Self {
242        self.sections.push(Section {
243            fraction: fraction.clamp(0.0, 1.0),
244            tone,
245            label: label.into(),
246        });
247        self
248    }
249
250    /// The thin line.
251    pub fn line(mut self) -> Self {
252        self.size = BarSize::Line;
253        self
254    }
255
256    pub fn size(mut self, size: BarSize) -> Self {
257        self.size = size;
258        self
259    }
260
261    /// Its width (the available width by default).
262    pub fn width(mut self, width: f32) -> Self {
263        self.width = Some(width);
264        self
265    }
266
267    /// Draws the name and the value text above the bar.
268    pub fn caption(mut self, on: bool) -> Self {
269        self.caption = on;
270        self
271    }
272
273    fn value(&self) -> Option<Value> {
274        match (self.counts, self.fraction) {
275            (Some((done, total)), _) => Some(Value {
276                value: done as f64,
277                min: 0.0,
278                max: total as f64,
279            }),
280            (None, Some(f)) => Some(Value {
281                value: (f64::from(f) * 100.0).round(),
282                min: 0.0,
283                max: 100.0,
284            }),
285            (None, None) => None,
286        }
287    }
288
289    fn value_text(&self) -> Option<String> {
290        self.text
291            .clone()
292            .or_else(|| match (self.counts, self.fraction) {
293                (Some((done, total)), _) => Some(format!("{done} of {total}")),
294                (None, Some(f)) => Some(percent(f)),
295                (None, None) => None,
296            })
297    }
298}
299
300impl Widget for ProgressBar {
301    fn ui(self, ui: &mut Ui) -> Response {
302        let ctx = ui.ctx().clone();
303        let t = Tokens::of(&ctx);
304        let kit = Kit::of(&ctx);
305        let track_kit = match self.size {
306            BarSize::Standard => &kit.progress_bar,
307            BarSize::Line => &kit.progress_line,
308        };
309        let thick = track_kit.data.height.max(1.0);
310        let width = self
311            .width
312            .unwrap_or_else(|| ui.available_width())
313            .max(thick * 4.0);
314        let font = FontId::proportional(t.font.small);
315        let caption_h = if self.caption {
316            ui.ctx().fonts_mut(|f| f.row_height(&font)) + t.space.xs
317        } else {
318            0.0
319        };
320        let (rect, response) =
321            ui.allocate_exact_size(vec2(width, caption_h + thick), Sense::hover());
322        let value_text = self.value_text();
323        if ui.is_rect_visible(rect) {
324            let painter = ui.painter();
325            let cx = KitCx {
326                painter,
327                ppp: ctx.pixels_per_point(),
328            };
329            if self.caption {
330                // The name, then the value text in the muted tone, at the
331                // row's end.
332                let caption = &kit.progress_caption;
333                let text = |s: &str, end: bool, tone: Tone| {
334                    let g =
335                        painter.layout_no_wrap(s.to_string(), font.clone(), Color32::PLACEHOLDER);
336                    let at = if end {
337                        pos2(rect.right() - g.size().x, rect.top())
338                    } else {
339                        rect.left_top()
340                    };
341                    let r = Rect::from_min_size(at, g.size());
342                    caption.paint_part(
343                        &cx,
344                        &Part {
345                            rect: r,
346                            room: r,
347                            state: State::REST.toned(tone),
348                            label: Some(&g),
349                        },
350                    );
351                };
352                text(&self.label, false, Tone::Neutral);
353                if let Some(v) = &value_text {
354                    text(v, true, Tone::Muted);
355                }
356            }
357            let track = Rect::from_min_max(pos2(rect.left(), rect.bottom() - thick), rect.max);
358            track_kit.paint_part(
359                &cx,
360                &Part {
361                    rect: track,
362                    room: track,
363                    state: State::REST,
364                    label: None,
365                },
366            );
367            match self.fraction {
368                Some(f) => {
369                    let parts = std::iter::once((f, self.tone))
370                        .chain(self.sections.iter().map(|s| (s.fraction, s.tone)));
371                    let mut x = track.left();
372                    for (share, tone) in parts {
373                        let w = (share * track.width()).min(track.right() - x);
374                        if w <= 0.0 {
375                            continue;
376                        }
377                        let part =
378                            Rect::from_min_max(pos2(x, track.top()), pos2(x + w, track.bottom()));
379                        paint_fill(&kit, &cx, part, track, tone);
380                        x += w;
381                    }
382                }
383                None if motion::reduced(&ctx) => {
384                    // Still: a striped track, the fill's colour at 60 %.
385                    let tone = kit.progress_fill.style_toned(self.tone, State::REST).fill;
386                    let step = (thick * 2.0).max(6.0);
387                    let clip = painter.with_clip_rect(track);
388                    let mut x = track.left();
389                    while x < track.right() {
390                        let part = Rect::from_min_max(
391                            pos2(x, track.top()),
392                            pos2((x + step / 2.0).min(track.right()), track.bottom()),
393                        );
394                        clip.rect_filled(part, 0.0, tone.gamma_multiply(0.6));
395                        x += step;
396                    }
397                }
398                None => {
399                    let seg = track.width() * 0.3;
400                    let phase = motion::phase(&ctx, f64::from(t.motion.progress_travel), 0.0);
401                    let x = track.left() - seg + phase * (track.width() + seg);
402                    let part =
403                        Rect::from_min_max(pos2(x, track.top()), pos2(x + seg, track.bottom()));
404                    // Its own room: rounded at both ends, clipped by the
405                    // track.
406                    let clip = painter.with_clip_rect(track);
407                    let clipped = KitCx {
408                        painter: &clip,
409                        ppp: cx.ppp,
410                    };
411                    paint_fill(&kit, &clipped, part, part, self.tone);
412                    motion::animate(&ctx);
413                }
414            }
415        }
416        let response = if self.label.is_empty() {
417            response
418        } else {
419            response.on_hover_text(match &value_text {
420                Some(v) => format!("{}: {v}", self.label),
421                None => self.label.clone(),
422            })
423        };
424        access(
425            ui,
426            &response,
427            None,
428            &self.label,
429            self.value().as_ref(),
430            value_text.as_deref(),
431        );
432        response
433    }
434}
435
436/// Points along an arc of a circle, from `start` turning `sweep`
437/// radians clockwise (screen y down).
438fn arc(center: Pos2, radius: f32, start: f32, sweep: f32) -> Vec<Pos2> {
439    let n = ((sweep.abs() / TAU) * 48.0).ceil().max(2.0) as usize;
440    (0..=n)
441        .map(|i| {
442            let a = start + sweep * i as f32 / n as f32;
443            center + radius * vec2(a.cos(), a.sin())
444        })
445        .collect()
446}
447
448/// Paints a ring in `rect`: an arc from the top for `fraction`, a
449/// turning arc when none (still under reduced motion), the arc in
450/// `color` over `progress-ring`'s track. For a ring that is part of
451/// another widget; [`Ring`] is the widget.
452pub fn paint_ring(ui: &Ui, rect: Rect, fraction: Option<f32>, color: Color32) {
453    paint_ring_on(ui.painter(), rect, fraction, color);
454}
455
456/// [`paint_ring`] with a painter of its own (another layer, a clip).
457pub fn paint_ring_on(painter: &Painter, rect: Rect, fraction: Option<f32>, color: Color32) {
458    let ctx = painter.ctx();
459    let t = Tokens::of(ctx);
460    let track = Kit::of(ctx).progress_ring.style(State::REST).fill;
461    let side = rect.width().min(rect.height());
462    let width = (side / 7.0).max(1.5);
463    let radius = side / 2.0 - width / 2.0;
464    painter.circle_stroke(rect.center(), radius, Stroke::new(width, track));
465    let top = -TAU / 4.0;
466    match fraction {
467        Some(f) if f > 0.0 => {
468            painter.line(
469                arc(rect.center(), radius, top, f.min(1.0) * TAU),
470                Stroke::new(width, color),
471            );
472        }
473        Some(_) => {}
474        None => {
475            let phase = motion::phase(ctx, f64::from(t.motion.spinner_turn), 0.125);
476            painter.line(
477                arc(rect.center(), radius, top + phase * TAU, TAU / 4.0),
478                Stroke::new(width, color),
479            );
480            motion::animate(ctx);
481        }
482    }
483}
484
485/// A small circular progress: determinate (an arc from the top) or
486/// indeterminate (a turning arc).
487///
488/// Need (state): a small circular progress.
489#[derive(Clone, Debug)]
490#[must_use = "add it with `ui.add`"]
491pub struct Ring {
492    fraction: Option<f32>,
493    tone: Tone,
494    size: Option<f32>,
495    label: String,
496}
497
498impl Ring {
499    pub fn new(fraction: Option<f32>) -> Self {
500        Self {
501            fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
502            tone: Tone::Accent,
503            size: None,
504            label: String::new(),
505        }
506    }
507
508    pub fn label(mut self, label: impl Into<String>) -> Self {
509        self.label = label.into();
510        self
511    }
512
513    pub fn tone(mut self, tone: Tone) -> Self {
514        self.tone = tone;
515        self
516    }
517
518    /// Its diameter (`progress-ring.width` by default).
519    pub fn size(mut self, size: f32) -> Self {
520        self.size = Some(size);
521        self
522    }
523}
524
525impl Widget for Ring {
526    fn ui(self, ui: &mut Ui) -> Response {
527        let ctx = ui.ctx().clone();
528        let kit = Kit::of(&ctx);
529        let ring = &kit.progress_ring;
530        let side = self.size.unwrap_or(ring.data.width.max(8.0));
531        let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
532        if ui.is_rect_visible(rect) {
533            let arc = ring.style_toned(self.tone, State::REST).indicator_color;
534            paint_ring(ui, rect, self.fraction, arc);
535        }
536        let value = self.fraction.map(|f| Value {
537            value: (f64::from(f) * 100.0).round(),
538            min: 0.0,
539            max: 100.0,
540        });
541        let text = self.fraction.map(percent);
542        let response = if self.label.is_empty() {
543            response
544        } else {
545            response.on_hover_text(match &text {
546                Some(v) => format!("{}: {v}", self.label),
547                None => self.label.clone(),
548            })
549        };
550        access(
551            ui,
552            &response,
553            None,
554            &self.label,
555            value.as_ref(),
556            text.as_deref(),
557        );
558        response
559    }
560}
561
562/// A value against thresholds (disk space, memory), not progress: a bar
563/// whose tone follows the highest threshold reached. AccessKit role
564/// `Meter`.
565///
566/// Need (status): a level against thresholds (disk space, memory).
567#[derive(Clone, Debug)]
568#[must_use = "add it with `ui.add`"]
569pub struct Meter {
570    value: f64,
571    min: f64,
572    max: f64,
573    thresholds: Vec<(f64, Tone)>,
574    label: String,
575    text: Option<String>,
576    width: Option<f32>,
577    size: Option<Vec2>,
578    vertical: bool,
579}
580
581impl Meter {
582    /// `value` between `min` and `max`.
583    pub fn new(value: f64, min: f64, max: f64) -> Self {
584        Self {
585            value,
586            min,
587            max: if max > min { max } else { min + 1.0 },
588            thresholds: Vec::new(),
589            label: String::new(),
590            text: None,
591            width: None,
592            size: None,
593            vertical: false,
594        }
595    }
596
597    /// From `at` on, the meter takes `tone`.
598    pub fn threshold(mut self, at: f64, tone: Tone) -> Self {
599        self.thresholds.push((at, tone));
600        self.thresholds.sort_by(|a, b| a.0.total_cmp(&b.0));
601        self
602    }
603
604    pub fn label(mut self, label: impl Into<String>) -> Self {
605        self.label = label.into();
606        self
607    }
608
609    /// Its value as text ("72 GB of 100 GB").
610    pub fn text(mut self, text: impl Into<String>) -> Self {
611        self.text = Some(text.into());
612        self
613    }
614
615    pub fn width(mut self, width: f32) -> Self {
616        self.width = Some(width);
617        self
618    }
619
620    /// Its size, for a value bar in a slot (a HUD's level, a property
621    /// row's read-out): the bar fills it, instead of the kit's thickness
622    /// (`meter.height`) across the width available.
623    pub fn size(mut self, size: Vec2) -> Self {
624        self.size = Some(size);
625        self
626    }
627
628    /// A vertical bar, filled from the bottom (a level meter); vertical
629    /// for assistive technologies too. Give it a [`size`](Self::size),
630    /// else it is the kit's thickness wide and a row and a half high.
631    pub fn vertical(mut self) -> Self {
632        self.vertical = true;
633        self
634    }
635
636    /// The tone at its value.
637    pub fn tone(&self) -> Tone {
638        self.thresholds
639            .iter()
640            .rev()
641            .find(|(at, _)| self.value >= *at)
642            .map_or(Tone::Accent, |(_, tone)| *tone)
643    }
644}
645
646impl Widget for Meter {
647    fn ui(self, ui: &mut Ui) -> Response {
648        let ctx = ui.ctx().clone();
649        let kit = Kit::of(&ctx);
650        let thick = kit.meter.data.height.max(1.0);
651        let size = match (self.size, self.vertical) {
652            (Some(s), _) => vec2(s.x.max(1.0), s.y.max(1.0)),
653            (None, false) => vec2(
654                self.width
655                    .unwrap_or_else(|| ui.available_width())
656                    .max(thick * 4.0),
657                thick,
658            ),
659            (None, true) => vec2(thick, ui.spacing().interact_size.y * 1.5),
660        };
661        let vertical = self.vertical;
662        let (rect, response) = ui.allocate_exact_size(size, Sense::hover());
663        let span = self.max - self.min;
664        let share = |v: f64| ((v - self.min) / span).clamp(0.0, 1.0) as f32;
665        // Where a value falls along the bar: from the left, or up from
666        // the bottom.
667        let at = |v: f64| {
668            if vertical {
669                rect.bottom() - rect.height() * share(v)
670            } else {
671                rect.left() + rect.width() * share(v)
672            }
673        };
674        if ui.is_rect_visible(rect) {
675            let cx = KitCx {
676                painter: ui.painter(),
677                ppp: ctx.pixels_per_point(),
678            };
679            let part = |rect: Rect| Part {
680                rect,
681                room: rect,
682                state: State::REST,
683                label: None,
684            };
685            kit.meter.paint_part(&cx, &part(rect));
686            let x = at(self.value);
687            if vertical && x < rect.bottom() {
688                let fill = Rect::from_min_max(pos2(rect.left(), x), rect.max);
689                paint_fill(&kit, &cx, fill, rect, self.tone());
690            } else if !vertical && x > rect.left() {
691                let fill = Rect::from_min_max(rect.min, pos2(x, rect.bottom()));
692                paint_fill(&kit, &cx, fill, rect, self.tone());
693            }
694            for (v, _) in &self.thresholds {
695                let x = at(*v);
696                let tick = if vertical {
697                    Rect::from_min_max(pos2(rect.left(), x), pos2(rect.right(), x))
698                } else {
699                    Rect::from_min_max(pos2(x, rect.top()), pos2(x, rect.bottom()))
700                };
701                kit.meter_tick.paint_part(&cx, &part(tick));
702            }
703        }
704        let text = self
705            .text
706            .clone()
707            .unwrap_or_else(|| percent(((self.value - self.min) / span) as f32));
708        let response = if self.label.is_empty() {
709            response
710        } else {
711            response.on_hover_text(format!("{}: {text}", self.label))
712        };
713        let value = Value {
714            value: self.value,
715            min: self.min,
716            max: self.max,
717        };
718        access(
719            ui,
720            &response,
721            Some(Role::Meter),
722            &self.label,
723            Some(&value),
724            Some(&text),
725        );
726        if vertical {
727            ctx.accesskit_node_builder(response.id, |node| {
728                node.set_orientation(egui::accesskit::Orientation::Vertical);
729            });
730        }
731        response
732    }
733}
734
735/// A spinner, with a label after it; [`Spinner::delayed`] shows it only
736/// after `motion.spinner.delay`, and keeps it `motion.spinner.min`.
737///
738/// Need (state): a busy spinner.
739/// Need (state): a value still loading.
740#[derive(Clone, Debug)]
741#[must_use = "add it with `ui.add`"]
742pub struct Spinner {
743    label: String,
744    name: Option<String>,
745    size: Option<f32>,
746    tone: Tone,
747    busy: Option<(Busy, bool)>,
748}
749
750impl Default for Spinner {
751    fn default() -> Self {
752        Self::new()
753    }
754}
755
756impl Spinner {
757    pub fn new() -> Self {
758        Self {
759            label: String::new(),
760            name: None,
761            size: None,
762            tone: Tone::Accent,
763            busy: None,
764        }
765    }
766
767    /// The text after it ("Loading previews"), also its accessible name.
768    pub fn label(mut self, label: impl Into<String>) -> Self {
769        self.label = label.into();
770        self
771    }
772
773    /// Its accessible name, no text drawn ("Updating free space"); a
774    /// [`Spinner::label`] is drawn and names it too. "Busy" by default.
775    pub fn name(mut self, name: impl Into<String>) -> Self {
776        self.name = Some(name.into());
777        self
778    }
779
780    pub fn size(mut self, size: f32) -> Self {
781        self.size = Some(size);
782        self
783    }
784
785    pub fn tone(mut self, tone: Tone) -> Self {
786        self.tone = tone;
787        self
788    }
789
790    /// Shown only for work going on (`busy`) since `since` (motion clock
791    /// seconds) for longer than the delay, then for the minimum. The
792    /// space stays taken while hidden, so nothing around it moves.
793    pub fn delayed(mut self, id: Id, since: f64, busy: bool) -> Self {
794        self.busy = Some((Busy::new(id, since), busy));
795        self
796    }
797}
798
799/// Paints a spinner's arc in `rect`, in `color` over `spinner`'s track.
800pub fn paint_spinner(ui: &Ui, rect: Rect, color: Color32) {
801    paint_spinner_on(ui.painter(), rect, color);
802}
803
804/// [`paint_spinner`] with a painter of its own (another layer, a clip).
805pub fn paint_spinner_on(painter: &Painter, rect: Rect, color: Color32) {
806    let ctx = painter.ctx();
807    let t = Tokens::of(ctx);
808    let track = Kit::of(ctx).spinner.style(State::REST).fill;
809    let side = rect.width().min(rect.height());
810    let width = (side / 7.0).max(1.5);
811    let radius = side / 2.0 - width / 2.0;
812    let phase = motion::phase(ctx, f64::from(t.motion.spinner_turn), 0.125);
813    painter.circle_stroke(rect.center(), radius, Stroke::new(width, track));
814    painter.line(
815        arc(rect.center(), radius, -TAU / 4.0 + phase * TAU, TAU * 0.3),
816        Stroke::new(width, color),
817    );
818    motion::animate(ctx);
819}
820
821impl Widget for Spinner {
822    fn ui(self, ui: &mut Ui) -> Response {
823        let ctx = ui.ctx().clone();
824        let t = Tokens::of(&ctx);
825        let kit = Kit::of(&ctx);
826        let spinner = &kit.spinner;
827        let label_color = spinner.style(State::REST).text;
828        let side = self.size.unwrap_or(spinner.data.width.max(8.0));
829        let visible = match &self.busy {
830            Some((busy, on)) => busy.visible(&ctx, *on),
831            None => true,
832        };
833        let font = FontId::proportional(t.font.body);
834        let galley = (!self.label.is_empty()).then(|| {
835            ui.painter()
836                .layout_no_wrap(self.label.clone(), font, label_color)
837        });
838        let text_w = galley.as_ref().map_or(0.0, |g| g.size().x + t.space.s);
839        let height = galley.as_ref().map_or(side, |g| g.size().y.max(side));
840        let (rect, response) = ui.allocate_exact_size(vec2(side + text_w, height), Sense::hover());
841        if visible && ui.is_rect_visible(rect) {
842            let icon = Rect::from_center_size(
843                pos2(rect.left() + side / 2.0, rect.center().y),
844                vec2(side, side),
845            );
846            let arc = spinner.style_toned(self.tone, State::REST).indicator_color;
847            paint_spinner(ui, icon, arc);
848            if let Some(g) = galley {
849                let at = pos2(icon.right() + t.space.s, rect.center().y - g.size().y / 2.0);
850                ui.painter().galley(at, g, label_color);
851            }
852        }
853        if visible {
854            let name = if !self.label.is_empty() {
855                self.label.clone()
856            } else if let Some(name) = &self.name {
857                name.clone()
858            } else {
859                crate::strings::tr(&ctx, &crate::strings::BUSY)
860            };
861            access(ui, &response, None, &name, None, None);
862        }
863        response
864    }
865}