#![allow(unsafe_code)]
use crate::IconData;
#[cfg(target_os = "windows")]
use std::mem;
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Gdi::*;
#[cfg(target_os = "windows")]
use windows::Win32::UI::Shell::*;
#[cfg(target_os = "windows")]
use windows::Win32::UI::WindowsAndMessaging::*;
#[cfg(target_os = "windows")]
use windows::core::PCWSTR;
const DEFAULT_ICON_SIZE: i32 = 32;
fn glyph_codepoint(name: &str) -> Option<u32> {
Some(match name {
"ChromeClose" => 0xE8BB,
"ChromeMinimize" => 0xE921,
"ChromeMaximize" => 0xE922,
"ChromeRestore" => 0xE923,
"Save" => 0xE74E,
"Copy" => 0xE8C8,
"Paste" => 0xE77F,
"Cut" => 0xE8C6,
"Undo" => 0xE7A7,
"Redo" => 0xE7A6,
"Edit" => 0xE70F,
"Add" => 0xE710,
"Remove" => 0xE738,
"Refresh" => 0xE72C,
"Search" => 0xE721,
"Settings" => 0xE713,
"Delete" => 0xE74D,
"Print" => 0xE749,
"Back" => 0xE72B,
"Forward" => 0xE72A,
"Up" => 0xE74A,
"Down" => 0xE74B,
"Home" => 0xE80F,
"GlobalNavigationButton" => 0xE700,
"CheckMark" => 0xE73E,
"Ringer" => 0xEA8F,
_ => return None,
})
}
#[cfg(target_os = "windows")]
fn siid_from_name(name: &str) -> Option<SHSTOCKICONID> {
Some(match name {
"SIID_WARNING" => SIID_WARNING,
"SIID_ERROR" => SIID_ERROR,
"SIID_INFO" => SIID_INFO,
"SIID_SHIELD" => SIID_SHIELD,
"SIID_DELETE" => SIID_DELETE,
"SIID_FIND" => SIID_FIND,
"SIID_SETTINGS" => SIID_SETTINGS,
"SIID_PRINTER" => SIID_PRINTER,
"SIID_DOCNOASSOC" => SIID_DOCNOASSOC,
"SIID_FOLDER" => SIID_FOLDER,
"SIID_FOLDEROPEN" => SIID_FOLDEROPEN,
"SIID_RECYCLER" => SIID_RECYCLER,
"SIID_RECYCLERFULL" => SIID_RECYCLERFULL,
"SIID_USERS" => SIID_USERS,
"SIID_HELP" => SIID_HELP,
"SIID_LOCK" => SIID_LOCK,
_ => return None,
})
}
fn bgra_to_rgba(pixels: &mut [u8]) {
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
}
fn gray8_to_rgba(gray: u8) -> [u8; 4] {
#[allow(clippy::integer_division, clippy::arithmetic_side_effects)]
let alpha = (u32::from(gray).saturating_mul(255) / 64).min(255) as u8;
[255, 255, 255, alpha]
}
#[cfg(target_os = "windows")]
unsafe fn hicon_to_rgba(hicon: HICON) -> Option<IconData> {
unsafe {
let mut icon_info = ICONINFO::default();
GetIconInfo(hicon, &mut icon_info).ok()?;
let mut bmp = BITMAP::default();
GetObjectW(
icon_info.hbmColor.into(),
mem::size_of::<BITMAP>() as i32,
Some(&mut bmp as *mut _ as *mut _),
);
let width = bmp.bmWidth as u32;
let height = bmp.bmHeight as u32;
if width == 0 || height == 0 {
let _ = DeleteObject(icon_info.hbmColor.into());
let _ = DeleteObject(icon_info.hbmMask.into());
return None;
}
let mut bmi = BITMAPINFO::default();
bmi.bmiHeader.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bmi.bmiHeader.biWidth = width as i32;
bmi.bmiHeader.biHeight = -(height as i32); bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB.0;
let mut pixels = vec![0u8; (width * height * 4) as usize];
let hdc = CreateCompatibleDC(None);
GetDIBits(
hdc,
icon_info.hbmColor,
0,
height,
Some(pixels.as_mut_ptr() as *mut _),
&mut bmi,
DIB_RGB_COLORS,
);
let _ = DeleteDC(hdc);
let _ = DeleteObject(icon_info.hbmColor.into());
let _ = DeleteObject(icon_info.hbmMask.into());
bgra_to_rgba(&mut pixels);
crate::color::unpremultiply_alpha(&mut pixels);
Some(IconData::Rgba {
width,
height,
data: pixels,
})
}
}
#[cfg(target_os = "windows")]
fn load_stock_icon(name: &str) -> Option<IconData> {
let siid = siid_from_name(name)?;
unsafe {
let mut sii = SHSTOCKICONINFO::default();
sii.cbSize = mem::size_of::<SHSTOCKICONINFO>() as u32;
SHGetStockIconInfo(siid, SHGSI_ICON | SHGSI_LARGEICON, &mut sii).ok()?;
let result = hicon_to_rgba(sii.hIcon);
let _ = DestroyIcon(sii.hIcon);
result
}
}
#[cfg(target_os = "windows")]
fn load_idi_icon() -> Option<IconData> {
unsafe {
let hicon = LoadIconW(None, IDI_QUESTION).ok()?;
hicon_to_rgba(hicon)
}
}
#[cfg(target_os = "windows")]
unsafe fn try_create_font(hdc: HDC, face_name: &str, size: i32) -> Option<HFONT> {
unsafe {
let wide_name: Vec<u16> = face_name.encode_utf16().chain(std::iter::once(0)).collect();
let font = CreateFontW(
size,
0,
0,
0,
FW_NORMAL.0 as i32,
0,
0,
0,
DEFAULT_CHARSET,
OUT_TT_PRECIS,
CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY,
(FF_DONTCARE.0 | DEFAULT_PITCH.0) as u32,
PCWSTR(wide_name.as_ptr()),
);
if font.is_invalid() {
return None;
}
let old = SelectObject(hdc, font.into());
let mut actual_name = [0u16; 64];
let len = GetTextFaceW(hdc, Some(&mut actual_name));
SelectObject(hdc, old);
if len == 0 {
let _ = DeleteObject(font.into());
return None;
}
let actual = String::from_utf16_lossy(&actual_name[..len as usize]);
if actual.trim_end_matches('\0') != face_name {
let _ = DeleteObject(font.into());
return None;
}
Some(font)
}
}
#[cfg(target_os = "windows")]
fn load_glyph_icon(codepoint: u32, size: i32, fg_color: Option<[u8; 3]>) -> Option<IconData> {
unsafe {
let hdc = CreateCompatibleDC(None);
let font = try_create_font(hdc, "Segoe Fluent Icons", size)
.or_else(|| try_create_font(hdc, "Segoe MDL2 Assets", size));
let font = match font {
Some(f) => f,
None => {
let _ = DeleteDC(hdc);
return None;
}
};
let old_font = SelectObject(hdc, font.into());
let mat2 = MAT2 {
eM11: FIXED { fract: 0, value: 1 },
eM12: FIXED { fract: 0, value: 0 },
eM21: FIXED { fract: 0, value: 0 },
eM22: FIXED { fract: 0, value: 1 },
};
let mut gm = GLYPHMETRICS::default();
let buf_size = GetGlyphOutlineW(hdc, codepoint, GGO_GRAY8_BITMAP, &mut gm, 0, None, &mat2);
if buf_size == GDI_ERROR as u32 || buf_size == 0 {
SelectObject(hdc, old_font);
let _ = DeleteObject(font.into());
let _ = DeleteDC(hdc);
return None;
}
let mut gray_buf = vec![0u8; buf_size as usize];
GetGlyphOutlineW(
hdc,
codepoint,
GGO_GRAY8_BITMAP,
&mut gm,
buf_size,
Some(gray_buf.as_mut_ptr() as *mut _),
&mat2,
);
SelectObject(hdc, old_font);
let _ = DeleteObject(font.into());
let _ = DeleteDC(hdc);
let glyph_w = gm.gmBlackBoxX;
let glyph_h = gm.gmBlackBoxY;
if glyph_w == 0 || glyph_h == 0 {
return None;
}
let pitch = ((glyph_w + 3) & !3) as usize;
let mut rgba = Vec::with_capacity((glyph_w * glyph_h * 4) as usize);
for y in 0..glyph_h as usize {
for x in 0..glyph_w as usize {
let gray = gray_buf[y * pitch + x];
rgba.extend_from_slice(&gray8_to_rgba(gray));
}
}
crate::color::tint_monochrome(&mut rgba, fg_color);
Some(IconData::Rgba {
width: glyph_w,
height: glyph_h,
data: rgba,
})
}
}
fn parse_hex_codepoint(name: &str) -> Option<u32> {
let hex = name
.strip_prefix("0x")
.or_else(|| name.strip_prefix("0X"))?;
if hex.is_empty() {
return None;
}
u32::from_str_radix(hex, 16).ok()
}
#[must_use]
pub(crate) fn load_windows_icon_by_name(name: &str, fg_color: Option<[u8; 3]>) -> Option<IconData> {
#[cfg(target_os = "windows")]
{
if name.starts_with("SIID_") {
return load_stock_icon(name);
}
if name == "IDI_QUESTION" {
return load_idi_icon();
}
if let Some(cp) = parse_hex_codepoint(name) {
return load_glyph_icon(cp, DEFAULT_ICON_SIZE, fg_color);
}
if let Some(cp) = glyph_codepoint(name) {
return load_glyph_icon(cp, DEFAULT_ICON_SIZE, fg_color);
}
None
}
#[cfg(not(target_os = "windows"))]
{
let _ = (name, fg_color);
None
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use crate::{IconRole, IconSet, icon_name};
fn load_role(role: IconRole) -> Option<IconData> {
load_windows_icon_by_name(icon_name(role, IconSet::SegoeIcons)?, None)
}
#[test]
fn bgra_to_rgba_conversion() {
let mut buf = [0u8, 0, 255, 255];
bgra_to_rgba(&mut buf);
assert_eq!(buf, [255, 0, 0, 255]);
}
#[test]
fn unpremultiply_correctness() {
let mut buf = [128u8, 0, 0, 128];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [255, 0, 0, 128]);
let mut buf = [100u8, 200, 50, 255];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [100, 200, 50, 255]);
let mut buf = [0u8, 0, 0, 0];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [0, 0, 0, 0]);
}
#[test]
fn gray8_alpha_scaling() {
let pixel = gray8_to_rgba(64);
assert_eq!(pixel, [255, 255, 255, 255]);
let pixel = gray8_to_rgba(0);
assert_eq!(pixel, [255, 255, 255, 0]);
let pixel = gray8_to_rgba(32);
assert_eq!(pixel, [255, 255, 255, 127]);
}
#[test]
fn glyph_codepoint_lookup() {
assert_eq!(glyph_codepoint("ChromeClose"), Some(0xE8BB));
assert_eq!(glyph_codepoint("Unknown"), None);
}
#[test]
fn action_roles_are_glyphs() {
for (role, name, codepoint) in [
(IconRole::ActionSearch, "Search", 0xE721),
(IconRole::ActionSettings, "Settings", 0xE713),
(IconRole::ActionDelete, "Delete", 0xE74D),
(IconRole::ActionPrint, "Print", 0xE749),
] {
assert_eq!(icon_name(role, IconSet::SegoeIcons), Some(name));
assert_eq!(glyph_codepoint(name), Some(codepoint));
}
}
#[test]
fn unmapped_role_returns_none() {
let result = load_role(IconRole::StatusBusy);
assert!(
result.is_none(),
"StatusBusy should return None (no Segoe mapping, no fallback)"
);
}
#[cfg(target_os = "windows")]
#[test]
fn stock_icon_returns_rgba() {
let result = load_role(IconRole::DialogWarning);
assert!(result.is_some(), "DialogWarning should return an icon");
if let Some(IconData::Rgba { .. }) = result {
} else {
panic!("Expected IconData::Rgba for stock icon");
}
}
#[cfg(target_os = "windows")]
#[test]
fn glyph_icon_returns_rgba() {
let result = load_role(IconRole::ActionCopy);
assert!(result.is_some(), "ActionCopy should return an icon");
if let Some(IconData::Rgba { .. }) = result {
} else {
panic!("Expected IconData::Rgba for glyph icon");
}
}
#[cfg(target_os = "windows")]
#[test]
fn rgba_dimensions_correct() {
if let Some(IconData::Rgba {
width,
height,
data,
}) = load_role(IconRole::DialogWarning)
{
assert_eq!(
(width * height * 4) as usize,
data.len(),
"RGBA buffer size must equal width * height * 4"
);
}
}
#[cfg(target_os = "windows")]
#[test]
fn idi_question_returns_some() {
let result = load_role(IconRole::DialogQuestion);
assert!(
result.is_some(),
"DialogQuestion should return an icon via LoadIconW"
);
}
#[test]
fn parse_hex_codepoint_with_prefix() {
assert_eq!(parse_hex_codepoint("0xE8BB"), Some(0xE8BB));
}
#[test]
fn parse_hex_codepoint_lowercase() {
assert_eq!(parse_hex_codepoint("0xe8bb"), Some(0xE8BB));
}
#[test]
fn parse_hex_codepoint_no_prefix_returns_none() {
assert_eq!(parse_hex_codepoint("E8BB"), None);
}
#[test]
fn parse_hex_codepoint_named_glyph_not_hex() {
assert_eq!(parse_hex_codepoint("ChromeClose"), None);
}
#[test]
fn parse_hex_codepoint_add_not_hex() {
assert_eq!(parse_hex_codepoint("Add"), None);
}
#[test]
fn parse_hex_codepoint_invalid() {
assert_eq!(parse_hex_codepoint("0xZZZZ"), None);
}
#[test]
fn parse_hex_codepoint_empty() {
assert_eq!(parse_hex_codepoint(""), None);
}
#[test]
fn parse_hex_codepoint_bare_0x() {
assert_eq!(parse_hex_codepoint("0x"), None);
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_hex_codepoint() {
let result = load_windows_icon_by_name("0xE8C8", None);
assert!(
result.is_some(),
"hex codepoint 0xE8C8 should load Copy glyph"
);
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_named_glyph() {
let result = load_windows_icon_by_name("Copy", None);
assert!(result.is_some(), "named glyph Copy should load");
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_stock_icon() {
let result = load_windows_icon_by_name("SIID_WARNING", None);
assert!(result.is_some(), "SIID_WARNING stock icon should load");
}
}