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 {
114 name,
115 action,
116 checked,
117 ..
118 } => menu.action_checked(name, action, checked),
119 OwnedMenuItem::Submenu(submenu) => {
120 submenu
121 .items
122 .into_iter()
123 .fold(menu, |menu, item| match item {
124 OwnedMenuItem::Separator => menu.separator(),
125 OwnedMenuItem::Action {
126 name,
127 action,
128 checked,
129 ..
130 } => menu.action_checked(name, action, checked),
131 OwnedMenuItem::Submenu(_) => menu,
132 OwnedMenuItem::SystemMenu(_) => {
133 // A system menu doesn't make sense in this context, so ignore it
134 menu
135 }
136 })
137 }
138 OwnedMenuItem::SystemMenu(_) => {
139 // A system menu doesn't make sense in this context, so ignore it
140 menu
141 }
142 })
143 })
144 }
145
146 fn render_application_menu(&self, entry: &MenuEntry) -> impl IntoElement {
147 let handle = entry.handle.clone();
148
149 let menu_name = entry.menu.name.clone();
150 let entry = entry.clone();
151
152 // Application menu must have same ids as first menu item in standard menu
153 div()
154 .id(SharedString::from(format!("{}-menu-item", menu_name)))
155 .occlude()
156 .child(
157 PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
158 .menu(move |window, cx| {
159 Self::build_menu_from_items(entry.clone(), window, cx).into()
160 })
161 .trigger_with_tooltip(
162 IconButton::new(
163 SharedString::from(format!("{}-menu-trigger", menu_name)),
164 ui::IconName::Menu,
165 )
166 .style(ButtonStyle::Subtle)
167 .icon_size(IconSize::Small),
168 Tooltip::text("Open Application Menu"),
169 )
170 .with_handle(handle),
171 )
172 }
173
174 fn render_standard_menu(&self, entry: &MenuEntry) -> impl IntoElement {
175 let current_handle = entry.handle.clone();
176
177 let menu_name = entry.menu.name.clone();
178 let entry = entry.clone();
179
180 let all_handles: Vec<_> = self
181 .entries
182 .iter()
183 .map(|entry| entry.handle.clone())
184 .collect();
185
186 div()
187 .id(SharedString::from(format!("{}-menu-item", menu_name)))
188 .occlude()
189 .child(
190 PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
191 .menu(move |window, cx| {
192 Self::build_menu_from_items(entry.clone(), window, cx).into()
193 })
194 .trigger(
195 Button::new(
196 SharedString::from(format!("{}-menu-trigger", menu_name)),
197 menu_name,
198 )
199 .style(ButtonStyle::Subtle)
200 .label_size(LabelSize::Small),
201 )
202 .with_handle(current_handle.clone()),
203 )
204 .on_hover(move |hover_enter, window, cx| {
205 if *hover_enter && !current_handle.is_deployed() {
206 all_handles.iter().for_each(|h| h.hide(cx));
207
208 // We need to defer this so that this menu handle can take focus from the previous menu
209 let handle = current_handle.clone();
210 window.defer(cx, move |window, cx| handle.show(window, cx));
211 }
212 })
213 }
214
215 #[cfg(not(target_os = "macos"))]
216 pub fn open_menu(
217 &mut self,
218 action: &OpenApplicationMenu,
219 _window: &mut Window,
220 _cx: &mut Context<Self>,
221 ) {
222 self.pending_menu_open = Some(action.0.clone());
223 }
224
225 #[cfg(not(target_os = "macos"))]
226 pub fn navigate_menus_in_direction(
227 &mut self,
228 direction: ActivateDirection,
229 window: &mut Window,
230 cx: &mut Context<Self>,
231 ) {
232 let current_index = self
233 .entries
234 .iter()
235 .position(|entry| entry.handle.is_deployed());
236 let Some(current_index) = current_index else {
237 return;
238 };
239
240 let next_index = match direction {
241 ActivateDirection::Left => {
242 if current_index == 0 {
243 self.entries.len() - 1
244 } else {
245 current_index - 1
246 }
247 }
248 ActivateDirection::Right => {
249 if current_index == self.entries.len() - 1 {
250 0
251 } else {
252 current_index + 1
253 }
254 }
255 };
256
257 self.entries[current_index].handle.hide(cx);
258
259 // We need to defer this so that this menu handle can take focus from the previous menu
260 let next_handle = self.entries[next_index].handle.clone();
261 cx.defer_in(window, move |_, window, cx| next_handle.show(window, cx));
262 }
263
264 pub fn all_menus_shown(&self, cx: &mut Context<Self>) -> bool {
265 show_menus(cx)
266 || self.entries.iter().any(|entry| entry.handle.is_deployed())
267 || self.pending_menu_open.is_some()
268 }
269}
270
271pub(crate) fn show_menus(cx: &mut App) -> bool {
272 TitleBarSettings::get_global(cx).show_menus
273 && (cfg!(not(target_os = "macos")) || option_env!("ZED_USE_CROSS_PLATFORM_MENU").is_some())
274}
275
276impl Render for ApplicationMenu {
277 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
278 let all_menus_shown = self.all_menus_shown(cx);
279
280 if let Some(pending_menu_open) = self.pending_menu_open.take()
281 && let Some(entry) = self
282 .entries
283 .iter()
284 .find(|entry| entry.menu.name == pending_menu_open && !entry.handle.is_deployed())
285 {
286 let handle_to_show = entry.handle.clone();
287 let handles_to_hide: Vec<_> = self
288 .entries
289 .iter()
290 .filter(|e| e.menu.name != pending_menu_open && e.handle.is_deployed())
291 .map(|e| e.handle.clone())
292 .collect();
293
294 if handles_to_hide.is_empty() {
295 // We need to wait for the next frame to show all menus first,
296 // before we can handle show/hide operations
297 window.on_next_frame(move |window, cx| {
298 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
299 window.defer(cx, move |window, cx| handle_to_show.show(window, cx));
300 });
301 } else {
302 // Since menus are already shown, we can directly handle show/hide operations
303 handles_to_hide.iter().for_each(|handle| handle.hide(cx));
304 cx.defer_in(window, move |_, window, cx| handle_to_show.show(window, cx));
305 }
306 }
307
308 div()
309 .key_context("ApplicationMenu")
310 .flex()
311 .flex_row()
312 .gap_x_1()
313 .when(!all_menus_shown && !self.entries.is_empty(), |this| {
314 this.child(self.render_application_menu(&self.entries[0]))
315 })
316 .when(all_menus_shown, |this| {
317 this.children(
318 self.entries
319 .iter()
320 .map(|entry| self.render_standard_menu(entry)),
321 )
322 })
323 }
324}