Skip to main content

sui_widgets/composites/
indicators.rs

1use crate::ControlMetrics;
2use crate::DefaultTheme;
3use crate::IconGlyph;
4use crate::Interpolate;
5use crate::ResolvedEffectStyle;
6use crate::SemanticTone;
7use crate::ThemeTextToken;
8use crate::composites::popups::{AnimatedScalar, TooltipPlacement};
9use crate::composites::status::{StatusBadge, paint_status_badge};
10use crate::controls::apply_hdr_policy_cap;
11use crate::text_align::paint_aligned_text;
12use crate::text_align::paint_single_line_aligned_text;
13use sui_core::Color;
14use sui_core::Path;
15use sui_core::PathBuilder;
16use sui_core::Point;
17use sui_core::Rect;
18use sui_core::SemanticsNode;
19use sui_core::SemanticsRole;
20use sui_core::SemanticsValue;
21use sui_core::Size;
22use sui_core::Vector;
23use sui_layout::Constraints;
24use sui_layout::Padding as Insets;
25use sui_runtime::MeasureCtx;
26use sui_runtime::PaintCtx;
27use sui_runtime::SemanticsCtx;
28use sui_runtime::Widget;
29use sui_scene::StrokeStyle;
30use sui_text::FontFeature;
31use sui_text::FontWeight;
32use sui_text::TextMeasurement;
33use sui_text::TextStyle;
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct CoverageDotsConfig {
37    pub current: usize,
38    pub target: usize,
39    pub tone: SemanticTone,
40    pub max_dots: usize,
41    pub show_label: bool,
42}
43
44impl CoverageDotsConfig {
45    pub fn new(current: usize, target: usize) -> Self {
46        Self {
47            current,
48            target,
49            tone: SemanticTone::Neutral,
50            max_dots: 4,
51            show_label: true,
52        }
53    }
54
55    pub(super) fn normalized_target(self) -> usize {
56        self.target.max(self.current)
57    }
58
59    pub(super) fn normalized_max_dots(self) -> usize {
60        self.max_dots.max(1)
61    }
62
63    pub(super) fn label(self) -> String {
64        format!("{}/{}", self.current, self.normalized_target())
65    }
66}
67
68pub fn paint_coverage_dots(
69    ctx: &mut PaintCtx,
70    theme: &DefaultTheme,
71    rect: Rect,
72    current: usize,
73    target: usize,
74    tone: SemanticTone,
75) {
76    let mut config = CoverageDotsConfig::new(current, target);
77    config.tone = tone;
78    paint_coverage_dots_with_config(ctx, theme, rect, config);
79}
80
81pub fn paint_coverage_dots_with_config(
82    ctx: &mut PaintCtx,
83    theme: &DefaultTheme,
84    rect: Rect,
85    config: CoverageDotsConfig,
86) {
87    let target = config.normalized_target();
88    if target == 0 || rect.width() <= 0.0 || rect.height() <= 0.0 {
89        return;
90    }
91
92    let (dot, gap, label_gap) = coverage_dot_metrics(theme);
93    let label = config.label();
94    let text_style = numeric_text_style(text_token_style(
95        theme,
96        theme.text.xs,
97        theme.palette.text_muted,
98    ));
99    let label_width = if config.show_label {
100        ctx.measure_text(label.clone(), text_style.clone())
101            .map(|measurement| measurement.width)
102            .unwrap_or(0.0)
103    } else {
104        0.0
105    };
106    // Keep the exact count readable first. Dots are redundant decoration and
107    // disappear as a group when their complete representation does not fit.
108    let shown = target.min(config.normalized_max_dots());
109    let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
110    let separation = if config.show_label { label_gap } else { 0.0 };
111    let show_dots = dots_width + separation + label_width <= rect.width();
112    let mut x = rect.x();
113    ctx.push_clip_rect(rect);
114    if show_dots {
115        let y = rect.y() + (rect.height() - dot) * 0.5;
116        let (tone_color, _) = theme.semantic_tone_colors(config.tone);
117        for index in 0..shown {
118            let dot_rect = Rect::new(x, y, dot, dot);
119            if index < config.current.min(shown) {
120                ctx.fill(rounded_rect_path(dot_rect, dot * 0.5), tone_color);
121            } else {
122                ctx.stroke(
123                    rounded_rect_path(dot_rect, dot * 0.5),
124                    theme.palette.border,
125                    StrokeStyle::new(theme.metrics.border_width.max(1.0)),
126                );
127            }
128            x += dot + gap;
129        }
130        x += separation - gap;
131    }
132    if config.show_label {
133        let label_rect = Rect::new(x, rect.y(), (rect.max_x() - x).max(0.0), rect.height());
134        paint_single_line_aligned_text(
135            ctx,
136            label_rect,
137            &label,
138            &text_style,
139            text_style.line_height,
140            0.0,
141        );
142    }
143    ctx.pop_clip();
144}
145
146pub(super) fn coverage_dot_metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
147    let dot = (theme.text.xs.size * 0.42).clamp(4.0, 6.0);
148    let gap = (dot * 0.65).clamp(2.0, 4.0);
149    let label_gap = (theme.metrics.icon_label_gap * 0.7).max(4.0);
150    (dot, gap, label_gap)
151}
152
153pub struct CoverageDots {
154    pub(super) theme: Box<DefaultTheme>,
155    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
156    pub(super) name: String,
157    pub(super) config: CoverageDotsConfig,
158    pub(super) min_width: Option<f32>,
159}
160
161impl CoverageDots {
162    pub fn new(name: impl Into<String>, current: usize, target: usize) -> Self {
163        Self {
164            theme: Box::new(DefaultTheme::default()),
165            theme_reader: None,
166            name: name.into(),
167            config: CoverageDotsConfig::new(current, target),
168            min_width: None,
169        }
170    }
171
172    pub fn theme(mut self, theme: DefaultTheme) -> Self {
173        self.theme = Box::new(theme);
174        self.theme_reader = None;
175        self
176    }
177
178    pub fn theme_when<F>(mut self, theme: F) -> Self
179    where
180        F: Fn() -> DefaultTheme + 'static,
181    {
182        self.theme_reader = Some(Box::new(theme));
183        self
184    }
185
186    pub fn tone(mut self, tone: SemanticTone) -> Self {
187        self.config.tone = tone;
188        self
189    }
190
191    pub fn max_dots(mut self, max_dots: usize) -> Self {
192        self.config.max_dots = max_dots;
193        self
194    }
195
196    pub fn show_label(mut self, show_label: bool) -> Self {
197        self.config.show_label = show_label;
198        self
199    }
200
201    pub fn min_width(mut self, min_width: f32) -> Self {
202        self.min_width = Some(min_width.max(0.0));
203        self
204    }
205
206    pub(super) fn resolved_theme(&self) -> DefaultTheme {
207        self.theme_reader
208            .as_ref()
209            .map(|theme| theme())
210            .unwrap_or(*self.theme)
211    }
212}
213
214impl Widget for CoverageDots {
215    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
216        let theme = self.resolved_theme();
217        let target = self.config.normalized_target();
218        if target == 0 {
219            return constraints.clamp(Size::ZERO);
220        }
221        let (dot, gap, label_gap) = coverage_dot_metrics(&theme);
222        let shown = target.min(self.config.normalized_max_dots());
223        let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
224        let label_width = if self.config.show_label {
225            measure_text(
226                ctx,
227                &self.config.label(),
228                &numeric_text_style(text_token_style(
229                    &theme,
230                    theme.text.xs,
231                    theme.palette.text_muted,
232                )),
233            )
234            .width
235                + label_gap
236        } else {
237            0.0
238        };
239        constraints.clamp(Size::new(
240            self.min_width.unwrap_or(0.0).max(dots_width + label_width),
241            theme
242                .text
243                .xs
244                .line_height
245                .max(dot + 2.0)
246                .max(theme.metrics.min_height * 0.55),
247        ))
248    }
249
250    fn paint(&self, ctx: &mut PaintCtx) {
251        paint_coverage_dots_with_config(ctx, &self.resolved_theme(), ctx.bounds(), self.config);
252    }
253
254    fn semantics(&self, ctx: &mut SemanticsCtx) {
255        let target = self.config.normalized_target();
256        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
257        node.name = Some(self.name.clone());
258        node.value = Some(SemanticsValue::Text(self.config.label()));
259        node.description = Some(format!(
260            "{} of {} covered",
261            self.config.current.min(target),
262            target
263        ));
264        ctx.push(node);
265    }
266}
267
268pub struct PlacementBadge {
269    pub(super) theme: Box<DefaultTheme>,
270    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
271    pub(super) label: String,
272    pub(super) label_reader: Option<Box<dyn Fn() -> String>>,
273    pub(super) icon: Option<IconGlyph>,
274    pub(super) tone: SemanticTone,
275    pub(super) tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
276    pub(super) coverage: Option<(usize, usize)>,
277    pub(super) coverage_reader: Option<Box<dyn Fn() -> Option<(usize, usize)>>>,
278    pub(super) min_width: Option<f32>,
279}
280
281impl PlacementBadge {
282    pub fn new(label: impl Into<String>) -> Self {
283        Self {
284            theme: Box::new(DefaultTheme::default()),
285            theme_reader: None,
286            label: label.into(),
287            label_reader: None,
288            icon: None,
289            tone: SemanticTone::Neutral,
290            tone_reader: None,
291            coverage: None,
292            coverage_reader: None,
293            min_width: None,
294        }
295    }
296
297    pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
298    where
299        F: Fn() -> String + 'static,
300    {
301        let mut badge = Self::new(fallback);
302        badge.label_reader = Some(Box::new(reader));
303        badge
304    }
305
306    pub fn theme(mut self, theme: DefaultTheme) -> Self {
307        self.theme = Box::new(theme);
308        self.theme_reader = None;
309        self
310    }
311
312    pub fn theme_when<F>(mut self, theme: F) -> Self
313    where
314        F: Fn() -> DefaultTheme + 'static,
315    {
316        self.theme_reader = Some(Box::new(theme));
317        self
318    }
319
320    pub fn icon(mut self, icon: IconGlyph) -> Self {
321        self.icon = Some(icon);
322        self
323    }
324
325    pub fn tone(mut self, tone: SemanticTone) -> Self {
326        self.tone = tone;
327        self.tone_reader = None;
328        self
329    }
330
331    pub fn tone_when<F>(mut self, tone: F) -> Self
332    where
333        F: Fn() -> SemanticTone + 'static,
334    {
335        self.tone_reader = Some(Box::new(tone));
336        self
337    }
338
339    pub fn coverage(mut self, current: usize, target: usize) -> Self {
340        self.coverage = Some((current, target));
341        self.coverage_reader = None;
342        self
343    }
344
345    pub fn coverage_when<F>(mut self, coverage: F) -> Self
346    where
347        F: Fn() -> Option<(usize, usize)> + 'static,
348    {
349        self.coverage_reader = Some(Box::new(coverage));
350        self
351    }
352
353    pub fn min_width(mut self, min_width: f32) -> Self {
354        self.min_width = Some(min_width.max(0.0));
355        self
356    }
357
358    pub(super) fn resolved_theme(&self) -> DefaultTheme {
359        self.theme_reader
360            .as_ref()
361            .map(|theme| theme())
362            .unwrap_or(*self.theme)
363    }
364
365    pub(super) fn label(&self) -> String {
366        self.label_reader
367            .as_ref()
368            .map(|reader| reader())
369            .unwrap_or_else(|| self.label.clone())
370    }
371
372    pub(super) fn resolved_tone(&self) -> SemanticTone {
373        self.tone_reader
374            .as_ref()
375            .map(|reader| reader())
376            .unwrap_or(self.tone)
377    }
378
379    pub(super) fn resolved_coverage(&self) -> Option<(usize, usize)> {
380        self.coverage_reader
381            .as_ref()
382            .map(|reader| reader())
383            .unwrap_or(self.coverage)
384            .filter(|(_, target)| *target > 0)
385    }
386
387    pub(super) fn metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
388        let height = (theme.metrics.min_height - 2.0).max(22.0);
389        let coverage_width = 50.0;
390        let gap = theme.metrics.icon_label_gap.max(6.0);
391        (height, coverage_width, gap)
392    }
393}
394
395#[derive(Clone, Copy, Debug, PartialEq)]
396pub struct PlacementBadgePaint {
397    pub padding: Insets,
398}
399
400impl PlacementBadgePaint {
401    pub const fn new() -> Self {
402        Self {
403            padding: Insets::ZERO,
404        }
405    }
406
407    pub const fn padding(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self {
408        self.padding = Insets {
409            left,
410            top,
411            right,
412            bottom,
413        };
414        self
415    }
416
417    pub(super) fn content_rect(self, rect: Rect) -> Rect {
418        Rect::new(
419            rect.x() + self.padding.left,
420            rect.y() + self.padding.top,
421            (rect.width() - self.padding.left - self.padding.right).max(0.0),
422            (rect.height() - self.padding.top - self.padding.bottom).max(0.0),
423        )
424    }
425}
426
427impl Default for PlacementBadgePaint {
428    fn default() -> Self {
429        Self::new()
430    }
431}
432
433pub fn paint_placement_badge(
434    ctx: &mut PaintCtx,
435    theme: &DefaultTheme,
436    rect: Rect,
437    label: &str,
438    icon: Option<IconGlyph>,
439    tone: SemanticTone,
440    coverage: Option<(usize, usize)>,
441) {
442    paint_placement_badge_with(
443        ctx,
444        theme,
445        rect,
446        label,
447        icon,
448        tone,
449        coverage,
450        PlacementBadgePaint::new(),
451    );
452}
453
454pub fn paint_placement_badge_with(
455    ctx: &mut PaintCtx,
456    theme: &DefaultTheme,
457    rect: Rect,
458    label: &str,
459    icon: Option<IconGlyph>,
460    tone: SemanticTone,
461    coverage: Option<(usize, usize)>,
462    paint: PlacementBadgePaint,
463) {
464    let rect = paint.content_rect(rect);
465    if rect.width() <= 0.0 || rect.height() <= 0.0 {
466        return;
467    }
468
469    let (_, coverage_width, gap) = PlacementBadge::metrics(theme);
470    let show_coverage = coverage.is_some() && rect.width() >= 118.0;
471    let coverage_slot = if show_coverage { coverage_width } else { 0.0 };
472    let slot_gap = if show_coverage { gap } else { 0.0 };
473    let badge_rect = Rect::new(
474        rect.x(),
475        rect.y(),
476        (rect.width() - coverage_slot - slot_gap).clamp(48.0, 86.0),
477        rect.height(),
478    );
479    let label_width = ctx
480        .measure_text(
481            label.to_string(),
482            semibold_control_text_style(theme, theme.palette.text),
483        )
484        .map(|measurement| measurement.width)
485        .unwrap_or(0.0);
486    let icon_width =
487        (rect.height() - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0);
488    let padding = theme.metrics.button_padding.left.max(6.0) * 1.5;
489    let icon = icon.filter(|_| label_width + icon_width + padding <= badge_rect.width());
490    paint_status_badge(ctx, badge_rect, theme, label, icon, tone);
491
492    if show_coverage && let Some((current, target)) = coverage {
493        let dots_rect = Rect::new(
494            badge_rect.max_x() + slot_gap,
495            rect.y(),
496            (rect.max_x() - badge_rect.max_x() - slot_gap).max(0.0),
497            rect.height(),
498        );
499        paint_coverage_dots(ctx, theme, dots_rect, current, target, tone);
500    }
501}
502
503impl Widget for PlacementBadge {
504    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
505        let theme = self.resolved_theme();
506        let (height, coverage_width, gap) = Self::metrics(&theme);
507        let label = self.label();
508        let tone = self.resolved_tone();
509        let icon_w = self
510            .icon
511            .map(|_| (height - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0))
512            .unwrap_or(0.0);
513        let text = measure_text(
514            ctx,
515            &label,
516            &StatusBadge::new(&label).text_style(&theme, &label, tone),
517        );
518        let badge_width =
519            (text.width.ceil() + icon_w + theme.metrics.button_padding.left.max(8.0) * 2.0)
520                .clamp(48.0, 86.0);
521        let coverage_width = if self.resolved_coverage().is_some() {
522            coverage_width + gap
523        } else {
524            0.0
525        };
526        constraints.clamp(Size::new(
527            self.min_width
528                .unwrap_or(0.0)
529                .max(badge_width + coverage_width),
530            height,
531        ))
532    }
533
534    fn paint(&self, ctx: &mut PaintCtx) {
535        let theme = self.resolved_theme();
536        paint_placement_badge(
537            ctx,
538            &theme,
539            ctx.bounds(),
540            &self.label(),
541            self.icon,
542            self.resolved_tone(),
543            self.resolved_coverage(),
544        );
545    }
546
547    fn semantics(&self, ctx: &mut SemanticsCtx) {
548        let label = self.label();
549        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
550        node.name = Some(label.clone());
551        node.value = Some(SemanticsValue::Text(label.clone()));
552        if let Some((current, target)) = self.resolved_coverage() {
553            let target = target.max(current);
554            node.description = Some(format!("{current} of {target} replicas available"));
555        }
556        ctx.push(node);
557    }
558}
559
560pub struct ProgressBar {
561    pub(super) theme: Box<DefaultTheme>,
562    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
563    pub(super) name: String,
564    pub(super) min: f64,
565    pub(super) max: f64,
566    pub(super) value: f64,
567    pub(super) tone: SemanticTone,
568    pub(super) min_width: Option<f32>,
569    pub(super) height: Option<f32>,
570    pub(super) show_value: bool,
571}
572
573impl ProgressBar {
574    pub fn new(name: impl Into<String>) -> Self {
575        Self {
576            theme: Box::new(DefaultTheme::default()),
577            theme_reader: None,
578            name: name.into(),
579            min: 0.0,
580            max: 1.0,
581            value: 0.0,
582            tone: SemanticTone::Accent,
583            min_width: None,
584            height: None,
585            show_value: false,
586        }
587    }
588
589    pub fn theme(mut self, theme: DefaultTheme) -> Self {
590        self.theme = Box::new(theme);
591        self.theme_reader = None;
592        self
593    }
594
595    pub fn theme_when<F>(mut self, theme: F) -> Self
596    where
597        F: Fn() -> DefaultTheme + 'static,
598    {
599        self.theme_reader = Some(Box::new(theme));
600        self
601    }
602
603    pub fn range(mut self, min: f64, max: f64) -> Self {
604        self.min = min.min(max);
605        self.max = max.max(min);
606        self.value = self.value.clamp(self.min, self.max);
607        self
608    }
609
610    pub fn value(mut self, value: f64) -> Self {
611        self.value = value.clamp(self.min, self.max);
612        self
613    }
614
615    pub fn tone(mut self, tone: SemanticTone) -> Self {
616        self.tone = tone;
617        self
618    }
619
620    pub fn min_width(mut self, min_width: f32) -> Self {
621        self.min_width = Some(min_width.max(0.0));
622        self
623    }
624
625    pub fn height(mut self, height: f32) -> Self {
626        self.height = Some(height.max(1.0));
627        self
628    }
629
630    pub fn show_value(mut self, show_value: bool) -> Self {
631        self.show_value = show_value;
632        self
633    }
634
635    pub(super) fn fraction(&self) -> f32 {
636        if (self.max - self.min).abs() <= f64::EPSILON {
637            0.0
638        } else {
639            ((self.value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) as f32
640        }
641    }
642
643    pub(super) fn resolved_theme(&self) -> DefaultTheme {
644        self.theme_reader
645            .as_ref()
646            .map(|theme| theme())
647            .unwrap_or(*self.theme)
648    }
649}
650
651pub fn paint_progress_bar(
652    ctx: &mut PaintCtx,
653    rect: Rect,
654    theme: &DefaultTheme,
655    fraction: f32,
656    tone: SemanticTone,
657) {
658    if rect.width() <= 0.0 || rect.height() <= 0.0 {
659        return;
660    }
661
662    let metrics = theme.metrics;
663    let palette = theme.palette;
664    let (tone, _) = theme.semantic_tone_colors(tone);
665    draw_control_shape(
666        ctx,
667        rect,
668        metrics.corner_radius,
669        physical_pixels(ctx, metrics.border_width).min(rect.height() * 0.5),
670        palette.control,
671        palette.border,
672    );
673
674    let fill = Rect::new(
675        rect.x(),
676        rect.y(),
677        rect.width() * fraction.clamp(0.0, 1.0),
678        rect.height(),
679    );
680    if fill.width() > 0.0 {
681        ctx.fill(rounded_rect_path(fill, metrics.corner_radius), tone);
682    }
683}
684
685impl Widget for ProgressBar {
686    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
687        let theme = self.resolved_theme();
688        let metrics = theme.metrics;
689        let min_height = if let Some(height) = self.height {
690            height
691        } else if self.show_value {
692            metrics
693                .progress_bar_value_height
694                .max(text_token_style(&theme, theme.text.sm, theme.palette.text).line_height)
695        } else {
696            metrics.progress_bar_height
697        };
698        constraints.clamp(Size::new(
699            self.min_width.unwrap_or(metrics.progress_bar_min_width),
700            min_height,
701        ))
702    }
703
704    fn paint(&self, ctx: &mut PaintCtx) {
705        let theme = self.resolved_theme();
706        let metrics = theme.metrics;
707        let (_, tone_text) = theme.semantic_tone_colors(self.tone);
708        paint_progress_bar(ctx, ctx.bounds(), &theme, self.fraction(), self.tone);
709        if self.show_value {
710            let label = format!("{:.0}%", self.fraction() * 100.0);
711            let text_style = numeric_text_style(text_token_style(&theme, theme.text.sm, tone_text));
712            let label_padding = Insets {
713                top: 0.0,
714                bottom: 0.0,
715                ..metrics.progress_bar_label_padding
716            };
717            let label_slot = inset_rect(ctx.bounds(), label_padding);
718            ctx.push_clip_rect(label_slot);
719            paint_aligned_text(
720                ctx,
721                label_slot,
722                &label,
723                &text_style,
724                text_style.line_height,
725                0.5,
726            );
727            ctx.pop_clip();
728        }
729    }
730
731    fn semantics(&self, ctx: &mut SemanticsCtx) {
732        let mut node =
733            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ProgressBar, ctx.bounds());
734        node.name = Some(self.name.clone());
735        node.value = Some(SemanticsValue::Range {
736            value: self.value,
737            min: self.min,
738            max: self.max,
739        });
740        ctx.push(node);
741    }
742}
743
744pub struct Spinner {
745    pub(super) theme: Box<DefaultTheme>,
746    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
747    pub(super) name: String,
748    pub(super) size: f32,
749    pub(super) label: Option<String>,
750}
751
752impl Spinner {
753    pub fn new(name: impl Into<String>) -> Self {
754        Self {
755            theme: Box::new(DefaultTheme::default()),
756            theme_reader: None,
757            name: name.into(),
758            size: 20.0,
759            label: None,
760        }
761    }
762
763    pub fn theme(mut self, theme: DefaultTheme) -> Self {
764        self.theme = Box::new(theme);
765        self.theme_reader = None;
766        self
767    }
768
769    pub fn theme_when<F>(mut self, theme: F) -> Self
770    where
771        F: Fn() -> DefaultTheme + 'static,
772    {
773        self.theme_reader = Some(Box::new(theme));
774        self
775    }
776
777    pub fn size(mut self, size: f32) -> Self {
778        self.size = size.max(8.0);
779        self
780    }
781
782    pub fn label(mut self, label: impl Into<String>) -> Self {
783        self.label = Some(label.into());
784        self
785    }
786
787    pub(super) fn indicator_rect(&self, bounds: Rect) -> Rect {
788        Rect::new(
789            bounds.x(),
790            bounds.y() + ((bounds.height() - self.size) * 0.5),
791            self.size,
792            self.size,
793        )
794    }
795
796    pub(super) fn resolved_theme(&self) -> DefaultTheme {
797        self.theme_reader
798            .as_ref()
799            .map(|theme| theme())
800            .unwrap_or(*self.theme)
801    }
802}
803
804impl Widget for Spinner {
805    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
806        let theme = self.resolved_theme();
807        let text_style = text_token_style(&theme, theme.text.sm, theme.palette.text);
808        let label_measurement = self
809            .label
810            .as_ref()
811            .map(|label| measure_text(ctx, label, &text_style));
812        let label_width = label_measurement
813            .map(|measurement| measurement.width + 12.0)
814            .unwrap_or(0.0);
815        let label_height = label_measurement
816            .map(|measurement| measurement.height.max(text_style.line_height))
817            .unwrap_or(0.0);
818        constraints.clamp(Size::new(
819            self.size + label_width,
820            self.size.max(20.0).max(label_height),
821        ))
822    }
823
824    fn paint(&self, ctx: &mut PaintCtx) {
825        let theme = self.resolved_theme();
826        let palette = theme.palette;
827        let indicator = self.indicator_rect(ctx.bounds());
828        let center = rect_center(indicator);
829        let radius = indicator.width().min(indicator.height()) * 0.4;
830        let dot_radius = (indicator.width() * 0.09).max(1.5);
831        for index in 0..10 {
832            let angle = (index as f32 / 10.0) * std::f32::consts::TAU;
833            let alpha = 0.22 + ((index as f32) / 10.0) * 0.72;
834            let color = Color::rgba(
835                palette.accent.red,
836                palette.accent.green,
837                palette.accent.blue,
838                alpha,
839            );
840            let dot = Point::new(
841                center.x + angle.cos() * radius,
842                center.y + angle.sin() * radius,
843            );
844            ctx.fill(Path::circle(dot, dot_radius), color);
845        }
846
847        if let Some(label) = &self.label {
848            let text_style = text_token_style(&theme, theme.text.sm, palette.text);
849            let text_slot = Rect::new(
850                indicator.max_x() + 12.0,
851                ctx.bounds().y(),
852                ctx.bounds().width() - indicator.width() - 12.0,
853                ctx.bounds().height(),
854            );
855            ctx.push_clip_rect(text_slot);
856            paint_aligned_text(
857                ctx,
858                text_slot,
859                label,
860                &text_style,
861                text_style.line_height,
862                0.0,
863            );
864            ctx.pop_clip();
865        }
866    }
867
868    fn semantics(&self, ctx: &mut SemanticsCtx) {
869        let mut node =
870            SemanticsNode::new(ctx.widget_id(), SemanticsRole::BusyIndicator, ctx.bounds());
871        node.name = Some(self.name.clone());
872        node.description = self.label.clone();
873        node.state.busy = true;
874        ctx.push(node);
875    }
876}
877
878pub type BusyIndicator = Spinner;
879
880pub(super) fn measure_text(ctx: &mut MeasureCtx, text: &str, style: &TextStyle) -> TextMeasurement {
881    ctx.layout()
882        .measure_text(text.to_string(), style.clone())
883        .unwrap_or(TextMeasurement {
884            width: 0.0,
885            height: style.line_height,
886            bounds: Rect::new(0.0, 0.0, 0.0, style.line_height),
887            ascent: style.font_size,
888            descent: 0.0,
889            cap_height: Some(style.font_size),
890        })
891}
892
893pub(super) fn text_token_style(
894    theme: &DefaultTheme,
895    token: ThemeTextToken,
896    color: Color,
897) -> TextStyle {
898    TextStyle {
899        font_size: token.size.max(1.0),
900        line_height: token.line_height.max(1.0),
901        color,
902        ..theme.body_text_style()
903    }
904}
905
906pub(super) fn semibold_control_text_style(theme: &DefaultTheme, color: Color) -> TextStyle {
907    let mut style = theme.text_style(color);
908    style.weight = FontWeight::SEMIBOLD;
909    style
910}
911
912pub(super) fn numeric_text_style(mut style: TextStyle) -> TextStyle {
913    style.features.enable(FontFeature::TABULAR_FIGURES);
914    style
915}
916
917pub(super) fn numeric_text_style_if_numeric(text: &str, style: TextStyle) -> TextStyle {
918    if text_contains_ascii_digit(text) {
919        numeric_text_style(style)
920    } else {
921        style
922    }
923}
924
925pub(super) fn text_contains_ascii_digit(text: &str) -> bool {
926    text.chars().any(|c| c.is_ascii_digit())
927}
928
929pub(super) fn rect_center(rect: Rect) -> Point {
930    Point::new(
931        rect.x() + (rect.width() * 0.5),
932        rect.y() + (rect.height() * 0.5),
933    )
934}
935
936pub(super) fn inset_rect(rect: Rect, padding: Insets) -> Rect {
937    Rect::new(
938        rect.x() + padding.left,
939        rect.y() + padding.top,
940        (rect.width() - padding.left - padding.right).max(0.0),
941        (rect.height() - padding.top - padding.bottom).max(0.0),
942    )
943}
944
945pub(super) fn rounded_rect_path(rect: Rect, radius: f32) -> Path {
946    Path::rounded_rect(rect, radius.min(rect.width().min(rect.height()) * 0.5))
947}
948
949pub(super) fn tab_indicator_rect<F>(
950    mut tab_rect: F,
951    from_index: usize,
952    selected_index: usize,
953    progress: f32,
954    padding: Insets,
955    thickness: f32,
956) -> Option<Rect>
957where
958    F: FnMut(usize) -> Option<Rect>,
959{
960    let to = tab_indicator_from_tab_rect(tab_rect(selected_index)?, padding, thickness);
961    let from = tab_rect(from_index)
962        .map(|rect| tab_indicator_from_tab_rect(rect, padding, thickness))
963        .unwrap_or(to);
964    Some(lerp_rect(from, to, progress))
965}
966
967pub(super) fn tab_indicator_from_tab_rect(rect: Rect, padding: Insets, thickness: f32) -> Rect {
968    Rect::new(
969        rect.x() + padding.left,
970        rect.max_y() - thickness,
971        (rect.width() - padding.left - padding.right).max(0.0),
972        thickness,
973    )
974}
975
976pub(super) fn sliding_inset_rect<F>(
977    mut item_rect: F,
978    from_index: usize,
979    selected_index: usize,
980    progress: f32,
981    insets: Insets,
982) -> Option<Rect>
983where
984    F: FnMut(usize) -> Option<Rect>,
985{
986    let to = inset_rect(item_rect(selected_index)?, insets);
987    let from = item_rect(from_index)
988        .map(|rect| inset_rect(rect, insets))
989        .unwrap_or(to);
990    Some(lerp_rect(from, to, progress))
991}
992
993pub(super) fn tab_panel_transition_translation(
994    from_index: usize,
995    selected_index: usize,
996    progress: f32,
997    metrics: ControlMetrics,
998) -> Vector {
999    if from_index == selected_index {
1000        return Vector::ZERO;
1001    }
1002
1003    let remaining = 1.0 - progress.clamp(0.0, 1.0);
1004    if remaining <= AnimatedScalar::EPSILON {
1005        return Vector::ZERO;
1006    }
1007
1008    let direction = if selected_index > from_index {
1009        1.0
1010    } else {
1011        -1.0
1012    };
1013    Vector::new(direction * metrics.tab_panel_gap * remaining, 0.0)
1014}
1015
1016pub(super) fn lerp_rect(from: Rect, to: Rect, progress: f32) -> Rect {
1017    let progress = progress.clamp(0.0, 1.0);
1018    Rect::new(
1019        f32::interpolate(from.x(), to.x(), progress),
1020        f32::interpolate(from.y(), to.y(), progress),
1021        f32::interpolate(from.width(), to.width(), progress),
1022        f32::interpolate(from.height(), to.height(), progress),
1023    )
1024}
1025
1026pub(super) fn tab_state_visuals(
1027    theme: &DefaultTheme,
1028    selected: bool,
1029    hovered: bool,
1030    pressed: bool,
1031    hover_amount: f32,
1032    press_amount: f32,
1033) -> Option<(Color, Color)> {
1034    let palette = theme.palette;
1035    let interaction = theme.interaction;
1036    if selected {
1037        Some((palette.selection, palette.selection_border))
1038    } else if pressed || press_amount > 0.0 {
1039        Some((
1040            mix_color(
1041                if hover_amount > 0.0 {
1042                    mix_color(
1043                        palette.control,
1044                        palette.control_hover,
1045                        interaction.hover_blend * hover_amount,
1046                    )
1047                } else {
1048                    palette.control
1049                },
1050                palette.control_active,
1051                interaction.pressed_blend * press_amount,
1052            ),
1053            palette.border_hover,
1054        ))
1055    } else if hovered || hover_amount > 0.0 {
1056        Some((
1057            mix_color(
1058                palette.control,
1059                palette.control_hover,
1060                interaction.hover_blend * hover_amount,
1061            ),
1062            palette.border_hover,
1063        ))
1064    } else {
1065        None
1066    }
1067}
1068
1069pub(super) fn draw_control_frame(
1070    ctx: &mut PaintCtx,
1071    bounds: Rect,
1072    radius: f32,
1073    metrics: ControlMetrics,
1074    background: Color,
1075    border: Color,
1076    focus_ring: Option<Color>,
1077) {
1078    draw_control_shape(
1079        ctx,
1080        bounds,
1081        radius,
1082        physical_pixels(ctx, metrics.border_width),
1083        background,
1084        border,
1085    );
1086
1087    if let Some(focus_ring) = focus_ring {
1088        draw_focus_ring_frame(ctx, bounds, radius, metrics, focus_ring);
1089    }
1090}
1091
1092pub(super) fn draw_focus_ring_frame(
1093    ctx: &mut PaintCtx,
1094    bounds: Rect,
1095    radius: f32,
1096    metrics: ControlMetrics,
1097    focus_ring: Color,
1098) {
1099    let focus_ring_outset = physical_pixels(ctx, metrics.focus_ring_outset);
1100    ctx.stroke(
1101        rounded_rect_path(
1102            bounds.inflate(focus_ring_outset, focus_ring_outset),
1103            radius + focus_ring_outset,
1104        ),
1105        focus_ring,
1106        StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
1107    );
1108}
1109
1110pub(super) fn draw_control_shape(
1111    ctx: &mut PaintCtx,
1112    bounds: Rect,
1113    radius: f32,
1114    border_width: f32,
1115    background: Color,
1116    border: Color,
1117) {
1118    let shape = rounded_rect_path(bounds, radius);
1119    ctx.fill(shape.clone(), background);
1120    ctx.stroke(shape, border, StrokeStyle::new(border_width));
1121}
1122
1123pub(super) fn mix_color(left: Color, right: Color, amount: f32) -> Color {
1124    crate::animation::Interpolate::interpolate(left, right, amount)
1125}
1126
1127pub(super) fn draw_popover_arrival_overlay(
1128    ctx: &mut PaintCtx,
1129    rect: Rect,
1130    metrics: ControlMetrics,
1131    background: Color,
1132    border: Color,
1133    arrival_effect: ResolvedEffectStyle,
1134) {
1135    let overlay_inset = physical_pixels(ctx, 1.0);
1136    let overlay_rect = rect.inflate(-overlay_inset, -overlay_inset);
1137    let overlay_radius = (metrics.corner_radius + 2.0 - overlay_inset).max(0.0);
1138    let overlay_fill = mix_color(background, arrival_effect.color, 0.35)
1139        .with_alpha((0.10 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.22));
1140    let stroke_color = apply_hdr_policy_cap(
1141        mix_color(border, arrival_effect.color, 0.55),
1142        arrival_effect
1143            .color
1144            .red
1145            .max(arrival_effect.color.green.max(arrival_effect.color.blue)),
1146    )
1147    .with_alpha((0.16 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.30));
1148
1149    ctx.fill(
1150        rounded_rect_path(overlay_rect, overlay_radius),
1151        overlay_fill,
1152    );
1153    ctx.stroke(
1154        rounded_rect_path(
1155            overlay_rect.inflate(-overlay_inset * 0.5, -overlay_inset * 0.5),
1156            (overlay_radius - (overlay_inset * 0.5)).max(0.0),
1157        ),
1158        stroke_color,
1159        StrokeStyle::new(physical_pixels(ctx, 1.0)),
1160    );
1161}
1162
1163pub(super) fn tooltip_tail(trigger: Rect, bubble: Rect, placement: TooltipPlacement) -> Path {
1164    let center_x = rect_center(trigger)
1165        .x
1166        .clamp(bubble.x() + 12.0, bubble.max_x() - 12.0);
1167    let mut builder = PathBuilder::new();
1168    match placement {
1169        TooltipPlacement::Above => {
1170            builder
1171                .move_to(Point::new(center_x - 6.0, bubble.max_y() - 1.0))
1172                .line_to(Point::new(center_x + 6.0, bubble.max_y() - 1.0))
1173                .line_to(Point::new(center_x, bubble.max_y() + 8.0));
1174        }
1175        TooltipPlacement::Below => {
1176            builder
1177                .move_to(Point::new(center_x - 6.0, bubble.y() + 1.0))
1178                .line_to(Point::new(center_x + 6.0, bubble.y() + 1.0))
1179                .line_to(Point::new(center_x, bubble.y() - 8.0));
1180        }
1181    }
1182    builder.build()
1183}
1184
1185pub(super) fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
1186    if value <= 0.0 {
1187        return 0.0;
1188    }
1189    ctx.dpi().physical_pixels_to_logical(value)
1190}