//! Tray icon on Linux through the StatusNotifierItem D-Bus protocol (KDE Plasma //! natively; GNOME with the AppIndicator extension). use std::sync::Mutex; use std::sync::mpsc::{Receiver, Sender, channel}; use ksni::blocking::{Handle, TrayMethods as _}; use ksni::menu::{CheckmarkItem, StandardItem}; use ksni::{Category, Icon, MenuItem, ToolTip}; use super::TrayCommand; use crate::linux_desktop::DESKTOP_ID; const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64]; const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff]; #[derive(Clone)] struct Labels { open: String, mute_sound: String, do_not_disturb: String, notifications: String, quit: String, } impl Labels { fn current() -> Labels { let tr = crate::ui_locale::tr; Labels { open: tr("tray.open"), mute_sound: tr("tray.mute_sound"), do_not_disturb: tr("tray.do_not_disturb"), notifications: tr("tray.notifications"), quit: tr("tray.quit"), } } } struct Item { commands: Sender, labels: Labels, sound_on: bool, do_not_disturb: bool, mention: bool, plain: Vec, dotted: Vec, } impl Item { fn send(&self, command: TrayCommand) { let _ = self.commands.send(command); } } /// Escapes the mnemonic underscores of a menu label. fn menu_label(text: &str) -> String { text.replace('_', "__") } impl ksni::Tray for Item { fn id(&self) -> String { DESKTOP_ID.to_owned() } fn title(&self) -> String { crate::APP_NAME.to_owned() } fn category(&self) -> Category { Category::Communications } fn icon_pixmap(&self) -> Vec { if self.mention { self.dotted.clone() } else { self.plain.clone() } } fn tool_tip(&self) -> ToolTip { ToolTip { title: crate::APP_NAME.to_owned(), ..Default::default() } } fn activate(&mut self, _x: i32, _y: i32) { self.send(TrayCommand::Toggle); } fn menu(&self) -> Vec> { vec![ StandardItem { label: menu_label(&self.labels.open), activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)), ..Default::default() } .into(), MenuItem::Separator, CheckmarkItem { label: menu_label(&self.labels.mute_sound), checked: !self.sound_on, activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)), ..Default::default() } .into(), CheckmarkItem { label: menu_label(&self.labels.do_not_disturb), checked: self.do_not_disturb, activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)), ..Default::default() } .into(), StandardItem { label: menu_label(&self.labels.notifications), activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)), ..Default::default() } .into(), MenuItem::Separator, StandardItem { label: menu_label(&self.labels.quit), icon_name: "application-exit".into(), activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)), ..Default::default() } .into(), ] } } pub struct Tray { handle: Handle, commands: Mutex>, } impl Tray { /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher). pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option { let (plain, dotted) = tray_icons(icon_png)?; let (sender, receiver) = channel(); let item = Item { commands: sender, labels: Labels::current(), sound_on, do_not_disturb, mention: false, plain, dotted, }; let handle = match item.spawn() { Ok(handle) => handle, Err(error) => { log::warn!("no tray icon: {error}"); return None; } }; Some(Tray { handle, commands: Mutex::new(receiver), }) } pub fn relocalize(&self) { let labels = Labels::current(); self.handle.update(move |item| item.labels = labels); } pub fn poll(&self) -> Vec { let Ok(receiver) = self.commands.lock() else { return Vec::new(); }; receiver.try_iter().collect() } pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) { let Some((plain, dotted)) = tray_icons(icon_png) else { return; }; self.handle.update(move |item| { item.plain = plain; item.dotted = dotted; item.mention = mention; }); } pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) { let labels = Labels::current(); self.handle.update(move |item| { item.labels = labels; item.sound_on = sound_on; item.do_not_disturb = do_not_disturb; item.mention = mention; }); } } impl Drop for Tray { fn drop(&mut self) { let _ = self.handle.shutdown(); } } /// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian. fn tray_icons(icon_png: &[u8]) -> Option<(Vec, Vec)> { let decoded = image::load_from_memory(icon_png).ok()?; let mut plain = Vec::new(); let mut dotted = Vec::new(); for size in TRAY_ICON_SIZES { let resized = decoded .resize_exact(size, size, image::imageops::FilterType::Lanczos3) .to_rgba8(); let mut with_dot = resized.clone(); let radius = size as f32 * 0.22; let center = size as f32 - radius - 0.5; for (column, row, pixel) in with_dot.enumerate_pixels_mut() { let distance = ((column as f32 + 0.5 - center).powi(2) + (row as f32 + 0.5 - center).powi(2)) .sqrt(); if distance <= radius { *pixel = image::Rgba(DOT_COLOR); } } plain.push(argb_icon(size, resized.as_raw())); dotted.push(argb_icon(size, with_dot.as_raw())); } Some((plain, dotted)) } fn argb_icon(size: u32, rgba: &[u8]) -> Icon { let data = rgba .chunks_exact(4) .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]]) .collect(); Icon { width: size as i32, height: size as i32, data, } } #[cfg(test)] mod tests { use super::*; #[test] fn icons_come_in_every_size_as_argb() { let png = crate::appearance::AppIcon::RustyTeams.png(); let (plain, dotted) = tray_icons(png).unwrap(); assert_eq!(plain.len(), TRAY_ICON_SIZES.len()); for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) { assert_eq!((icon.width, icon.height), (size as i32, size as i32)); assert_eq!(icon.data.len(), (size * size * 4) as usize); } let last = dotted.last().unwrap(); let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12); assert_eq!( &last.data[bottom_right..bottom_right + 4], &[0xff, 0xef, 0x44, 0x44] ); assert!(tray_icons(b"not a png").is_none()); } #[test] fn argb_moves_alpha_first() { let icon = argb_icon(1, &[1, 2, 3, 4]); assert_eq!(icon.data, vec![4, 1, 2, 3]); } #[test] fn underscores_stay_visible_in_menu_labels() { assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb"); } }