BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / native_menu / macos.rs

macos.rs

macos.rs 7.3 KiB Download Raw
1//! macOS native menu implementation (AppKit `NSMenu` via objc2).
2
3use std::{cell::Cell, sync::Arc};
4
5use gpui::{Action, App, AssetSource, Pixels, Point, Window};
6use objc2::rc::Retained;
7use objc2::runtime::{AnyObject, NSObject};
8use objc2::{AnyThread, DefinedClass, MainThreadMarker, define_class, msg_send, sel};
9use objc2_app_kit::{NSImage, NSMenu, NSMenuItem, NSView};
10use objc2_foundation::{NSData, NSPoint, NSSize, NSString};
11use raw_window_handle::{HasWindowHandle, RawWindowHandle};
12
13use super::{NativeMenuItem, resolve_icon_image};
14
15/// Side length (in points) menu item images are scaled to. AppKit does not resize the image to fit
16/// the row, so a large file would otherwise overflow it.
17const MENU_IMAGE_SIZE: f64 = 16.0;
18
19/// Ivars for [`MenuTarget`]: the tag of the selected item, or `-1` if none.
20struct MenuTargetIvars {
21 selected: Cell<isize>,
22}
23
24define_class!(
25 // A throwaway Objective-C object that receives the menu item action and
26 // records which item (by tag) was clicked.
27 #[unsafe(super(NSObject))]
28 #[name = "GPUIComponentNativeMenuTarget"]
29 #[ivars = MenuTargetIvars]
30 struct MenuTarget;
31
32 impl MenuTarget {
33 #[unsafe(method(menuItemClicked:))]
34 fn menu_item_clicked(&self, sender: &NSMenuItem) {
35 self.ivars().selected.set(sender.tag());
36 }
37 }
38);
39
40impl MenuTarget {
41 fn new() -> Retained<Self> {
42 let this = Self::alloc().set_ivars(MenuTargetIvars {
43 selected: Cell::new(-1),
44 });
45 unsafe { msg_send![super(this), init] }
46 }
47}
48
49/// Show a native popup menu and dispatch the selected item's action.
50///
51/// The AppKit tracking loop is run from a foreground task so that GPUI is not
52/// borrowed while the menu is open.
53pub(super) fn show(
54 items: Vec<NativeMenuItem>,
55 asset_source: Arc<dyn AssetSource>,
56 position: Point<Pixels>,
57 window: &mut Window,
58 cx: &mut App,
59) {
60 let Some(view_ptr) = ns_view_ptr(window) else {
61 return;
62 };
63 // Inherent `Window::window_handle` (GPUI's `AnyWindowHandle`), not the
64 // `raw_window_handle::HasWindowHandle` trait method in scope below.
65 let handle = Window::window_handle(window);
66
67 cx.spawn(async move |cx| {
68 let action = run_menu(view_ptr, &items, asset_source.as_ref(), position);
69 let _ = cx.update(move |app| {
70 let _ = handle.update(app, move |_, window, app| {
71 if let Some(action) = action {
72 window.dispatch_action(action, app);
73 }
74 // Wake GPUI after the AppKit tracking loop returns so the window
75 // resumes painting and re-registers its mouse handlers. Without
76 // this, a dismissed menu (especially when nothing is selected)
77 // leaves the window idle and unresponsive to a second
78 // right-click.
79 window.refresh();
80 });
81 });
82 })
83 .detach();
84}
85
86/// Build the menu (recursively, including submenus), show it, and return the
87/// selected item's action.
88fn run_menu(
89 view_ptr: usize,
90 items: &[NativeMenuItem],
91 asset_source: &dyn AssetSource,
92 position: Point<Pixels>,
93) -> Option<Box<dyn Action>> {
94 let mtm = MainThreadMarker::new()?;
95 // SAFETY: `view_ptr` came from the window's AppKit handle, and the window
96 // outlives this synchronous call.
97 let view: &NSView = unsafe { &*(view_ptr as *const NSView) };
98
99 let target = MenuTarget::new();
100 let mut actions: Vec<&Box<dyn Action>> = Vec::new();
101 let ns_menu = build_menu(items, asset_source, &target, mtm, &mut actions);
102
103 // `position` is window-relative, logical pixels, origin top-left (GPUI).
104 // AppKit view coordinates have their origin at the bottom-left, so flip y.
105 let height = view.bounds().size.height;
106 let location = NSPoint::new(
107 f32::from(position.x) as f64,
108 height - f32::from(position.y) as f64,
109 );
110 ns_menu.popUpMenuPositioningItem_atLocation_inView(None, location, Some(view));
111
112 let tag = target.ivars().selected.get();
113 if tag >= 0 {
114 actions.get(tag as usize).map(|action| action.boxed_clone())
115 } else {
116 None
117 }
118}
119
120/// Recursively build an `NSMenu`. Each actionable leaf item is given a tag equal
121/// to its index in `actions`, so the selected tag maps back to its action.
122fn build_menu<'a>(
123 items: &'a [NativeMenuItem],
124 asset_source: &dyn AssetSource,
125 target: &MenuTarget,
126 mtm: MainThreadMarker,
127 actions: &mut Vec<&'a Box<dyn Action>>,
128) -> Retained<NSMenu> {
129 let menu = NSMenu::new(mtm);
130 // Items are configured explicitly, so disable AppKit's automatic enabling.
131 menu.setAutoenablesItems(false);
132
133 for item in items {
134 match item {
135 NativeMenuItem::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
136 NativeMenuItem::Item {
137 label,
138 disabled,
139 checked,
140 icon,
141 action,
142 } => {
143 let ns_item = NSMenuItem::new(mtm);
144 unsafe {
145 ns_item.setTitle(&NSString::from_str(label));
146 ns_item.setEnabled(!*disabled);
147 if let Some(icon) = icon {
148 if let Some(ns_image) = ns_image_for_icon(icon, asset_source) {
149 ns_image.setSize(NSSize::new(MENU_IMAGE_SIZE, MENU_IMAGE_SIZE));
150 ns_image.setTemplate(true);
151 ns_item.setImage(Some(&ns_image));
152 }
153 }
154
155 if *checked {
156 // `NSControlStateValueOn`
157 ns_item.setState(1);
158 }
159 if let Some(action) = action {
160 if !*disabled {
161 ns_item.setTag(actions.len() as isize);
162 actions.push(action);
163 ns_item.setTarget(Some(target as &AnyObject));
164 ns_item.setAction(Some(sel!(menuItemClicked:)));
165 }
166 }
167 }
168 menu.addItem(&ns_item);
169 }
170 NativeMenuItem::Submenu {
171 label,
172 disabled,
173 items,
174 } => {
175 let ns_item = NSMenuItem::new(mtm);
176 let submenu = build_menu(items, asset_source, target, mtm, actions);
177 ns_item.setTitle(&NSString::from_str(label));
178 ns_item.setEnabled(!*disabled);
179 ns_item.setSubmenu(Some(&submenu));
180 menu.addItem(&ns_item);
181 }
182 }
183 }
184
185 menu
186}
187
188fn ns_image_for_icon(
189 icon: &crate::Icon,
190 asset_source: &dyn AssetSource,
191) -> Option<Retained<NSImage>> {
192 let image = resolve_icon_image(icon, asset_source)?;
193 if image.bytes.is_empty() {
194 return None;
195 }
196
197 let data = unsafe {
198 NSData::dataWithBytes_length(image.bytes.as_ptr().cast(), image.bytes.len() as _)
199 };
200 NSImage::initWithData(NSImage::alloc(), &data)
201}
202
203/// Extract the AppKit `NSView` pointer from the window's raw handle.
204fn ns_view_ptr(window: &Window) -> Option<usize> {
205 let handle = HasWindowHandle::window_handle(window).ok()?;
206 let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
207 return None;
208 };
209 Some(handle.ns_view.as_ptr() as usize)
210}