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 Tooltip::text("Open Application Menu"),
160 )
161 .with_handle(handle),
162 )
163 }
164
165 fn render_standard_menu(&self, entry: &MenuEntry) -> impl IntoElement {
166 let current_handle = entry.handle.clone();
167
168 let menu_name = entry.menu.name.clone();
169 let entry = entry.clone();
170
171 let all_handles: Vec<_> = self
172 .entries
173 .iter()
174 .map(|entry| entry.handle.clone())
175 .collect();
176
177 div()
178 .id(SharedString::from(format!("{}-menu-item", menu_name)))
179 .occlude()
180 .child(
181 PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
182 .menu(move |window, cx| {
183 Self::build_menu_from_items(entry.clone(), window, cx).into()
184 })
185 .trigger(
186 Button::new(
187 SharedString::from(format!("{}-menu-trigger", menu_name)),
188 menu_name,
189 )
190 .style(ButtonStyle::Subtle)
191 .label_size(LabelSize::Small),
192 )
193 .with_handle(current_handle.clone()),
194 )
195 .on_hover(move |hover_enter, window, cx| {
196 if *hover_enter && !current_handle.is_deployed() {
197 all_handles.iter().for_each(|h| h.hide(cx));
198
199 // We need to defer this so that this menu handle can take focus from the previous menu
200 let handle = current_handle.clone();
201 window.defer(cx, move |window, cx| handle.show(window, cx));
202 }
203 })
204 }
205
206 #[cfg(not(target_os = "macos"))]
207 pub fn open_menu(
208 &mut self,
209 action: &OpenApplicationMenu,
210 _window: &mut Window,
211 _cx: &mut Context<Self>,
212 ) {
213 self.pending_menu_open = Some(action.0.clone());
214 }
215
216 #[cfg(not(target_os = "macos"))]
217 pub fn navigate_menus_in_direction(
218 &mut self,
219 direction: ActivateDirection,
220 window: &mut Window,
221 cx: &mut Context<Self>,
222 ) {
223 let current_index = self
224 .entries
225 .iter()
226 .position(|entry| entry.handle.is_deployed());
227 let Some(current_index) = current_index else {
228 return;
229 };
230
231 let next_index = match direction {
232 ActivateDirection::Left => {
233 if current_index == 0 {
234 self.entries.len() - 1
235 } else {
236 current_index - 1
237 }
238 }
239 ActivateDirection::Right => {
240 if current_index == self.entries.len() - 1 {
241 0
242 } else {
243 current_index + 1
244 }
245 }
246 };
247
248 self.entries[current_index].handle.hide(cx);
249
250 // We need to defer this so that this menu handle can take focus from the previous menu
251 let next_handle = self.entries[next_index].handle.clone();
252 cx.defer_in(window, move |_, window, cx| next_handle.show(window, cx));
253 }
254
255 pub fn all_menus_shown(&self, cx: &mut Context<Self>) -> bool {
256 show_menus(cx)
257 || self.entries.iter().any(|entry| entry.handle.is_deployed())
258 || self.pending_menu_open.is_some()
259 }
260}
261
262pub(crate) fn show_menus(cx: &mut App) -> bool {
263 TitleBarSettings::get_global(cx).show_menus
264 && (cfg!(not(target_os = "macos")) || option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some())
265}
266
267impl Render for ApplicationMenu {
268 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
269 let all_menus_shown = self.all_menus_shown(cx);
270
271 if let Some(pending_menu_open) = self.pending_menu_open.take()
272 && let Some(entry) = self
273 .entries
274 .iter()
275 .find(|entry| entry.menu.name == pending_menu_open && !entry.handle.is_deployed())
276 {
277 let handle_to_show = entry.handle.clone();
278 let handles_to_hide: Vec<_> = self
279 .entries
280 .iter()
281 .filter(|e| e.menu.name != pending_menu_open && e.handle.is_deployed())
282 .map(|e| e.handle.clone())
283 .collect();
284
285 if handles_to_hide.is_empty() {
286 // We need to wait for the next frame to show all menus first,
287 // before we can handle show/hide operations
288 window.on_next_frame(move |window, cx| {
289 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
290 window.defer(cx, move |window, cx| handle_to_show.show(window, cx));
291 });
292 } else {
293 // Since menus are already shown, we can directly handle show/hide operations
294 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
295 cx.defer_in(window, move |_, window, cx| handle_to_show.show(window, cx));
296 }
297 }
298
299 div()
300 .key_context("ApplicationMenu")
301 .flex()
302 .flex_row()
303 .gap_x_1()
304 .when(!all_menus_shown && !self.entries.is_empty(), |this| {
305 this.child(self.render_application_menu(&self.entries[0]))
306 })
307 .when(all_menus_shown, |this| {
308 this.children(
309 self.entries
310 .iter()
311 .map(|entry| self.render_standard_menu(entry)),
312 )
313 })
314 }
315}