native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Windows icon loader
//
// Resolves Segoe icon names (the names `icon_name` gives each IconRole in
// IconSet::SegoeIcons) to RGBA pixel data via two pipelines:
// 1. Stock icons via SHGetStockIconInfo (13 SIID_ prefixed roles), and
//    IDI_QUESTION via LoadIconW -- full-colour
// 2. Font glyphs via GetGlyphOutlineW from Segoe Fluent Icons (27 glyph
//    roles) -- monochrome, drawn in the requested colour or white
//
// Both pipelines produce IconData::Rgba with correct RGBA byte order and
// straight (non-premultiplied) alpha. Returns None when the name is not
// one of them or the icon cannot be loaded on this system.
//
// This module is compiled on all platforms (gated by feature = "system-icons")
// so that platform-independent logic like `parse_hex_codepoint` can be tested
// everywhere. Windows-specific code is behind `#[cfg(target_os = "windows")]`.

// Win32 GDI FFI -- no safe alternative
#![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;

/// Default icon size in pixels for font glyph rendering.
const DEFAULT_ICON_SIZE: i32 = 32;

/// Map a Segoe Fluent Icons glyph name to its Unicode PUA codepoint.
///
/// These codepoints are shared between Segoe Fluent Icons (Win11) and
/// Segoe MDL2 Assets (Win10).
fn glyph_codepoint(name: &str) -> Option<u32> {
    Some(match name {
        // Window Controls
        "ChromeClose" => 0xE8BB,
        "ChromeMinimize" => 0xE921,
        "ChromeMaximize" => 0xE922,
        "ChromeRestore" => 0xE923,
        // Actions
        "Save" => 0xE74E,
        "Copy" => 0xE8C8,
        "Paste" => 0xE77F,
        "Cut" => 0xE8C6,
        "Undo" => 0xE7A7,
        "Redo" => 0xE7A6,
        "Edit" => 0xE70F,
        "Add" => 0xE710,
        "Remove" => 0xE738,
        "Refresh" => 0xE72C,
        // Names and codepoints as the Segoe Fluent Icons reference lists them:
        // https://learn.microsoft.com/en-us/windows/apps/design/style/segoe-fluent-icons-font
        "Search" => 0xE721,
        "Settings" => 0xE713,
        "Delete" => 0xE74D,
        "Print" => 0xE749,
        // Navigation
        "Back" => 0xE72B,
        "Forward" => 0xE72A,
        "Up" => 0xE74A,
        "Down" => 0xE74B,
        "Home" => 0xE80F,
        "GlobalNavigationButton" => 0xE700,
        // Status
        "CheckMark" => 0xE73E,
        // System
        "Ringer" => 0xEA8F,
        _ => return None,
    })
}

/// Map a SIID_ string name to its SHSTOCKICONID constant.
#[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,
    })
}

/// Swap BGRA byte order to RGBA by exchanging bytes 0 and 2 in each pixel.
fn bgra_to_rgba(pixels: &mut [u8]) {
    for pixel in pixels.as_chunks_mut::<4>().0 {
        pixel.swap(0, 2);
    }
}

/// Convert a GGO_GRAY8_BITMAP grayscale value (0-64) to an RGBA pixel.
///
/// Produces white foreground (255,255,255) with alpha scaled from the
/// 65-level grayscale: `alpha = min(255, gray * 255 / 64)`.
fn gray8_to_rgba(gray: u8) -> [u8; 4] {
    // gray is 0..=64 per GGO_GRAY8 contract. `u32::from(gray) * 255` max is 16320,
    // no overflow risk. Division by literal 64 is arithmetically safe (non-zero
    // constant); `.min(255)` caps the result so the `as u8` cast is exact.
    #[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]
}

/// Extract RGBA pixels from an HICON handle.
///
/// Uses GetIconInfo to obtain the color bitmap, then GetDIBits with a
/// top-down 32-bit BITMAPINFOHEADER to extract BGRA pixels. Converts
/// to RGBA and applies unpremultiply.
#[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()?;

        // Get bitmap dimensions
        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 {
            // A failed delete of a bitmap we own has no recovery.
            let _ = DeleteObject(icon_info.hbmColor.into());
            let _ = DeleteObject(icon_info.hbmMask.into());
            return None;
        }

        // Set up BITMAPINFOHEADER for 32-bit top-down BGRA
        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); // negative = top-down
        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);

        // Cleanup bitmaps. A failed delete of a bitmap we own has no recovery.
        let _ = DeleteObject(icon_info.hbmColor.into());
        let _ = DeleteObject(icon_info.hbmMask.into());

        // Convert BGRA to RGBA and fix premultiplied alpha
        bgra_to_rgba(&mut pixels);
        crate::color::unpremultiply_alpha(&mut pixels);

        Some(IconData::Rgba {
            width,
            height,
            data: pixels,
        })
    }
}

/// Load a stock system icon by its SIID_ name.
///
/// Maps the name to a SHSTOCKICONID, calls SHGetStockIconInfo to get
/// an HICON, extracts RGBA pixels, and cleans up the icon handle.
#[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);

        // Clean up the icon handle
        let _ = DestroyIcon(sii.hIcon);

        result
    }
}

/// Load the system question dialog icon via LoadIconW.
///
/// DialogQuestion maps to IDI_QUESTION which requires LoadIconW instead
/// of SHGetStockIconInfo (there is no SIID_QUESTION constant).
/// Note: system icons from LoadIconW are shared resources and should
/// NOT be destroyed with DestroyIcon.
#[cfg(target_os = "windows")]
fn load_idi_icon() -> Option<IconData> {
    unsafe {
        let hicon = LoadIconW(None, IDI_QUESTION).ok()?;
        hicon_to_rgba(hicon)
        // Do NOT call DestroyIcon -- shared system resource
    }
}

