use std::hash::Hash;
use super::{Popup, Response, ScrollArea, Ui};
use crate::winit::keyboard::KeyCode;
use crate::{
context::{HitAction, HitRegion},
Id, Padding, Rect, Vec2,
};
mod access;
mod actions;
mod cache;
pub(in crate::components) mod paint;
#[derive(Clone, Debug, PartialEq)]
pub struct ContextMenuItem {
pub id: Option<Id>,
pub text: String,
pub icon: String,
pub icon_shapes: Vec<crate::Shape>,
pub left_text: String,
pub right_text: String,
pub enabled: bool,
pub checked: bool,
pub(crate) submenu: bool,
pub(crate) action: bool,
}
impl ContextMenuItem {
pub fn new(id: impl Hash, text: impl Into<String>) -> Self {
Self {
id: Some(Id::new(id)),
text: text.into(),
icon: String::new(),
icon_shapes: Vec::new(),
left_text: String::new(),
right_text: String::new(),
enabled: true,
checked: false,
submenu: false,
action: false,
}
}
pub fn action(id: impl Hash) -> Self {
let mut item = Self::new("", "");
item.id = Some(crate::actions::action_id(id));
item.action = true;
item
}
pub fn separator() -> Self {
Self {
id: None,
text: String::new(),
icon: String::new(),
icon_shapes: Vec::new(),
left_text: String::new(),
right_text: String::new(),
enabled: false,
checked: false,
submenu: false,
action: false,
}
}
pub fn icon(mut self, icon: impl Into<String>) -> Self {
self.icon = icon.into();
self.icon_shapes.clear();
self
}
pub fn icon_shapes(mut self, shapes: impl IntoIterator<Item = crate::Shape>) -> Self {
self.icon_shapes = shapes.into_iter().collect();
self.icon.clear();
self
}
pub fn left_text(mut self, text: impl Into<String>) -> Self {
self.left_text = text.into();
self
}
pub fn right_text(mut self, text: impl Into<String>) -> Self {
self.right_text = text.into();
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
}
#[derive(Clone, Debug)]
pub struct ContextMenuStyle {
pub min_width: f32,
pub row_height: f32,
pub font_size: f32,
pub separator_height: f32,
pub padding: Padding,
pub popup: crate::PopupStyle,
pub item: crate::ControlStyle,
}
impl ContextMenuStyle {
#[track_caller]
pub(in crate::components) fn normalize(&mut self) {
use super::sanitize::{length, positive};
let default = Self::default();
self.min_width =
positive("ContextMenuStyle::min_width", self.min_width).unwrap_or(default.min_width);
self.row_height =
positive("ContextMenuStyle::row_height", self.row_height).unwrap_or(default.row_height);
self.separator_height =
positive("ContextMenuStyle::separator_height", self.separator_height)
.unwrap_or(default.separator_height);
self.font_size =
positive("ContextMenuStyle::font_size", self.font_size).unwrap_or(default.font_size);
self.padding.left = length("ContextMenuStyle::padding", self.padding.left);
self.padding.right = length("ContextMenuStyle::padding", self.padding.right);
self.padding.top = length("ContextMenuStyle::padding", self.padding.top);
self.padding.bottom = length("ContextMenuStyle::padding", self.padding.bottom);
}
}
impl Default for ContextMenuStyle {
fn default() -> Self {
Self {
min_width: 220.0,
row_height: 24.0,
font_size: 14.0,
separator_height: 9.0,
padding: Padding::all(4.0),
popup: Default::default(),
item: Default::default(),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ContextMenuOutput {
pub open: bool,
pub rect: Option<Rect>,
pub selected: Option<Id>,
}
#[derive(Default)]
pub(crate) struct MenuState {
open: bool,
position: Vec2,
active: Option<Id>,
pointer: Option<Vec2>,
keyboard: bool,
cache: Option<cache::MenuCache>,
pub(crate) last_frame: u64,
}
pub struct ContextMenu<'a> {
source: Id,
items: &'a [ContextMenuItem],
style: ContextMenuStyle,
position: Option<Vec2>,
target: access::Target,
}
impl<'a> ContextMenu<'a> {
pub fn new(source: impl Hash, items: &'a [ContextMenuItem]) -> Self {
Self {
source: Id::new(source),
items,
style: Default::default(),
position: None,
target: access::Target::Find,
}
}
pub fn style(mut self, style: ContextMenuStyle) -> Self {
self.style = style;
self
}
#[track_caller]
pub fn open_at(mut self, position: Vec2) -> Self {
self.position =
super::sanitize::finite_vec2("ContextMenu::open_at", position).or(self.position);
self
}
pub fn show(self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
if !actions::any(self.items) {
return self.show_items(ui, target);
}
let items = actions::resolve(ui, self.items);
let menu = ContextMenu {
source: self.source,
items: &items,
style: self.style,
position: self.position,
target: self.target,
};
let mut output = menu.show_items(ui, target);
actions::raise(ui, &items, &mut output.selected);
output
}
fn show_items(mut self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
self.style.normalize();
let style = &self.style;
let id = ui.scope.with(("context-menu", self.source, target.id));
let anchor_id = id.with("anchor");
let hit = HitRegion {
id: anchor_id,
window: ui.window,
rect: target.rect,
clip: ui.clip,
action: HitAction::ContextMenu,
};
if !ui.attach_tooltip_anchor(target.id, hit) {
ui.context.register_hit(hit);
}
let popup_id = Popup::id(ui, Id::new(id));
let mut state = ui
.context
.menus
.context_menus
.remove(&id)
.unwrap_or_default();
state.last_frame = ui.context.frame;
if ui.context.take_popup_dismissal(popup_id) {
state.open = false;
}
let pointer_open = ui.context.gestures.secondary_position(anchor_id);
let asked = access::asked(ui, self.target, target, anchor_id, !self.items.is_empty());
let placed = self.position.or(pointer_open);
let opening = placed.or(asked);
if let Some(position) = opening {
state.position = position;
state.keyboard = placed.is_none();
state.open = ui.enabled;
state.active = self
.items
.iter()
.find(|i| i.enabled && i.id.is_some())
.and_then(|i| i.id);
ui.context.request_repaint();
}
state.open &= ui.enabled && !self.items.is_empty();
let mut output = ContextMenuOutput::default();
if state.open {
let pointer = ui.context.input().pointer;
let pointer_moved = pointer != state.pointer;
state.pointer = pointer;
if pointer_moved {
state.keyboard = false;
}
let cache = match state.cache.take() {
Some(cache) if cache.matches(self.items, style) => cache,
_ => cache::MenuCache::new(ui, self.items, style),
};
let enabled = &cache.enabled;
if !state.active.is_some_and(|id| enabled.contains(&id)) {
state.active = enabled.first().copied();
}
let mut reveal = false;
for key in ui.context.take_menu_keys(id) {
let index = state
.active
.and_then(|a| enabled.iter().position(|i| *i == a))
.unwrap_or(0);
let next = match key {
KeyCode::ArrowDown => Some((index + 1) % enabled.len().max(1)),
KeyCode::ArrowUp => {
Some((index + enabled.len().saturating_sub(1)) % enabled.len().max(1))
}
KeyCode::Home => Some(0),
KeyCode::End => Some(enabled.len().saturating_sub(1)),
KeyCode::Enter | KeyCode::Space => {
output.selected = state.active;
None
}
_ => None,
};
if let Some(next) = next {
state.active = enabled.get(next).copied();
state.keyboard = true;
reveal = true;
}
}
let metrics = &cache.metrics;
let popup_style = paint::popup_style(ui, style);
let mut popup = Popup::new(id, Rect::from_min_size(state.position, Vec2::ZERO))
.size(Vec2::new(
metrics.width + style.padding.size().x,
metrics.height + style.padding.size().y,
))
.gap(0.0)
.padding(style.padding)
.style(popup_style);
popup.key_target = Some(id);
if placed.is_none() && asked.is_some() {
popup = popup.return_focus(target.id);
}
let active = state.keyboard.then_some(state.active).flatten();
let focus = id.with("focus");
let shown = popup.show(ui, &mut state.open, |ui| {
ui.context.register_hit(HitRegion {
id: focus,
window: ui.window,
rect: ui.layout.bounds,
clip: ui.clip,
action: HitAction::Focus,
});
let mut scroll = ui.style().scroll;
scroll.padding = Padding::all(0.0);
scroll.spacing = 0.0;
scroll.bar_margin = 0.0;
let mut scroll_area = ScrollArea::vertical()
.id_source(id.with("scroll"))
.max_height(ui.available_height())
.overlay_scrollbars(true)
.style(scroll)
.show_hints(false)
.middle_mouse_scroll(false)
.a11y_hidden();
let menu = ui.a11y_begin(id, crate::AccessRole::Menu, |node| {
node.focus_on(focus);
if let Some(active) = active {
node.active_descendant(id.with(("item", active)));
}
});
if reveal {
if let Some(index) = self
.items
.iter()
.position(|item| item.id == active && item.id.is_some())
{
scroll_area = scroll_area.scroll_to_rect(Rect::from_min_size(
Vec2::new(0.0, cache.offsets[index]),
Vec2::new(metrics.width, style.row_height),
));
}
}
let area = scroll_area.show(ui, |ui| {
ui.layout.spacing = 0.0;
let origin = ui.layout.bounds.min;
let visible = ui.clip_rect();
let first = cache
.offsets
.partition_point(|y| *y <= visible.min.y - origin.y)
.saturating_sub(1)
.min(self.items.len());
let end = cache
.offsets
.partition_point(|y| *y < visible.max.y - origin.y)
.min(self.items.len())
.max(first);
ui.add_space(cache.offsets[first]);
for item in &self.items[first..end] {
let (response, selected) = paint::row(ui, id, item, active, metrics, style);
if selected {
output.selected = item.id;
}
if let Some(response) = response {
if pointer_moved && response.hovered && response.enabled {
state.active = item.id;
}
}
}
ui.add_space(metrics.height - cache.offsets[end]);
});
ui.context.a11y_scroll(&menu, area.id);
ui.a11y_end(menu, Some(area.viewport));
});
output.rect = shown.map(|p| p.rect);
if opening.is_some() && state.open {
ui.context.set_focus(Some(focus));
}
if output.selected.is_some() {
ui.context.close_popup();
state.open = false;
}
state.cache = Some(cache);
}
output.open = state.open;
ui.context.menus.context_menus.insert(id, state);
output
}
}
pub struct ContextMenuWidget<'a, W> {
widget: W,
items: &'a [ContextMenuItem],
}
impl<'a, W> ContextMenuWidget<'a, W> {
pub(super) fn new(widget: W, items: &'a [ContextMenuItem]) -> Self {
Self { widget, items }
}
}
impl<W: super::Widget> super::Widget for ContextMenuWidget<'_, W> {
fn ui(self, ui: &mut Ui<'_>) -> Response {
let before = access::before(ui);
let mut response = self.widget.ui(ui);
let mut menu = ContextMenu::new(response.id, self.items);
menu.target = access::wrapped(ui, before);
response.menu_selected = menu.show(ui, response).selected;
response
}
}
impl Ui<'_> {
pub fn context_menu(
&mut self,
target: Response,
items: &[ContextMenuItem],
) -> ContextMenuOutput {
ContextMenu::new(target.id, items).show(self, target)
}
}