eframe/native/app_icon.rs
1//! Set the native app icon at runtime.
2//!
3//! TODO(emilk): port this to [`winit`].
4
5use std::sync::Arc;
6
7use egui::IconData;
8
9pub struct AppTitleIconSetter {
10 title: String,
11 icon_data: Option<Arc<IconData>>,
12 status: AppIconStatus,
13}
14
15impl AppTitleIconSetter {
16 pub fn new(title: String, mut icon_data: Option<Arc<IconData>>) -> Self {
17 if let Some(icon) = &icon_data
18 && **icon == IconData::default()
19 {
20 icon_data = None;
21 }
22
23 Self {
24 title,
25 icon_data,
26 status: AppIconStatus::NotSetTryAgain,
27 }
28 }
29
30 /// Call once per frame; we will set the icon when we can.
31 pub fn update(&mut self) {
32 if self.status == AppIconStatus::NotSetTryAgain {
33 self.status = set_title_and_icon(&self.title, self.icon_data.as_deref());
34 }
35 }
36}
37
38/// In which state the app icon is (as far as we know).
39#[derive(PartialEq, Eq)]
40enum AppIconStatus {
41 /// We did not set it or failed to do it. In any case we won't try again.
42 NotSetIgnored,
43
44 /// We haven't set the icon yet, we should try again next frame.
45 ///
46 /// This can happen repeatedly due to lazy window creation on some platforms.
47 NotSetTryAgain,
48
49 /// We successfully set the icon and it should be visible now.
50 #[allow(clippy::allow_attributes, dead_code)] // Not used on Linux
51 Set,
52}
53
54/// Sets app icon at runtime.
55///
56/// By setting the icon at runtime and not via resource files etc. we ensure that we'll get the chance
57/// to set the same icon when the process/window is started from python (which sets its own icon ahead of us!).
58///
59/// Since window creation can be lazy, call this every frame until it's either successfully or gave up.
60/// (See [`AppIconStatus`])
61fn set_title_and_icon(_title: &str, _icon_data: Option<&IconData>) -> AppIconStatus {
62 profiling::function_scope!();
63
64 #[cfg(target_os = "windows")]
65 {
66 if let Some(icon_data) = _icon_data {
67 return set_app_icon_windows(icon_data);
68 }
69 }
70
71 #[cfg(target_os = "macos")]
72 return set_title_and_icon_mac(_title, _icon_data);
73
74 #[allow(clippy::allow_attributes, unreachable_code)]
75 AppIconStatus::NotSetIgnored
76}
77
78/// Set icon for Windows applications.
79#[cfg(target_os = "windows")]
80#[expect(unsafe_code)]
81fn set_app_icon_windows(icon_data: &IconData) -> AppIconStatus {
82 use crate::icon_data::IconDataExt as _;
83 use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
84 use windows_sys::Win32::UI::WindowsAndMessaging::{
85 CreateIconFromResourceEx, GetSystemMetrics, HICON, ICON_BIG, ICON_SMALL, LR_DEFAULTCOLOR,
86 SM_CXICON, SM_CXSMICON, SendMessageW, WM_SETICON,
87 };
88
89 // We would get fairly far already with winit's `set_window_icon` (which is exposed to eframe) actually!
90 // However, it only sets ICON_SMALL, i.e. doesn't allow us to set a higher resolution icon for the task bar.
91 // Also, there is scaling issues, detailed below.
92
93 // TODO(andreas): This does not set the task bar icon for when our application is started from python.
94 // Things tried so far:
95 // * Querying for an owning window and setting icon there (there doesn't seem to be an owning window)
96 // * using undocumented SetConsoleIcon method (successfully queried via GetProcAddress)
97
98 // SAFETY: WinApi function without side-effects.
99 let window_handle = unsafe { GetActiveWindow() };
100 if window_handle.is_null() {
101 // The Window isn't available yet. Try again later!
102 return AppIconStatus::NotSetTryAgain;
103 }
104
105 fn create_hicon_with_scale(unscaled_image: &image::RgbaImage, target_size: i32) -> HICON {
106 let image_scaled = image::imageops::resize(
107 unscaled_image,
108 target_size as _,
109 target_size as _,
110 image::imageops::Lanczos3,
111 );
112
113 // Creating transparent icons with WinApi is a huge mess.
114 // We'd need to go through CreateIconIndirect's ICONINFO struct which then
115 // takes a mask HBITMAP and a color HBITMAP and creating each of these is pain.
116 // Instead we workaround this by creating a png which CreateIconFromResourceEx magically understands.
117 // This is a pretty horrible hack as we spend a lot of time encoding, but at least the code is a lot shorter.
118 let mut image_scaled_bytes: Vec<u8> = Vec::new();
119 if image_scaled
120 .write_to(
121 &mut std::io::Cursor::new(&mut image_scaled_bytes),
122 image::ImageFormat::Png,
123 )
124 .is_err()
125 {
126 return core::ptr::null_mut();
127 }
128
129 // SAFETY: Creating an HICON which should be readonly on our data.
130 unsafe {
131 CreateIconFromResourceEx(
132 image_scaled_bytes.as_mut_ptr(),
133 image_scaled_bytes.len() as u32,
134 1, // Means this is an icon, not a cursor.
135 0x00030000, // Version number of the HICON
136 target_size, // Note that this method can scale, but it does so *very* poorly. So let's avoid that!
137 target_size,
138 LR_DEFAULTCOLOR,
139 )
140 }
141 }
142
143 let unscaled_image = match icon_data.to_image() {
144 Ok(unscaled_image) => unscaled_image,
145 Err(err) => {
146 log::warn!("Invalid icon: {err}");
147 return AppIconStatus::NotSetIgnored;
148 }
149 };
150
151 // Only setting ICON_BIG with the icon size for big icons (SM_CXICON) works fine
152 // but the scaling it does then for the small icon is pretty bad.
153 // Instead we set the correct sizes manually and take over the scaling ourselves.
154 // For this to work we first need to set the big icon and then the small one.
155 //
156 // Note that ICON_SMALL may be used even if we don't render a title bar as it may be used in alt+tab!
157 {
158 // SAFETY: WinAPI getter function with no known side effects.
159 let icon_size_big = unsafe { GetSystemMetrics(SM_CXICON) };
160 let icon_big = create_hicon_with_scale(&unscaled_image, icon_size_big);
161 if icon_big.is_null() {
162 log::warn!("Failed to create HICON (for big icon) from embedded png data.");
163 return AppIconStatus::NotSetIgnored; // We could try independently with the small icon but what's the point, it would look bad!
164 }
165
166 // SAFETY: Unsafe WinApi function, takes objects previously created with WinAPI, all checked for null prior.
167 unsafe {
168 SendMessageW(
169 window_handle,
170 WM_SETICON,
171 ICON_BIG as usize,
172 icon_big as isize,
173 );
174 }
175 }
176 {
177 // SAFETY: WinAPI getter function with no known side effects.
178 let icon_size_small = unsafe { GetSystemMetrics(SM_CXSMICON) };
179 let icon_small = create_hicon_with_scale(&unscaled_image, icon_size_small);
180 if icon_small.is_null() {
181 log::warn!("Failed to create HICON (for small icon) from embedded png data.");
182 return AppIconStatus::NotSetIgnored;
183 }
184
185 // SAFETY: Unsafe WinApi function, takes objects previously created with WinAPI, all checked for null prior.
186 unsafe {
187 SendMessageW(
188 window_handle,
189 WM_SETICON,
190 ICON_SMALL as usize,
191 icon_small as isize,
192 );
193 }
194 }
195
196 // It _probably_ worked out.
197 AppIconStatus::Set
198}
199
200/// Set icon & app title for `MacOS` applications.
201#[cfg(target_os = "macos")]
202#[expect(unsafe_code)]
203fn set_title_and_icon_mac(title: &str, icon_data: Option<&IconData>) -> AppIconStatus {
204 use crate::icon_data::IconDataExt as _;
205 profiling::function_scope!();
206
207 use objc2::AnyThread as _;
208 use objc2_app_kit::{NSApplication, NSImage};
209 use objc2_foundation::NSString;
210
211 // Do NOT use png even though creating `NSImage` from it is much easier than from raw images data!
212 //
213 // Some MacOS versions have a bug where creating an `NSImage` from a png will cause it to load an arbitrary `libpng.dylib`.
214 // If this dylib isn't the right version, the application will crash with SIGBUS.
215 // For details see https://github.com/emilk/egui/issues/7155
216 let image = if let Some(icon_data) = icon_data {
217 match icon_data.to_image() {
218 Ok(image) => Some(image),
219 Err(err) => {
220 log::warn!("Failed to read icon data: {err}");
221 return AppIconStatus::NotSetIgnored;
222 }
223 }
224 } else {
225 None
226 };
227
228 // TODO(madsmtm): Move this into `objc2-app-kit`
229 unsafe extern "C" {
230 static NSApp: Option<&'static NSApplication>;
231 }
232
233 // SAFETY: we don't do anything dangerous here
234 unsafe {
235 let Some(app) = NSApp else {
236 log::debug!("NSApp is null");
237 return AppIconStatus::NotSetIgnored;
238 };
239
240 if let Some(image) = image {
241 use objc2_app_kit::{NSBitmapImageRep, NSDeviceRGBColorSpace};
242 use objc2_foundation::NSSize;
243
244 log::trace!(
245 "NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel"
246 );
247 let Some(image_rep) = NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
248 NSBitmapImageRep::alloc(),
249 [image.as_raw().as_ptr().cast_mut()].as_mut_ptr(),
250 image.width() as isize,
251 image.height() as isize,
252 8, // bits per sample
253 4, // samples per pixel
254 true, // has alpha
255 false, // is not planar
256 NSDeviceRGBColorSpace,
257 (image.width() * 4) as isize, // bytes per row
258 32 // bits per pixel
259 ) else {
260 log::warn!("Failed to create NSBitmapImageRep from app icon data.");
261 return AppIconStatus::NotSetIgnored;
262 };
263
264 log::trace!("NSImage::initWithSize");
265 let app_icon = NSImage::initWithSize(
266 NSImage::alloc(),
267 NSSize::new(image.width() as f64, image.height() as f64),
268 );
269 log::trace!("NSImage::addRepresentation");
270 app_icon.addRepresentation(&image_rep);
271
272 profiling::scope!("setApplicationIconImage_");
273 log::trace!("setApplicationIconImageā¦");
274 app.setApplicationIconImage(Some(&app_icon));
275 }
276
277 // Change the title in the top bar - for python processes this would be again "python" otherwise.
278 if let Some(main_menu) = app.mainMenu()
279 && let Some(item) = main_menu.itemAtIndex(0)
280 && let Some(app_menu) = item.submenu()
281 {
282 profiling::scope!("setTitle_");
283 app_menu.setTitle(&NSString::from_str(title));
284 }
285
286 // The title in the Dock apparently can't be changed.
287 // At least these people didn't figure it out either:
288 // https://stackoverflow.com/questions/69831167/qt-change-application-title-dynamically-on-macos
289 // https://stackoverflow.com/questions/28808226/changing-cocoa-app-icon-title-and-menu-labels-at-runtime
290 }
291
292 AppIconStatus::Set
293}