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