BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / notify / platform / linux_notifications.rs

linux_notifications.rs

linux_notifications.rs 16.9 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
4use std::sync::{Mutex, OnceLock};
5use std::thread;
6use std::time::{Duration, Instant};
7
8use futures_util::StreamExt;
9use zbus::Connection;
10use zbus::zvariant::{OwnedValue, Value};
11
12use crate::APP_NAME;
13use crate::linux_desktop::DESKTOP_ID;
14
15const SERVICE: &str = "org.freedesktop.Notifications";
16const PATH: &str = "/org/freedesktop/Notifications";
17const INTERFACE: &str = "org.freedesktop.Notifications";
18
19const STARTUP_TIMEOUT: Duration = Duration::from_secs(3);
20
21static MISSING_DAEMON_LOGGED: AtomicBool = AtomicBool::new(false);
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct NotificationImage {
25 pub width: u32,
26 pub height: u32,
27 pub rgba: Vec<u8>,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct BusNotification {
32 pub logical_key: String,
33 pub replace_key: String,
34 pub summary: String,
35 pub body: String,
36 pub actions: Vec<(String, String)>,
37 pub timeout_ms: i32,
38 pub urgency: u8,
39 pub category: String,
40 pub image: Option<NotificationImage>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum NotificationEvent {
45 Action {
46 logical_key: String,
47 action_id: String,
48 },
49 Reply {
50 logical_key: String,
51 text: String,
52 },
53 Closed {
54 logical_key: String,
55 reason: u32,
56 },
57}
58
59enum Command {
60 Sync {
61 visible: Vec<BusNotification>,
62 close: Vec<String>,
63 },
64 Shutdown,
65}
66
67struct Published {
68 dbus_id: u32,
69 logical_key: String,
70 fingerprint: u64,
71}
72
73pub struct DesktopNotifications {
74 commands: Sender<Command>,
75 events: Mutex<Receiver<NotificationEvent>>,
76 startup: Mutex<Option<Startup>>,
77}
78
79struct Startup {
80 ready: Receiver<Result<(), String>>,
81 since: Instant,
82}
83
84impl DesktopNotifications {
85 pub fn start() -> Option<Self> {
86 let (command_tx, command_rx) = channel();
87 let (event_tx, event_rx) = channel();
88 let (ready_tx, ready_rx) = channel();
89 thread::Builder::new()
90 .name("linux-notifications".into())
91 .spawn(move || {
92 let runtime = match tokio::runtime::Builder::new_current_thread()
93 .enable_all()
94 .build()
95 {
96 Ok(runtime) => runtime,
97 Err(error) => {
98 let _ = ready_tx.send(Err(error.to_string()));
99 return;
100 }
101 };
102 runtime.block_on(worker(command_rx, event_tx, ready_tx));
103 })
104 .ok()?;
105 Some(Self {
106 commands: command_tx,
107 events: Mutex::new(event_rx),
108 startup: Mutex::new(Some(Startup {
109 ready: ready_rx,
110 since: Instant::now(),
111 })),
112 })
113 }
114
115 /// Without a notification daemon the caller falls back to its own toast windows.
116 pub fn failed(&self) -> bool {
117 let Ok(mut startup) = self.startup.lock() else {
118 return true;
119 };
120 let Some(pending) = startup.as_ref() else {
121 return false;
122 };
123 let error = match pending.ready.try_recv() {
124 Ok(Ok(())) => {
125 *startup = None;
126 return false;
127 }
128 Err(TryRecvError::Empty) if pending.since.elapsed() < STARTUP_TIMEOUT => return false,
129 Ok(Err(error)) => error,
130 Err(TryRecvError::Empty) => "notification daemon did not answer".to_owned(),
131 Err(TryRecvError::Disconnected) => "notification worker did not start".to_owned(),
132 };
133 log_missing_once(&error);
134 true
135 }
136
137 pub fn sync(&self, visible: Vec<BusNotification>, close: Vec<String>) {
138 let _ = self.commands.send(Command::Sync { visible, close });
139 }
140
141 pub fn poll(&self) -> Vec<NotificationEvent> {
142 let Ok(receiver) = self.events.lock() else {
143 return Vec::new();
144 };
145 let mut events = Vec::new();
146 loop {
147 match receiver.try_recv() {
148 Ok(event) => events.push(event),
149 Err(TryRecvError::Empty | TryRecvError::Disconnected) => break,
150 }
151 }
152 events
153 }
154}
155
156impl Drop for DesktopNotifications {
157 fn drop(&mut self) {
158 let _ = self.commands.send(Command::Shutdown);
159 }
160}
161
162fn log_missing_once(detail: &str) {
163 if MISSING_DAEMON_LOGGED
164 .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
165 .is_ok()
166 {
167 log::warn!("desktop notifications unavailable: {detail}");
168 }
169}
170
171fn fingerprint(note: &BusNotification) -> u64 {
172 use std::hash::{Hash, Hasher};
173 let mut hasher = std::collections::hash_map::DefaultHasher::new();
174 note.logical_key.hash(&mut hasher);
175 note.replace_key.hash(&mut hasher);
176 note.summary.hash(&mut hasher);
177 note.body.hash(&mut hasher);
178 note.actions.hash(&mut hasher);
179 note.timeout_ms.hash(&mut hasher);
180 note.urgency.hash(&mut hasher);
181 note.category.hash(&mut hasher);
182 note.image
183 .as_ref()
184 .map(|image| (image.width, image.height, image.rgba.len()))
185 .hash(&mut hasher);
186 hasher.finish()
187}
188
189async fn worker(
190 commands: Receiver<Command>,
191 events: Sender<NotificationEvent>,
192 ready: Sender<Result<(), String>>,
193) {
194 let connection = match Connection::session().await {
195 Ok(connection) => connection,
196 Err(error) => {
197 let _ = ready.send(Err(error.to_string()));
198 return;
199 }
200 };
201 let caps = match get_capabilities(&connection).await {
202 Ok(caps) => caps,
203 Err(error) => {
204 let _ = ready.send(Err(error));
205 return;
206 }
207 };
208 let _ = ready.send(Ok(()));
209
210 let mut by_replace: HashMap<String, Published> = HashMap::new();
211 let mut by_dbus: HashMap<u32, String> = HashMap::new();
212 let mut supports_inline_reply = caps.iter().any(|cap| cap == "inline-reply");
213
214 let mut action_stream = match receive_signal(&connection, "ActionInvoked").await {
215 Ok(stream) => stream,
216 Err(error) => {
217 log::warn!("notifications ActionInvoked stream failed: {error}");
218 return;
219 }
220 };
221 let mut replied_stream = receive_signal(&connection, "NotificationReplied")
222 .await
223 .ok();
224 let mut closed_stream = receive_signal(&connection, "NotificationClosed").await.ok();
225
226 loop {
227 tokio::select! {
228 biased;
229 message = action_stream.next() => {
230 let Some(message) = message else { break };
231 if let Ok(message) = message
232 && let Some(event) = parse_action_invoked(&message, &by_dbus)
233 {
234 let _ = events.send(event);
235 }
236 }
237 message = async {
238 match replied_stream.as_mut() {
239 Some(stream) => stream.next().await,
240 None => std::future::pending().await,
241 }
242 } => {
243 if let Some(Ok(message)) = message
244 && let Some(event) = parse_replied(&message, &by_dbus)
245 {
246 let _ = events.send(event);
247 }
248 }
249 message = async {
250 match closed_stream.as_mut() {
251 Some(stream) => stream.next().await,
252 None => std::future::pending().await,
253 }
254 } => {
255 if let Some(Ok(message)) = message
256 && let Some(event) = parse_closed(&message, &by_dbus)
257 {
258 let _ = events.send(event);
259 }
260 }
261 _ = tokio::time::sleep(Duration::from_millis(40)) => {
262 match commands.try_recv() {
263 Ok(Command::Shutdown) | Err(TryRecvError::Disconnected) => break,
264 Err(TryRecvError::Empty) => {}
265 Ok(Command::Sync { visible, close }) => {
266 if let Ok(caps) = get_capabilities(&connection).await {
267 supports_inline_reply = caps.iter().any(|cap| cap == "inline-reply");
268 }
269 apply_sync(
270 &connection,
271 &mut by_replace,
272 &mut by_dbus,
273 visible,
274 close,
275 supports_inline_reply,
276 )
277 .await;
278 }
279 }
280 }
281 }
282 }
283}
284
285async fn apply_sync(
286 connection: &Connection,
287 by_replace: &mut HashMap<String, Published>,
288 by_dbus: &mut HashMap<u32, String>,
289 visible: Vec<BusNotification>,
290 close: Vec<String>,
291 supports_inline_reply: bool,
292) {
293 for logical in close {
294 if let Some((replace_key, dbus_id)) = by_replace
295 .iter()
296 .find(|(_, published)| published.logical_key == logical)
297 .map(|(key, published)| (key.clone(), published.dbus_id))
298 {
299 let _ = close_notification(connection, dbus_id).await;
300 by_dbus.remove(&dbus_id);
301 by_replace.remove(&replace_key);
302 }
303 }
304 let visible_keys: std::collections::HashSet<_> = visible
305 .iter()
306 .map(|note| note.replace_key.clone())
307 .collect();
308 by_replace.retain(|key, published| {
309 if visible_keys.contains(key) {
310 true
311 } else {
312 by_dbus.remove(&published.dbus_id);
313 false
314 }
315 });
316 for note in visible {
317 let print = fingerprint(&note);
318 if let Some(existing) = by_replace.get(&note.replace_key)
319 && existing.fingerprint == print
320 && existing.logical_key == note.logical_key
321 {
322 continue;
323 }
324 let replaces = by_replace
325 .get(&note.replace_key)
326 .map(|published| published.dbus_id)
327 .unwrap_or(0);
328 match notify(connection, &note, replaces, supports_inline_reply).await {
329 Ok(dbus_id) => {
330 if let Some(previous) = by_replace.insert(
331 note.replace_key.clone(),
332 Published {
333 dbus_id,
334 logical_key: note.logical_key.clone(),
335 fingerprint: print,
336 },
337 ) {
338 by_dbus.remove(&previous.dbus_id);
339 }
340 by_dbus.insert(dbus_id, note.logical_key);
341 }
342 Err(error) => log::warn!("Notify failed: {error}"),
343 }
344 }
345}
346
347async fn get_capabilities(connection: &Connection) -> Result<Vec<String>, String> {
348 let reply = connection
349 .call_method(Some(SERVICE), PATH, Some(INTERFACE), "GetCapabilities", &())
350 .await
351 .map_err(|error| error.to_string())?;
352 reply
353 .body()
354 .deserialize()
355 .map_err(|error| error.to_string())
356}
357
358async fn close_notification(connection: &Connection, id: u32) -> Result<(), String> {
359 connection
360 .call_method(
361 Some(SERVICE),
362 PATH,
363 Some(INTERFACE),
364 "CloseNotification",
365 &id,
366 )
367 .await
368 .map(|_| ())
369 .map_err(|error| error.to_string())
370}
371
372async fn notify(
373 connection: &Connection,
374 note: &BusNotification,
375 replaces_id: u32,
376 supports_inline_reply: bool,
377) -> Result<u32, String> {
378 let mut actions: Vec<String> = Vec::new();
379 actions.push("default".into());
380 actions.push(String::new());
381 for (id, label) in &note.actions {
382 let id = if id == "inline-reply" && !supports_inline_reply {
383 "reply-open"
384 } else {
385 id.as_str()
386 };
387 actions.push(id.to_owned());
388 actions.push(label.clone());
389 }
390 let action_refs: Vec<&str> = actions.iter().map(String::as_str).collect();
391
392 let mut hints: HashMap<&str, Value<'_>> = HashMap::new();
393 hints.insert("urgency", Value::U8(note.urgency));
394 hints.insert("category", Value::Str(note.category.as_str().into()));
395 hints.insert("desktop-entry", Value::Str(DESKTOP_ID.into()));
396 hints.insert("suppress-sound", Value::Bool(true));
397
398 if let Some(image) = &note.image {
399 let rowstride = image.width * 4;
400 let value = Value::from((
401 image.width as i32,
402 image.height as i32,
403 rowstride as i32,
404 true,
405 8_i32,
406 4_i32,
407 image.rgba.clone(),
408 ));
409 hints.insert("image-data", value);
410 }
411
412 let reply = connection
413 .call_method(
414 Some(SERVICE),
415 PATH,
416 Some(INTERFACE),
417 "Notify",
418 &(
419 APP_NAME,
420 replaces_id,
421 "",
422 note.summary.as_str(),
423 note.body.as_str(),
424 action_refs,
425 hints,
426 note.timeout_ms,
427 ),
428 )
429 .await
430 .map_err(|error| error.to_string())?;
431 reply
432 .body()
433 .deserialize()
434 .map_err(|error| error.to_string())
435}
436
437async fn receive_signal(
438 connection: &Connection,
439 member: &str,
440) -> Result<zbus::MessageStream, String> {
441 let rule = zbus::MatchRule::builder()
442 .msg_type(zbus::message::Type::Signal)
443 .interface(INTERFACE)
444 .map_err(|error| error.to_string())?
445 .member(member)
446 .map_err(|error| error.to_string())?
447 .path(PATH)
448 .map_err(|error| error.to_string())?
449 .build();
450 zbus::MessageStream::for_match_rule(rule, connection, Some(32))
451 .await
452 .map_err(|error| error.to_string())
453}
454
455fn parse_action_invoked(
456 message: &zbus::Message,
457 by_dbus: &HashMap<u32, String>,
458) -> Option<NotificationEvent> {
459 let (id, action_key): (u32, String) = message.body().deserialize().ok()?;
460 let logical_key = by_dbus.get(&id)?.clone();
461 if action_key == "inline-reply" {
462 return None;
463 }
464 Some(NotificationEvent::Action {
465 logical_key,
466 action_id: if action_key.is_empty() {
467 "default".into()
468 } else {
469 action_key
470 },
471 })
472}
473
474fn parse_replied(
475 message: &zbus::Message,
476 by_dbus: &HashMap<u32, String>,
477) -> Option<NotificationEvent> {
478 let (id, text): (u32, String) = message.body().deserialize().ok()?;
479 let logical_key = by_dbus.get(&id)?.clone();
480 Some(NotificationEvent::Reply { logical_key, text })
481}
482
483fn parse_closed(
484 message: &zbus::Message,
485 by_dbus: &HashMap<u32, String>,
486) -> Option<NotificationEvent> {
487 let (id, reason): (u32, u32) = message.body().deserialize().ok()?;
488 let logical_key = by_dbus.get(&id)?.clone();
489 Some(NotificationEvent::Closed {
490 logical_key,
491 reason,
492 })
493}
494
495fn inhibit_runtime() -> Option<&'static tokio::runtime::Runtime> {
496 static RUNTIME: OnceLock<Option<tokio::runtime::Runtime>> = OnceLock::new();
497 RUNTIME
498 .get_or_init(|| {
499 // Multi-thread so `block_on` is safe from the UI thread and tests.
500 tokio::runtime::Builder::new_multi_thread()
501 .worker_threads(1)
502 .enable_all()
503 .build()
504 .ok()
505 })
506 .as_ref()
507}
508
509pub fn notifications_inhibited() -> bool {
510 let Some(runtime) = inhibit_runtime() else {
511 return false;
512 };
513 runtime.block_on(async {
514 let Ok(connection) = Connection::session().await else {
515 return false;
516 };
517 let reply = connection
518 .call_method(
519 Some(SERVICE),
520 PATH,
521 Some("org.freedesktop.DBus.Properties"),
522 "Get",
523 &(INTERFACE, "Inhibited"),
524 )
525 .await;
526 let Ok(reply) = reply else {
527 return false;
528 };
529 let Ok(value) = reply.body().deserialize::<OwnedValue>() else {
530 return false;
531 };
532 bool::try_from(value).unwrap_or(false)
533 })
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539
540 #[test]
541 fn fingerprint_changes_with_body() {
542 let mut note = BusNotification {
543 logical_key: "message:1".into(),
544 replace_key: "conversation:a".into(),
545 summary: "Priya".into(),
546 body: "one".into(),
547 actions: vec![("mark-read".into(), "Mark as read".into())],
548 timeout_ms: 6000,
549 urgency: 1,
550 category: "im.received".into(),
551 image: None,
552 };
553 let first = fingerprint(&note);
554 note.body = "two".into();
555 assert_ne!(first, fingerprint(&note));
556 }
557
558 #[test]
559 fn missing_inhibited_property_is_not_quiet() {
560 let _ = notifications_inhibited();
561 }
562
563 #[test]
564 fn log_missing_once_is_idempotent() {
565 MISSING_DAEMON_LOGGED.store(false, Ordering::Relaxed);
566 log_missing_once("test");
567 log_missing_once("test again");
568 assert!(MISSING_DAEMON_LOGGED.load(Ordering::Relaxed));
569 }
570}