Skip to main content

winit/platform_impl/windows/
icon.rs

1use std::ffi::c_void;
2use std::path::Path;
3use std::sync::Arc;
4use std::{fmt, io, mem};
5
6use cursor_icon::CursorIcon;
7use windows_sys::core::PCWSTR;
8use windows_sys::Win32::Foundation::HWND;
9use windows_sys::Win32::Graphics::Gdi::{
10    CreateBitmap, CreateCompatibleBitmap, DeleteObject, GetDC, ReleaseDC, SetBitmapBits,
11};
12use windows_sys::Win32::UI::WindowsAndMessaging::{
13    CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, LoadImageW, SendMessageW, HCURSOR,
14    HICON, ICONINFO, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE, WM_SETICON,
15};
16
17use crate::cursor::CursorImage;
18use crate::dpi::PhysicalSize;
19use crate::icon::*;
20
21use super::util;
22
23impl Pixel {
24    fn convert_to_bgra(&mut self) {
25        mem::swap(&mut self.r, &mut self.b);
26    }
27}
28
29impl RgbaIcon {
30    fn into_windows_icon(self) -> Result<WinIcon, BadIcon> {
31        let rgba = self.rgba;
32        let pixel_count = rgba.len() / PIXEL_SIZE;
33        let mut and_mask = Vec::with_capacity(pixel_count);
34        let pixels =
35            unsafe { std::slice::from_raw_parts_mut(rgba.as_ptr() as *mut Pixel, pixel_count) };
36        for pixel in pixels {
37            and_mask.push(pixel.a.wrapping_sub(u8::MAX)); // invert alpha channel
38            pixel.convert_to_bgra();
39        }
40        assert_eq!(and_mask.len(), pixel_count);
41        let handle = unsafe {
42            CreateIcon(
43                0,
44                self.width as i32,
45                self.height as i32,
46                1,
47                (PIXEL_SIZE * 8) as u8,
48                and_mask.as_ptr(),
49                rgba.as_ptr(),
50            )
51        };
52        if handle != 0 {
53            Ok(WinIcon::from_handle(handle))
54        } else {
55            Err(BadIcon::OsError(io::Error::last_os_error()))
56        }
57    }
58}
59
60#[derive(Debug)]
61pub enum IconType {
62    Small = ICON_SMALL as isize,
63    Big = ICON_BIG as isize,
64}
65
66#[derive(Debug)]
67struct RaiiIcon {
68    handle: HICON,
69}
70
71#[derive(Clone)]
72pub struct WinIcon {
73    inner: Arc<RaiiIcon>,
74}
75
76unsafe impl Send for WinIcon {}
77
78impl WinIcon {
79    pub fn as_raw_handle(&self) -> HICON {
80        self.inner.handle
81    }
82
83    pub fn from_path<P: AsRef<Path>>(
84        path: P,
85        size: Option<PhysicalSize<u32>>,
86    ) -> Result<Self, BadIcon> {
87        // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size
88        let (width, height) = size.map(Into::into).unwrap_or((0, 0));
89
90        let wide_path = util::encode_wide(path.as_ref());
91
92        let handle = unsafe {
93            LoadImageW(
94                0,
95                wide_path.as_ptr(),
96                IMAGE_ICON,
97                width,
98                height,
99                LR_DEFAULTSIZE | LR_LOADFROMFILE,
100            )
101        };
102        if handle != 0 {
103            Ok(WinIcon::from_handle(handle as HICON))
104        } else {
105            Err(BadIcon::OsError(io::Error::last_os_error()))
106        }
107    }
108
109    pub fn from_resource(
110        resource_id: u16,
111        size: Option<PhysicalSize<u32>>,
112    ) -> Result<Self, BadIcon> {
113        Self::from_resource_ptr(resource_id as PCWSTR, size)
114    }
115
116    pub fn from_resource_name(
117        resource_name: &str,
118        size: Option<PhysicalSize<u32>>,
119    ) -> Result<Self, BadIcon> {
120        let wide_name = util::encode_wide(resource_name);
121        Self::from_resource_ptr(wide_name.as_ptr(), size)
122    }
123
124    fn from_resource_ptr(
125        resource: PCWSTR,
126        size: Option<PhysicalSize<u32>>,
127    ) -> Result<Self, BadIcon> {
128        // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size
129        let (width, height) = size.map(Into::into).unwrap_or((0, 0));
130        let handle = unsafe {
131            LoadImageW(
132                util::get_instance_handle(),
133                resource,
134                IMAGE_ICON,
135                width,
136                height,
137                LR_DEFAULTSIZE,
138            )
139        };
140        if handle != 0 {
141            Ok(WinIcon::from_handle(handle as HICON))
142        } else {
143            Err(BadIcon::OsError(io::Error::last_os_error()))
144        }
145    }
146
147    pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
148        let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?;
149        rgba_icon.into_windows_icon()
150    }
151
152    pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) {
153        unsafe {
154            SendMessageW(hwnd, WM_SETICON, icon_type as usize, self.as_raw_handle());
155        }
156    }
157
158    fn from_handle(handle: HICON) -> Self {
159        Self { inner: Arc::new(RaiiIcon { handle }) }
160    }
161}
162
163impl Drop for RaiiIcon {
164    fn drop(&mut self) {
165        unsafe { DestroyIcon(self.handle) };
166    }
167}
168
169impl fmt::Debug for WinIcon {
170    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
171        (*self.inner).fmt(formatter)
172    }
173}
174
175pub fn unset_for_window(hwnd: HWND, icon_type: IconType) {
176    unsafe {
177        SendMessageW(hwnd, WM_SETICON, icon_type as usize, 0);
178    }
179}
180
181#[derive(Debug, Clone)]
182pub enum SelectedCursor {
183    Named(CursorIcon),
184    Custom(Arc<RaiiCursor>),
185}
186
187impl Default for SelectedCursor {
188    fn default() -> Self {
189        Self::Named(Default::default())
190    }
191}
192
193#[derive(Clone, Debug, Hash, Eq, PartialEq)]
194pub enum WinCursor {
195    Cursor(Arc<RaiiCursor>),
196    Failed,
197}
198
199impl WinCursor {
200    pub(crate) fn new(image: &CursorImage) -> Result<Self, io::Error> {
201        let mut bgra = image.rgba.clone();
202        bgra.chunks_exact_mut(4).for_each(|chunk| chunk.swap(0, 2));
203
204        let w = image.width as i32;
205        let h = image.height as i32;
206
207        unsafe {
208            let hdc_screen = GetDC(0);
209            if hdc_screen == 0 {
210                return Err(io::Error::last_os_error());
211            }
212            let hbm_color = CreateCompatibleBitmap(hdc_screen, w, h);
213            ReleaseDC(0, hdc_screen);
214            if hbm_color == 0 {
215                return Err(io::Error::last_os_error());
216            }
217            if SetBitmapBits(hbm_color, bgra.len() as u32, bgra.as_ptr() as *const c_void) == 0 {
218                DeleteObject(hbm_color);
219                return Err(io::Error::last_os_error());
220            };
221
222            // Mask created according to https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-createbitmap#parameters
223            let mask_bits: Vec<u8> = vec![0xff; ((((w + 15) >> 4) << 1) * h) as usize];
224            let hbm_mask = CreateBitmap(w, h, 1, 1, mask_bits.as_ptr() as *const _);
225            if hbm_mask == 0 {
226                DeleteObject(hbm_color);
227                return Err(io::Error::last_os_error());
228            }
229
230            let icon_info = ICONINFO {
231                fIcon: 0,
232                xHotspot: image.hotspot_x as u32,
233                yHotspot: image.hotspot_y as u32,
234                hbmMask: hbm_mask,
235                hbmColor: hbm_color,
236            };
237
238            let handle = CreateIconIndirect(&icon_info as *const _);
239            DeleteObject(hbm_color);
240            DeleteObject(hbm_mask);
241            if handle == 0 {
242                return Err(io::Error::last_os_error());
243            }
244
245            Ok(Self::Cursor(Arc::new(RaiiCursor { handle })))
246        }
247    }
248}
249
250#[derive(Debug, Hash, Eq, PartialEq)]
251pub struct RaiiCursor {
252    handle: HCURSOR,
253}
254
255impl Drop for RaiiCursor {
256    fn drop(&mut self) {
257        unsafe { DestroyCursor(self.handle) };
258    }
259}
260
261impl RaiiCursor {
262    pub fn as_raw_handle(&self) -> HICON {
263        self.handle
264    }
265}