Skip to main content

sui_widgets/composites/
toolbars.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::controls::draw_icon_glyph;
11use crate::draw::{inset_rect, measure_text, mix_color, rect_center};
12use crate::frame::{draw_control_frame, draw_control_shape, physical_pixels};
13use sui_core::Color;
14use sui_core::Event;
15use sui_core::KeyState;
16use sui_core::Point;
17use sui_core::PointerButton;
18use sui_core::PointerEventKind;
19use sui_core::Rect;
20use sui_core::SemanticsAction;
21use sui_core::SemanticsNode;
22use sui_core::SemanticsPopupKind;
23use sui_core::SemanticsRole;
24use sui_core::SemanticsValue;
25use sui_core::Size;
26use sui_core::WidgetId;
27use sui_layout::Alignment;
28use sui_layout::Axis;
29use sui_layout::Constraints;
30use sui_layout::FlexAlignContent;
31use sui_layout::FlexItem;
32use sui_layout::FlexJustify;
33use sui_layout::FlexLayout;
34use sui_layout::FlexStyle;
35use sui_layout::FlexWrap;
36use sui_layout::Padding as Insets;
37use sui_layout::arrange_flex;
38use sui_layout::flex_layout;
39use sui_reactive::Observable;
40use sui_runtime::ArrangeCtx;
41use sui_runtime::EventCtx;
42use sui_runtime::FrameClock;
43use sui_runtime::MeasureCtx;
44use sui_runtime::PaintCtx;
45use sui_runtime::SemanticsCtx;
46use sui_runtime::Widget;
47use sui_runtime::WidgetChildren;
48use sui_runtime::WidgetPod;
49use sui_runtime::WidgetPodMutVisitor;
50use sui_runtime::WidgetPodVisitor;
51use sui_scene::StrokeStyle;
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct MenuItem {
55    pub(super) label: String,
56    pub(super) shortcut: Option<String>,
57    pub(super) enabled: bool,
58    pub(super) destructive: bool,
59    pub(super) separator_before: bool,
60    pub(super) submenu: Vec<MenuItem>,
61}
62
63impl MenuItem {
64    pub fn new(label: impl Into<String>) -> Self {
65        Self {
66            label: label.into(),
67            shortcut: None,
68            enabled: true,
69            destructive: false,
70            separator_before: false,
71            submenu: Vec::new(),
72        }
73    }
74
75    pub fn label(&self) -> &str {
76        &self.label
77    }
78
79    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
80        self.shortcut = Some(shortcut.into());
81        self
82    }
83
84    /// Whether the item can be chosen. Items are enabled unless set
85    /// otherwise.
86    pub fn enabled(mut self, enabled: bool) -> Self {
87        self.enabled = enabled;
88        self
89    }
90
91    pub fn destructive(mut self, destructive: bool) -> Self {
92        self.destructive = destructive;
93        self
94    }
95
96    pub fn separator_before(mut self, separator_before: bool) -> Self {
97        self.separator_before = separator_before;
98        self
99    }
100
101    /// Add the nested actions presented when this item is opened by a
102    /// [`ContextMenu`](crate::ContextMenu).
103    pub fn submenu<I>(mut self, items: I) -> Self
104    where
105        I: IntoIterator<Item = MenuItem>,
106    {
107        self.submenu.extend(items);
108        self
109    }
110
111    /// The nested actions owned by this item.
112    pub fn submenu_items(&self) -> &[MenuItem] {
113        &self.submenu
114    }
115
116    /// Whether this item opens a nested menu.
117    pub fn has_submenu(&self) -> bool {
118        !self.submenu.is_empty()
119    }
120
121    pub(super) fn text_color(&self, theme: &DefaultTheme) -> Color {
122        if !self.enabled {
123            theme.palette.placeholder
124        } else if self.destructive {
125            theme.semantic_tone_color(SemanticTone::Danger)
126        } else {
127            theme.palette.text
128        }
129    }
130}
131
132pub(super) fn virtual_menu_item_id(parent: WidgetId, index: usize) -> WidgetId {
133    virtual_menu_item_path_id(parent, &[index])
134}
135
136pub(super) fn virtual_menu_item_path_id(parent: WidgetId, path: &[usize]) -> WidgetId {
137    let value = path.iter().fold(parent.get(), |value, index| {
138        value.wrapping_mul(257).wrapping_add(*index as u64 + 1)
139    });
140    WidgetId::new((1_u64 << 63) | value)
141}
142
143pub(super) fn menu_row_height(theme: &DefaultTheme) -> f32 {
144    theme.metrics.menu_row_height
145}
146
147pub(super) fn themed_menu_height_for_rows(
148    theme: &DefaultTheme,
149    row_height: f32,
150    rows: usize,
151) -> f32 {
152    theme.metrics.menu_padding.top + theme.metrics.menu_padding.bottom + (row_height * rows as f32)
153}
154
155pub(super) fn menu_submenu_indicator_width(theme: &DefaultTheme) -> f32 {
156    menu_row_height(theme) * 0.55
157}
158
159/// How wide a menu panel needs to be to show `items` unclipped: the widest
160/// label with its shortcut column, and its submenu arrow when `submenus`,
161/// inside the row and panel padding. Never narrower than the theme allows.
162pub(super) fn menu_width_for_items(
163    ctx: &mut MeasureCtx,
164    theme: &DefaultTheme,
165    items: &[MenuItem],
166    submenus: bool,
167) -> f32 {
168    let metrics = theme.metrics;
169    let label_style = theme.body_text_style();
170    let content = items
171        .iter()
172        .map(|item| {
173            let label = measure_text(ctx, item.label(), &label_style).width.ceil();
174            let shortcut = if item.shortcut.is_some() {
175                metrics.menu_shortcut_width
176            } else {
177                0.0
178            };
179            let indicator = if submenus && item.has_submenu() {
180                menu_submenu_indicator_width(theme)
181            } else {
182                0.0
183            };
184            label + shortcut + indicator
185        })
186        .fold(0.0, f32::max);
187    (content
188        + metrics.menu_item_padding.left
189        + metrics.menu_item_padding.right
190        + metrics.menu_padding.left
191        + metrics.menu_padding.right)
192        .max(metrics.menu_min_width)
193}
194
195pub(super) fn menu_item_semantics_node(
196    parent: WidgetId,
197    index: usize,
198    item: &MenuItem,
199    bounds: Rect,
200    highlighted: bool,
201) -> SemanticsNode {
202    let mut node = SemanticsNode::new(
203        virtual_menu_item_id(parent, index),
204        SemanticsRole::MenuItem,
205        bounds,
206    );
207    node.parent = Some(parent);
208    node.name = Some(item.label.clone());
209    node.state.disabled = !item.enabled;
210    node.state.selected = highlighted;
211    if item.enabled {
212        node.actions = vec![SemanticsAction::Activate];
213    }
214    node
215}
216
217pub(super) fn context_menu_item_semantics_node(
218    root: WidgetId,
219    parent: WidgetId,
220    path: &[usize],
221    item: &MenuItem,
222    bounds: Rect,
223    highlighted: bool,
224    expanded: bool,
225) -> SemanticsNode {
226    let mut node = SemanticsNode::new(
227        virtual_menu_item_path_id(root, path),
228        SemanticsRole::MenuItem,
229        bounds,
230    );
231    node.parent = Some(parent);
232    node.name = Some(item.label.clone());
233    node.state.disabled = !item.enabled;
234    node.state.selected = highlighted;
235    if item.has_submenu() {
236        node.state.expanded = Some(expanded);
237        node.popup = Some(SemanticsPopupKind::Menu);
238    }
239    if item.enabled {
240        node.actions = if item.has_submenu() {
241            vec![
242                SemanticsAction::Activate,
243                SemanticsAction::Expand,
244                SemanticsAction::Collapse,
245            ]
246        } else {
247            vec![SemanticsAction::Activate]
248        };
249    }
250    node
251}
252
253pub struct Toolbar {
254    pub(super) theme: Box<DefaultTheme>,
255    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
256    pub(super) axis: Axis,
257    pub(super) name: Option<String>,
258    pub(super) extent: Option<f32>,
259    pub(super) padding: Option<Insets>,
260    pub(super) spacing: Option<f32>,
261    pub(super) line_spacing: Option<f32>,
262    pub(super) wrap: FlexWrap,
263    pub(super) background: Option<Color>,
264    pub(super) divider: bool,
265    pub(super) children: WidgetChildren,
266    pub(super) layout: Option<FlexLayout>,
267}
268
269impl Toolbar {
270    pub fn horizontal() -> Self {
271        Self::new(Axis::Horizontal)
272    }
273
274    pub fn vertical() -> Self {
275        Self::new(Axis::Vertical)
276    }
277
278    pub fn new(axis: Axis) -> Self {
279        Self {
280            theme: Box::new(DefaultTheme::default()),
281            theme_reader: None,
282            axis,
283            name: None,
284            extent: None,
285            padding: None,
286            spacing: None,
287            line_spacing: None,
288            wrap: FlexWrap::NoWrap,
289            background: None,
290            divider: true,
291            children: WidgetChildren::new(),
292            layout: None,
293        }
294    }
295
296    pub fn theme(mut self, theme: DefaultTheme) -> Self {
297        self.theme = Box::new(theme);
298        self.theme_reader = None;
299        self
300    }
301
302    pub fn theme_when<F>(mut self, theme: F) -> Self
303    where
304        F: Fn() -> DefaultTheme + 'static,
305    {
306        self.theme_reader = Some(Box::new(theme));
307        self
308    }
309
310    pub fn name(mut self, name: impl Into<String>) -> Self {
311        self.name = Some(name.into());
312        self
313    }
314
315    pub fn extent(mut self, extent: f32) -> Self {
316        self.extent = Some(extent.max(0.0));
317        self
318    }
319
320    pub fn padding(mut self, padding: Insets) -> Self {
321        self.padding = Some(padding);
322        self
323    }
324
325    pub fn gap(mut self, gap: f32) -> Self {
326        self.spacing = Some(gap.max(0.0));
327        self
328    }
329
330    /// Allow toolbar items to flow into additional rows or columns while
331    /// retaining their original widget identities and navigation order.
332    pub fn wrap(mut self, wrap: FlexWrap) -> Self {
333        self.wrap = wrap;
334        self
335    }
336
337    pub fn wrapping(self) -> Self {
338        self.wrap(FlexWrap::Wrap)
339    }
340
341    pub fn cross_gap(mut self, gap: f32) -> Self {
342        self.line_spacing = Some(gap.max(0.0));
343        self
344    }
345
346    pub fn background(mut self, color: Color) -> Self {
347        self.background = Some(color);
348        self
349    }
350
351    pub fn divider(mut self, divider: bool) -> Self {
352        self.divider = divider;
353        self
354    }
355
356    pub fn with_child<W>(mut self, child: W) -> Self
357    where
358        W: Widget + 'static,
359    {
360        self.children.push(child);
361        self
362    }
363
364    pub fn push<W>(&mut self, child: W)
365    where
366        W: Widget + 'static,
367    {
368        self.children.push(child);
369    }
370
371    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
372        self.children.as_slice()
373    }
374
375    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
376        self.children.as_mut_slice()
377    }
378
379    pub(super) fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
380        self.extent.unwrap_or(metrics.toolbar_extent)
381    }
382
383    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
384        self.padding.unwrap_or(metrics.toolbar_padding)
385    }
386
387    pub(super) fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
388        self.spacing.unwrap_or(metrics.toolbar_spacing)
389    }
390
391    pub(super) fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
392        let padding = self.resolved_padding(metrics);
393        Rect::new(
394            bounds.x() + padding.left,
395            bounds.y() + padding.top,
396            (bounds.width() - padding.left - padding.right).max(0.0),
397            (bounds.height() - padding.top - padding.bottom).max(0.0),
398        )
399    }
400
401    pub(super) fn resolved_theme(&self) -> DefaultTheme {
402        self.theme_reader
403            .as_ref()
404            .map(|theme| theme())
405            .unwrap_or_else(|| *self.theme)
406    }
407}
408
409impl Default for Toolbar {
410    fn default() -> Self {
411        Self::horizontal()
412    }
413}
414
415impl Widget for Toolbar {
416    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
417        let theme = self.resolved_theme();
418        let metrics = theme.metrics;
419        let extent = self.resolved_extent(metrics);
420        let padding = self.resolved_padding(metrics);
421        let spacing = self.resolved_spacing(metrics);
422        if self.wrap == FlexWrap::Wrap {
423            let line_spacing = self.line_spacing.unwrap_or(spacing);
424            let max_content = Size::new(
425                if constraints.max.width.is_finite() {
426                    (constraints.max.width - padding.left - padding.right).max(0.0)
427                } else {
428                    f32::INFINITY
429                },
430                if constraints.max.height.is_finite() {
431                    (constraints.max.height - padding.top - padding.bottom).max(0.0)
432                } else {
433                    f32::INFINITY
434                },
435            );
436            let min_cross = match self.axis {
437                Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
438                Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
439            };
440            let min_content = match self.axis {
441                Axis::Horizontal => Size::new(
442                    if max_content.width.is_finite() {
443                        max_content.width
444                    } else {
445                        0.0
446                    },
447                    min_cross,
448                ),
449                Axis::Vertical => Size::new(
450                    min_cross,
451                    if max_content.height.is_finite() {
452                        max_content.height
453                    } else {
454                        0.0
455                    },
456                ),
457            };
458            let style = FlexStyle::new(self.axis)
459                .wrap(FlexWrap::Wrap)
460                .main_gap(spacing)
461                .cross_gap(line_spacing)
462                .justify(FlexJustify::Start)
463                .align_items(Alignment::Center)
464                .align_content(FlexAlignContent::Start);
465            let items = vec![FlexItem::new(); self.children.len()];
466            let layout = flex_layout(
467                style,
468                &items,
469                Constraints::new(min_content, max_content),
470                |index, child_constraints| {
471                    self.children.measure_child(index, ctx, child_constraints)
472                },
473            );
474            let natural = Size::new(
475                layout.size.width + padding.left + padding.right,
476                layout.size.height + padding.top + padding.bottom,
477            );
478            self.layout = Some(layout);
479            return constraints.clamp(natural);
480        }
481        self.layout = None;
482        let content_cross = match self.axis {
483            Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
484            Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
485        };
486        let child_constraints = match self.axis {
487            Axis::Horizontal => {
488                Constraints::new(Size::ZERO, Size::new(f32::INFINITY, content_cross))
489            }
490            Axis::Vertical => Constraints::new(Size::ZERO, Size::new(content_cross, f32::INFINITY)),
491        };
492
493        let mut main: f32 = 0.0;
494        let mut cross: f32 = 0.0;
495        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
496            let child_size = child.measure(ctx, child_constraints);
497            if index > 0 {
498                main += spacing;
499            }
500            main += toolbar_main(self.axis, child_size);
501            cross = cross.max(toolbar_cross(self.axis, child_size));
502        }
503
504        let natural = match self.axis {
505            Axis::Horizontal => Size::new(
506                main + padding.left + padding.right,
507                extent.max(cross + padding.top + padding.bottom),
508            ),
509            Axis::Vertical => Size::new(
510                extent.max(cross + padding.left + padding.right),
511                main + padding.top + padding.bottom,
512            ),
513        };
514        let filled = match self.axis {
515            Axis::Horizontal => Size::new(
516                if constraints.max.width.is_finite() {
517                    constraints.max.width
518                } else {
519                    natural.width
520                },
521                extent,
522            ),
523            Axis::Vertical => Size::new(
524                extent,
525                if constraints.max.height.is_finite() {
526                    constraints.max.height
527                } else {
528                    natural.height
529                },
530            ),
531        };
532
533        constraints.clamp(filled)
534    }
535
536    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
537        let theme = self.resolved_theme();
538        let metrics = theme.metrics;
539        let spacing = self.resolved_spacing(metrics);
540        let content = self.content_bounds(bounds, metrics);
541        if self.wrap == FlexWrap::Wrap {
542            let style = FlexStyle::new(self.axis)
543                .wrap(FlexWrap::Wrap)
544                .main_gap(spacing)
545                .cross_gap(self.line_spacing.unwrap_or(spacing))
546                .justify(FlexJustify::Start)
547                .align_items(Alignment::Center)
548                .align_content(FlexAlignContent::Start);
549            let items = vec![FlexItem::new(); self.children.len()];
550            let measured = self
551                .children
552                .as_slice()
553                .iter()
554                .map(WidgetPod::measured_size)
555                .collect::<Vec<_>>();
556            let layout = arrange_flex(style, &items, content.size, &measured);
557            for (index, item) in layout.items.iter().enumerate() {
558                self.children.arrange_child(
559                    index,
560                    ctx,
561                    item.rect.translate(content.origin.to_vector()),
562                );
563            }
564            self.layout = Some(layout);
565            return;
566        }
567        let content_main = toolbar_main(self.axis, content.size);
568        let content_cross = toolbar_cross(self.axis, content.size);
569        let mut main_offset = 0.0;
570
571        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
572            if index > 0 {
573                main_offset += spacing;
574            }
575
576            let measured = child.measured_size();
577            let remaining = (content_main - main_offset).max(0.0);
578            let child_main = toolbar_main(self.axis, measured).min(remaining);
579            let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
580            let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
581            let origin = match self.axis {
582                Axis::Horizontal => {
583                    Point::new(content.x() + main_offset, content.y() + cross_offset)
584                }
585                Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
586            };
587            child.arrange(
588                ctx,
589                Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
590            );
591            main_offset += child_main;
592        }
593    }
594
595    fn paint(&self, ctx: &mut PaintCtx) {
596        let theme = self.resolved_theme();
597        let palette = theme.palette;
598        let bounds = ctx.bounds();
599        ctx.fill_bounds(self.background.unwrap_or(palette.surface));
600        if self.divider {
601            let divider = match self.axis {
602                Axis::Horizontal => {
603                    Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
604                }
605                Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
606            };
607            ctx.stroke_rect(
608                divider,
609                palette.border.with_alpha(0.85),
610                StrokeStyle::new(1.0),
611            );
612        }
613        self.children.paint(ctx);
614    }
615
616    fn semantics(&self, ctx: &mut SemanticsCtx) {
617        if let Some(name) = &self.name {
618            let mut node = SemanticsNode::new(
619                ctx.widget_id(),
620                SemanticsRole::GenericContainer,
621                ctx.bounds(),
622            );
623            node.name = Some(name.clone());
624            ctx.push(node);
625        }
626        self.children.semantics(ctx);
627    }
628
629    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
630        self.children.visit_children(visitor);
631    }
632
633    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
634        self.children.visit_children_mut(visitor);
635    }
636}
637
638pub struct CommandGroup {
639    pub(super) theme: Box<DefaultTheme>,
640    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
641    pub(super) axis: Axis,
642    pub(super) name: Option<String>,
643    pub(super) padding: Option<Insets>,
644    pub(super) spacing: Option<f32>,
645    pub(super) corner_radius: Option<f32>,
646    pub(super) background: Option<Color>,
647    pub(super) border: Option<Color>,
648    pub(super) children: WidgetChildren,
649}
650
651impl CommandGroup {
652    pub fn horizontal(name: impl Into<String>) -> Self {
653        Self::new(Axis::Horizontal, name)
654    }
655
656    pub fn vertical(name: impl Into<String>) -> Self {
657        Self::new(Axis::Vertical, name)
658    }
659
660    pub fn new(axis: Axis, name: impl Into<String>) -> Self {
661        Self {
662            theme: Box::new(DefaultTheme::default()),
663            theme_reader: None,
664            axis,
665            name: Some(name.into()),
666            padding: None,
667            spacing: None,
668            corner_radius: None,
669            background: None,
670            border: None,
671            children: WidgetChildren::new(),
672        }
673    }
674
675    pub fn theme(mut self, theme: DefaultTheme) -> Self {
676        self.theme = Box::new(theme);
677        self.theme_reader = None;
678        self
679    }
680
681    pub fn theme_when<F>(mut self, theme: F) -> Self
682    where
683        F: Fn() -> DefaultTheme + 'static,
684    {
685        self.theme_reader = Some(Box::new(theme));
686        self
687    }
688
689    pub fn unnamed(mut self) -> Self {
690        self.name = None;
691        self
692    }
693
694    pub fn padding(mut self, padding: Insets) -> Self {
695        self.padding = Some(padding);
696        self
697    }
698
699    pub fn gap(mut self, gap: f32) -> Self {
700        self.spacing = Some(gap.max(0.0));
701        self
702    }
703
704    pub fn corner_radius(mut self, corner_radius: f32) -> Self {
705        self.corner_radius = Some(corner_radius.max(0.0));
706        self
707    }
708
709    pub fn background(mut self, color: Color) -> Self {
710        self.background = Some(color);
711        self
712    }
713
714    pub fn border(mut self, color: Color) -> Self {
715        self.border = Some(color);
716        self
717    }
718
719    pub fn with_child<W>(mut self, child: W) -> Self
720    where
721        W: Widget + 'static,
722    {
723        self.children.push(child);
724        self
725    }
726
727    pub fn push<W>(&mut self, child: W)
728    where
729        W: Widget + 'static,
730    {
731        self.children.push(child);
732    }
733
734    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
735        self.children.as_slice()
736    }
737
738    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
739        self.children.as_mut_slice()
740    }
741
742    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
743        self.padding.unwrap_or(metrics.command_group_padding)
744    }
745
746    pub(super) fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
747        self.spacing.unwrap_or(metrics.command_group_spacing)
748    }
749
750    pub(super) fn resolved_corner_radius(&self, metrics: ControlMetrics) -> f32 {
751        self.corner_radius.unwrap_or(metrics.command_group_radius)
752    }
753
754    pub(super) fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
755        inset_rect(bounds, self.resolved_padding(metrics))
756    }
757
758    pub(super) fn resolved_theme(&self) -> DefaultTheme {
759        self.theme_reader
760            .as_ref()
761            .map(|theme| theme())
762            .unwrap_or_else(|| *self.theme)
763    }
764}
765
766impl Widget for CommandGroup {
767    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
768        let theme = self.resolved_theme();
769        let metrics = theme.metrics;
770        let padding = self.resolved_padding(metrics);
771        let spacing = self.resolved_spacing(metrics);
772        let max_width = if constraints.max.width.is_finite() {
773            (constraints.max.width - padding.left - padding.right).max(0.0)
774        } else {
775            f32::INFINITY
776        };
777        let max_height = if constraints.max.height.is_finite() {
778            (constraints.max.height - padding.top - padding.bottom).max(0.0)
779        } else {
780            f32::INFINITY
781        };
782        let child_constraints = Constraints::new(Size::ZERO, Size::new(max_width, max_height));
783
784        let mut main: f32 = 0.0;
785        let mut cross: f32 = 0.0;
786        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
787            let child_size = child.measure(ctx, child_constraints);
788            if index > 0 {
789                main += spacing;
790            }
791            main += toolbar_main(self.axis, child_size);
792            cross = cross.max(toolbar_cross(self.axis, child_size));
793        }
794
795        let natural = match self.axis {
796            Axis::Horizontal => Size::new(
797                main + padding.left + padding.right,
798                cross + padding.top + padding.bottom,
799            ),
800            Axis::Vertical => Size::new(
801                cross + padding.left + padding.right,
802                main + padding.top + padding.bottom,
803            ),
804        };
805        constraints.clamp(natural)
806    }
807
808    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
809        let theme = self.resolved_theme();
810        let metrics = theme.metrics;
811        let spacing = self.resolved_spacing(metrics);
812        let content = self.content_bounds(bounds, metrics);
813        let content_main = toolbar_main(self.axis, content.size);
814        let content_cross = toolbar_cross(self.axis, content.size);
815        let mut main_offset = 0.0;
816
817        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
818            if index > 0 {
819                main_offset += spacing;
820            }
821
822            let measured = child.measured_size();
823            let remaining = (content_main - main_offset).max(0.0);
824            let child_main = toolbar_main(self.axis, measured).min(remaining);
825            let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
826            let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
827            let origin = match self.axis {
828                Axis::Horizontal => {
829                    Point::new(content.x() + main_offset, content.y() + cross_offset)
830                }
831                Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
832            };
833            child.arrange(
834                ctx,
835                Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
836            );
837            main_offset += child_main;
838        }
839    }
840
841    fn paint(&self, ctx: &mut PaintCtx) {
842        let theme = self.resolved_theme();
843        let radius = self
844            .resolved_corner_radius(theme.metrics)
845            .min(ctx.bounds().width().min(ctx.bounds().height()) * 0.5);
846        let background = self.background.unwrap_or(theme.palette.surface_raised);
847        let border = self.border.unwrap_or(theme.palette.border);
848        draw_control_shape(
849            ctx,
850            ctx.bounds(),
851            radius,
852            physical_pixels(ctx, 1.0),
853            background,
854            border,
855        );
856        self.children.paint(ctx);
857    }
858
859    fn semantics(&self, ctx: &mut SemanticsCtx) {
860        if let Some(name) = &self.name {
861            let mut node = SemanticsNode::new(
862                ctx.widget_id(),
863                SemanticsRole::GenericContainer,
864                ctx.bounds(),
865            );
866            node.name = Some(name.clone());
867            ctx.push(node);
868        }
869        self.children.semantics(ctx);
870    }
871
872    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
873        self.children.visit_children(visitor);
874    }
875
876    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
877        self.children.visit_children_mut(visitor);
878    }
879}
880
881pub(super) fn toolbar_main(axis: Axis, size: Size) -> f32 {
882    match axis {
883        Axis::Horizontal => size.width,
884        Axis::Vertical => size.height,
885    }
886}
887
888pub(super) fn toolbar_cross(axis: Axis, size: Size) -> f32 {
889    match axis {
890        Axis::Horizontal => size.height,
891        Axis::Vertical => size.width,
892    }
893}
894
895pub(super) fn toolbar_size(axis: Axis, main: f32, cross: f32) -> Size {
896    match axis {
897        Axis::Horizontal => Size::new(main, cross),
898        Axis::Vertical => Size::new(cross, main),
899    }
900}
901
902#[derive(Debug, Clone, PartialEq, Eq)]
903pub struct ToolPaletteItem {
904    pub(super) icon: IconGlyph,
905    pub(super) label: String,
906    pub(super) enabled: bool,
907}
908
909impl ToolPaletteItem {
910    pub fn new(icon: IconGlyph, label: impl Into<String>) -> Self {
911        Self {
912            icon,
913            label: label.into(),
914            enabled: true,
915        }
916    }
917
918    /// Whether the item can be chosen. Items are enabled unless set
919    /// otherwise.
920    pub fn enabled(mut self, enabled: bool) -> Self {
921        self.enabled = enabled;
922        self
923    }
924
925    pub fn label(&self) -> &str {
926        &self.label
927    }
928}
929
930pub struct ToolPalette {
931    pub(super) theme: Box<DefaultTheme>,
932    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
933    pub(super) enabled: Binding<bool>,
934    pub(super) axis: Axis,
935    pub(super) name: String,
936    pub(super) items: Vec<ToolPaletteItem>,
937    pub(super) selected: Option<usize>,
938    pub(super) selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
939    pub(super) hovered: Option<usize>,
940    pub(super) hover_visual: Option<usize>,
941    pub(super) pressed: Option<usize>,
942    pub(super) press_visual: Option<usize>,
943    pub(super) hover_animation: Progress,
944    pub(super) press_animation: Progress,
945    pub(super) focus_animation: Progress,
946    pub(super) extent: Option<f32>,
947    pub(super) padding: Option<Insets>,
948    pub(super) spacing: Option<f32>,
949    pub(super) item_size: Option<f32>,
950    pub(super) icon_size: Option<f32>,
951    pub(super) background: Option<Color>,
952    pub(super) divider: bool,
953    pub(super) on_change: Option<Box<dyn FnMut(usize, String)>>,
954    pub(super) on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String)>>,
955}
956
957impl ToolPalette {
958    pub fn vertical(name: impl Into<String>) -> Self {
959        Self::new(Axis::Vertical, name)
960    }
961
962    pub fn horizontal(name: impl Into<String>) -> Self {
963        Self::new(Axis::Horizontal, name)
964    }
965
966    pub fn new(axis: Axis, name: impl Into<String>) -> Self {
967        Self {
968            theme: Box::new(DefaultTheme::default()),
969            theme_reader: None,
970            enabled: Binding::new(true),
971            axis,
972            name: name.into(),
973            items: Vec::new(),
974            selected: None,
975            selected_reader: None,
976            hovered: None,
977            hover_visual: None,
978            pressed: None,
979            press_visual: None,
980            hover_animation: Progress::new(0.0),
981            press_animation: Progress::new(0.0),
982            focus_animation: Progress::new(0.0),
983            extent: None,
984            padding: None,
985            spacing: None,
986            item_size: None,
987            icon_size: None,
988            background: None,
989            divider: true,
990            on_change: None,
991            on_change_with_ctx: None,
992        }
993    }
994
995    pub fn theme(mut self, theme: DefaultTheme) -> Self {
996        self.theme = Box::new(theme);
997        self.theme_reader = None;
998        self
999    }
1000
1001    pub fn theme_when<F>(mut self, theme: F) -> Self
1002    where
1003        F: Fn() -> DefaultTheme + 'static,
1004    {
1005        self.theme_reader = Some(Box::new(theme));
1006        self
1007    }
1008
1009    /// Whether the user can use the widget. Disabled, it ignores input,
1010    /// can't take focus, draws in the theme's disabled colors, and tells
1011    /// assistive technology it and its items are unavailable.
1012    pub fn enabled(mut self, enabled: bool) -> Self {
1013        self.enabled.set(enabled);
1014        self
1015    }
1016
1017    /// [`Self::enabled`], read whenever the widget needs it.
1018    pub fn enabled_when<F>(mut self, enabled: F) -> Self
1019    where
1020        F: Fn() -> bool + 'static,
1021    {
1022        self.enabled.set_when(enabled);
1023        self
1024    }
1025
1026    /// [`Self::enabled`], following an observable and repainting when it
1027    /// changes.
1028    pub fn enabled_from<O>(mut self, enabled: O) -> Self
1029    where
1030        O: Observable<bool> + 'static,
1031    {
1032        self.enabled.set_from(enabled);
1033        self
1034    }
1035
1036    pub fn is_enabled(&self) -> bool {
1037        self.enabled.get()
1038    }
1039
1040    /// The theme to paint with: the disabled look while the widget is
1041    /// disabled.
1042    fn paint_theme(&self) -> DefaultTheme {
1043        let theme = self.resolved_theme();
1044        if self.enabled.get() {
1045            theme
1046        } else {
1047            theme.for_disabled_control()
1048        }
1049    }
1050
1051    pub fn item(mut self, item: ToolPaletteItem) -> Self {
1052        self.items.push(item);
1053        self
1054    }
1055
1056    pub fn items<I>(mut self, items: I) -> Self
1057    where
1058        I: IntoIterator<Item = ToolPaletteItem>,
1059    {
1060        self.items.extend(items);
1061        self
1062    }
1063
1064    /// Select item `index`, or nothing with `None`; `selected(2)` and
1065    /// `selected(None)` both work.
1066    pub fn selected(mut self, selected: impl Into<Option<usize>>) -> Self {
1067        let selected = selected.into();
1068        self.selected = selected;
1069        self.selected_reader = None;
1070        self
1071    }
1072
1073    pub fn selected_when<F>(mut self, selected: F) -> Self
1074    where
1075        F: Fn() -> Option<usize> + 'static,
1076    {
1077        self.selected_reader = Some(Box::new(selected));
1078        self
1079    }
1080
1081    pub fn extent(mut self, extent: f32) -> Self {
1082        self.extent = Some(extent.max(0.0));
1083        self
1084    }
1085
1086    pub fn padding(mut self, padding: Insets) -> Self {
1087        self.padding = Some(padding);
1088        self
1089    }
1090
1091    pub fn gap(mut self, gap: f32) -> Self {
1092        self.spacing = Some(gap.max(0.0));
1093        self
1094    }
1095
1096    pub fn item_size(mut self, item_size: f32) -> Self {
1097        self.item_size = Some(item_size.max(0.0));
1098        self
1099    }
1100
1101    pub fn icon_size(mut self, icon_size: f32) -> Self {
1102        self.icon_size = Some(icon_size.max(0.0));
1103        self
1104    }
1105
1106    pub fn background(mut self, color: Color) -> Self {
1107        self.background = Some(color);
1108        self
1109    }
1110
1111    pub fn divider(mut self, divider: bool) -> Self {
1112        self.divider = divider;
1113        self
1114    }
1115
1116    pub fn on_change<F>(mut self, on_change: F) -> Self
1117    where
1118        F: FnMut(usize, String) + 'static,
1119    {
1120        self.on_change = Some(Box::new(on_change));
1121        self
1122    }
1123
1124    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
1125    where
1126        F: FnMut(&mut EventCtx, usize, String) + 'static,
1127    {
1128        self.on_change_with_ctx = Some(Box::new(on_change));
1129        self
1130    }
1131
1132    pub fn selected_index(&self) -> Option<usize> {
1133        self.current_selected()
1134    }
1135
1136    pub(super) fn current_selected(&self) -> Option<usize> {
1137        self.selected_reader
1138            .as_ref()
1139            .map(|selected| selected())
1140            .unwrap_or(self.selected)
1141            .filter(|index| *index < self.items.len())
1142    }
1143
1144    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1145        self.theme_reader
1146            .as_ref()
1147            .map(|theme| theme())
1148            .unwrap_or_else(|| *self.theme)
1149    }
1150
1151    pub(super) fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
1152        self.extent.unwrap_or(metrics.toolbar_extent)
1153    }
1154
1155    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1156        self.padding.unwrap_or(metrics.toolbar_padding)
1157    }
1158
1159    pub(super) fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1160        self.spacing.unwrap_or(metrics.toolbar_spacing)
1161    }
1162
1163    pub(super) fn resolved_item_size(&self, metrics: ControlMetrics) -> f32 {
1164        self.item_size.unwrap_or(metrics.tool_palette_item_size)
1165    }
1166
1167    pub(super) fn resolved_icon_size(&self, metrics: ControlMetrics) -> f32 {
1168        self.icon_size.unwrap_or(metrics.tool_palette_icon_size)
1169    }
1170
1171    pub(super) fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1172        let padding = self.resolved_padding(metrics);
1173        Rect::new(
1174            bounds.x() + padding.left,
1175            bounds.y() + padding.top,
1176            (bounds.width() - padding.left - padding.right).max(0.0),
1177            (bounds.height() - padding.top - padding.bottom).max(0.0),
1178        )
1179    }
1180
1181    pub(super) fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
1182        if index >= self.items.len() {
1183            return None;
1184        }
1185
1186        let metrics = self.resolved_theme().metrics;
1187        let item_size = self.resolved_item_size(metrics);
1188        let spacing = self.resolved_spacing(metrics);
1189        let content = self.content_bounds(bounds, metrics);
1190        let content_main = toolbar_main(self.axis, content.size);
1191        let content_cross = toolbar_cross(self.axis, content.size);
1192        let item_main = item_size.min(content_main);
1193        let item_cross = item_size.min(content_cross);
1194        let main_offset = index as f32 * (item_size + spacing);
1195        if main_offset >= content_main {
1196            return None;
1197        }
1198        let cross_offset = ((content_cross - item_cross) * 0.5).max(0.0);
1199        let origin = match self.axis {
1200            Axis::Horizontal => Point::new(content.x() + main_offset, content.y() + cross_offset),
1201            Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1202        };
1203        Some(Rect::from_origin_size(
1204            origin,
1205            toolbar_size(self.axis, item_main, item_cross),
1206        ))
1207    }
1208
1209    pub(super) fn hit_at(&self, bounds: Rect, position: Point) -> Option<usize> {
1210        (0..self.items.len()).find(|index| {
1211            self.items[*index].enabled
1212                && self
1213                    .item_rect(bounds, *index)
1214                    .is_some_and(|rect| rect.contains(position))
1215        })
1216    }
1217
1218    pub(super) fn select(&mut self, ctx: &mut EventCtx, index: usize) {
1219        let Some(item) = self.items.get(index) else {
1220            return;
1221        };
1222        if !item.enabled {
1223            return;
1224        }
1225
1226        self.selected = Some(index);
1227        if let Some(on_change) = &mut self.on_change {
1228            on_change(index, item.label.clone());
1229        }
1230        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
1231            on_change_with_ctx(ctx, index, item.label.clone());
1232        }
1233    }
1234
1235    pub(super) fn move_selection(&mut self, ctx: &mut EventCtx, delta: isize) {
1236        if self.items.is_empty() {
1237            return;
1238        }
1239
1240        let start = self.current_selected().unwrap_or(0);
1241        let mut index = start as isize;
1242        let last = self.items.len() as isize - 1;
1243        for _ in 0..self.items.len() {
1244            index = (index + delta).clamp(0, last);
1245            if self
1246                .items
1247                .get(index as usize)
1248                .is_some_and(|item| item.enabled)
1249            {
1250                self.select(ctx, index as usize);
1251                return;
1252            }
1253            if index == 0 || index == last {
1254                return;
1255            }
1256        }
1257    }
1258
1259    pub(super) fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
1260        if self.hovered == hovered {
1261            return;
1262        }
1263        let theme = self.resolved_theme();
1264        self.hovered = hovered;
1265        if let Some(index) = hovered {
1266            self.hover_visual = Some(index);
1267            self.hover_animation = Progress::new(0.0);
1268            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
1269        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
1270            self.hover_visual = None;
1271        }
1272        ctx.request_paint();
1273        ctx.request_semantics();
1274    }
1275
1276    pub(super) fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
1277        if self.pressed == pressed {
1278            return;
1279        }
1280        let theme = self.resolved_theme();
1281        set_item_press(
1282            &mut self.pressed,
1283            &mut self.press_visual,
1284            &mut self.press_animation,
1285            pressed,
1286            &theme,
1287            ctx,
1288        );
1289    }
1290
1291    pub(super) fn hover_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
1292        if self.hover_visual == Some(index) {
1293            self.hover_animation.get(clock)
1294        } else {
1295            0.0
1296        }
1297    }
1298
1299    pub(super) fn press_amount_for(&self, index: usize, clock: &impl FrameClock) -> f32 {
1300        if self.press_visual == Some(index) {
1301            self.press_animation.get(clock)
1302        } else {
1303            0.0
1304        }
1305    }
1306}
1307
1308impl Widget for ToolPalette {
1309    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1310        if !self.enabled.get() {
1311            // Disabled, the widget takes no input, but it lets go of a
1312            // pointer it captured while enabled.
1313            if let Event::Pointer(pointer) = event
1314                && pointer.kind == PointerEventKind::Up
1315            {
1316                ctx.release_pointer_capture(pointer.pointer_id);
1317            }
1318            return;
1319        }
1320        match event {
1321            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1322                self.set_hovered(self.hit_at(ctx.bounds(), pointer.position), ctx);
1323            }
1324            Event::Pointer(pointer)
1325                if pointer.kind == PointerEventKind::Down
1326                    && pointer.button == Some(PointerButton::Primary) =>
1327            {
1328                let hovered = self.hit_at(ctx.bounds(), pointer.position);
1329                self.set_hovered(hovered, ctx);
1330                self.set_pressed(hovered, ctx);
1331                if self.pressed.is_some() {
1332                    ctx.request_focus();
1333                    ctx.request_pointer_capture(pointer.pointer_id);
1334                    ctx.set_handled();
1335                }
1336            }
1337            Event::Pointer(pointer)
1338                if pointer.kind == PointerEventKind::Up
1339                    && pointer.button == Some(PointerButton::Primary) =>
1340            {
1341                let hovered = self.hit_at(ctx.bounds(), pointer.position);
1342                if let Some(index) = self
1343                    .pressed
1344                    .zip(hovered)
1345                    .filter(|(left, right)| left == right)
1346                    .map(|(index, _)| index)
1347                {
1348                    self.select(ctx, index);
1349                }
1350                self.set_hovered(hovered, ctx);
1351                self.set_pressed(None, ctx);
1352                ctx.release_pointer_capture(pointer.pointer_id);
1353                ctx.set_handled();
1354            }
1355            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
1356                self.set_hovered(None, ctx);
1357            }
1358            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1359                if self.pressed.is_some() {
1360                    self.set_pressed(None, ctx);
1361                    self.set_hovered(None, ctx);
1362                    ctx.release_pointer_capture(pointer.pointer_id);
1363                    ctx.set_handled();
1364                }
1365            }
1366            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1367                match key.key.as_str() {
1368                    "ArrowUp" if self.axis == Axis::Vertical => self.move_selection(ctx, -1),
1369                    "ArrowDown" if self.axis == Axis::Vertical => self.move_selection(ctx, 1),
1370                    "ArrowLeft" if self.axis == Axis::Horizontal => self.move_selection(ctx, -1),
1371                    "ArrowRight" if self.axis == Axis::Horizontal => self.move_selection(ctx, 1),
1372                    "Home" => {
1373                        if let Some(index) = self.items.iter().position(|item| item.enabled) {
1374                            self.select(ctx, index);
1375                        }
1376                    }
1377                    "End" => {
1378                        if let Some(index) = self.items.iter().rposition(|item| item.enabled) {
1379                            self.select(ctx, index);
1380                        }
1381                    }
1382                    "Enter" | " " => {
1383                        if let Some(index) = self.current_selected() {
1384                            self.select(ctx, index);
1385                        }
1386                    }
1387                    _ => return,
1388                }
1389                ctx.request_paint();
1390                ctx.request_semantics();
1391                ctx.set_handled();
1392            }
1393            _ => {}
1394        }
1395    }
1396
1397    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1398        let theme = self.resolved_theme();
1399        let metrics = theme.metrics;
1400        let item_size = self.resolved_item_size(metrics);
1401        let spacing = self.resolved_spacing(metrics);
1402        let padding = self.resolved_padding(metrics);
1403        let extent = self.resolved_extent(metrics);
1404        let item_count = self.items.len();
1405        let main = if item_count == 0 {
1406            0.0
1407        } else {
1408            (item_size * item_count as f32) + (spacing * (item_count - 1) as f32)
1409        };
1410        let natural = match self.axis {
1411            Axis::Horizontal => Size::new(main + padding.left + padding.right, extent),
1412            Axis::Vertical => Size::new(extent, main + padding.top + padding.bottom),
1413        };
1414        let filled = match self.axis {
1415            Axis::Horizontal => Size::new(
1416                if constraints.max.width.is_finite() {
1417                    constraints.max.width
1418                } else {
1419                    natural.width
1420                },
1421                natural.height,
1422            ),
1423            Axis::Vertical => Size::new(
1424                natural.width,
1425                if constraints.max.height.is_finite() {
1426                    constraints.max.height
1427                } else {
1428                    natural.height
1429                },
1430            ),
1431        };
1432
1433        constraints.clamp(filled)
1434    }
1435
1436    fn paint(&self, ctx: &mut PaintCtx) {
1437        self.enabled.observe(|source| {
1438            ctx.observe(source);
1439        });
1440        let theme = self.paint_theme();
1441        let palette = theme.palette;
1442        let metrics = theme.metrics;
1443        let interaction = theme.interaction;
1444        let icon_size = self.resolved_icon_size(metrics);
1445        let bounds = ctx.bounds();
1446        ctx.fill_bounds(self.background.unwrap_or(palette.surface));
1447        if self.divider {
1448            let divider = match self.axis {
1449                Axis::Horizontal => {
1450                    Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
1451                }
1452                Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
1453            };
1454            ctx.stroke_rect(
1455                divider,
1456                palette.border.with_alpha(0.85),
1457                StrokeStyle::new(1.0),
1458            );
1459        }
1460
1461        let selected = self.current_selected();
1462        for (index, item) in self.items.iter().enumerate() {
1463            let Some(rect) = self.item_rect(bounds, index) else {
1464                continue;
1465            };
1466            let selected_item = selected == Some(index);
1467            let hovered = self.hovered == Some(index);
1468            let hover_amount = self.hover_amount_for(index, ctx);
1469            let press_amount = self.press_amount_for(index, ctx);
1470            let enabled = item.enabled;
1471            let base_background = if selected_item {
1472                palette.selection
1473            } else {
1474                palette.surface
1475            };
1476            let background = if !enabled {
1477                mix_color(
1478                    base_background,
1479                    palette.surface,
1480                    interaction.disabled_opacity,
1481                )
1482            } else if press_amount > 0.0 {
1483                mix_color(
1484                    if hover_amount > 0.0 {
1485                        mix_color(
1486                            base_background,
1487                            palette.control_hover,
1488                            interaction.hover_blend
1489                                * if selected_item { 0.35 } else { 1.0 }
1490                                * hover_amount,
1491                        )
1492                    } else {
1493                        base_background
1494                    },
1495                    palette.control_active,
1496                    interaction.pressed_blend
1497                        * if selected_item { 0.45 } else { 1.0 }
1498                        * press_amount,
1499                )
1500            } else if hover_amount > 0.0 {
1501                mix_color(
1502                    base_background,
1503                    palette.control_hover,
1504                    interaction.hover_blend * if selected_item { 0.35 } else { 1.0 } * hover_amount,
1505                )
1506            } else {
1507                base_background
1508            };
1509            let border = if !enabled {
1510                palette.border.with_alpha(0.55)
1511            } else if selected_item {
1512                palette.selection_border
1513            } else if hovered || hover_amount > 0.0 || press_amount > 0.0 {
1514                palette.border_hover
1515            } else {
1516                palette.border
1517            };
1518            draw_control_frame(
1519                ctx,
1520                rect,
1521                metrics.corner_radius,
1522                metrics,
1523                background,
1524                border,
1525                (self.focus_animation.get(ctx) > Progress::EPSILON && selected_item).then_some(
1526                    palette
1527                        .focus_ring
1528                        .with_alpha(palette.focus_ring.alpha * self.focus_animation.get(ctx)),
1529                ),
1530            );
1531            let center = rect_center(rect);
1532            let side = icon_size.min(rect.width().min(rect.height())).max(0.0);
1533            let pressed_offset = press_amount * interaction.pressed_offset;
1534            let icon_rect = Rect::new(
1535                center.x - side * 0.5,
1536                center.y - side * 0.5 + pressed_offset,
1537                side,
1538                side,
1539            );
1540            draw_icon_glyph(
1541                ctx,
1542                item.icon,
1543                icon_rect,
1544                if !enabled {
1545                    palette.text.with_alpha(0.38)
1546                } else {
1547                    palette.text
1548                },
1549            );
1550        }
1551    }
1552
1553    fn semantics(&self, ctx: &mut SemanticsCtx) {
1554        self.enabled.observe(|source| {
1555            ctx.observe(source);
1556        });
1557        let enabled = self.enabled.get();
1558        let selected = self.current_selected();
1559        let mut node = SemanticsNode::new(
1560            ctx.widget_id(),
1561            SemanticsRole::GenericContainer,
1562            ctx.bounds(),
1563        );
1564        node.name = Some(self.name.clone());
1565        node.value = selected
1566            .and_then(|index| self.items.get(index))
1567            .map(|item| SemanticsValue::Text(item.label.clone()));
1568        node.state.focused = ctx.is_focused();
1569        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
1570        if !enabled {
1571            node.state.disabled = true;
1572            node.actions.clear();
1573        }
1574        ctx.push(node);
1575
1576        for (index, item) in self.items.iter().enumerate() {
1577            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
1578                continue;
1579            };
1580            let mut item_node = SemanticsNode::new(
1581                tool_palette_item_id(ctx.widget_id(), index),
1582                SemanticsRole::Button,
1583                rect,
1584            );
1585            item_node.parent = Some(ctx.widget_id());
1586            item_node.name = Some(item.label.clone());
1587            item_node.value = Some(SemanticsValue::Text(item.label.clone()));
1588            item_node.state.disabled = !item.enabled;
1589            item_node.state.hovered = self.hovered == Some(index);
1590            item_node.state.selected = selected == Some(index);
1591            if item.enabled {
1592                item_node.actions = vec![SemanticsAction::Activate];
1593            }
1594            if !enabled {
1595                item_node.state.disabled = true;
1596                item_node.actions.clear();
1597            }
1598            ctx.push(item_node);
1599        }
1600    }
1601
1602    fn accepts_focus(&self) -> bool {
1603        self.enabled.get() && (self.items.iter().any(|item| item.enabled))
1604    }
1605
1606    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1607        let theme = self.resolved_theme();
1608        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1609        ctx.request_paint();
1610        ctx.request_semantics();
1611    }
1612}
1613
1614pub(super) fn tool_palette_item_id(parent: WidgetId, index: usize) -> WidgetId {
1615    const TAG: u64 = 4_u64 << 50;
1616    const LOW_MASK: u64 = (1_u64 << 50) - 1;
1617
1618    WidgetId::new(
1619        TAG | (parent
1620            .get()
1621            .wrapping_mul(397)
1622            .wrapping_add(index as u64 + 1)
1623            & LOW_MASK),
1624    )
1625}