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
use std::{io, mem, os::windows::ffi::OsStrExt, path::Path, ptr};

use winapi::{
    ctypes::{c_int, wchar_t},
    shared::{
        minwindef::{BYTE, LPARAM, WPARAM},
        windef::{HICON, HWND},
    },
    um::winuser,
};

use crate::icon::{Icon, Pixel, PIXEL_SIZE};

impl Pixel {
    fn to_bgra(&mut self) {
        mem::swap(&mut self.r, &mut self.b);
    }
}

#[derive(Debug)]
pub enum IconType {
    Small = winuser::ICON_SMALL as isize,
    Big = winuser::ICON_BIG as isize,
}

#[derive(Clone, Debug)]
pub struct WinIcon {
    pub handle: HICON,
}

unsafe impl Send for WinIcon {}

impl WinIcon {
    #[allow(dead_code)]
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
        let wide_path: Vec<u16> = path.as_ref().as_os_str().encode_wide().collect();
        let handle = unsafe {
            winuser::LoadImageW(
                ptr::null_mut(),
                wide_path.as_ptr() as *const wchar_t,
                winuser::IMAGE_ICON,
                0, // 0 indicates that we want to use the actual width
                0, // and height
                winuser::LR_LOADFROMFILE,
            ) as HICON
        };
        if !handle.is_null() {
            Ok(WinIcon { handle })
        } else {
            Err(io::Error::last_os_error())
        }
    }

    pub fn from_icon(icon: Icon) -> Result<Self, io::Error> {
        Self::from_rgba(icon.rgba, icon.width, icon.height)
    }

    pub fn from_rgba(mut rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, io::Error> {
        assert_eq!(rgba.len() % PIXEL_SIZE, 0);
        let pixel_count = rgba.len() / PIXEL_SIZE;
        assert_eq!(pixel_count, (width * height) as usize);
        let mut and_mask = Vec::with_capacity(pixel_count);
        let pixels = rgba.as_mut_ptr() as *mut Pixel; // how not to write idiomatic Rust
        for pixel_index in 0..pixel_count {
            let pixel = unsafe { &mut *pixels.offset(pixel_index as isize) };
            and_mask.push(pixel.a.wrapping_sub(std::u8::MAX)); // invert alpha channel
            pixel.to_bgra();
        }
        assert_eq!(and_mask.len(), pixel_count);
        let handle = unsafe {
            winuser::CreateIcon(
                ptr::null_mut(),
                width as c_int,
                height as c_int,
                1,
                (PIXEL_SIZE * 8) as BYTE,
                and_mask.as_ptr() as *const BYTE,
                rgba.as_ptr() as *const BYTE,
            ) as HICON
        };
        if !handle.is_null() {
            Ok(WinIcon { handle })
        } else {
            Err(io::Error::last_os_error())
        }
    }

    pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) {
        unsafe {
            winuser::SendMessageW(
                hwnd,
                winuser::WM_SETICON,
                icon_type as WPARAM,
                self.handle as LPARAM,
            );
        }
    }
}

impl Drop for WinIcon {
    fn drop(&mut self) {
        unsafe { winuser::DestroyIcon(self.handle) };
    }
}

pub fn unset_for_window(hwnd: HWND, icon_type: IconType) {
    unsafe {
        winuser::SendMessageW(hwnd, winuser::WM_SETICON, icon_type as WPARAM, 0 as LPARAM);
    }
}