use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::time::Instant;
use gpui::{
Anchor, AnyElement, App, ClickEvent, ElementId, FontWeight, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, Rgba, SharedString, Window, anchored, canvas, deferred, div,
point, prelude::*, px,
};
use crate::controls::WidgetContext;
use crate::keyboard::{self, Dismiss, Key, Orientation};
use crate::lighting;
use crate::palette::Palette;
use crate::state::{ComboId, ControlHost, ControlState, MenuBranch};
const ITEM_HEIGHT: f32 = 26.0;
const HEADER_HEIGHT: f32 = 22.0;
const SEPARATOR_GAP: f32 = 3.0;
const SEPARATOR_HEIGHT: f32 = 2.0 * SEPARATOR_GAP + 1.0;
const MENU_PADDING: f32 = 5.0;
const MENU_RADIUS: f32 = 7.0;
const MENU_MIN_WIDTH: f32 = 168.0;
const MENU_MAX_HEIGHT: f32 = 520.0;
const ICON_SLOT: f32 = 16.0;
const ICON_SIZE: f32 = 14.0;
pub(crate) const VIEWPORT_MARGIN: f32 = 8.0;
#[derive(Clone)]
pub struct MenuIcon(Rc<dyn Fn(f32, Rgba) -> AnyElement>);
impl MenuIcon {
pub fn new(draw: impl Fn(f32, Rgba) -> AnyElement + 'static) -> Self {
Self(Rc::new(draw))
}
pub fn draw(&self, size: f32, color: Rgba) -> AnyElement {
(self.0)(size, color)
}
}
impl fmt::Debug for MenuIcon {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("MenuIcon")
}
}
#[derive(Clone, Debug)]
pub enum MenuItem<I = ComboId> {
Action(MenuAction<I>),
Submenu {
label: SharedString,
items: Vec<MenuItem<I>>,
enabled: bool,
icon: Option<MenuIcon>,
},
Separator,
Header(SharedString),
}
#[derive(Clone, Debug)]
pub struct MenuAction<I = ComboId> {
pub id: I,
pub label: SharedString,
pub shortcut: Option<SharedString>,
pub enabled: bool,
pub checked: bool,
pub danger: bool,
pub icon: Option<MenuIcon>,
}
impl<I> MenuItem<I> {
pub fn action(id: I, label: impl Into<SharedString>) -> Self {
MenuItem::Action(MenuAction {
id,
label: label.into(),
shortcut: None,
enabled: true,
checked: false,
danger: false,
icon: None,
})
}
pub fn header(label: impl Into<SharedString>) -> Self {
MenuItem::Header(label.into())
}
pub fn submenu(label: impl Into<SharedString>, items: Vec<MenuItem<I>>) -> Self {
MenuItem::Submenu {
label: label.into(),
items,
enabled: true,
icon: None,
}
}
pub fn separator() -> Self {
MenuItem::Separator
}
pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
if let MenuItem::Action(action) = &mut self {
action.shortcut = Some(shortcut.into());
}
self
}
pub fn disabled(mut self) -> Self {
self.set_enabled(false);
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.set_enabled(enabled);
self
}
fn set_enabled(&mut self, value: bool) {
match self {
MenuItem::Action(action) => action.enabled = value,
MenuItem::Submenu { enabled, .. } => *enabled = value,
_ => {}
}
}
pub fn checked(mut self, checked: bool) -> Self {
if let MenuItem::Action(action) = &mut self {
action.checked = checked;
}
self
}
pub fn danger(mut self) -> Self {
if let MenuItem::Action(action) = &mut self {
action.danger = true;
}
self
}
pub fn icon(mut self, icon: impl Into<MenuIcon>) -> Self {
match &mut self {
MenuItem::Action(action) => action.icon = Some(icon.into()),
MenuItem::Submenu { icon: slot, .. } => *slot = Some(icon.into()),
_ => {}
}
self
}
pub fn icon_of(&self) -> Option<&MenuIcon> {
match self {
MenuItem::Action(action) => action.icon.as_ref(),
MenuItem::Submenu { icon, .. } => icon.as_ref(),
_ => None,
}
}
pub fn label(&self) -> Option<&str> {
match self {
MenuItem::Action(action) => Some(&action.label),
MenuItem::Submenu { label, .. } | MenuItem::Header(label) => Some(label),
MenuItem::Separator => None,
}
}
pub fn reachable(&self) -> bool {
match self {
MenuItem::Action(action) => action.enabled,
MenuItem::Submenu { enabled, .. } => *enabled,
_ => false,
}
}
pub fn any_icon(items: &[MenuItem<I>]) -> bool {
items.iter().any(|item| item.icon_of().is_some())
}
pub fn action_mut(
items: &mut [MenuItem<I>],
matches: impl Fn(&MenuAction<I>) -> bool + Copy,
) -> Option<&mut MenuAction<I>> {
for item in items {
match item {
MenuItem::Action(action) if matches(action) => return Some(action),
MenuItem::Submenu { items, .. } => {
if let Some(found) = MenuItem::action_mut(items, matches) {
return Some(found);
}
}
_ => {}
}
}
None
}
}
fn submenu_identity<I>(label: &SharedString, children: &[MenuItem<I>]) -> u64 {
let mut hasher = DefaultHasher::new();
label.hash(&mut hasher);
children.len().hash(&mut hasher);
for item in children {
match item {
MenuItem::Action(action) => {
0_u8.hash(&mut hasher);
action.label.hash(&mut hasher);
}
MenuItem::Submenu { label, .. } => {
1_u8.hash(&mut hasher);
label.hash(&mut hasher);
}
MenuItem::Separator => 2_u8.hash(&mut hasher),
MenuItem::Header(label) => {
3_u8.hash(&mut hasher);
label.hash(&mut hasher);
}
}
}
hasher.finish()
}
fn visible_level<'a, I>(
mut items: &'a [MenuItem<I>],
levels: &[MenuBranch],
) -> Option<(&'a [MenuItem<I>], Option<&'a SharedString>)> {
let mut title = None;
for branch in levels {
let MenuItem::Submenu {
label,
items: children,
enabled: true,
..
} = items.get(branch.index)?
else {
return None;
};
if submenu_identity(label, children) != branch.identity {
return None;
}
items = children;
title = Some(label);
}
Some((items, title))
}
fn settle_levels<I>(
items: &[MenuItem<I>],
levels: &mut Vec<MenuBranch>,
highlight: &mut Option<usize>,
) -> Option<MenuBranch> {
let mut left = None;
while visible_level(items, levels).is_none() {
left = Some(levels.pop()?);
}
let branch = left?;
let (level, _) = visible_level(items, levels)?;
let still_there = reachable_indices(level).get(branch.highlight) == Some(&branch.index)
&& matches!(level.get(branch.index), Some(MenuItem::Submenu { .. }));
*highlight = still_there.then_some(branch.highlight);
Some(branch)
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum MenuCommand<I = ComboId> {
Back { close_at_root: bool },
Enter {
row: usize,
at: usize,
identity: u64,
},
Run(I),
Highlight(usize),
}
fn menu_commands<I: Clone>(items: &[MenuItem<I>], reachable: &[usize]) -> Vec<MenuCommand<I>> {
reachable
.iter()
.enumerate()
.map(|(at, &row)| match &items[row] {
MenuItem::Action(action) => MenuCommand::Run(action.id.clone()),
MenuItem::Submenu { label, items, .. } => MenuCommand::Enter {
row,
at,
identity: submenu_identity(label, items),
},
_ => unreachable!("reachable rows are actions or enabled submenus"),
})
.collect()
}
fn menu_command<I: Clone>(
key: Key,
at: Option<usize>,
commands: &[MenuCommand<I>],
) -> Option<MenuCommand<I>> {
let at = at.filter(|at| *at < commands.len());
match key {
Key::Dismiss => Some(MenuCommand::Back {
close_at_root: true,
}),
Key::Left => Some(MenuCommand::Back {
close_at_root: false,
}),
Key::Activate => commands.get(at?).cloned(),
Key::Right => match commands.get(at?)? {
command @ MenuCommand::Enter { .. } => Some(command.clone()),
_ => None,
},
key => step_highlight(key, at, commands.len()).map(MenuCommand::Highlight),
}
}
fn step_highlight(key: Key, at: Option<usize>, len: usize) -> Option<usize> {
if len == 0 {
return None;
}
match at {
Some(at) => keyboard::step(key, Orientation::Vertical, at, len),
None => match key {
Key::Down | Key::Home => Some(0),
Key::Up | Key::End => Some(len - 1),
_ => None,
},
}
}
fn reachable_indices<I>(items: &[MenuItem<I>]) -> Vec<usize> {
items
.iter()
.enumerate()
.filter_map(|(index, item)| item.reachable().then_some(index))
.collect()
}
fn menu_height<I>(items: &[MenuItem<I>], nested: bool) -> f32 {
let rows: f32 = items
.iter()
.map(|item| match item {
MenuItem::Separator => SEPARATOR_HEIGHT,
MenuItem::Header(_) => HEADER_HEIGHT,
_ => ITEM_HEIGHT,
})
.sum();
let back = if nested {
ITEM_HEIGHT + SEPARATOR_HEIGHT
} else {
0.0
};
(rows + back + 2.0 * (MENU_PADDING + 1.0)).min(MENU_MAX_HEIGHT)
}
fn fit_to_window(height: f32, window: Option<f32>) -> f32 {
let Some(window) = window else {
return height;
};
let room = window - 2.0 * VIEWPORT_MARGIN;
height.min(room.max(ITEM_HEIGHT + 2.0 * (MENU_PADDING + 1.0)))
}
#[allow(clippy::too_many_arguments)]
pub fn context_menu<V: ControlHost, I: Clone + 'static>(
id: ComboId,
items: &[MenuItem<I>],
palette: Palette,
view: &mut V,
cx: &mut Context<V>,
on_activate: impl Fn(&mut V, I, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
let state = view.control_state_mut();
let left = {
let menu = state.menu.as_mut()?;
if menu.id != id {
return None;
}
settle_levels(items, &mut menu.levels, &mut menu.highlight)
};
if let Some(branch) = left {
state.menu_level_changed(branch.scroll);
}
let menu = state.menu.as_ref()?;
let (anchor, under, opened_at, highlight, levels) = (
menu.anchor,
menu.under,
menu.opened_at,
menu.highlight,
menu.levels.clone(),
);
let tree = items;
let (level, title) = visible_level(items, &levels)?;
let title = title.cloned();
let items = level;
let reachable = reachable_indices(items);
let key_commands = menu_commands(items, &reachable);
let key_reachable = reachable.clone();
let selected = highlight.filter(|index| *index < reachable.len());
let nested = !levels.is_empty();
let icons = MenuItem::any_icon(items);
let row_offset = if nested { 2 } else { 0 };
let dark = palette.is_dark;
let on_activate: Activate<V, I> = Rc::new(on_activate);
let on_key_activate = on_activate.clone();
let focus = view.control_state_mut().menu_focus(cx);
let focus_on_open = focus.clone();
let weak = cx.entity().downgrade();
let scroll = view.control_state().menu_scroll(id);
let key_scroll = scroll.clone();
let window_height = view
.control_state()
.measured((id, "menu-window"))
.map(|window| f32::from(window.size.height));
let at = under
.map(|under| under.bottom_left() + point(px(0.0), px(4.0)))
.unwrap_or(anchor);
let reveal = crate::easing::ease_out_cubic(crate::easing::progress(
opened_at,
view.control_state().scaled(crate::state::COMBO_REVEAL),
));
let level_key = {
let mut hasher = DefaultHasher::new();
for branch in &levels {
(branch.index, branch.identity).hash(&mut hasher);
}
hasher.finish()
};
let depth = levels.len() as f32;
let position =
view.control_state()
.tween((id, "menu-level", opened_at), depth, crate::state::MOVE);
let level_reveal = (1.0 - (position - depth).abs()).clamp(0.0, 1.0);
let level_offset = (depth - position) * 10.0;
let height = fit_to_window(
view.control_state().tween(
(id, "menu-height", opened_at),
menu_height(items, nested),
crate::state::MOVE,
),
window_height,
);
let mut rows: Vec<gpui::AnyElement> = Vec::with_capacity(items.len() + row_offset);
if let Some(title) = title {
rows.push(render_back(title, id, opened_at, palette, cx));
rows.push(render_item(
Row {
index: 0,
reachable_at: None,
item: &MenuItem::Separator,
lit: 0.0,
icons,
},
id,
opened_at,
palette,
cx,
&on_activate,
));
}
for (index, item) in items.iter().enumerate() {
let reachable_at = reachable.binary_search(&index).ok();
let lit = selected.is_some_and(|at| reachable.get(at) == Some(&index));
let lit = view.control_state().blend(
(id, "menu-lit", (opened_at, level_key, index)),
lit,
crate::state::SWITCH_SLIDE,
);
rows.push(render_item(
Row {
index,
reachable_at,
item,
lit,
icons,
},
id,
opened_at,
palette,
cx,
&on_activate,
));
}
let panel = div()
.id(ElementId::Name(format!("{id}-menu").into()))
.opacity(reveal)
.mt(px(-4.0 * (1.0 - reveal)))
.h(px(height))
.min_w(px(MENU_MIN_WIDTH))
.max_w(px(360.0))
.p(px(MENU_PADDING))
.flex()
.flex_col()
.rounded(px(MENU_RADIUS))
.bg(if dark {
palette.soft_fill
} else {
palette.field_surface
})
.border_1()
.border_color(lighting::rim(
if dark {
palette.soft_fill
} else {
palette.field_surface
},
dark,
))
.shadow(lighting::panel(dark))
.track_focus(&focus)
.child(
canvas(
move |_bounds, window, cx| {
let viewport =
gpui::Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
if let Some(host) = weak.upgrade() {
let resized = host.update(cx, |host, _cx| {
let state = host.control_state_mut();
let resized = state.measured((id, "menu-window")) != Some(viewport);
if resized {
state.measure((id, "menu-window"), viewport);
}
resized
});
if resized {
window.request_animation_frame();
}
}
if focus_on_open.is_focused(window) {
return;
}
let previous = window.focused(cx);
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().menu_return_focus = previous;
});
}
window.focus(&focus_on_open, cx);
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.size_full(),
)
.on_action(cx.listener(move |this, _: &Dismiss, window, cx| {
if !this.control_state_mut().back_menu() {
this.control_state_mut().close_menu();
restore_focus(this, window, cx);
}
cx.notify();
}))
.on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
let Some(key) = keyboard::key(event) else {
return;
};
cx.stop_propagation();
let at = this.control_state().menu_highlight();
match menu_command(key, at, &key_commands) {
Some(MenuCommand::Back { close_at_root }) => {
if !this.control_state_mut().back_menu() && close_at_root {
this.control_state_mut().close_menu();
restore_focus(this, window, cx);
}
}
Some(MenuCommand::Enter { row, at, identity }) => {
this.control_state_mut().enter_menu(row, at, identity, true);
}
Some(MenuCommand::Run(action)) => {
activate(this, action, opened_at, window, cx, &on_key_activate);
}
Some(MenuCommand::Highlight(moved)) => {
this.control_state_mut().highlight_menu(Some(moved));
if let Some(&row) = key_reachable.get(moved) {
key_scroll.scroll_to_item(row + row_offset);
}
}
None => {}
}
cx.notify();
}))
.on_hover(cx.listener(|this, hovered: &bool, _window, cx| {
if !*hovered && this.control_state().menu_highlight().is_some() {
this.control_state_mut().highlight_menu(None);
cx.notify();
}
}))
.occlude()
.on_mouse_down_out(
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
let on_own_button = this
.control_state()
.track(id)
.is_some_and(|bounds| bounds.contains(&event.position));
if on_own_button {
return;
}
this.control_state_mut().close_menu();
restore_focus(this, window, cx);
cx.notify();
}),
)
.on_mouse_down(
MouseButton::Right,
cx.listener(|_this, _event: &MouseDownEvent, _window, _cx| {}),
)
.child(
div()
.flex_1()
.min_h(px(0.0))
.flex()
.flex_col()
.overflow_hidden()
.child(
div()
.id(ElementId::Name(format!("{id}-menu-rows").into()))
.relative()
.left(px(level_offset))
.opacity(level_reveal)
.flex_1()
.min_h(px(0.0))
.flex()
.flex_col()
.overflow_y_scroll()
.restrict_scroll_to_axis()
.track_scroll(&scroll)
.children(rows),
),
)
.child(
div()
.h(px(0.0))
.flex_none()
.flex()
.flex_col()
.overflow_hidden()
.children(
every_level(tree)
.into_iter()
.flat_map(|level| {
let icons = MenuItem::any_icon(level);
level.iter().map(move |item| sizing_row(item, icons))
})
.flatten(),
),
);
let panel = crate::state::handle_mouse(panel, cx);
Some(
deferred(
anchored()
.position(at)
.anchor(Anchor::TopLeft)
.snap_to_window_with_margin(px(VIEWPORT_MARGIN))
.child(panel),
)
.priority(200),
)
}
type Activate<V, I> = Rc<dyn Fn(&mut V, I, &mut Window, &mut Context<V>)>;
fn restore_focus<V: ControlHost>(view: &mut V, window: &mut Window, cx: &mut App) {
view.control_state_mut().restore_menu_focus(window, cx);
}
fn activate<V: ControlHost, I>(
view: &mut V,
id: I,
opened_at: Instant,
window: &mut Window,
cx: &mut Context<V>,
on_activate: &Activate<V, I>,
) {
restore_focus(view, window, cx);
on_activate(view, id, window, cx);
if view.control_state().menu_opened_at() == Some(opened_at) {
view.control_state_mut().close_menu();
}
}
fn every_level<I>(items: &[MenuItem<I>]) -> Vec<&[MenuItem<I>]> {
let mut levels = Vec::new();
let mut stack = vec![items];
while let Some(level) = stack.pop() {
levels.push(level);
for item in level {
if let MenuItem::Submenu { items, .. } = item {
stack.push(items);
}
}
}
levels
}
#[cfg(test)]
fn every_row<I>(items: &[MenuItem<I>]) -> Vec<&MenuItem<I>> {
every_level(items).into_iter().flatten().collect()
}
fn sizing_row<I>(item: &MenuItem<I>, icons: bool) -> Option<gpui::AnyElement> {
let row = div()
.flex()
.items_center()
.gap(px(8.0))
.pr(px(8.0))
.whitespace_nowrap()
.when(icons && !matches!(item, MenuItem::Header(_)), |row| {
row.child(div().w(px(ICON_SLOT)).flex_none())
});
Some(match item {
MenuItem::Separator => return None,
MenuItem::Header(label) => row
.pl(px(8.0))
.text_size(px(11.0))
.font_weight(FontWeight::MEDIUM)
.child(label.clone())
.into_any_element(),
MenuItem::Submenu { label, .. } => row
.pl(px(8.0))
.text_size(px(12.5))
.font_weight(FontWeight::MEDIUM)
.child(label.clone())
.when(icons, |row| row.child(div().w(px(ICON_SLOT)).flex_none()))
.child(div().w(px(10.0)).flex_none())
.into_any_element(),
MenuItem::Action(action) => row
.pl(px(8.0))
.text_size(px(12.5))
.child(action.label.clone())
.children(
action
.shortcut
.clone()
.map(|shortcut| div().text_size(px(11.5)).child(shortcut)),
)
.when(icons, |row| row.child(div().w(px(ICON_SLOT)).flex_none()))
.when(action.checked, |row| {
row.child(div().w(px(12.0)).flex_none())
})
.into_any_element(),
})
}
#[derive(Clone, Copy)]
enum RowClick {
Navigate,
Activate,
}
fn takes_click(
state: &ControlState,
opened_at: Instant,
click_count: usize,
kind: RowClick,
) -> bool {
(matches!(kind, RowClick::Navigate) || click_count <= 1) && state.menu_takes_click(opened_at)
}
fn hover_row<V: ControlHost>(view: &mut V, reachable_at: Option<usize>, cx: &mut Context<V>) {
if let Some(at) = reachable_at
&& view.control_state().menu_highlight() != Some(at)
{
view.control_state_mut().highlight_menu(Some(at));
cx.notify();
}
}
fn chevron(right: bool, color: gpui::Rgba) -> impl IntoElement {
let color: gpui::Hsla = crate::color::to_hsla(color);
div().w(px(10.0)).h(px(10.0)).flex_none().child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let mut builder = gpui::PathBuilder::stroke(px(1.4));
let edge = if right { 7.0 } else { 3.0 };
let tip = if right { 3.0 } else { 7.0 };
builder.move_to(point(origin.x + px(tip), origin.y + px(1.5)));
builder.line_to(point(origin.x + px(edge), origin.y + px(5.0)));
builder.line_to(point(origin.x + px(tip), origin.y + px(8.5)));
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
},
)
.size_full(),
)
}
fn icon_slot(icon: Option<&MenuIcon>, color: Rgba) -> gpui::Div {
let slot = div()
.w(px(ICON_SLOT))
.h(px(ICON_SLOT))
.flex_none()
.flex()
.items_center()
.justify_center();
match icon {
Some(icon) => slot.child(icon.draw(ICON_SIZE, color)),
None => slot,
}
}
fn tick_mark(color: gpui::Hsla) -> gpui::Div {
div().w(px(12.0)).h(px(12.0)).flex_none().child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let mut builder = gpui::PathBuilder::stroke(px(1.5));
builder.move_to(point(origin.x + px(1.5), origin.y + px(6.0)));
builder.line_to(point(origin.x + px(4.5), origin.y + px(9.0)));
builder.line_to(point(origin.x + px(10.5), origin.y + px(2.5)));
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
},
)
.size_full(),
)
}
fn render_back<V: ControlHost>(
title: SharedString,
menu_id: ComboId,
opened_at: Instant,
palette: Palette,
cx: &mut Context<V>,
) -> gpui::AnyElement {
div()
.id(ElementId::Name(format!("{menu_id}-menu-back").into()))
.h(px(ITEM_HEIGHT))
.flex_none()
.w_full()
.px(px(8.0))
.flex()
.items_center()
.gap(px(8.0))
.rounded(px(MENU_RADIUS - 3.0))
.text_size(px(12.5))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_primary)
.cursor_pointer()
.hover(move |style| style.bg(lighting::lit(palette.row_hover, 0.08)))
.on_mouse_move(cx.listener(|this, _: &MouseMoveEvent, _window, cx| {
if this.control_state().menu_highlight().is_some() {
this.control_state_mut().highlight_menu(None);
cx.notify();
}
}))
.on_click(cx.listener(move |this, event: &ClickEvent, _window, cx| {
if takes_click(
this.control_state(),
opened_at,
event.click_count(),
RowClick::Navigate,
) {
this.control_state_mut().back_menu();
cx.notify();
}
}))
.child(div().flex_1().overflow_hidden().child(title))
.child(chevron(false, palette.text_secondary))
.into_any_element()
}
fn menu_row_labels(palette: Palette, danger: bool, lit: f32) -> (gpui::Rgba, gpui::Rgba) {
let label = if danger {
palette.danger_label
} else {
palette.text_primary
};
let highlighted = if danger {
palette.danger_label
} else {
palette.control_label
};
(
crate::color::lerp(label, highlighted, lit),
crate::color::lerp(palette.text_secondary, highlighted, lit),
)
}
struct Row<'a, I> {
index: usize,
reachable_at: Option<usize>,
item: &'a MenuItem<I>,
lit: f32,
icons: bool,
}
fn render_item<V: ControlHost, I: Clone + 'static>(
row: Row<'_, I>,
menu_id: ComboId,
opened_at: Instant,
palette: Palette,
cx: &mut Context<V>,
on_activate: &Activate<V, I>,
) -> gpui::AnyElement {
let Row {
index,
reachable_at,
item,
lit,
icons,
} = row;
match item {
MenuItem::Separator => {
let mut color: gpui::Hsla = crate::color::to_hsla(palette.field_border);
color.alpha = 0.8;
div()
.my(px(SEPARATOR_GAP))
.h(px(1.0))
.w_full()
.flex_none()
.bg(color)
.into_any_element()
}
MenuItem::Header(label) => div()
.h(px(HEADER_HEIGHT))
.flex_none()
.px(px(8.0))
.flex()
.items_center()
.text_size(px(11.0))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.whitespace_nowrap()
.child(label.clone())
.into_any_element(),
MenuItem::Submenu {
label,
items,
enabled,
icon,
} => {
let identity = submenu_identity(label, items);
let (label_color, chevron_color) = menu_row_labels(palette, false, lit);
div()
.id(ElementId::NamedInteger(
format!("{menu_id}-submenu").into(),
index as u64,
))
.h(px(ITEM_HEIGHT))
.flex_none()
.w_full()
.px(px(8.0))
.flex()
.items_center()
.gap(px(8.0))
.rounded(px(MENU_RADIUS - 3.0))
.text_size(px(12.5))
.text_color(label_color)
.whitespace_nowrap()
.overflow_hidden()
.when(!enabled, |el| el.opacity(0.45))
.when(lit > 0.01, |el| {
el.bg(lighting::lit_at(palette.control_fill, 0.08, lit))
})
.on_mouse_move(cx.listener(move |this, _: &MouseMoveEvent, _window, cx| {
hover_row(this, reachable_at, cx);
}))
.when(*enabled, |el| {
el.cursor_pointer().on_click(cx.listener(
move |this, event: &ClickEvent, _window, cx| {
if takes_click(
this.control_state(),
opened_at,
event.click_count(),
RowClick::Navigate,
) && let Some(at) = reachable_at
{
this.control_state_mut()
.enter_menu(index, at, identity, false);
cx.notify();
}
},
))
})
.child(div().flex_1().overflow_hidden().child(label.clone()))
.when(icons, |el| {
el.child(icon_slot(icon.as_ref(), chevron_color))
})
.child(chevron(true, chevron_color))
.into_any_element()
}
MenuItem::Action(action) => {
let on_activate = on_activate.clone();
let id = action.id.clone();
let (label_color, shortcut_color) = menu_row_labels(palette, action.danger, lit);
let tick: gpui::Hsla = crate::color::to_hsla(label_color);
let (enabled, checked, danger) = (action.enabled, action.checked, action.danger);
div()
.id(ElementId::NamedInteger(
format!("{menu_id}-item").into(),
index as u64,
))
.h(px(ITEM_HEIGHT))
.flex_none()
.w_full()
.pl(px(8.0))
.pr(px(8.0))
.flex()
.items_center()
.gap(px(8.0))
.rounded(px(MENU_RADIUS - 3.0))
.text_size(px(12.5))
.text_color(label_color)
.whitespace_nowrap()
.overflow_hidden()
.when(!enabled, |el| el.opacity(0.45))
.when(lit > 0.01, move |el| {
el.bg(lighting::lit_at(
if danger {
palette.danger_fill
} else {
palette.control_fill
},
0.08,
lit,
))
})
.on_mouse_move(cx.listener(move |this, _: &MouseMoveEvent, _window, cx| {
hover_row(this, reachable_at, cx);
}))
.when(enabled, move |el| {
let on_activate = on_activate.clone();
el.cursor_pointer().on_click(cx.listener(
move |this, event: &ClickEvent, window, cx| {
if takes_click(
this.control_state(),
opened_at,
event.click_count(),
RowClick::Activate,
) {
activate(this, id.clone(), opened_at, window, cx, &on_activate);
cx.notify();
}
},
))
})
.child(div().flex_1().overflow_hidden().child(action.label.clone()))
.children(action.shortcut.clone().map(|shortcut| {
div()
.flex_none()
.text_size(px(11.5))
.text_color(shortcut_color)
.child(shortcut)
}))
.when(icons, |el| {
el.child(icon_slot(action.icon.as_ref(), label_color))
})
.when(checked, |el| el.child(tick_mark(tick)))
.into_any_element()
}
}
}
pub fn menu_button<V: ControlHost>(
id: ComboId,
label: &str,
enabled: bool,
ctx: WidgetContext<'_, '_, '_, V>,
) -> impl IntoElement {
let WidgetContext { palette, view, cx } = ctx;
let dark = palette.is_dark;
let open = view.control_state().is_menu_open(id);
let fill = if dark {
palette.soft_fill
} else {
palette.field_surface
};
let weak = cx.entity().downgrade();
div()
.id(ElementId::Name(format!("{id}-menu-button").into()))
.relative()
.h(px(crate::controls::CONTROL_HEIGHT))
.flex_none()
.px(px(12.0))
.flex()
.items_center()
.gap(px(6.0))
.rounded(px(crate::controls::CONTROL_RADIUS))
.bg(lighting::lit(fill, 0.05))
.border_1()
.border_color(if open {
palette.accent
} else {
lighting::rim(fill, dark)
})
.shadow(lighting::raised(dark))
.text_size(px(12.5))
.text_color(palette.text_primary)
.whitespace_nowrap()
.when(!enabled, |el| el.opacity(0.5))
.when(enabled, |el| {
el.cursor_pointer()
.hover(move |style| style.bg(lighting::lit(fill, 0.09)))
})
.child(
canvas(
move |bounds, _window, cx| {
if let Some(host) = weak.upgrade() {
host.update(cx, |host, _cx| {
host.control_state_mut().record_track(id, bounds);
});
}
},
|_bounds, _state, _window, _cx| {},
)
.absolute()
.size_full(),
)
.child(SharedString::from(label.to_string()))
.child(
div().w(px(9.0)).h(px(9.0)).flex_none().child(
canvas(
|_bounds, _window, _cx| {},
move |bounds, _state, window, _cx| {
let origin = bounds.origin;
let mut builder = gpui::PathBuilder::stroke(px(1.4));
builder.move_to(point(origin.x + px(0.5), origin.y + px(3.0)));
builder.line_to(point(origin.x + px(4.5), origin.y + px(7.0)));
builder.line_to(point(origin.x + px(8.5), origin.y + px(3.0)));
if let Ok(path) = builder.build() {
let color: gpui::Hsla = crate::color::to_hsla(palette.text_secondary);
window.paint_path(path, color);
}
},
)
.size_full(),
),
)
.when(enabled, |el| {
el.on_click(cx.listener(move |this, _event, window, cx| {
let state = this.control_state_mut();
if state.is_menu_open(id) {
state.close_menu();
state.restore_menu_focus(window, cx);
} else if let Some(bounds) = state.track(id) {
state.open_menu_under(id, bounds, "");
}
cx.notify();
}))
})
.when(enabled, |el| {
el.child(
keyboard::ring(
ElementId::Name(format!("{id}-menu-button-focus").into()),
crate::controls::CONTROL_RADIUS,
palette,
)
.on_key_down(cx.listener(
move |this, event: &KeyDownEvent, _window, cx| {
if !matches!(keyboard::key(event), Some(Key::Activate | Key::Down)) {
return;
}
cx.stop_propagation();
if let Some(bounds) = this.control_state().track(id) {
this.control_state_mut().open_menu_under(id, bounds, "");
cx.notify();
}
},
)),
)
})
}
pub fn menu_target<V: ControlHost>(
menu: ComboId,
target: impl Into<SharedString>,
cx: &mut Context<V>,
on_open: impl Fn(&mut V, SharedString, &mut Context<V>) + 'static,
child: impl IntoElement,
) -> gpui::Div {
let target = target.into();
div()
.flex_none()
.on_mouse_down(
MouseButton::Right,
cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
on_open(this, target.clone(), cx);
this.control_state_mut()
.open_menu(menu, event.position, target.clone());
cx.notify();
}),
)
.child(child)
}
pub use crate::state::OpenMenu as ContextMenu;
#[cfg(test)]
mod tests {
use super::{
MenuBranch, MenuCommand, MenuIcon, MenuItem, RowClick, every_row, fit_to_window,
menu_command, menu_commands, menu_height, menu_row_labels, reachable_indices,
settle_levels, step_highlight, submenu_identity, takes_click, visible_level,
};
use crate::ControlState;
use crate::keyboard::Key;
#[test]
fn keyboard_snapshot_owns_typed_ids_without_retaining_icons_or_subtrees() {
let token = std::rc::Rc::new(());
let weak = std::rc::Rc::downgrade(&token);
let icon = MenuIcon::new(move |_, _| {
let _ = &token;
gpui::IntoElement::into_any_element(gpui::Empty)
});
let items = vec![
MenuItem::action(String::from("disabled"), "Disabled").disabled(),
MenuItem::action(String::from("open"), "Open").icon(icon),
MenuItem::submenu(
"More",
vec![MenuItem::action(String::from("nested"), "Nested")],
),
];
let reachable = reachable_indices(&items);
let commands = menu_commands(&items, &reachable);
drop(items);
assert!(weak.upgrade().is_none());
assert_eq!(
menu_command(Key::Activate, Some(0), &commands),
Some(MenuCommand::Run(String::from("open")))
);
assert_eq!(menu_command(Key::Right, Some(0), &commands), None);
assert!(matches!(
menu_command(Key::Right, Some(1), &commands),
Some(MenuCommand::Enter { row: 2, at: 1, .. })
));
}
#[test]
fn highlighted_menu_text_and_marks_use_the_fills_label_role() {
for hue in (0..360).step_by(30) {
for saturation in [0.0, 1.0, 2.0, crate::MAX_SATURATION] {
for dark in [false, true] {
let palette =
crate::Palette::from_hue_and_saturation(hue as f64, saturation, dark);
for (danger, lit, expected) in [
(false, 0.0, (palette.text_primary, palette.text_secondary)),
(false, 1.0, (palette.control_label, palette.control_label)),
(true, 1.0, (palette.danger_label, palette.danger_label)),
] {
let actual = menu_row_labels(palette, danger, lit);
for (actual, expected) in [(actual.0, expected.0), (actual.1, expected.1)] {
for (actual, expected) in crate::color::channels(actual)
.into_iter()
.zip(crate::color::channels(expected))
{
assert!((actual - expected).abs() < 1e-6);
}
}
}
}
}
}
}
fn branch(item: &MenuItem, index: usize, highlight: usize) -> MenuBranch {
let MenuItem::Submenu { label, items, .. } = item else {
panic!("expected submenu");
};
MenuBranch {
index,
highlight,
identity: submenu_identity(label, items),
scroll: Default::default(),
}
}
fn children(item: &MenuItem) -> &[MenuItem] {
let MenuItem::Submenu { items, .. } = item else {
panic!("expected submenu");
};
items
}
fn tree(move_to: &[&'static str], tag: &[&'static str]) -> Vec<MenuItem> {
let actions = |ids: &[&'static str]| {
ids.iter()
.map(|id| MenuItem::action(*id, *id))
.collect::<Vec<_>>()
};
vec![
MenuItem::action("open", "Open"),
MenuItem::submenu(
"Organize",
vec![
MenuItem::action("pin", "Pin"),
MenuItem::submenu("Move to", actions(move_to)),
MenuItem::submenu("Tag", actions(tag)),
],
),
]
}
fn path_to_move(items: &[MenuItem]) -> Vec<MenuBranch> {
vec![
branch(&items[1], 1, 1),
branch(&children(&items[1])[1], 1, 1),
]
}
#[test]
fn nested_levels_find_the_leaf_and_reject_a_removed_branch() {
let items = vec![MenuItem::submenu(
"Organize",
vec![MenuItem::submenu(
"Move to",
vec![MenuItem::action("inbox", "Inbox")],
)],
)];
let MenuItem::Submenu {
items: children, ..
} = &items[0]
else {
unreachable!();
};
let path = [branch(&items[0], 0, 0), branch(&children[0], 0, 0)];
let (level, title) = visible_level(&items, &path).expect("nested level");
assert_eq!(title.map(|title| title.as_ref()), Some("Move to"));
assert!(matches!(level, [MenuItem::Action(action)] if action.id == "inbox"));
let disabled: Vec<MenuItem> = vec![MenuItem::submenu("Organize", vec![]).disabled()];
assert!(visible_level(&disabled, &path[..1]).is_none());
}
#[test]
fn a_reordered_or_replaced_branch_cannot_show_another_submenu() {
let original = vec![
MenuItem::submenu("Organize", vec![MenuItem::action("inbox", "Inbox")]),
MenuItem::submenu("Other", vec![MenuItem::action("settings", "Settings")]),
];
let path = [branch(&original[0], 0, 0)];
assert!(visible_level(&original, &path).is_some());
let reordered = vec![original[1].clone(), original[0].clone()];
assert!(visible_level(&reordered, &path).is_none());
let replaced = vec![MenuItem::submenu(
"Organize",
vec![MenuItem::action("archive", "Archive")],
)];
assert!(visible_level(&replaced, &path).is_none());
let toggled = vec![MenuItem::submenu(
"Organize",
vec![MenuItem::action("inbox", "Inbox").checked(true).disabled()],
)];
assert!(visible_level(&toggled, &path).is_some());
let commands: Vec<MenuItem<Option<u32>>> = vec![MenuItem::submenu(
"Organize",
vec![
MenuItem::action(Some(7), "Inbox"),
MenuItem::action(None, "Gone"),
],
)];
let MenuItem::Submenu { label, items, .. } = &commands[0] else {
unreachable!();
};
let path = [MenuBranch {
index: 0,
highlight: 0,
identity: submenu_identity(label, items),
scroll: Default::default(),
}];
assert!(visible_level(&commands, &path).is_some());
}
#[test]
fn an_edit_in_a_sibling_subtree_keeps_the_open_level() {
let original = tree(&["inbox"], &["red"]);
let path = path_to_move(&original);
let retagged = tree(&["inbox"], &["red", "blue"]);
let (level, title) = visible_level(&retagged, &path).expect("still open");
assert_eq!(title.map(|title| title.as_ref()), Some("Move to"));
assert!(matches!(level, [MenuItem::Action(action)] if action.id == "inbox"));
let moved = tree(&["archive"], &["red"]);
assert!(visible_level(&moved, &path).is_none());
assert!(visible_level(&moved, &path[..1]).is_some());
}
#[test]
fn settling_backs_out_only_as_far_as_the_tree_changed() {
let original = tree(&["inbox"], &["red"]);
let path = path_to_move(&original);
let mut levels = path.clone();
let mut highlight = Some(0);
let retagged = tree(&["inbox"], &["red", "blue"]);
assert_eq!(settle_levels(&retagged, &mut levels, &mut highlight), None);
assert_eq!((levels.len(), highlight), (2, Some(0)));
let moved = tree(&["archive"], &["red"]);
let left = settle_levels(&moved, &mut levels, &mut highlight);
assert_eq!(left, Some(path[1]));
assert_eq!((levels.len(), highlight), (1, Some(1)));
let mut levels = path.clone();
let mut highlight = Some(0);
let flattened = vec![
MenuItem::action("open", "Open"),
MenuItem::action("delete", "Delete").danger(),
];
let left = settle_levels(&flattened, &mut levels, &mut highlight);
assert_eq!(left, Some(path[0]));
assert!(levels.is_empty());
assert_eq!(highlight, None);
}
#[test]
fn arrows_in_a_level_with_nothing_reachable_go_nowhere() {
for key in [Key::Down, Key::Home, Key::Up, Key::End] {
assert_eq!(step_highlight(key, None, 0), None);
assert_eq!(step_highlight(key, Some(3), 0), None);
}
let inert = vec![
MenuItem::header("Recent"),
MenuItem::separator(),
MenuItem::action("none", "Nothing yet").disabled(),
];
let reachable = reachable_indices(&inert);
assert!(reachable.is_empty());
assert_eq!(
menu_command(Key::Down, None, &menu_commands(&inert, &reachable)),
None
);
assert_eq!(
menu_command(Key::Home, Some(0), &menu_commands(&inert, &reachable)),
None
);
assert_eq!(
menu_command(Key::Activate, Some(0), &menu_commands(&inert, &reachable)),
None
);
assert_eq!(step_highlight(Key::Down, None, 3), Some(0));
assert_eq!(step_highlight(Key::Up, None, 3), Some(2));
}
#[test]
fn left_and_escape_go_back_and_only_escape_closes_the_root() {
let items = tree(&["inbox"], &["red"]);
let reachable = reachable_indices(&items);
assert_eq!(
menu_command(Key::Left, None, &menu_commands(&items, &reachable)),
Some(MenuCommand::Back {
close_at_root: false
})
);
assert_eq!(
menu_command(Key::Dismiss, None, &menu_commands(&items, &reachable)),
Some(MenuCommand::Back {
close_at_root: true
})
);
assert_eq!(
menu_command(Key::Right, Some(1), &menu_commands(&items, &reachable)),
Some(MenuCommand::Enter {
row: 1,
at: 1,
identity: branch(&items[1], 1, 1).identity,
})
);
assert_eq!(
menu_command(Key::Activate, Some(0), &menu_commands(&items, &reachable)),
Some(MenuCommand::Run("open"))
);
assert_eq!(
menu_command(Key::Right, Some(0), &menu_commands(&items, &reachable)),
None
);
}
#[test]
fn navigation_skips_inert_rows_but_enters_enabled_submenus() {
let items = vec![
MenuItem::header("Files"),
MenuItem::action("open", "Open"),
MenuItem::separator(),
MenuItem::action("closed", "Closed").disabled(),
MenuItem::submenu("Organize", vec![MenuItem::action("move", "Move")]),
MenuItem::submenu("Unavailable", vec![]).disabled(),
];
assert_eq!(reachable_indices(&items), vec![1, 4]);
}
#[test]
fn long_levels_scroll_and_nested_levels_make_room_for_back() {
let short = vec![MenuItem::action("open", "Open")];
assert_eq!(menu_height(&short, true) - menu_height(&short, false), 33.0);
let long: Vec<MenuItem> = (0..40).map(|_| MenuItem::header("Section")).collect();
assert_eq!(menu_height(&long, false), super::MENU_MAX_HEIGHT);
}
#[test]
fn repeated_navigation_settles_without_requiring_pointer_movement() {
let mut state = ControlState::new();
state.open_menu("row", gpui::point(gpui::px(0.0), gpui::px(0.0)), "");
let opening = state.menu_opened_at().expect("open");
assert!(takes_click(&state, opening, 1, RowClick::Activate));
assert!(!takes_click(&state, opening, 2, RowClick::Activate));
state.enter_menu(1, 1, 7, false);
assert!(!takes_click(&state, opening, 1, RowClick::Activate));
assert!(!takes_click(&state, opening, 2, RowClick::Navigate));
state.set_time_scale(0.001);
std::thread::sleep(std::time::Duration::from_millis(2));
assert!(takes_click(&state, opening, 1, RowClick::Activate));
assert!(!takes_click(&state, opening, 2, RowClick::Activate));
assert!(takes_click(&state, opening, 2, RowClick::Navigate));
assert!(state.back_menu());
assert!(!takes_click(&state, opening, 3, RowClick::Navigate));
std::thread::sleep(std::time::Duration::from_millis(2));
assert!(takes_click(&state, opening, 3, RowClick::Navigate));
state.close_menu();
assert!(!takes_click(&state, opening, 4, RowClick::Navigate));
}
#[test]
fn menu_height_counts_rows_at_their_drawn_heights() {
let chrome = 2.0 * (super::MENU_PADDING + 1.0);
let one = |item: MenuItem| menu_height(&[item], false) - chrome;
assert_eq!(one(MenuItem::separator()), 7.0);
assert_eq!(one(MenuItem::header("Recent")), 22.0);
assert_eq!(one(MenuItem::action("open", "Open")), super::ITEM_HEIGHT);
assert_eq!(super::SEPARATOR_HEIGHT, 2.0 * super::SEPARATOR_GAP + 1.0);
}
#[test]
fn the_width_is_taken_from_every_level() {
let items = tree(&["inbox"], &["a-very-long-tag"]);
let ids: Vec<_> = every_row(&items)
.into_iter()
.filter_map(|item| match item {
MenuItem::Action(action) => Some(action.id),
_ => None,
})
.collect();
for id in ["open", "pin", "inbox", "a-very-long-tag"] {
assert!(ids.contains(&id), "{id} missing");
}
}
#[test]
fn a_short_window_cuts_the_panel_to_fit() {
assert_eq!(fit_to_window(520.0, None), 520.0);
assert_eq!(fit_to_window(520.0, Some(900.0)), 520.0);
assert_eq!(
fit_to_window(520.0, Some(300.0)),
300.0 - 2.0 * super::VIEWPORT_MARGIN
);
assert_eq!(fit_to_window(520.0, Some(10.0)), 38.0);
}
#[test]
fn an_icon_anywhere_in_a_level_opens_the_icon_column() {
let icon = MenuIcon::new(|_, _| gpui::IntoElement::into_any_element(gpui::Empty));
let plain: Vec<MenuItem> = vec![
MenuItem::action("open", "Open"),
MenuItem::submenu(
"Move to",
vec![MenuItem::action("inbox", "Inbox").icon(icon)],
),
];
assert!(!MenuItem::any_icon(&plain));
assert!(MenuItem::any_icon(children(&plain[1])));
assert!(plain[1].icon_of().is_none());
assert_eq!(plain[1].label(), Some("Move to"));
assert_eq!(MenuItem::<&str>::separator().label(), None);
}
#[test]
fn an_action_is_found_at_any_depth_to_relabel() {
let mut items = tree(&["inbox"], &["red"]);
assert!(MenuItem::action_mut(&mut items, |action| action.id == "none").is_none());
let inbox =
MenuItem::action_mut(&mut items, |action| action.id == "inbox").expect("nested");
inbox.label = "Move to Inbox".into();
let organize = children(&items[1]);
let moved = children(&organize[1]);
assert_eq!(moved[0].label(), Some("Move to Inbox"));
}
}
#[cfg(test)]
#[path = "ownership_bench.rs"]
pub(crate) mod ownership_bench;