BlueGit

ict rusty-teams

Files

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

linux_tray.rs

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