muda 0.20.0

Menu Utilities for Desktop 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
// Copyright 2022-2022 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

// taken from https://github.com/rust-windowing/winit/blob/92fdf5ba85f920262a61cee4590f4a11ad5738d1/src/icon.rs

use crate::platform_impl::PlatformIcon;
use std::{error::Error, fmt, io, mem};

#[repr(C)]
#[derive(Debug)]
pub(crate) struct Pixel {
    pub(crate) r: u8,
    pub(crate) g: u8,
    pub(crate) b: u8,
    pub(crate) a: u8,
}

pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();

#[derive(Debug)]
/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
pub enum BadIcon {
    /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
    /// safely interpreted as 32bpp RGBA pixels.
    ByteCountNotDivisibleBy4 { byte_count: usize },
    /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
    /// At least one of your arguments is incorrect.
    DimensionsVsPixelCount {
        width: u32,
        height: u32,
        width_x_height: usize,
        pixel_count: usize,
    },
    /// Produced when underlying OS functionality failed to create the icon
    OsError(io::Error),
}

impl fmt::Display for BadIcon {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
                "The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
                byte_count,
            ),
            BadIcon::DimensionsVsPixelCount {
                width,
                height,
                width_x_height,
                pixel_count,
            } => write!(f,
                "The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.",
                width, height, pixel_count, width_x_height,
            ),
            BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {:?}", e),
        }
    }
}

impl Error for BadIcon {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RgbaIcon {
    pub(crate) rgba: Vec<u8>,
    pub(crate) width: u32,
    pub(crate) height: u32,
}

/// For platforms which don't have window icons (e.g. web)
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NoIcon;

#[allow(dead_code)] // These are not used on every platform
mod constructors {
    use super::*;

    impl RgbaIcon {
        pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
            if !rgba.len().is_multiple_of(PIXEL_SIZE) {
                return Err(BadIcon::ByteCountNotDivisibleBy4 {
                    byte_count: rgba.len(),
                });
            }
            let pixel_count = rgba.len() / PIXEL_SIZE;
            if pixel_count != (width * height) as usize {
                Err(BadIcon::DimensionsVsPixelCount {
                    width,
                    height,
                    width_x_height: (width * height) as usize,
                    pixel_count,
                })
            } else {
                Ok(RgbaIcon {
                    rgba,
                    width,
                    height,
                })
            }
        }
    }

    impl NoIcon {
        pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
            // Create the rgba icon anyway to validate the input
            let _ = RgbaIcon::from_rgba(rgba, width, height)?;
            Ok(NoIcon)
        }
    }
}

/// An icon used for the window titlebar, taskbar, etc.
#[derive(Clone)]
pub struct Icon {
    pub(crate) inner: PlatformIcon,
    #[cfg(feature = "snapshot")]
    pub(crate) rgba: Option<RgbaIcon>,
}

impl fmt::Debug for Icon {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(&self.inner, formatter)
    }
}

impl Icon {
    /// Creates an icon from 32bpp RGBA data.
    ///
    /// The length of `rgba` must be divisible by 4, and `width * height` must equal
    /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
    pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
        #[cfg(feature = "snapshot")]
        {
            let rgba = RgbaIcon::from_rgba(rgba, width, height)?;
            Ok(Icon {
                inner: PlatformIcon::from_rgba(rgba.rgba.clone(), width, height)?,
                rgba: Some(rgba),
            })
        }

        #[cfg(not(feature = "snapshot"))]
        {
            Ok(Icon {
                inner: PlatformIcon::from_rgba(rgba, width, height)?,
            })
        }
    }

    /// Create an icon from a file path.
    ///
    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
    /// icon size from the file.
    ///
    /// In cases where the specified size does not exist in the file, Windows may perform scaling
    /// to get an icon of the desired size.
    #[cfg(windows)]
    pub fn from_path<P: AsRef<std::path::Path>>(
        path: P,
        size: Option<(u32, u32)>,
    ) -> Result<Self, BadIcon> {
        let win_icon = PlatformIcon::from_path(path, size)?;
        Ok(Icon {
            inner: win_icon,
            #[cfg(feature = "snapshot")]
            rgba: None,
        })
    }

    /// Create an icon from a resource embedded in this executable or library.
    ///
    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
    /// icon size from the file.
    ///
    /// In cases where the specified size does not exist in the file, Windows may perform scaling
    /// to get an icon of the desired size.
    #[cfg(windows)]
    pub fn from_resource(ordinal: u16, size: Option<(u32, u32)>) -> Result<Self, BadIcon> {
        let win_icon = PlatformIcon::from_resource(ordinal, size)?;
        Ok(Icon {
            inner: win_icon,
            #[cfg(feature = "snapshot")]
            rgba: None,
        })
    }
}

