1use 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#[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 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 pub fn tooltip(mut self, text: impl Into<String>) -> Self {
51 self.tooltip = Some(text.into());
52 self
53 }
54
55 pub fn item(mut self, item: &MenuItem) -> Self {
57 self.items.push(item.clone());
58 self
59 }
60
61 #[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
72pub type TrayItem = MenuItem;
74
75pub(crate) const QUIT: &str = "hypersig-desktop-tray-quit";
77
78pub(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
112fn 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 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}