1use 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 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#[derive(Clone, Debug, PartialEq)]
60pub struct ProgressTokens {
61 pub track: Color32,
63 pub fill: Color32,
65 pub height: f32,
67 pub line: f32,
69 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#[derive(Clone, Debug, PartialEq)]
88pub struct Section {
89 pub fraction: f32,
91 pub tone: Tone,
92 pub label: String,
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub enum BarSize {
98 #[default]
100 Standard,
101 Line,
104}
105
106#[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
118fn 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
155fn 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#[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 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 pub fn indeterminate() -> Self {
205 Self::new(None)
206 }
207
208 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 pub fn label(mut self, label: impl Into<String>) -> Self {
223 self.label = label.into();
224 self
225 }
226
227 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 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 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 pub fn width(mut self, width: f32) -> Self {
263 self.width = Some(width);
264 self
265 }
266
267 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 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 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 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
436fn 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
448pub fn paint_ring(ui: &Ui, rect: Rect, fraction: Option<f32>, color: Color32) {
453 paint_ring_on(ui.painter(), rect, fraction, color);
454}
455
456pub 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#[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 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#[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 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 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 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 pub fn size(mut self, size: Vec2) -> Self {
624 self.size = Some(size);
625 self
626 }
627
628 pub fn vertical(mut self) -> Self {
632 self.vertical = true;
633 self
634 }
635
636 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 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#[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 pub fn label(mut self, label: impl Into<String>) -> Self {
769 self.label = label.into();
770 self
771 }
772
773 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 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
799pub fn paint_spinner(ui: &Ui, rect: Rect, color: Color32) {
801 paint_spinner_on(ui.painter(), rect, color);
802}
803
804pub 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}