Skip to main content

gpui_component/native_menu/
mod.rs

1//! A menu rendered natively by the operating system.
2//!
3//! Unlike [`crate::menu::PopupMenu`], which is drawn by GPUI and therefore
4//! clipped to the window bounds, [`NativeMenu`] is rendered by the OS. It can
5//! extend beyond the window — useful for small windows where a GPUI-drawn popup
6//! menu would otherwise be cut off.
7//!
8//! Items carry a GPUI [`Action`], dispatched via [`Window::dispatch_action`]
9//! when selected — the same mechanism the application menu bar and key bindings
10//! use. A [`NativeMenu`] can therefore be built directly from GPUI
11//! [`gpui::MenuItem`]s (see [`NativeMenu::from_menu_items`] /
12//! [`From<gpui::Menu>`]).
13//!
14//! ```ignore
15//! use gpui_kit::component::native_menu::NativeMenu;
16//!
17//! NativeMenu::new()
18//!     .menu("Copy", Box::new(Copy))
19//!     .menu("Paste", Box::new(Paste))
20//!     .separator()
21//!     .menu("Delete", Box::new(Delete))
22//!     .show(position, window, cx);
23//! ```
24
25#[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", test))]
32use gpui::AssetRegistry;
33use gpui::{Action, App, Pixels, Point, SharedString, Window};
34#[cfg(any(target_os = "macos", target_os = "windows", test))]
35use gpui::{Image, ImageFormat};
36#[cfg(any(target_os = "macos", target_os = "windows", test))]
37use std::{path::Path, sync::Arc};
38
39#[cfg(target_os = "macos")]
40mod macos;
41#[cfg(target_os = "windows")]
42mod windows;
43
44// Drawn-menu fallback (used on platforms without an OS-native popup, e.g. Linux).
45// Compiled on all platforms because `Root` holds the overlay entity.
46mod fallback;
47pub(crate) use fallback::FallbackMenuOverlay;
48
49enum NativeMenuItem {
50    Separator,
51    Item {
52        label: SharedString,
53        disabled: bool,
54        checked: bool,
55        /// Icon shown next to the label.
56        icon: Option<Box<Icon>>,
57        /// Action dispatched when the item is selected.
58        action: Option<Box<dyn Action>>,
59    },
60    Submenu {
61        label: SharedString,
62        disabled: bool,
63        items: Vec<NativeMenuItem>,
64    },
65}
66
67/// A menu rendered by the operating system.
68///
69/// Build it with the [`NativeMenu::menu`] / [`NativeMenu::separator`] builders,
70/// then call [`NativeMenu::show`] to display it at a position.
71#[derive(Default)]
72pub struct NativeMenu {
73    items: Vec<NativeMenuItem>,
74}
75
76impl NativeMenu {
77    /// Create an empty native menu.
78    pub fn new() -> Self {
79        Self::default()
80    }
81
82    /// Append a clickable item that dispatches `action` when selected.
83    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    /// Append an item, controlling its `disabled` state.
88    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    /// Append an item, controlling its `checked` state (a check mark is shown).
98    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    /// Append an item showing `icon` next to its label.
108    ///
109    /// Native platform menus load absolute paths ([`Path::is_absolute`]) from the filesystem,
110    /// and every other path through the application [`gpui::AssetRegistry`].
111    /// Icons created with [`Icon::data`] use their SVG bytes directly, without an asset lookup.
112    /// [`crate::IconName`] resolves as an asset and works across all backends.
113    /// - **macOS**: loaded into an `NSImage` as a template image, so it tints with the item
114    /// text and assigned to the item ([`NSMenuItem::image`]).
115    /// - **Windows**: loaded into an `HBITMAP` and set as the item's
116    /// content bitmap (`MENUITEMINFOW::hbmpItem`), shown beside the label. SVG files are
117    /// rasterized, with `resvg`; other formats (PNG, JPEG, BMP, ...) are decoded by GDI+.
118    /// **Other platforms** (fallback): rendered as the menu item's [`crate::Icon`].
119    ///
120    /// Note: this is the menu item's *content* icon, not its state/check-mark indicator.
121    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    /// Append an item showing `icon` next to its label, controlling its `disabled` state.
131    ///
132    /// Same icon behavior as [`Self::menu_with_icon`]. Use this when an item
133    /// carries an icon but should be greyed out.
134    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    /// Add Menu Item with Icon and disabled state.
145    ///
146    /// Alias for [`Self::menu_with_icon_disabled`], matching [`crate::menu::PopupMenu`].
147    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    /// Append a separator line.
176    pub fn separator(mut self) -> Self {
177        self.items.push(NativeMenuItem::Separator);
178        self
179    }
180
181    /// Append a submenu built from another [`NativeMenu`].
182    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    /// Whether the menu has no items.
192    pub fn is_empty(&self) -> bool {
193        self.items.is_empty()
194    }
195
196    /// Pop up the menu at `position` (window coordinates, in logical pixels).
197    ///
198    /// The menu is shown without blocking the caller: the OS tracking loop runs
199    /// off GPUI's call stack, so GPUI is not borrowed while it is open. When an
200    /// item is selected, its action is dispatched via [`Window::dispatch_action`].
201    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.assets().clone(), position, window, cx);
209        }
210        #[cfg(target_os = "windows")]
211        {
212            windows::show(
213                self.items,
214                cx.assets().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", test))]
227pub(super) fn resolve_icon_image(icon: &Icon, assets: &AssetRegistry) -> Option<Arc<Image>> {
228    let path = match icon.source_ref() {
229        IconSource::Path(path) => path,
230        IconSource::Data(bytes) => {
231            return Some(Arc::new(Image::from_bytes(
232                ImageFormat::Svg,
233                bytes.to_vec(),
234            )));
235        }
236    };
237    if path.is_empty() {
238        return None;
239    }
240
241    let icon_path = Path::new(path.as_ref());
242    // Relative paths are asset identifiers and must not resolve against the process CWD.
243    let bytes = if icon_path.is_absolute() {
244        std::fs::read(icon_path).ok()?
245    } else {
246        assets.load(path.as_ref())?.into_owned()
247    };
248    let format = image_format(path.as_ref(), &bytes)?;
249    Some(Arc::new(Image::from_bytes(format, bytes)))
250}
251
252#[cfg(any(target_os = "macos", target_os = "windows", test))]
253fn image_format(path: &str, bytes: &[u8]) -> Option<ImageFormat> {
254    if let Some(extension) = Path::new(path)
255        .extension()
256        .and_then(|extension| extension.to_str())
257    {
258        let format = match extension.to_ascii_lowercase().as_str() {
259            "png" => ImageFormat::Png,
260            "jpg" | "jpeg" => ImageFormat::Jpeg,
261            "webp" => ImageFormat::Webp,
262            "gif" => ImageFormat::Gif,
263            "svg" => ImageFormat::Svg,
264            "bmp" => ImageFormat::Bmp,
265            "tif" | "tiff" => ImageFormat::Tiff,
266            "ico" => ImageFormat::Ico,
267            "pbm" | "pgm" | "ppm" | "pnm" => ImageFormat::Pnm,
268            _ => return None,
269        };
270        return Some(format);
271    }
272
273    image_format_from_bytes(bytes)
274}
275
276#[cfg(any(target_os = "macos", target_os = "windows", test))]
277fn image_format_from_bytes(bytes: &[u8]) -> Option<ImageFormat> {
278    let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
279    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
280        Some(ImageFormat::Png)
281    } else if bytes.starts_with(b"\xff\xd8\xff") {
282        Some(ImageFormat::Jpeg)
283    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
284        Some(ImageFormat::Gif)
285    } else if bytes.starts_with(b"BM") {
286        Some(ImageFormat::Bmp)
287    } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
288        Some(ImageFormat::Webp)
289    } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
290        Some(ImageFormat::Tiff)
291    } else if bytes.starts_with(b"\0\0\x01\0") || bytes.starts_with(b"\0\0\x02\0") {
292        Some(ImageFormat::Ico)
293    } else if is_svg_bytes(bytes) {
294        Some(ImageFormat::Svg)
295    } else if matches!(
296        bytes.get(0..2),
297        Some(b"P1" | b"P2" | b"P3" | b"P4" | b"P5" | b"P6")
298    ) {
299        Some(ImageFormat::Pnm)
300    } else {
301        None
302    }
303}
304
305#[cfg(any(target_os = "macos", target_os = "windows", test))]
306fn is_svg_bytes(bytes: &[u8]) -> bool {
307    let text = match std::str::from_utf8(&bytes[..bytes.len().min(256)]) {
308        Ok(text) => text.trim_start(),
309        Err(_) => return false,
310    };
311    text.starts_with("<svg") || text.starts_with("<?xml")
312}
313
314/// Reuse an existing GPUI menu definition as a native menu.
315///
316/// `Action`s, separators, submenus, `checked`, and `disabled` are mapped over;
317/// system menus (e.g. macOS Services) have no native popup equivalent and are
318/// skipped.
319impl From<gpui::Menu> for NativeMenu {
320    fn from(menu: gpui::Menu) -> Self {
321        let mut native = Self::new();
322        for item in menu.items {
323            match item {
324                gpui::MenuItem::Separator => native.items.push(NativeMenuItem::Separator),
325                gpui::MenuItem::Action {
326                    name,
327                    action,
328                    checked,
329                    disabled,
330                    ..
331                } => native.items.push(NativeMenuItem::Item {
332                    label: name,
333                    disabled,
334                    checked,
335                    icon: None,
336                    action: Some(action),
337                }),
338                gpui::MenuItem::Submenu(submenu) => native.items.push(NativeMenuItem::Submenu {
339                    label: submenu.name.clone(),
340                    disabled: submenu.disabled,
341                    items: Self::from(submenu).items,
342                }),
343                gpui::MenuItem::SystemMenu(_) => {}
344            }
345        }
346        native
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use crate::IconName;
354    use serde::Deserialize;
355
356    #[derive(Action, Clone, PartialEq, Deserialize)]
357    #[action(namespace = native_menu_tests, no_json)]
358    struct TestAction;
359
360    #[test]
361    fn test_native_menu_builder_accepts_icon() {
362        let menu =
363            NativeMenu::new().menu_with_icon("Github", IconName::Github, Box::new(TestAction));
364
365        assert_eq!(menu.items.len(), 1);
366        let NativeMenuItem::Item {
367            label,
368            disabled,
369            checked,
370            icon: Some(icon),
371            action: Some(_),
372        } = &menu.items[0]
373        else {
374            panic!("expected an actionable item with an icon");
375        };
376
377        assert_eq!(label, "Github");
378        assert!(!disabled);
379        assert!(!checked);
380        assert!(matches!(icon.source_ref(), IconSource::Path(path) if path == "icons/github.svg"));
381    }
382
383    #[test]
384    fn test_native_menu_builder_accepts_icon_and_disabled_alias() {
385        let menu = NativeMenu::new().menu_with_icon_and_disabled(
386            "Inbox",
387            IconName::Inbox,
388            Box::new(TestAction),
389            true,
390        );
391
392        assert_eq!(menu.items.len(), 1);
393        let NativeMenuItem::Item {
394            label,
395            disabled,
396            checked,
397            icon: Some(icon),
398            action: Some(_),
399        } = &menu.items[0]
400        else {
401            panic!("expected a disabled actionable item with an icon");
402        };
403
404        assert_eq!(label, "Inbox");
405        assert!(disabled);
406        assert!(!checked);
407        assert!(matches!(icon.source_ref(), IconSource::Path(path) if path.ends_with("inbox.svg")));
408    }
409
410    // Exercise native icon lookup on every test host, including Linux.
411    mod icon_resolution {
412        use super::*;
413        use std::{borrow::Cow, fs, path::PathBuf};
414
415        const ASSET_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#;
416        const FILE_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg"><path/></svg>"#;
417
418        fn assets(path: impl Into<SharedString>, bytes: &'static [u8]) -> AssetRegistry {
419            let mut assets = AssetRegistry::default();
420            assets.insert(path, Cow::Borrowed(bytes)).unwrap();
421            assets
422        }
423
424        /// A file written into the current directory for the duration of one test.
425        ///
426        /// The shadowing tests need a file the process would find by walking a *relative*
427        /// path, so it has to live in the current directory rather than a temporary one.
428        /// Nothing else is created alongside it, so dropping the file leaves no residue.
429        struct TestIconFile(PathBuf);
430
431        impl TestIconFile {
432            fn create(path: impl Into<PathBuf>, bytes: &[u8]) -> Self {
433                let path = path.into();
434                assert!(
435                    !path.exists(),
436                    "leftover test file, delete it and re-run: {}",
437                    path.display()
438                );
439                fs::write(&path, bytes).expect("test file should be written");
440                Self(path)
441            }
442        }
443
444        impl Drop for TestIconFile {
445            fn drop(&mut self) {
446                let _ = fs::remove_file(&self.0);
447            }
448        }
449
450        #[test]
451        fn test_native_menu_icon_asset_resolves_to_bytes() {
452            let icon = Icon::new(IconName::Github);
453            let image = resolve_icon_image(&icon, &AssetRegistry::from(gpui_kit_assets::Assets))
454                .expect("icon asset should resolve");
455
456            assert_eq!(image.format, ImageFormat::Svg);
457            assert!(!image.bytes.is_empty());
458        }
459
460        #[test]
461        fn test_relative_icon_path_only_uses_assets() {
462            let path: SharedString = "native-menu-relative-shadow-test.svg".into();
463            let _file = TestIconFile::create(path.as_ref(), FILE_SVG);
464
465            let icon = Icon::default().path(path.clone());
466            let image = resolve_icon_image(&icon, &assets(path, ASSET_SVG))
467                .expect("relative icon should resolve from the asset source");
468            assert_eq!(image.bytes, ASSET_SVG);
469
470            assert!(resolve_icon_image(&icon, &AssetRegistry::default()).is_none());
471        }
472
473        #[test]
474        fn test_on_demand_icon_uses_the_registry_loader() {
475            let mut assets = AssetRegistry::default();
476            assets
477                .insert("icons/on-demand.svg", || Some(Cow::Borrowed(ASSET_SVG)))
478                .unwrap();
479            let image = resolve_icon_image(&Icon::default().path("icons/on-demand.svg"), &assets)
480                .expect("on-demand registry entries should resolve");
481            assert_eq!(image.bytes, ASSET_SVG);
482        }
483
484        #[test]
485        fn test_absolute_icon_path_loads_from_filesystem() {
486            let path = std::env::current_dir()
487                .expect("test current directory should be available")
488                .join("native-menu-absolute-path-test.svg");
489            let _file = TestIconFile::create(&path, FILE_SVG);
490            let path: SharedString = path.to_string_lossy().into_owned().into();
491
492            let image = resolve_icon_image(
493                &Icon::default().path(path.clone()),
494                &assets(path, ASSET_SVG),
495            )
496            .expect("absolute icon should resolve from the filesystem");
497            assert_eq!(image.bytes, FILE_SVG);
498        }
499
500        #[test]
501        fn test_native_menu_icon_data_replaces_path_and_survives_clone() {
502            let icon = Icon::default().path("icons/previous.png").data(FILE_SVG);
503            let image = resolve_icon_image(&icon.clone(), &AssetRegistry::default())
504                .expect("SVG data should resolve without an asset source");
505            assert_eq!(image.format, ImageFormat::Svg);
506            assert_eq!(image.bytes, FILE_SVG);
507
508            let icon = icon.path("icons/replacement.svg");
509            let image = resolve_icon_image(&icon, &assets("icons/replacement.svg", ASSET_SVG))
510                .expect("a later path should replace the data source");
511            assert_eq!(image.bytes, ASSET_SVG);
512        }
513    }
514}