Skip to main content

sui_widgets/composites/
popups.rs

1use crate::DefaultTheme;
2use crate::HdrThemeMode;
3use crate::MotionScalar;
4use crate::ResolvedEffectStyle;
5use crate::ResolvedHdrStyle;
6use crate::WidgetColorRole;
7use crate::WidgetEffectRole;
8use crate::WidgetLuminanceRole;
9use crate::WidgetMaterialRole;
10use crate::composites::forms::{
11    set_focus_animation_target, set_hover_animation_target, set_press_animation_target,
12};
13use crate::composites::indicators::{
14    draw_control_frame, draw_focus_ring_frame, draw_popover_arrival_overlay, inset_rect,
15    measure_text, mix_color, rounded_rect_path, text_token_style, tooltip_tail,
16};
17use crate::composites::toolbars::{
18    MenuItem, context_menu_item_semantics_node, menu_item_semantics_node, menu_row_height,
19    menu_submenu_indicator_width, themed_menu_height_for_rows, virtual_menu_item_path_id,
20};
21use crate::controls::cap_resolved_hdr_style;
22use crate::overlay::OverlayAlignment;
23use crate::overlay::OverlayPlacement;
24use crate::overlay::OverlayPlacementRequest;
25use crate::overlay::OverlaySide;
26use crate::overlay::place_overlay;
27use crate::paint_theme_shadow;
28use crate::resolve_widget_hdr_style;
29use crate::text_align::paint_aligned_text;
30use std::cell::RefCell;
31use std::rc::Rc;
32use sui_core::Color;
33use sui_core::Event;
34use sui_core::InvalidationKind;
35use sui_core::InvalidationRequest;
36use sui_core::InvalidationTarget;
37use sui_core::KeyState;
38use sui_core::Point;
39use sui_core::PointerButton;
40use sui_core::PointerEventKind;
41use sui_core::Rect;
42use sui_core::SemanticsAction;
43use sui_core::SemanticsNode;
44use sui_core::SemanticsPopupKind;
45use sui_core::SemanticsRole;
46use sui_core::SemanticsState;
47use sui_core::SemanticsValue;
48use sui_core::Size;
49use sui_core::TimerToken;
50use sui_core::Vector;
51use sui_core::WakeEvent;
52use sui_core::WidgetId;
53use sui_layout::Constraints;
54use sui_runtime::ArrangeCtx;
55use sui_runtime::Command;
56use sui_runtime::EventCtx;
57use sui_runtime::EventPhase;
58use sui_runtime::LayerOptions;
59use sui_runtime::MeasureCtx;
60use sui_runtime::OVERLAY_DISMISS_REQUEST;
61use sui_runtime::OverlayDismissPolicy;
62use sui_runtime::OverlayFocusBehavior;
63use sui_runtime::OverlayKind;
64use sui_runtime::OverlayOptions;
65use sui_runtime::PaintBoundaryMode;
66use sui_runtime::PaintCtx;
67use sui_runtime::SemanticsCtx;
68use sui_runtime::SingleChild;
69use sui_runtime::StackSurfaceOptions;
70use sui_runtime::Widget;
71use sui_runtime::WidgetPodMutVisitor;
72use sui_runtime::WidgetPodVisitor;
73use sui_scene::LayerCompositionMode;
74use sui_scene::LayerProperties;
75use sui_text::TextMeasurement;
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum TooltipPlacement {
79    Above,
80    Below,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum TooltipAlignment {
85    Start,
86    Center,
87    End,
88}
89
90pub struct Menu {
91    pub(super) theme: Box<DefaultTheme>,
92    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
93    pub(super) name: String,
94    pub(super) items: Vec<MenuItem>,
95    pub(super) highlighted: Option<usize>,
96    pub(super) highlight_visual: Option<usize>,
97    pub(super) pressed: Option<usize>,
98    pub(super) press_visual: Option<usize>,
99    pub(super) highlight_animation: AnimatedScalar,
100    pub(super) press_animation: AnimatedScalar,
101    pub(super) focus_animation: AnimatedScalar,
102    pub(super) measured_width: f32,
103    pub(super) focus_on_pointer_down: bool,
104    pub(super) on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
105    pub(super) on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
106}
107
108impl Menu {
109    pub fn new(name: impl Into<String>) -> Self {
110        Self {
111            theme: Box::new(DefaultTheme::default()),
112            theme_reader: None,
113            name: name.into(),
114            items: Vec::new(),
115            highlighted: None,
116            highlight_visual: None,
117            pressed: None,
118            press_visual: None,
119            highlight_animation: AnimatedScalar::new(0.0),
120            press_animation: AnimatedScalar::new(0.0),
121            focus_animation: AnimatedScalar::new(0.0),
122            measured_width: 220.0,
123            focus_on_pointer_down: true,
124            on_activate: None,
125            on_activate_with_ctx: None,
126        }
127    }
128
129    pub fn theme(mut self, theme: DefaultTheme) -> Self {
130        self.theme = Box::new(theme);
131        self.theme_reader = None;
132        self
133    }
134
135    pub fn theme_when<F>(mut self, theme: F) -> Self
136    where
137        F: Fn() -> DefaultTheme + 'static,
138    {
139        self.theme_reader = Some(Box::new(theme));
140        self
141    }
142
143    pub fn item(mut self, item: MenuItem) -> Self {
144        self.items.push(item);
145        self
146    }
147
148    pub fn items<I>(mut self, items: I) -> Self
149    where
150        I: IntoIterator<Item = MenuItem>,
151    {
152        self.items.extend(items);
153        self
154    }
155
156    pub fn highlighted(mut self, index: usize) -> Self {
157        self.highlighted = Some(index);
158        self.highlight_visual = Some(index);
159        self.highlight_animation = AnimatedScalar::new(1.0);
160        self
161    }
162
163    pub fn on_activate<F>(mut self, on_activate: F) -> Self
164    where
165        F: FnMut(usize, MenuItem) + 'static,
166    {
167        self.on_activate = Some(Box::new(on_activate));
168        self
169    }
170
171    pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
172    where
173        F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
174    {
175        self.on_activate_with_ctx = Some(Box::new(on_activate));
176        self
177    }
178
179    pub fn focus_on_pointer_down(mut self, focus_on_pointer_down: bool) -> Self {
180        self.focus_on_pointer_down = focus_on_pointer_down;
181        self
182    }
183
184    pub(super) fn row_height(&self) -> f32 {
185        let theme = self.resolved_theme();
186        menu_row_height(&theme)
187    }
188
189    pub(super) fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
190        let Some(item) = self.items.get(index).cloned() else {
191            return;
192        };
193        if !item.enabled {
194            return;
195        }
196        match (&mut self.on_activate, &mut self.on_activate_with_ctx) {
197            (Some(on_activate), _) => on_activate(index, item),
198            (None, Some(on_activate)) => on_activate(ctx, index, item),
199            (None, None) => {}
200        }
201    }
202
203    pub(super) fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
204        if index >= self.items.len() {
205            return None;
206        }
207        let theme = self.resolved_theme();
208        let padding = theme.metrics.menu_padding;
209        let x = bounds.x() + padding.left;
210        let y = bounds.y() + padding.top + (index as f32 * self.row_height());
211        Some(Rect::new(
212            x,
213            y,
214            (bounds.width() - padding.left - padding.right).max(0.0),
215            self.row_height(),
216        ))
217    }
218
219    pub(super) fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
220        self.items.iter().enumerate().find_map(|(index, _)| {
221            self.item_rect(bounds, index)
222                .filter(|rect| rect.contains(position))
223                .map(|_| index)
224        })
225    }
226
227    pub(super) fn move_highlight(&mut self, delta: isize, ctx: &mut EventCtx) {
228        if self.items.is_empty() {
229            return;
230        }
231
232        let len = self.items.len() as isize;
233        let start = self.highlighted.unwrap_or(0) as isize;
234        let mut index = (start + delta).clamp(0, len - 1);
235        while !self.items[index as usize].enabled {
236            let next = (index + delta).clamp(0, len - 1);
237            if next == index {
238                break;
239            }
240            index = next;
241        }
242        self.set_highlighted(Some(index as usize), ctx);
243    }
244
245    pub(super) fn resolved_theme(&self) -> DefaultTheme {
246        self.theme_reader
247            .as_ref()
248            .map(|theme| theme())
249            .unwrap_or(*self.theme)
250    }
251
252    pub(super) fn set_highlighted(&mut self, highlighted: Option<usize>, ctx: &mut EventCtx) {
253        if self.highlighted == highlighted {
254            return;
255        }
256        let theme = self.resolved_theme();
257        self.highlighted = highlighted;
258        if let Some(index) = highlighted {
259            self.highlight_visual = Some(index);
260            self.highlight_animation = AnimatedScalar::new(0.0);
261            set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
262        } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
263            self.highlight_visual = None;
264        }
265        ctx.request_paint();
266        ctx.request_semantics();
267    }
268
269    pub(super) fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
270        if self.pressed == pressed {
271            return;
272        }
273        let theme = self.resolved_theme();
274        self.pressed = pressed;
275        if let Some(index) = pressed {
276            self.press_visual = Some(index);
277            self.press_animation = AnimatedScalar::new(0.0);
278            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
279        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
280            self.press_visual = None;
281        }
282        ctx.request_paint();
283        ctx.request_semantics();
284    }
285
286    pub(super) fn highlight_amount_for(&self, index: usize) -> f32 {
287        if self.highlight_visual == Some(index) {
288            self.highlight_animation.value
289        } else {
290            0.0
291        }
292    }
293
294    pub(super) fn press_amount_for(&self, index: usize) -> f32 {
295        if self.press_visual == Some(index) {
296            self.press_animation.value
297        } else {
298            0.0
299        }
300    }
301
302    pub(super) fn advance_animations(&mut self, time: f64) -> bool {
303        let highlight_animating = self.highlight_animation.advance(time);
304        if !highlight_animating
305            && self.highlighted.is_none()
306            && self.highlight_animation.value <= AnimatedScalar::EPSILON
307        {
308            self.highlight_visual = None;
309        }
310
311        let press_animating = self.press_animation.advance(time);
312        if !press_animating
313            && self.pressed.is_none()
314            && self.press_animation.value <= AnimatedScalar::EPSILON
315        {
316            self.press_visual = None;
317        }
318
319        highlight_animating | press_animating | self.focus_animation.advance(time)
320    }
321}
322
323impl Widget for Menu {
324    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
325        match event {
326            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
327                self.set_highlighted(self.item_at(ctx.bounds(), pointer.position), ctx);
328            }
329            Event::Pointer(pointer)
330                if pointer.kind == PointerEventKind::Down
331                    && pointer.button == Some(PointerButton::Primary) =>
332            {
333                let highlighted = self.item_at(ctx.bounds(), pointer.position);
334                self.set_highlighted(highlighted, ctx);
335                self.set_pressed(
336                    highlighted
337                        .filter(|index| self.items.get(*index).is_some_and(|item| item.enabled)),
338                    ctx,
339                );
340                if self.focus_on_pointer_down {
341                    ctx.request_focus();
342                }
343                ctx.request_pointer_capture(pointer.pointer_id);
344                ctx.set_handled();
345            }
346            Event::Pointer(pointer)
347                if pointer.kind == PointerEventKind::Up
348                    && pointer.button == Some(PointerButton::Primary) =>
349            {
350                let highlighted = self.item_at(ctx.bounds(), pointer.position);
351                if let Some(index) = self
352                    .pressed
353                    .zip(highlighted)
354                    .filter(|(left, right)| left == right)
355                    .map(|(index, _)| index)
356                {
357                    self.activate(ctx, index);
358                }
359                self.set_highlighted(highlighted, ctx);
360                self.set_pressed(None, ctx);
361                ctx.release_pointer_capture(pointer.pointer_id);
362                ctx.set_handled();
363            }
364            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
365                if self.pressed.is_some() {
366                    self.set_pressed(None, ctx);
367                    ctx.release_pointer_capture(pointer.pointer_id);
368                    ctx.set_handled();
369                }
370            }
371            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
372                match key.key.as_str() {
373                    "ArrowDown" => self.move_highlight(1, ctx),
374                    "ArrowUp" => self.move_highlight(-1, ctx),
375                    "Home" => {
376                        self.set_highlighted(self.items.iter().position(|item| item.enabled), ctx);
377                    }
378                    "End" => {
379                        self.set_highlighted(self.items.iter().rposition(|item| item.enabled), ctx);
380                    }
381                    "Enter" | " " => {
382                        if let Some(index) = self.highlighted {
383                            self.activate(ctx, index);
384                        }
385                    }
386                    _ => return,
387                }
388                ctx.request_paint();
389                ctx.request_semantics();
390                ctx.set_handled();
391            }
392            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
393                if self.advance_animations(*time) {
394                    ctx.request_animation_frame();
395                }
396                ctx.request_paint();
397            }
398            _ => {}
399        }
400    }
401
402    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
403        let theme = self.resolved_theme();
404        let label_style = theme.body_text_style();
405        let shortcut_style = theme.placeholder_text_style();
406        let mut width: f32 = 0.0;
407        for item in &self.items {
408            let label = measure_text(ctx, item.label(), &label_style).width;
409            let shortcut = item
410                .shortcut
411                .as_ref()
412                .map(|text| measure_text(ctx, text, &shortcut_style).width)
413                .unwrap_or(0.0);
414            width = width.max(
415                label
416                    + shortcut
417                    + theme.metrics.menu_item_padding.left
418                    + theme.metrics.menu_item_padding.right
419                    + theme.metrics.menu_shortcut_width,
420            );
421        }
422        self.measured_width = width.max(220.0);
423        let height = themed_menu_height_for_rows(&theme, self.row_height(), self.items.len());
424        constraints.clamp(Size::new(
425            self.measured_width,
426            height.max(themed_menu_height_for_rows(&theme, self.row_height(), 1)),
427        ))
428    }
429
430    fn paint(&self, ctx: &mut PaintCtx) {
431        let theme = self.resolved_theme();
432        let palette = theme.palette;
433        let metrics = theme.metrics;
434        let interaction = theme.interaction;
435        let item_padding = metrics.menu_item_padding;
436
437        // Cast an elevation shadow behind the raised menu surface before any
438        // fill so the soft drop shadow is not clipped by the frame.
439        let surface_radius = metrics.corner_radius + 2.0;
440        paint_theme_shadow(
441            ctx,
442            ctx.bounds(),
443            [surface_radius; 4],
444            &theme.shadows.box_shadow.lg,
445        );
446
447        draw_control_frame(
448            ctx,
449            ctx.bounds(),
450            surface_radius,
451            metrics,
452            palette.surface_raised,
453            palette.border,
454            (self.focus_animation.value > AnimatedScalar::EPSILON).then_some(
455                palette
456                    .focus_ring
457                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
458            ),
459        );
460
461        for (index, item) in self.items.iter().enumerate() {
462            let Some(row) = self.item_rect(ctx.bounds(), index) else {
463                continue;
464            };
465
466            if item.separator_before {
467                let line = Rect::new(
468                    row.x(),
469                    row.y() - (metrics.menu_padding.top * 0.5),
470                    row.width(),
471                    1.0,
472                );
473                ctx.fill(rounded_rect_path(line, 0.5), palette.border);
474            }
475
476            let highlighted = self.highlighted == Some(index);
477            let highlight_amount = self.highlight_amount_for(index);
478            let press_amount = self.press_amount_for(index);
479            let label_style = theme.text_style(item.text_color(&theme));
480            let label_slot = Rect::new(
481                row.x() + item_padding.left,
482                row.y(),
483                (row.width()
484                    - item_padding.left
485                    - item_padding.right
486                    - item
487                        .shortcut
488                        .as_ref()
489                        .map(|_| metrics.menu_shortcut_width)
490                        .unwrap_or(0.0))
491                .max(0.0),
492                row.height(),
493            );
494            if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
495                let highlight_background =
496                    mix_color(palette.control, palette.selection, highlight_amount);
497                let background = if press_amount > 0.0 {
498                    mix_color(
499                        highlight_background,
500                        palette.control_active,
501                        interaction.pressed_blend * press_amount,
502                    )
503                } else {
504                    highlight_background
505                };
506                ctx.fill(
507                    rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
508                    background,
509                );
510            }
511
512            ctx.push_clip_rect(label_slot);
513            paint_aligned_text(
514                ctx,
515                label_slot,
516                &item.label,
517                &label_style,
518                label_style.line_height,
519                0.0,
520            );
521            ctx.pop_clip();
522
523            if let Some(shortcut) = &item.shortcut {
524                let shortcut_style = theme.placeholder_text_style();
525                let shortcut_slot = Rect::new(
526                    row.max_x() - item_padding.right - metrics.menu_shortcut_width,
527                    row.y(),
528                    metrics.menu_shortcut_width,
529                    row.height(),
530                );
531                ctx.push_clip_rect(shortcut_slot);
532                paint_aligned_text(
533                    ctx,
534                    shortcut_slot,
535                    shortcut,
536                    &shortcut_style,
537                    shortcut_style.line_height,
538                    1.0,
539                );
540                ctx.pop_clip();
541            }
542        }
543    }
544
545    fn semantics(&self, ctx: &mut SemanticsCtx) {
546        let state = SemanticsState {
547            focused: ctx.is_focused(),
548            ..SemanticsState::default()
549        };
550        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Menu, ctx.bounds());
551        node.name = Some(self.name.clone());
552        node.state = state;
553        node.value = self
554            .highlighted
555            .and_then(|index| self.items.get(index))
556            .map(|item| SemanticsValue::Text(item.label.clone()));
557        node.actions = vec![
558            SemanticsAction::Focus,
559            SemanticsAction::SetValue,
560            SemanticsAction::Activate,
561        ];
562        ctx.push(node);
563        for (index, item) in self.items.iter().enumerate() {
564            let Some(row) = self.item_rect(ctx.bounds(), index) else {
565                continue;
566            };
567            ctx.push(menu_item_semantics_node(
568                ctx.widget_id(),
569                index,
570                item,
571                row,
572                self.highlighted == Some(index),
573            ));
574        }
575    }
576
577    fn accepts_focus(&self) -> bool {
578        true
579    }
580
581    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
582        let theme = self.resolved_theme();
583        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
584        ctx.request_paint();
585        ctx.request_semantics();
586    }
587}
588
589pub(super) type AnimatedScalar = MotionScalar;
590
591pub(super) fn request_child_invalidation(
592    ctx: &mut EventCtx,
593    widget_id: WidgetId,
594    kind: InvalidationKind,
595) {
596    ctx.request(InvalidationRequest::new(
597        InvalidationTarget::Widget(widget_id),
598        kind,
599    ));
600}
601
602pub(super) fn tooltip_fallback_measurement(theme: &DefaultTheme) -> TextMeasurement {
603    TextMeasurement {
604        width: 120.0,
605        height: theme.typography.body_line_height,
606        bounds: Rect::new(0.0, 0.0, 120.0, theme.typography.body_line_height),
607        ascent: theme.typography.body_font_size,
608        descent: 0.0,
609        cap_height: Some(theme.typography.body_font_size),
610    }
611}
612
613pub(super) fn tooltip_bubble_rect(
614    trigger_bounds: Rect,
615    measurement: Option<TextMeasurement>,
616    theme: &DefaultTheme,
617    placement: TooltipPlacement,
618    alignment: TooltipAlignment,
619    viewport: Rect,
620) -> (Rect, TooltipPlacement) {
621    let measurement = measurement.unwrap_or_else(|| tooltip_fallback_measurement(theme));
622    let padding = theme.metrics.tooltip_padding;
623    let width =
624        (measurement.width + padding.left + padding.right).max(theme.metrics.tooltip_min_width);
625    let height =
626        measurement.height.max(theme.typography.body_line_height) + padding.top + padding.bottom;
627    let side = match placement {
628        TooltipPlacement::Above => OverlaySide::Top,
629        TooltipPlacement::Below => OverlaySide::Bottom,
630    };
631    let alignment = match alignment {
632        TooltipAlignment::Start => OverlayAlignment::Start,
633        TooltipAlignment::Center => OverlayAlignment::Center,
634        TooltipAlignment::End => OverlayAlignment::End,
635    };
636    let result = place_overlay(
637        &OverlayPlacementRequest::new(
638            trigger_bounds,
639            Size::new(width, height),
640            viewport,
641            OverlayPlacement::new(side, alignment),
642        )
643        .gap(theme.metrics.tooltip_gap)
644        .margin(theme.metrics.tooltip_gap.max(4.0)),
645    );
646    let resolved = if result.placement.side == OverlaySide::Top {
647        TooltipPlacement::Above
648    } else {
649        TooltipPlacement::Below
650    };
651    (result.bounds, resolved)
652}
653
654#[derive(Debug, Clone)]
655pub(super) struct TooltipPresentationState {
656    pub(super) theme: DefaultTheme,
657    pub(super) text: String,
658    pub(super) placement: TooltipPlacement,
659    pub(super) resolved_placement: TooltipPlacement,
660    pub(super) alignment: TooltipAlignment,
661    pub(super) measurement: Option<TextMeasurement>,
662    pub(super) hovered: bool,
663    pub(super) trigger_bounds: Rect,
664    pub(super) bubble_bounds: Rect,
665    pub(super) reveal: AnimatedScalar,
666}
667
668impl TooltipPresentationState {
669    pub(super) fn new(text: String) -> Self {
670        Self {
671            theme: DefaultTheme::default(),
672            text,
673            placement: TooltipPlacement::Above,
674            resolved_placement: TooltipPlacement::Above,
675            alignment: TooltipAlignment::Center,
676            measurement: None,
677            hovered: false,
678            trigger_bounds: Rect::ZERO,
679            bubble_bounds: Rect::ZERO,
680            reveal: AnimatedScalar::new(0.0),
681        }
682    }
683
684    pub(super) fn is_presented(&self) -> bool {
685        self.reveal.is_presented()
686    }
687
688    pub(super) fn layer_properties(&self) -> LayerProperties {
689        let direction = match self.resolved_placement {
690            TooltipPlacement::Above => -1.0,
691            TooltipPlacement::Below => 1.0,
692        };
693        LayerProperties {
694            opacity: self.reveal.value,
695            translation: Vector::new(
696                0.0,
697                self.theme.metrics.tooltip_reveal_offset * (1.0 - self.reveal.value) * direction,
698            ),
699        }
700    }
701}
702
703pub(super) struct TooltipOverlay {
704    pub(super) state: Rc<RefCell<TooltipPresentationState>>,
705}
706
707impl TooltipOverlay {
708    pub(super) fn new(state: Rc<RefCell<TooltipPresentationState>>) -> Self {
709        Self { state }
710    }
711}
712
713impl Widget for TooltipOverlay {
714    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
715        let state = self.state.borrow();
716        if !state.is_presented() {
717            return Size::ZERO;
718        }
719        state.bubble_bounds.size
720    }
721
722    fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
723        self.state.borrow_mut().bubble_bounds = bounds;
724    }
725
726    fn paint(&self, ctx: &mut PaintCtx) {
727        let state = self.state.borrow();
728        if !state.is_presented() {
729            return;
730        }
731
732        let bubble = ctx.bounds();
733        let metrics = state.theme.metrics;
734        // Soft elevation behind the tooltip bubble, drawn before the fill.
735        paint_theme_shadow(
736            ctx,
737            bubble,
738            [metrics.corner_radius; 4],
739            &state.theme.shadows.box_shadow.sm,
740        );
741        draw_control_frame(
742            ctx,
743            bubble,
744            metrics.corner_radius,
745            metrics,
746            state.theme.surfaces.tooltip,
747            state.theme.surfaces.tooltip_border,
748            None,
749        );
750        let tail = tooltip_tail(state.trigger_bounds, bubble, state.resolved_placement);
751        ctx.fill(tail, state.theme.surfaces.tooltip);
752        let text_style = text_token_style(
753            &state.theme,
754            state.theme.text.sm,
755            state.theme.surfaces.tooltip_text,
756        );
757        let text_slot = inset_rect(bubble, metrics.tooltip_padding);
758        ctx.push_clip_rect(text_slot);
759        paint_aligned_text(
760            ctx,
761            text_slot,
762            &state.text,
763            &text_style,
764            text_style.line_height,
765            0.0,
766        );
767        ctx.pop_clip();
768    }
769
770    fn layer_options(&self) -> LayerOptions {
771        let presented = self.state.borrow().is_presented();
772        LayerOptions {
773            paint_boundary: PaintBoundaryMode::Explicit,
774            composition_mode: if presented {
775                LayerCompositionMode::Overlay
776            } else {
777                LayerCompositionMode::Normal
778            },
779        }
780    }
781
782    fn layer_properties(&self) -> LayerProperties {
783        self.state.borrow().layer_properties()
784    }
785
786    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
787        self.state
788            .borrow()
789            .is_presented()
790            .then_some(StackSurfaceOptions {
791                transient: true,
792                hit_test: false,
793                ..StackSurfaceOptions::default()
794            })
795    }
796}
797
798pub struct Tooltip {
799    pub(super) child: SingleChild,
800    pub(super) overlay: SingleChild,
801    pub(super) state: Rc<RefCell<TooltipPresentationState>>,
802}
803
804impl Tooltip {
805    pub fn new<W>(text: impl Into<String>, child: W) -> Self
806    where
807        W: Widget + 'static,
808    {
809        let state = Rc::new(RefCell::new(TooltipPresentationState::new(text.into())));
810        Self {
811            child: SingleChild::new(child),
812            overlay: SingleChild::new(TooltipOverlay::new(Rc::clone(&state))),
813            state,
814        }
815    }
816
817    pub fn theme(self, theme: DefaultTheme) -> Self {
818        self.state.borrow_mut().theme = theme;
819        self
820    }
821
822    pub fn placement(self, placement: TooltipPlacement) -> Self {
823        self.state.borrow_mut().placement = placement;
824        self
825    }
826
827    pub fn alignment(self, alignment: TooltipAlignment) -> Self {
828        self.state.borrow_mut().alignment = alignment;
829        self
830    }
831
832    pub(super) fn set_hovered(&mut self, ctx: &mut EventCtx, hovered: bool) {
833        let overlay_id = self.overlay.child().id();
834        let mut state = self.state.borrow_mut();
835        if state.hovered == hovered {
836            return;
837        }
838        let was_presented = state.is_presented();
839        let motion = state.theme.motion;
840        state.hovered = hovered;
841        let should_animate = state.reveal.set_target(
842            hovered as u8 as f32,
843            ctx.current_time(),
844            motion.entrance_duration(),
845            motion.entrance_easing(),
846        );
847        let is_presented = state.is_presented();
848        drop(state);
849
850        if was_presented != is_presented {
851            ctx.request_measure();
852            request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
853        }
854        if should_animate {
855            ctx.request_animation_frame();
856        }
857        ctx.request_semantics();
858    }
859}
860
861impl Widget for Tooltip {
862    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
863        match event {
864            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
865                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
866            }
867            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
868                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
869            }
870            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
871                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
872            }
873            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
874                let overlay_id = self.overlay.child().id();
875                let mut state = self.state.borrow_mut();
876                let was_presented = state.is_presented();
877                let previous = state.reveal.value;
878                let animating = state.reveal.advance(*time);
879                let changed = state.reveal.changed_since(previous);
880                let is_presented = state.is_presented();
881                drop(state);
882
883                if changed {
884                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Transform);
885                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Effect);
886                }
887                if was_presented != is_presented {
888                    ctx.request_measure();
889                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
890                }
891                if animating {
892                    ctx.request_animation_frame();
893                }
894                ctx.set_handled();
895            }
896            _ => {}
897        }
898    }
899
900    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
901        let mut state = self.state.borrow_mut();
902        let text_style = text_token_style(
903            &state.theme,
904            state.theme.text.sm,
905            state.theme.surfaces.tooltip_text,
906        );
907        state.measurement = Some(measure_text(ctx, &state.text, &text_style));
908        drop(state);
909        self.child.measure(ctx, constraints)
910    }
911
912    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
913        let trigger_bounds =
914            Rect::from_origin_size(bounds.origin, self.child.child().measured_size());
915        self.child.arrange(ctx, trigger_bounds);
916
917        let mut state = self.state.borrow_mut();
918        state.trigger_bounds = trigger_bounds;
919        let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
920        let (bubble_bounds, resolved_placement) = tooltip_bubble_rect(
921            trigger_bounds,
922            state.measurement,
923            &state.theme,
924            state.placement,
925            state.alignment,
926            viewport,
927        );
928        state.bubble_bounds = bubble_bounds;
929        state.resolved_placement = resolved_placement;
930        let overlay_bounds = if state.is_presented() {
931            state.bubble_bounds
932        } else {
933            Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
934        };
935        drop(state);
936        self.overlay.arrange(ctx, overlay_bounds);
937    }
938
939    fn paint(&self, ctx: &mut PaintCtx) {
940        self.child.paint(ctx);
941        self.overlay.paint(ctx);
942    }
943
944    fn overlay_options(&self) -> Option<OverlayOptions> {
945        self.state.borrow().is_presented().then_some(
946            OverlayOptions::new(OverlayKind::Tooltip)
947                .dismiss(OverlayDismissPolicy::NONE)
948                .focus(OverlayFocusBehavior::NONE),
949        )
950    }
951
952    fn semantics(&self, ctx: &mut SemanticsCtx) {
953        self.child.semantics(ctx);
954        let state = self.state.borrow();
955        if state.hovered {
956            let mut node =
957                SemanticsNode::new(ctx.widget_id(), SemanticsRole::Tooltip, state.bubble_bounds);
958            node.name = Some(state.text.clone());
959            ctx.push(node);
960        }
961    }
962
963    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
964        self.child.visit_children(visitor);
965        if self.state.borrow().is_presented() {
966            self.overlay.visit_children(visitor);
967        }
968    }
969
970    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
971        self.child.visit_children_mut(visitor);
972        if self.state.borrow().is_presented() {
973            self.overlay.visit_children_mut(visitor);
974        }
975    }
976}
977
978#[derive(Debug, Clone, Copy, PartialEq)]
979pub(super) struct PopoverVisuals {
980    pub(super) background: Color,
981    pub(super) border: Color,
982    pub(super) focus_ring: Option<Color>,
983    pub(super) surface_style: Option<ResolvedHdrStyle>,
984    pub(super) arrival_effect: Option<ResolvedEffectStyle>,
985}
986
987#[derive(Debug, Clone)]
988pub(super) struct PopoverSurfaceState {
989    pub(super) theme: DefaultTheme,
990    pub(super) frame_rect: Rect,
991    pub(super) arrival_active: bool,
992    pub(super) reveal: AnimatedScalar,
993    pub(super) focus_animation: AnimatedScalar,
994}
995
996impl PopoverSurfaceState {
997    pub(super) fn new() -> Self {
998        Self {
999            theme: DefaultTheme::default(),
1000            frame_rect: Rect::ZERO,
1001            arrival_active: false,
1002            reveal: AnimatedScalar::new(0.0),
1003            focus_animation: AnimatedScalar::new(0.0),
1004        }
1005    }
1006
1007    pub(super) fn is_presented(&self) -> bool {
1008        self.reveal.is_presented()
1009    }
1010
1011    pub(super) fn arrival_duration(&self) -> f64 {
1012        (0.18 / self.theme.hdr.effects.pulse.speed.max(0.25) as f64).clamp(0.10, 0.28)
1013    }
1014
1015    pub(super) fn layer_properties(&self) -> LayerProperties {
1016        LayerProperties {
1017            opacity: self.reveal.value,
1018            translation: Vector::new(
1019                0.0,
1020                -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
1021            ),
1022        }
1023    }
1024
1025    pub(super) fn resolved_visuals(&self) -> PopoverVisuals {
1026        let palette = self.theme.palette;
1027
1028        if !self.is_presented() || matches!(self.theme.hdr.mode, HdrThemeMode::Disabled) {
1029            return PopoverVisuals {
1030                background: palette.surface_raised,
1031                border: palette.border,
1032                focus_ring: Some(palette.focus_ring),
1033                surface_style: None,
1034                arrival_effect: None,
1035            };
1036        }
1037
1038        let surface_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
1039            &self.theme.hdr,
1040            WidgetColorRole::SurfaceElevated,
1041            WidgetLuminanceRole::Standard,
1042            WidgetMaterialRole::Raised,
1043            self.arrival_active.then_some(WidgetEffectRole::Pulse),
1044        ));
1045        let border_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
1046            &self.theme.hdr,
1047            WidgetColorRole::SurfaceOutline,
1048            WidgetLuminanceRole::Standard,
1049            WidgetMaterialRole::Flat,
1050            None,
1051        ));
1052
1053        PopoverVisuals {
1054            background: surface_style.color,
1055            border: border_style.color,
1056            focus_ring: Some(border_style.color.with_alpha(palette.focus_ring.alpha)),
1057            surface_style: Some(surface_style),
1058            arrival_effect: surface_style.effect,
1059        }
1060    }
1061}
1062
1063pub(super) struct PopoverSurface {
1064    pub(super) content: SingleChild,
1065    pub(super) state: Rc<RefCell<PopoverSurfaceState>>,
1066}
1067
1068impl PopoverSurface {
1069    pub(super) fn new<C>(state: Rc<RefCell<PopoverSurfaceState>>, content: C) -> Self
1070    where
1071        C: Widget + 'static,
1072    {
1073        Self {
1074            content: SingleChild::new(content),
1075            state,
1076        }
1077    }
1078}
1079
1080impl Widget for PopoverSurface {
1081    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1082        let state = self.state.borrow();
1083        if !state.is_presented() {
1084            return Size::ZERO;
1085        }
1086        let padding = state.theme.metrics.popover_padding;
1087        drop(state);
1088
1089        let content_constraints = Constraints::new(
1090            Size::ZERO,
1091            Size::new(
1092                if constraints.max.width.is_finite() {
1093                    (constraints.max.width - padding.left - padding.right).max(0.0)
1094                } else {
1095                    f32::INFINITY
1096                },
1097                if constraints.max.height.is_finite() {
1098                    (constraints.max.height - padding.top - padding.bottom).max(0.0)
1099                } else {
1100                    f32::INFINITY
1101                },
1102            ),
1103        );
1104        let content_size = self.content.measure(ctx, content_constraints);
1105        Size::new(
1106            content_size.width + padding.left + padding.right,
1107            content_size.height + padding.top + padding.bottom,
1108        )
1109    }
1110
1111    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1112        let state = self.state.borrow();
1113        if !state.is_presented() {
1114            drop(state);
1115            self.content
1116                .arrange(ctx, Rect::from_origin_size(bounds.origin, Size::ZERO));
1117            return;
1118        }
1119        let padding = state.theme.metrics.popover_padding;
1120        drop(state);
1121        let content_size = self.content.child().measured_size();
1122        self.content.arrange(
1123            ctx,
1124            Rect::new(
1125                bounds.x() + padding.left,
1126                bounds.y() + padding.top,
1127                content_size.width,
1128                content_size.height,
1129            ),
1130        );
1131    }
1132
1133    fn paint(&self, ctx: &mut PaintCtx) {
1134        let state = self.state.borrow();
1135        if !state.is_presented() {
1136            return;
1137        }
1138
1139        let rect = ctx.bounds();
1140        let metrics = state.theme.metrics;
1141        let visuals = state.resolved_visuals();
1142        // Elevation shadow behind the popover surface, drawn before the fill.
1143        let surface_radius = metrics.corner_radius + 2.0;
1144        paint_theme_shadow(
1145            ctx,
1146            rect,
1147            [surface_radius; 4],
1148            &state.theme.shadows.box_shadow.md,
1149        );
1150        draw_control_frame(
1151            ctx,
1152            rect,
1153            surface_radius,
1154            metrics,
1155            visuals.background,
1156            visuals.border,
1157            None,
1158        );
1159        if let Some(arrival_effect) = visuals.arrival_effect {
1160            draw_popover_arrival_overlay(
1161                ctx,
1162                rect,
1163                metrics,
1164                visuals.background,
1165                visuals.border,
1166                arrival_effect,
1167            );
1168        }
1169        drop(state);
1170        self.content.paint(ctx);
1171    }
1172
1173    fn layer_options(&self) -> LayerOptions {
1174        let presented = self.state.borrow().is_presented();
1175        LayerOptions {
1176            paint_boundary: PaintBoundaryMode::Explicit,
1177            composition_mode: if presented {
1178                LayerCompositionMode::Overlay
1179            } else {
1180                LayerCompositionMode::Normal
1181            },
1182        }
1183    }
1184
1185    fn layer_properties(&self) -> LayerProperties {
1186        self.state.borrow().layer_properties()
1187    }
1188
1189    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
1190        self.state
1191            .borrow()
1192            .is_presented()
1193            .then_some(StackSurfaceOptions {
1194                transient: true,
1195                ..StackSurfaceOptions::default()
1196            })
1197    }
1198
1199    fn semantics(&self, ctx: &mut SemanticsCtx) {
1200        self.content.semantics(ctx);
1201    }
1202
1203    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1204        self.content.visit_children(visitor);
1205    }
1206
1207    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1208        self.content.visit_children_mut(visitor);
1209    }
1210}
1211
1212pub(super) struct PopoverFocusSurface {
1213    pub(super) state: Rc<RefCell<PopoverSurfaceState>>,
1214}
1215
1216impl PopoverFocusSurface {
1217    pub(super) fn new(state: Rc<RefCell<PopoverSurfaceState>>) -> Self {
1218        Self { state }
1219    }
1220}
1221
1222impl Widget for PopoverFocusSurface {
1223    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
1224        let state = self.state.borrow();
1225        if state.is_presented() {
1226            state.frame_rect.size
1227        } else {
1228            Size::ZERO
1229        }
1230    }
1231
1232    fn paint(&self, ctx: &mut PaintCtx) {
1233        let state = self.state.borrow();
1234        if !state.is_presented() || !state.focus_animation.is_presented() {
1235            return;
1236        }
1237
1238        let Some(focus_ring) = state.resolved_visuals().focus_ring else {
1239            return;
1240        };
1241        let progress = state.focus_animation.value;
1242        if progress <= AnimatedScalar::EPSILON {
1243            return;
1244        }
1245
1246        let metrics = state.theme.metrics;
1247        draw_focus_ring_frame(
1248            ctx,
1249            ctx.bounds(),
1250            metrics.corner_radius + 2.0,
1251            metrics,
1252            focus_ring.with_alpha(focus_ring.alpha * progress),
1253        );
1254    }
1255
1256    fn layer_options(&self) -> LayerOptions {
1257        LayerOptions {
1258            paint_boundary: PaintBoundaryMode::Explicit,
1259            composition_mode: LayerCompositionMode::Normal,
1260        }
1261    }
1262
1263    fn layer_properties(&self) -> LayerProperties {
1264        self.state.borrow().layer_properties()
1265    }
1266
1267    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
1268        let state = self.state.borrow();
1269        (state.is_presented() && state.focus_animation.is_presented()).then_some(
1270            StackSurfaceOptions {
1271                transient: true,
1272                hit_test: false,
1273                ..StackSurfaceOptions::default()
1274            },
1275        )
1276    }
1277}
1278
1279#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1280pub enum PopoverAlignment {
1281    #[default]
1282    Start,
1283    End,
1284}
1285
1286pub struct Popover {
1287    pub(super) name: String,
1288    pub(super) trigger: SingleChild,
1289    pub(super) surface: SingleChild,
1290    pub(super) focus_surface: SingleChild,
1291    pub(super) open: bool,
1292    pub(super) open_reader: Option<Box<dyn Fn() -> bool>>,
1293    pub(super) on_open_change: Option<Box<dyn FnMut(bool)>>,
1294    pub(super) alignment: PopoverAlignment,
1295    pub(super) gap: f32,
1296    pub(super) arrival_timer: Option<TimerToken>,
1297    pub(super) state: Rc<RefCell<PopoverSurfaceState>>,
1298}
1299
1300impl Popover {
1301    pub fn new<T, C>(name: impl Into<String>, trigger: T, content: C) -> Self
1302    where
1303        T: Widget + 'static,
1304        C: Widget + 'static,
1305    {
1306        let state = Rc::new(RefCell::new(PopoverSurfaceState::new()));
1307        Self {
1308            name: name.into(),
1309            trigger: SingleChild::new(trigger),
1310            surface: SingleChild::new(PopoverSurface::new(Rc::clone(&state), content)),
1311            focus_surface: SingleChild::new(PopoverFocusSurface::new(Rc::clone(&state))),
1312            open: false,
1313            open_reader: None,
1314            on_open_change: None,
1315            alignment: PopoverAlignment::Start,
1316            gap: DefaultTheme::default().metrics.popover_gap,
1317            arrival_timer: None,
1318            state,
1319        }
1320    }
1321
1322    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1323        self.gap = theme.metrics.popover_gap;
1324        self.state.borrow_mut().theme = theme;
1325        self
1326    }
1327
1328    pub fn open(mut self, open: bool) -> Self {
1329        self.open = open;
1330        self.open_reader = None;
1331        {
1332            let mut state = self.state.borrow_mut();
1333            state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
1334        }
1335        self
1336    }
1337
1338    pub fn open_when<F>(mut self, open: F) -> Self
1339    where
1340        F: Fn() -> bool + 'static,
1341    {
1342        self.open_reader = Some(Box::new(open));
1343        self
1344    }
1345
1346    pub fn on_open_change<F>(mut self, on_open_change: F) -> Self
1347    where
1348        F: FnMut(bool) + 'static,
1349    {
1350        self.on_open_change = Some(Box::new(on_open_change));
1351        self
1352    }
1353
1354    /// Aligns a narrower trigger and surface within the popover's measured
1355    /// width. End alignment keeps title-bar and trailing toolbar triggers
1356    /// anchored while a wider surface opens beneath them.
1357    pub fn alignment(mut self, alignment: PopoverAlignment) -> Self {
1358        self.alignment = alignment;
1359        self
1360    }
1361
1362    pub(super) fn sync_external_open(&mut self) {
1363        let Some(open) = self.open_reader.as_ref().map(|open| open()) else {
1364            return;
1365        };
1366        if self.open == open {
1367            return;
1368        }
1369        self.open = open;
1370        let mut state = self.state.borrow_mut();
1371        state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
1372        state.arrival_active = false;
1373    }
1374
1375    pub(super) fn start_arrival(&mut self, ctx: &mut EventCtx) {
1376        if let Some(token) = self.arrival_timer.take() {
1377            ctx.cancel_timer(token);
1378        }
1379
1380        let mut state = self.state.borrow_mut();
1381        state.arrival_active = !matches!(state.theme.hdr.mode, HdrThemeMode::Disabled)
1382            && state.theme.hdr.effects.pulse.intensity > 0.0;
1383        if state.arrival_active {
1384            self.arrival_timer = Some(ctx.schedule_timer_after(state.arrival_duration()));
1385        }
1386    }
1387
1388    pub(super) fn stop_arrival(&mut self, ctx: &mut EventCtx) {
1389        self.state.borrow_mut().arrival_active = false;
1390        if let Some(token) = self.arrival_timer.take() {
1391            ctx.cancel_timer(token);
1392        }
1393    }
1394
1395    pub(super) fn trigger_rect(&self) -> Rect {
1396        self.trigger.child().bounds()
1397    }
1398
1399    pub(super) fn content_rect(&self) -> Rect {
1400        self.state.borrow().frame_rect
1401    }
1402
1403    pub(super) fn is_inside_open_regions(&self, position: Point) -> bool {
1404        self.trigger_rect().contains(position)
1405            || (self.open && self.content_rect().contains(position))
1406    }
1407
1408    pub(super) fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
1409        if self.open == open {
1410            return;
1411        }
1412
1413        if open {
1414            self.start_arrival(ctx);
1415        } else {
1416            self.stop_arrival(ctx);
1417        }
1418
1419        self.open = open;
1420        if let Some(on_open_change) = &mut self.on_open_change {
1421            on_open_change(open);
1422        }
1423        let surface_id = self.surface.child().id();
1424        let focus_surface_id = self.focus_surface.child().id();
1425        let mut state = self.state.borrow_mut();
1426        let was_presented = state.is_presented();
1427        let motion = state.theme.motion;
1428        let should_animate = state.reveal.set_target(
1429            open as u8 as f32,
1430            ctx.current_time(),
1431            motion.entrance_duration(),
1432            motion.entrance_easing(),
1433        );
1434        let is_presented = state.is_presented();
1435        drop(state);
1436
1437        if open || was_presented != is_presented {
1438            ctx.request_measure();
1439            request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
1440            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
1441        }
1442        if should_animate {
1443            ctx.request_animation_frame();
1444        }
1445        ctx.request_semantics();
1446    }
1447}
1448
1449impl Widget for Popover {
1450    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
1451        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
1452            self.set_open(ctx, false);
1453            ctx.set_handled();
1454        }
1455    }
1456
1457    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1458        match event {
1459            Event::Pointer(pointer)
1460                if pointer.kind == PointerEventKind::Down
1461                    && pointer.button == Some(PointerButton::Primary)
1462                    && self.trigger_rect().contains(pointer.position) =>
1463            {
1464                let next = !self.open;
1465                self.set_open(ctx, next);
1466                ctx.request_focus();
1467                ctx.set_handled();
1468            }
1469            Event::Pointer(pointer)
1470                if pointer.kind == PointerEventKind::Down
1471                    && pointer.button == Some(PointerButton::Primary)
1472                    && self.open
1473                    && !self.is_inside_open_regions(pointer.position) =>
1474            {
1475                self.set_open(ctx, false);
1476            }
1477            Event::Keyboard(key)
1478                if ctx.is_focused()
1479                    && key.state == KeyState::Pressed
1480                    && key.key == "Escape"
1481                    && self.open =>
1482            {
1483                self.set_open(ctx, false);
1484                ctx.set_handled();
1485            }
1486            Event::Keyboard(key)
1487                if ctx.is_focused()
1488                    && key.state == KeyState::Pressed
1489                    && matches!(key.key.as_str(), "Enter" | " ") =>
1490            {
1491                self.set_open(ctx, !self.open);
1492                ctx.set_handled();
1493            }
1494            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
1495                let open = match semantics.action {
1496                    sui_core::SemanticsActionRequest::Expand => Some(true),
1497                    sui_core::SemanticsActionRequest::Collapse => Some(false),
1498                    _ => None,
1499                };
1500                if let Some(open) = open {
1501                    self.set_open(ctx, open);
1502                    ctx.set_handled();
1503                }
1504            }
1505            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1506                let surface_id = self.surface.child().id();
1507                let focus_surface_id = self.focus_surface.child().id();
1508                let mut state = self.state.borrow_mut();
1509                let was_presented = state.is_presented();
1510                let was_focus_presented = state.focus_animation.is_presented();
1511                let previous_reveal = state.reveal.value;
1512                let previous_focus = state.focus_animation.value;
1513                let reveal_animating = state.reveal.advance(*time);
1514                let focus_animating = state.focus_animation.advance(*time);
1515                let reveal_changed = state.reveal.changed_since(previous_reveal);
1516                let focus_changed = state.focus_animation.changed_since(previous_focus);
1517                let is_presented = state.is_presented();
1518                let is_focus_presented = state.focus_animation.is_presented();
1519                drop(state);
1520
1521                if reveal_changed {
1522                    request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
1523                    request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
1524                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
1525                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
1526                }
1527                if focus_changed {
1528                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
1529                }
1530                if was_presented != is_presented {
1531                    ctx.request_measure();
1532                    request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
1533                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
1534                }
1535                if was_focus_presented != is_focus_presented {
1536                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
1537                }
1538                if reveal_animating || focus_animating {
1539                    ctx.request_animation_frame();
1540                }
1541                ctx.set_handled();
1542            }
1543            Event::Wake(WakeEvent::Timer { token, .. }) if self.arrival_timer == Some(*token) => {
1544                self.arrival_timer = None;
1545                let surface_id = self.surface.child().id();
1546                let mut state = self.state.borrow_mut();
1547                if state.arrival_active {
1548                    state.arrival_active = false;
1549                    drop(state);
1550                    request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
1551                } else {
1552                    drop(state);
1553                }
1554                ctx.set_handled();
1555            }
1556            _ => {}
1557        }
1558    }
1559
1560    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1561        self.sync_external_open();
1562        let trigger_size = self.trigger.measure(ctx, constraints.loosen());
1563        // A popover's trigger belongs to its parent's layout, but its surface belongs to the
1564        // window overlay stack. In particular, toolbar and title-bar slots are commonly tight to
1565        // the trigger; reusing those constraints for the surface collapses a wide panel into that
1566        // narrow slot. Measure the overlay against the viewport instead and keep it out of the
1567        // parent's reported size.
1568        let viewport = ctx.dpi().viewport;
1569        let viewport_margin = self.gap.max(4.0);
1570        let surface_max = Size::new(
1571            if viewport.width > 0.0 {
1572                (viewport.width - viewport_margin * 2.0).max(0.0)
1573            } else {
1574                f32::INFINITY
1575            },
1576            if viewport.height > 0.0 {
1577                (viewport.height - viewport_margin * 2.0).max(0.0)
1578            } else {
1579                f32::INFINITY
1580            },
1581        );
1582        let surface_size = self
1583            .surface
1584            .measure(ctx, Constraints::new(Size::ZERO, surface_max));
1585        let presented = self.state.borrow().is_presented();
1586        let focus_size = if presented { surface_size } else { Size::ZERO };
1587        self.focus_surface
1588            .measure(ctx, Constraints::tight(focus_size));
1589        constraints.clamp(trigger_size)
1590    }
1591
1592    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1593        let trigger_size = self.trigger.child().measured_size();
1594        let aligned_x = |width: f32| match self.alignment {
1595            PopoverAlignment::Start => bounds.x(),
1596            PopoverAlignment::End => bounds.max_x() - width,
1597        };
1598        let trigger_bounds = Rect::new(
1599            aligned_x(trigger_size.width),
1600            bounds.y(),
1601            trigger_size.width,
1602            trigger_size.height,
1603        );
1604        self.trigger.arrange(ctx, trigger_bounds);
1605
1606        let presented = self.state.borrow().is_presented();
1607        let surface_bounds = if presented {
1608            let surface_size = self.surface.child().measured_size();
1609            let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
1610            let margin = self.gap.max(4.0);
1611            let width = surface_size.width.max(trigger_size.width);
1612            let alignment = match self.alignment {
1613                PopoverAlignment::Start => OverlayAlignment::Start,
1614                PopoverAlignment::End => OverlayAlignment::End,
1615            };
1616            place_overlay(
1617                &OverlayPlacementRequest::new(
1618                    trigger_bounds,
1619                    Size::new(width, surface_size.height),
1620                    viewport,
1621                    OverlayPlacement::new(OverlaySide::Bottom, alignment),
1622                )
1623                .fallbacks([OverlayPlacement::new(OverlaySide::Top, alignment)])
1624                .gap(self.gap)
1625                .margin(margin),
1626            )
1627            .bounds
1628        } else {
1629            Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
1630        };
1631        self.state.borrow_mut().frame_rect = surface_bounds;
1632        self.surface.arrange(ctx, surface_bounds);
1633        self.focus_surface.arrange(ctx, surface_bounds);
1634    }
1635
1636    fn paint(&self, ctx: &mut PaintCtx) {
1637        self.trigger.paint(ctx);
1638        if self.state.borrow().is_presented() {
1639            self.surface.paint(ctx);
1640            self.focus_surface.paint(ctx);
1641        }
1642    }
1643
1644    fn semantics(&self, ctx: &mut SemanticsCtx) {
1645        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Popover, ctx.bounds());
1646        node.name = Some(self.name.clone());
1647        node.state.focused = ctx.is_focused();
1648        node.state.expanded = Some(self.open);
1649        node.popup = Some(SemanticsPopupKind::Dialog);
1650        node.actions = vec![
1651            SemanticsAction::Focus,
1652            SemanticsAction::Expand,
1653            SemanticsAction::Collapse,
1654        ];
1655        ctx.push(node);
1656        self.trigger.semantics(ctx);
1657        if self.open {
1658            self.surface.semantics(ctx);
1659        }
1660    }
1661
1662    fn accepts_focus(&self) -> bool {
1663        true
1664    }
1665
1666    fn overlay_options(&self) -> Option<OverlayOptions> {
1667        (self.open || self.state.borrow().is_presented()).then_some(
1668            OverlayOptions::new(OverlayKind::Popover)
1669                .dismiss(if self.open {
1670                    OverlayDismissPolicy::TRANSIENT
1671                } else {
1672                    OverlayDismissPolicy::NONE
1673                })
1674                .focus(OverlayFocusBehavior::NONE),
1675        )
1676    }
1677
1678    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1679        let focus_surface_id = self.focus_surface.child().id();
1680        let mut state = self.state.borrow_mut();
1681        let was_focus_presented = state.focus_animation.is_presented();
1682        let theme = state.theme;
1683        set_focus_animation_target(
1684            &mut state.focus_animation,
1685            focused as u8 as f32,
1686            &theme,
1687            ctx,
1688        );
1689        let is_focus_presented = state.focus_animation.is_presented();
1690        drop(state);
1691
1692        if was_focus_presented != is_focus_presented {
1693            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
1694        }
1695        request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
1696        if !focused && self.open {
1697            self.set_open(ctx, false);
1698        }
1699        ctx.request_semantics();
1700    }
1701
1702    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1703        self.trigger.visit_children(visitor);
1704        if self.open || self.state.borrow().is_presented() {
1705            self.surface.visit_children(visitor);
1706            self.focus_surface.visit_children(visitor);
1707        }
1708    }
1709
1710    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1711        self.trigger.visit_children_mut(visitor);
1712        if self.open || self.state.borrow().is_presented() {
1713            self.surface.visit_children_mut(visitor);
1714            self.focus_surface.visit_children_mut(visitor);
1715        }
1716    }
1717}
1718
1719#[derive(Debug, Clone)]
1720pub(super) struct ContextMenuPanel {
1721    pub(super) prefix: Vec<usize>,
1722    pub(super) items: Vec<MenuItem>,
1723    pub(super) frame_rect: Rect,
1724    pub(super) opens_left: bool,
1725}
1726
1727impl ContextMenuPanel {
1728    pub(super) fn item_rect(
1729        &self,
1730        theme: &DefaultTheme,
1731        row_height: f32,
1732        index: usize,
1733    ) -> Option<Rect> {
1734        if index >= self.items.len() {
1735            return None;
1736        }
1737        let padding = theme.metrics.menu_padding;
1738        Some(Rect::new(
1739            self.frame_rect.x() + padding.left,
1740            self.frame_rect.y() + padding.top + (index as f32 * row_height),
1741            (self.frame_rect.width() - padding.left - padding.right).max(0.0),
1742            row_height,
1743        ))
1744    }
1745}
1746
1747#[derive(Debug, Clone)]
1748pub(super) struct ContextMenuPresentationState {
1749    pub(super) theme: DefaultTheme,
1750    pub(super) panels: Vec<ContextMenuPanel>,
1751    pub(super) highlighted: Option<Vec<usize>>,
1752    pub(super) highlight_visual: Option<Vec<usize>>,
1753    pub(super) pressed: Option<Vec<usize>>,
1754    pub(super) press_visual: Option<Vec<usize>>,
1755    pub(super) surface_rect: Rect,
1756    pub(super) row_height: f32,
1757    pub(super) reveal: AnimatedScalar,
1758    pub(super) focus_animation: AnimatedScalar,
1759    pub(super) highlight_animation: AnimatedScalar,
1760    pub(super) press_animation: AnimatedScalar,
1761}
1762
1763impl ContextMenuPresentationState {
1764    pub(super) fn new() -> Self {
1765        let theme = DefaultTheme::default();
1766        Self {
1767            theme,
1768            panels: Vec::new(),
1769            highlighted: None,
1770            highlight_visual: None,
1771            pressed: None,
1772            press_visual: None,
1773            surface_rect: Rect::ZERO,
1774            row_height: menu_row_height(&theme),
1775            reveal: AnimatedScalar::new(0.0),
1776            focus_animation: AnimatedScalar::new(0.0),
1777            highlight_animation: AnimatedScalar::new(0.0),
1778            press_animation: AnimatedScalar::new(0.0),
1779        }
1780    }
1781
1782    pub(super) fn is_presented(&self) -> bool {
1783        self.reveal.is_presented()
1784    }
1785
1786    pub(super) fn item_rect(&self, panel: usize, index: usize) -> Option<Rect> {
1787        self.panels
1788            .get(panel)?
1789            .item_rect(&self.theme, self.row_height, index)
1790    }
1791
1792    pub(super) fn layer_properties(&self) -> LayerProperties {
1793        LayerProperties {
1794            opacity: self.reveal.value,
1795            translation: Vector::new(
1796                0.0,
1797                -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
1798            ),
1799        }
1800    }
1801
1802    pub(super) fn highlight_amount_for(&self, path: &[usize]) -> f32 {
1803        if self.highlight_visual.as_deref() == Some(path) {
1804            self.highlight_animation.value
1805        } else {
1806            0.0
1807        }
1808    }
1809
1810    pub(super) fn press_amount_for(&self, path: &[usize]) -> f32 {
1811        if self.press_visual.as_deref() == Some(path) {
1812            self.press_animation.value
1813        } else {
1814            0.0
1815        }
1816    }
1817}
1818
1819pub(super) struct ContextMenuSurface {
1820    pub(super) state: Rc<RefCell<ContextMenuPresentationState>>,
1821}
1822
1823impl ContextMenuSurface {
1824    pub(super) fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
1825        Self { state }
1826    }
1827}
1828
1829impl Widget for ContextMenuSurface {
1830    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
1831        let state = self.state.borrow();
1832        if state.is_presented() {
1833            state.surface_rect.size
1834        } else {
1835            Size::ZERO
1836        }
1837    }
1838
1839    fn paint(&self, ctx: &mut PaintCtx) {
1840        let state = self.state.borrow();
1841        if !state.is_presented() {
1842            return;
1843        }
1844
1845        let theme = state.theme;
1846        let metrics = theme.metrics;
1847        let palette = theme.palette;
1848        let interaction = theme.interaction;
1849        let item_padding = metrics.menu_item_padding;
1850        let surface_radius = metrics.corner_radius + 2.0;
1851        let submenu_width = menu_submenu_indicator_width(&theme);
1852
1853        for (panel_index, panel) in state.panels.iter().enumerate() {
1854            let menu = panel.frame_rect;
1855            paint_theme_shadow(ctx, menu, [surface_radius; 4], &theme.shadows.box_shadow.lg);
1856            draw_control_frame(
1857                ctx,
1858                menu,
1859                surface_radius,
1860                metrics,
1861                palette.surface_raised,
1862                palette.border,
1863                None,
1864            );
1865
1866            for (index, item) in panel.items.iter().enumerate() {
1867                let Some(row) = state.item_rect(panel_index, index) else {
1868                    continue;
1869                };
1870                let mut path = panel.prefix.clone();
1871                path.push(index);
1872
1873                if item.separator_before {
1874                    let line = Rect::new(
1875                        row.x(),
1876                        row.y() - (metrics.menu_padding.top * 0.5),
1877                        row.width(),
1878                        1.0,
1879                    );
1880                    ctx.fill(rounded_rect_path(line, 0.5), palette.border);
1881                }
1882
1883                let highlighted = state.highlighted.as_deref() == Some(path.as_slice());
1884                let highlight_amount = state.highlight_amount_for(&path);
1885                let press_amount = state.press_amount_for(&path);
1886                let label_style = theme.text_style(item.text_color(&theme));
1887                let shortcut_width = item
1888                    .shortcut
1889                    .as_ref()
1890                    .map(|_| metrics.menu_shortcut_width)
1891                    .unwrap_or(0.0);
1892                let indicator_width = if item.has_submenu() {
1893                    submenu_width
1894                } else {
1895                    0.0
1896                };
1897                let label_slot = Rect::new(
1898                    row.x() + item_padding.left,
1899                    row.y(),
1900                    (row.width()
1901                        - item_padding.left
1902                        - item_padding.right
1903                        - shortcut_width
1904                        - indicator_width)
1905                        .max(0.0),
1906                    row.height(),
1907                );
1908                if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
1909                    let highlight_background =
1910                        mix_color(palette.control, palette.selection, highlight_amount);
1911                    let background = if press_amount > 0.0 {
1912                        mix_color(
1913                            highlight_background,
1914                            palette.control_active,
1915                            interaction.pressed_blend * press_amount,
1916                        )
1917                    } else {
1918                        highlight_background
1919                    };
1920                    ctx.fill(
1921                        rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
1922                        background,
1923                    );
1924                }
1925
1926                ctx.push_clip_rect(label_slot);
1927                paint_aligned_text(
1928                    ctx,
1929                    label_slot,
1930                    &item.label,
1931                    &label_style,
1932                    label_style.line_height,
1933                    0.0,
1934                );
1935                ctx.pop_clip();
1936
1937                if let Some(shortcut) = &item.shortcut {
1938                    let shortcut_style = theme.placeholder_text_style();
1939                    let shortcut_slot = Rect::new(
1940                        row.max_x()
1941                            - item_padding.right
1942                            - indicator_width
1943                            - metrics.menu_shortcut_width,
1944                        row.y(),
1945                        metrics.menu_shortcut_width,
1946                        row.height(),
1947                    );
1948                    ctx.push_clip_rect(shortcut_slot);
1949                    paint_aligned_text(
1950                        ctx,
1951                        shortcut_slot,
1952                        shortcut,
1953                        &shortcut_style,
1954                        shortcut_style.line_height,
1955                        1.0,
1956                    );
1957                    ctx.pop_clip();
1958                }
1959
1960                if item.has_submenu() {
1961                    let indicator_style = theme.text_style(item.text_color(&theme));
1962                    let indicator_slot = Rect::new(
1963                        row.max_x() - item_padding.right - indicator_width,
1964                        row.y(),
1965                        indicator_width,
1966                        row.height(),
1967                    );
1968                    ctx.push_clip_rect(indicator_slot);
1969                    paint_aligned_text(
1970                        ctx,
1971                        indicator_slot,
1972                        "\u{203a}",
1973                        &indicator_style,
1974                        indicator_style.line_height,
1975                        1.0,
1976                    );
1977                    ctx.pop_clip();
1978                }
1979            }
1980        }
1981    }
1982
1983    fn layer_options(&self) -> LayerOptions {
1984        let presented = self.state.borrow().is_presented();
1985        LayerOptions {
1986            paint_boundary: PaintBoundaryMode::Explicit,
1987            composition_mode: if presented {
1988                LayerCompositionMode::Overlay
1989            } else {
1990                LayerCompositionMode::Normal
1991            },
1992        }
1993    }
1994
1995    fn layer_properties(&self) -> LayerProperties {
1996        self.state.borrow().layer_properties()
1997    }
1998
1999    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
2000        self.state
2001            .borrow()
2002            .is_presented()
2003            .then_some(StackSurfaceOptions {
2004                transient: true,
2005                ..StackSurfaceOptions::default()
2006            })
2007    }
2008}
2009
2010pub(super) struct ContextMenuFocusSurface {
2011    pub(super) state: Rc<RefCell<ContextMenuPresentationState>>,
2012}
2013
2014impl ContextMenuFocusSurface {
2015    pub(super) fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
2016        Self { state }
2017    }
2018}
2019
2020impl Widget for ContextMenuFocusSurface {
2021    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
2022        let state = self.state.borrow();
2023        if state.is_presented() {
2024            state.surface_rect.size
2025        } else {
2026            Size::ZERO
2027        }
2028    }
2029
2030    fn paint(&self, ctx: &mut PaintCtx) {
2031        let state = self.state.borrow();
2032        if !state.is_presented() || !state.focus_animation.is_presented() {
2033            return;
2034        }
2035
2036        let progress = state.focus_animation.value;
2037        if progress <= AnimatedScalar::EPSILON {
2038            return;
2039        }
2040
2041        let metrics = state.theme.metrics;
2042        let palette = state.theme.palette;
2043        for panel in &state.panels {
2044            draw_focus_ring_frame(
2045                ctx,
2046                panel.frame_rect,
2047                metrics.corner_radius + 2.0,
2048                metrics,
2049                palette
2050                    .focus_ring
2051                    .with_alpha(palette.focus_ring.alpha * progress),
2052            );
2053        }
2054    }
2055
2056    fn layer_options(&self) -> LayerOptions {
2057        LayerOptions {
2058            paint_boundary: PaintBoundaryMode::Explicit,
2059            composition_mode: LayerCompositionMode::Normal,
2060        }
2061    }
2062
2063    fn layer_properties(&self) -> LayerProperties {
2064        self.state.borrow().layer_properties()
2065    }
2066
2067    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
2068        let state = self.state.borrow();
2069        (state.is_presented() && state.focus_animation.is_presented()).then_some(
2070            StackSurfaceOptions {
2071                transient: true,
2072                hit_test: false,
2073                ..StackSurfaceOptions::default()
2074            },
2075        )
2076    }
2077}
2078
2079pub struct ContextMenu {
2080    pub(super) theme: Box<DefaultTheme>,
2081    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2082    pub(super) name: String,
2083    pub(super) trigger: SingleChild,
2084    pub(super) items: Vec<MenuItem>,
2085    pub(super) items_provider: Option<Box<dyn Fn() -> Vec<MenuItem>>>,
2086    pub(super) open: bool,
2087    pub(super) open_path: Vec<usize>,
2088    pub(super) highlighted: Option<Vec<usize>>,
2089    pub(super) highlight_visual: Option<Vec<usize>>,
2090    pub(super) pressed: Option<Vec<usize>>,
2091    pub(super) press_visual: Option<Vec<usize>>,
2092    pub(super) highlight_animation: AnimatedScalar,
2093    pub(super) press_animation: AnimatedScalar,
2094    pub(super) panels: Vec<ContextMenuPanel>,
2095    pub(super) surface: SingleChild,
2096    pub(super) focus_surface: SingleChild,
2097    pub(super) surface_state: Rc<RefCell<ContextMenuPresentationState>>,
2098    pub(super) activation_button: PointerButton,
2099    pub(super) primary_trigger_press: Option<u64>,
2100    pub(super) anchor_to_pointer: Option<bool>,
2101    pub(super) open_position: Option<Point>,
2102    pub(super) on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
2103    pub(super) on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
2104    pub(super) on_activate_path: Option<Box<dyn FnMut(Vec<usize>, MenuItem)>>,
2105    pub(super) on_activate_path_with_ctx:
2106        Option<Box<dyn FnMut(&mut EventCtx, Vec<usize>, MenuItem)>>,
2107}
2108
2109impl ContextMenu {
2110    pub fn new<W>(name: impl Into<String>, trigger: W) -> Self
2111    where
2112        W: Widget + 'static,
2113    {
2114        let surface_state = Rc::new(RefCell::new(ContextMenuPresentationState::new()));
2115        Self {
2116            theme: Box::new(DefaultTheme::default()),
2117            theme_reader: None,
2118            name: name.into(),
2119            trigger: SingleChild::new(trigger),
2120            items: Vec::new(),
2121            items_provider: None,
2122            open: false,
2123            open_path: Vec::new(),
2124            highlighted: None,
2125            highlight_visual: None,
2126            pressed: None,
2127            press_visual: None,
2128            highlight_animation: AnimatedScalar::new(0.0),
2129            press_animation: AnimatedScalar::new(0.0),
2130            panels: Vec::new(),
2131            surface: SingleChild::new(ContextMenuSurface::new(Rc::clone(&surface_state))),
2132            focus_surface: SingleChild::new(ContextMenuFocusSurface::new(Rc::clone(
2133                &surface_state,
2134            ))),
2135            surface_state,
2136            activation_button: PointerButton::Secondary,
2137            primary_trigger_press: None,
2138            anchor_to_pointer: None,
2139            open_position: None,
2140            on_activate: None,
2141            on_activate_with_ctx: None,
2142            on_activate_path: None,
2143            on_activate_path_with_ctx: None,
2144        }
2145    }
2146
2147    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2148        self.theme = Box::new(theme);
2149        self.theme_reader = None;
2150        self
2151    }
2152
2153    pub fn theme_when<F>(mut self, theme: F) -> Self
2154    where
2155        F: Fn() -> DefaultTheme + 'static,
2156    {
2157        self.theme_reader = Some(Box::new(theme));
2158        self
2159    }
2160
2161    pub fn item(mut self, item: MenuItem) -> Self {
2162        self.items.push(item);
2163        self
2164    }
2165
2166    pub fn items<I>(mut self, items: I) -> Self
2167    where
2168        I: IntoIterator<Item = MenuItem>,
2169    {
2170        self.items.extend(items);
2171        self
2172    }
2173
2174    /// Rebuild the item list every time the menu opens, so per-item enabled
2175    /// state can reflect current application state (selection, clipboard, …).
2176    pub fn items_when<F>(mut self, provider: F) -> Self
2177    where
2178        F: Fn() -> Vec<MenuItem> + 'static,
2179    {
2180        self.items_provider = Some(Box::new(provider));
2181        self
2182    }
2183
2184    /// Widget id of the wrapped trigger. Menu activations can route commands
2185    /// back to it via `EventCtx::post_event` — for example the standard text
2186    /// editing commands (`TextCommand`) understood by the text widgets.
2187    pub fn trigger_id(&self) -> WidgetId {
2188        self.trigger.child().id()
2189    }
2190
2191    /// Handle leaf activation.
2192    ///
2193    /// Flat menus receive the activated item index as before. A nested leaf
2194    /// receives the index of its root submenu owner; use
2195    /// [`Self::on_activate_path`] when the complete path is significant.
2196    pub fn on_activate<F>(mut self, on_activate: F) -> Self
2197    where
2198        F: FnMut(usize, MenuItem) + 'static,
2199    {
2200        self.on_activate = Some(Box::new(on_activate));
2201        self
2202    }
2203
2204    /// Event-context variant of [`Self::on_activate`].
2205    pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
2206    where
2207        F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
2208    {
2209        self.on_activate_with_ctx = Some(Box::new(on_activate));
2210        self
2211    }
2212
2213    /// Handle leaf activation with the complete index path from the root item
2214    /// to the activated nested item.
2215    pub fn on_activate_path<F>(mut self, on_activate: F) -> Self
2216    where
2217        F: FnMut(Vec<usize>, MenuItem) + 'static,
2218    {
2219        self.on_activate_path = Some(Box::new(on_activate));
2220        self
2221    }
2222
2223    /// Handle leaf activation with event context and its complete nested index
2224    /// path.
2225    pub fn on_activate_path_with_ctx<F>(mut self, on_activate: F) -> Self
2226    where
2227        F: FnMut(&mut EventCtx, Vec<usize>, MenuItem) + 'static,
2228    {
2229        self.on_activate_path_with_ctx = Some(Box::new(on_activate));
2230        self
2231    }
2232
2233    /// Set the pointer button that opens the menu.
2234    ///
2235    /// Primary activation owns the trigger click during capture, so an
2236    /// interactive trigger such as [`crate::Button`] does not consume or also
2237    /// execute the click. Secondary activation remains in target/bubble order
2238    /// so context-menu triggers can update their targeted row before opening.
2239    pub fn activation_button(mut self, activation_button: PointerButton) -> Self {
2240        self.activation_button = activation_button;
2241        self
2242    }
2243
2244    /// Whether the menu opens at the press position instead of dropping below
2245    /// the trigger. Defaults by activation button: right-click menus anchor to
2246    /// the pointer (standard context-menu behavior, and the only sensible
2247    /// placement for large triggers), other buttons keep the dropdown layout.
2248    pub fn anchor_to_pointer(mut self, anchor_to_pointer: bool) -> Self {
2249        self.anchor_to_pointer = Some(anchor_to_pointer);
2250        self
2251    }
2252
2253    pub(super) fn anchors_to_pointer(&self) -> bool {
2254        self.anchor_to_pointer
2255            .unwrap_or(self.activation_button == PointerButton::Secondary)
2256    }
2257
2258    pub(super) fn row_height(&self) -> f32 {
2259        menu_row_height(&self.resolved_theme())
2260    }
2261
2262    pub(super) fn measured_menu_width_for_items(
2263        &self,
2264        ctx: &mut MeasureCtx,
2265        items: &[MenuItem],
2266    ) -> f32 {
2267        let theme = self.resolved_theme();
2268        let label_style = theme.body_text_style();
2269        let shortcut_style = theme.placeholder_text_style();
2270        let mut width: f32 = 220.0;
2271        for item in items {
2272            let label = measure_text(ctx, item.label(), &label_style).width;
2273            let shortcut = item
2274                .shortcut
2275                .as_ref()
2276                .map(|text| measure_text(ctx, text, &shortcut_style).width)
2277                .unwrap_or(0.0);
2278            width = width.max(
2279                label
2280                    + shortcut
2281                    + theme.metrics.menu_item_padding.left
2282                    + theme.metrics.menu_item_padding.right
2283                    + theme.metrics.menu_shortcut_width
2284                    + if item.has_submenu() {
2285                        menu_submenu_indicator_width(&theme)
2286                    } else {
2287                        0.0
2288                    },
2289            );
2290        }
2291        width
2292    }
2293
2294    pub(super) fn resolved_theme(&self) -> DefaultTheme {
2295        self.theme_reader
2296            .as_ref()
2297            .map(|theme| theme())
2298            .unwrap_or(*self.theme)
2299    }
2300
2301    pub(super) fn trigger_rect(&self) -> Rect {
2302        self.trigger.child().bounds()
2303    }
2304
2305    pub(super) fn items_at_prefix(&self, prefix: &[usize]) -> Option<&[MenuItem]> {
2306        let mut items = self.items.as_slice();
2307        for index in prefix {
2308            items = items.get(*index)?.submenu_items();
2309        }
2310        Some(items)
2311    }
2312
2313    pub(super) fn item_at_path(&self, path: &[usize]) -> Option<&MenuItem> {
2314        let (&index, prefix) = path.split_last()?;
2315        self.items_at_prefix(prefix)?.get(index)
2316    }
2317
2318    pub(super) fn item_rect(&self, bounds: Rect, path: &[usize]) -> Option<Rect> {
2319        if !self.open {
2320            return None;
2321        }
2322        let (&index, prefix) = path.split_last()?;
2323        let panel = self.panels.get(prefix.len())?;
2324        if panel.prefix != prefix {
2325            return None;
2326        }
2327        let theme = self.resolved_theme();
2328        panel
2329            .item_rect(&theme, self.row_height(), index)
2330            .map(|rect| rect.translate(bounds.origin.to_vector()))
2331    }
2332
2333    pub(super) fn item_at(&self, bounds: Rect, position: Point) -> Option<Vec<usize>> {
2334        self.panels.iter().rev().find_map(|panel| {
2335            panel.items.iter().enumerate().find_map(|(index, _)| {
2336                let mut path = panel.prefix.clone();
2337                path.push(index);
2338                self.item_rect(bounds, &path)
2339                    .filter(|rect| rect.contains(position))
2340                    .map(|_| path)
2341            })
2342        })
2343    }
2344
2345    pub(super) fn surface_rect(&self) -> Rect {
2346        self.panels
2347            .iter()
2348            .map(|panel| panel.frame_rect)
2349            .reduce(Rect::union)
2350            .unwrap_or(Rect::ZERO)
2351    }
2352
2353    pub(super) fn sync_surface_state(&self, bounds: Rect) {
2354        let theme = self.resolved_theme();
2355        let translation = bounds.origin.to_vector();
2356        let mut state = self.surface_state.borrow_mut();
2357        state.theme = theme;
2358        state.panels = self
2359            .panels
2360            .iter()
2361            .cloned()
2362            .map(|mut panel| {
2363                panel.frame_rect = panel.frame_rect.translate(translation);
2364                panel
2365            })
2366            .collect();
2367        state.highlighted = self.highlighted.clone();
2368        state.highlight_visual = self.highlight_visual.clone();
2369        state.pressed = self.pressed.clone();
2370        state.press_visual = self.press_visual.clone();
2371        state.highlight_animation = self.highlight_animation;
2372        state.press_animation = self.press_animation;
2373        state.surface_rect = self.surface_rect().translate(translation);
2374        state.row_height = self.row_height();
2375    }
2376
2377    pub(super) fn refresh_surface_interaction_state(&self, ctx: &mut EventCtx) {
2378        let surface_id = self.surface.child().id();
2379        let mut state = self.surface_state.borrow_mut();
2380        let changed = state.highlighted != self.highlighted
2381            || state.highlight_visual != self.highlight_visual
2382            || state.pressed != self.pressed
2383            || state.press_visual != self.press_visual
2384            || state.highlight_animation != self.highlight_animation
2385            || state.press_animation != self.press_animation;
2386        state.highlighted = self.highlighted.clone();
2387        state.highlight_visual = self.highlight_visual.clone();
2388        state.pressed = self.pressed.clone();
2389        state.press_visual = self.press_visual.clone();
2390        state.highlight_animation = self.highlight_animation;
2391        state.press_animation = self.press_animation;
2392        let presented = state.is_presented();
2393        drop(state);
2394
2395        if changed && presented {
2396            request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
2397        }
2398    }
2399
2400    pub(super) fn set_highlighted(&mut self, highlighted: Option<Vec<usize>>, ctx: &mut EventCtx) {
2401        if self.highlighted == highlighted {
2402            return;
2403        }
2404        let theme = self.resolved_theme();
2405        self.highlighted = highlighted.clone();
2406        if let Some(path) = highlighted {
2407            self.highlight_visual = Some(path);
2408            self.highlight_animation = AnimatedScalar::new(0.0);
2409            set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
2410        } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
2411            self.highlight_visual = None;
2412        }
2413        self.refresh_surface_interaction_state(ctx);
2414        ctx.request_paint();
2415        ctx.request_semantics();
2416    }
2417
2418    pub(super) fn set_pressed(&mut self, pressed: Option<Vec<usize>>, ctx: &mut EventCtx) {
2419        if self.pressed == pressed {
2420            return;
2421        }
2422        let theme = self.resolved_theme();
2423        self.pressed = pressed.clone();
2424        if let Some(path) = pressed {
2425            self.press_visual = Some(path);
2426            self.press_animation = AnimatedScalar::new(0.0);
2427            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
2428        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
2429            self.press_visual = None;
2430        }
2431        self.refresh_surface_interaction_state(ctx);
2432        ctx.request_paint();
2433        ctx.request_semantics();
2434    }
2435
2436    pub(super) fn advance_row_animations(&mut self, time: f64) -> bool {
2437        let highlight_animating = self.highlight_animation.advance(time);
2438        if !highlight_animating
2439            && self.highlighted.is_none()
2440            && self.highlight_animation.value <= AnimatedScalar::EPSILON
2441        {
2442            self.highlight_visual = None;
2443        }
2444
2445        let press_animating = self.press_animation.advance(time);
2446        if !press_animating
2447            && self.pressed.is_none()
2448            && self.press_animation.value <= AnimatedScalar::EPSILON
2449        {
2450            self.press_visual = None;
2451        }
2452
2453        highlight_animating | press_animating
2454    }
2455
2456    pub(super) fn set_open_path(&mut self, ctx: &mut EventCtx, open_path: Vec<usize>) {
2457        if self.open_path == open_path {
2458            return;
2459        }
2460        self.open_path = open_path;
2461        ctx.request_measure();
2462        ctx.request_paint();
2463        ctx.request_semantics();
2464    }
2465
2466    pub(super) fn update_pointer_highlight(
2467        &mut self,
2468        ctx: &mut EventCtx,
2469        highlighted: Option<Vec<usize>>,
2470    ) {
2471        if let Some(path) = highlighted {
2472            let opens_submenu = self
2473                .item_at_path(&path)
2474                .is_some_and(|item| item.enabled && item.has_submenu());
2475            let open_path = if opens_submenu {
2476                path.clone()
2477            } else {
2478                path[..path.len().saturating_sub(1)].to_vec()
2479            };
2480            self.set_open_path(ctx, open_path);
2481            self.set_highlighted(Some(path), ctx);
2482        } else {
2483            self.set_highlighted(None, ctx);
2484        }
2485    }
2486
2487    pub(super) fn open_highlighted_submenu(&mut self, ctx: &mut EventCtx) -> bool {
2488        let Some(path) = self.highlighted.clone() else {
2489            return false;
2490        };
2491        let first_enabled = self.item_at_path(&path).and_then(|item| {
2492            item.enabled
2493                .then(|| item.submenu_items().iter().position(|child| child.enabled))
2494                .flatten()
2495        });
2496        if self
2497            .item_at_path(&path)
2498            .is_none_or(|item| !item.enabled || !item.has_submenu())
2499        {
2500            return false;
2501        }
2502        self.set_open_path(ctx, path.clone());
2503        if let Some(index) = first_enabled {
2504            let mut child = path;
2505            child.push(index);
2506            self.set_highlighted(Some(child), ctx);
2507        }
2508        true
2509    }
2510
2511    pub(super) fn close_current_submenu(&mut self, ctx: &mut EventCtx) -> bool {
2512        let Some(path) = self.highlighted.clone() else {
2513            return false;
2514        };
2515        if path.len() > 1 {
2516            let owner = path[..path.len() - 1].to_vec();
2517            let parent_open_path = owner[..owner.len().saturating_sub(1)].to_vec();
2518            self.set_open_path(ctx, parent_open_path);
2519            self.set_highlighted(Some(owner), ctx);
2520            true
2521        } else if self.open_path == path {
2522            self.set_open_path(ctx, Vec::new());
2523            true
2524        } else {
2525            false
2526        }
2527    }
2528
2529    pub(super) fn move_highlight(&mut self, delta: isize, ctx: &mut EventCtx) {
2530        let prefix = self
2531            .highlighted
2532            .as_deref()
2533            .map(|path| &path[..path.len().saturating_sub(1)])
2534            .unwrap_or(&[])
2535            .to_vec();
2536        let Some(items) = self.items_at_prefix(&prefix) else {
2537            return;
2538        };
2539        if items.is_empty() {
2540            return;
2541        }
2542        let current = self
2543            .highlighted
2544            .as_deref()
2545            .and_then(|path| path.last().copied());
2546        let len = items.len() as isize;
2547        let mut index = current.map_or(if delta > 0 { -1 } else { len }, |index| index as isize);
2548        loop {
2549            let next = (index + delta).clamp(0, len - 1);
2550            if next == index {
2551                return;
2552            }
2553            index = next;
2554            if items[index as usize].enabled {
2555                break;
2556            }
2557        }
2558        let mut path = prefix.clone();
2559        path.push(index as usize);
2560        self.set_open_path(ctx, prefix);
2561        self.set_highlighted(Some(path), ctx);
2562    }
2563
2564    pub(super) fn move_highlight_to_edge(&mut self, first: bool, ctx: &mut EventCtx) {
2565        let prefix = self
2566            .highlighted
2567            .as_deref()
2568            .map(|path| &path[..path.len().saturating_sub(1)])
2569            .unwrap_or(&[])
2570            .to_vec();
2571        let Some(items) = self.items_at_prefix(&prefix) else {
2572            return;
2573        };
2574        let index = if first {
2575            items.iter().position(|item| item.enabled)
2576        } else {
2577            items.iter().rposition(|item| item.enabled)
2578        };
2579        if let Some(index) = index {
2580            let mut path = prefix.clone();
2581            path.push(index);
2582            self.set_open_path(ctx, prefix);
2583            self.set_highlighted(Some(path), ctx);
2584        }
2585    }
2586
2587    pub(super) fn visible_path_for_semantics_id(
2588        &self,
2589        root: WidgetId,
2590        target: WidgetId,
2591    ) -> Option<Vec<usize>> {
2592        self.panels.iter().find_map(|panel| {
2593            panel.items.iter().enumerate().find_map(|(index, _)| {
2594                let mut path = panel.prefix.clone();
2595                path.push(index);
2596                (virtual_menu_item_path_id(root, &path) == target).then_some(path)
2597            })
2598        })
2599    }
2600
2601    pub(super) fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
2602        if self.open == open {
2603            return;
2604        }
2605
2606        if open && let Some(provider) = &self.items_provider {
2607            self.items = provider();
2608        }
2609        if !open {
2610            self.open_position = None;
2611        }
2612
2613        self.open = open;
2614        self.open_path.clear();
2615        self.highlighted = if open {
2616            self.items
2617                .iter()
2618                .position(|item| item.enabled)
2619                .map(|index| vec![index])
2620        } else {
2621            None
2622        };
2623        self.highlight_visual = self.highlighted.clone();
2624        self.highlight_animation = AnimatedScalar::new(self.highlighted.is_some() as u8 as f32);
2625        self.pressed = None;
2626        self.press_visual = None;
2627        self.press_animation = AnimatedScalar::new(0.0);
2628        self.panels.clear();
2629
2630        let surface_id = self.surface.child().id();
2631        let focus_surface_id = self.focus_surface.child().id();
2632        let theme = self.resolved_theme();
2633        let mut state = self.surface_state.borrow_mut();
2634        state.theme = theme;
2635        state.panels.clear();
2636        state.highlighted = self.highlighted.clone();
2637        state.highlight_visual = self.highlight_visual.clone();
2638        state.pressed = self.pressed.clone();
2639        state.press_visual = self.press_visual.clone();
2640        state.highlight_animation = self.highlight_animation;
2641        state.press_animation = self.press_animation;
2642        let was_presented = state.is_presented();
2643        let should_animate = if open {
2644            let motion = theme.motion;
2645            state.reveal.set_target(
2646                1.0,
2647                ctx.current_time(),
2648                motion.entrance_duration(),
2649                motion.entrance_easing(),
2650            )
2651        } else {
2652            state.reveal = AnimatedScalar::new(0.0);
2653            false
2654        };
2655        let is_presented = state.is_presented();
2656        drop(state);
2657
2658        if open || was_presented != is_presented {
2659            ctx.request_measure();
2660            request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
2661            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
2662        }
2663        if should_animate {
2664            ctx.request_animation_frame();
2665        }
2666        ctx.request_paint();
2667        ctx.request_semantics();
2668    }
2669
2670    pub(super) fn activate_path(&mut self, ctx: &mut EventCtx, path: Vec<usize>) {
2671        let Some(item) = self.item_at_path(&path).cloned() else {
2672            return;
2673        };
2674        if !item.enabled || item.has_submenu() {
2675            return;
2676        }
2677        let Some(root_index) = path.first().copied() else {
2678            return;
2679        };
2680        if let Some(on_activate) = &mut self.on_activate {
2681            on_activate(root_index, item.clone());
2682        }
2683        if let Some(on_activate) = &mut self.on_activate_with_ctx {
2684            on_activate(ctx, root_index, item.clone());
2685        }
2686        if let Some(on_activate) = &mut self.on_activate_path {
2687            on_activate(path.clone(), item.clone());
2688        }
2689        if let Some(on_activate) = &mut self.on_activate_path_with_ctx {
2690            on_activate(ctx, path, item);
2691        }
2692    }
2693}
2694
2695impl Widget for ContextMenu {
2696    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
2697        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
2698            self.set_open(ctx, false);
2699            ctx.set_handled();
2700        }
2701    }
2702
2703    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2704        match event {
2705            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move && self.open => {
2706                let highlighted = self.item_at(ctx.bounds(), pointer.position);
2707                self.update_pointer_highlight(ctx, highlighted);
2708            }
2709            Event::Pointer(pointer)
2710                if pointer.kind == PointerEventKind::Down
2711                    && pointer.button == Some(self.activation_button)
2712                    && if self.activation_button == PointerButton::Primary {
2713                        ctx.phase() == EventPhase::Capture
2714                    } else {
2715                        ctx.phase() != EventPhase::Capture
2716                    }
2717                    && self.trigger_rect().contains(pointer.position) =>
2718            {
2719                // Context-click targets see the press first so they can update selection.
2720                // Primary dropdowns own the trigger press during capture but defer opening
2721                // until release. Registering a transient overlay during the opening press can
2722                // otherwise make the overlay host classify that same press as an outside click.
2723                if self.activation_button == PointerButton::Primary {
2724                    if self.open {
2725                        self.set_open(ctx, false);
2726                    } else {
2727                        self.primary_trigger_press = Some(pointer.pointer_id);
2728                        ctx.request_pointer_capture(pointer.pointer_id);
2729                    }
2730                } else {
2731                    let open = !self.open;
2732                    self.open_position = (open && self.anchors_to_pointer()).then(|| {
2733                        let origin = ctx.bounds().origin;
2734                        Point::new(pointer.position.x - origin.x, pointer.position.y - origin.y)
2735                    });
2736                    self.set_open(ctx, open);
2737                    if open {
2738                        ctx.request_focus();
2739                    }
2740                }
2741                ctx.set_handled();
2742            }
2743            Event::Pointer(pointer)
2744                if pointer.kind == PointerEventKind::Up
2745                    && pointer.button == Some(PointerButton::Primary)
2746                    && self.primary_trigger_press == Some(pointer.pointer_id) =>
2747            {
2748                self.primary_trigger_press = None;
2749                ctx.release_pointer_capture(pointer.pointer_id);
2750                if self.trigger_rect().contains(pointer.position) {
2751                    self.open_position = None;
2752                    self.set_open(ctx, true);
2753                    ctx.request_focus();
2754                }
2755                ctx.set_handled();
2756            }
2757            Event::Pointer(pointer)
2758                if pointer.kind == PointerEventKind::Down
2759                    && pointer.button == Some(PointerButton::Primary)
2760                    && self.open =>
2761            {
2762                if let Some(path) = self.item_at(ctx.bounds(), pointer.position) {
2763                    self.update_pointer_highlight(ctx, Some(path.clone()));
2764                    self.set_pressed(
2765                        self.item_at_path(&path)
2766                            .filter(|item| item.enabled)
2767                            .map(|_| path),
2768                        ctx,
2769                    );
2770                    ctx.request_pointer_capture(pointer.pointer_id);
2771                    ctx.set_handled();
2772                } else if !self.trigger_rect().contains(pointer.position) {
2773                    self.set_open(ctx, false);
2774                }
2775            }
2776            Event::Pointer(pointer)
2777                if pointer.kind == PointerEventKind::Up
2778                    && pointer.button == Some(PointerButton::Primary)
2779                    && self.open =>
2780            {
2781                let highlighted = self.item_at(ctx.bounds(), pointer.position);
2782                if let Some(path) = self
2783                    .pressed
2784                    .clone()
2785                    .zip(highlighted)
2786                    .filter(|(left, right)| left == right)
2787                    .map(|(path, _)| path)
2788                {
2789                    if self.item_at_path(&path).is_some_and(MenuItem::has_submenu) {
2790                        self.set_open_path(ctx, path);
2791                    } else {
2792                        self.activate_path(ctx, path);
2793                        self.set_open(ctx, false);
2794                    }
2795                }
2796                self.set_pressed(None, ctx);
2797                ctx.release_pointer_capture(pointer.pointer_id);
2798                ctx.set_handled();
2799            }
2800            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2801                if self.primary_trigger_press == Some(pointer.pointer_id) {
2802                    self.primary_trigger_press = None;
2803                    ctx.release_pointer_capture(pointer.pointer_id);
2804                    ctx.set_handled();
2805                }
2806                if self.pressed.is_some() {
2807                    self.set_pressed(None, ctx);
2808                    ctx.release_pointer_capture(pointer.pointer_id);
2809                    ctx.set_handled();
2810                }
2811            }
2812            Event::Keyboard(key)
2813                if self.activation_button == PointerButton::Primary
2814                    && ctx.is_focused()
2815                    && key.state == KeyState::Pressed
2816                    && !self.open
2817                    && matches!(key.key.as_str(), "Enter" | " ") =>
2818            {
2819                self.open_position = None;
2820                self.set_open(ctx, true);
2821                ctx.request_focus();
2822                ctx.set_handled();
2823            }
2824            Event::Keyboard(key)
2825                if ctx.is_focused() && key.state == KeyState::Pressed && self.open =>
2826            {
2827                match key.key.as_str() {
2828                    "ArrowDown" => self.move_highlight(1, ctx),
2829                    "ArrowUp" => self.move_highlight(-1, ctx),
2830                    "Home" => self.move_highlight_to_edge(true, ctx),
2831                    "End" => self.move_highlight_to_edge(false, ctx),
2832                    "ArrowRight" => {
2833                        self.open_highlighted_submenu(ctx);
2834                    }
2835                    "ArrowLeft" => {
2836                        self.close_current_submenu(ctx);
2837                    }
2838                    "Enter" | " " => {
2839                        if !self.open_highlighted_submenu(ctx)
2840                            && let Some(path) = self.highlighted.clone()
2841                        {
2842                            self.activate_path(ctx, path);
2843                            self.set_open(ctx, false);
2844                        }
2845                    }
2846                    "Escape" => {
2847                        self.set_open(ctx, false);
2848                    }
2849                    _ => return,
2850                }
2851                self.refresh_surface_interaction_state(ctx);
2852                ctx.request_paint();
2853                ctx.request_semantics();
2854                ctx.set_handled();
2855            }
2856            Event::Semantics(semantics) if self.open && semantics.target != ctx.widget_id() => {
2857                let Some(path) =
2858                    self.visible_path_for_semantics_id(ctx.widget_id(), semantics.target)
2859                else {
2860                    return;
2861                };
2862                let has_submenu = self
2863                    .item_at_path(&path)
2864                    .is_some_and(|item| item.enabled && item.has_submenu());
2865                match semantics.action {
2866                    sui_core::SemanticsActionRequest::Activate
2867                    | sui_core::SemanticsActionRequest::Expand
2868                        if has_submenu =>
2869                    {
2870                        self.set_highlighted(Some(path), ctx);
2871                        self.open_highlighted_submenu(ctx);
2872                    }
2873                    sui_core::SemanticsActionRequest::Collapse if has_submenu => {
2874                        self.set_open_path(ctx, path[..path.len().saturating_sub(1)].to_vec());
2875                        self.set_highlighted(Some(path), ctx);
2876                    }
2877                    sui_core::SemanticsActionRequest::Activate => {
2878                        self.activate_path(ctx, path);
2879                        self.set_open(ctx, false);
2880                    }
2881                    sui_core::SemanticsActionRequest::Focus => {
2882                        self.set_highlighted(Some(path), ctx);
2883                        ctx.request_focus();
2884                    }
2885                    _ => return,
2886                }
2887                ctx.set_handled();
2888            }
2889            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
2890                let open = match semantics.action {
2891                    sui_core::SemanticsActionRequest::Activate => Some(!self.open),
2892                    sui_core::SemanticsActionRequest::Expand => Some(true),
2893                    sui_core::SemanticsActionRequest::Collapse => Some(false),
2894                    _ => None,
2895                };
2896                if let Some(open) = open {
2897                    self.open_position = None;
2898                    self.set_open(ctx, open);
2899                    if open {
2900                        ctx.request_focus();
2901                    }
2902                    ctx.set_handled();
2903                }
2904            }
2905            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
2906                let surface_id = self.surface.child().id();
2907                let focus_surface_id = self.focus_surface.child().id();
2908                let mut state = self.surface_state.borrow_mut();
2909                let was_presented = state.is_presented();
2910                let was_focus_presented = state.focus_animation.is_presented();
2911                let previous = state.reveal.value;
2912                let previous_focus = state.focus_animation.value;
2913                let reveal_animating = state.reveal.advance(*time);
2914                let focus_animating = state.focus_animation.advance(*time);
2915                let reveal_changed = state.reveal.changed_since(previous);
2916                let focus_changed = state.focus_animation.changed_since(previous_focus);
2917                let is_presented = state.is_presented();
2918                let is_focus_presented = state.focus_animation.is_presented();
2919                drop(state);
2920
2921                let previous_highlight = self.highlight_animation.value;
2922                let previous_press = self.press_animation.value;
2923                let row_animating = self.advance_row_animations(*time);
2924                let row_changed = self.highlight_animation.changed_since(previous_highlight)
2925                    || self.press_animation.changed_since(previous_press);
2926                if row_changed {
2927                    self.refresh_surface_interaction_state(ctx);
2928                    request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
2929                }
2930
2931                if reveal_changed {
2932                    request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
2933                    request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
2934                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
2935                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
2936                }
2937                if focus_changed {
2938                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
2939                }
2940                if was_presented != is_presented {
2941                    ctx.request_measure();
2942                    request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
2943                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
2944                }
2945                if was_focus_presented != is_focus_presented {
2946                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
2947                }
2948                if reveal_animating || row_animating || focus_animating {
2949                    ctx.request_animation_frame();
2950                }
2951                ctx.set_handled();
2952            }
2953            _ => {}
2954        }
2955    }
2956
2957    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2958        let trigger_size = self.trigger.measure(ctx, constraints.loosen());
2959        if self.open {
2960            let theme = self.resolved_theme();
2961            let pointer_anchored = self.open_position.is_some();
2962            self.panels.clear();
2963            let mut prefix = Vec::new();
2964            while let Some(items) = self.items_at_prefix(&prefix).map(<[MenuItem]>::to_vec) {
2965                let mut width = self.measured_menu_width_for_items(ctx, &items);
2966                if prefix.is_empty() && !pointer_anchored {
2967                    width = width.max(trigger_size.width);
2968                }
2969                let height = themed_menu_height_for_rows(&theme, self.row_height(), items.len());
2970                self.panels.push(ContextMenuPanel {
2971                    prefix: prefix.clone(),
2972                    items: items.clone(),
2973                    frame_rect: Rect::from_origin_size(Point::ZERO, Size::new(width, height)),
2974                    opens_left: false,
2975                });
2976                if prefix.len() >= self.open_path.len() {
2977                    break;
2978                }
2979                let next = self.open_path[prefix.len()];
2980                if items
2981                    .get(next)
2982                    .is_none_or(|item| !item.enabled || !item.has_submenu())
2983                {
2984                    break;
2985                }
2986                prefix.push(next);
2987            }
2988
2989            let estimated_width = self
2990                .panels
2991                .iter()
2992                .map(|panel| panel.frame_rect.width())
2993                .sum::<f32>();
2994            let estimated_height = self
2995                .panels
2996                .iter()
2997                .map(|panel| panel.frame_rect.height())
2998                .sum::<f32>();
2999            let estimated_size = Size::new(estimated_width, estimated_height);
3000            {
3001                let mut state = self.surface_state.borrow_mut();
3002                state.theme = theme;
3003                state.panels = self.panels.clone();
3004                state.highlighted = self.highlighted.clone();
3005                state.highlight_visual = self.highlight_visual.clone();
3006                state.pressed = self.pressed.clone();
3007                state.press_visual = self.press_visual.clone();
3008                state.highlight_animation = self.highlight_animation;
3009                state.press_animation = self.press_animation;
3010                state.surface_rect = Rect::from_origin_size(Point::ZERO, estimated_size);
3011                state.row_height = self.row_height();
3012            }
3013            self.surface
3014                .measure(ctx, Constraints::tight(estimated_size));
3015            self.focus_surface
3016                .measure(ctx, Constraints::tight(estimated_size));
3017        } else {
3018            self.panels.clear();
3019        }
3020        constraints.clamp(trigger_size)
3021    }
3022
3023    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3024        self.trigger.arrange(
3025            ctx,
3026            Rect::from_origin_size(bounds.origin, self.trigger.child().measured_size()),
3027        );
3028        if self.open && !self.panels.is_empty() {
3029            let theme = self.resolved_theme();
3030            let anchor = self.open_position.map_or_else(
3031                || self.trigger.child().bounds(),
3032                |position| {
3033                    Rect::from_origin_size(
3034                        Point::new(bounds.x() + position.x, bounds.y() + position.y),
3035                        Size::ZERO,
3036                    )
3037                },
3038            );
3039            let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
3040            let result = place_overlay(
3041                &OverlayPlacementRequest::new(
3042                    anchor,
3043                    self.panels[0].frame_rect.size,
3044                    viewport,
3045                    OverlayPlacement::BOTTOM_START,
3046                )
3047                .fallbacks([
3048                    OverlayPlacement::TOP_START,
3049                    OverlayPlacement::RIGHT_START,
3050                    OverlayPlacement::LEFT_START,
3051                ])
3052                .gap(if self.open_position.is_some() {
3053                    0.0
3054                } else {
3055                    theme.metrics.popover_gap
3056                })
3057                .margin(theme.metrics.popover_gap.max(4.0)),
3058            );
3059            self.panels[0].frame_rect = result
3060                .bounds
3061                .translate(Vector::new(-bounds.x(), -bounds.y()));
3062
3063            for depth in 1..self.panels.len() {
3064                let owner_path = self.panels[depth].prefix.clone();
3065                let Some(anchor) = self.item_rect(bounds, &owner_path) else {
3066                    continue;
3067                };
3068                let margin = theme.metrics.popover_gap.max(4.0);
3069                let remaining_cascade_width = self.panels[depth..]
3070                    .iter()
3071                    .map(|panel| panel.frame_rect.width())
3072                    .sum::<f32>();
3073                let room_left = (anchor.x() - viewport.x() - margin).max(0.0);
3074                let room_right = (viewport.max_x() - anchor.max_x() - margin).max(0.0);
3075                let prefer_left = self.panels[depth - 1].opens_left
3076                    || (room_right < remaining_cascade_width
3077                        && room_left >= remaining_cascade_width);
3078                let (placement, fallbacks) = if prefer_left {
3079                    (
3080                        OverlayPlacement::LEFT_START,
3081                        [
3082                            OverlayPlacement::RIGHT_START,
3083                            OverlayPlacement::LEFT_END,
3084                            OverlayPlacement::RIGHT_END,
3085                        ],
3086                    )
3087                } else {
3088                    (
3089                        OverlayPlacement::RIGHT_START,
3090                        [
3091                            OverlayPlacement::LEFT_START,
3092                            OverlayPlacement::RIGHT_END,
3093                            OverlayPlacement::LEFT_END,
3094                        ],
3095                    )
3096                };
3097                let result = place_overlay(
3098                    &OverlayPlacementRequest::new(
3099                        anchor,
3100                        self.panels[depth].frame_rect.size,
3101                        viewport,
3102                        placement,
3103                    )
3104                    .fallbacks(fallbacks)
3105                    .gap(0.0)
3106                    .margin(margin),
3107                );
3108                self.panels[depth].opens_left = result.placement.side == OverlaySide::Left;
3109                self.panels[depth].frame_rect = result
3110                    .bounds
3111                    .translate(Vector::new(-bounds.x(), -bounds.y()));
3112            }
3113        }
3114        self.sync_surface_state(bounds);
3115        let state = self.surface_state.borrow();
3116        let surface_bounds = if state.is_presented() {
3117            state.surface_rect
3118        } else {
3119            Rect::from_origin_size(bounds.origin, Size::ZERO)
3120        };
3121        drop(state);
3122        self.surface.arrange(ctx, surface_bounds);
3123        self.focus_surface.arrange(ctx, surface_bounds);
3124    }
3125
3126    fn paint(&self, ctx: &mut PaintCtx) {
3127        self.trigger.paint(ctx);
3128        if self.surface_state.borrow().is_presented() {
3129            self.surface.paint(ctx);
3130            self.focus_surface.paint(ctx);
3131        }
3132    }
3133
3134    fn semantics(&self, ctx: &mut SemanticsCtx) {
3135        let mut node =
3136            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ContextMenu, ctx.bounds());
3137        node.name = Some(self.name.clone());
3138        node.state.focused = ctx.is_focused();
3139        node.state.expanded = Some(self.open);
3140        node.popup = Some(SemanticsPopupKind::Menu);
3141        node.value = self
3142            .highlighted
3143            .as_deref()
3144            .and_then(|path| self.item_at_path(path))
3145            .map(|item| SemanticsValue::Text(item.label.clone()));
3146        node.actions = vec![
3147            SemanticsAction::Focus,
3148            SemanticsAction::Expand,
3149            SemanticsAction::Collapse,
3150            SemanticsAction::Activate,
3151        ];
3152        ctx.push(node);
3153        if self.open {
3154            for panel in &self.panels {
3155                let parent = if panel.prefix.is_empty() {
3156                    ctx.widget_id()
3157                } else {
3158                    virtual_menu_item_path_id(ctx.widget_id(), &panel.prefix)
3159                };
3160                for (index, item) in panel.items.iter().enumerate() {
3161                    let mut path = panel.prefix.clone();
3162                    path.push(index);
3163                    let Some(row) = self.item_rect(ctx.bounds(), &path) else {
3164                        continue;
3165                    };
3166                    ctx.push(context_menu_item_semantics_node(
3167                        ctx.widget_id(),
3168                        parent,
3169                        &path,
3170                        item,
3171                        row,
3172                        self.highlighted.as_deref() == Some(path.as_slice()),
3173                        self.open_path.starts_with(&path),
3174                    ));
3175                }
3176            }
3177        }
3178        self.trigger.semantics(ctx);
3179    }
3180
3181    fn accepts_focus(&self) -> bool {
3182        true
3183    }
3184
3185    fn overlay_options(&self) -> Option<OverlayOptions> {
3186        (self.open || self.surface_state.borrow().is_presented()).then_some(
3187            OverlayOptions::new(OverlayKind::Menu)
3188                .dismiss(if self.open {
3189                    OverlayDismissPolicy::TRANSIENT
3190                } else {
3191                    OverlayDismissPolicy::NONE
3192                })
3193                .focus(OverlayFocusBehavior::NONE),
3194        )
3195    }
3196
3197    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3198        if !focused && self.open {
3199            self.set_open(ctx, false);
3200        }
3201        let focus_surface_id = self.focus_surface.child().id();
3202        {
3203            let mut state = self.surface_state.borrow_mut();
3204            let was_focus_presented = state.focus_animation.is_presented();
3205            let theme = state.theme;
3206            set_focus_animation_target(
3207                &mut state.focus_animation,
3208                focused as u8 as f32,
3209                &theme,
3210                ctx,
3211            );
3212            if was_focus_presented != state.focus_animation.is_presented() {
3213                request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
3214            }
3215        }
3216        request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
3217        ctx.request_semantics();
3218    }
3219
3220    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3221        self.trigger.visit_children(visitor);
3222        if self.surface_state.borrow().is_presented() {
3223            self.surface.visit_children(visitor);
3224            self.focus_surface.visit_children(visitor);
3225        }
3226    }
3227
3228    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3229        self.trigger.visit_children_mut(visitor);
3230        if self.surface_state.borrow().is_presented() {
3231            self.surface.visit_children_mut(visitor);
3232            self.focus_surface.visit_children_mut(visitor);
3233        }
3234    }
3235}