Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Linux alerts: one connection and one listener, however many alerts

Yashwanth Kamireddi157bc99589a3
diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rs
index beb91f8..fc1beb6 100644
--- a/src-tauri/src/alerts.rs
+++ b/src-tauri/src/alerts.rs
@@ -105,18 +105,23 @@ pub fn tell(app: &AppHandle, title: &str, body: &str) {
.icon(icon_path(&app).unwrap_or("quince"));
#[cfg(all(unix, not(target_os = "macos")))]
{
- notice
- .hint(notify_rust::Hint::DesktopEntry(
- app.config().identifier.clone(),
- ))
- .action("default", "Open");
- if let Ok(handle) = notice.show() {
- handle.wait_for_action(|action| {
- if action == "default" {
- crate::show_window(&app);
- }
- });
- }
+ let _ = notice;
+ let notice = crate::notices::Notice {
+ summary: &title,
+ body: &body,
+ icon: icon_path(&app).unwrap_or("quince"),
+ actions: &[("default", "Open")],
+ category: None,
+ desktop_entry: Some(app.config().identifier.clone()),
+ sound: None,
+ resident: false,
+ };
+ let app = app.clone();
+ crate::notices::show(&notice, move |action| {
+ if action == "default" {
+ crate::show_window(&app);
+ }
+ });
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
notice.show().ok();
@@ -129,15 +134,14 @@ pub fn tell(app: &AppHandle, title: &str, body: &str) {
/// and it is played here through libcanberra, which keeps to the sound theme and to the
/// desktop's "event sounds" switch. Without this every alert on such a desktop was silent.
#[cfg(all(unix, not(target_os = "macos")))]
-fn chime(alert: &mut notify_rust::Notification) {
+fn chime() -> Option<&'static str> {
const SOUND: &str = "alarm-clock-elapsed";
static SERVER_PLAYS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let server_plays = *SERVER_PLAYS.get_or_init(|| {
notify_rust::get_capabilities().is_ok_and(|c| c.iter().any(|x| x == "sound"))
});
if server_plays {
- alert.hint(notify_rust::Hint::SoundName(SOUND.into()));
- return;
+ return Some(SOUND);
}
// The alert never stands behind its sound, and the sound is waited for on a thread of its own:
// left unwaited, every alert left a finished player behind as a zombie process.
@@ -152,6 +156,7 @@ fn chime(alert: &mut notify_rust::Notification) {
let _ = player.wait();
});
}
+ None
}
fn icon_path(app: &AppHandle) -> Option<&'static str> {
@@ -331,32 +336,37 @@ fn show(app: AppHandle, due: DueAlarm) {
}
#[cfg(all(unix, not(target_os = "macos")))]
{
- let mut alert = notify_rust::Notification::new();
- chime(&mut alert);
- let shown = alert
- .appname("Skykeep")
- .summary(&due.title)
- .body(&body)
- .icon(icon_path(&app).unwrap_or("quince"))
- .hint(notify_rust::Hint::Category("reminder".into()))
- .hint(notify_rust::Hint::DesktopEntry(format!(
- "{}.Reminders",
- app.config().identifier
- )))
- .hint(notify_rust::Hint::Resident(true))
- .action("default", "Open")
- .action("complete", "Mark as Completed")
- .action("snooze", "Remind Me in 1 Hour")
- .timeout(notify_rust::Timeout::Never)
- .show();
- let Ok(handle) = shown else {
- return;
+ let notice = crate::notices::Notice {
+ summary: &due.title,
+ body: &body,
+ icon: icon_path(&app).unwrap_or("quince"),
+ actions: &[
+ ("default", "Open"),
+ ("complete", "Mark as Completed"),
+ ("snooze", "Remind Me in 1 Hour"),
+ ],
+ category: Some("reminder"),
+ desktop_entry: Some(format!("{}.Reminders", app.config().identifier)),
+ sound: chime(),
+ resident: true,
};
- handle.wait_for_action(|action| answer(&app, &due, due_then, action));
+ let (answering, due_answered) = (app.clone(), due.clone());
+ crate::notices::show(&notice, move |action| {
+ answer(&answering, &due_answered, due_then, action);
+ });
}
});
}
+/// Alerts read for events no longer coming let go of.
+fn forget_gone<T>(
+ known: &mut std::collections::HashMap<String, T>,
+ coming: &[quince_core::calendar::Event],
+) {
+ let still: std::collections::HashSet<&str> = coming.iter().map(|e| e.guid.as_str()).collect();
+ known.retain(|guid, _| still.contains(guid.as_str()));
+}
+
/// Calendar alerts on the desktop, rung as the phone rings them.
///
/// Apple keeps an event's alerts beside it, read one event at a time, so this looks only at
@@ -384,6 +394,9 @@ pub fn spawn_events(app: AppHandle) {
.filter_map(|(guid, _)| library.event(&guid).ok().flatten())
.collect()
};
+ // What is no longer coming is forgotten: kept, the map grew by every event that
+ // ever came near, for as long as the app ran.
+ forget_gone(&mut known, &coming);
// Ask for the alerts of any event not yet read, or changed since.
let stale: Vec<_> = coming
.iter()
@@ -490,27 +503,22 @@ fn show_event(app: AppHandle, event: quince_core::calendar::Event, minutes: i64)
}
#[cfg(all(unix, not(target_os = "macos")))]
{
- let mut alert = notify_rust::Notification::new();
- chime(&mut alert);
- let shown = alert
- .appname("Skykeep")
- .summary(&event.title)
- .body(&body)
- .icon(icon_path(&app).unwrap_or("quince"))
- .hint(notify_rust::Hint::Category("calendar".into()))
- .hint(notify_rust::Hint::DesktopEntry(format!(
- "{}.Calendar",
- app.config().identifier
- )))
- .action("default", "Open")
- .show();
- if let Ok(handle) = shown {
- handle.wait_for_action(|action| {
- if action == "default" {
- crate::show_window(&app);
- }
- });
- }
+ let notice = crate::notices::Notice {
+ summary: &event.title,
+ body: &body,
+ icon: icon_path(&app).unwrap_or("quince"),
+ actions: &[("default", "Open")],
+ category: Some("calendar"),
+ desktop_entry: Some(format!("{}.Calendar", app.config().identifier)),
+ sound: chime(),
+ resident: false,
+ };
+ let app = app.clone();
+ crate::notices::show(&notice, move |action| {
+ if action == "default" {
+ crate::show_window(&app);
+ }
+ });
}
});
}
@@ -518,6 +526,18 @@ fn show_event(app: AppHandle, event: quince_core::calendar::Event, minutes: i64)
#[cfg(test)]
mod tests {
+ #[test]
+ fn alerts_of_events_no_longer_coming_are_let_go_of() {
+ let mut known: std::collections::HashMap<String, ()> =
+ [("past".to_string(), ()), ("soon".to_string(), ())].into();
+ let soon = quince_core::calendar::Event {
+ guid: "soon".into(),
+ ..Default::default()
+ };
+ super::forget_gone(&mut known, &[soon]);
+ assert_eq!(known.keys().collect::<Vec<_>>(), ["soon"]);
+ }
+
#[test]
fn an_alert_rings_unless_settings_turned_it_off() {
let mut library = quince_core::Library::in_memory().unwrap();
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 5172cf5..b082cdf 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -27,6 +27,8 @@ mod migrate;
mod mount;
mod mount_photos;
mod notes_cmds;
+#[cfg(target_os = "linux")]
+mod notices;
mod outbox;
mod photo_cache;
mod photos;
diff --git a/src-tauri/src/notices.rs b/src-tauri/src/notices.rs
new file mode 100644
index 0000000..0f5359b
--- /dev/null
+++ b/src-tauri/src/notices.rs
@@ -0,0 +1,201 @@
+//! Desktop notifications on Linux, sent and answered over one session-bus connection.
+//!
+//! Each alert used to be shown through notify-rust on a thread of its own, blocked in
+//! `wait_for_action` — with a connection of its own — until the notification closed. A reminder
+//! alert stays (resident, no timeout) and GNOME and KDE keep it in their list indefinitely; a
+//! notification server that restarts never says it closed. A tray app left running for weeks
+//! with daily reminders gathered a thread and a D-Bus connection for every alert it had ever
+//! shown. Now there is one connection, one thread listening on it, and the answer to each
+//! notification is looked up by its id. The answers are listened for on the connection that
+//! sent the notifications: a server may say which button was pressed to the sender alone.
+
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock};
+use std::time::{Duration, Instant};
+use zbus::zvariant::Value;
+
+const SERVICE: &str = "org.freedesktop.Notifications";
+const PATH: &str = "/org/freedesktop/Notifications";
+
+/// What a press on a notification does, given the action's key.
+type Answer = Box<dyn FnOnce(&str) + Send>;
+
+/// One notification to show.
+pub struct Notice<'a> {
+ pub summary: &'a str,
+ pub body: &'a str,
+ pub icon: &'a str,
+ /// (key, label) pairs; "default" is a click on the notification itself.
+ pub actions: &'a [(&'a str, &'a str)],
+ pub category: Option<&'a str>,
+ pub desktop_entry: Option<String>,
+ pub sound: Option<&'a str>,
+ /// Kept in the server's list after a press, and never timed out (a reminder).
+ pub resident: bool,
+}
+
+/// How long an answer is waited for: a notification still unanswered after this was dismissed
+/// unseen, or lost with a server that restarted.
+const KEPT: Duration = Duration::from_secs(7 * 24 * 3600);
+
+/// The answers waiting, by notification id.
+#[derive(Default)]
+struct Waiting(HashMap<u32, (Instant, Answer)>);
+
+impl Waiting {
+ fn add(&mut self, id: u32, now: Instant, answer: Answer) {
+ self.0.retain(|_, (at, _)| now.duration_since(*at) < KEPT);
+ self.0.insert(id, (now, answer));
+ }
+ /// The answer for `id`, once: a second press finds nothing.
+ fn take(&mut self, id: u32) -> Option<Answer> {
+ self.0.remove(&id).map(|(_, answer)| answer)
+ }
+}
+
+fn waiting() -> &'static Mutex<Waiting> {
+ static WAITING: OnceLock<Mutex<Waiting>> = OnceLock::new();
+ WAITING.get_or_init(Mutex::default)
+}
+
+/// The one connection, and its listener started the first time it is asked for.
+fn bus() -> Option<&'static zbus::blocking::Connection> {
+ static BUS: OnceLock<Option<zbus::blocking::Connection>> = OnceLock::new();
+ BUS.get_or_init(|| {
+ let conn = zbus::blocking::Connection::session().ok()?;
+ let listening = conn.clone();
+ std::thread::Builder::new()
+ .name("notices".into())
+ .spawn(move || listen(&listening))
+ .ok()?;
+ Some(conn)
+ })
+ .as_ref()
+}
+
+fn listen(conn: &zbus::blocking::Connection) {
+ let rule = || -> zbus::Result<zbus::MatchRule<'static>> {
+ Ok(zbus::MatchRule::builder()
+ .msg_type(zbus::message::Type::Signal)
+ .interface(SERVICE)?
+ .path(PATH)?
+ .build())
+ };
+ let Ok(rule) = rule() else {
+ return;
+ };
+ let Ok(messages) = zbus::blocking::MessageIterator::for_match_rule(rule, conn, Some(64)) else {
+ return;
+ };
+ for message in messages.flatten() {
+ let header = message.header();
+ match header.member().map(zbus::names::MemberName::as_str) {
+ Some("ActionInvoked") => {
+ if let Ok((id, key)) = message.body().deserialize::<(u32, String)>() {
+ let answer = waiting()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take(id);
+ // On a thread of its own while it works (a tick waits on the library): the
+ // next signal is not held up behind it.
+ if let Some(answer) = answer {
+ std::thread::spawn(move || answer(&key));
+ }
+ }
+ }
+ Some("NotificationClosed") => {
+ if let Ok((id, _reason)) = message.body().deserialize::<(u32, u32)>() {
+ let _ = waiting()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take(id);
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+/// Show `notice`; `answer` is called with the action's key when one is pressed.
+pub fn show(notice: &Notice<'_>, answer: impl FnOnce(&str) + Send + 'static) {
+ let Some(conn) = bus() else {
+ return;
+ };
+ let actions: Vec<&str> = notice
+ .actions
+ .iter()
+ .flat_map(|(key, label)| [*key, *label])
+ .collect();
+ let mut hints: HashMap<&str, Value<'_>> = HashMap::new();
+ if let Some(category) = notice.category {
+ hints.insert("category", Value::from(category));
+ }
+ if let Some(entry) = &notice.desktop_entry {
+ hints.insert("desktop-entry", Value::from(entry.as_str()));
+ }
+ if let Some(sound) = notice.sound {
+ hints.insert("sound-name", Value::from(sound));
+ }
+ if notice.resident {
+ hints.insert("resident", Value::from(true));
+ }
+ // 0: never times out. -1: the server's own choice.
+ let timeout: i32 = if notice.resident { 0 } else { -1 };
+ // Registered before the reply is read, under the lock the listener takes: a press can
+ // never arrive for an id not yet known.
+ let mut held = waiting()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let reply = conn.call_method(
+ Some(SERVICE),
+ PATH,
+ Some(SERVICE),
+ "Notify",
+ &(
+ "Skykeep",
+ 0u32,
+ notice.icon,
+ notice.summary,
+ notice.body,
+ actions,
+ hints,
+ timeout,
+ ),
+ );
+ if let Ok(id) = reply.and_then(|r| r.body().deserialize::<u32>()) {
+ held.add(id, Instant::now(), Box::new(answer));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ /// Each answer reaches its own notification once; one never answered is let go of after a
+ /// week, so nothing gathers however long Skykeep runs.
+ #[test]
+ fn answers_go_to_their_own_notification_once_and_none_gather() {
+ let mut w = Waiting::default();
+ let pressed = Arc::new(AtomicUsize::new(0));
+ let start = Instant::now();
+ for id in 1..=3 {
+ let pressed = Arc::clone(&pressed);
+ w.add(
+ id,
+ start,
+ Box::new(move |key| {
+ assert_eq!(key, "complete");
+ pressed.fetch_add(id as usize, Ordering::SeqCst);
+ }),
+ );
+ }
+ w.take(2).unwrap()("complete");
+ assert_eq!(pressed.load(Ordering::SeqCst), 2);
+ assert!(w.take(2).is_none(), "a second press finds nothing");
+ // A week on, a new alert finds the old unanswered ones gone.
+ w.add(9, start + KEPT, Box::new(|_| {}));
+ assert_eq!(w.0.len(), 1);
+ }
+}