Skip to main content

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