Skip to main content

hypersig_desktop/
tray.rs

1//! The icon in the system tray, with a menu of items whose clicks reach the
2//! application: the menu bar on macOS, the notification area on Windows,
3//! and the `StatusNotifierItem` tray of the desktop on Linux.
4
5use std::fmt;
6use std::sync::Arc;
7
8use tray_icon::menu::{Menu, MenuItem as SystemItem, PredefinedMenuItem};
9use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
10
11use crate::error::Error;
12use crate::item::MenuItem;
13
14/// An icon in the system tray with a menu, for [`Os::tray`](crate::Os::tray).
15///
16/// While it is shown, closing the last window leaves the application
17/// running, and its Quit item ends it.
18#[derive(Clone)]
19#[must_use = "a tray shows only when it is given to `Os::tray`"]
20pub struct Tray {
21    pub(crate) icon: Arc<[u8]>,
22    pub(crate) quit: String,
23    pub(crate) tooltip: Option<String>,
24    pub(crate) items: Vec<MenuItem>,
25}
26
27impl fmt::Debug for Tray {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.debug_struct("Tray")
30            .field("quit", &self.quit)
31            .field("tooltip", &self.tooltip)
32            .field("items", &self.items)
33            .finish_non_exhaustive()
34    }
35}
36
37impl Tray {
38    /// A tray icon drawn from `png`, whose menu ends with an item labeled
39    /// `quit` that ends the application.
40    pub fn new(png: impl Into<Arc<[u8]>>, quit: impl Into<String>) -> Self {
41        Self {
42            icon: png.into(),
43            quit: quit.into(),
44            tooltip: None,
45            items: Vec::new(),
46        }
47    }
48
49    /// Shows `text` while the pointer rests on the icon.
50    pub fn tooltip(mut self, text: impl Into<String>) -> Self {
51        self.tooltip = Some(text.into());
52        self
53    }
54
55    /// Adds `item` to the menu, above the items added after it.
56    pub fn item(mut self, item: &MenuItem) -> Self {
57        self.items.push(item.clone());
58        self
59    }
60
61    /// The labels of the menu's items, the Quit item last.
62    #[must_use]
63    pub fn labels(&self) -> Vec<&str> {
64        self.items
65            .iter()
66            .map(|item| item.label.as_str())
67            .chain(std::iter::once(self.quit.as_str()))
68            .collect()
69    }
70}
71
72/// An item of a [`Tray`]'s menu, the same type as a [`MenuItem`] of the menu bar.
73pub type TrayItem = MenuItem;
74
75/// The id of the Quit item of every tray.
76pub(crate) const QUIT: &str = "hypersig-desktop-tray-quit";
77
78/// Makes the tray icon `tray` describes. The icon lasts as long as the
79/// returned value, and its menu's clicks arrive as `muda::MenuEvent`s.
80///
81/// # Errors
82///
83/// Fails when `png` is not a PNG, and when the system has no tray to put
84/// the icon in.
85pub(crate) fn show(tray: &Tray) -> Result<TrayIcon, Error> {
86    let icon = decode(&tray.icon)?;
87    let menu = Menu::new();
88    for item in &tray.items {
89        menu.append(&SystemItem::with_id(
90            item.id.clone(),
91            &item.label,
92            true,
93            None,
94        ))
95        .map_err(Error::tray)?;
96    }
97    if !tray.items.is_empty() {
98        menu.append(&PredefinedMenuItem::separator())
99            .map_err(Error::tray)?;
100    }
101    menu.append(&SystemItem::with_id(QUIT, &tray.quit, true, None))
102        .map_err(Error::tray)?;
103    let mut builder = TrayIconBuilder::new()
104        .with_icon(icon)
105        .with_menu(Box::new(menu));
106    if let Some(tooltip) = &tray.tooltip {
107        builder = builder.with_tooltip(tooltip);
108    }
109    builder.build().map_err(Error::tray)
110}
111
112/// The pixels of the PNG `bytes`, as the tray takes them.
113fn decode(bytes: &[u8]) -> Result<Icon, Error> {
114    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
115    decoder.set_transformations(
116        png::Transformations::normalize_to_color8() | png::Transformations::ALPHA,
117    );
118    let mut reader = decoder.read_info().map_err(Error::tray)?;
119    let mut pixels = vec![
120        0;
121        reader
122            .output_buffer_size()
123            .ok_or_else(|| Error::tray("the PNG is too large"))?
124    ];
125    let frame = reader.next_frame(&mut pixels).map_err(Error::tray)?;
126    pixels.truncate(frame.buffer_size());
127    let rgba = match frame.color_type {
128        png::ColorType::Rgba => pixels,
129        png::ColorType::GrayscaleAlpha => pixels
130            .as_chunks::<2>()
131            .0
132            .iter()
133            .flat_map(|&[gray, alpha]| [gray, gray, gray, alpha])
134            .collect(),
135        other => {
136            return Err(Error::tray(format!(
137                "the PNG's pixels are {other:?}, not RGBA"
138            )));
139        }
140    };
141    Icon::from_rgba(rgba, frame.width, frame.height).map_err(Error::tray)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::{Tray, TrayItem, decode};
147
148    /// A 2 by 2 red PNG.
149    fn red() -> Vec<u8> {
150        let mut bytes = Vec::new();
151        let mut encoder = png::Encoder::new(&mut bytes, 2, 2);
152        encoder.set_color(png::ColorType::Rgba);
153        encoder.set_depth(png::BitDepth::Eight);
154        let mut writer = encoder
155            .write_header()
156            .unwrap_or_else(|error| panic!("{error}"));
157        writer
158            .write_image_data(&[255, 0, 0, 255].repeat(4))
159            .unwrap_or_else(|error| panic!("{error}"));
160        drop(writer);
161        bytes
162    }
163
164    #[test]
165    fn a_png_is_decoded_and_bytes_that_are_not_one_are_refused() {
166        decode(&red()).unwrap_or_else(|error| panic!("{error}"));
167        decode(b"not a png").map(|_| ()).unwrap_err();
168    }
169
170    #[test]
171    fn the_quit_item_comes_last() {
172        let show = TrayItem::new("Show");
173        let tray = Tray::new(red(), "Quit").item(&show);
174        assert_eq!(tray.labels(), ["Show", "Quit"]);
175        assert_ne!(TrayItem::new("A").id, TrayItem::new("A").id);
176    }
177}