BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / notify / platform / linux_tray.rs

linux_tray.rs

09e74698 History
linux_tray.rs 7.9 KiB Download Raw
1//! Tray icon on Linux through the StatusNotifierItem D-Bus protocol (KDE Plasma
2//! natively; GNOME with the AppIndicator extension).
3
4use std::sync::Mutex;
5use std::sync::mpsc::{Receiver, Sender, channel};
6
7use ksni::blocking::{Handle, TrayMethods as _};
8use ksni::menu::{CheckmarkItem, StandardItem};
9use ksni::{Category, Icon, MenuItem, ToolTip};
10
11use super::TrayCommand;
12
13/// The window and desktop entry id (`rusty-teams.desktop`).
14const DESKTOP_ID: &str = "rusty-teams";
15
16const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
17const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
18
19#[derive(Clone)]
20struct Labels {
21 open: String,
22 mute_sound: String,
23 do_not_disturb: String,
24 notifications: String,
25 quit: String,
26}
27
28impl Labels {
29 fn current() -> Labels {
30 let tr = crate::ui_locale::tr;
31 Labels {
32 open: tr("tray.open"),
33 mute_sound: tr("tray.mute_sound"),
34 do_not_disturb: tr("tray.do_not_disturb"),
35 notifications: tr("tray.notifications"),
36 quit: tr("tray.quit"),
37 }
38 }
39}
40
41struct Item {
42 commands: Sender<TrayCommand>,
43 labels: Labels,
44 sound_on: bool,
45 do_not_disturb: bool,
46 mention: bool,
47 plain: Vec<Icon>,
48 dotted: Vec<Icon>,
49}
50
51impl Item {
52 fn send(&self, command: TrayCommand) {
53 let _ = self.commands.send(command);
54 }
55}
56
57/// Escapes the mnemonic underscores of a menu label.
58fn menu_label(text: &str) -> String {
59 text.replace('_', "__")
60}
61
62impl ksni::Tray for Item {
63 fn id(&self) -> String {
64 DESKTOP_ID.to_owned()
65 }
66
67 fn title(&self) -> String {
68 crate::APP_NAME.to_owned()
69 }
70
71 fn category(&self) -> Category {
72 Category::Communications
73 }
74
75 fn icon_pixmap(&self) -> Vec<Icon> {
76 if self.mention {
77 self.dotted.clone()
78 } else {
79 self.plain.clone()
80 }
81 }
82
83 fn tool_tip(&self) -> ToolTip {
84 ToolTip {
85 title: crate::APP_NAME.to_owned(),
86 ..Default::default()
87 }
88 }
89
90 fn activate(&mut self, _x: i32, _y: i32) {
91 self.send(TrayCommand::Toggle);
92 }
93
94 fn menu(&self) -> Vec<MenuItem<Self>> {
95 vec![
96 StandardItem {
97 label: menu_label(&self.labels.open),
98 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)),
99 ..Default::default()
100 }
101 .into(),
102 MenuItem::Separator,
103 CheckmarkItem {
104 label: menu_label(&self.labels.mute_sound),
105 checked: !self.sound_on,
106 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)),
107 ..Default::default()
108 }
109 .into(),
110 CheckmarkItem {
111 label: menu_label(&self.labels.do_not_disturb),
112 checked: self.do_not_disturb,
113 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)),
114 ..Default::default()
115 }
116 .into(),
117 StandardItem {
118 label: menu_label(&self.labels.notifications),
119 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)),
120 ..Default::default()
121 }
122 .into(),
123 MenuItem::Separator,
124 StandardItem {
125 label: menu_label(&self.labels.quit),
126 icon_name: "application-exit".into(),
127 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)),
128 ..Default::default()
129 }
130 .into(),
131 ]
132 }
133}
134
135pub struct Tray {
136 handle: Handle<Item>,
137 commands: Mutex<Receiver<TrayCommand>>,
138}
139
140impl Tray {
141 /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher).
142 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
143 let (plain, dotted) = tray_icons(icon_png)?;
144 let (sender, receiver) = channel();
145 let item = Item {
146 commands: sender,
147 labels: Labels::current(),
148 sound_on,
149 do_not_disturb,
150 mention: false,
151 plain,
152 dotted,
153 };
154 let handle = match item.spawn() {
155 Ok(handle) => handle,
156 Err(error) => {
157 log::warn!("no tray icon: {error}");
158 return None;
159 }
160 };
161 Some(Tray {
162 handle,
163 commands: Mutex::new(receiver),
164 })
165 }
166
167 pub fn relocalize(&self) {
168 let labels = Labels::current();
169 self.handle.update(move |item| item.labels = labels);
170 }
171
172 pub fn poll(&self) -> Vec<TrayCommand> {
173 let Ok(receiver) = self.commands.lock() else {
174 return Vec::new();
175 };
176 receiver.try_iter().collect()
177 }
178
179 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
180 let Some((plain, dotted)) = tray_icons(icon_png) else {
181 return;
182 };
183 self.handle.update(move |item| {
184 item.plain = plain;
185 item.dotted = dotted;
186 item.mention = mention;
187 });
188 }
189
190 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
191 let labels = Labels::current();
192 self.handle.update(move |item| {
193 item.labels = labels;
194 item.sound_on = sound_on;
195 item.do_not_disturb = do_not_disturb;
196 item.mention = mention;
197 });
198 }
199}
200
201impl Drop for Tray {
202 fn drop(&mut self) {
203 let _ = self.handle.shutdown();
204 }
205}
206
207/// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian.
208fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> {
209 let decoded = image::load_from_memory(icon_png).ok()?;
210 let mut plain = Vec::new();
211 let mut dotted = Vec::new();
212 for size in TRAY_ICON_SIZES {
213 let resized = decoded
214 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
215 .to_rgba8();
216 let mut with_dot = resized.clone();
217 let radius = size as f32 * 0.22;
218 let center = size as f32 - radius - 0.5;
219 for (column, row, pixel) in with_dot.enumerate_pixels_mut() {
220 let distance = ((column as f32 + 0.5 - center).powi(2)
221 + (row as f32 + 0.5 - center).powi(2))
222 .sqrt();
223 if distance <= radius {
224 *pixel = image::Rgba(DOT_COLOR);
225 }
226 }
227 plain.push(argb_icon(size, resized.as_raw()));
228 dotted.push(argb_icon(size, with_dot.as_raw()));
229 }
230 Some((plain, dotted))
231}
232
233fn argb_icon(size: u32, rgba: &[u8]) -> Icon {
234 let data = rgba
235 .chunks_exact(4)
236 .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]])
237 .collect();
238 Icon {
239 width: size as i32,
240 height: size as i32,
241 data,
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 #[test]
250 fn icons_come_in_every_size_as_argb() {
251 let png = crate::appearance::AppIcon::RustyTeams.png();
252 let (plain, dotted) = tray_icons(png).unwrap();
253 assert_eq!(plain.len(), TRAY_ICON_SIZES.len());
254 for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) {
255 assert_eq!((icon.width, icon.height), (size as i32, size as i32));
256 assert_eq!(icon.data.len(), (size * size * 4) as usize);
257 }
258 let last = dotted.last().unwrap();
259 let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12);
260 assert_eq!(
261 &last.data[bottom_right..bottom_right + 4],
262 &[0xff, 0xef, 0x44, 0x44]
263 );
264 assert!(tray_icons(b"not a png").is_none());
265 }
266
267 #[test]
268 fn argb_moves_alpha_first() {
269 let icon = argb_icon(1, &[1, 2, 3, 4]);
270 assert_eq!(icon.data, vec![4, 1, 2, 3]);
271 }
272
273 #[test]
274 fn underscores_stay_visible_in_menu_labels() {
275 assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb");
276 }
277}