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