/// A native icon to be used for menu items.
///
/// Known variants use platform-native icon names or identifiers where an equivalent exists.
/// Use [`NativeIcon::Raw`] for a platform-specific value:
///
/// - **macOS / GTK 3 / GTK 4**: a native icon name string.
/// - **Windows**: a [`SHSTOCKICONID`] value.
///
/// [`SHSTOCKICONID`]: https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ne-shellapi-shstockiconid
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(windows, derive(Copy))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NativeIcon {
    /// An add item template image.
    Add,
    /// Advanced preferences toolbar icon for the preferences window.
    Advanced,
    /// A Bluetooth template image.
    Bluetooth,
    /// Bookmarks image suitable for a template.
    Bookmarks,
    /// A caution image.
    Caution,
    /// A color panel toolbar icon.
    ColorPanel,
    /// A column view mode template image.
    ColumnView,
    /// A computer icon.
    Computer,
    /// An enter full-screen mode template image.
    EnterFullScreen,
    /// Permissions for all users.
    Everyone,
    /// An exit full-screen mode template image.
    ExitFullScreen,
    /// A cover flow view mode template image.
    FlowView,
    /// A folder image.
    Folder,
    /// A burnable folder icon.
    FolderBurnable,
    /// A smart folder icon.
    FolderSmart,
    /// A link template image.
    FollowLinkFreestanding,
    /// A font panel toolbar icon.
    FontPanel,
    /// A `go back` template image.
    GoLeft,
    /// A `go forward` template image.
    GoRight,
    /// Home image suitable for a template.
    Home,
    /// An iChat Theater template image.
    IChatTheater,
    /// An icon view mode template image.
    IconView,
    /// An information toolbar icon.
    Info,
    /// A template image used to denote invalid data.
    InvalidDataFreestanding,
    /// A generic left-facing triangle template image.
    LeftFacingTriangle,
    /// A list view mode template image.
    ListView,
    /// A locked padlock template image.
    LockLocked,
    /// An unlocked padlock template image.
    LockUnlocked,
    /// A horizontal dash, for use in menus.
    MenuMixedState,
    /// A check mark template image, for use in menus.
    MenuOnState,
    /// A MobileMe icon.
    MobileMe,
    /// A drag image for multiple items.
    MultipleDocuments,
    /// A network icon.
    Network,
    /// A path button template image.
    Path,
    /// General preferences toolbar icon for the preferences window.
    PreferencesGeneral,
    /// A Quick Look template image.
    QuickLook,
    /// A refresh template image.
    RefreshFreestanding,
    /// A refresh template image.
    Refresh,
    /// A remove item template image.
    Remove,
    /// A reveal contents template image.
    RevealFreestanding,
    /// A generic right-facing triangle template image.
    RightFacingTriangle,
    /// A share view template image.
    Share,
    /// A slideshow template image.
    Slideshow,
    /// A badge for a `smart` item.
    SmartBadge,
    /// Small green indicator, similar to iChat's available image.
    StatusAvailable,
    /// Small clear indicator.
    StatusNone,
    /// Small yellow indicator, similar to iChat's idle image.
    StatusPartiallyAvailable,
    /// Small red indicator, similar to iChat's unavailable image.
    StatusUnavailable,
    /// A stop progress template image.
    StopProgressFreestanding,
    /// A stop progress button template image.
    StopProgress,
    /// An image of the empty trash can.
    TrashEmpty,
    /// An image of the full trash can.
    TrashFull,
    /// Permissions for a single user.
    User,
    /// User account toolbar icon for the preferences window.
    UserAccounts,
    /// Permissions for a group of users.
    UserGroup,
    /// Permissions for guests.
    UserGuest,
    /// A platform-specific native icon value.
    #[cfg(windows)]
    Raw(i32),
    /// A platform-specific native icon name.
    #[cfg(not(windows))]
    Raw(String),
}

