#![cfg_attr(
test,
allow(
clippy::disallowed_methods,
reason = "in a test these are the assertion, not a hazard"
)
)]
use std::sync::{Arc, Mutex, OnceLock};
mod calendar;
mod caps;
pub use calendar::{AlarmSchedule, CalendarAlarm};
pub mod conformance;
#[cfg(all(target_os = "linux", feature = "host-portals"))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(unix)]
pub mod service;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
#[doc(hidden)]
pub mod windows_toasts {
pub use crate::windows::{HostNotifications, ScheduledNotice, register_shortcut};
}
pub use caps::{Availability, Feature, Unsupported, availability, available};
pub use tilo_clock::time::SystemTime;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct Notification {
pub tag: String,
pub title: String,
pub body: String,
pub activation: Option<String>,
pub action: Option<String>,
pub severity: Severity,
pub buttons: Vec<NotificationButton>,
pub silent: bool,
pub app: Option<String>,
pub from: Option<NotificationSender>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct NotificationSender {
pub name: String,
pub id: String,
pub agent: bool,
}
pub const MAX_BUTTONS: usize = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct NotificationButton {
pub label: String,
pub activation: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub enum Severity {
#[default]
Info,
Warning,
Error,
}
impl Notification {
pub fn new(tag: impl Into<String>, title: impl Into<String>, body: impl Into<String>) -> Self {
Self {
tag: tag.into(),
title: title.into(),
body: body.into(),
activation: None,
action: None,
severity: Severity::Info,
buttons: Vec::new(),
silent: false,
app: None,
from: None,
}
}
#[must_use]
pub fn from_app(mut self, name: &str) -> Self {
let name = name.trim();
self.app = (!name.is_empty()).then(|| name.to_owned());
self
}
#[must_use]
pub fn from_agent(mut self, name: impl Into<String>, id: impl Into<String>) -> Self {
self.from = Some(NotificationSender {
name: name.into(),
id: id.into(),
agent: true,
});
self
}
#[must_use]
pub fn quietly(mut self) -> Self {
self.silent = true;
self
}
#[must_use]
pub fn with_button(mut self, label: impl Into<String>, uri: impl Into<String>) -> Self {
self.buttons.push(NotificationButton {
label: label.into(),
activation: uri.into(),
});
self
}
#[must_use]
pub fn with_activation(mut self, uri: impl Into<String>) -> Self {
self.activation = Some(uri.into());
self
}
#[must_use]
pub fn with_action(mut self, label: impl Into<String>) -> Self {
self.action = Some(label.into());
self
}
#[must_use]
pub fn with_severity(mut self, severity: Severity) -> Self {
self.severity = severity;
self
}
}
type ActivationHandler = Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Default)]
struct Activations {
handlers: std::collections::HashMap<String, ActivationHandler>,
pending: Vec<String>,
}
fn scheme_of(uri: &str) -> &str {
uri.split_once(':').map_or(uri, |(scheme, _)| scheme)
}
fn activations() -> &'static Mutex<Activations> {
static ACTIVATIONS: OnceLock<Mutex<Activations>> = OnceLock::new();
ACTIVATIONS.get_or_init(Mutex::default)
}
const PENDING_ACTIVATIONS: usize = 16;
pub fn set_activation_handler(scheme: &str, handler: impl Fn(&str) + Send + Sync + 'static) {
let handler: ActivationHandler = Arc::new(handler);
let pending = {
let Ok(mut activations) = activations().lock() else {
return;
};
activations
.handlers
.insert(scheme.to_owned(), handler.clone());
let (mine, others) = std::mem::take(&mut activations.pending)
.into_iter()
.partition(|uri| scheme_of(uri) == scheme);
activations.pending = others;
mine
};
for uri in pending {
handler(&uri);
}
}
pub fn report_activation(uri: &str) {
if valid_activation(uri) {
activated(uri);
}
}
pub(crate) fn activated(uri: &str) {
let handler = {
let Ok(mut activations) = activations().lock() else {
return;
};
if let Some(handler) = activations.handlers.get(scheme_of(uri)) {
handler.clone()
} else {
if activations.pending.len() == PENDING_ACTIVATIONS {
activations.pending.remove(0);
}
activations.pending.push(uri.to_owned());
return;
}
};
handler(uri);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub enum CloseReason {
Expired,
Dismissed,
Closed,
}
impl CloseReason {
#[must_use]
pub fn code(self) -> u32 {
match self {
Self::Expired => 1,
Self::Dismissed => 2,
Self::Closed => 3,
}
}
#[must_use]
pub fn from_code(code: u32) -> Option<Self> {
match code {
1 => Some(Self::Expired),
2 => Some(Self::Dismissed),
3 => Some(Self::Closed),
_ => None,
}
}
}
type CloseHandler = Arc<dyn Fn(&str, CloseReason) + Send + Sync>;
fn close_handlers() -> &'static Mutex<std::collections::HashMap<String, CloseHandler>> {
static HANDLERS: OnceLock<Mutex<std::collections::HashMap<String, CloseHandler>>> =
OnceLock::new();
HANDLERS.get_or_init(Mutex::default)
}
pub fn set_close_handler(
prefix: &str,
handler: impl Fn(&str, CloseReason) + Send + Sync + 'static,
) {
let Ok(mut handlers) = close_handlers().lock() else {
return;
};
handlers.insert(prefix.to_owned(), Arc::new(handler));
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the freedesktop backend reports closes")
)]
pub(crate) fn closed(tag: &str, reason: CloseReason) {
let handler = {
let Ok(handlers) = close_handlers().lock() else {
return;
};
handlers
.iter()
.filter(|(prefix, _)| tag.starts_with(prefix.as_str()))
.max_by_key(|(prefix, _)| prefix.len())
.map(|(_, handler)| Arc::clone(handler))
};
if let Some(handler) = handler {
handler(tag, reason);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotifyError {
Unavailable,
Unsupported(Unsupported),
Invalid(&'static str),
Failed(String),
}
impl std::fmt::Display for NotifyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unavailable => f.write_str("Notifications aren't available here"),
Self::Unsupported(unsupported) => unsupported.fmt(f),
Self::Invalid(reason) => f.write_str(reason),
Self::Failed(reason) => f.write_str(reason),
}
}
}
impl std::error::Error for NotifyError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct Scheduled {
pub tag: String,
pub at: SystemTime,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AlarmState {
pub tag: String,
pub alarm: CalendarAlarm,
pub enabled_at_ms: i64,
pub next_at: Option<SystemTime>,
pub last_at: Option<SystemTime>,
pub last_rung: Option<jiff::civil::Date>,
}
pub trait Notifier: Send + Sync {
fn show(&self, notification: &Notification) -> Result<(), NotifyError>;
fn withdraw(&self, tag: &str) -> Result<(), NotifyError>;
fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
let _ = (notification, at);
Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
}
fn schedule_alarm(
&self,
notification: &Notification,
at: SystemTime,
schedule: AlarmSchedule,
) -> Result<(), NotifyError> {
if !schedule.alarm.valid() {
return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
}
self.schedule(notification, at)
}
fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
Ok(Vec::new())
}
fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
}
fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
let _ = tag;
Err(NotifyError::Unsupported(Unsupported::of(Feature::Schedule)))
}
}
pub(crate) fn validate(notification: &Notification) -> Result<(), NotifyError> {
validate_tag(¬ification.tag)?;
if notification.title.trim().is_empty() {
return Err(NotifyError::Invalid("a notification needs a title"));
}
if let Some(uri) = ¬ification.activation
&& !valid_activation(uri)
{
return Err(NotifyError::Invalid(
"a notification's activation must be a URI with a scheme",
));
}
if notification.buttons.len() > MAX_BUTTONS {
return Err(NotifyError::Invalid("a notification has too many buttons"));
}
for button in ¬ification.buttons {
if button.label.trim().is_empty() || button.label.chars().any(char::is_control) {
return Err(NotifyError::Invalid("a notification's button needs a name"));
}
if !valid_activation(&button.activation) {
return Err(NotifyError::Invalid(
"a notification button's activation must be a URI with a scheme",
));
}
}
Ok(())
}
pub fn valid_activation(uri: &str) -> bool {
let Some((scheme, _)) = uri.split_once(':') else {
return false;
};
let mut letters = scheme.chars();
letters
.next()
.is_some_and(|first| first.is_ascii_alphabetic())
&& letters.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
&& uri.len() <= 2048
&& !uri.chars().any(|c| c.is_control() || c.is_whitespace())
}
pub(crate) fn validate_tag(tag: &str) -> Result<(), NotifyError> {
if tag.is_empty() {
return Err(NotifyError::Invalid("a notification needs a tag"));
}
if tag.chars().any(char::is_control) {
return Err(NotifyError::Invalid(
"a notification tag has control characters",
));
}
Ok(())
}
pub fn system(app_id: Option<&str>) -> Arc<dyn Notifier> {
#[cfg(unix)]
if let Some(notifier) = service::ServiceNotifier::from_env() {
return Arc::new(notifier);
}
match app_id.filter(|id| !id.is_empty()) {
Some(app_id) => backend(app_id),
None if cfg!(all(target_arch = "wasm32", target_os = "unknown")) => backend(""),
None => unavailable(),
}
}
#[cfg(target_os = "linux")]
fn backend(app_id: &str) -> Arc<dyn Notifier> {
#[cfg(feature = "host-portals")]
{
Arc::new(linux::SessionNotifier::new(app_id))
}
#[cfg(not(feature = "host-portals"))]
{
let _ = app_id;
let _ = app_id;
unavailable()
}
}
#[cfg(target_os = "macos")]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
macos::notifier()
}
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
Arc::new(web::PageNotifier)
}
#[cfg(windows)]
fn backend(app_id: &str) -> Arc<dyn Notifier> {
Arc::new(windows::Toasts::new(app_id))
}
#[cfg(not(any(
target_os = "linux",
target_os = "macos",
windows,
all(target_arch = "wasm32", target_os = "unknown")
)))]
fn backend(_app_id: &str) -> Arc<dyn Notifier> {
unavailable()
}
pub fn unavailable() -> Arc<dyn Notifier> {
Arc::new(UnavailableNotifier)
}
struct UnavailableNotifier;
impl Notifier for UnavailableNotifier {
fn show(&self, _notification: &Notification) -> Result<(), NotifyError> {
Err(NotifyError::Unavailable)
}
fn withdraw(&self, _tag: &str) -> Result<(), NotifyError> {
Err(NotifyError::Unavailable)
}
fn schedule(&self, _notification: &Notification, _at: SystemTime) -> Result<(), NotifyError> {
Err(schedule_refusal())
}
fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
Err(schedule_refusal())
}
fn cancel_scheduled(&self, _tag: &str) -> Result<(), NotifyError> {
Err(schedule_refusal())
}
}
fn schedule_refusal() -> NotifyError {
match availability(Feature::Schedule) {
Availability::Unsupported(_) => {
NotifyError::Unsupported(Unsupported::of(Feature::Schedule))
}
Availability::Available | Availability::Prompt => NotifyError::Unavailable,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(unix, derive(serde::Serialize, serde::Deserialize))]
pub struct PriorityContact {
pub id: String,
pub name: String,
pub endpoints: Vec<String>,
}
pub fn publish_priority_contacts(
app_id: &str,
contacts: &[PriorityContact],
) -> Result<(), NotifyError> {
priority_contacts(app_id, contacts)
}
#[cfg(unix)]
fn priority_contacts(app_id: &str, contacts: &[PriorityContact]) -> Result<(), NotifyError> {
if service::inherited_service() {
return service::publish_priority_contacts(contacts);
}
#[cfg(all(target_os = "linux", feature = "host-portals"))]
{
linux::publish_priority_contacts(app_id, contacts)
}
#[cfg(not(all(target_os = "linux", feature = "host-portals")))]
{
let _ = app_id;
Err(NotifyError::Unsupported(Unsupported::of(
Feature::PriorityContacts,
)))
}
}
#[cfg(not(unix))]
fn priority_contacts(_app_id: &str, _contacts: &[PriorityContact]) -> Result<(), NotifyError> {
Err(NotifyError::Unsupported(Unsupported::of(
Feature::PriorityContacts,
)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn notifiers_that_reach_no_platform_conform() {
let absent = unavailable();
let recording = conformance::Recording::default();
let rows: [(&str, &dyn Notifier); 2] = [
("the_unavailable_notifier_conforms", &*absent),
("a_recording_notifier_conforms", &recording),
];
for (row, notifier) in rows {
eprintln!("row: {row}");
conformance::check_contract(notifier);
}
}
#[test]
fn the_system_notifier_refuses_malformed_requests_before_the_platform() {
conformance::check_system(&*system(Some("so.tilo.notify-test")));
conformance::check_system(&*system(None));
}
#[test]
fn activations_wait_for_a_handler_and_then_reach_it() {
activated("tilo-test:launch");
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = seen.clone();
activated("tilo-other:launch");
set_activation_handler("tilo-test", move |uri| {
sink.lock().unwrap().push(uri.to_owned());
});
activated("tilo-test:later");
activated("tilo-other:later");
assert_eq!(
*seen.lock().unwrap(),
["tilo-test:launch", "tilo-test:later"],
"a handler sees only its scheme's clicks"
);
}
#[test]
fn an_activation_must_be_a_uri() {
let notification = |uri: &str| Notification::new("t", "Title", "").with_activation(uri);
assert_eq!(validate(¬ification("tilo-clocks:timer/1")), Ok(()));
for bad in ["no scheme", "1x:y", "tilo:a b", "tilo:\n"] {
assert!(validate(¬ification(bad)).is_err(), "{bad:?}");
}
}
#[test]
fn buttons_are_named_bounded_and_carry_uris() {
let notification =
Notification::new("t", "Title", "").with_button("Pause", "tilo-test:pause");
assert_eq!(validate(¬ification), Ok(()));
for bad in [
Notification::new("t", "Title", "").with_button(" ", "tilo-test:pause"),
Notification::new("t", "Title", "").with_button("Pause", "no scheme"),
(0..=MAX_BUTTONS).fold(Notification::new("t", "Title", ""), |n, i| {
n.with_button(format!("B{i}"), "tilo-test:b")
}),
] {
assert!(validate(&bad).is_err(), "{bad:?}");
}
}
#[test]
fn a_close_reason_is_the_specifications_code() {
for (reason, code) in [
(CloseReason::Expired, 1),
(CloseReason::Dismissed, 2),
(CloseReason::Closed, 3),
] {
assert_eq!(reason.code(), code);
assert_eq!(CloseReason::from_code(code), Some(reason));
}
assert_eq!(CloseReason::from_code(0), None);
assert_eq!(CloseReason::from_code(4), None);
}
#[test]
fn a_close_reaches_the_handler_that_names_its_tag_and_nothing_else() {
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = seen.clone();
set_close_handler("tilo-close-test:", move |tag, reason| {
sink.lock().unwrap().push((tag.to_owned(), reason));
});
closed("tilo-close-other:1", CloseReason::Dismissed);
closed("tilo-close-test:1", CloseReason::Dismissed);
closed("tilo-close-test:2", CloseReason::Expired);
closed("tilo-close-test:3", CloseReason::Closed);
assert_eq!(
*seen.lock().unwrap(),
[
("tilo-close-test:1".to_owned(), CloseReason::Dismissed),
("tilo-close-test:2".to_owned(), CloseReason::Expired),
("tilo-close-test:3".to_owned(), CloseReason::Closed),
],
"every reason reaches it, and only its own tags"
);
}
#[test]
fn the_longest_matching_prefix_receives_a_close() {
let narrow = Arc::new(Mutex::new(Vec::new()));
let wide = Arc::new(Mutex::new(Vec::new()));
for (prefix, seen) in [
("tilo-narrow-test:", Arc::clone(&narrow)),
("tilo-narrow-test:one/", Arc::clone(&wide)),
] {
set_close_handler(prefix, move |tag, _| {
seen.lock().unwrap().push(tag.to_owned());
});
}
closed("tilo-narrow-test:one/1", CloseReason::Dismissed);
closed("tilo-narrow-test:two/1", CloseReason::Dismissed);
assert_eq!(*wide.lock().unwrap(), ["tilo-narrow-test:one/1"]);
assert_eq!(*narrow.lock().unwrap(), ["tilo-narrow-test:two/1"]);
}
}