From 413358ed85777c442eced43d2cc632dbd9b2e096 Mon Sep 17 00:00:00 2001 From: Yu-Wei Wu Date: Sun, 8 May 2022 14:32:31 +0800 Subject: [PATCH] Add init_for_nsapp --- README.md | 2 ++ examples/tao.rs | 5 +++++ examples/winit.rs | 5 +++++ src/lib.rs | 8 ++++++++ src/platform_impl/macos/mod.rs | 15 ++++++++++++++- 5 files changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3c74f61..4e923c2 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ let cut_item = file_menu.add_text_item("Cut", true); menu.init_for_hwnd(window.hwnd() as isize); #[cfg(target_os = "linux")] menu.init_for_gtk_window(>k_window); +#[cfg(target_os = "macos")] +menu.init_for_nsapp(); ``` Then listen for the events ```rs diff --git a/examples/tao.rs b/examples/tao.rs index 1aa0661..d6f4104 100644 --- a/examples/tao.rs +++ b/examples/tao.rs @@ -38,6 +38,11 @@ fn main() { menu_bar.init_for_gtk_window(window2.gtk_window()); } + #[cfg(target_os = "macos")] + { + menu_bar.init_for_nsapp(); + } + let menu_channel = menu_event_receiver(); let mut open_item_disabled = false; let mut counter = 0; diff --git a/examples/winit.rs b/examples/winit.rs index 5137c78..4861487 100644 --- a/examples/winit.rs +++ b/examples/winit.rs @@ -31,6 +31,11 @@ fn main() { menu_bar.init_for_hwnd(_window2.hwnd() as _); } + #[cfg(target_os = "macos")] + { + menu_bar.init_for_nsapp(); + } + let menu_channel = menu_event_receiver(); let mut open_item_disabled = false; let mut counter = 0; diff --git a/src/lib.rs b/src/lib.rs index e3ca153..aeb4822 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,6 +40,8 @@ //! menu.init_for_hwnd(window.hwnd() as isize); //! #[cfg(target_os = "linux")] //! menu.init_for_gtk_window(>k_window); +//! #[cfg(target_os = "macos")] +//! menu.init_for_nsapp(); //! ``` //! //! # Processing menu events @@ -118,6 +120,12 @@ impl Menu { pub fn init_for_hwnd(&self, hwnd: isize) { self.0.init_for_hwnd(hwnd) } + + /// Adds this menu to NSApp. + #[cfg(target_os = "macos")] + pub fn init_for_nsapp(&self) { + self.0.init_for_nsapp() + } } #[derive(Clone)] diff --git a/src/platform_impl/macos/mod.rs b/src/platform_impl/macos/mod.rs index 367ee15..b04eb7f 100644 --- a/src/platform_impl/macos/mod.rs +++ b/src/platform_impl/macos/mod.rs @@ -23,10 +23,23 @@ impl Menu { pub fn add_submenu(&mut self, label: impl AsRef, enabled: bool) -> Submenu { let mut sub_menu = Submenu(Menu::new()); - sub_menu.set_label(label); + sub_menu.set_label(label.as_ref()); sub_menu.set_enabled(enabled); + let item = TextMenuItem::new(label, enabled, sel!(fireMenubarAction:)); + + unsafe { + item.ns_menu_item.setSubmenu_(sub_menu.0 .0); + self.0.addItem_(item.ns_menu_item); + } + sub_menu } + + pub fn init_for_nsapp(&self) { + unsafe { + NSApp().setMainMenu_(self.0); + } + } } #[derive(Debug, Clone)]