impl NativeIcon {
    /// Creates a native icon from a Windows `SHSTOCKICONID`.
    #[cfg(windows)]
    pub fn from_id(id: i32) -> Self {
        Self::Raw(id)
    }

    /// Creates a native icon from a platform icon name.
    #[cfg(not(windows))]
    pub fn from_name<S: Into<String>>(icon: S) -> Self {
        Self::Raw(icon.into())
    }
}

#[cfg(windows)]
impl From<i32> for NativeIcon {
    fn from(id: i32) -> Self {
        Self::from_id(id)
    }
}

#[cfg(not(windows))]
impl From<String> for NativeIcon {
    fn from(icon: String) -> Self {
        Self::from_name(icon)
    }
}

#[cfg(not(windows))]
impl From<&str> for NativeIcon {
    fn from(icon: &str) -> Self {
        Self::from_name(icon)
    }
}

impl crate::NativeIcon {
    /// Returns the corresponding freedesktop icon name.
    pub fn freedesktop_name(&self) -> &str {
        match self {
            Self::Add => "list-add-symbolic",
            Self::Advanced => "preferences-system-symbolic",
            Self::Bluetooth => "bluetooth-symbolic",
            Self::Bookmarks => "user-bookmarks-symbolic",
            Self::Caution => "dialog-warning-symbolic",
            Self::ColorPanel => "applications-graphics-symbolic",
            Self::ColumnView => "view-list-symbolic",
            Self::Computer => "computer-symbolic",
            Self::EnterFullScreen => "view-fullscreen-symbolic",
            Self::Everyone => "system-users-symbolic",
            Self::ExitFullScreen => "view-restore-symbolic",
            Self::FlowView => "view-grid-symbolic",
            Self::Folder => "folder-symbolic",
            Self::FolderBurnable => "media-optical-symbolic",
            Self::FolderSmart => "folder-saved-search-symbolic",
            Self::FollowLinkFreestanding => "insert-link-symbolic",
            Self::FontPanel => "preferences-desktop-font-symbolic",
            Self::GoLeft => "go-previous-symbolic",
            Self::GoRight => "go-next-symbolic",
            Self::Home => "user-home-symbolic",
            Self::IChatTheater => "camera-video-symbolic",
            Self::IconView => "view-grid-symbolic",
            Self::Info => "dialog-information-symbolic",
            Self::InvalidDataFreestanding => "dialog-error-symbolic",
            Self::LeftFacingTriangle => "pan-start-symbolic",
            Self::ListView => "view-list-symbolic",
            Self::LockLocked => "changes-prevent-symbolic",
            Self::LockUnlocked => "changes-allow-symbolic",
            Self::MenuMixedState => "list-remove-symbolic",
            Self::MenuOnState => "object-select-symbolic",
            Self::MobileMe => "network-server-symbolic",
            Self::MultipleDocuments => "edit-copy-symbolic",
            Self::Network => "network-workgroup-symbolic",
            Self::Path => "document-open-recent-symbolic",
            Self::PreferencesGeneral => "preferences-system-symbolic",
            Self::QuickLook => "document-preview-symbolic",
            Self::RefreshFreestanding | Self::Refresh => "view-refresh-symbolic",
            Self::Remove => "list-remove-symbolic",
            Self::RevealFreestanding => "folder-open-symbolic",
            Self::RightFacingTriangle => "pan-end-symbolic",
            Self::Share => "emblem-shared-symbolic",
            Self::Slideshow => "view-presentation-symbolic",
            Self::SmartBadge => "emblem-favorite-symbolic",
            Self::StatusAvailable => "user-available-symbolic",
            Self::StatusNone => "user-offline-symbolic",
            Self::StatusPartiallyAvailable => "user-idle-symbolic",
            Self::StatusUnavailable => "user-busy-symbolic",
            Self::StopProgressFreestanding | Self::StopProgress => "process-stop-symbolic",
            Self::TrashEmpty => "user-trash-symbolic",
            Self::TrashFull => "user-trash-full-symbolic",
            Self::User => "avatar-default-symbolic",
            Self::UserAccounts | Self::UserGroup => "system-users-symbolic",
            Self::UserGuest => "avatar-default-symbolic",
            #[cfg(not(windows))]
            Self::Raw(name) => name,
            #[cfg(windows)]
            Self::Raw(_) => "unknown",
        }
    }
}