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