Skip to main content

tray_icon/
icon.rs

1// Copyright 2022-2022 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5// taken from https://github.com/rust-windowing/winit/blob/92fdf5ba85f920262a61cee4590f4a11ad5738d1/src/icon.rs
6
7use crate::platform_impl::PlatformIcon;
8use muda::NativeIcon;
9use std::{error::Error, fmt, io, mem};
10
11#[repr(C)]
12#[derive(Debug)]
13pub(crate) struct Pixel {
14    pub(crate) r: u8,
15    pub(crate) g: u8,
16    pub(crate) b: u8,
17    pub(crate) a: u8,
18}
19
20pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
21
22#[derive(Debug)]
23/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
24pub enum BadIcon {
25    /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
26    /// safely interpreted as 32bpp RGBA pixels.
27    ByteCountNotDivisibleBy4 { byte_count: usize },
28    /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
29    /// At least one of your arguments is incorrect.
30    DimensionsVsPixelCount {
31        width: u32,
32        height: u32,
33        width_x_height: usize,
34        pixel_count: usize,
35    },
36    /// Produced when underlying OS functionality failed to create the icon
37    OsError(io::Error),
38}
39
40impl fmt::Display for BadIcon {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
44                "The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
45                byte_count,
46            ),
47            BadIcon::DimensionsVsPixelCount {
48                width,
49                height,
50                width_x_height,
51                pixel_count,
52            } => write!(f,
53                "The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.",
54                width, height, pixel_count, width_x_height,
55            ),
56            BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {:?}", e),
57        }
58    }
59}
60
61impl Error for BadIcon {
62    fn source(&self) -> Option<&(dyn Error + 'static)> {
63        match self {
64            BadIcon::OsError(e) => Some(e),
65            _ => None,
66        }
67    }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub(crate) struct RgbaIcon {
72    pub(crate) rgba: Vec<u8>,
73    pub(crate) width: u32,
74    pub(crate) height: u32,
75}
76
77/// For platforms which don't have window icons (e.g. web)
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub(crate) struct NoIcon;
80
81#[allow(dead_code)] // These are not used on every platform
82mod constructors {
83    use super::*;
84
85    impl RgbaIcon {
86        pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
87            if !rgba.len().is_multiple_of(PIXEL_SIZE) {
88                return Err(BadIcon::ByteCountNotDivisibleBy4 {
89                    byte_count: rgba.len(),
90                });
91            }
92            let pixel_count = rgba.len() / PIXEL_SIZE;
93            if pixel_count != (width * height) as usize {
94                Err(BadIcon::DimensionsVsPixelCount {
95                    width,
96                    height,
97                    width_x_height: (width * height) as usize,
98                    pixel_count,
99                })
100            } else {
101                Ok(RgbaIcon {
102                    rgba,
103                    width,
104                    height,
105                })
106            }
107        }
108    }
109
110    impl NoIcon {
111        pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
112            // Create the rgba icon anyway to validate the input
113            let _ = RgbaIcon::from_rgba(rgba, width, height)?;
114            Ok(NoIcon)
115        }
116    }
117}
118
119#[derive(Debug, Clone)]
120pub(crate) enum IconType {
121    Custom(Icon),
122    Native(NativeIcon),
123}
124
125/// An icon used for the window titlebar, taskbar, etc.
126#[derive(Clone)]
127pub struct Icon {
128    pub(crate) inner: PlatformIcon,
129}
130
131impl fmt::Debug for Icon {
132    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
133        fmt::Debug::fmt(&self.inner, formatter)
134    }
135}
136
137impl Icon {
138    /// Creates an icon from 32bpp RGBA data.
139    ///
140    /// The length of `rgba` must be divisible by 4, and `width * height` must equal
141    /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
142    pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
143        Ok(Icon {
144            inner: PlatformIcon::from_rgba(rgba, width, height)?,
145        })
146    }
147
148    /// Create an icon from a file path.
149    ///
150    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
151    /// icon size from the file.
152    ///
153    /// In cases where the specified size does not exist in the file, Windows may perform scaling
154    /// to get an icon of the desired size.
155    #[cfg(windows)]
156    pub fn from_path<P: AsRef<std::path::Path>>(
157        path: P,
158        size: Option<(u32, u32)>,
159    ) -> Result<Self, BadIcon> {
160        let win_icon = PlatformIcon::from_path(path, size)?;
161        Ok(Icon { inner: win_icon })
162    }
163
164    /// Create an icon from a resource embedded in this executable or library.
165    ///
166    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
167    /// icon size from the file.
168    ///
169    /// In cases where the specified size does not exist in the file, Windows may perform scaling
170    /// to get an icon of the desired size.
171    #[cfg(windows)]
172    pub fn from_resource(ordinal: u16, size: Option<(u32, u32)>) -> Result<Self, BadIcon> {
173        let win_icon = PlatformIcon::from_resource(ordinal, size)?;
174        Ok(Icon { inner: win_icon })
175    }
176
177    /// This is basically the same as from_resource, but takes a resource name
178    /// rather than oridinal id.
179    #[cfg(windows)]
180    pub fn from_resource_name(
181        resource_name: &str,
182        size: Option<(u32, u32)>,
183    ) -> Result<Self, BadIcon> {
184        let win_icon = PlatformIcon::from_resource_name(resource_name, size)?;
185        Ok(Icon { inner: win_icon })
186    }
187
188    /// Create an icon from an HICON
189    #[cfg(windows)]
190    pub fn from_handle(handle: isize) -> Self {
191        let win_icon = PlatformIcon::from_handle(handle as _);
192        Icon { inner: win_icon }
193    }
194}