Skip to main content

sui_widgets/composites/
status.rs

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