#![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: u32 = 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(all(test, target_os = "windows"))]
thread_local! {
static LAST_FAILURE: std::cell::Cell<Option<String>> = const { std::cell::Cell::new(None) };
}
#[cfg(target_os = "windows")]
fn note_failure(step: std::fmt::Arguments<'_>) {
#[cfg(test)]
LAST_FAILURE.with(|last| last.set(Some(step.to_string())));
#[cfg(not(test))]
let _ = step;
}
#[cfg(target_os = "windows")]
unsafe fn hicon_to_rgba(hicon: HICON) -> Option<IconData> {
let mut icon_info = ICONINFO::default();
unsafe { GetIconInfo(hicon, &mut icon_info) }
.inspect_err(|err| note_failure(format_args!("GetIconInfo: {err}")))
.ok()?;
let bitmap = unsafe { bitmap_bgra(icon_info.hbmColor) };
unsafe {
let _ = DeleteObject(icon_info.hbmColor.into());
let _ = DeleteObject(icon_info.hbmMask.into());
}
let (width, height, mut pixels) = bitmap?;
bgra_to_rgba(&mut pixels);
crate::color::unpremultiply_alpha(&mut pixels);
IconData::rgba(width, height, pixels)
}
#[cfg(target_os = "windows")]
unsafe fn bitmap_bgra(hbm: HBITMAP) -> Option<(u32, u32, Vec<u8>)> {
let mut bmp = BITMAP::default();
let written = unsafe {
GetObjectW(
hbm.into(),
mem::size_of::<BITMAP>() as i32,
Some(&mut bmp as *mut _ as *mut _),
)
};
if written == 0 {
note_failure(format_args!("GetObjectW wrote nothing"));
return None;
}
let size = u32::try_from(bmp.bmWidth)
.ok()
.zip(u32::try_from(bmp.bmHeight).ok())
.and_then(|(w, h)| {
let top_down = bmp.bmHeight.checked_neg()?;
Some((w, h, top_down, crate::icons::raster_bytes_in_bound(w, h)?))
});
let Some((width, height, top_down, bytes)) = size else {
note_failure(format_args!(
"a {} x {} bitmap is negative, empty or over the decode bound",
bmp.bmWidth, bmp.bmHeight
));
return None;
};
let mut bmi = BITMAPINFO::default();
bmi.bmiHeader.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bmi.bmiHeader.biWidth = bmp.bmWidth;
bmi.bmiHeader.biHeight = top_down;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB.0;
let mut pixels = vec![0u8; bytes];
let hdc = unsafe { CreateCompatibleDC(None) };
if hdc.is_invalid() {
note_failure(format_args!("CreateCompatibleDC returned no DC"));
return None;
}
let lines = unsafe {
GetDIBits(
hdc,
hbm,
0,
height,
Some(pixels.as_mut_ptr() as *mut _),
&mut bmi,
DIB_RGB_COLORS,
)
};
let _ = unsafe { DeleteDC(hdc) };
if u32::try_from(lines).ok() != Some(height) {
note_failure(format_args!(
"GetDIBits copied {lines} of the {height} lines"
));
return None;
}
Some((width, height, pixels))
}
#[cfg(target_os = "windows")]
static STOCK_ICON_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(target_os = "windows")]
fn load_stock_icon(name: &str) -> Option<IconData> {
let siid = siid_from_name(name)?;
let _one_at_a_time = STOCK_ICON_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
unsafe {
let mut sii = SHSTOCKICONINFO {
cbSize: mem::size_of::<SHSTOCKICONINFO>() as u32,
..Default::default()
};
SHGetStockIconInfo(siid, SHGSI_ICON | SHGSI_LARGEICON, &mut sii)
.inspect_err(|err| note_failure(format_args!("SHGetStockIconInfo: {err}")))
.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, em_height: u32) -> Option<HFONT> {
let height = i32::try_from(em_height).ok()?.checked_neg()?;
unsafe {
let wide_name: Vec<u16> = face_name.encode_utf16().chain(std::iter::once(0)).collect();
let font = CreateFontW(
height,
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);
let actual = usize::try_from(len)
.ok()
.filter(|&len| len > 0)
.and_then(|len| actual_name.get(..len))
.map(String::from_utf16_lossy);
let loaded = actual
.as_deref()
.map(|actual| actual.trim_end_matches('\0'));
if loaded != Some(face_name) {
let _ = DeleteObject(font.into());
return None;
}
Some(font)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct GlyphBox {
width: u32,
height: u32,
origin_x: i32,
origin_y: i32,
}
fn glyph_canvas(gray: &[u8], glyph: GlyphBox, ascent: i32, size: u32) -> Option<Vec<u8>> {
if !crate::icons::raster_size_in_bound(size) || glyph.width == 0 || glyph.height == 0 {
return None;
}
let glyph_w = usize::try_from(glyph.width).ok()?;
let glyph_h = usize::try_from(glyph.height).ok()?;
let pitch = glyph_w.checked_add(3)? & !3;
if gray.len() < pitch.checked_mul(glyph_h)? {
return None;
}
let rows = gray
.chunks(pitch)
.take(glyph_h)
.map(|row| row.get(..glyph_w))
.collect::<Option<Vec<_>>>()?;
let top = i64::from(ascent).checked_sub(i64::from(glyph.origin_y))?;
let left = i64::from(glyph.origin_x);
let size = usize::try_from(size).ok()?;
let mut canvas = vec![gray8_to_rgba(0); size.checked_mul(size)?];
for (y, out_row) in canvas.chunks_exact_mut(size).enumerate() {
let Some(row) = box_offset(y, top).and_then(|y| rows.get(y)) else {
continue;
};
for (x, pixel) in out_row.iter_mut().enumerate() {
if let Some(&gray) = box_offset(x, left).and_then(|x| row.get(x)) {
*pixel = gray8_to_rgba(gray);
}
}
}
Some(canvas.into_flattened())
}
fn box_offset(at: usize, start: i64) -> Option<usize> {
usize::try_from(i64::try_from(at).ok()?.checked_sub(start)?).ok()
}
fn em_ascent(tm_ascent: i32, tm_internal_leading: i32) -> Option<i32> {
tm_ascent.checked_sub(tm_internal_leading)
}
#[cfg(target_os = "windows")]
fn load_glyph_icon(codepoint: u32, size: u32, fg_color: Option<[u8; 3]>) -> Option<IconData> {
if !crate::icons::raster_size_in_bound(size) {
return None;
}
let hdc = unsafe { CreateCompatibleDC(None) };
if hdc.is_invalid() {
return None;
}
let font = unsafe {
try_create_font(hdc, "Segoe Fluent Icons", size)
.or_else(|| try_create_font(hdc, "Segoe MDL2 Assets", size))
};
let rgba = font.and_then(|font| {
let rgba = unsafe { render_glyph(hdc, font, codepoint, size) };
let _ = unsafe { DeleteObject(font.into()) };
rgba
});
let _ = unsafe { DeleteDC(hdc) };
let mut rgba = rgba?;
crate::color::tint_monochrome(&mut rgba, fg_color);
IconData::rgba(size, size, rgba)
}
#[cfg(target_os = "windows")]
unsafe fn render_glyph(hdc: HDC, font: HFONT, codepoint: u32, size: u32) -> Option<Vec<u8>> {
let old_font = unsafe { SelectObject(hdc, font.into()) };
let outline = unsafe { glyph_outline(hdc, codepoint) };
unsafe { SelectObject(hdc, old_font) };
let (gray, glyph, ascent) = outline?;
glyph_canvas(&gray, glyph, ascent, size)
}
#[cfg(target_os = "windows")]
unsafe fn glyph_outline(hdc: HDC, codepoint: u32) -> Option<(Vec<u8>, GlyphBox, i32)> {
let mut tm = TEXTMETRICW::default();
if !unsafe { GetTextMetricsW(hdc, &mut tm) }.as_bool() {
return None;
}
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 =
unsafe { GetGlyphOutlineW(hdc, codepoint, GGO_GRAY8_BITMAP, &mut gm, 0, None, &mat2) };
if buf_size == GDI_ERROR as u32 || buf_size == 0 {
return None;
}
let len = usize::try_from(buf_size)
.ok()
.filter(|&len| len <= crate::icons::MAX_ICON_DECODE_BYTES)?;
let mut gray = vec![0u8; len];
let written = unsafe {
GetGlyphOutlineW(
hdc,
codepoint,
GGO_GRAY8_BITMAP,
&mut gm,
buf_size,
Some(gray.as_mut_ptr() as *mut _),
&mat2,
)
};
if written == GDI_ERROR as u32 {
return None;
}
let glyph = GlyphBox {
width: gm.gmBlackBoxX,
height: gm.gmBlackBoxY,
origin_x: gm.gmptGlyphOrigin.x,
origin_y: gm.gmptGlyphOrigin.y,
};
Some((gray, glyph, em_ascent(tm.tmAscent, tm.tmInternalLeading)?))
}
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,
size: Option<u32>,
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();
}
let size = size.unwrap_or(DEFAULT_ICON_SIZE);
if let Some(cp) = parse_hex_codepoint(name) {
return load_glyph_icon(cp, size, fg_color);
}
if let Some(cp) = glyph_codepoint(name) {
return load_glyph_icon(cp, size, fg_color);
}
None
}
#[cfg(not(target_os = "windows"))]
{
let _ = (name, size, 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::SegoeFluent)?, None, None)
}
fn stock_roles() -> Vec<IconRole> {
IconRole::ALL
.iter()
.copied()
.filter(|&role| {
icon_name(role, IconSet::SegoeFluent).is_some_and(|n| n.starts_with("SIID_"))
})
.collect()
}
#[cfg(target_os = "windows")]
fn last_failure() -> String {
LAST_FAILURE
.with(|last| last.take())
.unwrap_or_else(|| "no step recorded".to_owned())
}
#[test]
fn stock_roles_are_the_siid_roles() {
assert_eq!(
stock_roles(),
[
IconRole::DialogWarning,
IconRole::DialogError,
IconRole::DialogInfo,
IconRole::Shield,
IconRole::FileGeneric,
IconRole::FolderClosed,
IconRole::FolderOpen,
IconRole::TrashEmpty,
IconRole::TrashFull,
IconRole::StatusError,
IconRole::UserAccount,
IconRole::Help,
IconRole::Lock,
]
);
}
#[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]);
}
fn gray_rows<R: AsRef<[u8]>>(rows: &[R], pitch: usize) -> Vec<u8> {
rows.iter()
.flat_map(|row| {
let mut padded = row.as_ref().to_vec();
padded.resize(pitch, 0);
padded
})
.collect()
}
fn alpha_at(canvas: &[u8], size: usize, x: usize, y: usize) -> u8 {
canvas[(y * size + x) * 4 + 3]
}
#[test]
fn glyph_canvas_is_the_em_box_whatever_the_ink() {
let bar = GlyphBox {
width: 6,
height: 1,
origin_x: 1,
origin_y: 4,
};
let square = GlyphBox {
width: 4,
height: 4,
origin_x: 2,
origin_y: 6,
};
let bar = glyph_canvas(&gray_rows(&[&[64; 6]], 8), bar, 7, 8).unwrap();
let square = glyph_canvas(&gray_rows(&[&[64; 4]; 4], 4), square, 7, 8).unwrap();
assert_eq!(bar.len(), 8 * 8 * 4);
assert_eq!(square.len(), 8 * 8 * 4);
}
#[test]
fn glyph_canvas_places_the_black_box_at_its_origin() {
let glyph = GlyphBox {
width: 2,
height: 2,
origin_x: 2,
origin_y: 5,
};
let canvas = glyph_canvas(&gray_rows(&[&[64, 32], &[16, 0]], 4), glyph, 7, 8).unwrap();
assert_eq!(alpha_at(&canvas, 8, 2, 2), 255);
assert_eq!(alpha_at(&canvas, 8, 3, 2), 127);
assert_eq!(alpha_at(&canvas, 8, 2, 3), 63);
let ink = canvas.chunks(4).filter(|pixel| pixel[3] != 0).count();
assert_eq!(ink, 3, "only the black box is drawn");
assert!(canvas.chunks(4).all(|pixel| pixel[..3] == [255, 255, 255]));
}
#[test]
fn glyph_canvas_em_box_leaves_out_the_internal_leading() {
let ascent = em_ascent(9, 2).unwrap();
assert_eq!(ascent, 7);
let glyph = GlyphBox {
width: 8,
height: 8,
origin_x: 0,
origin_y: 7,
};
let canvas = glyph_canvas(&gray_rows(&[&[64; 8]; 8], 8), glyph, ascent, 8).unwrap();
assert!((0..8).all(|y| (0..8).all(|x| alpha_at(&canvas, 8, x, y) == 255)));
assert_eq!(em_ascent(9, 0), Some(9), "no leading, the ascent");
assert_eq!(em_ascent(i32::MIN, 1), None);
}
#[test]
fn glyph_canvas_clips_the_black_box() {
let glyph = GlyphBox {
width: 6,
height: 7,
origin_x: -1,
origin_y: 5,
};
let canvas = glyph_canvas(&gray_rows(&[&[64; 6]; 7], 8), glyph, 3, 4).unwrap();
assert_eq!(canvas.len(), 4 * 4 * 4);
assert!((0..4).all(|y| (0..4).all(|x| alpha_at(&canvas, 4, x, y) == 255)));
let far = GlyphBox {
width: 2,
height: 2,
origin_x: i32::MAX,
origin_y: i32::MIN,
};
let canvas = glyph_canvas(&gray_rows(&[&[64; 2]; 2], 4), far, i32::MAX, 4).unwrap();
assert!(canvas.chunks(4).all(|pixel| pixel[3] == 0));
}
#[test]
fn glyph_canvas_rejects_what_it_cannot_draw() {
let glyph = GlyphBox {
width: 5,
height: 2,
origin_x: 0,
origin_y: 0,
};
assert!(glyph_canvas(&[64; 15], glyph, 0, 8).is_none());
assert!(glyph_canvas(&[64; 16], glyph, 0, 8).is_some());
let empty = GlyphBox { width: 0, ..glyph };
assert!(glyph_canvas(&[], empty, 0, 8).is_none());
assert!(glyph_canvas(&[64; 16], glyph, 0, 0).is_none());
assert!(glyph_canvas(&[64; 16], glyph, 0, 4097).is_none());
let wide = GlyphBox {
width: u32::MAX,
..glyph
};
assert!(glyph_canvas(&[64; 16], wide, 0, 8).is_none());
}
#[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::SegoeFluent), 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; failed at: {}",
last_failure()
);
if let Some(IconData::Rgba(_)) = result {
} else {
panic!("Expected IconData::Rgba for stock icon");
}
}
#[cfg(target_os = "windows")]
#[test]
fn stock_icons_load_from_threads_at_once() {
let roles = stock_roles();
assert_eq!(roles.len(), 13);
let start = std::sync::Barrier::new(roles.len());
std::thread::scope(|scope| {
let loads: Vec<_> = roles
.iter()
.map(|&role| {
let start = &start;
scope.spawn(move || {
start.wait();
let icon = load_role(role);
(role, icon, last_failure())
})
})
.collect();
for load in loads {
let (role, icon, failure) = load.join().unwrap();
assert!(
matches!(icon, Some(IconData::Rgba(_))),
"{role:?} should load as RGBA; failed at: {failure}"
);
}
});
}
#[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() {
let Some(IconData::Rgba(rgba)) = load_role(IconRole::DialogWarning) else {
panic!(
"DialogWarning should load as RGBA; failed at: {}",
last_failure()
);
};
assert_eq!(
(rgba.width() * rgba.height() * 4) as usize,
rgba.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, 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, None);
assert!(result.is_some(), "named glyph Copy should load");
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_glyph_size_scales_the_raster() {
let small = load_windows_icon_by_name("Copy", Some(16), None);
let large = load_windows_icon_by_name("Copy", Some(64), None);
let (Some(IconData::Rgba(small)), Some(IconData::Rgba(large))) = (small, large) else {
panic!("Copy should load as RGBA at 16 and 64 px");
};
assert!(
large.height() > small.height(),
"64 px ({}) should be taller than 16 px ({})",
large.height(),
small.height()
);
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_glyphs_of_different_ink_share_the_em_box() {
let inked_rows = |name: &str| {
let Some(IconData::Rgba(rgba)) = load_windows_icon_by_name(name, Some(32), None) else {
panic!("{name} should load as RGBA");
};
assert_eq!((rgba.width(), rgba.height()), (32, 32), "{name}");
let rows: Vec<usize> = rgba
.data()
.chunks(32 * 4)
.enumerate()
.filter(|(_, row)| row.chunks(4).any(|pixel| pixel[3] != 0))
.map(|(y, _)| y)
.collect();
eprintln!("{name}: inked rows {rows:?}");
rows
};
let bar = inked_rows("Remove");
let square = inked_rows("ChromeMaximize");
assert!(!bar.is_empty(), "Remove has ink");
assert!(
bar.len() < square.len(),
"the bar is shorter than the square"
);
let (Some(bar_top), Some(bar_bottom)) = (bar.first(), bar.last()) else {
panic!("Remove has ink");
};
let (Some(square_top), Some(square_bottom)) = (square.first(), square.last()) else {
panic!("ChromeMaximize has ink");
};
assert!(
square_top <= bar_top && bar_bottom <= square_bottom,
"the bar ({bar_top}..={bar_bottom}) lies within the square \
({square_top}..={square_bottom})"
);
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_glyph_size_out_of_bound_returns_none() {
assert!(load_windows_icon_by_name("Copy", Some(0), None).is_none());
assert!(load_windows_icon_by_name("Copy", Some(u32::MAX), None).is_none());
}
#[cfg(target_os = "windows")]
#[test]
fn load_by_name_stock_icon() {
let result = load_windows_icon_by_name("SIID_WARNING", None, None);
assert!(
result.is_some(),
"SIID_WARNING stock icon should load; failed at: {}",
last_failure()
);
}
}