Skip to main content

sui_widgets/composites/
status.rs

1use crate::ControlMetrics;
2use crate::DefaultTheme;
3use crate::IconGlyph;
4use crate::Progress;
5use crate::SemanticTone;
6use crate::binding::Binding;
7use crate::composites::forms::{
8    set_focus_animation_target, set_hover_animation_target, set_item_press,
9};
10use crate::composites::indicators::{
11    numeric_text_style_if_numeric, semibold_control_text_style, text_token_style,
12};
13use crate::composites::painting::{EmptyStatePaint, paint_empty_state};
14use crate::controls::draw_icon_glyph;
15use crate::draw::{inset_rect, measure_text, mix_color};
16use crate::frame::{draw_control_shape, draw_focus_ring, physical_pixels};
17use crate::text_align::paint_aligned_text_contained;
18use crate::text_align::paint_text;
19use sui_core::Color;
20use sui_core::Event;
21use sui_core::KeyState;
22use sui_core::Path;
23use sui_core::Point;
24use sui_core::PointerButton;
25use sui_core::PointerEventKind;
26use sui_core::Rect;
27use sui_core::SemanticsAction;
28use sui_core::SemanticsNode;
29use sui_core::SemanticsRole;
30use sui_core::SemanticsValue;
31use sui_core::Size;
32use sui_core::Vector;
33use sui_core::WidgetId;
34use sui_layout::Constraints;
35use sui_reactive::Observable;
36use sui_runtime::ArrangeCtx;
37use sui_runtime::EventCtx;
38use sui_runtime::FrameClock;
39use sui_runtime::MeasureCtx;
40use sui_runtime::PaintCtx;
41use sui_runtime::SemanticsCtx;
42use sui_runtime::SingleChild;
43use sui_runtime::Widget;
44use sui_runtime::WidgetPod;
45use sui_runtime::WidgetPodMutVisitor;
46use sui_runtime::WidgetPodVisitor;
47use sui_scene::StrokeStyle;
48use sui_text::TextStyle;
49use sui_text::{TextAlign, TextMeasurement};
50
51pub struct EmptyState {
52    pub(super) theme: Box<DefaultTheme>,
53    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
54    pub(super) name: Option<String>,
55    pub(super) icon: Option<IconGlyph>,
56    pub(super) title: String,
57    pub(super) description: String,
58    pub(super) detail: Option<String>,
59    pub(super) action: Option<SingleChild>,
60    pub(super) action_height: f32,
61    pub(super) action_max_width: f32,
62    pub(super) background: Option<Color>,
63}
64
65impl EmptyState {
66    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
67        Self {
68            theme: Box::new(DefaultTheme::default()),
69            theme_reader: None,
70            name: None,
71            icon: None,
72            title: title.into(),
73            description: description.into(),
74            detail: None,
75            action: None,
76            action_height: 32.0,
77            action_max_width: 360.0,
78            background: None,
79        }
80    }
81
82    pub fn theme(mut self, theme: DefaultTheme) -> Self {
83        self.theme = Box::new(theme);
84        self.theme_reader = None;
85        self
86    }
87
88    pub fn theme_when<F>(mut self, theme: F) -> Self
89    where
90        F: Fn() -> DefaultTheme + 'static,
91    {
92        self.theme_reader = Some(Box::new(theme));
93        self
94    }
95
96    pub fn name(mut self, name: impl Into<String>) -> Self {
97        self.name = Some(name.into());
98        self
99    }
100
101    pub fn icon(mut self, icon: IconGlyph) -> Self {
102        self.icon = Some(icon);
103        self
104    }
105
106    pub fn detail(mut self, detail: impl Into<String>) -> Self {
107        self.detail = Some(detail.into());
108        self
109    }
110
111    pub fn action<W>(mut self, action: W) -> Self
112    where
113        W: Widget + 'static,
114    {
115        self.action = Some(SingleChild::new(action));
116        self
117    }
118
119    pub fn action_height(mut self, height: f32) -> Self {
120        self.action_height = height.max(32.0);
121        self
122    }
123
124    pub fn action_max_width(mut self, width: f32) -> Self {
125        self.action_max_width = width.max(0.0);
126        self
127    }
128
129    pub fn background(mut self, color: Color) -> Self {
130        self.background = Some(color);
131        self
132    }
133
134    pub fn transparent(mut self) -> Self {
135        self.background = Some(Color::TRANSPARENT);
136        self
137    }
138
139    pub fn action_child(&self) -> Option<&WidgetPod> {
140        self.action.as_ref().map(SingleChild::child)
141    }
142
143    pub fn action_child_mut(&mut self) -> Option<&mut WidgetPod> {
144        self.action.as_mut().map(SingleChild::child_mut)
145    }
146
147    pub(super) fn resolved_theme(&self) -> DefaultTheme {
148        self.theme_reader
149            .as_ref()
150            .map(|reader| reader())
151            .unwrap_or_else(|| *self.theme)
152    }
153
154    pub(super) fn action_rect(
155        bounds: Rect,
156        action_size: Size,
157        action_max_width: f32,
158        action_height: f32,
159    ) -> Rect {
160        let max_width = action_max_width.min((bounds.width() - 32.0).max(0.0));
161        let width = action_size.width.min(max_width).max(0.0);
162        let height = action_size.height.max(action_height);
163        let cx = bounds.x() + bounds.width() * 0.5;
164        let cy = bounds.y() + bounds.height() * 0.5 - 18.0;
165        Rect::new(cx - width * 0.5, cy + 54.0, width, height)
166    }
167}
168
169impl Widget for EmptyState {
170    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
171        let width = if constraints.max.width.is_finite() {
172            constraints.max.width
173        } else {
174            constraints.min.width.max(self.action_max_width + 32.0)
175        };
176        let action_height = if let Some(action) = &mut self.action {
177            let action_width = self.action_max_width.min((width - 32.0).max(0.0));
178            let action_size = action.measure(
179                ctx,
180                Constraints::new(
181                    Size::new(0.0, self.action_height),
182                    Size::new(action_width, f32::INFINITY),
183                ),
184            );
185            action_size.height.max(self.action_height)
186        } else {
187            0.0
188        };
189        let height = if constraints.max.height.is_finite() {
190            constraints.max.height
191        } else {
192            constraints
193                .min
194                .height
195                .max(142.0 + action_height + if action_height > 0.0 { 12.0 } else { 0.0 })
196        };
197        constraints.clamp(Size::new(width, height))
198    }
199
200    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
201        let action_max_width = self.action_max_width;
202        let action_height = self.action_height;
203        if let Some(action) = &mut self.action {
204            let action_rect = Self::action_rect(
205                bounds,
206                action.child().measured_size(),
207                action_max_width,
208                action_height,
209            );
210            action.arrange(ctx, action_rect);
211        }
212    }
213
214    fn paint(&self, ctx: &mut PaintCtx) {
215        let theme = self.resolved_theme();
216        let bounds = ctx.bounds();
217        let mut paint = EmptyStatePaint::new(&self.title, &self.description)
218            .background(self.background.unwrap_or(theme.surfaces.window))
219            .reserve_action_space(self.action.is_some());
220        if let Some(icon) = self.icon {
221            paint = paint.icon(icon);
222        }
223        if let Some(detail) = self.detail.as_deref() {
224            paint = paint.detail(detail);
225        }
226        ctx.push_clip_rect(bounds);
227        paint_empty_state(ctx, &theme, bounds, paint);
228
229        if let Some(action) = &self.action {
230            action.paint(ctx);
231        }
232        ctx.pop_clip();
233    }
234
235    fn semantics(&self, ctx: &mut SemanticsCtx) {
236        let mut node = SemanticsNode::new(
237            ctx.widget_id(),
238            SemanticsRole::GenericContainer,
239            ctx.bounds(),
240        );
241        node.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
242        node.description = Some(match &self.detail {
243            Some(detail)
244                if matches!(
245                    self.description.chars().last(),
246                    Some('.') | Some('!') | Some('?')
247                ) =>
248            {
249                format!("{} {}", self.description, detail)
250            }
251            Some(detail) => format!("{}. {}", self.description, detail),
252            None => self.description.clone(),
253        });
254        ctx.push(node);
255        if let Some(action) = &self.action {
256            action.semantics(ctx);
257        }
258    }
259
260    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
261        if let Some(action) = &self.action {
262            action.visit_children(visitor);
263        }
264    }
265
266    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
267        if let Some(action) = &mut self.action {
268            action.visit_children_mut(visitor);
269        }
270    }
271}
272
273pub struct PresetStrip {
274    pub(super) theme: Box<DefaultTheme>,
275    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
276    pub(super) enabled: Binding<bool>,
277    pub(super) name: String,
278    pub(super) presets: Vec<String>,
279    pub(super) selected: Option<usize>,
280    pub(super) selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
281    pub(super) hovered: Option<usize>,
282    pub(super) hover_visual: Option<usize>,
283    pub(super) pressed: Option<usize>,
284    pub(super) press_visual: Option<usize>,
285    pub(super) hover_animation: Progress,
286    pub(super) press_animation: Progress,
287    pub(super) focus_animation: Progress,
288    pub(super) item_width: Option<f32>,
289    pub(super) item_height: Option<f32>,
290    pub(super) gap: Option<f32>,
291    pub(super) label_measurements: Vec<TextMeasurement>,
292    pub(super) item_widths: Vec<f32>,
293    pub(super) on_change: Option<Box<dyn FnMut(usize, String)>>,
294    pub(super) on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String)>>,
295}
296
297impl PresetStrip {
298    pub fn new(name: impl Into<String>) -> Self {
299        Self {
300            theme: Box::new(DefaultTheme::default()),
301            theme_reader: None,
302            enabled: Binding::new(true),
303            name: name.into(),
304            presets: Vec::new(),
305            selected: None,
306            selected_reader: None,
307            hovered: None,
308            hover_visual: None,
309            pressed: None,
310            press_visual: None,
311            hover_animation: Progress::new(0.0),
312            press_animation: Progress::new(0.0),
313            focus_animation: Progress::new(0.0),
314            item_width: None,
315            item_height: None,
316            gap: None,
317            label_measurements: Vec::new(),
318            item_widths: Vec::new(),
319            on_change: None,
320            on_change_with_ctx: None,
321        }
322    }
323
324    pub fn theme(mut self, theme: DefaultTheme) -> Self {
325        self.theme = Box::new(theme);
326        self.theme_reader = None;
327        self
328    }
329
330    pub fn theme_when<F>(mut self, theme: F) -> Self
331    where
332        F: Fn() -> DefaultTheme + 'static,
333    {
334        self.theme_reader = Some(Box::new(theme));
335        self
336    }
337
338    /// Whether the user can use the widget. Disabled, it ignores input,
339    /// can't take focus, draws in the theme's disabled colors, and tells
340    /// assistive technology it and its items are unavailable.
341    pub fn enabled(mut self, enabled: bool) -> Self {
342        self.enabled.set(enabled);
343        self
344    }
345
346    /// [`Self::enabled`], read whenever the widget needs it.
347    pub fn enabled_when<F>(mut self, enabled: F) -> Self
348    where
349        F: Fn() -> bool + 'static,
350    {
351        self.enabled.set_when(enabled);
352        self
353    }
354
355    /// [`Self::enabled`], following an observable and repainting when it
356    /// changes.
357    pub fn enabled_from<O>(mut self, enabled: O) -> Self
358    where
359        O: Observable<bool> + 'static,
360    {
361        self.enabled.set_from(enabled);
362        self
363    }
364
365    pub fn is_enabled(&self) -> bool {
366        self.enabled.get()
367    }
368
369    /// The theme to paint with: the disabled look while the widget is
370    /// disabled.
371    fn paint_theme(&self) -> DefaultTheme {
372        let theme = self.resolved_theme();
373        if self.enabled.get() {
374            theme
375        } else {
376            theme.for_disabled_control()
377        }
378    }
379
380    pub fn preset(mut self, preset: impl Into<String>) -> Self {
381        self.presets.push(preset.into());
382        self
383    }
384
385    pub fn presets<I, S>(mut self, presets: I) -> Self
386    where
387        I: IntoIterator<Item = S>,
388        S: Into<String>,
389    {
390        self.presets.extend(presets.into_iter().map(Into::into));
391        self
392    }
393
394    /// Select item `index`, or nothing with `None`; `selected(2)` and
395    /// `selected(None)` both work.
396    pub fn selected(mut self, selected: impl Into<Option<usize>>) -> Self {
397        let selected = selected.into();
398        self.selected = selected;
399        self.selected_reader = None;
400        self
401    }
402
403    pub fn selected_when<F>(mut self, selected: F) -> Self
404    where
405        F: Fn() -> Option<usize> + 'static,
406    {
407        self.selected_reader = Some(Box::new(selected));
408        self
409    }
410
411    pub fn item_width(mut self, width: f32) -> Self {
412        self.item_width = Some(width.max(0.0));
413        self
414    }
415
416    pub fn item_height(mut self, height: f32) -> Self {
417        self.item_height = Some(height.max(20.0));
418        self
419    }
420
421    pub fn gap(mut self, gap: f32) -> Self {
422        self.gap = Some(gap.max(0.0));
423        self
424    }
425
426    pub fn on_change<F>(mut self, on_change: F) -> Self
427    where
428        F: FnMut(usize, String) + 'static,
429    {
430        self.on_change = Some(Box::new(on_change));
431        self
432    }
433
434    /// [`Self::on_change`], with the event context first.
435    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
436    where
437        F: FnMut(&mut EventCtx, usize, String) + 'static,
438    {
439        self.on_change_with_ctx = Some(Box::new(on_change));
440        self
441    }
442
443    pub fn selected_index(&self) -> Option<usize> {
444        self.current_selected()
445    }
446
447    pub(super) fn current_selected(&self) -> Option<usize> {
448        self.selected_reader
449            .as_ref()
450            .map(|selected| selected())
451            .unwrap_or(self.selected)
452            .filter(|index| *index < self.presets.len())
453    }
454
455    pub(super) fn resolved_theme(&self) -> DefaultTheme {
456        self.theme_reader
457            .as_ref()
458            .map(|theme| theme())
459            .unwrap_or_else(|| *self.theme)
460    }
461
462    pub(super) fn resolved_item_height(&self, metrics: ControlMetrics) -> f32 {
463        self.item_height.unwrap_or(metrics.preset_strip_item_height)
464    }
465
466    pub(super) fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
467        self.gap.unwrap_or(metrics.preset_strip_gap)
468    }
469
470    pub(super) fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
471        if index >= self.presets.len() || self.item_widths.len() != self.presets.len() {
472            return None;
473        }
474
475        let metrics = self.resolved_theme().metrics;
476        let item_height = self.resolved_item_height(metrics);
477        let gap = self.resolved_gap(metrics);
478        let mut x = bounds.x();
479        for (current, width) in self.item_widths.iter().enumerate() {
480            let available = (bounds.max_x() - x).max(0.0);
481            let rect = Rect::new(x, bounds.y(), width.min(available), item_height);
482            if current == index {
483                return (!rect.is_empty()).then_some(rect);
484            }
485            x += *width + gap;
486        }
487
488        None
489    }
490
491    pub(super) fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
492        self.presets.iter().enumerate().find_map(|(index, _)| {
493            self.item_rect(bounds, index)
494                .filter(|rect| rect.contains(position))
495                .map(|_| index)
496        })
497    }
498
499    pub(super) fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
500        if self.presets.is_empty() {
501            return;
502        }
503
504        let index = index.min(self.presets.len() - 1);
505        self.selected = Some(index);
506        if let Some(on_change) = &mut self.on_change {
507            on_change(index, self.presets[index].clone());
508        }
509        if let Some(on_change) = &mut self.on_change_with_ctx {
510            on_change(ctx, index, self.presets[index].clone());
511        }
512    }
513
514    pub(super) fn move_selection(&mut self, ctx: &mut EventCtx, delta: isize) {
515        if self.presets.is_empty() {
516            return;
517        }
518
519        let current = self.current_selected().unwrap_or(0) as isize;
520        let last = self.presets.len() as isize - 1;
521        let next = (current + delta).clamp(0, last) as usize;
522        self.hovered = Some(next);
523        self.activate(ctx, next);
524    }
525
526    pub(super) fn selected_text(&self) -> Option<String> {
527        self.current_selected()
528            .and_then(|index| self.presets.get(index).cloned())
529    }
530
531    pub(super) fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
532        if self.hovered == hovered {
533            return;
534        }
535        let theme = self.resolved_theme();
536        self.hovered = hovered;
537        if let Some(index) = hovered {
538            self.hover_visual = Some(index);
539            self.hover_animation = Progress::new(0.0);
540            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
541        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
542            self.hover_visual = None;
543        }
544        ctx.request_paint();
545        ctx.request_semantics();
546    }
547
548    pub(super) fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
549        if self.pressed == pressed {
550            return;
551        }
552        let theme = self.resolved_theme();
553        set_item_press(
554            &mut self.pressed,
555            &mut self.press_visual,
556            &mut self.press_animation,
557            pressed,
558            &theme,
559            ctx,
560        );
561    }
562
563    pub(super) fn hover_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
564        if self.hover_visual == Some(index) {
565            self.hover_animation.get(clock)
566        } else {
567            0.0
568        }
569    }
570
571    pub(super) fn press_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
572        if self.press_visual == Some(index) {
573            self.press_animation.get(clock)
574        } else {
575            0.0
576        }
577    }
578}
579
580impl Widget for PresetStrip {
581    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
582        if !self.enabled.get() {
583            // Disabled, the widget takes no input, but it lets go of a
584            // pointer it captured while enabled.
585            if let Event::Pointer(pointer) = event
586                && pointer.kind == PointerEventKind::Up
587            {
588                ctx.release_pointer_capture(pointer.pointer_id);
589            }
590            return;
591        }
592        match event {
593            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
594                self.set_hovered(self.item_at(ctx.bounds(), pointer.position), ctx);
595            }
596            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
597                self.set_hovered(None, ctx);
598            }
599            Event::Pointer(pointer)
600                if pointer.kind == PointerEventKind::Down
601                    && pointer.button == Some(PointerButton::Primary) =>
602            {
603                let hovered = self.item_at(ctx.bounds(), pointer.position);
604                self.set_hovered(hovered, ctx);
605                self.set_pressed(hovered, ctx);
606                if self.hovered.is_some() {
607                    ctx.request_focus();
608                    ctx.request_pointer_capture(pointer.pointer_id);
609                    ctx.set_handled();
610                }
611            }
612            Event::Pointer(pointer)
613                if pointer.kind == PointerEventKind::Up
614                    && pointer.button == Some(PointerButton::Primary) =>
615            {
616                let hovered = self.item_at(ctx.bounds(), pointer.position);
617                if let Some(index) = self
618                    .pressed
619                    .zip(hovered)
620                    .filter(|(left, right)| left == right)
621                    .map(|(index, _)| index)
622                {
623                    self.activate(ctx, index);
624                }
625                self.set_hovered(hovered, ctx);
626                self.set_pressed(None, ctx);
627                ctx.release_pointer_capture(pointer.pointer_id);
628                ctx.set_handled();
629            }
630            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
631                if self.pressed.is_some() {
632                    self.set_pressed(None, ctx);
633                    self.set_hovered(None, ctx);
634                    ctx.release_pointer_capture(pointer.pointer_id);
635                    ctx.set_handled();
636                }
637            }
638            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
639                match key.key.as_str() {
640                    "ArrowLeft" | "ArrowUp" => self.move_selection(ctx, -1),
641                    "ArrowRight" | "ArrowDown" => self.move_selection(ctx, 1),
642                    "Home" => self.activate(ctx, 0),
643                    "End" if !self.presets.is_empty() => self.activate(ctx, self.presets.len() - 1),
644                    "Enter" | " " => {
645                        if let Some(selected) = self.current_selected().or(Some(0)) {
646                            self.activate(ctx, selected);
647                        }
648                    }
649                    _ => return,
650                }
651                ctx.request_paint();
652                ctx.request_semantics();
653                ctx.set_handled();
654            }
655            _ => {}
656        }
657    }
658
659    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
660        let theme = self.resolved_theme();
661        let metrics = theme.metrics;
662        let item_height = self.resolved_item_height(metrics);
663        let gap = self.resolved_gap(metrics);
664        let style = theme.text_style(theme.palette.text);
665        self.label_measurements = self
666            .presets
667            .iter()
668            .map(|preset| measure_text(ctx, preset, &style))
669            .collect();
670        self.item_widths = self
671            .label_measurements
672            .iter()
673            .map(|measurement| {
674                self.item_width.unwrap_or(
675                    (measurement.width
676                        + metrics.preset_strip_item_padding.left
677                        + metrics.preset_strip_item_padding.right)
678                        .max(metrics.preset_strip_item_min_width),
679                )
680            })
681            .collect();
682
683        let width = self.item_widths.iter().sum::<f32>()
684            + (gap * self.presets.len().saturating_sub(1) as f32);
685        constraints.clamp(Size::new(width, item_height))
686    }
687
688    fn paint(&self, ctx: &mut PaintCtx) {
689        self.enabled.observe(|source| {
690            ctx.observe(source);
691        });
692        let theme = self.paint_theme();
693        let palette = theme.palette;
694        let metrics = theme.metrics;
695        let interaction = theme.interaction;
696        let selected = self.current_selected();
697        let style = theme.text_style(palette.text);
698
699        if self.focus_animation.get(ctx) > Progress::EPSILON {
700            draw_focus_ring(
701                ctx,
702                ctx.bounds(),
703                metrics.corner_radius,
704                metrics,
705                palette
706                    .focus_ring
707                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.get(ctx)),
708            );
709        }
710
711        for (index, preset) in self.presets.iter().enumerate() {
712            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
713                continue;
714            };
715            let is_selected = selected == Some(index);
716            let is_hovered = self.hovered == Some(index);
717            let hover_amount = self.hover_amount_for(index, ctx);
718            let press_amount = self.press_amount_for(index, ctx);
719            let base_background = if is_selected {
720                palette.selection
721            } else {
722                palette.surface
723            };
724            let hover_background = if hover_amount > 0.0 {
725                mix_color(
726                    base_background,
727                    palette.control_hover,
728                    interaction.hover_blend * if is_selected { 0.35 } else { 1.0 } * hover_amount,
729                )
730            } else {
731                base_background
732            };
733            let background = if press_amount > 0.0 {
734                mix_color(
735                    hover_background,
736                    palette.control_active,
737                    interaction.pressed_blend * if is_selected { 0.45 } else { 1.0 } * press_amount,
738                )
739            } else {
740                hover_background
741            };
742            let border = if is_selected {
743                palette.selection_border
744            } else if is_hovered || hover_amount > 0.0 || press_amount > 0.0 {
745                palette.border_hover
746            } else {
747                palette.border
748            };
749            let text_color = palette.text;
750
751            draw_control_shape(
752                ctx,
753                rect,
754                metrics.corner_radius,
755                physical_pixels(ctx, metrics.border_width),
756                background,
757                border,
758            );
759
760            let text_slot = inset_rect(rect, metrics.preset_strip_label_padding);
761            let pressed_offset = press_amount * interaction.pressed_offset;
762            let text_style = TextStyle {
763                color: text_color,
764                ..style.clone()
765            };
766            ctx.push_clip_rect(text_slot);
767            paint_text(
768                ctx,
769                text_slot.translate(Vector::new(0.0, pressed_offset)),
770                preset,
771                &text_style,
772                TextAlign::Center,
773            );
774            ctx.pop_clip();
775        }
776    }
777
778    fn semantics(&self, ctx: &mut SemanticsCtx) {
779        self.enabled.observe(|source| {
780            ctx.observe(source);
781        });
782        let enabled = self.enabled.get();
783        let mut node = SemanticsNode::new(
784            ctx.widget_id(),
785            SemanticsRole::GenericContainer,
786            ctx.bounds(),
787        );
788        node.name = Some(self.name.clone());
789        node.value = self.selected_text().map(SemanticsValue::Text);
790        node.state.focused = ctx.is_focused();
791        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
792        if !enabled {
793            node.state.disabled = true;
794            node.actions.clear();
795        }
796        ctx.push(node);
797
798        let selected = self.current_selected();
799        for (index, preset) in self.presets.iter().enumerate() {
800            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
801                continue;
802            };
803            let mut item = SemanticsNode::new(
804                preset_strip_item_id(ctx.widget_id(), index),
805                SemanticsRole::Button,
806                rect,
807            );
808            item.parent = Some(ctx.widget_id());
809            item.name = Some(preset.clone());
810            item.value = Some(SemanticsValue::Text(preset.clone()));
811            item.state.hovered = self.hovered == Some(index);
812            item.state.selected = selected == Some(index);
813            item.actions = vec![SemanticsAction::Activate];
814            if !enabled {
815                item.state.disabled = true;
816                item.actions.clear();
817            }
818            ctx.push(item);
819        }
820    }
821
822    fn accepts_focus(&self) -> bool {
823        self.enabled.get() && (!self.presets.is_empty())
824    }
825
826    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
827        let theme = self.resolved_theme();
828        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
829        ctx.request_paint();
830        ctx.request_semantics();
831    }
832}
833
834pub(super) fn preset_strip_item_id(parent: WidgetId, index: usize) -> WidgetId {
835    const TAG: u64 = 6_u64 << 50;
836    const LOW_MASK: u64 = (1_u64 << 50) - 1;
837
838    WidgetId::new(
839        TAG | (parent
840            .get()
841            .wrapping_mul(487)
842            .wrapping_add(index as u64 + 1)
843            & LOW_MASK),
844    )
845}
846
847pub struct StatusBarSegment {
848    pub(super) text: String,
849    pub(super) reader: Option<Box<dyn Fn() -> String>>,
850    pub(super) min_width: Option<f32>,
851    pub(super) tone: SemanticTone,
852    pub(super) expand: bool,
853}
854
855impl StatusBarSegment {
856    pub fn new(text: impl Into<String>) -> Self {
857        Self {
858            text: text.into(),
859            reader: None,
860            min_width: None,
861            tone: SemanticTone::Neutral,
862            expand: false,
863        }
864    }
865
866    /// The text, read each time the status bar lays out.
867    pub fn text_when<F>(mut self, text: F) -> Self
868    where
869        F: Fn() -> String + 'static,
870    {
871        self.reader = Some(Box::new(text));
872        self
873    }
874
875    pub fn min_width(mut self, min_width: f32) -> Self {
876        self.min_width = Some(min_width.max(0.0));
877        self
878    }
879
880    pub fn tone(mut self, tone: SemanticTone) -> Self {
881        self.tone = tone;
882        self
883    }
884
885    pub fn expand(mut self, expand: bool) -> Self {
886        self.expand = expand;
887        self
888    }
889
890    pub(super) fn text(&self) -> String {
891        self.reader
892            .as_ref()
893            .map(|reader| reader())
894            .unwrap_or_else(|| self.text.clone())
895    }
896}
897
898pub struct StatusBar {
899    pub(super) theme: Box<DefaultTheme>,
900    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
901    pub(super) name: Option<String>,
902    pub(super) description: Option<String>,
903    pub(super) description_reader: Option<Box<dyn Fn() -> String>>,
904    pub(super) height: Option<f32>,
905    pub(super) segments: Vec<StatusBarSegment>,
906    pub(super) measured_widths: Vec<f32>,
907}
908
909impl StatusBar {
910    pub fn new() -> Self {
911        Self {
912            theme: Box::new(DefaultTheme::default()),
913            theme_reader: None,
914            name: None,
915            description: None,
916            description_reader: None,
917            height: None,
918            segments: Vec::new(),
919            measured_widths: Vec::new(),
920        }
921    }
922
923    pub fn theme(mut self, theme: DefaultTheme) -> Self {
924        self.theme = Box::new(theme);
925        self.theme_reader = None;
926        self
927    }
928
929    pub fn theme_when<F>(mut self, theme: F) -> Self
930    where
931        F: Fn() -> DefaultTheme + 'static,
932    {
933        self.theme_reader = Some(Box::new(theme));
934        self
935    }
936
937    pub fn name(mut self, name: impl Into<String>) -> Self {
938        self.name = Some(name.into());
939        self
940    }
941
942    pub fn description(mut self, description: impl Into<String>) -> Self {
943        self.description = Some(description.into());
944        self.description_reader = None;
945        self
946    }
947
948    pub fn description_when<F>(mut self, description: F) -> Self
949    where
950        F: Fn() -> String + 'static,
951    {
952        self.description_reader = Some(Box::new(description));
953        self
954    }
955
956    pub fn height(mut self, height: f32) -> Self {
957        self.height = Some(height.max(18.0));
958        self
959    }
960
961    pub fn segment(mut self, segment: StatusBarSegment) -> Self {
962        self.segments.push(segment);
963        self
964    }
965
966    pub fn text_segment(self, text: impl Into<String>) -> Self {
967        self.segment(StatusBarSegment::new(text))
968    }
969
970    pub(super) fn text_style(&self) -> TextStyle {
971        let theme = self.resolved_theme();
972        text_token_style(&theme, theme.text.xs, theme.palette.placeholder)
973    }
974
975    pub(super) fn resolved_theme(&self) -> DefaultTheme {
976        self.theme_reader
977            .as_ref()
978            .map(|theme| theme())
979            .unwrap_or_else(|| *self.theme)
980    }
981
982    pub(super) fn resolved_height(&self, metrics: ControlMetrics) -> f32 {
983        self.height.unwrap_or(metrics.status_bar_height)
984    }
985
986    pub(super) fn description_text(&self) -> Option<String> {
987        self.description_reader
988            .as_ref()
989            .map(|reader| reader())
990            .or_else(|| self.description.clone())
991    }
992
993    pub(super) fn resolved_segment_min_width(
994        segment: &StatusBarSegment,
995        metrics: ControlMetrics,
996    ) -> f32 {
997        segment
998            .min_width
999            .unwrap_or(metrics.status_bar_segment_min_width)
1000    }
1001
1002    pub(super) fn segment_widths(&self, metrics: ControlMetrics) -> Vec<f32> {
1003        if self.measured_widths.len() == self.segments.len() {
1004            self.measured_widths.clone()
1005        } else {
1006            self.segments
1007                .iter()
1008                .map(|segment| Self::resolved_segment_min_width(segment, metrics))
1009                .collect()
1010        }
1011    }
1012
1013    pub(super) fn segment_rects(&self, bounds: Rect, metrics: ControlMetrics) -> Vec<Rect> {
1014        let mut widths = self.segment_widths(metrics);
1015        let expandable = self
1016            .segments
1017            .iter()
1018            .filter(|segment| segment.expand)
1019            .count();
1020        if expandable > 0 {
1021            let fixed: f32 = widths.iter().sum();
1022            let extra = (bounds.width() - fixed).max(0.0) / expandable as f32;
1023            for (index, segment) in self.segments.iter().enumerate() {
1024                if segment.expand {
1025                    widths[index] += extra;
1026                }
1027            }
1028        }
1029
1030        let mut x = bounds.x();
1031        widths
1032            .into_iter()
1033            .map(|width| {
1034                let available = (bounds.max_x() - x).max(0.0);
1035                let rect = Rect::new(x, bounds.y(), width.min(available), bounds.height());
1036                x = rect.max_x();
1037                rect
1038            })
1039            .collect()
1040    }
1041}
1042
1043impl Default for StatusBar {
1044    fn default() -> Self {
1045        Self::new()
1046    }
1047}
1048
1049pub struct StatusBarHost {
1050    pub(super) content: SingleChild,
1051    pub(super) status_bar: SingleChild,
1052}
1053
1054impl StatusBarHost {
1055    pub fn new<C, S>(content: C, status_bar: S) -> Self
1056    where
1057        C: Widget + 'static,
1058        S: Widget + 'static,
1059    {
1060        Self {
1061            content: SingleChild::new(content),
1062            status_bar: SingleChild::new(status_bar),
1063        }
1064    }
1065
1066    pub fn content(&self) -> &sui_runtime::WidgetPod {
1067        self.content.child()
1068    }
1069
1070    pub fn content_mut(&mut self) -> &mut sui_runtime::WidgetPod {
1071        self.content.child_mut()
1072    }
1073
1074    pub fn status_bar(&self) -> &sui_runtime::WidgetPod {
1075        self.status_bar.child()
1076    }
1077
1078    pub fn status_bar_mut(&mut self) -> &mut sui_runtime::WidgetPod {
1079        self.status_bar.child_mut()
1080    }
1081}
1082
1083impl Widget for StatusBarHost {
1084    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1085        let max = constraints.max;
1086        let status_size = self.status_bar.measure(
1087            ctx,
1088            Constraints::new(Size::ZERO, Size::new(max.width, max.height)),
1089        );
1090        let content_max_height = if max.height.is_finite() {
1091            (max.height - status_size.height).max(0.0)
1092        } else {
1093            f32::INFINITY
1094        };
1095        let content_size = self.content.measure(
1096            ctx,
1097            Constraints::new(Size::ZERO, Size::new(max.width, content_max_height)),
1098        );
1099
1100        constraints.clamp(Size::new(
1101            content_size.width.max(status_size.width),
1102            content_size.height + status_size.height,
1103        ))
1104    }
1105
1106    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1107        let status_height = self
1108            .status_bar
1109            .child()
1110            .measured_size()
1111            .height
1112            .min(bounds.height())
1113            .max(0.0);
1114        let content_height = (bounds.height() - status_height).max(0.0);
1115
1116        self.content.arrange(
1117            ctx,
1118            Rect::new(bounds.x(), bounds.y(), bounds.width(), content_height),
1119        );
1120        self.status_bar.arrange(
1121            ctx,
1122            Rect::new(
1123                bounds.x(),
1124                bounds.y() + content_height,
1125                bounds.width(),
1126                status_height,
1127            ),
1128        );
1129    }
1130
1131    fn paint(&self, ctx: &mut PaintCtx) {
1132        self.content.paint(ctx);
1133        self.status_bar.paint(ctx);
1134    }
1135
1136    fn semantics(&self, ctx: &mut SemanticsCtx) {
1137        self.content.semantics(ctx);
1138        self.status_bar.semantics(ctx);
1139    }
1140
1141    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1142        self.content.visit_children(visitor);
1143        self.status_bar.visit_children(visitor);
1144    }
1145
1146    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1147        self.content.visit_children_mut(visitor);
1148        self.status_bar.visit_children_mut(visitor);
1149    }
1150}
1151
1152impl Widget for StatusBar {
1153    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1154        let theme = self.resolved_theme();
1155        let metrics = theme.metrics;
1156        let text_style = self.text_style();
1157        self.measured_widths = self
1158            .segments
1159            .iter()
1160            .map(|segment| {
1161                let text = segment.text();
1162                let segment_style = numeric_text_style_if_numeric(&text, text_style.clone());
1163                let measured = measure_text(ctx, &text, &segment_style).width
1164                    + metrics.status_bar_segment_padding * 2.0;
1165                Self::resolved_segment_min_width(segment, metrics).max(measured.ceil())
1166            })
1167            .collect();
1168        let natural_width: f32 = self.measured_widths.iter().sum();
1169        constraints.clamp(Size::new(
1170            if constraints.max.width.is_finite() {
1171                constraints.max.width
1172            } else {
1173                natural_width
1174            },
1175            self.resolved_height(metrics),
1176        ))
1177    }
1178
1179    fn paint(&self, ctx: &mut PaintCtx) {
1180        let theme = self.resolved_theme();
1181        let palette = theme.palette;
1182        let metrics = theme.metrics;
1183        let bounds = ctx.bounds();
1184        ctx.fill_bounds(palette.surface);
1185        ctx.stroke_rect(
1186            Rect::new(bounds.x(), bounds.y(), bounds.width(), 1.0),
1187            palette.border,
1188            StrokeStyle::new(theme.metrics.border_width.max(1.0)),
1189        );
1190
1191        let text_style = self.text_style();
1192        for (index, (segment, rect)) in self
1193            .segments
1194            .iter()
1195            .zip(self.segment_rects(bounds, metrics))
1196            .enumerate()
1197        {
1198            if rect.is_empty() {
1199                continue;
1200            }
1201            if index > 0 {
1202                let inset = metrics.status_bar_separator_inset.min(rect.height() * 0.5);
1203                ctx.stroke_rect(
1204                    Rect::new(
1205                        rect.x(),
1206                        rect.y() + inset,
1207                        1.0,
1208                        (rect.height() - inset * 2.0).max(0.0),
1209                    ),
1210                    palette.border.with_alpha(0.7),
1211                    StrokeStyle::new(1.0),
1212                );
1213            }
1214            let segment_text = segment.text();
1215            let segment_style = if segment.tone == SemanticTone::Neutral {
1216                text_style.clone()
1217            } else {
1218                let tone = theme.semantic_tone_color(segment.tone);
1219                let pill = Rect::new(
1220                    rect.x() + metrics.status_bar_separator_inset.min(rect.width() * 0.5),
1221                    rect.y() + metrics.status_bar_separator_inset.min(rect.height() * 0.5),
1222                    (rect.width() - metrics.status_bar_separator_inset * 2.0).max(0.0),
1223                    (rect.height() - metrics.status_bar_separator_inset * 2.0).max(0.0),
1224                );
1225                if !pill.is_empty() {
1226                    ctx.fill(
1227                        Path::rounded_rect(pill, metrics.indicator_corner_radius),
1228                        tone.with_alpha(0.12),
1229                    );
1230                }
1231                TextStyle {
1232                    color: tone,
1233                    ..text_style.clone()
1234                }
1235            };
1236            let segment_style = numeric_text_style_if_numeric(&segment_text, segment_style);
1237            let content_rect = Rect::new(
1238                rect.x() + metrics.status_bar_segment_padding,
1239                rect.y(),
1240                (rect.width() - metrics.status_bar_segment_padding * 2.0).max(0.0),
1241                rect.height(),
1242            );
1243            ctx.push_clip_rect(content_rect);
1244            paint_text(
1245                ctx,
1246                content_rect,
1247                &segment_text,
1248                &segment_style,
1249                TextAlign::Start,
1250            );
1251            ctx.pop_clip();
1252        }
1253    }
1254
1255    fn semantics(&self, ctx: &mut SemanticsCtx) {
1256        let theme = self.resolved_theme();
1257        let metrics = theme.metrics;
1258        let mut node = SemanticsNode::new(
1259            ctx.widget_id(),
1260            SemanticsRole::GenericContainer,
1261            ctx.bounds(),
1262        );
1263        node.name = self.name.clone();
1264        if let Some(description) = self.description_text() {
1265            node.value = Some(SemanticsValue::Text(description.clone()));
1266            node.description = Some(description);
1267        }
1268        ctx.push(node);
1269
1270        for (index, (segment, rect)) in self
1271            .segments
1272            .iter()
1273            .zip(self.segment_rects(ctx.bounds(), metrics))
1274            .enumerate()
1275        {
1276            let text = segment.text();
1277            let mut child = SemanticsNode::new(
1278                status_bar_segment_id(ctx.widget_id(), index),
1279                SemanticsRole::Text,
1280                rect,
1281            );
1282            child.parent = Some(ctx.widget_id());
1283            child.name = Some(text.clone());
1284            child.value = Some(SemanticsValue::Text(text));
1285            ctx.push(child);
1286        }
1287    }
1288}
1289
1290pub(super) fn status_bar_segment_id(parent: WidgetId, index: usize) -> WidgetId {
1291    const TAG: u64 = 2_u64 << 51;
1292    const LOW_MASK: u64 = (1_u64 << 51) - 1;
1293
1294    WidgetId::new(
1295        TAG | (parent
1296            .get()
1297            .wrapping_mul(263)
1298            .wrapping_add(index as u64 + 1)
1299            & LOW_MASK),
1300    )
1301}
1302
1303pub(super) type SegmentedControlChange = Box<dyn FnMut(usize, String)>;
1304pub(super) type SegmentedControlContextChange = Box<dyn FnMut(&mut EventCtx, usize, String)>;
1305
1306pub(super) fn segmented_control_item_id(parent: WidgetId, index: usize) -> WidgetId {
1307    const TAG: u64 = 3_u64 << 51;
1308    const LOW_MASK: u64 = (1_u64 << 51) - 1;
1309
1310    WidgetId::new(
1311        TAG | (parent
1312            .get()
1313            .wrapping_mul(269)
1314            .wrapping_add(index as u64 + 1)
1315            & LOW_MASK),
1316    )
1317}
1318
1319pub struct StatusBadge {
1320    pub(super) theme: Box<DefaultTheme>,
1321    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1322    pub(super) label: Binding<String>,
1323    pub(super) icon: Option<IconGlyph>,
1324    pub(super) tone: SemanticTone,
1325    pub(super) tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
1326    pub(super) min_width: Option<f32>,
1327}
1328
1329impl StatusBadge {
1330    pub fn new(label: impl Into<String>) -> Self {
1331        Self {
1332            theme: Box::new(DefaultTheme::default()),
1333            theme_reader: None,
1334            label: Binding::new(label.into()),
1335            icon: None,
1336            tone: SemanticTone::Neutral,
1337            tone_reader: None,
1338            min_width: None,
1339        }
1340    }
1341
1342    /// The label, read each time the badge lays out.
1343    pub fn label_when<F>(mut self, label: F) -> Self
1344    where
1345        F: Fn() -> String + 'static,
1346    {
1347        self.label.set_when(label);
1348        self
1349    }
1350
1351    /// The label, following an observable and laying out again when it
1352    /// changes.
1353    pub fn label_from<O>(mut self, label: O) -> Self
1354    where
1355        O: Observable<String> + 'static,
1356    {
1357        self.label.set_from(label);
1358        self
1359    }
1360
1361    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1362        self.theme = Box::new(theme);
1363        self.theme_reader = None;
1364        self
1365    }
1366
1367    pub fn theme_when<F>(mut self, theme: F) -> Self
1368    where
1369        F: Fn() -> DefaultTheme + 'static,
1370    {
1371        self.theme_reader = Some(Box::new(theme));
1372        self
1373    }
1374
1375    pub fn icon(mut self, icon: IconGlyph) -> Self {
1376        self.icon = Some(icon);
1377        self
1378    }
1379
1380    pub fn tone(mut self, tone: SemanticTone) -> Self {
1381        self.tone = tone;
1382        self.tone_reader = None;
1383        self
1384    }
1385
1386    pub fn tone_when<F>(mut self, tone: F) -> Self
1387    where
1388        F: Fn() -> SemanticTone + 'static,
1389    {
1390        self.tone_reader = Some(Box::new(tone));
1391        self
1392    }
1393
1394    pub fn min_width(mut self, min_width: f32) -> Self {
1395        self.min_width = Some(min_width.max(0.0));
1396        self
1397    }
1398
1399    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1400        self.theme_reader
1401            .as_ref()
1402            .map(|theme| theme())
1403            .unwrap_or_else(|| *self.theme)
1404    }
1405
1406    pub(super) fn label(&self) -> String {
1407        self.label.get()
1408    }
1409
1410    pub(super) fn resolved_tone(&self) -> SemanticTone {
1411        self.tone_reader
1412            .as_ref()
1413            .map(|reader| reader())
1414            .unwrap_or(self.tone)
1415    }
1416
1417    pub(super) fn text_style(
1418        &self,
1419        theme: &DefaultTheme,
1420        label: &str,
1421        tone: SemanticTone,
1422    ) -> TextStyle {
1423        // Mesh badge label: contextual control text at 600 in the status ink
1424        // that reads on the soft wash.
1425        let (_, tone_ink) = theme.semantic_tone_soft_colors(tone);
1426        let style = semibold_control_text_style(theme, tone_ink);
1427        numeric_text_style_if_numeric(label, style)
1428    }
1429
1430    pub(super) fn metrics(&self, theme: &DefaultTheme) -> (f32, f32, f32, f32) {
1431        let height = (theme.metrics.min_height - 2.0).max(22.0);
1432        let icon_size = (height - 13.0).clamp(11.0, 15.0);
1433        let gap = theme.metrics.icon_label_gap.max(4.0);
1434        let padding = theme.metrics.button_padding.left.max(8.0);
1435        (height, icon_size, gap, padding)
1436    }
1437}
1438
1439pub fn paint_status_badge(
1440    ctx: &mut PaintCtx,
1441    rect: Rect,
1442    theme: &DefaultTheme,
1443    label: &str,
1444    icon: Option<IconGlyph>,
1445    tone: SemanticTone,
1446) {
1447    if rect.width() <= 0.0 || rect.height() <= 0.0 {
1448        return;
1449    }
1450
1451    // Mesh badge: soft status wash, no border, status-hued ink (`--sm-*-soft`
1452    // fill + `--sm-*-text` content) at the contextual control/600 label size,
1453    // r-1 corners.
1454    let (tone_soft, tone_ink) = theme.semantic_tone_soft_colors(tone);
1455    let icon_size = (rect.height() - 13.0).clamp(11.0, 15.0);
1456    let gap = theme.metrics.icon_label_gap.max(4.0);
1457    let padding = theme.metrics.button_padding.left.max(6.0);
1458    let radius = theme.radius.sm.min(rect.height() * 0.5);
1459
1460    ctx.fill(Path::rounded_rect(rect, radius), tone_soft);
1461
1462    let mut x = rect.x() + padding.min(rect.width() * 0.5);
1463    if let Some(icon) = icon {
1464        let icon_rect = Rect::new(
1465            x,
1466            rect.y() + (rect.height() - icon_size) * 0.5,
1467            icon_size,
1468            icon_size,
1469        );
1470        draw_icon_glyph(ctx, icon, icon_rect, tone_ink);
1471        x = icon_rect.max_x() + gap;
1472    }
1473    let content_rect = Rect::new(
1474        x,
1475        rect.y(),
1476        (rect.max_x() - x - padding * 0.5).max(0.0),
1477        rect.height(),
1478    );
1479    if content_rect.width() <= 0.0 {
1480        return;
1481    }
1482
1483    let style = semibold_control_text_style(theme, tone_ink);
1484    let style = numeric_text_style_if_numeric(label, style);
1485    ctx.push_clip_rect(content_rect);
1486    paint_aligned_text_contained(ctx, content_rect, label, &style, style.line_height, 0.0);
1487    ctx.pop_clip();
1488}