| 1 | //! Tray icon on Linux through the StatusNotifierItem D-Bus protocol (KDE Plasma |
| 2 | //! natively; GNOME with the AppIndicator extension). |
| 3 | |
| 4 | use std::sync::Mutex; |
| 5 | use std::sync::mpsc::{Receiver, Sender, channel}; |
| 6 | |
| 7 | use chatsvc::ForcedKind; |
| 8 | use ksni::blocking::{Handle, TrayMethods as _}; |
| 9 | use ksni::menu::{CheckmarkItem, StandardItem, SubMenu}; |
| 10 | use ksni::{Category, Icon, MenuItem, ToolTip}; |
| 11 | |
| 12 | use super::{TrayCommand, TrayPresence}; |
| 13 | use crate::linux_desktop::DESKTOP_ID; |
| 14 | use crate::notify::tray_status; |
| 15 | |
| 16 | const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64]; |
| 17 | const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff]; |
| 18 | |
| 19 | #[derive(Clone)] |
| 20 | struct Labels { |
| 21 | open: String, |
| 22 | notifications: String, |
| 23 | quit: String, |
| 24 | duration: String, |
| 25 | reset: String, |
| 26 | } |
| 27 | |
| 28 | impl Labels { |
| 29 | fn current() -> Labels { |
| 30 | let tr = crate::ui_locale::tr; |
| 31 | Labels { |
| 32 | open: tr("tray.open"), |
| 33 | notifications: tr("tray.notifications"), |
| 34 | quit: tr("tray.quit"), |
| 35 | duration: tray_status::duration_menu_label().to_owned(), |
| 36 | reset: tray_status::reset_label().to_owned(), |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | struct Item { |
| 42 | commands: Sender<TrayCommand>, |
| 43 | labels: Labels, |
| 44 | title: String, |
| 45 | forced: Option<ForcedKind>, |
| 46 | mention: bool, |
| 47 | plain: Vec<Icon>, |
| 48 | dotted: Vec<Icon>, |
| 49 | } |
| 50 | |
| 51 | impl 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. |
| 58 | fn menu_label(text: &str) -> String { |
| 59 | text.replace('_', "__") |
| 60 | } |
| 61 | |
| 62 | fn status_submenu(item: &Item) -> MenuItem<Item> { |
| 63 | let mut entries = Vec::new(); |
| 64 | for kind in tray_status::STATUS_CHOICES { |
| 65 | let label = tray_status::choice_label(kind); |
| 66 | entries.push( |
| 67 | CheckmarkItem { |
| 68 | label: menu_label(label), |
| 69 | checked: item.forced == Some(kind), |
| 70 | activate: Box::new(move |item: &mut Item| { |
| 71 | item.send(TrayCommand::SetStatus(kind)) |
| 72 | }), |
| 73 | ..Default::default() |
| 74 | } |
| 75 | .into(), |
| 76 | ); |
| 77 | } |
| 78 | entries.push(MenuItem::Separator); |
| 79 | let duration_enabled = tray_status::duration_target(item.forced).is_some(); |
| 80 | let mut duration_items = Vec::new(); |
| 81 | for duration in tray_status::STATUS_DURATIONS { |
| 82 | duration_items.push( |
| 83 | StandardItem { |
| 84 | label: menu_label(tray_status::duration_label(duration)), |
| 85 | enabled: duration_enabled, |
| 86 | activate: Box::new(move |item: &mut Item| { |
| 87 | item.send(TrayCommand::SetStatusDuration(duration)) |
| 88 | }), |
| 89 | ..Default::default() |
| 90 | } |
| 91 | .into(), |
| 92 | ); |
| 93 | } |
| 94 | entries.push( |
| 95 | SubMenu { |
| 96 | label: menu_label(&item.labels.duration), |
| 97 | enabled: duration_enabled, |
| 98 | submenu: duration_items, |
| 99 | ..Default::default() |
| 100 | } |
| 101 | .into(), |
| 102 | ); |
| 103 | entries.push( |
| 104 | StandardItem { |
| 105 | label: menu_label(&item.labels.reset), |
| 106 | activate: Box::new(|item: &mut Item| item.send(TrayCommand::ResetStatus)), |
| 107 | ..Default::default() |
| 108 | } |
| 109 | .into(), |
| 110 | ); |
| 111 | SubMenu { |
| 112 | label: menu_label(&item.title), |
| 113 | submenu: entries, |
| 114 | ..Default::default() |
| 115 | } |
| 116 | .into() |
| 117 | } |
| 118 | |
| 119 | impl ksni::Tray for Item { |
| 120 | fn id(&self) -> String { |
| 121 | DESKTOP_ID.to_owned() |
| 122 | } |
| 123 | |
| 124 | fn title(&self) -> String { |
| 125 | crate::APP_NAME.to_owned() |
| 126 | } |
| 127 | |
| 128 | fn category(&self) -> Category { |
| 129 | Category::Communications |
| 130 | } |
| 131 | |
| 132 | fn icon_pixmap(&self) -> Vec<Icon> { |
| 133 | if self.mention { |
| 134 | self.dotted.clone() |
| 135 | } else { |
| 136 | self.plain.clone() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | fn tool_tip(&self) -> ToolTip { |
| 141 | ToolTip { |
| 142 | title: crate::APP_NAME.to_owned(), |
| 143 | ..Default::default() |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn activate(&mut self, _x: i32, _y: i32) { |
| 148 | self.send(TrayCommand::Toggle); |
| 149 | } |
| 150 | |
| 151 | fn menu(&self) -> Vec<MenuItem<Self>> { |
| 152 | vec![ |
| 153 | StandardItem { |
| 154 | label: menu_label(&self.labels.open), |
| 155 | activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)), |
| 156 | ..Default::default() |
| 157 | } |
| 158 | .into(), |
| 159 | MenuItem::Separator, |
| 160 | status_submenu(self), |
| 161 | StandardItem { |
| 162 | label: menu_label(&self.labels.notifications), |
| 163 | activate: Box::new(|item: &mut Self| item.send(TrayCommand::Notifications)), |
| 164 | ..Default::default() |
| 165 | } |
| 166 | .into(), |
| 167 | MenuItem::Separator, |
| 168 | StandardItem { |
| 169 | label: menu_label(&self.labels.quit), |
| 170 | icon_name: "application-exit".into(), |
| 171 | activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)), |
| 172 | ..Default::default() |
| 173 | } |
| 174 | .into(), |
| 175 | ] |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | pub struct Tray { |
| 180 | handle: Handle<Item>, |
| 181 | commands: Mutex<Receiver<TrayCommand>>, |
| 182 | } |
| 183 | |
| 184 | impl Tray { |
| 185 | /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher). |
| 186 | pub fn new(presence: TrayPresence, icon_png: &[u8]) -> Option<Self> { |
| 187 | let (plain, dotted) = tray_icons(icon_png)?; |
| 188 | let (sender, receiver) = channel(); |
| 189 | let item = Item { |
| 190 | commands: sender, |
| 191 | labels: Labels::current(), |
| 192 | title: presence.title, |
| 193 | forced: presence.forced, |
| 194 | mention: presence.mention, |
| 195 | plain, |
| 196 | dotted, |
| 197 | }; |
| 198 | let handle = match item.spawn() { |
| 199 | Ok(handle) => handle, |
| 200 | Err(error) => { |
| 201 | log::warn!("no tray icon: {error}"); |
| 202 | return None; |
| 203 | } |
| 204 | }; |
| 205 | Some(Tray { |
| 206 | handle, |
| 207 | commands: Mutex::new(receiver), |
| 208 | }) |
| 209 | } |
| 210 | |
| 211 | pub fn relocalize(&self) { |
| 212 | let labels = Labels::current(); |
| 213 | self.handle.update(move |item| item.labels = labels); |
| 214 | } |
| 215 | |
| 216 | pub fn poll(&self) -> Vec<TrayCommand> { |
| 217 | let Ok(receiver) = self.commands.lock() else { |
| 218 | return Vec::new(); |
| 219 | }; |
| 220 | receiver.try_iter().collect() |
| 221 | } |
| 222 | |
| 223 | pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) { |
| 224 | let Some((plain, dotted)) = tray_icons(icon_png) else { |
| 225 | return; |
| 226 | }; |
| 227 | self.handle.update(move |item| { |
| 228 | item.plain = plain; |
| 229 | item.dotted = dotted; |
| 230 | item.mention = mention; |
| 231 | }); |
| 232 | } |
| 233 | |
| 234 | pub fn sync(&self, presence: TrayPresence) { |
| 235 | let labels = Labels::current(); |
| 236 | self.handle.update(move |item| { |
| 237 | item.labels = labels; |
| 238 | item.title = presence.title; |
| 239 | item.forced = presence.forced; |
| 240 | item.mention = presence.mention; |
| 241 | }); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | impl Drop for Tray { |
| 246 | fn drop(&mut self) { |
| 247 | let _ = self.handle.shutdown(); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian. |
| 252 | fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> { |
| 253 | let decoded = image::load_from_memory(icon_png).ok()?; |
| 254 | let mut plain = Vec::new(); |
| 255 | let mut dotted = Vec::new(); |
| 256 | for size in TRAY_ICON_SIZES { |
| 257 | let resized = decoded |
| 258 | .resize_exact(size, size, image::imageops::FilterType::Lanczos3) |
| 259 | .to_rgba8(); |
| 260 | let mut with_dot = resized.clone(); |
| 261 | let radius = size as f32 * 0.22; |
| 262 | let center = size as f32 - radius - 0.5; |
| 263 | for (column, row, pixel) in with_dot.enumerate_pixels_mut() { |
| 264 | let distance = ((column as f32 + 0.5 - center).powi(2) |
| 265 | + (row as f32 + 0.5 - center).powi(2)) |
| 266 | .sqrt(); |
| 267 | if distance <= radius { |
| 268 | *pixel = image::Rgba(DOT_COLOR); |
| 269 | } |
| 270 | } |
| 271 | plain.push(argb_icon(size, resized.as_raw())); |
| 272 | dotted.push(argb_icon(size, with_dot.as_raw())); |
| 273 | } |
| 274 | Some((plain, dotted)) |
| 275 | } |
| 276 | |
| 277 | fn argb_icon(size: u32, rgba: &[u8]) -> Icon { |
| 278 | let data = rgba |
| 279 | .chunks_exact(4) |
| 280 | .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]]) |
| 281 | .collect(); |
| 282 | Icon { |
| 283 | width: size as i32, |
| 284 | height: size as i32, |
| 285 | data, |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[cfg(test)] |
| 290 | mod tests { |
| 291 | use super::*; |
| 292 | |
| 293 | #[test] |
| 294 | fn icons_come_in_every_size_as_argb() { |
| 295 | let png = crate::appearance::AppIcon::RustyTeams.png(); |
| 296 | let (plain, dotted) = tray_icons(png).unwrap(); |
| 297 | assert_eq!(plain.len(), TRAY_ICON_SIZES.len()); |
| 298 | for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) { |
| 299 | assert_eq!((icon.width, icon.height), (size as i32, size as i32)); |
| 300 | assert_eq!(icon.data.len(), (size * size * 4) as usize); |
| 301 | } |
| 302 | let last = dotted.last().unwrap(); |
| 303 | let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12); |
| 304 | assert_eq!( |
| 305 | &last.data[bottom_right..bottom_right + 4], |
| 306 | &[0xff, 0xef, 0x44, 0x44] |
| 307 | ); |
| 308 | assert!(tray_icons(b"not a png").is_none()); |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn argb_moves_alpha_first() { |
| 313 | let icon = argb_icon(1, &[1, 2, 3, 4]); |
| 314 | assert_eq!(icon.data, vec![4, 1, 2, 3]); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn underscores_stay_visible_in_menu_labels() { |
| 319 | assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb"); |
| 320 | } |
| 321 | |
| 322 | #[test] |
| 323 | fn status_submenu_lists_every_choice_and_reset() { |
| 324 | let (sender, _receiver) = channel(); |
| 325 | let item = Item { |
| 326 | commands: sender, |
| 327 | labels: Labels::current(), |
| 328 | title: "Available".into(), |
| 329 | forced: Some(ForcedKind::Busy), |
| 330 | mention: false, |
| 331 | plain: Vec::new(), |
| 332 | dotted: Vec::new(), |
| 333 | }; |
| 334 | let MenuItem::SubMenu(menu) = status_submenu(&item) else { |
| 335 | panic!("expected status submenu"); |
| 336 | }; |
| 337 | assert_eq!(menu.label, "Available"); |
| 338 | let labels: Vec<_> = menu |
| 339 | .submenu |
| 340 | .iter() |
| 341 | .filter_map(|entry| match entry { |
| 342 | MenuItem::Checkmark(item) => Some(item.label.as_str()), |
| 343 | MenuItem::Standard(item) => Some(item.label.as_str()), |
| 344 | MenuItem::SubMenu(item) => Some(item.label.as_str()), |
| 345 | _ => None, |
| 346 | }) |
| 347 | .collect(); |
| 348 | for kind in tray_status::STATUS_CHOICES { |
| 349 | assert!(labels.contains(&tray_status::choice_label(kind))); |
| 350 | } |
| 351 | assert!(labels.contains(&tray_status::reset_label())); |
| 352 | assert!(labels.contains(&tray_status::duration_menu_label())); |
| 353 | } |
| 354 | } |