BlueGit

ict rusty-teams

Files

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

windows.rs

windows.rs 17.6 KiB Download Raw
1//! Windows native menu implementation (Win32 popup menus).
2
3use std::{
4 ffi::c_void,
5 sync::{Arc, OnceLock},
6};
7
8use gpui::{Action, App, AssetSource, ImageFormat, Pixels, Point, Window};
9use raw_window_handle::{HasWindowHandle, RawWindowHandle};
10use windows::Win32::Foundation::{BOOL, GlobalFree, HANDLE, HWND, POINT};
11use windows::Win32::Graphics::Gdi::{
12 BI_RGB, BITMAPINFO, BITMAPINFOHEADER, ClientToScreen, CreateDIBSection, DIB_RGB_COLORS,
13 DeleteObject, HBITMAP, HDC, HGDIOBJ,
14};
15use windows::Win32::Graphics::GdiPlus::{
16 GdipCreateBitmapFromStream, GdipCreateHBITMAPFromBitmap, GdipDisposeImage,
17 GdipGetImageThumbnail, GdiplusShutdown, GdiplusStartup, GdiplusStartupInput, GpBitmap, GpImage,
18};
19use windows::Win32::System::Com::StructuredStorage::CreateStreamOnHGlobal;
20use windows::Win32::System::LibraryLoader::{
21 GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
22};
23use windows::Win32::System::Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock};
24use windows::Win32::UI::WindowsAndMessaging::{
25 AppendMenuW, CreatePopupMenu, DestroyMenu, HMENU, MENUITEMINFOW, MF_CHECKED, MF_GRAYED,
26 MF_POPUP, MF_SEPARATOR, MF_STRING, MIIM_BITMAP, SetForegroundWindow, SetMenuItemInfoW,
27 TPM_LEFTALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_TOPALIGN, TrackPopupMenuEx,
28};
29use windows::core::{PCSTR, PCWSTR};
30
31use super::{NativeMenuItem, resolve_icon_image};
32
33/// Side length (in **logical pixels**) menu item images are scaled to. The
34/// physical bitmap size is this multiplied by the window's scale factor (see
35/// [`show`]), so images stay sharp on the HiDPI displays.
36const MENU_IMAGE_SIZE: u32 = 16;
37
38/// Show a native popup menu and dispatch the selected item's action.
39///
40/// The Win32 tracking loop (`TrackPopupMenuEx`) blocks, so — like macOS — it is
41/// run from a foreground task to avoid re-entering GPUI while it is borrowed.
42pub(super) fn show(
43 items: Vec<NativeMenuItem>,
44 asset_source: Arc<dyn AssetSource>,
45 position: Point<Pixels>,
46 dark_mode: bool,
47 window: &mut Window,
48 cx: &mut App,
49) {
50 let Some(hwnd) = hwnd_ptr(window) else {
51 return;
52 };
53 // `position` is logical pixels; Win32 wants physical pixels.
54 let scale = window.scale_factor();
55 let client_x = (f32::from(position.x) * scale).round() as i32;
56 let client_y = (f32::from(position.y) * scale).round() as i32;
57 // The menu draws item bitmaps at their native pixel size, so rasterize them
58 // at the device pixel size to keep them sharp on HiDPI displays.
59 let image_px = (MENU_IMAGE_SIZE as f32 * scale).round().max(1.0) as u32;
60 // Inherent `Window::window_handle` (GPUI's `AnyWindowHandle`), not the
61 // `raw_window_handle::HasWindowHandle` trait method in scope below.
62 let handle = Window::window_handle(window);
63
64 cx.spawn(async move |cx| {
65 let Some(action) = run_menu(
66 hwnd,
67 &items,
68 asset_source.as_ref(),
69 client_x,
70 client_y,
71 image_px,
72 dark_mode,
73 ) else {
74 return;
75 };
76 cx.update(move |app| {
77 let _ = handle.update(app, move |_, window, app| {
78 window.dispatch_action(action, app);
79 });
80 });
81 })
82 .detach();
83}
84
85/// Build the menu (recursively, including submenus), show it, and return the
86/// selected item's action.
87fn run_menu(
88 hwnd: isize,
89 items: &[NativeMenuItem],
90 asset_source: &dyn AssetSource,
91 client_x: i32,
92 client_y: i32,
93 image_px: u32,
94 dark_mode: bool,
95) -> Option<Box<dyn Action>> {
96 let hwnd = HWND(hwnd as *mut c_void);
97
98 // SAFETY: Win32 menu calls on a live window owned by the calling (main)
99 // thread. The menu (and its submenus) is destroyed before returning.
100 unsafe {
101 // Start GDI+ so item images can be loaded into bitmaps. If it fails, the menu is still
102 // built (images are skipped).
103 let gdiplus = GdiplusSession::start();
104 let mut actions: Vec<&Box<dyn Action>> = Vec::new();
105
106 // Bitmaps attached to menu items must outlive the menu; freed below.
107 let mut bitmaps: Vec<HBITMAP> = Vec::new();
108 let menu = build_menu(items, asset_source, &mut actions, &mut bitmaps, image_px)?;
109
110 let mut point = POINT {
111 x: client_x,
112 y: client_y,
113 };
114 let _ = ClientToScreen(hwnd, &mut point);
115 // Required so the menu dismisses correctly when clicking elsewhere.
116 let _ = SetForegroundWindow(hwnd);
117 apply_menu_theme(hwnd, dark_mode);
118
119 let flags = TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RETURNCMD | TPM_NONOTIFY;
120 let selected = TrackPopupMenuEx(menu, flags.0, point.x, point.y, hwnd, None);
121 // Destroying the top menu also destroys its attached submenus.
122 let _ = DestroyMenu(menu);
123
124 // The menu no longer references the bitmaps, so they can be freed.
125 for bitmap in &bitmaps {
126 let _ = DeleteObject(HGDIOBJ(bitmap.0));
127 }
128 drop(gdiplus);
129
130 // Ids are 1-based (0 means "no selection"); map back to `actions`.
131 match selected.0 {
132 id if id > 0 => actions
133 .get((id - 1) as usize)
134 .map(|action| action.boxed_clone()),
135 _ => None,
136 }
137 }
138}
139
140/// Make Win32 popup menus follow the application's theme.
141///
142/// Windows does not expose a documented dark-mode API for `HMENU`. These
143/// dynamically resolved uxtheme entry points are used by Windows itself and
144/// degrade to the normal system menu when unavailable.
145unsafe fn apply_menu_theme(hwnd: HWND, dark_mode: bool) {
146 type AllowDarkModeForWindow = unsafe extern "system" fn(HWND, BOOL) -> BOOL;
147 type SetPreferredAppMode = unsafe extern "system" fn(i32) -> i32;
148 type FlushMenuThemes = unsafe extern "system" fn();
149
150 static UXTHEME_MODULE: OnceLock<isize> = OnceLock::new();
151 let module = *UXTHEME_MODULE.get_or_init(|| {
152 // Restrict this system DLL to System32 to prevent application-directory DLL planting.
153 unsafe {
154 LoadLibraryExW(
155 windows::core::w!("uxtheme.dll"),
156 HANDLE::default(),
157 LOAD_LIBRARY_SEARCH_SYSTEM32,
158 )
159 }
160 .map(|module| module.0 as isize)
161 .unwrap_or_default()
162 });
163 if module == 0 {
164 return;
165 }
166 let module = windows::Win32::Foundation::HMODULE(module as *mut c_void);
167
168 let allow_dark_mode = unsafe { GetProcAddress(module, PCSTR(133usize as *const u8)) };
169 let set_preferred_mode = unsafe { GetProcAddress(module, PCSTR(135usize as *const u8)) };
170 let flush_menu_themes = unsafe { GetProcAddress(module, PCSTR(136usize as *const u8)) };
171
172 if let Some(function) = allow_dark_mode {
173 let function: AllowDarkModeForWindow = unsafe { std::mem::transmute(function) };
174 let _ = unsafe { function(hwnd, BOOL::from(dark_mode)) };
175 }
176 if let Some(function) = set_preferred_mode {
177 let function: SetPreferredAppMode = unsafe { std::mem::transmute(function) };
178 const FORCE_DARK: i32 = 2;
179 const FORCE_LIGHT: i32 = 3;
180 let _ = unsafe { function(if dark_mode { FORCE_DARK } else { FORCE_LIGHT }) };
181 }
182 if let Some(function) = flush_menu_themes {
183 let function: FlushMenuThemes = unsafe { std::mem::transmute(function) };
184 unsafe { function() };
185 }
186}
187
188/// Recursively create an `HMENU`. Each actionable leaf gets a 1-based id equal
189/// to its index in `actions` plus one, so the returned id maps back to its action.
190///
191/// Any bitmaps created for item images are pushed onto `bitmaps`; the caller
192/// must free them after destroying the menu with `DeleteObject`. Item images
193/// are sized to `image_px` (physical pixels).
194///
195/// # Safety
196/// Win32 menu creation; the returned `HMENU` must be destroyed by the caller.
197unsafe fn build_menu<'a>(
198 items: &'a [NativeMenuItem],
199 asset_source: &dyn AssetSource,
200 actions: &mut Vec<&'a Box<dyn Action>>,
201 bitmaps: &mut Vec<HBITMAP>,
202 image_px: u32,
203) -> Option<HMENU> {
204 let menu = unsafe { CreatePopupMenu() }.ok()?;
205
206 // 0-based position of the next item appended, used to attach bitmaps by position (separators
207 // and submenus advance it too).
208 let mut position: u32 = 0;
209 for item in items {
210 match item {
211 NativeMenuItem::Separator => {
212 let _ = unsafe { AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null()) };
213 position += 1;
214 }
215 NativeMenuItem::Item {
216 label,
217 disabled,
218 checked,
219 icon,
220 action,
221 } => {
222 let mut flags = MF_STRING;
223 if *disabled {
224 flags |= MF_GRAYED;
225 }
226 if *checked {
227 flags |= MF_CHECKED;
228 }
229 let wide: Vec<u16> = label.encode_utf16().chain(std::iter::once(0)).collect();
230 // Actionable, enabled items get an id; others use 0.
231 let id = match action {
232 Some(action) if !*disabled => {
233 actions.push(action);
234 actions.len()
235 }
236 _ => 0,
237 };
238 let _ = unsafe { AppendMenuW(menu, flags, id, PCWSTR(wide.as_ptr())) };
239 if let Some(icon) = icon {
240 if let Some(bitmap) = unsafe { load_hbitmap(icon, asset_source, image_px) } {
241 let info = MENUITEMINFOW {
242 cbSize: std::mem::size_of::<MENUITEMINFOW>() as u32,
243 fMask: MIIM_BITMAP,
244 hbmpItem: bitmap,
245 ..Default::default()
246 };
247 let _ = unsafe { SetMenuItemInfoW(menu, position, true, &info) };
248 bitmaps.push(bitmap);
249 }
250 }
251 position += 1;
252 }
253 NativeMenuItem::Submenu {
254 label,
255 disabled,
256 items,
257 } => {
258 let Some(submenu) =
259 (unsafe { build_menu(items, asset_source, actions, bitmaps, image_px) })
260 else {
261 continue;
262 };
263 let mut flags = MF_POPUP;
264 if *disabled {
265 flags |= MF_GRAYED;
266 }
267 let wide: Vec<u16> = label.encode_utf16().chain(std::iter::once(0)).collect();
268 // For MF_POPUP, the id parameter is the submenu handle.
269 let _ =
270 unsafe { AppendMenuW(menu, flags, submenu.0 as usize, PCWSTR(wide.as_ptr())) };
271 position += 1;
272 }
273 }
274 }
275
276 Some(menu)
277}
278
279/// RAII guard for a GDI+ session (`GdiplusStartup` / `GdiplusShutdown`).
280///
281/// Loading image files into bitmaps requires GDI+ to be initialized. A `None` token means startup
282/// failed; image loading is then skipped gracefully.
283struct GdiplusSession {
284 token: usize,
285}
286
287impl GdiplusSession {
288 /// Start GDI+. Returns a guard whose `Drop` calls `GdiplusShutdown`.
289 unsafe fn start() -> Option<Self> {
290 let input = GdiplusStartupInput {
291 GdiplusVersion: 1,
292 DebugEventCallback: 0,
293 SuppressBackgroundThread: BOOL(0),
294 SuppressExternalCodecs: BOOL(0),
295 };
296
297 let mut token: usize = 0;
298 let status = unsafe { GdiplusStartup(&mut token, &input, std::ptr::null_mut()) };
299 if status.0 == 0 {
300 Some(Self { token })
301 } else {
302 None
303 }
304 }
305}
306
307impl Drop for GdiplusSession {
308 fn drop(&mut self) {
309 unsafe { GdiplusShutdown(self.token) };
310 }
311}
312
313/// Load an image into an `HBITMAP`, scaled to `image_px` square so it
314/// doesn't overflow the menu row.
315///
316/// SVG files are rasterized with `resvg` (see [`rasterize_svg`]); GDI+ has no
317/// SVG codec. Every other format (PNG, JPEG, BMP, ...) is decoded by GDI+, which
318/// must already be initialized (see [`GdiplusSession`]).
319///
320/// Returns `None` if the file can't be read or decoded. The returned bitmap
321/// must be freed with `DeleteObject`.
322///
323/// # Safety
324/// Calls GDI+ /GDI flat APIs; the returned handle is owned by the caller.
325unsafe fn load_hbitmap(
326 icon: &crate::Icon,
327 asset_source: &dyn AssetSource,
328 image_px: u32,
329) -> Option<HBITMAP> {
330 let image = resolve_icon_image(icon, asset_source)?;
331 if image.bytes.is_empty() {
332 return None;
333 }
334
335 if image.format == ImageFormat::Svg {
336 return unsafe { rasterize_svg(&image.bytes, image_px) };
337 }
338
339 let stream = unsafe { stream_from_bytes(&image.bytes) }?;
340 let mut gp_bitmap: *mut GpBitmap = std::ptr::null_mut();
341 let status = unsafe { GdipCreateBitmapFromStream(&stream, &mut gp_bitmap) };
342 if status.0 != 0 || gp_bitmap.is_null() {
343 return None;
344 }
345
346 unsafe { thumbnail_hbitmap(gp_bitmap, image_px) }
347}
348
349unsafe fn thumbnail_hbitmap(gp_bitmap: *mut GpBitmap, image_px: u32) -> Option<HBITMAP> {
350 // Scale to a menu icon sized thumbnail; GDI+ does not resize on display.
351 let mut thumb: *mut GpImage = std::ptr::null_mut();
352 let status = unsafe {
353 GdipGetImageThumbnail(
354 gp_bitmap.cast(),
355 image_px,
356 image_px,
357 &mut thumb,
358 0,
359 std::ptr::null_mut(),
360 )
361 };
362
363 unsafe { GdipDisposeImage(gp_bitmap.cast()) };
364 if status.0 != 0 || thumb.is_null() {
365 return None;
366 }
367
368 let mut hbitmap = HBITMAP::default();
369 // ARGB background 0 (fully transparent) for the alpha conversion.
370 let status = unsafe { GdipCreateHBITMAPFromBitmap(thumb.cast(), &mut hbitmap, 0) };
371
372 unsafe { GdipDisposeImage(thumb) };
373
374 if status.0 != 0 || hbitmap.is_invalid() {
375 None
376 } else {
377 Some(hbitmap)
378 }
379}
380
381unsafe fn stream_from_bytes(bytes: &[u8]) -> Option<windows::Win32::System::Com::IStream> {
382 let hglobal = unsafe { GlobalAlloc(GMEM_MOVEABLE, bytes.len()) }.ok()?;
383 let data = unsafe { GlobalLock(hglobal) };
384 if data.is_null() {
385 let _ = unsafe { GlobalFree(hglobal) };
386 return None;
387 }
388
389 unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len()) };
390 let _ = unsafe { GlobalUnlock(hglobal) };
391
392 match unsafe { CreateStreamOnHGlobal(hglobal, BOOL(1)) } {
393 Ok(stream) => Some(stream),
394 Err(_) => {
395 let _ = unsafe { GlobalFree(hglobal) };
396 None
397 }
398 }
399}
400
401/// Extract the Win32 `HWND` (as an `isize`) from the window's raw handle.
402fn hwnd_ptr(window: &Window) -> Option<isize> {
403 let handle = HasWindowHandle::window_handle(window).ok()?;
404 let RawWindowHandle::Win32(handle) = handle.as_raw() else {
405 return None;
406 };
407 Some(handle.hwnd.get())
408}
409
410/// Rasterize SVG bytes into an `HBITMAP`, scaled to `image_px` square.
411///
412/// GDI+ has no SVG codec, so SVG data is rendered with `resvg` and wrapped in a
413/// 32-bit DIB section. The SVG is scaled uniformly to fit the square and centered.
414/// Returns `None` if the SVG can't be parsed. The returned bitmap must be freed
415/// with `DeleteObject`.
416///
417/// # Safety
418/// Creates a GDI DIB section; the returned handle is owned by the caller.
419unsafe fn rasterize_svg(data: &[u8], image_px: u32) -> Option<HBITMAP> {
420 use resvg::{tiny_skia, usvg};
421
422 let tree = usvg::Tree::from_data(data, &usvg::Options::default()).ok()?;
423
424 let size = image_px;
425 let mut pixmap = tiny_skia::Pixmap::new(size, size)?;
426
427 // Fit the SVG into square without distortion, then center it.
428 let svg = tree.size();
429 let scale = (size as f32 / svg.width()).min(size as f32 / svg.height());
430 let tx = (size as f32 - svg.width() * scale) / 2.0;
431 let ty = (size as f32 - svg.height() * scale) / 2.0;
432 let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(tx, ty);
433
434 resvg::render(&tree, transform, &mut pixmap.as_mut());
435
436 // tiny-skia produces premultiplied RGBA; a 32 bit DIB is laid out RGBA, so
437 // swap the red and blue channels in place. The alpha is already
438 // premultiplied, which is what the menu's alpha blending expects.
439 let mut pixels = pixmap.take();
440 for px in pixels.chunks_exact_mut(4) {
441 px.swap(0, 2)
442 }
443
444 unsafe { create_dib(&pixels, size, size) }
445}
446
447/// Wrap premultiplied-RGBA `pixels` (top-down, `width` x `height`) in a 32-bit
448/// DIB section `HBITMAP`. Returns `None` if creation fails; the returned bitmap
449/// must be freed with `DeleteObject`.
450///
451/// # Safety
452/// Calls GDI flat APIs and copies `pixels` into the section's backing store,
453/// which must be `width * height * 4` bytes.
454unsafe fn create_dib(pixels: &[u8], width: u32, height: u32) -> Option<HBITMAP> {
455 let info = BITMAPINFO {
456 bmiHeader: BITMAPINFOHEADER {
457 biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
458 biWidth: width as i32,
459 // Negative height selects a top-down DIB (origin at top-left), matching
460 // tiny-skia's row order.
461 biHeight: -(height as i32),
462 biPlanes: 1,
463 biBitCount: 32,
464 biCompression: BI_RGB.0,
465 ..Default::default()
466 },
467 ..Default::default()
468 };
469
470 let mut bits: *mut c_void = std::ptr::null_mut();
471 // A null `HDC` is fine with `DIB_RGB_COLORS` (no palette to resolve).
472 let hbitmap = unsafe {
473 CreateDIBSection(
474 HDC::default(),
475 &info,
476 DIB_RGB_COLORS,
477 &mut bits,
478 HANDLE::default(),
479 0,
480 )
481 }
482 .ok()?;
483
484 if bits.is_null() {
485 let _ = unsafe { DeleteObject(HGDIOBJ(hbitmap.0)) };
486 return None;
487 }
488
489 unsafe { std::ptr::copy_nonoverlapping(pixels.as_ptr(), bits as *mut u8, pixels.len()) };
490 Some(hbitmap)
491}