use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use zbus::blocking::Connection;
use zbus::zvariant::Value;
use crate::{
AlarmSchedule, AlarmState, CalendarAlarm, Notification, Notifier, NotifyError, PriorityContact,
Scheduled, SystemTime,
};
type AlarmStateWire = (String, (u8, u8, u8, i64), Vec<i64>, Vec<i64>, String);
const CALL_BUDGET: Duration = Duration::from_secs(3);
const NOT_TILO: &str = "Only an app Tilo launched may name priority contacts.";
const PORTAL: (&str, &str, &str) = (
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
"org.freedesktop.portal.Notification",
);
const FREEDESKTOP: (&str, &str, &str) = (
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
);
type Job = Box<dyn FnOnce(Option<&Connection>) + Send>;
fn bus() -> Option<&'static Mutex<mpsc::Sender<Job>>> {
static BUS: OnceLock<Option<Mutex<mpsc::Sender<Job>>>> = OnceLock::new();
BUS.get_or_init(|| {
let (tx, rx) = mpsc::channel::<Job>();
tilo_rt::spawn_thread("tilo-notify-bus", move || {
let connection = Connection::session()
.inspect_err(|error| tracing::debug!(%error, "no session bus for notifications"))
.ok();
while let Ok(job) = rx.recv() {
job(connection.as_ref());
}
})
.ok()?;
Some(Mutex::new(tx))
})
.as_ref()
}
fn on_bus<T: Send + 'static>(
call: impl FnOnce(&Connection) -> Result<T, NotifyError> + Send + 'static,
) -> Result<T, NotifyError> {
let (reply, answer) = mpsc::channel();
let job: Job = Box::new(move |connection| {
let _ = reply.send(connection.map_or(Err(NotifyError::Unavailable), call));
});
bus()
.and_then(|bus| bus.lock().ok()?.send(job).ok())
.ok_or(NotifyError::Unavailable)?;
answer.recv_timeout(CALL_BUDGET).unwrap_or_else(|_| {
Err(NotifyError::Failed(
"the notification service did not answer".into(),
))
})
}
fn missing(error: &zbus::Error) -> bool {
let zbus::Error::MethodError(name, _, _) = error else {
return false;
};
matches!(
name.as_str(),
"org.freedesktop.DBus.Error.ServiceUnknown"
| "org.freedesktop.DBus.Error.UnknownInterface"
| "org.freedesktop.DBus.Error.UnknownMethod"
| "org.freedesktop.DBus.Error.UnknownObject"
| "org.freedesktop.DBus.Error.NameHasNoOwner"
)
}
#[allow(
clippy::needless_pass_by_value,
reason = "`map_err` hands it the error by value"
)]
fn failed(error: zbus::Error) -> NotifyError {
NotifyError::Failed(error.to_string())
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Service {
Portal,
Freedesktop,
}
pub(crate) struct SessionNotifier {
app_id: String,
}
fn ids() -> &'static Mutex<HashMap<String, u32>> {
static IDS: OnceLock<Mutex<HashMap<String, u32>>> = OnceLock::new();
IDS.get_or_init(Mutex::default)
}
fn chosen() -> &'static Mutex<Option<Service>> {
static CHOSEN: OnceLock<Mutex<Option<Service>>> = OnceLock::new();
CHOSEN.get_or_init(Mutex::default)
}
impl SessionNotifier {
pub(crate) fn new(app_id: &str) -> Self {
Self {
app_id: app_id.to_owned(),
}
}
}
const PORTAL_ACTION: &str = "tilo-activate";
const DEFAULT_ACTION: &str = "default";
const BUTTON_ACTION: &str = "tilo-button-";
fn button_action(index: usize) -> String {
format!("{BUTTON_ACTION}{index}")
}
type Activations = Vec<(String, String)>;
fn activation_ids() -> &'static Mutex<HashMap<u32, Activations>> {
static IDS: OnceLock<Mutex<HashMap<u32, Activations>>> = OnceLock::new();
IDS.get_or_init(Mutex::default)
}
fn activations_of(n: &Notification) -> Activations {
n.activation
.iter()
.map(|uri| (DEFAULT_ACTION.to_owned(), uri.clone()))
.chain(
n.buttons
.iter()
.enumerate()
.map(|(index, button)| (button_action(index), button.activation.clone())),
)
.collect()
}
fn take_shown(id: u32) -> Option<String> {
let tag = ids()
.lock()
.ok()?
.iter()
.find(|(_, shown)| **shown == id)
.map(|(tag, _)| tag.clone())?;
if let Ok(mut ids) = ids().lock() {
ids.remove(&tag);
}
if let Ok(mut known) = activation_ids().lock() {
known.remove(&id);
}
Some(tag)
}
fn freedesktop_closed(id: u32, code: u32) {
let Some(tag) = take_shown(id) else {
return;
};
let Some(reason) = crate::CloseReason::from_code(code) else {
tracing::debug!(%code, %tag, "a notification closed for an unknown reason");
return;
};
crate::closed(&tag, reason);
}
fn listen_for_reports(connection: &Connection) {
static LISTENING: std::sync::Once = std::sync::Once::new();
LISTENING.call_once(|| {
let portal = connection.clone();
let spawned = tilo_rt::spawn_thread("tilo-notify-portal-clicks", move || {
let (dest, path, iface) = PORTAL;
let Ok(proxy) = zbus::blocking::Proxy::new(&portal, dest, path, iface) else {
return;
};
let Ok(signals) = proxy.receive_signal("ActionInvoked") else {
return;
};
for signal in signals {
let Ok((_app, _id, action, parameter)) =
signal
.body()
.deserialize::<(String, String, String, Vec<zbus::zvariant::OwnedValue>)>()
else {
continue;
};
let uri = parameter
.first()
.and_then(|value| String::try_from(value.try_clone().ok()?).ok());
if (action == PORTAL_ACTION || action.starts_with(BUTTON_ACTION))
&& let Some(uri) = uri
{
crate::activated(&uri);
}
}
});
let freedesktop = connection.clone();
let spawned = spawned.and_then(|_| {
tilo_rt::spawn_thread("tilo-notify-clicks", move || {
let (dest, path, iface) = FREEDESKTOP;
let Ok(proxy) = zbus::blocking::Proxy::new(&freedesktop, dest, path, iface) else {
return;
};
let Ok(signals) = proxy.receive_signal("ActionInvoked") else {
return;
};
for signal in signals {
let Ok((id, action)) = signal.body().deserialize::<(u32, String)>() else {
continue;
};
let uri = activation_ids().lock().ok().and_then(|ids| {
ids.get(&id)?
.iter()
.find(|(invoked, _)| *invoked == action)
.map(|(_, uri)| uri.clone())
});
if let Some(uri) = uri {
crate::activated(&uri);
}
}
})
});
let closing = connection.clone();
let spawned = spawned.and_then(|_| {
tilo_rt::spawn_thread("tilo-notify-closes", move || {
let (dest, path, iface) = FREEDESKTOP;
let Ok(proxy) = zbus::blocking::Proxy::new(&closing, dest, path, iface) else {
return;
};
let Ok(signals) = proxy.receive_signal("NotificationClosed") else {
return;
};
for signal in signals {
let Ok((id, code)) = signal.body().deserialize::<(u32, u32)>() else {
continue;
};
freedesktop_closed(id, code);
}
})
});
if let Err(error) = spawned {
tracing::debug!(%error, "cannot listen for what became of notifications");
}
});
}
fn portal_content(n: &Notification) -> HashMap<&'static str, Value<'_>> {
let mut content: HashMap<&'static str, Value<'_>> = HashMap::new();
content.insert("title", Value::from(n.title.as_str()));
content.insert("body", Value::from(n.body.as_str()));
if let Some(uri) = &n.activation {
content.insert("default-action", Value::from(PORTAL_ACTION));
content.insert("default-action-target", Value::from(uri.as_str()));
}
if !n.buttons.is_empty() {
let buttons: Vec<HashMap<&str, Value<'_>>> = n
.buttons
.iter()
.enumerate()
.map(|(index, button)| {
HashMap::from([
("label", Value::from(button.label.as_str())),
("action", Value::from(button_action(index))),
("target", Value::from(button.activation.as_str())),
])
})
.collect();
content.insert("buttons", Value::from(buttons));
}
if n.silent {
content.insert("sound", Value::from("silent"));
}
content
}
fn portal_add(connection: &Connection, n: &Notification) -> zbus::Result<()> {
let content = portal_content(n);
let (dest, path, iface) = PORTAL;
connection
.call_method(
Some(dest),
path,
Some(iface),
"AddNotification",
&(n.tag.as_str(), content),
)
.map(drop)
}
fn portal_remove(connection: &Connection, tag: &str) -> zbus::Result<()> {
let (dest, path, iface) = PORTAL;
connection
.call_method(Some(dest), path, Some(iface), "RemoveNotification", &(tag,))
.map(drop)
}
fn freedesktop_hints(n: &Notification) -> HashMap<&'static str, Value<'static>> {
let mut hints = HashMap::new();
if n.severity == crate::Severity::Error {
hints.insert("urgency", Value::U8(2));
}
if n.silent {
hints.insert("suppress-sound", Value::Bool(true));
}
hints
}
fn freedesktop_notify(connection: &Connection, app: &str, n: &Notification) -> zbus::Result<()> {
let replaces = ids()
.lock()
.ok()
.and_then(|ids| ids.get(&n.tag).copied())
.unwrap_or(0);
let hints = freedesktop_hints(n);
let activations = activations_of(n);
let mut actions: Vec<&str> = Vec::new();
if n.activation.is_some() {
actions.extend([DEFAULT_ACTION, n.action.as_deref().unwrap_or("Open")]);
}
for ((action, _), button) in activations
.iter()
.skip(usize::from(n.activation.is_some()))
.zip(&n.buttons)
{
actions.extend([action.as_str(), button.label.as_str()]);
}
let (dest, path, iface) = FREEDESKTOP;
let reply = connection.call_method(
Some(dest),
path,
Some(iface),
"Notify",
&(
app,
replaces,
"",
n.title.as_str(),
n.body.as_str(),
actions,
hints,
-1_i32,
),
)?;
let id: u32 = reply.body().deserialize()?;
if let Ok(mut ids) = ids().lock() {
ids.insert(n.tag.clone(), id);
}
if let Ok(mut known) = activation_ids().lock() {
if activations.is_empty() {
known.remove(&id);
} else {
known.insert(id, activations);
}
}
Ok(())
}
fn freedesktop_close(connection: &Connection, tag: &str) -> zbus::Result<()> {
let Some(id) = ids().lock().ok().and_then(|mut ids| ids.remove(tag)) else {
return Ok(());
};
let (dest, path, iface) = FREEDESKTOP;
connection
.call_method(Some(dest), path, Some(iface), "CloseNotification", &(id,))
.map(drop)
}
fn either(
connection: &Connection,
portal: impl FnOnce(&Connection) -> zbus::Result<()>,
freedesktop: impl FnOnce(&Connection) -> zbus::Result<()>,
) -> Result<(), NotifyError> {
let known = chosen().lock().ok().and_then(|chosen| *chosen);
if known != Some(Service::Freedesktop) {
match portal(connection) {
Ok(()) => {
remember(Service::Portal);
return Ok(());
}
Err(error) if known.is_none() && missing(&error) => {}
Err(error) => return Err(failed(error)),
}
}
match freedesktop(connection) {
Ok(()) => {
remember(Service::Freedesktop);
Ok(())
}
Err(error) if missing(&error) => Err(NotifyError::Unavailable),
Err(error) => Err(failed(error)),
}
}
fn remember(service: Service) {
if let Ok(mut chosen) = chosen().lock() {
*chosen = Some(service);
}
}
fn schedule_notification(
notification: &Notification,
at: SystemTime,
calendar: Vec<(u8, u8, u8, i64, String)>,
) -> Result<(), NotifyError> {
crate::validate(notification)?;
let millis = at
.duration_since(SystemTime::UNIX_EPOCH)
.ok()
.and_then(|d| i64::try_from(d.as_millis()).ok())
.ok_or(NotifyError::Invalid("invalid notification deadline"))?;
let args = (
notification.tag.clone(),
notification.title.clone(),
notification.body.clone(),
notification.activation.clone().unwrap_or_default(),
millis,
calendar,
);
on_bus(move |connection| {
let (dest, path, iface) = FREEDESKTOP;
connection
.call_method(
Some(dest),
path,
Some(iface),
"XTiloScheduleNotification",
&args,
)
.map(drop)
.map_err(schedule_error)
})
}
fn decode_deadline(values: &[i64]) -> Result<Option<SystemTime>, NotifyError> {
match values {
[] => Ok(None),
[millis] => {
let millis = u64::try_from(*millis)
.map_err(|_| NotifyError::Invalid("invalid alarm deadline"))?;
SystemTime::UNIX_EPOCH
.checked_add(Duration::from_millis(millis))
.map(Some)
.ok_or(NotifyError::Invalid("invalid alarm deadline"))
}
_ => Err(NotifyError::Invalid("expected at most one alarm deadline")),
}
}
fn schedule_error(error: zbus::Error) -> NotifyError {
if missing(&error) {
NotifyError::Unsupported(crate::Unsupported {
feature: crate::Feature::Schedule,
reason: "This desktop does not provide Tilo's durable notification scheduler.",
})
} else {
failed(error)
}
}
impl Notifier for SessionNotifier {
fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
schedule_notification(notification, at, Vec::new())
}
fn schedule_alarm(
&self,
notification: &Notification,
at: SystemTime,
schedule: AlarmSchedule,
) -> Result<(), NotifyError> {
let alarm = schedule.alarm;
if !alarm.valid() {
return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
}
schedule_notification(
notification,
at,
vec![(
alarm.hour,
alarm.minute,
alarm.weekdays,
schedule.enabled_at_ms,
schedule
.last_rung
.map(|date| date.to_string())
.unwrap_or_default(),
)],
)
}
fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
on_bus(|connection| {
let (dest, path, iface) = FREEDESKTOP;
let response = connection
.call_method(
Some(dest),
path,
Some(iface),
"XTiloScheduledNotifications",
&(),
)
.map_err(schedule_error)?;
let rows: Vec<(String, i64)> = response.body().deserialize().map_err(failed)?;
rows.into_iter()
.map(|(tag, at)| {
let millis = u64::try_from(at)
.map_err(|_| NotifyError::Invalid("invalid stored deadline"))?;
let at = SystemTime::UNIX_EPOCH
.checked_add(Duration::from_millis(millis))
.ok_or(NotifyError::Invalid("invalid stored deadline"))?;
Ok(Scheduled { tag, at })
})
.collect()
})
}
fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
on_bus(|connection| {
let (dest, path, iface) = FREEDESKTOP;
let response = connection
.call_method(Some(dest), path, Some(iface), "XTiloScheduledAlarms", &())
.map_err(schedule_error)?;
let rows: Vec<AlarmStateWire> = response.body().deserialize().map_err(failed)?;
rows.into_iter()
.map(
|(tag, (hour, minute, weekdays, enabled_at_ms), next, last, date)| {
let last_rung = if date.is_empty() {
None
} else {
Some(jiff::civil::Date::strptime("%Y-%m-%d", &date).map_err(|_| {
NotifyError::Invalid("invalid delivered alarm date")
})?)
};
Ok(AlarmState {
tag,
alarm: CalendarAlarm {
hour,
minute,
weekdays,
},
enabled_at_ms,
next_at: decode_deadline(&next)?,
last_at: decode_deadline(&last)?,
last_rung,
})
},
)
.collect()
})
}
fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
crate::validate_tag(tag)?;
let tag = tag.to_owned();
on_bus(move |connection| {
let (dest, path, iface) = FREEDESKTOP;
connection
.call_method(
Some(dest),
path,
Some(iface),
"XTiloCancelScheduledNotification",
&(tag,),
)
.map(drop)
.map_err(schedule_error)
})
}
fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
crate::validate(notification)?;
let notification = notification.clone();
let app = self.app_id.clone();
on_bus(move |connection| {
listen_for_reports(connection);
either(
connection,
|c| portal_add(c, ¬ification),
|c| freedesktop_notify(c, &app, ¬ification),
)
})
}
fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
crate::validate_tag(tag)?;
let tag = tag.to_owned();
on_bus(move |connection| {
either(
connection,
|c| portal_remove(c, &tag),
|c| freedesktop_close(c, &tag),
)
})
}
}
pub(crate) fn publish_priority_contacts(
app_id: &str,
contacts: &[PriorityContact],
) -> Result<(), NotifyError> {
if std::env::var("TILO_PACKAGE_ID").as_deref() != Ok(app_id) {
return Err(NotifyError::Unsupported(crate::Unsupported {
feature: crate::Feature::PriorityContacts,
reason: NOT_TILO,
}));
}
let wire: Vec<(String, String, Vec<String>)> = contacts
.iter()
.map(|c| (c.id.clone(), c.name.clone(), c.endpoints.clone()))
.collect();
on_bus(move |connection| {
let (dest, path, iface) = FREEDESKTOP;
connection
.call_method(
Some(dest),
path,
Some(iface),
"XTiloReplacePriorityContacts",
&(wire,),
)
.map(drop)
.map_err(|error| {
if missing(&error) {
NotifyError::Unavailable
} else {
failed(error)
}
})
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn a_quiet_notification_asks_both_services_for_no_sound() {
let loud = Notification::new("t", "Title", "");
assert!(!portal_content(&loud).contains_key("sound"));
assert!(!freedesktop_hints(&loud).contains_key("suppress-sound"));
let quiet = loud.quietly();
assert_eq!(
portal_content(&quiet).get("sound"),
Some(&Value::from("silent"))
);
assert_eq!(
freedesktop_hints(&quiet).get("suppress-sound"),
Some(&Value::Bool(true))
);
}
fn closings(tag: &str) -> Arc<Mutex<Vec<(String, crate::CloseReason)>>> {
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
crate::set_close_handler(tag, move |tag, reason| {
sink.lock().unwrap().push((tag.to_owned(), reason));
});
seen
}
#[test]
fn what_the_service_closed_is_reported_under_its_tag_and_reason() {
let seen = closings("closing-test:");
let id = 41_001;
if let Ok(mut ids) = ids().lock() {
ids.insert("closing-test:expired".to_owned(), id);
}
if let Ok(mut known) = activation_ids().lock() {
known.insert(
id,
vec![(DEFAULT_ACTION.to_owned(), "tilo-test:open".into())],
);
}
freedesktop_closed(id, 1);
assert_eq!(
*seen.lock().unwrap(),
[(
"closing-test:expired".to_owned(),
crate::CloseReason::Expired
)],
"an expiry says so"
);
assert!(
!ids().lock().unwrap().contains_key("closing-test:expired"),
"the tag is forgotten"
);
assert!(
!activation_ids().lock().unwrap().contains_key(&id),
"its actions are forgotten"
);
freedesktop_closed(id, 1);
assert_eq!(seen.lock().unwrap().len(), 1, "reported once");
}
#[test]
fn a_dismissal_and_an_apps_own_close_are_told_apart() {
let seen = closings("dismissed-test:");
for (id, tag, code, reason) in [
(
41_011,
"dismissed-test:person",
2,
crate::CloseReason::Dismissed,
),
(41_012, "dismissed-test:app", 3, crate::CloseReason::Closed),
] {
if let Ok(mut ids) = ids().lock() {
ids.insert(tag.to_owned(), id);
}
freedesktop_closed(id, code);
assert_eq!(
seen.lock().unwrap().pop(),
Some((tag.to_owned(), reason)),
"code {code} under {tag}"
);
}
}
#[test]
fn a_close_for_a_notification_shown_elsewhere_or_a_reason_the_spec_leaves_open_says_nothing() {
let seen = closings("unknown-test:");
if let Ok(mut ids) = ids().lock() {
ids.insert("elsewhere-test:1".to_owned(), 41_021);
}
freedesktop_closed(41_021, 2);
freedesktop_closed(41_022, 2);
if let Ok(mut ids) = ids().lock() {
ids.insert("unknown-test:1".to_owned(), 41_023);
}
freedesktop_closed(41_023, 7);
assert!(
seen.lock().unwrap().is_empty(),
"nothing to report: {:#?}",
seen.lock().unwrap()
);
}
}