Skip to main content

native_gui_core/
tray.rs

1//! Portable system tray service model.
2//!
3//! Provides the shared, backend-agnostic specification and identifiers for
4//! system tray (notification area / status item) icons.
5//!
6//! Tray icons are application-level services owned directly by [`Ui`](crate::Ui),
7//! outside the hierarchical layout tree: they do not have a `WidgetId` and do
8//! not participate in hierarchical layout.
9
10use std::fmt;
11
12use crate::menus::MenuId;
13
14/// Stable identifier for a system tray / status bar icon.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct TrayIconId(pub u64);
17
18impl TrayIconId {
19    /// Returns the raw numeric identifier.
20    pub const fn get(self) -> u64 {
21        self.0
22    }
23}
24
25impl fmt::Display for TrayIconId {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "tray icon {}", self.0)
28    }
29}
30
31/// Specification for a system tray icon.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct TrayIconSpec {
34    /// Stable identifier for the tray icon.
35    pub id: TrayIconId,
36    /// Hover tooltip text.
37    pub tooltip: String,
38    /// Optional context menu bound to the tray icon.
39    pub menu: Option<MenuId>,
40    /// Whether the tray icon is visible in the status area.
41    pub visible: bool,
42    /// Optional raw icon pixels.
43    ///
44    /// The shared encoding contract is a **square straight-alpha RGBA
45    /// raster**: `side * side * 4` bytes in row-major order. A lane whose
46    /// native image loader recognises container formats may additionally
47    /// accept an encoded image (Cocoa decodes PNG/TIFF/ICNS/JPEG/GIF/BMP and
48    /// the ISO base media family); a payload that fits neither shape is
49    /// refused with a typed error. `None` leaves the icon on the platform
50    /// default image.
51    pub icon_bytes: Option<Vec<u8>>,
52}
53
54impl TrayIconSpec {
55    /// Creates a visible tray icon specification with default settings.
56    pub fn new(id: TrayIconId, tooltip: impl Into<String>) -> Self {
57        Self {
58            id,
59            tooltip: tooltip.into(),
60            menu: None,
61            visible: true,
62            icon_bytes: None,
63        }
64    }
65
66    /// Sets the context menu for the tray icon.
67    pub fn with_menu(mut self, menu: MenuId) -> Self {
68        self.menu = Some(menu);
69        self
70    }
71
72    /// Sets whether the tray icon is visible.
73    pub fn with_visible(mut self, visible: bool) -> Self {
74        self.visible = visible;
75        self
76    }
77
78    /// Sets the raw icon pixels for the tray icon.
79    ///
80    /// See [`TrayIconSpec::icon_bytes`] for the shared encoding contract
81    /// (square straight-alpha RGBA, or an encoded container the lane's loader
82    /// recognises).
83    pub fn with_icon_bytes(mut self, icon_bytes: Vec<u8>) -> Self {
84        self.icon_bytes = Some(icon_bytes);
85        self
86    }
87}
88
89/// Interaction events occurring on a system tray icon.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum TrayEvent {
92    /// Primary or single click on the tray icon.
93    Clicked { id: TrayIconId },
94    /// Double-click on the tray icon.
95    DoubleClicked { id: TrayIconId },
96    /// Secondary or right click on the tray icon.
97    RightClicked { id: TrayIconId },
98}
99
100impl TrayEvent {
101    /// Returns the target [`TrayIconId`] associated with this event.
102    pub fn id(&self) -> TrayIconId {
103        match self {
104            Self::Clicked { id } | Self::DoubleClicked { id } | Self::RightClicked { id } => *id,
105        }
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn tray_icon_id_display_and_helpers() {
115        let id = TrayIconId(42);
116        assert_eq!(id.get(), 42);
117        assert_eq!(format!("{id}"), "tray icon 42");
118    }
119
120    #[test]
121    fn tray_icon_spec_builder() {
122        let id = TrayIconId(1);
123        let spec = TrayIconSpec::new(id, "Test Tooltip")
124            .with_menu(MenuId(99))
125            .with_visible(false)
126            .with_icon_bytes(vec![1, 2, 3, 4]);
127
128        assert_eq!(spec.id, id);
129        assert_eq!(spec.tooltip, "Test Tooltip");
130        assert_eq!(spec.menu, Some(MenuId(99)));
131        assert!(!spec.visible);
132        assert_eq!(spec.icon_bytes, Some(vec![1, 2, 3, 4]));
133    }
134
135    #[test]
136    fn tray_event_helpers() {
137        let id = TrayIconId(7);
138        let ev1 = TrayEvent::Clicked { id };
139        let ev2 = TrayEvent::DoubleClicked { id };
140        let ev3 = TrayEvent::RightClicked { id };
141
142        assert_eq!(ev1.id(), id);
143        assert_eq!(ev2.id(), id);
144        assert_eq!(ev3.id(), id);
145    }
146}