/// Try to create a font and verify it was actually loaded (not substituted).
///
/// GDI silently substitutes a different font if the requested one is not
/// available. We detect this by comparing GetTextFaceW output against the
/// requested name.
#[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;
        }

        // Verify the actual loaded font matches what we requested
        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 {
            // Font was substituted -- not actually available
            let _ = DeleteObject(font.into());
            return None;
        }

        Some(font)
    }
}

/// Render a font glyph to RGBA pixels via GetGlyphOutlineW.
///
/// Tries Segoe Fluent Icons first (Win11), then Segoe MDL2 Assets (Win10).
/// Returns None if neither font is available (caller falls back to bundled).
///
/// Uses GGO_GRAY8_BITMAP which produces a 65-level grayscale alpha mask
/// (values 0-64), converted to RGBA with scaled alpha and a white
/// foreground, or `fg_color` where it is given.
#[cfg(target_os = "windows")]
fn load_glyph_icon(codepoint: u32, size: i32, fg_color: Option<[u8; 3]>) -> Option<IconData> {
    unsafe {
        let hdc = CreateCompatibleDC(None);

        // Try Segoe Fluent Icons first (Win11), then Segoe MDL2 Assets (Win10)
        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());

        // Identity matrix (no transform)
        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();

        // First call: get buffer size
        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;
        }

        // Second call: get the grayscale bitmap
        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;
        }

        // GGO_GRAY8_BITMAP rows are DWORD-aligned
        let pitch = ((glyph_w + 3) & !3) as usize;

        // Convert grayscale (0-64) to RGBA (white with scaled alpha)
        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,
        })
    }
}

/// Parse a hex codepoint string like "0xE8BB" or "0xe8bb" to a u32.
///
/// Requires the `0x` or `0X` prefix to avoid ambiguity with named glyphs
/// (e.g., "Add" is both a valid glyph name and valid hex).
///
/// Returns `None` for non-hex strings or strings without the 0x prefix.
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()
}

/// Load a Windows icon by its name string.
///
/// Accepts multiple name formats:
/// - `"SIID_*"` -- stock system icon via SHGetStockIconInfo
/// - `"IDI_QUESTION"` -- system dialog icon via LoadIconW
/// - `"0xE8BB"` -- hex codepoint for Segoe Fluent Icons glyph
/// - `"ChromeClose"` -- named Segoe Fluent Icons glyph
///
/// A glyph is drawn in `fg_color` where it is given, white otherwise; the
/// stock and dialog icons are full-colour and ignore it.
///
/// Returns `None` if the name doesn't match any known format or
/// the icon cannot be loaded on this system.
#[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();
        }
        // Try hex codepoint (e.g., "0xE8BB")
        if let Some(cp) = parse_hex_codepoint(name) {
            return load_glyph_icon(cp, DEFAULT_ICON_SIZE, fg_color);
        }
        // Try named glyph (e.g., "ChromeClose")
        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};

    /// Load a role's icon the way `IconLoader::load` does: by the name
    /// `icon_name` gives it in the Segoe set.
    fn load_role(role: IconRole) -> Option<IconData> {
        load_windows_icon_by_name(icon_name(role, IconSet::SegoeIcons)?, None)
    }

    // === Platform-independent unit tests ===

    #[test]
    fn bgra_to_rgba_conversion() {
        // BGRA blue [0, 0, 255, 255] -> RGBA red [255, 0, 0, 255]
        let mut buf = [0u8, 0, 255, 255];
        bgra_to_rgba(&mut buf);
        assert_eq!(buf, [255, 0, 0, 255]);
    }

    #[test]
    fn unpremultiply_correctness() {
        // Premultiplied [128, 0, 0, 128] -> straight [255, 0, 0, 128]
        let mut buf = [128u8, 0, 0, 128];
        crate::color::unpremultiply_alpha(&mut buf);
        assert_eq!(buf, [255, 0, 0, 128]);

        // Fully opaque pixels are unchanged
        let mut buf = [100u8, 200, 50, 255];
        crate::color::unpremultiply_alpha(&mut buf);
        assert_eq!(buf, [100, 200, 50, 255]);

        // Fully transparent pixels are unchanged
        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() {
        // gray=64 -> full alpha (255)
        let pixel = gray8_to_rgba(64);
        assert_eq!(pixel, [255, 255, 255, 255]);

        // gray=0 -> transparent (0)
        let pixel = gray8_to_rgba(0);
        assert_eq!(pixel, [255, 255, 255, 0]);

        // gray=32 -> half alpha: (32 * 255) / 64 = 127
        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);
    }

    /// Every action role is a Segoe Fluent glyph, drawn in the loader's
    /// colour, not a full-colour stock icon.
    #[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() {
        // StatusBusy has no Segoe mapping (known gap), should return None
        let result = load_role(IconRole::StatusBusy);
        assert!(
            result.is_none(),
            "StatusBusy should return None (no Segoe mapping, no fallback)"
        );
    }

    // === Windows-only integration tests ===

    #[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 {
            // Stock icons should return RGBA
        } 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 {
            // Font glyph icons should return RGBA
        } 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"
        );
    }

    // === parse_hex_codepoint tests ===

    #[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() {
        // "E8BB" is valid hex but without 0x prefix, requires prefix per design
        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() {
        // "Add" is both a valid glyph name and valid hex -- 0x prefix disambiguates
        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);
    }

    // === Windows-only load_windows_icon_by_name tests ===

    #[cfg(target_os = "windows")]
    #[test]
    fn load_by_name_hex_codepoint() {
        // 0xE8C8 is the Copy glyph
        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");
    }
}