1#[cfg(target_os = "windows")]
26use crate::ActiveTheme as _;
27use crate::Icon;
28#[cfg(any(target_os = "macos", target_os = "windows", test))]
29use crate::icon::IconSource;
30
31#[cfg(any(target_os = "macos", target_os = "windows"))]
32use gpui::AssetSource;
33use gpui::{Action, App, Pixels, Point, SharedString, Window};
34#[cfg(any(target_os = "macos", target_os = "windows"))]
35use gpui::{Image, ImageFormat};
36#[cfg(any(target_os = "macos", target_os = "windows"))]
37use std::{path::Path, sync::Arc};
38
39#[cfg(target_os = "macos")]
40mod macos;
41#[cfg(target_os = "windows")]
42mod windows;
43
44mod fallback;
47pub(crate) use fallback::FallbackMenuOverlay;
48
49enum NativeMenuItem {
50 Separator,
51 Item {
52 label: SharedString,
53 disabled: bool,
54 checked: bool,
55 icon: Option<Box<Icon>>,
57 action: Option<Box<dyn Action>>,
59 },
60 Submenu {
61 label: SharedString,
62 disabled: bool,
63 items: Vec<NativeMenuItem>,
64 },
65}
66
67#[derive(Default)]
72pub struct NativeMenu {
73 items: Vec<NativeMenuItem>,
74}
75
76impl NativeMenu {
77 pub fn new() -> Self {
79 Self::default()
80 }
81
82 pub fn menu(self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
84 self.menu_with(label, false, false, None, Some(action))
85 }
86
87 pub fn menu_with_disabled(
89 self,
90 label: impl Into<SharedString>,
91 disabled: bool,
92 action: Box<dyn Action>,
93 ) -> Self {
94 self.menu_with(label, disabled, false, None, Some(action))
95 }
96
97 pub fn menu_with_check(
99 self,
100 label: impl Into<SharedString>,
101 checked: bool,
102 action: Box<dyn Action>,
103 ) -> Self {
104 self.menu_with(label, false, checked, None, Some(action))
105 }
106
107 pub fn menu_with_icon(
122 self,
123 label: impl Into<SharedString>,
124 icon: impl Into<Icon>,
125 action: Box<dyn Action>,
126 ) -> Self {
127 self.menu_with(label, false, false, Some(icon.into()), Some(action))
128 }
129
130 pub fn menu_with_icon_disabled(
135 self,
136 label: impl Into<SharedString>,
137 icon: impl Into<Icon>,
138 disabled: bool,
139 action: Box<dyn Action>,
140 ) -> Self {
141 self.menu_with(label, disabled, false, Some(icon.into()), Some(action))
142 }
143
144 pub fn menu_with_icon_and_disabled(
148 self,
149 label: impl Into<SharedString>,
150 icon: impl Into<Icon>,
151 action: Box<dyn Action>,
152 disabled: bool,
153 ) -> Self {
154 self.menu_with_icon_disabled(label, icon, disabled, action)
155 }
156
157 fn menu_with(
158 mut self,
159 label: impl Into<SharedString>,
160 disabled: bool,
161 checked: bool,
162 icon: Option<Icon>,
163 action: Option<Box<dyn Action>>,
164 ) -> Self {
165 self.items.push(NativeMenuItem::Item {
166 label: label.into(),
167 disabled,
168 checked,
169 icon: icon.map(Box::new),
170 action,
171 });
172 self
173 }
174
175 pub fn separator(mut self) -> Self {
177 self.items.push(NativeMenuItem::Separator);
178 self
179 }
180
181 pub fn submenu(mut self, label: impl Into<SharedString>, submenu: NativeMenu) -> Self {
183 self.items.push(NativeMenuItem::Submenu {
184 label: label.into(),
185 disabled: false,
186 items: submenu.items,
187 });
188 self
189 }
190
191 pub fn is_empty(&self) -> bool {
193 self.items.is_empty()
194 }
195
196 pub fn show(self, position: Point<Pixels>, window: &mut Window, cx: &mut App) {
202 if self.items.is_empty() {
203 return;
204 }
205
206 #[cfg(target_os = "macos")]
207 {
208 macos::show(self.items, cx.asset_source().clone(), position, window, cx);
209 }
210 #[cfg(target_os = "windows")]
211 {
212 windows::show(
213 self.items,
214 cx.asset_source().clone(),
215 position,
216 cx.theme().is_dark(),
217 window,
218 cx,
219 );
220 }
221 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
222 fallback::show(self.items, position, window, cx);
223 }
224}
225
226#[cfg(any(target_os = "macos", target_os = "windows"))]
227pub(super) fn resolve_icon_image(
228 icon: &Icon,
229 asset_source: &dyn AssetSource,
230) -> Option<Arc<Image>> {
231 let path = match icon.source_ref() {
232 IconSource::Path(path) => path,
233 IconSource::Data(bytes) => {
234 return Some(Arc::new(Image::from_bytes(
235 ImageFormat::Svg,
236 bytes.to_vec(),
237 )));
238 }
239 };
240 if path.is_empty() {
241 return None;
242 }
243
244 let icon_path = Path::new(path.as_ref());
245 let bytes = if icon_path.is_absolute() {
247 std::fs::read(icon_path).ok()?
248 } else {
249 asset_source
250 .load(path.as_ref())
251 .ok()
252 .flatten()?
253 .into_owned()
254 };
255 let format = image_format(path.as_ref(), &bytes)?;
256 Some(Arc::new(Image::from_bytes(format, bytes)))
257}
258
259#[cfg(any(target_os = "macos", target_os = "windows"))]
260fn image_format(path: &str, bytes: &[u8]) -> Option<ImageFormat> {
261 if let Some(extension) = Path::new(path)
262 .extension()
263 .and_then(|extension| extension.to_str())
264 {
265 let format = match extension.to_ascii_lowercase().as_str() {
266 "png" => ImageFormat::Png,
267 "jpg" | "jpeg" => ImageFormat::Jpeg,
268 "webp" => ImageFormat::Webp,
269 "gif" => ImageFormat::Gif,
270 "svg" => ImageFormat::Svg,
271 "bmp" => ImageFormat::Bmp,
272 "tif" | "tiff" => ImageFormat::Tiff,
273 "ico" => ImageFormat::Ico,
274 "pbm" | "pgm" | "ppm" | "pnm" => ImageFormat::Pnm,
275 _ => return None,
276 };
277 return Some(format);
278 }
279
280 image_format_from_bytes(bytes)
281}
282
283#[cfg(any(target_os = "macos", target_os = "windows"))]
284fn image_format_from_bytes(bytes: &[u8]) -> Option<ImageFormat> {
285 let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
286 if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
287 Some(ImageFormat::Png)
288 } else if bytes.starts_with(b"\xff\xd8\xff") {
289 Some(ImageFormat::Jpeg)
290 } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
291 Some(ImageFormat::Gif)
292 } else if bytes.starts_with(b"BM") {
293 Some(ImageFormat::Bmp)
294 } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
295 Some(ImageFormat::Webp)
296 } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
297 Some(ImageFormat::Tiff)
298 } else if bytes.starts_with(b"\0\0\x01\0") || bytes.starts_with(b"\0\0\x02\0") {
299 Some(ImageFormat::Ico)
300 } else if is_svg_bytes(bytes) {
301 Some(ImageFormat::Svg)
302 } else if matches!(
303 bytes.get(0..2),
304 Some(b"P1" | b"P2" | b"P3" | b"P4" | b"P5" | b"P6")
305 ) {
306 Some(ImageFormat::Pnm)
307 } else {
308 None
309 }
310}
311
312#[cfg(any(target_os = "macos", target_os = "windows"))]
313fn is_svg_bytes(bytes: &[u8]) -> bool {
314 let head = &bytes[..bytes.len().min(256)];
315 let text = match std::str::from_utf8(head) {
316 Ok(text) => text,
317 Err(err) if err.error_len().is_none() => {
320 std::str::from_utf8(&head[..err.valid_up_to()]).unwrap_or_default()
321 }
322 Err(_) => return false,
323 }
324 .trim_start();
325 text.starts_with("<svg") || text.starts_with("<?xml")
326}
327
328impl From<gpui::Menu> for NativeMenu {
334 fn from(menu: gpui::Menu) -> Self {
335 let mut native = Self::new();
336 for item in menu.items {
337 match item {
338 gpui::MenuItem::Separator => native.items.push(NativeMenuItem::Separator),
339 gpui::MenuItem::Action {
340 name,
341 action,
342 checked,
343 disabled,
344 ..
345 } => native.items.push(NativeMenuItem::Item {
346 label: name,
347 disabled,
348 checked,
349 icon: None,
350 action: Some(action),
351 }),
352 gpui::MenuItem::Submenu(submenu) => native.items.push(NativeMenuItem::Submenu {
353 label: submenu.name.clone(),
354 disabled: submenu.disabled,
355 items: Self::from(submenu).items,
356 }),
357 gpui::MenuItem::SystemMenu(_) => {}
358 }
359 }
360 native
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use crate::IconName;
368 use serde::Deserialize;
369
370 #[derive(Action, Clone, PartialEq, Deserialize)]
371 #[action(namespace = native_menu_tests, no_json)]
372 struct TestAction;
373
374 #[test]
375 fn test_native_menu_builder_accepts_icon() {
376 let menu =
377 NativeMenu::new().menu_with_icon("Github", IconName::Github, Box::new(TestAction));
378
379 assert_eq!(menu.items.len(), 1);
380 let NativeMenuItem::Item {
381 label,
382 disabled,
383 checked,
384 icon: Some(icon),
385 action: Some(_),
386 } = &menu.items[0]
387 else {
388 panic!("expected an actionable item with an icon");
389 };
390
391 assert_eq!(label, "Github");
392 assert!(!disabled);
393 assert!(!checked);
394 assert!(matches!(icon.source_ref(), IconSource::Path(path) if path == "icons/github.svg"));
395 }
396
397 #[test]
398 fn test_native_menu_builder_accepts_icon_and_disabled_alias() {
399 let menu = NativeMenu::new().menu_with_icon_and_disabled(
400 "Inbox",
401 IconName::Inbox,
402 Box::new(TestAction),
403 true,
404 );
405
406 assert_eq!(menu.items.len(), 1);
407 let NativeMenuItem::Item {
408 label,
409 disabled,
410 checked,
411 icon: Some(icon),
412 action: Some(_),
413 } = &menu.items[0]
414 else {
415 panic!("expected a disabled actionable item with an icon");
416 };
417
418 assert_eq!(label, "Inbox");
419 assert!(disabled);
420 assert!(!checked);
421 assert!(matches!(icon.source_ref(), IconSource::Path(path) if path.ends_with("inbox.svg")));
422 }
423
424 #[cfg(any(target_os = "macos", target_os = "windows"))]
426 mod icon_resolution {
427 use super::*;
428 use std::{borrow::Cow, fs, path::PathBuf};
429
430 const ASSET_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#;
431 const FILE_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg"><path/></svg>"#;
432
433 struct TestAssetSource(Option<&'static [u8]>);
434
435 impl AssetSource for TestAssetSource {
436 fn load(&self, _path: &str) -> gpui::Result<Option<Cow<'static, [u8]>>> {
437 Ok(self.0.map(Cow::Borrowed))
438 }
439
440 fn list(&self, _path: &str) -> gpui::Result<Vec<SharedString>> {
441 Ok(Vec::new())
442 }
443 }
444
445 struct TestIconFile(PathBuf);
451
452 impl TestIconFile {
453 fn create(path: impl Into<PathBuf>, bytes: &[u8]) -> Self {
454 let path = path.into();
455 assert!(
456 !path.exists(),
457 "leftover test file, delete it and re-run: {}",
458 path.display()
459 );
460 fs::write(&path, bytes).expect("test file should be written");
461 Self(path)
462 }
463 }
464
465 impl Drop for TestIconFile {
466 fn drop(&mut self) {
467 let _ = fs::remove_file(&self.0);
468 }
469 }
470
471 #[test]
472 fn test_native_menu_icon_asset_resolves_to_bytes() {
473 let icon = Icon::new(IconName::Github);
474 let image = resolve_icon_image(&icon, &gpui_kit_assets::Assets)
475 .expect("icon asset should resolve");
476
477 assert_eq!(image.format, ImageFormat::Svg);
478 assert!(!image.bytes.is_empty());
479 }
480
481 #[test]
482 fn test_relative_icon_path_only_uses_asset_source() {
483 let path: SharedString = "native-menu-relative-shadow-test.svg".into();
484 let _file = TestIconFile::create(path.as_ref(), FILE_SVG);
485
486 let icon = Icon::default().path(path);
487 let image = resolve_icon_image(&icon, &TestAssetSource(Some(ASSET_SVG)))
488 .expect("relative icon should resolve from the asset source");
489 assert_eq!(image.bytes, ASSET_SVG);
490
491 assert!(resolve_icon_image(&icon, &TestAssetSource(None)).is_none());
492 }
493
494 #[test]
495 fn test_absolute_icon_path_loads_from_filesystem() {
496 let path = std::env::current_dir()
497 .expect("test current directory should be available")
498 .join("native-menu-absolute-path-test.svg");
499 let _file = TestIconFile::create(&path, FILE_SVG);
500 let path: SharedString = path.to_string_lossy().into_owned().into();
501
502 let image = resolve_icon_image(
503 &Icon::default().path(path),
504 &TestAssetSource(Some(ASSET_SVG)),
505 )
506 .expect("absolute icon should resolve from the filesystem");
507 assert_eq!(image.bytes, FILE_SVG);
508 }
509
510 #[test]
511 fn test_svg_bytes_detected_when_256_byte_cut_splits_a_character() {
512 let mut svg = br#"<svg xmlns="http://www.w3.org/2000/svg"><title>"#.to_vec();
514 svg.resize(255, b'a');
515 svg.extend_from_slice("가</title></svg>".as_bytes());
516
517 assert_eq!(image_format_from_bytes(&svg), Some(ImageFormat::Svg));
518 }
519
520 #[test]
521 fn test_native_menu_icon_data_replaces_path_and_survives_clone() {
522 let icon = Icon::default().path("icons/previous.png").data(FILE_SVG);
523 let image = resolve_icon_image(&icon, &TestAssetSource(None))
524 .expect("SVG data should resolve without an asset source");
525 assert_eq!(image.format, ImageFormat::Svg);
526 assert_eq!(image.bytes, FILE_SVG);
527
528 let icon = icon.path("icons/replacement.svg");
529 let image = resolve_icon_image(&icon, &TestAssetSource(Some(ASSET_SVG)))
530 .expect("a later path should replace the data source");
531 assert_eq!(image.bytes, ASSET_SVG);
532 }
533 }
534}