Skip to content

Commit c735ba3

Browse files
Razshyrenovate[bot]Legend-Masterlucasfernog
authored
fix(codegen): select largest ICO entry instead of first (#15241)
* fix(codegen): select largest ICO entry instead of first * fix(runtime-wry): use exe resource icon on Windows * fix: cap codegen icon at 32x32, use exe resource for ICON_BIG * chore(deps): update dependency vitest to v4.1.0 [security] (#15462) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Remove setting taskbar icon > #15241 (comment) * Switch back to the biggest entry * Generate the ico in regular ascending order * fix(codegen): pick the largest ICO entry by area and depth, describe the post-#15274 scope Compare width*height (with bits_per_pixel as tie-breaker) instead of width alone, and panic with the icon path instead of a bare unwrap when the ICO has no entries. Since #15274 the Windows default window icon is read from the exe resource, so this only affects .ico files embedded via include_image! or as the tray icon; update the change file accordingly. * change from_app_icon_resource to load the largest icon too * add tests * readd size input * lint --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Tony <legendmastertony@gmail.com> Co-authored-by: Tony <68118705+Legend-Master@users.noreply.github.com> Co-authored-by: Lucas Nogueira <lucas@tauri.app>
1 parent 21ec647 commit c735ba3

5 files changed

Lines changed: 177 additions & 4 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"tauri-cli": patch:bug
3+
"@tauri-apps/cli": patch:bug
4+
---
5+
6+
Fix broken child window icons in Task Manager, you'll need to re-run `tauri icon` to generate the fixed icons

‎.changes/fix-ico-largest-entry.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri-codegen": patch:bug
3+
---
4+
5+
Select the largest entry of an ICO file instead of the first one when embedding it with `include_image!` or as the tray icon, so the OS downscales a high-resolution source instead of upscaling the 16x16 entry.

‎crates/tauri-cli/src/icon.rs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,7 @@ fn ico(source: &Source, out_dir: &Path) -> Result<()> {
451451
log::info!(action = "ICO"; "Creating icon.ico");
452452
let mut frames = Vec::new();
453453

454-
for size in [32, 16, 24, 48, 64, 256] {
454+
for size in [16, 24, 32, 48, 64, 256] {
455455
let image = source.resize_exact(size);
456456

457457
// Only the 256px layer can be compressed according to the ico specs.
@@ -1133,4 +1133,28 @@ mod tests {
11331133
assert_eq!(image.get_pixel(32, 2)[3], 0);
11341134
assert_eq!(image.get_pixel(32, 32)[3], 255);
11351135
}
1136+
1137+
#[test]
1138+
fn ico_stores_entries_smallest_first() {
1139+
let out_dir = tempfile::tempdir().unwrap();
1140+
ico(&landscape(64, 64), out_dir.path()).unwrap();
1141+
let bytes = std::fs::read(out_dir.path().join("icon.ico")).unwrap();
1142+
1143+
// ICONDIR: idReserved, idType and idCount (u16 each) followed by `idCount` 16-byte
1144+
// ICONDIRENTRY records starting with bWidth and bHeight, where 0 means 256
1145+
assert_eq!(&bytes[..4], &[0, 0, 1, 0]);
1146+
let count = u16::from_le_bytes([bytes[4], bytes[5]]) as usize;
1147+
let dimension = |b: u8| if b == 0 { 256 } else { u32::from(b) };
1148+
let sizes: Vec<_> = bytes[6..]
1149+
.as_chunks::<16>()
1150+
.0
1151+
.iter()
1152+
.take(count)
1153+
.map(|entry| (dimension(entry[0]), dimension(entry[1])))
1154+
.collect();
1155+
assert_eq!(
1156+
sizes,
1157+
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (256, 256)]
1158+
);
1159+
}
11361160
}

‎crates/tauri-codegen/src/image.rs‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ impl CachedIcon {
5454
let icon_dir = ico::IconDir::read(Cursor::new(&buf))
5555
.unwrap_or_else(|e| panic!("failed to parse icon {}: {}", icon.display(), e));
5656

57-
let entry = &icon_dir.entries()[0];
57+
let entry = largest_ico_entry(&icon_dir)
58+
.unwrap_or_else(|| panic!("icon {} has no entries", icon.display()));
5859
let rgba = entry
5960
.decode()
6061
.unwrap_or_else(|e| panic!("failed to decode icon {}: {}", icon.display(), e))
@@ -103,6 +104,17 @@ impl CachedIcon {
103104
}
104105
}
105106

107+
/// Picks the entry of an ICO file to embed: the largest one (and, for equal sizes, the deepest).
108+
///
109+
/// ICO files conventionally store entries smallest-first, so taking the first entry would give
110+
/// the OS a 16x16 image to upscale; the largest entry lets it downscale a high-resolution source instead.
111+
fn largest_ico_entry(icon_dir: &ico::IconDir) -> Option<&ico::IconDirEntry> {
112+
icon_dir
113+
.entries()
114+
.iter()
115+
.max_by_key(|e| (e.width() * e.height(), e.bits_per_pixel()))
116+
}
117+
106118
impl ToTokens for CachedIcon {
107119
fn to_tokens(&self, tokens: &mut TokenStream) {
108120
let root = &self.root;
@@ -116,3 +128,81 @@ impl ToTokens for CachedIcon {
116128
})
117129
}
118130
}
131+
132+
#[cfg(test)]
133+
mod tests {
134+
use super::largest_ico_entry;
135+
use ico::{IconDir, IconDirEntry, IconImage, ResourceType};
136+
use std::io::Cursor;
137+
138+
fn image(size: u32, alpha: u8) -> IconImage {
139+
let rgba = [255, 0, 0, alpha].repeat((size * size) as usize);
140+
IconImage::from_rgba_data(size, size, rgba)
141+
}
142+
143+
/// Builds an ICO with an opaque entry for each size, in the given order, and reads it back
144+
/// through the same parser `CachedIcon::new_ico` uses.
145+
fn icon_dir(sizes: &[u32]) -> IconDir {
146+
let mut dir = IconDir::new(ResourceType::Icon);
147+
for &size in sizes {
148+
let entry = if size == 256 {
149+
IconDirEntry::encode_as_png(&image(size, 255)).unwrap()
150+
} else {
151+
IconDirEntry::encode_as_bmp(&image(size, 255)).unwrap()
152+
};
153+
dir.add_entry(entry);
154+
}
155+
let mut buf = Vec::new();
156+
dir.write(&mut buf).unwrap();
157+
IconDir::read(Cursor::new(buf)).unwrap()
158+
}
159+
160+
#[test]
161+
fn picks_largest_entry_regardless_of_order() {
162+
// the entry order `tauri icon` used to generate, with the PNG-compressed 256 entry last
163+
let dir = icon_dir(&[32, 16, 24, 48, 64, 256]);
164+
let entry = largest_ico_entry(&dir).unwrap();
165+
assert_eq!((entry.width(), entry.height()), (256, 256));
166+
assert!(entry.is_png());
167+
168+
// largest first, in the middle and alone
169+
for sizes in [&[64, 48, 16][..], &[16, 64, 48], &[64]] {
170+
let dir = icon_dir(sizes);
171+
let entry = largest_ico_entry(&dir).unwrap();
172+
assert_eq!((entry.width(), entry.height()), (64, 64), "{sizes:?}");
173+
}
174+
}
175+
176+
#[test]
177+
fn picks_deepest_entry_for_equal_sizes() {
178+
// a single opaque color encodes as a low-depth BMP, a translucent one needs 32bpp
179+
let shallow = IconDirEntry::encode_as_bmp(&image(32, 255)).unwrap();
180+
let deep = IconDirEntry::encode_as_bmp(&image(32, 128)).unwrap();
181+
assert!(shallow.bits_per_pixel() < deep.bits_per_pixel());
182+
let deep_bpp = deep.bits_per_pixel();
183+
184+
for entries in [[shallow.clone(), deep.clone()], [deep, shallow]] {
185+
let mut dir = IconDir::new(ResourceType::Icon);
186+
for entry in entries {
187+
dir.add_entry(entry);
188+
}
189+
let entry = largest_ico_entry(&dir).unwrap();
190+
assert_eq!((entry.width(), entry.height()), (32, 32));
191+
assert_eq!(entry.bits_per_pixel(), deep_bpp);
192+
}
193+
}
194+
195+
#[test]
196+
fn selected_entry_decodes_at_its_own_size() {
197+
let dir = icon_dir(&[16, 256]);
198+
let entry = largest_ico_entry(&dir).unwrap();
199+
let decoded = entry.decode().unwrap();
200+
assert_eq!((decoded.width(), decoded.height()), (256, 256));
201+
assert_eq!(decoded.rgba_data().len(), 256 * 256 * 4);
202+
}
203+
204+
#[test]
205+
fn no_entries() {
206+
assert!(largest_ico_entry(&IconDir::new(ResourceType::Icon)).is_none());
207+
}
208+
}

‎crates/tauri/src/image/mod.rs‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ use windows::{
1919
},
2020
System::LibraryLoader::GetModuleHandleW,
2121
UI::WindowsAndMessaging::{
22-
GetIconInfo, HICON, ICONINFO, IMAGE_ICON, LR_DEFAULTCOLOR, LoadImageW,
22+
GetIconInfo, GetSystemMetrics, HICON, ICONINFO, IMAGE_ICON, LR_DEFAULTCOLOR, LoadImageW,
23+
SM_CXICON, SM_CYICON,
2324
},
2425
},
2526
core::{Owned, PCWSTR},
@@ -58,7 +59,20 @@ impl<'a> From<&'a str> for IconResource<'a> {
5859
#[cfg(windows)]
5960
#[doc(hidden)]
6061
pub fn default_window_icon_from_app_icon_resource() -> Option<Image<'static>> {
61-
match Image::from_app_icon_resource(64) {
62+
// the window icon is drawn in the title bar and, as a fallback for the taskbar icon,
63+
// at the system's large icon size (32x32 at 96 DPI, scaled with the system DPI),
64+
// so pick the entry Windows would use for the taskbar instead of a larger one it has to shrink
65+
// `GetSystemMetrics` returns 0 on failure
66+
let metric = |index| match unsafe { GetSystemMetrics(index) } {
67+
n if n > 0 => n as u32,
68+
_ => 32,
69+
};
70+
let (width, height) = (metric(SM_CXICON), metric(SM_CYICON));
71+
match Image::from_icon_resource(
72+
crate::utils::platform::WINDOWS_APP_ICON_RESOURCE_ID,
73+
width,
74+
height,
75+
) {
6276
Ok(icon) => Some(icon),
6377
Err(e) => {
6478
// a logger is usually not installed yet when `generate_context!` runs
@@ -477,3 +491,37 @@ impl JsImage {
477491
}
478492
}
479493
}
494+
495+
#[cfg(all(test, windows))]
496+
mod tests {
497+
use super::{IconResource, Image, default_window_icon_from_app_icon_resource};
498+
499+
/// The test executable has no icon resources, so every lookup must fail with an error
500+
/// (instead of panicking or returning a stretched placeholder).
501+
#[test]
502+
fn from_icon_resource_missing_resource_is_an_error() {
503+
for resource in [
504+
IconResource::Id(u16::MAX),
505+
IconResource::Name("tauri-image-test-missing-icon"),
506+
] {
507+
let error = Image::from_icon_resource(resource, 32, 32).unwrap_err();
508+
assert!(
509+
matches!(error, crate::Error::ImageFromResource(_)),
510+
"{resource:?}: {error:?}"
511+
);
512+
}
513+
514+
assert!(default_window_icon_from_app_icon_resource().is_none());
515+
}
516+
517+
#[test]
518+
fn from_icon_resource_rejects_invalid_sizes() {
519+
for (width, height) in [(0, 32), (32, 0), (u32::MAX, 32), (32, i32::MAX as u32 + 1)] {
520+
let error = Image::from_icon_resource(1, width, height).unwrap_err();
521+
assert!(
522+
matches!(error, crate::Error::ImageFromResource(_)),
523+
"{width}x{height}: {error:?}"
524+
);
525+
}
526+
}
527+
}

0 commit comments

Comments
 (0)