fix(linux): address Copilot review on desktop notifications
Reuse one Tokio runtime for Inhibited, poll the desktop bus once per tick, cache decoded notification avatars by user and source hash, and cover ring action locale keys in the ui_locale test.
@@ -1,7 +1,7 @@
1
1
//! Desktop notifications on Linux through `org.freedesktop.Notifications`.
2
2
3
3
use std::collections::HashMap;
4
use std::sync::Mutex;
4
use std::sync::{Mutex, OnceLock};
5
5
use std::sync::atomic::{AtomicBool, Ordering};
6
6
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
7
7
use std::thread;
@@ -477,12 +477,23 @@ fn parse_closed(
477
477
})
478
478
}
479
479
480
fn inhibit_runtime() -> Option<&'static tokio::runtime::Runtime> {
481
static RUNTIME: OnceLock<Option<tokio::runtime::Runtime>> = OnceLock::new();
482
RUNTIME
483
.get_or_init(|| {
484
// Multi-thread so `block_on` is safe from the UI thread and tests.
485
tokio::runtime::Builder::new_multi_thread()
486
.worker_threads(1)
487
.enable_all()
488
.build()
489
.ok()
490
})
491
.as_ref()
492
}
493
480
494
/// Reads the optional `Inhibited` property (Plasma / modern GNOME). Missing → false.
481
495
pub fn notifications_inhibited() -> bool {
482
let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
483
.enable_all()
484
.build()
485
else {
496
let Some(runtime) = inhibit_runtime() else {
486
497
return false;
487
498
};
488
499
runtime.block_on(async {
@@ -1,7 +1,7 @@1
//! Desktop notifications on Linux through `org.freedesktop.Notifications`.1
//! Desktop notifications on Linux through `org.freedesktop.Notifications`.2
2
3
use std::collections::HashMap;3
use std::collections::HashMap;4
use std::sync::Mutex;4
use std::sync::{Mutex, OnceLock};5
use std::sync::atomic::{AtomicBool, Ordering};5
use std::sync::atomic::{AtomicBool, Ordering};6
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};6
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};7
use std::thread;7
use std::thread;@@ -477,12 +477,23 @@ fn parse_closed(477
})477
})478
}478
}479
479
480
fn inhibit_runtime() -> Option<&'static tokio::runtime::Runtime> {481
static RUNTIME: OnceLock<Option<tokio::runtime::Runtime>> = OnceLock::new();482
RUNTIME483
.get_or_init(|| {484
// Multi-thread so `block_on` is safe from the UI thread and tests.485
tokio::runtime::Builder::new_multi_thread()486
.worker_threads(1)487
.enable_all()488
.build()489
.ok()490
})491
.as_ref()492
}493
480
/// Reads the optional `Inhibited` property (Plasma / modern GNOME). Missing → false.494
/// Reads the optional `Inhibited` property (Plasma / modern GNOME). Missing → false.481
pub fn notifications_inhibited() -> bool {495
pub fn notifications_inhibited() -> bool {482
let Ok(runtime) = tokio::runtime::Builder::new_current_thread()496
let Some(runtime) = inhibit_runtime() else {483
.enable_all()484
.build()485
else {486
return false;497
return false;487
};498
};488
runtime.block_on(async {499
runtime.block_on(async {@@ -256,12 +256,18 @@ mod tests {
256
256
assert_eq!(tr("notify.mark_read"), "Mark as read");
257
257
assert_eq!(tr("notify.reply"), "Reply");
258
258
assert_eq!(tr("notify.decline"), "Decline");
259
assert_eq!(tr("notify.accept"), "Accept");
260
assert_eq!(tr("notify.audio"), "Audio");
261
assert_eq!(tr("notify.video"), "Video");
259
262
assert_eq!(tr("notify.join"), "Join");
260
263
assert_eq!(tr("notify.snooze"), "Snooze");
261
264
apply_locale("de");
262
265
assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");
263
266
assert_eq!(tr("notify.reply"), "Antworten");
264
267
assert_eq!(tr("notify.decline"), "Ablehnen");
268
assert_eq!(tr("notify.accept"), "Annehmen");
269
assert_eq!(tr("notify.audio"), "Audio");
270
assert_eq!(tr("notify.video"), "Video");
265
271
assert_eq!(tr("notify.join"), "Teilnehmen");
266
272
assert_eq!(tr("notify.snooze"), "Schlummern");
267
273
}
@@ -256,12 +256,18 @@ mod tests {256
assert_eq!(tr("notify.mark_read"), "Mark as read");256
assert_eq!(tr("notify.mark_read"), "Mark as read");257
assert_eq!(tr("notify.reply"), "Reply");257
assert_eq!(tr("notify.reply"), "Reply");258
assert_eq!(tr("notify.decline"), "Decline");258
assert_eq!(tr("notify.decline"), "Decline");259
assert_eq!(tr("notify.accept"), "Accept");260
assert_eq!(tr("notify.audio"), "Audio");261
assert_eq!(tr("notify.video"), "Video");259
assert_eq!(tr("notify.join"), "Join");262
assert_eq!(tr("notify.join"), "Join");260
assert_eq!(tr("notify.snooze"), "Snooze");263
assert_eq!(tr("notify.snooze"), "Snooze");261
apply_locale("de");264
apply_locale("de");262
assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");265
assert_eq!(tr("notify.mark_read"), "Als gelesen markieren");263
assert_eq!(tr("notify.reply"), "Antworten");266
assert_eq!(tr("notify.reply"), "Antworten");264
assert_eq!(tr("notify.decline"), "Ablehnen");267
assert_eq!(tr("notify.decline"), "Ablehnen");268
assert_eq!(tr("notify.accept"), "Annehmen");269
assert_eq!(tr("notify.audio"), "Audio");270
assert_eq!(tr("notify.video"), "Video");265
assert_eq!(tr("notify.join"), "Teilnehmen");271
assert_eq!(tr("notify.join"), "Teilnehmen");266
assert_eq!(tr("notify.snooze"), "Schlummern");272
assert_eq!(tr("notify.snooze"), "Schlummern");267
}273
}@@ -124,6 +124,9 @@ pub struct NotificationCenter {
124
124
desktop_close: Vec<String>,
125
125
#[cfg(target_os = "linux")]
126
126
desktop_published: HashSet<String>,
127
/// Decoded 64×64 notification avatars, keyed by user id and source fingerprint.
128
#[cfg(target_os = "linux")]
129
desktop_avatar_cache: HashMap<String, (u64, NotificationImage)>,
127
130
app_icon: AppIcon,
128
131
shown_badge: Option<Badge>,
129
132
shown_mention_dot: bool,
@@ -217,6 +220,8 @@ impl NotificationCenter {
217
220
desktop_close: Vec::new(),
218
221
#[cfg(target_os = "linux")]
219
222
desktop_published: HashSet::new(),
223
#[cfg(target_os = "linux")]
224
desktop_avatar_cache: HashMap::new(),
220
225
app_icon,
221
226
shown_badge: None,
222
227
shown_mention_dot: false,
@@ -812,7 +817,7 @@ impl NotificationCenter {
812
817
fn sync_windows(&mut self, cx: &mut Context<Self>) {
813
818
#[cfg(target_os = "linux")]
814
819
{
815
self.poll_desktop(cx);
820
// `tick` polls desktop events once per frame; sync only publishes.
816
821
self.sync_desktop(cx);
817
822
return;
818
823
}
@@ -1174,14 +1179,15 @@ impl NotificationCenter {
1174
1179
let needs_sync = needs_sync
1175
1180
|| !self.desktop_close.is_empty()
1176
1181
|| !self.desktop_published.is_empty();
1177
if needs_sync {
1178
self.sync_windows(cx);
1179
cx.notify();
1180
}
1182
// Poll desktop actions before sync so dismiss/reply land in the same tick.
1181
1183
#[cfg(target_os = "linux")]
1182
1184
if self.desktop.is_some() {
1183
1185
self.poll_desktop(cx);
1184
1186
}
1187
if needs_sync {
1188
self.sync_windows(cx);
1189
cx.notify();
1190
}
1185
1191
self.poll_tray(cx);
1186
1192
if single_instance::take_activation() {
1187
1193
self.raise_main_window(cx);
@@ -1270,63 +1276,110 @@ impl NotificationCenter {
1270
1276
}
1271
1277
1272
1278
#[cfg(target_os = "linux")]
1273
fn avatar_notification_image(state: &AppState, user_id: Option<&str>) -> Option<NotificationImage> {
1279
fn avatar_notification_image(
1280
&mut self,
1281
state: &AppState,
1282
user_id: Option<&str>,
1283
) -> Option<NotificationImage> {
1274
1284
use crate::data::AvatarState;
1275
1285
use image::imageops::FilterType;
1286
use std::collections::hash_map::DefaultHasher;
1287
use std::hash::{Hash, Hasher};
1276
1288
1277
1289
let user_id = user_id?;
1278
1290
let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {
1279
1291
return None;
1280
1292
};
1281
let decoded = image::load_from_memory(photo.source_bytes()).ok()?;
1293
let bytes = photo.source_bytes();
1294
let mut hasher = DefaultHasher::new();
1295
bytes.hash(&mut hasher);
1296
let fingerprint = hasher.finish();
1297
if let Some((cached_fp, image)) = self.desktop_avatar_cache.get(user_id)
1298
&& *cached_fp == fingerprint
1299
{
1300
return Some(image.clone());
1301
}
1302
let decoded = image::load_from_memory(bytes).ok()?;
1282
1303
let rgba = decoded
1283
1304
.resize_exact(64, 64, FilterType::Lanczos3)
1284
1305
.into_rgba8();
1285
Some(NotificationImage {
1306
let image = NotificationImage {
1286
1307
width: rgba.width(),
1287
1308
height: rgba.height(),
1288
1309
rgba: rgba.into_raw(),
1289
})
1310
};
1311
self.desktop_avatar_cache
1312
.insert(user_id.to_owned(), (fingerprint, image.clone()));
1313
Some(image)
1290
1314
}
1291
1315
1292
1316
#[cfg(target_os = "linux")]
1293
1317
fn sync_desktop(&mut self, cx: &mut Context<Self>) {
1294
let Some(desktop) = &self.desktop else {
1318
if self.desktop.is_none() {
1295
1319
return;
1296
};
1320
}
1297
1321
let preview_on = shows_preview(&self.settings);
1298
1322
let message_labels = Self::message_labels();
1299
1323
let ring_labels = Self::ring_labels();
1300
1324
let meeting_labels = Self::meeting_labels();
1301
let state = self.app.read(cx);
1302
1325
let mut visible = Vec::new();
1303
1326
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());
1327
let mut used_avatars = HashSet::new();
1328
let message_toasts: Vec<_> = self.stack.visible().to_vec();
1329
let (ring_payloads, meeting_payloads) = {
1330
let state = self.app.read(cx);
1331
let rings: Vec<_> = state
1332
.rings
1333
.ringing()
1334
.map(|entry| {
1335
(
1336
desktop_payload::ring_payload(
1337
entry.ring.ring_id,
1338
entry.caller_name(),
1339
entry.subtitle(),
1340
entry.ring.video,
1341
&ring_labels,
1342
),
1343
entry.caller_user_id(),
1344
)
1345
})
1346
.collect();
1347
let now = Utc::now();
1348
let offset = Local::now().offset().fix();
1349
let meetings: Vec<_> = state
1350
.meeting_toasts
1351
.entries()
1352
.iter()
1353
.map(|toast| {
1354
let body = crate::call::meeting_subtitle(toast, now, offset);
1355
desktop_payload::meeting_payload(toast, &body, &meeting_labels)
1356
})
1357
.collect();
1358
(rings, meetings)
1359
};
1360
for toast in &message_toasts {
1361
if let Some(user_id) = toast.sender_id.as_deref() {
1362
used_avatars.insert(user_id.to_owned());
1363
}
1364
let image = self.avatar_notification_image(self.app.read(cx), toast.sender_id.as_deref());
1306
1365
let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);
1307
1366
visible_logical.insert(payload.key.replace_token());
1308
1367
visible.push(Self::to_bus(payload, image));
1309
1368
}
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());
1369
for (payload, caller_id) in ring_payloads {
1370
if let Some(user_id) = caller_id.as_deref() {
1371
used_avatars.insert(user_id.to_owned());
1372
}
1373
let image = self.avatar_notification_image(self.app.read(cx), caller_id.as_deref());
1319
1374
visible_logical.insert(payload.key.replace_token());
1320
1375
visible.push(Self::to_bus(payload, image));
1321
1376
}
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);
1377
for payload in meeting_payloads {
1327
1378
visible_logical.insert(payload.key.replace_token());
1328
1379
visible.push(Self::to_bus(payload, None));
1329
1380
}
1381
self.desktop_avatar_cache
1382
.retain(|user_id, _| used_avatars.contains(user_id));
1330
1383
let mut close = std::mem::take(&mut self.desktop_close);
1331
1384
for previous in &self.desktop_published {
1332
1385
if visible_logical.contains(previous) {
@@ -1339,7 +1392,9 @@ impl NotificationCenter {
1339
1392
}
1340
1393
close.sort();
1341
1394
close.dedup();
1342
desktop.sync(visible, close);
1395
if let Some(desktop) = &self.desktop {
1396
desktop.sync(visible, close);
1397
}
1343
1398
self.desktop_published = visible_logical;
1344
1399
}
1345
1400
@@ -124,6 +124,9 @@ pub struct NotificationCenter {124
desktop_close: Vec<String>,124
desktop_close: Vec<String>,125
#[cfg(target_os = "linux")]125
#[cfg(target_os = "linux")]126
desktop_published: HashSet<String>,126
desktop_published: HashSet<String>,127
/// Decoded 64×64 notification avatars, keyed by user id and source fingerprint.128
#[cfg(target_os = "linux")]129
desktop_avatar_cache: HashMap<String, (u64, NotificationImage)>,127
app_icon: AppIcon,130
app_icon: AppIcon,128
shown_badge: Option<Badge>,131
shown_badge: Option<Badge>,129
shown_mention_dot: bool,132
shown_mention_dot: bool,@@ -217,6 +220,8 @@ impl NotificationCenter {217
desktop_close: Vec::new(),220
desktop_close: Vec::new(),218
#[cfg(target_os = "linux")]221
#[cfg(target_os = "linux")]219
desktop_published: HashSet::new(),222
desktop_published: HashSet::new(),223
#[cfg(target_os = "linux")]224
desktop_avatar_cache: HashMap::new(),220
app_icon,225
app_icon,221
shown_badge: None,226
shown_badge: None,222
shown_mention_dot: false,227
shown_mention_dot: false,@@ -812,7 +817,7 @@ impl NotificationCenter {812
fn sync_windows(&mut self, cx: &mut Context<Self>) {817
fn sync_windows(&mut self, cx: &mut Context<Self>) {813
#[cfg(target_os = "linux")]818
#[cfg(target_os = "linux")]814
{819
{815
self.poll_desktop(cx);820
// `tick` polls desktop events once per frame; sync only publishes.816
self.sync_desktop(cx);821
self.sync_desktop(cx);817
return;822
return;818
}823
}@@ -1174,14 +1179,15 @@ impl NotificationCenter {1174
let needs_sync = needs_sync1179
let needs_sync = needs_sync1175
|| !self.desktop_close.is_empty()1180
|| !self.desktop_close.is_empty()1176
|| !self.desktop_published.is_empty();1181
|| !self.desktop_published.is_empty();1177
if needs_sync {1182
// Poll desktop actions before sync so dismiss/reply land in the same tick.1178
self.sync_windows(cx);1179
cx.notify();1180
}1181
#[cfg(target_os = "linux")]1183
#[cfg(target_os = "linux")]1182
if self.desktop.is_some() {1184
if self.desktop.is_some() {1183
self.poll_desktop(cx);1185
self.poll_desktop(cx);1184
}1186
}1187
if needs_sync {1188
self.sync_windows(cx);1189
cx.notify();1190
}1185
self.poll_tray(cx);1191
self.poll_tray(cx);1186
if single_instance::take_activation() {1192
if single_instance::take_activation() {1187
self.raise_main_window(cx);1193
self.raise_main_window(cx);@@ -1270,63 +1276,110 @@ impl NotificationCenter {1270
}1276
}1271
1277
1272
#[cfg(target_os = "linux")]1278
#[cfg(target_os = "linux")]1273
fn avatar_notification_image(state: &AppState, user_id: Option<&str>) -> Option<NotificationImage> {1279
fn avatar_notification_image(1280
&mut self,1281
state: &AppState,1282
user_id: Option<&str>,1283
) -> Option<NotificationImage> {1274
use crate::data::AvatarState;1284
use crate::data::AvatarState;1275
use image::imageops::FilterType;1285
use image::imageops::FilterType;1286
use std::collections::hash_map::DefaultHasher;1287
use std::hash::{Hash, Hasher};1276
1288
1277
let user_id = user_id?;1289
let user_id = user_id?;1278
let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {1290
let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {1279
return None;1291
return None;1280
};1292
};1281
let decoded = image::load_from_memory(photo.source_bytes()).ok()?;1293
let bytes = photo.source_bytes();1294
let mut hasher = DefaultHasher::new();1295
bytes.hash(&mut hasher);1296
let fingerprint = hasher.finish();1297
if let Some((cached_fp, image)) = self.desktop_avatar_cache.get(user_id)1298
&& *cached_fp == fingerprint1299
{1300
return Some(image.clone());1301
}1302
let decoded = image::load_from_memory(bytes).ok()?;1282
let rgba = decoded1303
let rgba = decoded1283
.resize_exact(64, 64, FilterType::Lanczos3)1304
.resize_exact(64, 64, FilterType::Lanczos3)1284
.into_rgba8();1305
.into_rgba8();1285
Some(NotificationImage {1306
let image = NotificationImage {1286
width: rgba.width(),1307
width: rgba.width(),1287
height: rgba.height(),1308
height: rgba.height(),1288
rgba: rgba.into_raw(),1309
rgba: rgba.into_raw(),1289
})1310
};1311
self.desktop_avatar_cache1312
.insert(user_id.to_owned(), (fingerprint, image.clone()));1313
Some(image)1290
}1314
}1291
1315
1292
#[cfg(target_os = "linux")]1316
#[cfg(target_os = "linux")]1293
fn sync_desktop(&mut self, cx: &mut Context<Self>) {1317
fn sync_desktop(&mut self, cx: &mut Context<Self>) {1294
let Some(desktop) = &self.desktop else {1318
if self.desktop.is_none() {1295
return;1319
return;1296
};1320
}1297
let preview_on = shows_preview(&self.settings);1321
let preview_on = shows_preview(&self.settings);1298
let message_labels = Self::message_labels();1322
let message_labels = Self::message_labels();1299
let ring_labels = Self::ring_labels();1323
let ring_labels = Self::ring_labels();1300
let meeting_labels = Self::meeting_labels();1324
let meeting_labels = Self::meeting_labels();1301
let state = self.app.read(cx);1302
let mut visible = Vec::new();1325
let mut visible = Vec::new();1303
let mut visible_logical = HashSet::new();1326
let mut visible_logical = HashSet::new();1304
for toast in self.stack.visible() {1327
let mut used_avatars = HashSet::new();1305
let image = Self::avatar_notification_image(state, toast.sender_id.as_deref());1328
let message_toasts: Vec<_> = self.stack.visible().to_vec();1329
let (ring_payloads, meeting_payloads) = {1330
let state = self.app.read(cx);1331
let rings: Vec<_> = state1332
.rings1333
.ringing()1334
.map(|entry| {1335
(1336
desktop_payload::ring_payload(1337
entry.ring.ring_id,1338
entry.caller_name(),1339
entry.subtitle(),1340
entry.ring.video,1341
&ring_labels,1342
),1343
entry.caller_user_id(),1344
)1345
})1346
.collect();1347
let now = Utc::now();1348
let offset = Local::now().offset().fix();1349
let meetings: Vec<_> = state1350
.meeting_toasts1351
.entries()1352
.iter()1353
.map(|toast| {1354
let body = crate::call::meeting_subtitle(toast, now, offset);1355
desktop_payload::meeting_payload(toast, &body, &meeting_labels)1356
})1357
.collect();1358
(rings, meetings)1359
};1360
for toast in &message_toasts {1361
if let Some(user_id) = toast.sender_id.as_deref() {1362
used_avatars.insert(user_id.to_owned());1363
}1364
let image = self.avatar_notification_image(self.app.read(cx), toast.sender_id.as_deref());1306
let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);1365
let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);1307
visible_logical.insert(payload.key.replace_token());1366
visible_logical.insert(payload.key.replace_token());1308
visible.push(Self::to_bus(payload, image));1367
visible.push(Self::to_bus(payload, image));1309
}1368
}1310
for entry in state.rings.ringing() {1369
for (payload, caller_id) in ring_payloads {1311
let payload = desktop_payload::ring_payload(1370
if let Some(user_id) = caller_id.as_deref() {1312
entry.ring.ring_id,1371
used_avatars.insert(user_id.to_owned());1313
entry.caller_name(),1372
}1314
entry.subtitle(),1373
let image = self.avatar_notification_image(self.app.read(cx), caller_id.as_deref());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());1374
visible_logical.insert(payload.key.replace_token());1320
visible.push(Self::to_bus(payload, image));1375
visible.push(Self::to_bus(payload, image));1321
}1376
}1322
let now = Utc::now();1377
for payload in meeting_payloads {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());1378
visible_logical.insert(payload.key.replace_token());1328
visible.push(Self::to_bus(payload, None));1379
visible.push(Self::to_bus(payload, None));1329
}1380
}1381
self.desktop_avatar_cache1382
.retain(|user_id, _| used_avatars.contains(user_id));1330
let mut close = std::mem::take(&mut self.desktop_close);1383
let mut close = std::mem::take(&mut self.desktop_close);1331
for previous in &self.desktop_published {1384
for previous in &self.desktop_published {1332
if visible_logical.contains(previous) {1385
if visible_logical.contains(previous) {@@ -1339,7 +1392,9 @@ impl NotificationCenter {1339
}1392
}1340
close.sort();1393
close.sort();1341
close.dedup();1394
close.dedup();1342
desktop.sync(visible, close);1395
if let Some(desktop) = &self.desktop {1396
desktop.sync(visible, close);1397
}1343
self.desktop_published = visible_logical;1398
self.desktop_published = visible_logical;1344
}1399
}1345
1400