1use gpui::{Entity, OwnedMenu, OwnedMenuItem};
2use settings::Settings;
3
4#[cfg(not(target_os = "macos"))]
5use gpui::{Action, actions};
6
7#[cfg(not(target_os = "macos"))]
8use schemars::JsonSchema;
9#[cfg(not(target_os = "macos"))]
10use serde::Deserialize;
11
12use smallvec::SmallVec;
13use ui::{ContextMenu, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*};
14
15use crate::title_bar_settings::TitleBarSettings;
16
17#[cfg(not(target_os = "macos"))]
18actions!(
19 app_menu,
20 [
21 /// Navigates to the menu item on the right.
22 ActivateMenuRight,
23 /// Navigates to the menu item on the left.
24 ActivateMenuLeft
25 ]
26);
27
28#[cfg(not(target_os = "macos"))]
29#[derive(Clone, Deserialize, JsonSchema, PartialEq, Default, Action)]
30#[action(namespace = app_menu)]
31pub struct OpenApplicationMenu(String);
32
33#[cfg(not(target_os = "macos"))]
34pub enum ActivateDirection {
35 Left,
36 Right,
37}
38
39#[derive(Clone)]
40struct MenuEntry {
41 menu: OwnedMenu,
42 handle: PopoverMenuHandle<ContextMenu>,
43}
44
45pub struct ApplicationMenu {
46 entries: SmallVec<[MenuEntry; 8]>,
47 pending_menu_open: Option<String>,
48}
49
50impl ApplicationMenu {
51 pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
52 let menus = cx.get_menus().unwrap_or_default();
53 Self {
54 entries: menus
55 .into_iter()
56 .map(|menu| MenuEntry {
57 menu,
58 handle: PopoverMenuHandle::default(),
59 })
60 .collect(),
61 pending_menu_open: None,
62 }
63 }
64
65 fn sanitize_menu_items(items: Vec<OwnedMenuItem>) -> Vec<OwnedMenuItem> {
66 let mut cleaned = Vec::new();
67 let mut last_was_separator = false;
68
69 for item in items {
70 match item {
71 OwnedMenuItem::Separator => {
72 if !last_was_separator {
73 cleaned.push(item);
74 last_was_separator = true;
75 }
76 }
77 OwnedMenuItem::Submenu(submenu) => {
78 // Skip empty submenus
79 if !submenu.items.is_empty() {
80 cleaned.push(OwnedMenuItem::Submenu(submenu));
81 last_was_separator = false;
82 }
83 }
84 item => {
85 cleaned.push(item);
86 last_was_separator = false;
87 }
88 }
89 }
90
91 // Remove trailing separator
92 if let Some(OwnedMenuItem::Separator) = cleaned.last() {
93 cleaned.pop();
94 }
95
96 cleaned
97 }
98
99 fn build_menu_from_items(
100 entry: MenuEntry,
101 window: &mut Window,
102 cx: &mut App,
103 ) -> Entity<ContextMenu> {
104 ContextMenu::build(window, cx, |menu, window, cx| {
105 // Grab current focus handle so menu can shown items in context with the focused element
106 let menu = menu.when_some(window.focused(cx), |menu, focused| menu.context(focused));
107 let sanitized_items = Self::sanitize_menu_items(entry.menu.items);
108
109 sanitized_items
110 .into_iter()
111 .fold(menu, |menu, item| match item {
112 OwnedMenuItem::Separator => menu.separator(),
113 OwnedMenuItem::Action { name, action, .. } => menu.action(name, action),
114 OwnedMenuItem::Submenu(submenu) => {
115 submenu
116 .items
117 .into_iter()
118 .fold(menu, |menu, item| match item {
119 OwnedMenuItem::Separator => menu.separator(),
120 OwnedMenuItem::Action { name, action, .. } => {
121 menu.action(name, action)
122 }
123 OwnedMenuItem::Submenu(_) => menu,
124 OwnedMenuItem::SystemMenu(_) => {
125 // A system menu doesn't make sense in this context, so ignore it
126 menu
127 }
128 })
129 }
130 OwnedMenuItem::SystemMenu(_) => {
131 // A system menu doesn't make sense in this context, so ignore it
132 menu
133 }
134 })
135 })
136 }
137
138 fn render_application_menu(&self, entry: &MenuEntry) -> impl IntoElement {
139 let handle = entry.handle.clone();
140
141 let menu_name = entry.menu.name.clone();
142 let entry = entry.clone();
143
144 // Application menu must have same ids as first menu item in standard menu
145 div()
146 .id(SharedString::from(format!("{}-menu-item", menu_name)))
147 .occlude()
148 .child(
149 PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
150 .menu(move |window, cx| {
151 Self::build_menu_from_items(entry.clone(), window, cx).into()
152 })
153 .trigger_with_tooltip(
154 IconButton::new(
155 SharedString::from(format!("{}-menu-trigger", menu_name)),
156 ui::IconName::Menu,
157 )
158 .style(ButtonStyle::Subtle)
159 .icon_size(IconSize::Small),
160 Tooltip::text("Open Application Menu"),
161 )
162 .with_handle(handle),
163 )
164 }
165
166 fn render_standard_menu(&self, entry: &MenuEntry) -> impl IntoElement {
167 let current_handle = entry.handle.clone();
168
169 let menu_name = entry.menu.name.clone();
170 let entry = entry.clone();
171
172 let all_handles: Vec<_> = self
173 .entries
174 .iter()
175 .map(|entry| entry.handle.clone())
176 .collect();
177
178 div()
179 .id(SharedString::from(format!("{}-menu-item", menu_name)))
180 .occlude()
181 .child(
182 PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
183 .menu(move |window, cx| {
184 Self::build_menu_from_items(entry.clone(), window, cx).into()
185 })
186 .trigger(
187 Button::new(
188 SharedString::from(format!("{}-menu-trigger", menu_name)),
189 menu_name,
190 )
191 .style(ButtonStyle::Subtle)
192 .label_size(LabelSize::Small),
193 )
194 .with_handle(current_handle.clone()),
195 )
196 .on_hover(move |hover_enter, window, cx| {
197 if *hover_enter && !current_handle.is_deployed() {
198 all_handles.iter().for_each(|h| h.hide(cx));
199
200 // We need to defer this so that this menu handle can take focus from the previous menu
201 let handle = current_handle.clone();
202 window.defer(cx, move |window, cx| handle.show(window, cx));
203 }
204 })
205 }
206
207 #[cfg(not(target_os = "macos"))]
208 pub fn open_menu(
209 &mut self,
210 action: &OpenApplicationMenu,
211 _window: &mut Window,
212 _cx: &mut Context<Self>,
213 ) {
214 self.pending_menu_open = Some(action.0.clone());
215 }
216
217 #[cfg(not(target_os = "macos"))]
218 pub fn navigate_menus_in_direction(
219 &mut self,
220 direction: ActivateDirection,
221 window: &mut Window,
222 cx: &mut Context<Self>,
223 ) {
224 let current_index = self
225 .entries
226 .iter()
227 .position(|entry| entry.handle.is_deployed());
228 let Some(current_index) = current_index else {
229 return;
230 };
231
232 let next_index = match direction {
233 ActivateDirection::Left => {
234 if current_index == 0 {
235 self.entries.len() - 1
236 } else {
237 current_index - 1
238 }
239 }
240 ActivateDirection::Right => {
241 if current_index == self.entries.len() - 1 {
242 0
243 } else {
244 current_index + 1
245 }
246 }
247 };
248
249 self.entries[current_index].handle.hide(cx);
250
251 // We need to defer this so that this menu handle can take focus from the previous menu
252 let next_handle = self.entries[next_index].handle.clone();
253 cx.defer_in(window, move |_, window, cx| next_handle.show(window, cx));
254 }
255
256 pub fn all_menus_shown(&self, cx: &mut Context<Self>) -> bool {
257 show_menus(cx)
258 || self.entries.iter().any(|entry| entry.handle.is_deployed())
259 || self.pending_menu_open.is_some()
260 }
261}
262
263pub(crate) fn show_menus(cx: &mut App) -> bool {
264 TitleBarSettings::get_global(cx).show_menus
265 && (cfg!(not(target_os = "macos")) || option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some())
266}
267
268impl Render for ApplicationMenu {
269 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
270 let all_menus_shown = self.all_menus_shown(cx);
271
272 if let Some(pending_menu_open) = self.pending_menu_open.take()
273 && let Some(entry) = self
274 .entries
275 .iter()
276 .find(|entry| entry.menu.name == pending_menu_open && !entry.handle.is_deployed())
277 {
278 let handle_to_show = entry.handle.clone();
279 let handles_to_hide: Vec<_> = self
280 .entries
281 .iter()
282 .filter(|e| e.menu.name != pending_menu_open && e.handle.is_deployed())
283 .map(|e| e.handle.clone())
284 .collect();
285
286 if handles_to_hide.is_empty() {
287 // We need to wait for the next frame to show all menus first,
288 // before we can handle show/hide operations
289 window.on_next_frame(move |window, cx| {
290 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
291 window.defer(cx, move |window, cx| handle_to_show.show(window, cx));
292 });
293 } else {
294 // Since menus are already shown, we can directly handle show/hide operations
295 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
296 cx.defer_in(window, move |_, window, cx| handle_to_show.show(window, cx));
297 }
298 }
299
300 div()
301 .key_context("ApplicationMenu")
302 .flex()
303 .flex_row()
304 .gap_x_1()
305 .when(!all_menus_shown && !self.entries.is_empty(), |this| {
306 this.child(self.render_application_menu(&self.entries[0]))
307 })
308 .when(all_menus_shown, |this| {
309 this.children(
310 self.entries
311 .iter()
312 .map(|entry| self.render_standard_menu(entry)),
313 )
314 })
315 }
316}