#[cfg(any(target_os = "linux", target_os = "windows"))] use crate::lang::w; pub const AVAILABLE: bool = cfg!(any(target_os = "linux", target_os = "windows")); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TrayAction { Show, Quit, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct TrayState { pub messages: u32, pub mentions: u32, } pub struct TrayHandle(Box); impl TrayHandle { pub fn set(&self, state: TrayState) { (self.0)(state); } } #[cfg(target_os = "linux")] pub use linux::start; #[cfg(target_os = "windows")] pub use windows::start; #[cfg(not(any(target_os = "linux", target_os = "windows")))] pub fn start() -> (tokio::sync::mpsc::UnboundedReceiver, TrayHandle) { ( tokio::sync::mpsc::unbounded_channel().1, TrayHandle(Box::new(|_| {})), ) } #[cfg(any(target_os = "linux", target_os = "windows"))] #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Badge { None, Unread, Mention, } #[cfg(any(target_os = "linux", target_os = "windows"))] impl TrayState { fn badge(self) -> Badge { match (self.messages, self.mentions) { (_, 1..) => Badge::Mention, (1.., _) => Badge::Unread, _ => Badge::None, } } fn tip(self) -> String { match self.badge() { Badge::None => crate::NAME.to_string(), _ => w().tray.tip(self.mentions, self.messages, crate::NAME), } } } #[cfg(any(target_os = "linux", target_os = "windows"))] const ICON_SIZE: i32 = 32; #[cfg(any(target_os = "linux", target_os = "windows"))] const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); #[cfg(any(target_os = "linux", target_os = "windows"))] const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; #[cfg(any(target_os = "linux", target_os = "windows"))] const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; #[cfg(any(target_os = "linux", target_os = "windows"))] fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); (radius - distance + 0.5).clamp(0.0, 1.0) } #[cfg(any(target_os = "linux", target_os = "windows"))] fn logo() -> Vec<([u8; 3], u8)> { crate::logo::rgba(ICON_SIZE as u32) .as_chunks::<4>() .0 .iter() .map(|&[r, g, b, a]| ([r, g, b], a)) .collect() } #[cfg(any(target_os = "linux", target_os = "windows"))] fn pixels(badge: Badge) -> impl Iterator { let dot = match badge { Badge::None => None, Badge::Unread => Some(UNREAD_COLOR), Badge::Mention => Some(MENTION_COLOR), }; logo().into_iter().enumerate().map(move |(index, base)| { let x = (index as i32 % ICON_SIZE) as f32 + 0.5; let y = (index as i32 / ICON_SIZE) as f32 + 0.5; match dot { Some(color) if coverage(x, y, BADGE) > 0.0 => { (color, (coverage(x, y, BADGE) * 255.0) as u8) } Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => (base.0, 0), _ => base, } }) } #[cfg(target_os = "linux")] mod linux { use ksni::TrayMethods; use tokio::sync::mpsc; use tracing::warn; use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; use crate::lang::w; pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { let (sender, receiver) = mpsc::unbounded_channel(); let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); let tray = Tray { sender, state: TrayState::default(), }; crate::spawn_runtime("tray", move || async move { match tray.assume_sni_available(true).spawn().await { Ok(handle) => { while let Some(state) = state_receiver.recv().await { handle.update(|tray| tray.state = state).await; } std::future::pending::<()>().await } Err(error) => warn!("tray: {error}"), } }); ( receiver, TrayHandle(Box::new(move |state| { let _ = state_sender.send(state); })), ) } struct Tray { sender: mpsc::UnboundedSender, state: TrayState, } impl ksni::Tray for Tray { fn id(&self) -> String { crate::NAME.to_string() } fn title(&self) -> String { crate::NAME.to_string() } fn icon_pixmap(&self) -> Vec { vec![icon(self.state.badge())] } fn status(&self) -> ksni::Status { match self.state.badge() { Badge::Mention => ksni::Status::NeedsAttention, _ => ksni::Status::Active, } } fn tool_tip(&self) -> ksni::ToolTip { ksni::ToolTip { title: self.state.tip(), ..Default::default() } } fn activate(&mut self, _x: i32, _y: i32) { let _ = self.sender.send(TrayAction::Show); } fn menu(&self) -> Vec> { use ksni::menu::StandardItem; vec![ StandardItem { label: w().tray.show.to_string(), activate: Box::new(|tray: &mut Self| { let _ = tray.sender.send(TrayAction::Show); }), ..Default::default() } .into(), StandardItem { label: w().tray.quit.to_string(), activate: Box::new(|tray: &mut Self| { let _ = tray.sender.send(TrayAction::Quit); }), ..Default::default() } .into(), ] } } fn icon(badge: Badge) -> ksni::Icon { ksni::Icon { width: ICON_SIZE, height: ICON_SIZE, data: pixels(badge) .flat_map(|([red, green, blue], alpha)| [alpha, red, green, blue]) .collect(), } } } #[cfg(target_os = "windows")] mod windows { use tokio::sync::mpsc; use tracing::warn; use tray_icon::{ Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent, menu::{Menu, MenuEvent, MenuItem}, }; use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; use crate::lang::w; fn icon(badge: Badge) -> Option { let rgba = pixels(badge) .flat_map(|([red, green, blue], alpha)| [red, green, blue, alpha]) .collect(); Icon::from_rgba(rgba, ICON_SIZE as u32, ICON_SIZE as u32).ok() } pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { let (sender, receiver) = mpsc::unbounded_channel(); let show = MenuItem::new(w().tray.show, true, None); let quit = MenuItem::new(w().tray.quit, true, None); let menu = Menu::new(); if let Err(error) = menu.append_items(&[&show, &quit]) { warn!("tray menu: {error}"); } let (show_id, quit_id) = (show.id().clone(), quit.id().clone()); let menu_sender = sender.clone(); MenuEvent::set_event_handler(Some(std::sync::Arc::new(move |event: MenuEvent| { let action = if event.id == show_id { TrayAction::Show } else if event.id == quit_id { TrayAction::Quit } else { return; }; let _ = menu_sender.send(action); }))); TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| { if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { let _ = sender.send(TrayAction::Show); } })); let mut builder = TrayIconBuilder::new() .with_menu(Box::new(menu)) .with_tooltip(crate::NAME); if let Some(icon) = icon(Badge::None) { builder = builder.with_icon(icon); } let handle = match builder.build() { Ok(tray) => TrayHandle(Box::new(move |state: TrayState| { let _ = tray.set_icon(icon(state.badge())); let _ = tray.set_tooltip(Some(state.tip())); })), Err(error) => { warn!("tray: {error}"); TrayHandle(Box::new(|_| {})) } }; (receiver, handle) } } #[cfg(all(test, any(target_os = "linux", target_os = "windows")))] mod tests { #[test] fn logo_renders() { let pixels = super::logo(); assert_eq!(pixels.len(), (super::ICON_SIZE * super::ICON_SIZE) as usize); assert!( pixels .iter() .any(|(color, alpha)| *alpha == 255 && color[0] > 200) ); } }