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