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