BlueGit

ict rusty-teams

feat(linux): desktop toasts via freedesktop Notifications

On Linux the decision layer and sounds already ran, but the corner card
never appeared because the Win32 GPUI popup hooks are stubs. Publish the
same message, ring, and meeting toasts through org.freedesktop.Notifications
with the card actions, suppress shell sound, and honour desktop Do not
disturb when the daemon exposes Inhibited.

metis Joachim Mild · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
0ca4096d8b1cc8ad918cc66e69e45f04414c53c1
Parent
0e3132f8
14 files changed +1328 −55
Cargo.lock +1 −0
@@ -338,6 +338,7 @@ dependencies = [
338 338 "tray-icon",
339 339 "windows 0.62.2",
340 340 "x11rb",
341 "zbus",
341 342 ]
342 343
343 344 [[package]]
@@ -338,6 +338,7 @@ dependencies = [
338 "tray-icon",
338 "tray-icon",
339 "windows 0.62.2",
339 "windows 0.62.2",
340 "x11rb",
340 "x11rb",
341 "zbus",
341]
342]
342
343
343[[package]]
344[[package]]
ROADMAP.md +3 −4
@@ -14,7 +14,7 @@ Feature parity with the Microsoft Teams desktop client.
14 14 | [Writing](#writing) | 100 % | 15 | 0 | 0 |
15 15 | [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16 16 | [Channels](#channels) | 100 % | 7 | 0 | 0 |
17 | [Notifications](#notifications) | 94 % | 8 | 1 | 0 |
17 | [Notifications](#notifications) | 100 % | 9 | 0 | 0 |
18 18 | [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
@@ -24,8 +24,7 @@ Feature parity with the Microsoft Teams desktop client.
24 24
25 25 | # | Feature | Note |
26 26 |---|---|---|
27 | 1 | Desktop toasts on Linux | Sounds are in, toasts are not |
28 | 2 | Incoming and 1:1 calls with a second person | Built, not yet rung live |
27 | 1 | Incoming and 1:1 calls with a second person | Built, not yet rung live |
29 28
30 29 ## Sign-in and app
31 30
@@ -134,7 +133,7 @@ Feature parity with the Microsoft Teams desktop client.
134 133 | Stack of 3, queue, Hide all, fade-out | Done | |
135 134 | Muted chats stay quiet | Done | Toast, sound and taskbar badge only for @mentions |
136 135 | Mute notifications during calls and meetings | Done | Settings > Notifications switch, default off; message toasts and sounds stay away while a call is active, call rings still show |
137 | Notifications on Linux | Partial | Message and ring sounds; desktop toasts still Windows only |
136 | Notifications on Linux | Done | Message and ring sounds; desktop toasts via `org.freedesktop.Notifications` (same actions as the Windows card; shell history and desktop Do not disturb when the daemon supports them) |
138 137
139 138 ## Search and navigation
140 139
@@ -14,7 +14,7 @@ Feature parity with the Microsoft Teams desktop client.
14| [Writing](#writing) | 100 % | 15 | 0 | 0 |
14| [Writing](#writing) | 100 % | 15 | 0 | 0 |
15| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
15| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16| [Channels](#channels) | 100 % | 7 | 0 | 0 |
16| [Channels](#channels) | 100 % | 7 | 0 | 0 |
17| [Notifications](#notifications) | 94 % | 8 | 1 | 0 |
17| [Notifications](#notifications) | 100 % | 9 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
@@ -24,8 +24,7 @@ Feature parity with the Microsoft Teams desktop client.
24
24
25| # | Feature | Note |
25| # | Feature | Note |
26|---|---|---|
26|---|---|---|
27| 1 | Desktop toasts on Linux | Sounds are in, toasts are not |
27| 1 | Incoming and 1:1 calls with a second person | Built, not yet rung live |
28| 2 | Incoming and 1:1 calls with a second person | Built, not yet rung live |
29
28
30## Sign-in and app
29## Sign-in and app
31
30
@@ -134,7 +133,7 @@ Feature parity with the Microsoft Teams desktop client.
134| Stack of 3, queue, Hide all, fade-out | Done | |
133| Stack of 3, queue, Hide all, fade-out | Done | |
135| Muted chats stay quiet | Done | Toast, sound and taskbar badge only for @mentions |
134| Muted chats stay quiet | Done | Toast, sound and taskbar badge only for @mentions |
136| Mute notifications during calls and meetings | Done | Settings > Notifications switch, default off; message toasts and sounds stay away while a call is active, call rings still show |
135| Mute notifications during calls and meetings | Done | Settings > Notifications switch, default off; message toasts and sounds stay away while a call is active, call rings still show |
137| Notifications on Linux | Partial | Message and ring sounds; desktop toasts still Windows only |
136| Notifications on Linux | Done | Message and ring sounds; desktop toasts via `org.freedesktop.Notifications` (same actions as the Windows card; shell history and desktop Do not disturb when the daemon supports them) |
138
137
139## Search and navigation
138## Search and navigation
140
139
crates/app-base/Cargo.toml +1 −0
@@ -39,6 +39,7 @@ rodio = { version = "0.22", default-features = false, features = ["playback", "m
39 39 [target.'cfg(target_os = "linux")'.dependencies]
40 40 x11rb = { version = "0.13", features = ["shape"] }
41 41 ksni = { version = "0.3", features = ["blocking"] }
42 zbus = { version = "5", default-features = false, features = ["tokio"] }
42 43
43 44 [target.'cfg(windows)'.dependencies]
44 45 libc = "0.2"
@@ -39,6 +39,7 @@ rodio = { version = "0.22", default-features = false, features = ["playback", "m
39[target.'cfg(target_os = "linux")'.dependencies]
39[target.'cfg(target_os = "linux")'.dependencies]
40x11rb = { version = "0.13", features = ["shape"] }
40x11rb = { version = "0.13", features = ["shape"] }
41ksni = { version = "0.3", features = ["blocking"] }
41ksni = { version = "0.3", features = ["blocking"] }
42zbus = { version = "5", default-features = false, features = ["tokio"] }
42
43
43[target.'cfg(windows)'.dependencies]
44[target.'cfg(windows)'.dependencies]
44libc = "0.2"
45libc = "0.2"
crates/app-base/locales/app.yml +25 −0
@@ -576,6 +576,31 @@ tray:
576 576 mute_sound:
577 577 en: Mute sound
578 578 de: Ton stumm schalten
579 notify:
580 mark_read:
581 en: Mark as read
582 de: Als gelesen markieren
583 reply:
584 en: Reply
585 de: Antworten
586 decline:
587 en: Decline
588 de: Ablehnen
589 accept:
590 en: Accept
591 de: Annehmen
592 audio:
593 en: Audio
594 de: Audio
595 video:
596 en: Video
597 de: Video
598 join:
599 en: Join
600 de: Teilnehmen
601 snooze:
602 en: Snooze
603 de: Schlummern
579 604 install:
580 605 title:
581 606 en: Install Rusty Teams?
@@ -576,6 +576,31 @@ tray:
576 mute_sound:
576 mute_sound:
577 en: Mute sound
577 en: Mute sound
578 de: Ton stumm schalten
578 de: Ton stumm schalten
579notify:
580 mark_read:
581 en: Mark as read
582 de: Als gelesen markieren
583 reply:
584 en: Reply
585 de: Antworten
586 decline:
587 en: Decline
588 de: Ablehnen
589 accept:
590 en: Accept
591 de: Annehmen
592 audio:
593 en: Audio
594 de: Audio
595 video:
596 en: Video
597 de: Video
598 join:
599 en: Join
600 de: Teilnehmen
601 snooze:
602 en: Snooze
603 de: Schlummern
579install:
604install:
580 title:
605 title:
581 en: Install Rusty Teams?
606 en: Install Rusty Teams?
crates/app-base/src/avatar_image.rs +4 −0
@@ -21,6 +21,10 @@ pub struct Texture {
21 21 }
22 22
23 23 impl AvatarPhoto {
24 pub fn source_bytes(&self) -> &[u8] {
25 &self.bytes
26 }
27
24 28 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
25 29 let (width, height) = ImageReader::new(Cursor::new(&bytes))
26 30 .with_guessed_format()
@@ -21,6 +21,10 @@ pub struct Texture {
21}
21}
22
22
23impl AvatarPhoto {
23impl AvatarPhoto {
24 pub fn source_bytes(&self) -> &[u8] {
25 &self.bytes
26 }
27
24 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
28 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
25 let (width, height) = ImageReader::new(Cursor::new(&bytes))
29 let (width, height) = ImageReader::new(Cursor::new(&bytes))
26 .with_guessed_format()
30 .with_guessed_format()
crates/app-base/src/notify/platform/linux_notifications.rs added +545 −0
@@ -0,0 +1,545 @@
1 //! Desktop notifications on Linux through `org.freedesktop.Notifications`.
2
3 use std::collections::HashMap;
4 use std::sync::Mutex;
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(&note);
302 if let Some(existing) = by_replace.get(&note.replace_key)
303 && existing.fingerprint == print
304 && existing.logical_key == note.logical_key
305 {
306 continue;
307 }
308 let replaces = by_replace
309 .get(&note.replace_key)
310 .map(|published| published.dbus_id)
311 .unwrap_or(0);
312 match notify(connection, &note, 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 &note.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) = &note.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 /// Reads the optional `Inhibited` property (Plasma / modern GNOME). Missing → false.
481 pub fn notifications_inhibited() -> bool {
482 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
483 .enable_all()
484 .build()
485 else {
486 return false;
487 };
488 runtime.block_on(async {
489 let Ok(connection) = Connection::session().await else {
490 return false;
491 };
492 let reply = connection
493 .call_method(
494 Some(SERVICE),
495 PATH,
496 Some("org.freedesktop.DBus.Properties"),
497 "Get",
498 &(INTERFACE, "Inhibited"),
499 )
500 .await;
501 let Ok(reply) = reply else {
502 return false;
503 };
504 let Ok(value) = reply.body().deserialize::<OwnedValue>() else {
505 return false;
506 };
507 bool::try_from(value).unwrap_or(false)
508 })
509 }
510
511 #[cfg(test)]
512 mod tests {
513 use super::*;
514
515 #[test]
516 fn fingerprint_changes_with_body() {
517 let mut note = BusNotification {
518 logical_key: "message:1".into(),
519 replace_key: "conversation:a".into(),
520 summary: "Priya".into(),
521 body: "one".into(),
522 actions: vec![("mark-read".into(), "Mark as read".into())],
523 timeout_ms: 6000,
524 urgency: 1,
525 category: "im.received".into(),
526 image: None,
527 };
528 let first = fingerprint(&note);
529 note.body = "two".into();
530 assert_ne!(first, fingerprint(&note));
531 }
532
533 #[test]
534 fn missing_inhibited_property_is_not_quiet() {
535 let _ = notifications_inhibited();
536 }
537
538 #[test]
539 fn log_missing_once_is_idempotent() {
540 MISSING_DAEMON_LOGGED.store(false, Ordering::Relaxed);
541 log_missing_once("test");
542 log_missing_once("test again");
543 assert!(MISSING_DAEMON_LOGGED.load(Ordering::Relaxed));
544 }
545 }
@@ -0,0 +1,545 @@
1//! Desktop notifications on Linux through `org.freedesktop.Notifications`.
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
7use std::thread;
8use std::time::Duration;
9
10use futures_util::StreamExt;
11use zbus::Connection;
12use zbus::zvariant::{OwnedValue, Value};
13
14use crate::APP_NAME;
15use crate::linux_desktop::DESKTOP_ID;
16
17const SERVICE: &str = "org.freedesktop.Notifications";
18const PATH: &str = "/org/freedesktop/Notifications";
19const INTERFACE: &str = "org.freedesktop.Notifications";
20
21static MISSING_DAEMON_LOGGED: AtomicBool = AtomicBool::new(false);
22
23/// RGBA image attached as the freedesktop `image-data` hint.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub 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)]
33pub 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)]
46pub 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
64enum Command {
65 Sync {
66 visible: Vec<BusNotification>,
67 close: Vec<String>,
68 },
69 Shutdown,
70}
71
72struct 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.
79pub struct DesktopNotifications {
80 commands: Sender<Command>,
81 events: Mutex<Receiver<NotificationEvent>>,
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 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
140impl Drop for DesktopNotifications {
141 fn drop(&mut self) {
142 let _ = self.commands.send(Command::Shutdown);
143 }
144}
145
146fn 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
155fn 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
173async 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
271async 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(&note);
302 if let Some(existing) = by_replace.get(&note.replace_key)
303 && existing.fingerprint == print
304 && existing.logical_key == note.logical_key
305 {
306 continue;
307 }
308 let replaces = by_replace
309 .get(&note.replace_key)
310 .map(|published| published.dbus_id)
311 .unwrap_or(0);
312 match notify(connection, &note, 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
331async 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
345async 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
359async 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 &note.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) = &note.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
422async 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
440fn 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
459fn 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
468fn 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/// Reads the optional `Inhibited` property (Plasma / modern GNOME). Missing → false.
481pub fn notifications_inhibited() -> bool {
482 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
483 .enable_all()
484 .build()
485 else {
486 return false;
487 };
488 runtime.block_on(async {
489 let Ok(connection) = Connection::session().await else {
490 return false;
491 };
492 let reply = connection
493 .call_method(
494 Some(SERVICE),
495 PATH,
496 Some("org.freedesktop.DBus.Properties"),
497 "Get",
498 &(INTERFACE, "Inhibited"),
499 )
500 .await;
501 let Ok(reply) = reply else {
502 return false;
503 };
504 let Ok(value) = reply.body().deserialize::<OwnedValue>() else {
505 return false;
506 };
507 bool::try_from(value).unwrap_or(false)
508 })
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514
515 #[test]
516 fn fingerprint_changes_with_body() {
517 let mut note = BusNotification {
518 logical_key: "message:1".into(),
519 replace_key: "conversation:a".into(),
520 summary: "Priya".into(),
521 body: "one".into(),
522 actions: vec![("mark-read".into(), "Mark as read".into())],
523 timeout_ms: 6000,
524 urgency: 1,
525 category: "im.received".into(),
526 image: None,
527 };
528 let first = fingerprint(&note);
529 note.body = "two".into();
530 assert_ne!(first, fingerprint(&note));
531 }
532
533 #[test]
534 fn missing_inhibited_property_is_not_quiet() {
535 let _ = notifications_inhibited();
536 }
537
538 #[test]
539 fn log_missing_once_is_idempotent() {
540 MISSING_DAEMON_LOGGED.store(false, Ordering::Relaxed);
541 log_missing_once("test");
542 log_missing_once("test again");
543 assert!(MISSING_DAEMON_LOGGED.load(Ordering::Relaxed));
544 }
545}
crates/app-base/src/notify/platform/mod.rs +7 −0
@@ -6,12 +6,19 @@ pub use windows_impl::*;
6 6 #[cfg(any(target_os = "linux", target_os = "macos"))]
7 7 mod linux_sound;
8 8 #[cfg(target_os = "linux")]
9 mod linux_notifications;
10 #[cfg(target_os = "linux")]
9 11 mod linux_tray;
10 12 #[cfg(not(windows))]
11 13 mod stub;
12 14 #[cfg(target_os = "linux")]
13 15 mod x11_input;
14 16 #[cfg(target_os = "linux")]
17 pub use linux_notifications::{
18 BusNotification, DesktopNotifications, NotificationEvent, NotificationImage,
19 notifications_inhibited,
20 };
21 #[cfg(target_os = "linux")]
15 22 pub use linux_tray::Tray;
16 23 #[cfg(not(windows))]
17 24 pub use stub::*;
@@ -6,12 +6,19 @@ pub use windows_impl::*;
6#[cfg(any(target_os = "linux", target_os = "macos"))]
6#[cfg(any(target_os = "linux", target_os = "macos"))]
7mod linux_sound;
7mod linux_sound;
8#[cfg(target_os = "linux")]
8#[cfg(target_os = "linux")]
9mod linux_notifications;
10#[cfg(target_os = "linux")]
9mod linux_tray;
11mod linux_tray;
10#[cfg(not(windows))]
12#[cfg(not(windows))]
11mod stub;
13mod stub;
12#[cfg(target_os = "linux")]
14#[cfg(target_os = "linux")]
13mod x11_input;
15mod x11_input;
14#[cfg(target_os = "linux")]
16#[cfg(target_os = "linux")]
17pub use linux_notifications::{
18 BusNotification, DesktopNotifications, NotificationEvent, NotificationImage,
19 notifications_inhibited,
20};
21#[cfg(target_os = "linux")]
15pub use linux_tray::Tray;
22pub use linux_tray::Tray;
16#[cfg(not(windows))]
23#[cfg(not(windows))]
17pub use stub::*;
24pub use stub::*;
crates/app-base/src/notify/platform/stub.rs +8 −1
@@ -77,7 +77,14 @@ pub fn share_geometry(_kind: ShareKind, _id: u64) -> Option<ShareGeometry> {
77 77 }
78 78
79 79 pub fn system_quiet() -> bool {
80 false
80 #[cfg(target_os = "linux")]
81 {
82 super::notifications_inhibited()
83 }
84 #[cfg(not(target_os = "linux"))]
85 {
86 false
87 }
81 88 }
82 89
83 90 pub fn restore_and_raise(_handle: NativeHandle) {}
@@ -77,7 +77,14 @@ pub fn share_geometry(_kind: ShareKind, _id: u64) -> Option<ShareGeometry> {
77}
77}
78
78
79pub fn system_quiet() -> bool {
79pub fn system_quiet() -> bool {
80 false
80 #[cfg(target_os = "linux")]
81 {
82 super::notifications_inhibited()
83 }
84 #[cfg(not(target_os = "linux"))]
85 {
86 false
87 }
81}
88}
82
89
83pub fn restore_and_raise(_handle: NativeHandle) {}
90pub fn restore_and_raise(_handle: NativeHandle) {}
crates/app-base/src/ui_locale.rs +17 −0
@@ -249,6 +249,23 @@ mod tests {
249 249 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
250 250 }
251 251
252 #[test]
253 fn ui_locale_notify_action_keys_resolve() {
254 let _guard = locale_test_lock();
255 apply_locale("en");
256 assert_eq!(tr("notify.mark_read"), "Mark as read");
257 assert_eq!(tr("notify.reply"), "Reply");
258 assert_eq!(tr("notify.decline"), "Decline");
259 assert_eq!(tr("notify.join"), "Join");
260 assert_eq!(tr("notify.snooze"), "Snooze");
261 apply_locale("de");
262 assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");
263 assert_eq!(tr("notify.reply"), "Antworten");
264 assert_eq!(tr("notify.decline"), "Ablehnen");
265 assert_eq!(tr("notify.join"), "Teilnehmen");
266 assert_eq!(tr("notify.snooze"), "Schlummern");
267 }
268
252 269 #[test]
253 270 fn ui_locale_fallback_missing_key_returns_english_or_key() {
254 271 let _guard = locale_test_lock();
@@ -249,6 +249,23 @@ mod tests {
249 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
249 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
250 }
250 }
251
251
252 #[test]
253 fn ui_locale_notify_action_keys_resolve() {
254 let _guard = locale_test_lock();
255 apply_locale("en");
256 assert_eq!(tr("notify.mark_read"), "Mark as read");
257 assert_eq!(tr("notify.reply"), "Reply");
258 assert_eq!(tr("notify.decline"), "Decline");
259 assert_eq!(tr("notify.join"), "Join");
260 assert_eq!(tr("notify.snooze"), "Snooze");
261 apply_locale("de");
262 assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");
263 assert_eq!(tr("notify.reply"), "Antworten");
264 assert_eq!(tr("notify.decline"), "Ablehnen");
265 assert_eq!(tr("notify.join"), "Teilnehmen");
266 assert_eq!(tr("notify.snooze"), "Schlummern");
267 }
268
252 #[test]
269 #[test]
253 fn ui_locale_fallback_missing_key_returns_english_or_key() {
270 fn ui_locale_fallback_missing_key_returns_english_or_key() {
254 let _guard = locale_test_lock();
271 let _guard = locale_test_lock();
crates/app-state/src/notify/desktop_payload.rs added +377 −0
@@ -0,0 +1,377 @@
1 //! Pure desktop-notification payloads (no D-Bus). Linux maps these to
2 //! `org.freedesktop.Notifications`; Windows keeps the GPUI card.
3
4 use super::stack::{
5 MENTION_DURATION, MESSAGE_DURATION, ToastModel,
6 };
7 use super::text::describe;
8 use crate::call::reminder::MeetingToast;
9 use crate::call::ReminderPhase;
10
11 /// Action ids used on the bus and when dispatching back into the notification center.
12 pub mod action {
13 pub const DEFAULT: &str = "default";
14 pub const MARK_READ: &str = "mark-read";
15 pub const REPLY: &str = "inline-reply";
16 pub const DECLINE: &str = "decline";
17 pub const ACCEPT_AUDIO: &str = "accept-audio";
18 pub const ACCEPT_VIDEO: &str = "accept-video";
19 pub const JOIN: &str = "join";
20 pub const SNOOZE: &str = "snooze";
21 }
22
23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24 pub enum Urgency {
25 Low = 0,
26 Normal = 1,
27 Critical = 2,
28 }
29
30 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
31 pub enum DesktopKey {
32 Message(u64),
33 Ring(u64),
34 Meeting(u64),
35 }
36
37 impl DesktopKey {
38 pub fn replace_token(&self) -> String {
39 match self {
40 DesktopKey::Message(id) => format!("message:{id}"),
41 DesktopKey::Ring(id) => format!("ring:{id}"),
42 DesktopKey::Meeting(id) => format!("meeting:{id}"),
43 }
44 }
45 }
46
47 #[derive(Debug, Clone, PartialEq, Eq)]
48 pub struct DesktopAction {
49 pub id: &'static str,
50 pub label: String,
51 }
52
53 #[derive(Debug, Clone, PartialEq, Eq)]
54 pub struct DesktopPayload {
55 pub key: DesktopKey,
56 /// Stable replace key across updates (conversation, ring id, meeting event).
57 pub replace_key: String,
58 pub summary: String,
59 pub body: String,
60 pub actions: Vec<DesktopAction>,
61 /// Milliseconds. `0` means do not expire.
62 pub timeout_ms: i32,
63 pub urgency: Urgency,
64 pub category: &'static str,
65 }
66
67 #[derive(Debug, Clone, PartialEq, Eq)]
68 pub struct MessageLabels {
69 pub mark_read: String,
70 pub reply: String,
71 }
72
73 #[derive(Debug, Clone, PartialEq, Eq)]
74 pub struct RingLabels {
75 pub decline: String,
76 pub accept: String,
77 pub audio: String,
78 pub video: String,
79 }
80
81 #[derive(Debug, Clone, PartialEq, Eq)]
82 pub struct MeetingLabels {
83 pub join: String,
84 pub snooze: String,
85 }
86
87 pub fn message_payload(
88 model: &ToastModel,
89 preview_on: bool,
90 labels: &MessageLabels,
91 ) -> DesktopPayload {
92 let text = describe(model, preview_on);
93 let body = if model.agent.is_some() {
94 if text.preview.is_empty() {
95 model
96 .agent
97 .as_ref()
98 .map(|agent| agent.body.clone())
99 .unwrap_or_default()
100 } else {
101 text.preview.clone()
102 }
103 } else {
104 text.preview.clone()
105 };
106 let summary = if let Some(agent) = &model.agent {
107 if agent.title.is_empty() {
108 text.title.clone()
109 } else {
110 agent.title.clone()
111 }
112 } else {
113 text.title.clone()
114 };
115 let mention = model.mentions_me;
116 let timeout_ms = if mention {
117 MENTION_DURATION.as_millis() as i32
118 } else {
119 MESSAGE_DURATION.as_millis() as i32
120 };
121 let urgency = if model.urgent {
122 Urgency::Critical
123 } else {
124 Urgency::Normal
125 };
126 let mut actions = vec![DesktopAction {
127 id: action::MARK_READ,
128 label: labels.mark_read.clone(),
129 }];
130 if model.agent.is_none() && !model.status_change {
131 actions.push(DesktopAction {
132 id: action::REPLY,
133 label: labels.reply.clone(),
134 });
135 }
136 DesktopPayload {
137 key: DesktopKey::Message(model.id),
138 replace_key: format!("conversation:{}", model.conversation_id),
139 summary,
140 body,
141 actions,
142 timeout_ms,
143 urgency,
144 category: if model.agent.is_some() {
145 "im"
146 } else {
147 "im.received"
148 },
149 }
150 }
151
152 pub fn ring_payload(
153 ring_id: u64,
154 caller_name: &str,
155 subtitle: &str,
156 video: bool,
157 labels: &RingLabels,
158 ) -> DesktopPayload {
159 let accept_label = if video {
160 labels.audio.clone()
161 } else {
162 labels.accept.clone()
163 };
164 let mut actions = vec![
165 DesktopAction {
166 id: action::DECLINE,
167 label: labels.decline.clone(),
168 },
169 DesktopAction {
170 id: action::ACCEPT_AUDIO,
171 label: accept_label,
172 },
173 ];
174 if video {
175 actions.push(DesktopAction {
176 id: action::ACCEPT_VIDEO,
177 label: labels.video.clone(),
178 });
179 }
180 DesktopPayload {
181 key: DesktopKey::Ring(ring_id),
182 replace_key: format!("ring:{ring_id}"),
183 summary: caller_name.to_owned(),
184 body: subtitle.to_owned(),
185 actions,
186 timeout_ms: 0,
187 urgency: Urgency::Critical,
188 category: "x-teams.call.incoming",
189 }
190 }
191
192 pub fn meeting_payload(toast: &MeetingToast, body: &str, labels: &MeetingLabels) -> DesktopPayload {
193 let mut actions = Vec::new();
194 if toast.phase == ReminderPhase::Soon {
195 actions.push(DesktopAction {
196 id: action::SNOOZE,
197 label: labels.snooze.clone(),
198 });
199 }
200 actions.push(DesktopAction {
201 id: action::JOIN,
202 label: labels.join.clone(),
203 });
204 DesktopPayload {
205 key: DesktopKey::Meeting(toast.id),
206 replace_key: format!("meeting:{}", toast.event_key),
207 summary: toast.subject.clone(),
208 body: body.to_owned(),
209 actions,
210 timeout_ms: 0,
211 urgency: Urgency::Normal,
212 category: "x-teams.meeting.reminder",
213 }
214 }
215
216 #[cfg(test)]
217 mod tests {
218 use std::time::Instant;
219
220 use super::*;
221 use crate::notify::rules::{ChatKind, Preview};
222 use crate::notify::stack::{Fade, ReplyState, ToastTimer};
223
224 fn message_labels() -> MessageLabels {
225 MessageLabels {
226 mark_read: "Mark as read".into(),
227 reply: "Reply".into(),
228 }
229 }
230
231 fn ring_labels() -> RingLabels {
232 RingLabels {
233 decline: "Decline".into(),
234 accept: "Accept".into(),
235 audio: "Audio".into(),
236 video: "Video".into(),
237 }
238 }
239
240 fn meeting_labels() -> MeetingLabels {
241 MeetingLabels {
242 join: "Join".into(),
243 snooze: "Snooze".into(),
244 }
245 }
246
247 fn toast(mention: bool, urgent: bool, preview: Preview) -> ToastModel {
248 ToastModel {
249 id: 7,
250 conversation_id: "chat-a".into(),
251 message_id: "m1".into(),
252 kind: ChatKind::Direct,
253 chat_title: String::new(),
254 sender_id: Some("u1".into()),
255 sender_name: "Priya Nair".into(),
256 preview,
257 mentions_me: mention,
258 count: 1,
259 timer: ToastTimer::new(Instant::now(), mention),
260 reply: ReplyState::Closed,
261 reply_text: String::new(),
262 hovered: false,
263 time: String::new(),
264 queued: false,
265 dismissed: false,
266 fade: Fade::shown(Instant::now()),
267 agent: None,
268 status_change: false,
269 urgent,
270 }
271 }
272
273 #[test]
274 fn preview_off_hides_message_text() {
275 let model = toast(false, false, Preview::Text("secret".into()));
276 let payload = message_payload(&model, false, &message_labels());
277 assert_eq!(payload.body, "New message");
278 assert_eq!(payload.replace_key, "conversation:chat-a");
279 assert_eq!(payload.timeout_ms, MESSAGE_DURATION.as_millis() as i32);
280 }
281
282 #[test]
283 fn mention_uses_longer_timeout() {
284 let model = toast(true, false, Preview::Text("hi".into()));
285 let payload = message_payload(&model, true, &message_labels());
286 assert_eq!(payload.timeout_ms, MENTION_DURATION.as_millis() as i32);
287 }
288
289 #[test]
290 fn urgent_sets_critical_urgency() {
291 let model = toast(false, true, Preview::Text("down".into()));
292 let payload = message_payload(&model, true, &message_labels());
293 assert_eq!(payload.urgency, Urgency::Critical);
294 }
295
296 #[test]
297 fn message_offers_mark_read_and_reply() {
298 let model = toast(false, false, Preview::Text("hi".into()));
299 let payload = message_payload(&model, true, &message_labels());
300 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
301 assert_eq!(ids, vec![action::MARK_READ, action::REPLY]);
302 }
303
304 #[test]
305 fn bundling_shares_conversation_replace_key() {
306 let first = toast(false, false, Preview::Text("one".into()));
307 let mut second = toast(false, false, Preview::Text("two".into()));
308 second.id = 99;
309 let a = message_payload(&first, true, &message_labels());
310 let b = message_payload(&second, true, &message_labels());
311 assert_eq!(a.replace_key, b.replace_key);
312 assert_ne!(a.key, b.key);
313 }
314
315 #[test]
316 fn audio_ring_has_no_timeout_and_no_video_action() {
317 let payload = ring_payload(3, "Alex", "Incoming audio call", false, &ring_labels());
318 assert_eq!(payload.timeout_ms, 0);
319 assert_eq!(payload.urgency, Urgency::Critical);
320 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
321 assert_eq!(ids, vec![action::DECLINE, action::ACCEPT_AUDIO]);
322 assert_eq!(payload.actions[1].label, "Accept");
323 }
324
325 #[test]
326 fn video_ring_offers_audio_and_video() {
327 let payload = ring_payload(3, "Alex", "Incoming video call", true, &ring_labels());
328 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
329 assert_eq!(
330 ids,
331 vec![action::DECLINE, action::ACCEPT_AUDIO, action::ACCEPT_VIDEO]
332 );
333 assert_eq!(payload.actions[1].label, "Audio");
334 }
335
336 #[test]
337 fn meeting_soon_offers_snooze_and_join() {
338 let toast = MeetingToast {
339 id: 1,
340 event_key: "e@1".into(),
341 event_id: "e".into(),
342 phase: ReminderPhase::Soon,
343 subject: "Standup".into(),
344 start: chrono::Utc::now(),
345 join_url: "https://teams.microsoft.com/l/meetup-join/x".into(),
346 };
347 let payload = meeting_payload(&toast, "in 5 minutes", &meeting_labels());
348 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
349 assert_eq!(ids, vec![action::SNOOZE, action::JOIN]);
350 assert_eq!(payload.timeout_ms, 0);
351 }
352
353 #[test]
354 fn meeting_live_drops_snooze_same_replace_key() {
355 let soon = MeetingToast {
356 id: 1,
357 event_key: "e@1".into(),
358 event_id: "e".into(),
359 phase: ReminderPhase::Soon,
360 subject: "Standup".into(),
361 start: chrono::Utc::now(),
362 join_url: "https://example".into(),
363 };
364 let live = MeetingToast {
365 id: 2,
366 phase: ReminderPhase::Live,
367 ..soon.clone()
368 };
369 let a = meeting_payload(&soon, "soon", &meeting_labels());
370 let b = meeting_payload(&live, "live now", &meeting_labels());
371 assert_eq!(a.replace_key, b.replace_key);
372 assert_eq!(
373 b.actions.iter().map(|a| a.id).collect::<Vec<_>>(),
374 vec![action::JOIN]
375 );
376 }
377 }
@@ -0,0 +1,377 @@
1//! Pure desktop-notification payloads (no D-Bus). Linux maps these to
2//! `org.freedesktop.Notifications`; Windows keeps the GPUI card.
3
4use super::stack::{
5 MENTION_DURATION, MESSAGE_DURATION, ToastModel,
6};
7use super::text::describe;
8use crate::call::reminder::MeetingToast;
9use crate::call::ReminderPhase;
10
11/// Action ids used on the bus and when dispatching back into the notification center.
12pub mod action {
13 pub const DEFAULT: &str = "default";
14 pub const MARK_READ: &str = "mark-read";
15 pub const REPLY: &str = "inline-reply";
16 pub const DECLINE: &str = "decline";
17 pub const ACCEPT_AUDIO: &str = "accept-audio";
18 pub const ACCEPT_VIDEO: &str = "accept-video";
19 pub const JOIN: &str = "join";
20 pub const SNOOZE: &str = "snooze";
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Urgency {
25 Low = 0,
26 Normal = 1,
27 Critical = 2,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum DesktopKey {
32 Message(u64),
33 Ring(u64),
34 Meeting(u64),
35}
36
37impl DesktopKey {
38 pub fn replace_token(&self) -> String {
39 match self {
40 DesktopKey::Message(id) => format!("message:{id}"),
41 DesktopKey::Ring(id) => format!("ring:{id}"),
42 DesktopKey::Meeting(id) => format!("meeting:{id}"),
43 }
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct DesktopAction {
49 pub id: &'static str,
50 pub label: String,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct DesktopPayload {
55 pub key: DesktopKey,
56 /// Stable replace key across updates (conversation, ring id, meeting event).
57 pub replace_key: String,
58 pub summary: String,
59 pub body: String,
60 pub actions: Vec<DesktopAction>,
61 /// Milliseconds. `0` means do not expire.
62 pub timeout_ms: i32,
63 pub urgency: Urgency,
64 pub category: &'static str,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct MessageLabels {
69 pub mark_read: String,
70 pub reply: String,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct RingLabels {
75 pub decline: String,
76 pub accept: String,
77 pub audio: String,
78 pub video: String,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct MeetingLabels {
83 pub join: String,
84 pub snooze: String,
85}
86
87pub fn message_payload(
88 model: &ToastModel,
89 preview_on: bool,
90 labels: &MessageLabels,
91) -> DesktopPayload {
92 let text = describe(model, preview_on);
93 let body = if model.agent.is_some() {
94 if text.preview.is_empty() {
95 model
96 .agent
97 .as_ref()
98 .map(|agent| agent.body.clone())
99 .unwrap_or_default()
100 } else {
101 text.preview.clone()
102 }
103 } else {
104 text.preview.clone()
105 };
106 let summary = if let Some(agent) = &model.agent {
107 if agent.title.is_empty() {
108 text.title.clone()
109 } else {
110 agent.title.clone()
111 }
112 } else {
113 text.title.clone()
114 };
115 let mention = model.mentions_me;
116 let timeout_ms = if mention {
117 MENTION_DURATION.as_millis() as i32
118 } else {
119 MESSAGE_DURATION.as_millis() as i32
120 };
121 let urgency = if model.urgent {
122 Urgency::Critical
123 } else {
124 Urgency::Normal
125 };
126 let mut actions = vec![DesktopAction {
127 id: action::MARK_READ,
128 label: labels.mark_read.clone(),
129 }];
130 if model.agent.is_none() && !model.status_change {
131 actions.push(DesktopAction {
132 id: action::REPLY,
133 label: labels.reply.clone(),
134 });
135 }
136 DesktopPayload {
137 key: DesktopKey::Message(model.id),
138 replace_key: format!("conversation:{}", model.conversation_id),
139 summary,
140 body,
141 actions,
142 timeout_ms,
143 urgency,
144 category: if model.agent.is_some() {
145 "im"
146 } else {
147 "im.received"
148 },
149 }
150}
151
152pub fn ring_payload(
153 ring_id: u64,
154 caller_name: &str,
155 subtitle: &str,
156 video: bool,
157 labels: &RingLabels,
158) -> DesktopPayload {
159 let accept_label = if video {
160 labels.audio.clone()
161 } else {
162 labels.accept.clone()
163 };
164 let mut actions = vec![
165 DesktopAction {
166 id: action::DECLINE,
167 label: labels.decline.clone(),
168 },
169 DesktopAction {
170 id: action::ACCEPT_AUDIO,
171 label: accept_label,
172 },
173 ];
174 if video {
175 actions.push(DesktopAction {
176 id: action::ACCEPT_VIDEO,
177 label: labels.video.clone(),
178 });
179 }
180 DesktopPayload {
181 key: DesktopKey::Ring(ring_id),
182 replace_key: format!("ring:{ring_id}"),
183 summary: caller_name.to_owned(),
184 body: subtitle.to_owned(),
185 actions,
186 timeout_ms: 0,
187 urgency: Urgency::Critical,
188 category: "x-teams.call.incoming",
189 }
190}
191
192pub fn meeting_payload(toast: &MeetingToast, body: &str, labels: &MeetingLabels) -> DesktopPayload {
193 let mut actions = Vec::new();
194 if toast.phase == ReminderPhase::Soon {
195 actions.push(DesktopAction {
196 id: action::SNOOZE,
197 label: labels.snooze.clone(),
198 });
199 }
200 actions.push(DesktopAction {
201 id: action::JOIN,
202 label: labels.join.clone(),
203 });
204 DesktopPayload {
205 key: DesktopKey::Meeting(toast.id),
206 replace_key: format!("meeting:{}", toast.event_key),
207 summary: toast.subject.clone(),
208 body: body.to_owned(),
209 actions,
210 timeout_ms: 0,
211 urgency: Urgency::Normal,
212 category: "x-teams.meeting.reminder",
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use std::time::Instant;
219
220 use super::*;
221 use crate::notify::rules::{ChatKind, Preview};
222 use crate::notify::stack::{Fade, ReplyState, ToastTimer};
223
224 fn message_labels() -> MessageLabels {
225 MessageLabels {
226 mark_read: "Mark as read".into(),
227 reply: "Reply".into(),
228 }
229 }
230
231 fn ring_labels() -> RingLabels {
232 RingLabels {
233 decline: "Decline".into(),
234 accept: "Accept".into(),
235 audio: "Audio".into(),
236 video: "Video".into(),
237 }
238 }
239
240 fn meeting_labels() -> MeetingLabels {
241 MeetingLabels {
242 join: "Join".into(),
243 snooze: "Snooze".into(),
244 }
245 }
246
247 fn toast(mention: bool, urgent: bool, preview: Preview) -> ToastModel {
248 ToastModel {
249 id: 7,
250 conversation_id: "chat-a".into(),
251 message_id: "m1".into(),
252 kind: ChatKind::Direct,
253 chat_title: String::new(),
254 sender_id: Some("u1".into()),
255 sender_name: "Priya Nair".into(),
256 preview,
257 mentions_me: mention,
258 count: 1,
259 timer: ToastTimer::new(Instant::now(), mention),
260 reply: ReplyState::Closed,
261 reply_text: String::new(),
262 hovered: false,
263 time: String::new(),
264 queued: false,
265 dismissed: false,
266 fade: Fade::shown(Instant::now()),
267 agent: None,
268 status_change: false,
269 urgent,
270 }
271 }
272
273 #[test]
274 fn preview_off_hides_message_text() {
275 let model = toast(false, false, Preview::Text("secret".into()));
276 let payload = message_payload(&model, false, &message_labels());
277 assert_eq!(payload.body, "New message");
278 assert_eq!(payload.replace_key, "conversation:chat-a");
279 assert_eq!(payload.timeout_ms, MESSAGE_DURATION.as_millis() as i32);
280 }
281
282 #[test]
283 fn mention_uses_longer_timeout() {
284 let model = toast(true, false, Preview::Text("hi".into()));
285 let payload = message_payload(&model, true, &message_labels());
286 assert_eq!(payload.timeout_ms, MENTION_DURATION.as_millis() as i32);
287 }
288
289 #[test]
290 fn urgent_sets_critical_urgency() {
291 let model = toast(false, true, Preview::Text("down".into()));
292 let payload = message_payload(&model, true, &message_labels());
293 assert_eq!(payload.urgency, Urgency::Critical);
294 }
295
296 #[test]
297 fn message_offers_mark_read_and_reply() {
298 let model = toast(false, false, Preview::Text("hi".into()));
299 let payload = message_payload(&model, true, &message_labels());
300 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
301 assert_eq!(ids, vec![action::MARK_READ, action::REPLY]);
302 }
303
304 #[test]
305 fn bundling_shares_conversation_replace_key() {
306 let first = toast(false, false, Preview::Text("one".into()));
307 let mut second = toast(false, false, Preview::Text("two".into()));
308 second.id = 99;
309 let a = message_payload(&first, true, &message_labels());
310 let b = message_payload(&second, true, &message_labels());
311 assert_eq!(a.replace_key, b.replace_key);
312 assert_ne!(a.key, b.key);
313 }
314
315 #[test]
316 fn audio_ring_has_no_timeout_and_no_video_action() {
317 let payload = ring_payload(3, "Alex", "Incoming audio call", false, &ring_labels());
318 assert_eq!(payload.timeout_ms, 0);
319 assert_eq!(payload.urgency, Urgency::Critical);
320 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
321 assert_eq!(ids, vec![action::DECLINE, action::ACCEPT_AUDIO]);
322 assert_eq!(payload.actions[1].label, "Accept");
323 }
324
325 #[test]
326 fn video_ring_offers_audio_and_video() {
327 let payload = ring_payload(3, "Alex", "Incoming video call", true, &ring_labels());
328 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
329 assert_eq!(
330 ids,
331 vec![action::DECLINE, action::ACCEPT_AUDIO, action::ACCEPT_VIDEO]
332 );
333 assert_eq!(payload.actions[1].label, "Audio");
334 }
335
336 #[test]
337 fn meeting_soon_offers_snooze_and_join() {
338 let toast = MeetingToast {
339 id: 1,
340 event_key: "e@1".into(),
341 event_id: "e".into(),
342 phase: ReminderPhase::Soon,
343 subject: "Standup".into(),
344 start: chrono::Utc::now(),
345 join_url: "https://teams.microsoft.com/l/meetup-join/x".into(),
346 };
347 let payload = meeting_payload(&toast, "in 5 minutes", &meeting_labels());
348 let ids: Vec<_> = payload.actions.iter().map(|a| a.id).collect();
349 assert_eq!(ids, vec![action::SNOOZE, action::JOIN]);
350 assert_eq!(payload.timeout_ms, 0);
351 }
352
353 #[test]
354 fn meeting_live_drops_snooze_same_replace_key() {
355 let soon = MeetingToast {
356 id: 1,
357 event_key: "e@1".into(),
358 event_id: "e".into(),
359 phase: ReminderPhase::Soon,
360 subject: "Standup".into(),
361 start: chrono::Utc::now(),
362 join_url: "https://example".into(),
363 };
364 let live = MeetingToast {
365 id: 2,
366 phase: ReminderPhase::Live,
367 ..soon.clone()
368 };
369 let a = meeting_payload(&soon, "soon", &meeting_labels());
370 let b = meeting_payload(&live, "live now", &meeting_labels());
371 assert_eq!(a.replace_key, b.replace_key);
372 assert_eq!(
373 b.actions.iter().map(|a| a.id).collect::<Vec<_>>(),
374 vec![action::JOIN]
375 );
376 }
377}
crates/app-state/src/notify/mod.rs +6 −0
@@ -1,3 +1,4 @@
1 pub mod desktop_payload;
1 2 pub mod incoming;
2 3 pub mod layout;
3 4 pub mod pause;
@@ -8,6 +9,11 @@ pub mod taskbar;
8 9 pub mod text;
9 10 pub mod urgent_repeat;
10 11
12 pub use desktop_payload::{
13 DesktopAction, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, Urgency,
14 action, meeting_payload, message_payload, ring_payload,
15 };
16
11 17 pub use app_base::notify::{badge, platform, sound_cache, sounds};
12 18 pub use chatsvc::sound_settings;
13 19 pub use incoming::{IncomingTracker, LateArrivals, preview_of};
@@ -1,3 +1,4 @@
1pub mod desktop_payload;
1pub mod incoming;
2pub mod incoming;
2pub mod layout;
3pub mod layout;
3pub mod pause;
4pub mod pause;
@@ -8,6 +9,11 @@ pub mod taskbar;
8pub mod text;
9pub mod text;
9pub mod urgent_repeat;
10pub mod urgent_repeat;
10
11
12pub use desktop_payload::{
13 DesktopAction, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, Urgency,
14 action, meeting_payload, message_payload, ring_payload,
15};
16
11pub use app_base::notify::{badge, platform, sound_cache, sounds};
17pub use app_base::notify::{badge, platform, sound_cache, sounds};
12pub use chatsvc::sound_settings;
18pub use chatsvc::sound_settings;
13pub use incoming::{IncomingTracker, LateArrivals, preview_of};
19pub use incoming::{IncomingTracker, LateArrivals, preview_of};
crates/app/src/notify/center.rs +311 −49
@@ -2,7 +2,7 @@ use std::cell::Cell;
2 2 use std::collections::{HashMap, HashSet};
3 3 use std::time::{Duration, Instant};
4 4
5 use chrono::{DateTime, Utc};
5 use chrono::{DateTime, Local, Offset, Utc};
6 6 use gpui_kit::*;
7 7 use store::Sidebar;
8 8 use teams_core::{ForcedAvailability, ForcedKind};
@@ -25,7 +25,16 @@ use super::stack::{
25 25 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
26 26 ToastModel, ToastStack,
27 27 };
28 #[cfg(target_os = "linux")]
29 use super::desktop_payload::{
30 self, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, action,
31 };
32 #[cfg(target_os = "linux")]
33 use super::platform::{
34 BusNotification, DesktopNotifications, NotificationEvent, NotificationImage,
35 };
28 36 use super::taskbar::taskbar_badge_count;
37 #[cfg(not(target_os = "linux"))]
29 38 use super::text::describe;
30 39 use super::toast::{PillView, ToastView};
31 40 use super::urgent_repeat::UrgentRepeats;
@@ -39,6 +48,7 @@ use crate::appearance::AppIcon;
39 48 use crate::autostart::{self, StartupSettings};
40 49 use crate::call::DemoScene;
41 50 use crate::data::{self, Directory, PresenceKind};
51 use crate::own_status::{self, StatusDuration};
42 52 use crate::runtime;
43 53 use crate::settings_section::SettingsSection;
44 54 use crate::single_instance;
@@ -107,6 +117,13 @@ pub struct NotificationCenter {
107 117 unread_mentions: HashSet<String>,
108 118 tray: Option<Tray>,
109 119 tray_do_not_disturb: bool,
120 #[cfg(target_os = "linux")]
121 desktop: Option<DesktopNotifications>,
122 /// Logical keys to CloseNotification on the next desktop sync (dismiss / open / ring gone).
123 #[cfg(target_os = "linux")]
124 desktop_close: Vec<String>,
125 #[cfg(target_os = "linux")]
126 desktop_published: HashSet<String>,
110 127 app_icon: AppIcon,
111 128 shown_badge: Option<Badge>,
112 129 shown_mention_dot: bool,
@@ -190,6 +207,16 @@ impl NotificationCenter {
190 207 unread_mentions: HashSet::new(),
191 208 tray,
192 209 tray_do_not_disturb,
210 #[cfg(target_os = "linux")]
211 desktop: if app.read(cx).mode.demo {
212 None
213 } else {
214 DesktopNotifications::start()
215 },
216 #[cfg(target_os = "linux")]
217 desktop_close: Vec::new(),
218 #[cfg(target_os = "linux")]
219 desktop_published: HashSet::new(),
193 220 app_icon,
194 221 shown_badge: None,
195 222 shown_mention_dot: false,
@@ -424,7 +451,7 @@ impl NotificationCenter {
424 451 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
425 452 AppEvent::Selection => self.on_selection(cx),
426 453 AppEvent::Sidebar => self.refresh_badge(cx),
427 AppEvent::Directory => self.sync_tray_presence(cx),
454 AppEvent::Directory | AppEvent::Status => self.sync_tray_presence(cx),
428 455 AppEvent::Ring => self.on_rings_changed(cx),
429 456 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
430 457 AppEvent::MeetingChime => self.on_meeting_chime(cx),
@@ -783,54 +810,64 @@ impl NotificationCenter {
783 810 }
784 811
785 812 fn sync_windows(&mut self, cx: &mut Context<Self>) {
786 let visible = self.visible_ids();
787 let stale: Vec<u64> = self
788 .windows
789 .keys()
790 .filter(|id| !visible.contains(id))
791 .copied()
792 .collect();
793 for id in stale {
794 self.close_window(id, cx);
795 }
796 let call_toasts = self.call_toasts(cx);
797 let stale_call_toasts: Vec<CallToast> = self
798 .call_windows
799 .keys()
800 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
801 .copied()
802 .collect();
803 for key in stale_call_toasts {
804 self.close_call_window(key, cx);
805 }
806 let area = self.work_area(cx);
807 let mut heights: Vec<f32> = self
808 .stack
809 .visible()
810 .iter()
811 .map(|toast| {
812 let lines = match &toast.agent {
813 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
814 None => {
815 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
816 }
817 };
818 layout::toast_height(toast, lines)
819 })
820 .collect();
821 heights.extend(call_toasts.iter().map(|(_, height)| *height));
822 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
823 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
824 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
825 self.place_toast(*id, *slot, area, cx);
813 #[cfg(target_os = "linux")]
814 {
815 self.poll_desktop(cx);
816 self.sync_desktop(cx);
817 return;
826 818 }
827 for ((key, _), slot) in call_toasts
828 .iter()
829 .zip(slots.toasts.iter().skip(visible.len()))
819 #[cfg(not(target_os = "linux"))]
830 820 {
831 self.place_call_toast(*key, *slot, area, cx);
821 let visible = self.visible_ids();
822 let stale: Vec<u64> = self
823 .windows
824 .keys()
825 .filter(|id| !visible.contains(id))
826 .copied()
827 .collect();
828 for id in stale {
829 self.close_window(id, cx);
830 }
831 let call_toasts = self.call_toasts(cx);
832 let stale_call_toasts: Vec<CallToast> = self
833 .call_windows
834 .keys()
835 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
836 .copied()
837 .collect();
838 for key in stale_call_toasts {
839 self.close_call_window(key, cx);
840 }
841 let area = self.work_area(cx);
842 let mut heights: Vec<f32> = self
843 .stack
844 .visible()
845 .iter()
846 .map(|toast| {
847 let lines = match &toast.agent {
848 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
849 None => preview_lines(
850 &describe(toast, shows_preview(&self.settings)).preview,
851 cx,
852 ),
853 };
854 layout::toast_height(toast, lines)
855 })
856 .collect();
857 heights.extend(call_toasts.iter().map(|(_, height)| *height));
858 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
859 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
860 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
861 self.place_toast(*id, *slot, area, cx);
862 }
863 for ((key, _), slot) in call_toasts
864 .iter()
865 .zip(slots.toasts.iter().skip(visible.len()))
866 {
867 self.place_call_toast(*key, *slot, area, cx);
868 }
869 self.sync_pill(slots.pill, area, cx);
832 870 }
833 self.sync_pill(slots.pill, area, cx);
834 871 }
835 872
836 873 fn place_call_toast(
@@ -1060,6 +1097,8 @@ impl NotificationCenter {
1060 1097 }
1061 1098
1062 1099 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1100 #[cfg(target_os = "linux")]
1101 self.queue_desktop_close(DesktopKey::Message(id));
1063 1102 let fast = self.animated(FAST_FADE);
1064 1103 self.stack.dismiss(id, Instant::now(), fast);
1065 1104 cx.notify();
@@ -1125,14 +1164,24 @@ impl NotificationCenter {
1125 1164 self.app
1126 1165 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
1127 1166 }
1128 if !self.stack.is_empty()
1167 let needs_sync = !self.stack.is_empty()
1129 1168 || !self.windows.is_empty()
1130 1169 || self.pill.is_some()
1131 1170 || !self.call_windows.is_empty()
1132 {
1171 || self.app.read(cx).rings.is_ringing()
1172 || !self.app.read(cx).meeting_toasts.is_empty();
1173 #[cfg(target_os = "linux")]
1174 let needs_sync = needs_sync
1175 || !self.desktop_close.is_empty()
1176 || !self.desktop_published.is_empty();
1177 if needs_sync {
1133 1178 self.sync_windows(cx);
1134 1179 cx.notify();
1135 1180 }
1181 #[cfg(target_os = "linux")]
1182 if self.desktop.is_some() {
1183 self.poll_desktop(cx);
1184 }
1136 1185 self.poll_tray(cx);
1137 1186 if single_instance::take_activation() {
1138 1187 self.raise_main_window(cx);
@@ -1170,6 +1219,206 @@ impl NotificationCenter {
1170 1219 }
1171 1220 }
1172 1221
1222 #[cfg(target_os = "linux")]
1223 fn queue_desktop_close(&mut self, key: DesktopKey) {
1224 self.desktop_close.push(key.replace_token());
1225 }
1226
1227 #[cfg(target_os = "linux")]
1228 fn message_labels() -> MessageLabels {
1229 MessageLabels {
1230 mark_read: crate::i18n::tr("notify.mark_read"),
1231 reply: crate::i18n::tr("notify.reply"),
1232 }
1233 }
1234
1235 #[cfg(target_os = "linux")]
1236 fn ring_labels() -> RingLabels {
1237 RingLabels {
1238 decline: crate::i18n::tr("notify.decline"),
1239 accept: crate::i18n::tr("notify.accept"),
1240 audio: crate::i18n::tr("notify.audio"),
1241 video: crate::i18n::tr("notify.video"),
1242 }
1243 }
1244
1245 #[cfg(target_os = "linux")]
1246 fn meeting_labels() -> MeetingLabels {
1247 MeetingLabels {
1248 join: crate::i18n::tr("notify.join"),
1249 snooze: crate::i18n::tr("notify.snooze"),
1250 }
1251 }
1252
1253 #[cfg(target_os = "linux")]
1254 fn to_bus(payload: DesktopPayload, image: Option<NotificationImage>) -> BusNotification {
1255 BusNotification {
1256 logical_key: payload.key.replace_token(),
1257 replace_key: payload.replace_key,
1258 summary: payload.summary,
1259 body: payload.body,
1260 actions: payload
1261 .actions
1262 .into_iter()
1263 .map(|action| (action.id.to_owned(), action.label))
1264 .collect(),
1265 timeout_ms: payload.timeout_ms,
1266 urgency: payload.urgency as u8,
1267 category: payload.category.to_owned(),
1268 image,
1269 }
1270 }
1271
1272 #[cfg(target_os = "linux")]
1273 fn avatar_notification_image(state: &AppState, user_id: Option<&str>) -> Option<NotificationImage> {
1274 use crate::data::AvatarState;
1275 use image::imageops::FilterType;
1276
1277 let user_id = user_id?;
1278 let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {
1279 return None;
1280 };
1281 let decoded = image::load_from_memory(photo.source_bytes()).ok()?;
1282 let rgba = decoded
1283 .resize_exact(64, 64, FilterType::Lanczos3)
1284 .into_rgba8();
1285 Some(NotificationImage {
1286 width: rgba.width(),
1287 height: rgba.height(),
1288 rgba: rgba.into_raw(),
1289 })
1290 }
1291
1292 #[cfg(target_os = "linux")]
1293 fn sync_desktop(&mut self, cx: &mut Context<Self>) {
1294 let Some(desktop) = &self.desktop else {
1295 return;
1296 };
1297 let preview_on = shows_preview(&self.settings);
1298 let message_labels = Self::message_labels();
1299 let ring_labels = Self::ring_labels();
1300 let meeting_labels = Self::meeting_labels();
1301 let state = self.app.read(cx);
1302 let mut visible = Vec::new();
1303 let mut visible_logical = HashSet::new();
1304 for toast in self.stack.visible() {
1305 let image = Self::avatar_notification_image(state, toast.sender_id.as_deref());
1306 let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);
1307 visible_logical.insert(payload.key.replace_token());
1308 visible.push(Self::to_bus(payload, image));
1309 }
1310 for entry in state.rings.ringing() {
1311 let payload = desktop_payload::ring_payload(
1312 entry.ring.ring_id,
1313 entry.caller_name(),
1314 entry.subtitle(),
1315 entry.ring.video,
1316 &ring_labels,
1317 );
1318 let image = Self::avatar_notification_image(state, entry.caller_user_id().as_deref());
1319 visible_logical.insert(payload.key.replace_token());
1320 visible.push(Self::to_bus(payload, image));
1321 }
1322 let now = Utc::now();
1323 let offset = Local::now().offset().fix();
1324 for toast in state.meeting_toasts.entries() {
1325 let body = crate::call::meeting_subtitle(toast, now, offset);
1326 let payload = desktop_payload::meeting_payload(toast, &body, &meeting_labels);
1327 visible_logical.insert(payload.key.replace_token());
1328 visible.push(Self::to_bus(payload, None));
1329 }
1330 let mut close = std::mem::take(&mut self.desktop_close);
1331 for previous in &self.desktop_published {
1332 if visible_logical.contains(previous) {
1333 continue;
1334 }
1335 // Rings and meetings must leave the shell when the call/reminder ends.
1336 if previous.starts_with("ring:") || previous.starts_with("meeting:") {
1337 close.push(previous.clone());
1338 }
1339 }
1340 close.sort();
1341 close.dedup();
1342 desktop.sync(visible, close);
1343 self.desktop_published = visible_logical;
1344 }
1345
1346 #[cfg(target_os = "linux")]
1347 fn poll_desktop(&mut self, cx: &mut Context<Self>) {
1348 let Some(desktop) = &self.desktop else {
1349 return;
1350 };
1351 let events = desktop.poll();
1352 for event in events {
1353 match event {
1354 NotificationEvent::Action {
1355 logical_key,
1356 action_id,
1357 } => self.handle_desktop_action(&logical_key, &action_id, cx),
1358 NotificationEvent::Reply { logical_key, text } => {
1359 if let Some(DesktopKey::Message(id)) = parse_logical_key(&logical_key) {
1360 self.submit_reply(id, text, cx);
1361 }
1362 }
1363 NotificationEvent::Closed {
1364 logical_key,
1365 reason,
1366 } => {
1367 // Reason 2 = dismissed by the user in the shell.
1368 if reason == 2
1369 && let Some(DesktopKey::Meeting(toast_id)) = parse_logical_key(&logical_key)
1370 {
1371 self.app.update(cx, |state, cx| {
1372 state.dismiss_meeting_toast(toast_id, cx)
1373 });
1374 }
1375 }
1376 }
1377 }
1378 }
1379
1380 #[cfg(target_os = "linux")]
1381 fn handle_desktop_action(&mut self, logical_key: &str, action_id: &str, cx: &mut Context<Self>) {
1382 let Some(key) = parse_logical_key(logical_key) else {
1383 return;
1384 };
1385 match key {
1386 DesktopKey::Message(id)
1387 if action_id == action::DEFAULT
1388 || action_id == action::REPLY
1389 || action_id == "reply-open" =>
1390 {
1391 self.activate(id, cx);
1392 }
1393 DesktopKey::Message(id) if action_id == action::MARK_READ => self.mark_read(id, cx),
1394 DesktopKey::Ring(ring_id) if action_id == action::DECLINE => {
1395 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1396 self.app
1397 .update(cx, |state, cx| state.decline_ring(ring_id, cx));
1398 }
1399 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_AUDIO => {
1400 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1401 self.accept_ring(ring_id, calling::AcceptMode::Audio, cx);
1402 }
1403 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_VIDEO => {
1404 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1405 self.accept_ring(ring_id, calling::AcceptMode::Video, cx);
1406 }
1407 DesktopKey::Meeting(toast_id)
1408 if action_id == action::JOIN || action_id == action::DEFAULT =>
1409 {
1410 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1411 self.join_meeting_toast(toast_id, cx);
1412 }
1413 DesktopKey::Meeting(toast_id) if action_id == action::SNOOZE => {
1414 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1415 self.app
1416 .update(cx, |state, cx| state.snooze_meeting_toast(toast_id, cx));
1417 }
1418 _ => {}
1419 }
1420 }
1421
1173 1422 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1174 1423 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1175 1424 for command in commands {
@@ -1547,6 +1796,7 @@ fn own_do_not_disturb(state: &AppState) -> bool {
1547 1796 own_presence(state) == PresenceKind::DoNotDisturb
1548 1797 }
1549 1798
1799
1550 1800 fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1551 1801 match (audible, handle.is_some()) {
1552 1802 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
@@ -1593,6 +1843,18 @@ fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
1593 1843 .sum()
1594 1844 }
1595 1845
1846 #[cfg(target_os = "linux")]
1847 fn parse_logical_key(key: &str) -> Option<DesktopKey> {
1848 let (kind, id) = key.split_once(':')?;
1849 let id = id.parse().ok()?;
1850 match kind {
1851 "message" => Some(DesktopKey::Message(id)),
1852 "ring" => Some(DesktopKey::Ring(id)),
1853 "meeting" => Some(DesktopKey::Meeting(id)),
1854 _ => None,
1855 }
1856 }
1857
1596 1858 fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1597 1859 let scale = area.scale;
1598 1860 let bounds = Bounds::new(
@@ -2,7 +2,7 @@ use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
2use std::collections::{HashMap, HashSet};
3use std::time::{Duration, Instant};
3use std::time::{Duration, Instant};
4
4
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Local, Offset, Utc};
6use gpui_kit::*;
6use gpui_kit::*;
7use store::Sidebar;
7use store::Sidebar;
8use teams_core::{ForcedAvailability, ForcedKind};
8use teams_core::{ForcedAvailability, ForcedKind};
@@ -25,7 +25,16 @@ use super::stack::{
25 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
25 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
26 ToastModel, ToastStack,
26 ToastModel, ToastStack,
27};
27};
28#[cfg(target_os = "linux")]
29use super::desktop_payload::{
30 self, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, action,
31};
32#[cfg(target_os = "linux")]
33use super::platform::{
34 BusNotification, DesktopNotifications, NotificationEvent, NotificationImage,
35};
28use super::taskbar::taskbar_badge_count;
36use super::taskbar::taskbar_badge_count;
37#[cfg(not(target_os = "linux"))]
29use super::text::describe;
38use super::text::describe;
30use super::toast::{PillView, ToastView};
39use super::toast::{PillView, ToastView};
31use super::urgent_repeat::UrgentRepeats;
40use super::urgent_repeat::UrgentRepeats;
@@ -39,6 +48,7 @@ use crate::appearance::AppIcon;
39use crate::autostart::{self, StartupSettings};
48use crate::autostart::{self, StartupSettings};
40use crate::call::DemoScene;
49use crate::call::DemoScene;
41use crate::data::{self, Directory, PresenceKind};
50use crate::data::{self, Directory, PresenceKind};
51use crate::own_status::{self, StatusDuration};
42use crate::runtime;
52use crate::runtime;
43use crate::settings_section::SettingsSection;
53use crate::settings_section::SettingsSection;
44use crate::single_instance;
54use crate::single_instance;
@@ -107,6 +117,13 @@ pub struct NotificationCenter {
107 unread_mentions: HashSet<String>,
117 unread_mentions: HashSet<String>,
108 tray: Option<Tray>,
118 tray: Option<Tray>,
109 tray_do_not_disturb: bool,
119 tray_do_not_disturb: bool,
120 #[cfg(target_os = "linux")]
121 desktop: Option<DesktopNotifications>,
122 /// Logical keys to CloseNotification on the next desktop sync (dismiss / open / ring gone).
123 #[cfg(target_os = "linux")]
124 desktop_close: Vec<String>,
125 #[cfg(target_os = "linux")]
126 desktop_published: HashSet<String>,
110 app_icon: AppIcon,
127 app_icon: AppIcon,
111 shown_badge: Option<Badge>,
128 shown_badge: Option<Badge>,
112 shown_mention_dot: bool,
129 shown_mention_dot: bool,
@@ -190,6 +207,16 @@ impl NotificationCenter {
190 unread_mentions: HashSet::new(),
207 unread_mentions: HashSet::new(),
191 tray,
208 tray,
192 tray_do_not_disturb,
209 tray_do_not_disturb,
210 #[cfg(target_os = "linux")]
211 desktop: if app.read(cx).mode.demo {
212 None
213 } else {
214 DesktopNotifications::start()
215 },
216 #[cfg(target_os = "linux")]
217 desktop_close: Vec::new(),
218 #[cfg(target_os = "linux")]
219 desktop_published: HashSet::new(),
193 app_icon,
220 app_icon,
194 shown_badge: None,
221 shown_badge: None,
195 shown_mention_dot: false,
222 shown_mention_dot: false,
@@ -424,7 +451,7 @@ impl NotificationCenter {
424 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
451 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
425 AppEvent::Selection => self.on_selection(cx),
452 AppEvent::Selection => self.on_selection(cx),
426 AppEvent::Sidebar => self.refresh_badge(cx),
453 AppEvent::Sidebar => self.refresh_badge(cx),
427 AppEvent::Directory => self.sync_tray_presence(cx),
454 AppEvent::Directory | AppEvent::Status => self.sync_tray_presence(cx),
428 AppEvent::Ring => self.on_rings_changed(cx),
455 AppEvent::Ring => self.on_rings_changed(cx),
429 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
456 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
430 AppEvent::MeetingChime => self.on_meeting_chime(cx),
457 AppEvent::MeetingChime => self.on_meeting_chime(cx),
@@ -783,54 +810,64 @@ impl NotificationCenter {
783 }
810 }
784
811
785 fn sync_windows(&mut self, cx: &mut Context<Self>) {
812 fn sync_windows(&mut self, cx: &mut Context<Self>) {
786 let visible = self.visible_ids();
813 #[cfg(target_os = "linux")]
787 let stale: Vec<u64> = self
814 {
788 .windows
815 self.poll_desktop(cx);
789 .keys()
816 self.sync_desktop(cx);
790 .filter(|id| !visible.contains(id))
817 return;
791 .copied()
792 .collect();
793 for id in stale {
794 self.close_window(id, cx);
795 }
796 let call_toasts = self.call_toasts(cx);
797 let stale_call_toasts: Vec<CallToast> = self
798 .call_windows
799 .keys()
800 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
801 .copied()
802 .collect();
803 for key in stale_call_toasts {
804 self.close_call_window(key, cx);
805 }
806 let area = self.work_area(cx);
807 let mut heights: Vec<f32> = self
808 .stack
809 .visible()
810 .iter()
811 .map(|toast| {
812 let lines = match &toast.agent {
813 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
814 None => {
815 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
816 }
817 };
818 layout::toast_height(toast, lines)
819 })
820 .collect();
821 heights.extend(call_toasts.iter().map(|(_, height)| *height));
822 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
823 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
824 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
825 self.place_toast(*id, *slot, area, cx);
826 }
818 }
827 for ((key, _), slot) in call_toasts
819 #[cfg(not(target_os = "linux"))]
828 .iter()
829 .zip(slots.toasts.iter().skip(visible.len()))
830 {
820 {
831 self.place_call_toast(*key, *slot, area, cx);
821 let visible = self.visible_ids();
822 let stale: Vec<u64> = self
823 .windows
824 .keys()
825 .filter(|id| !visible.contains(id))
826 .copied()
827 .collect();
828 for id in stale {
829 self.close_window(id, cx);
830 }
831 let call_toasts = self.call_toasts(cx);
832 let stale_call_toasts: Vec<CallToast> = self
833 .call_windows
834 .keys()
835 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
836 .copied()
837 .collect();
838 for key in stale_call_toasts {
839 self.close_call_window(key, cx);
840 }
841 let area = self.work_area(cx);
842 let mut heights: Vec<f32> = self
843 .stack
844 .visible()
845 .iter()
846 .map(|toast| {
847 let lines = match &toast.agent {
848 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
849 None => preview_lines(
850 &describe(toast, shows_preview(&self.settings)).preview,
851 cx,
852 ),
853 };
854 layout::toast_height(toast, lines)
855 })
856 .collect();
857 heights.extend(call_toasts.iter().map(|(_, height)| *height));
858 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
859 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
860 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
861 self.place_toast(*id, *slot, area, cx);
862 }
863 for ((key, _), slot) in call_toasts
864 .iter()
865 .zip(slots.toasts.iter().skip(visible.len()))
866 {
867 self.place_call_toast(*key, *slot, area, cx);
868 }
869 self.sync_pill(slots.pill, area, cx);
832 }
870 }
833 self.sync_pill(slots.pill, area, cx);
834 }
871 }
835
872
836 fn place_call_toast(
873 fn place_call_toast(
@@ -1060,6 +1097,8 @@ impl NotificationCenter {
1060 }
1097 }
1061
1098
1062 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1099 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1100 #[cfg(target_os = "linux")]
1101 self.queue_desktop_close(DesktopKey::Message(id));
1063 let fast = self.animated(FAST_FADE);
1102 let fast = self.animated(FAST_FADE);
1064 self.stack.dismiss(id, Instant::now(), fast);
1103 self.stack.dismiss(id, Instant::now(), fast);
1065 cx.notify();
1104 cx.notify();
@@ -1125,14 +1164,24 @@ impl NotificationCenter {
1125 self.app
1164 self.app
1126 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
1165 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
1127 }
1166 }
1128 if !self.stack.is_empty()
1167 let needs_sync = !self.stack.is_empty()
1129 || !self.windows.is_empty()
1168 || !self.windows.is_empty()
1130 || self.pill.is_some()
1169 || self.pill.is_some()
1131 || !self.call_windows.is_empty()
1170 || !self.call_windows.is_empty()
1132 {
1171 || self.app.read(cx).rings.is_ringing()
1172 || !self.app.read(cx).meeting_toasts.is_empty();
1173 #[cfg(target_os = "linux")]
1174 let needs_sync = needs_sync
1175 || !self.desktop_close.is_empty()
1176 || !self.desktop_published.is_empty();
1177 if needs_sync {
1133 self.sync_windows(cx);
1178 self.sync_windows(cx);
1134 cx.notify();
1179 cx.notify();
1135 }
1180 }
1181 #[cfg(target_os = "linux")]
1182 if self.desktop.is_some() {
1183 self.poll_desktop(cx);
1184 }
1136 self.poll_tray(cx);
1185 self.poll_tray(cx);
1137 if single_instance::take_activation() {
1186 if single_instance::take_activation() {
1138 self.raise_main_window(cx);
1187 self.raise_main_window(cx);
@@ -1170,6 +1219,206 @@ impl NotificationCenter {
1170 }
1219 }
1171 }
1220 }
1172
1221
1222 #[cfg(target_os = "linux")]
1223 fn queue_desktop_close(&mut self, key: DesktopKey) {
1224 self.desktop_close.push(key.replace_token());
1225 }
1226
1227 #[cfg(target_os = "linux")]
1228 fn message_labels() -> MessageLabels {
1229 MessageLabels {
1230 mark_read: crate::i18n::tr("notify.mark_read"),
1231 reply: crate::i18n::tr("notify.reply"),
1232 }
1233 }
1234
1235 #[cfg(target_os = "linux")]
1236 fn ring_labels() -> RingLabels {
1237 RingLabels {
1238 decline: crate::i18n::tr("notify.decline"),
1239 accept: crate::i18n::tr("notify.accept"),
1240 audio: crate::i18n::tr("notify.audio"),
1241 video: crate::i18n::tr("notify.video"),
1242 }
1243 }
1244
1245 #[cfg(target_os = "linux")]
1246 fn meeting_labels() -> MeetingLabels {
1247 MeetingLabels {
1248 join: crate::i18n::tr("notify.join"),
1249 snooze: crate::i18n::tr("notify.snooze"),
1250 }
1251 }
1252
1253 #[cfg(target_os = "linux")]
1254 fn to_bus(payload: DesktopPayload, image: Option<NotificationImage>) -> BusNotification {
1255 BusNotification {
1256 logical_key: payload.key.replace_token(),
1257 replace_key: payload.replace_key,
1258 summary: payload.summary,
1259 body: payload.body,
1260 actions: payload
1261 .actions
1262 .into_iter()
1263 .map(|action| (action.id.to_owned(), action.label))
1264 .collect(),
1265 timeout_ms: payload.timeout_ms,
1266 urgency: payload.urgency as u8,
1267 category: payload.category.to_owned(),
1268 image,
1269 }
1270 }
1271
1272 #[cfg(target_os = "linux")]
1273 fn avatar_notification_image(state: &AppState, user_id: Option<&str>) -> Option<NotificationImage> {
1274 use crate::data::AvatarState;
1275 use image::imageops::FilterType;
1276
1277 let user_id = user_id?;
1278 let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {
1279 return None;
1280 };
1281 let decoded = image::load_from_memory(photo.source_bytes()).ok()?;
1282 let rgba = decoded
1283 .resize_exact(64, 64, FilterType::Lanczos3)
1284 .into_rgba8();
1285 Some(NotificationImage {
1286 width: rgba.width(),
1287 height: rgba.height(),
1288 rgba: rgba.into_raw(),
1289 })
1290 }
1291
1292 #[cfg(target_os = "linux")]
1293 fn sync_desktop(&mut self, cx: &mut Context<Self>) {
1294 let Some(desktop) = &self.desktop else {
1295 return;
1296 };
1297 let preview_on = shows_preview(&self.settings);
1298 let message_labels = Self::message_labels();
1299 let ring_labels = Self::ring_labels();
1300 let meeting_labels = Self::meeting_labels();
1301 let state = self.app.read(cx);
1302 let mut visible = Vec::new();
1303 let mut visible_logical = HashSet::new();
1304 for toast in self.stack.visible() {
1305 let image = Self::avatar_notification_image(state, toast.sender_id.as_deref());
1306 let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);
1307 visible_logical.insert(payload.key.replace_token());
1308 visible.push(Self::to_bus(payload, image));
1309 }
1310 for entry in state.rings.ringing() {
1311 let payload = desktop_payload::ring_payload(
1312 entry.ring.ring_id,
1313 entry.caller_name(),
1314 entry.subtitle(),
1315 entry.ring.video,
1316 &ring_labels,
1317 );
1318 let image = Self::avatar_notification_image(state, entry.caller_user_id().as_deref());
1319 visible_logical.insert(payload.key.replace_token());
1320 visible.push(Self::to_bus(payload, image));
1321 }
1322 let now = Utc::now();
1323 let offset = Local::now().offset().fix();
1324 for toast in state.meeting_toasts.entries() {
1325 let body = crate::call::meeting_subtitle(toast, now, offset);
1326 let payload = desktop_payload::meeting_payload(toast, &body, &meeting_labels);
1327 visible_logical.insert(payload.key.replace_token());
1328 visible.push(Self::to_bus(payload, None));
1329 }
1330 let mut close = std::mem::take(&mut self.desktop_close);
1331 for previous in &self.desktop_published {
1332 if visible_logical.contains(previous) {
1333 continue;
1334 }
1335 // Rings and meetings must leave the shell when the call/reminder ends.
1336 if previous.starts_with("ring:") || previous.starts_with("meeting:") {
1337 close.push(previous.clone());
1338 }
1339 }
1340 close.sort();
1341 close.dedup();
1342 desktop.sync(visible, close);
1343 self.desktop_published = visible_logical;
1344 }
1345
1346 #[cfg(target_os = "linux")]
1347 fn poll_desktop(&mut self, cx: &mut Context<Self>) {
1348 let Some(desktop) = &self.desktop else {
1349 return;
1350 };
1351 let events = desktop.poll();
1352 for event in events {
1353 match event {
1354 NotificationEvent::Action {
1355 logical_key,
1356 action_id,
1357 } => self.handle_desktop_action(&logical_key, &action_id, cx),
1358 NotificationEvent::Reply { logical_key, text } => {
1359 if let Some(DesktopKey::Message(id)) = parse_logical_key(&logical_key) {
1360 self.submit_reply(id, text, cx);
1361 }
1362 }
1363 NotificationEvent::Closed {
1364 logical_key,
1365 reason,
1366 } => {
1367 // Reason 2 = dismissed by the user in the shell.
1368 if reason == 2
1369 && let Some(DesktopKey::Meeting(toast_id)) = parse_logical_key(&logical_key)
1370 {
1371 self.app.update(cx, |state, cx| {
1372 state.dismiss_meeting_toast(toast_id, cx)
1373 });
1374 }
1375 }
1376 }
1377 }
1378 }
1379
1380 #[cfg(target_os = "linux")]
1381 fn handle_desktop_action(&mut self, logical_key: &str, action_id: &str, cx: &mut Context<Self>) {
1382 let Some(key) = parse_logical_key(logical_key) else {
1383 return;
1384 };
1385 match key {
1386 DesktopKey::Message(id)
1387 if action_id == action::DEFAULT
1388 || action_id == action::REPLY
1389 || action_id == "reply-open" =>
1390 {
1391 self.activate(id, cx);
1392 }
1393 DesktopKey::Message(id) if action_id == action::MARK_READ => self.mark_read(id, cx),
1394 DesktopKey::Ring(ring_id) if action_id == action::DECLINE => {
1395 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1396 self.app
1397 .update(cx, |state, cx| state.decline_ring(ring_id, cx));
1398 }
1399 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_AUDIO => {
1400 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1401 self.accept_ring(ring_id, calling::AcceptMode::Audio, cx);
1402 }
1403 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_VIDEO => {
1404 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1405 self.accept_ring(ring_id, calling::AcceptMode::Video, cx);
1406 }
1407 DesktopKey::Meeting(toast_id)
1408 if action_id == action::JOIN || action_id == action::DEFAULT =>
1409 {
1410 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1411 self.join_meeting_toast(toast_id, cx);
1412 }
1413 DesktopKey::Meeting(toast_id) if action_id == action::SNOOZE => {
1414 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1415 self.app
1416 .update(cx, |state, cx| state.snooze_meeting_toast(toast_id, cx));
1417 }
1418 _ => {}
1419 }
1420 }
1421
1173 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1422 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1174 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1423 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1175 for command in commands {
1424 for command in commands {
@@ -1547,6 +1796,7 @@ fn own_do_not_disturb(state: &AppState) -> bool {
1547 own_presence(state) == PresenceKind::DoNotDisturb
1796 own_presence(state) == PresenceKind::DoNotDisturb
1548}
1797}
1549
1798
1799
1550fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1800fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1551 match (audible, handle.is_some()) {
1801 match (audible, handle.is_some()) {
1552 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
1802 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
@@ -1593,6 +1843,18 @@ fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
1593 .sum()
1843 .sum()
1594}
1844}
1595
1845
1846#[cfg(target_os = "linux")]
1847fn parse_logical_key(key: &str) -> Option<DesktopKey> {
1848 let (kind, id) = key.split_once(':')?;
1849 let id = id.parse().ok()?;
1850 match kind {
1851 "message" => Some(DesktopKey::Message(id)),
1852 "ring" => Some(DesktopKey::Ring(id)),
1853 "meeting" => Some(DesktopKey::Meeting(id)),
1854 _ => None,
1855 }
1856}
1857
1596fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1858fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1597 let scale = area.scale;
1859 let scale = area.scale;
1598 let bounds = Bounds::new(
1860 let bounds = Bounds::new(
docs/decisions/0015-linux-desktop-toasts-use-freedesktop-notifications.md added +21 −0
@@ -0,0 +1,21 @@
1 ---
2 status: proposed
3 date: 2026-11-14
4 ---
5
6 # ADR 0015: Linux desktop toasts use freedesktop Notifications
7
8 ## Context
9
10 Message, ring, and meeting toasts on Windows are GPUI popup windows placed with Win32 (topmost, no activate, work-area corner). On Linux those platform hooks are stubs, so the decision layer and sounds already run but nothing appears. Copying the Win32 card with GPUI fails on Wayland: the toolkit cannot hide or decorate a borderless always-on-top inactive popup the way Teams expects. Options were: keep Linux silent, force a broken GPUI popup, or use the desktop notification service.
11
12 ## Decision
13
14 On Linux, toasts go through `org.freedesktop.Notifications`. Show/hide rules, texts, and actions stay the same as the Windows card. The app keeps playing its own notification and ring tones and asks the shell to stay silent. Leaving a notification in the desktop history after the popup times out, honouring desktop Do not disturb via `Inhibited` when present, and attaching a sender avatar when available are intentional extras beyond the Windows card. macOS stays stubbed until a separate change. Windows keeps the GPUI card.
15
16 ## Consequences
17
18 - Linux users get corner notifications on KDE and GNOME without a second UI toolkit path.
19 - Behaviour can differ by shell (history, inline reply, Do not disturb property).
20 - Without a notification daemon the app logs once and still plays sounds.
21 - A future macOS path should follow the same “OS surface, shared policy” split.
@@ -0,0 +1,21 @@
1---
2status: proposed
3date: 2026-11-14
4---
5
6# ADR 0015: Linux desktop toasts use freedesktop Notifications
7
8## Context
9
10Message, ring, and meeting toasts on Windows are GPUI popup windows placed with Win32 (topmost, no activate, work-area corner). On Linux those platform hooks are stubs, so the decision layer and sounds already run but nothing appears. Copying the Win32 card with GPUI fails on Wayland: the toolkit cannot hide or decorate a borderless always-on-top inactive popup the way Teams expects. Options were: keep Linux silent, force a broken GPUI popup, or use the desktop notification service.
11
12## Decision
13
14On Linux, toasts go through `org.freedesktop.Notifications`. Show/hide rules, texts, and actions stay the same as the Windows card. The app keeps playing its own notification and ring tones and asks the shell to stay silent. Leaving a notification in the desktop history after the popup times out, honouring desktop Do not disturb via `Inhibited` when present, and attaching a sender avatar when available are intentional extras beyond the Windows card. macOS stays stubbed until a separate change. Windows keeps the GPUI card.
15
16## Consequences
17
18- Linux users get corner notifications on KDE and GNOME without a second UI toolkit path.
19- Behaviour can differ by shell (history, inline reply, Do not disturb property).
20- Without a notification daemon the app logs once and still plays sounds.
21- A future macOS path should follow the same “OS surface, shared policy” split.
docs/decisions/README.md +2 −1
@@ -30,5 +30,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
30 30 | [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
31 31 | [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
32 32 | [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33 | [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
33 34
34 Records `0001` to `0014` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
35 Records `0001` to `0014` are the decisions already shipped. `0015` stays `proposed` until the Linux desktop-notifications change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -30,5 +30,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
30| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
30| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
31| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
31| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
32| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
32| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
33
34
34Records `0001` to `0014` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
35Records `0001` to `0014` are the decisions already shipped. `0015` stays `proposed` until the Linux desktop-notifications change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.