forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

tray.rs313 lines, 9.5 KiBHistoryRawDownload
1#[cfg(any(target_os = "linux", target_os = "windows"))]
2use crate::lang::w;
3
4pub const AVAILABLE: bool = cfg!(any(target_os = "linux", target_os = "windows"));
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum TrayAction {
8 Show,
9 Quit,
10}
11
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13pub struct TrayState {
14 pub messages: u32,
15 pub mentions: u32,
16}
17
18pub struct TrayHandle(Box<dyn Fn(TrayState)>);
19
20impl TrayHandle {
21 pub fn set(&self, state: TrayState) {
22 (self.0)(state);
23 }
24}
25
26#[cfg(target_os = "linux")]
27pub use linux::start;
28#[cfg(target_os = "windows")]
29pub use windows::start;
30
31#[cfg(not(any(target_os = "linux", target_os = "windows")))]
32pub fn start() -> (tokio::sync::mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
33 (
34 tokio::sync::mpsc::unbounded_channel().1,
35 TrayHandle(Box::new(|_| {})),
36 )
37}
38
39#[cfg(any(target_os = "linux", target_os = "windows"))]
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41enum Badge {
42 None,
43 Unread,
44 Mention,
45}
46
47#[cfg(any(target_os = "linux", target_os = "windows"))]
48impl TrayState {
49 fn badge(self) -> Badge {
50 match (self.messages, self.mentions) {
51 (_, 1..) => Badge::Mention,
52 (1.., _) => Badge::Unread,
53 _ => Badge::None,
54 }
55 }
56
57 fn tip(self) -> String {
58 match self.badge() {
59 Badge::None => crate::NAME.to_string(),
60 _ => w().tray.tip(self.mentions, self.messages, crate::NAME),
61 }
62 }
63}
64
65#[cfg(any(target_os = "linux", target_os = "windows"))]
66const ICON_SIZE: i32 = 32;
67#[cfg(any(target_os = "linux", target_os = "windows"))]
68const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0);
69#[cfg(any(target_os = "linux", target_os = "windows"))]
70const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6];
71#[cfg(any(target_os = "linux", target_os = "windows"))]
72const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44];
73
74#[cfg(any(target_os = "linux", target_os = "windows"))]
75fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 {
76 let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt();
77 (radius - distance + 0.5).clamp(0.0, 1.0)
78}
79
80#[cfg(any(target_os = "linux", target_os = "windows"))]
81fn logo() -> Vec<([u8; 3], u8)> {
82 crate::logo::rgba(ICON_SIZE as u32)
83 .as_chunks::<4>()
84 .0
85 .iter()
86 .map(|&[r, g, b, a]| ([r, g, b], a))
87 .collect()
88}
89
90#[cfg(any(target_os = "linux", target_os = "windows"))]
91fn pixels(badge: Badge) -> impl Iterator<Item = ([u8; 3], u8)> {
92 let dot = match badge {
93 Badge::None => None,
94 Badge::Unread => Some(UNREAD_COLOR),
95 Badge::Mention => Some(MENTION_COLOR),
96 };
97 logo().into_iter().enumerate().map(move |(index, base)| {
98 let x = (index as i32 % ICON_SIZE) as f32 + 0.5;
99 let y = (index as i32 / ICON_SIZE) as f32 + 0.5;
100 match dot {
101 Some(color) if coverage(x, y, BADGE) > 0.0 => {
102 (color, (coverage(x, y, BADGE) * 255.0) as u8)
103 }
104 Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => (base.0, 0),
105 _ => base,
106 }
107 })
108}
109
110#[cfg(target_os = "linux")]
111mod linux {
112 use ksni::TrayMethods;
113 use tokio::sync::mpsc;
114 use tracing::warn;
115
116 use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels};
117 use crate::lang::w;
118
119 pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
120 let (sender, receiver) = mpsc::unbounded_channel();
121 let (state_sender, mut state_receiver) = mpsc::unbounded_channel();
122 let tray = Tray {
123 sender,
124 state: TrayState::default(),
125 };
126
127 let _ = std::thread::Builder::new()
128 .name("tray".to_string())
129 .spawn(move || {
130 let runtime = match tokio::runtime::Builder::new_current_thread()
131 .enable_all()
132 .build()
133 {
134 Ok(runtime) => runtime,
135 Err(error) => {
136 warn!("tray runtime: {error}");
137 return;
138 }
139 };
140 runtime.block_on(async move {
141 match tray.assume_sni_available(true).spawn().await {
142 Ok(handle) => {
143 while let Some(state) = state_receiver.recv().await {
144 handle.update(|tray| tray.state = state).await;
145 }
146 std::future::pending::<()>().await
147 }
148 Err(error) => warn!("tray: {error}"),
149 }
150 });
151 });
152
153 (
154 receiver,
155 TrayHandle(Box::new(move |state| {
156 let _ = state_sender.send(state);
157 })),
158 )
159 }
160
161 struct Tray {
162 sender: mpsc::UnboundedSender<TrayAction>,
163 state: TrayState,
164 }
165
166 impl ksni::Tray for Tray {
167 fn id(&self) -> String {
168 crate::NAME.to_string()
169 }
170
171 fn title(&self) -> String {
172 crate::NAME.to_string()
173 }
174
175 fn icon_pixmap(&self) -> Vec<ksni::Icon> {
176 vec![icon(self.state.badge())]
177 }
178
179 fn status(&self) -> ksni::Status {
180 match self.state.badge() {
181 Badge::Mention => ksni::Status::NeedsAttention,
182 _ => ksni::Status::Active,
183 }
184 }
185
186 fn tool_tip(&self) -> ksni::ToolTip {
187 ksni::ToolTip {
188 title: self.state.tip(),
189 ..Default::default()
190 }
191 }
192
193 fn activate(&mut self, _x: i32, _y: i32) {
194 let _ = self.sender.send(TrayAction::Show);
195 }
196
197 fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
198 use ksni::menu::StandardItem;
199
200 vec![
201 StandardItem {
202 label: w().tray.show.to_string(),
203 activate: Box::new(|tray: &mut Self| {
204 let _ = tray.sender.send(TrayAction::Show);
205 }),
206 ..Default::default()
207 }
208 .into(),
209 StandardItem {
210 label: w().tray.quit.to_string(),
211 activate: Box::new(|tray: &mut Self| {
212 let _ = tray.sender.send(TrayAction::Quit);
213 }),
214 ..Default::default()
215 }
216 .into(),
217 ]
218 }
219 }
220
221 fn icon(badge: Badge) -> ksni::Icon {
222 ksni::Icon {
223 width: ICON_SIZE,
224 height: ICON_SIZE,
225 data: pixels(badge)
226 .flat_map(|([red, green, blue], alpha)| [alpha, red, green, blue])
227 .collect(),
228 }
229 }
230}
231
232#[cfg(target_os = "windows")]
233mod windows {
234 use tokio::sync::mpsc;
235 use tracing::warn;
236 use tray_icon::{
237 Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent,
238 menu::{Menu, MenuEvent, MenuItem},
239 };
240
241 use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels};
242 use crate::lang::w;
243
244 fn icon(badge: Badge) -> Option<Icon> {
245 let rgba = pixels(badge)
246 .flat_map(|([red, green, blue], alpha)| [red, green, blue, alpha])
247 .collect();
248 Icon::from_rgba(rgba, ICON_SIZE as u32, ICON_SIZE as u32).ok()
249 }
250
251 pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
252 let (sender, receiver) = mpsc::unbounded_channel();
253 let show = MenuItem::new(w().tray.show, true, None);
254 let quit = MenuItem::new(w().tray.quit, true, None);
255 let menu = Menu::new();
256 if let Err(error) = menu.append_items(&[&show, &quit]) {
257 warn!("tray menu: {error}");
258 }
259 let (show_id, quit_id) = (show.id().clone(), quit.id().clone());
260 let menu_sender = sender.clone();
261 MenuEvent::set_event_handler(Some(std::sync::Arc::new(move |event: MenuEvent| {
262 let action = if event.id == show_id {
263 TrayAction::Show
264 } else if event.id == quit_id {
265 TrayAction::Quit
266 } else {
267 return;
268 };
269 let _ = menu_sender.send(action);
270 })));
271 TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| {
272 if let TrayIconEvent::Click {
273 button: MouseButton::Left,
274 button_state: MouseButtonState::Up,
275 ..
276 } = event
277 {
278 let _ = sender.send(TrayAction::Show);
279 }
280 }));
281 let mut builder = TrayIconBuilder::new()
282 .with_menu(Box::new(menu))
283 .with_tooltip(crate::NAME);
284 if let Some(icon) = icon(Badge::None) {
285 builder = builder.with_icon(icon);
286 }
287 let handle = match builder.build() {
288 Ok(tray) => TrayHandle(Box::new(move |state: TrayState| {
289 let _ = tray.set_icon(icon(state.badge()));
290 let _ = tray.set_tooltip(Some(state.tip()));
291 })),
292 Err(error) => {
293 warn!("tray: {error}");
294 TrayHandle(Box::new(|_| {}))
295 }
296 };
297 (receiver, handle)
298 }
299}
300
301#[cfg(all(test, any(target_os = "linux", target_os = "windows")))]
302mod tests {
303 #[test]
304 fn logo_renders() {
305 let pixels = super::logo();
306 assert_eq!(pixels.len(), (super::ICON_SIZE * super::ICON_SIZE) as usize);
307 assert!(
308 pixels
309 .iter()
310 .any(|(color, alpha)| *alpha == 255 && color[0] > 200)
311 );
312 }
313}