use std::collections::{HashMap, VecDeque};
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use futures_lite::{StreamExt, future};
use lune_terminal::{DesktopNotification, NotificationUrgency};
use winit::event_loop::EventLoopProxy;
use zbus::proxy::SignalStream;
use zbus::zvariant::Value;
use super::{Event, PaneId};
const CHANNEL_CAPACITY: usize = 8;
const MAX_TRACKED_NOTIFICATIONS: usize = 64;
const DEFAULT_ACTION_KEY: &str = "default";
const DEFAULT_ACTION_LABEL: &str = "Focus";
struct Message {
pane_id: PaneId,
id: Option<String>,
title: String,
body: String,
urgency: NotificationUrgency,
}
#[derive(Default)]
struct Queue {
pending: Mutex<VecDeque<Message>>,
closed: AtomicBool,
wake: event_listener::Event,
}
impl Queue {
fn push(&self, message: Message) {
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
if pending.len() >= CHANNEL_CAPACITY {
return;
}
pending.push_back(message);
drop(pending);
self.wake.notify(1);
}
fn pop(&self) -> Option<Message> {
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.pop_front()
}
fn has_pending(&self) -> bool {
!self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
}
fn is_closed(&self) -> bool {
self.closed.load(Ordering::Acquire)
}
fn close(&self) {
self.closed.store(true, Ordering::Release);
self.wake.notify(usize::MAX);
}
}
#[derive(Default)]
struct NotificationTracker {
replaces_ids: HashMap<(PaneId, String), u32>,
entries: VecDeque<(u32, PaneId)>,
pending_tokens: VecDeque<(u32, String)>,
}
impl NotificationTracker {
fn replaces_id(&self, pane_id: PaneId, osc_id: Option<&str>) -> u32 {
osc_id
.and_then(|key| self.replaces_ids.get(&(pane_id, key.to_owned())).copied())
.unwrap_or(0)
}
fn record_sent(&mut self, assigned_id: u32, pane_id: PaneId, osc_id: Option<String>) {
if assigned_id == 0 {
return;
}
self.entries.retain(|(id, _)| *id != assigned_id);
if self.entries.len() >= MAX_TRACKED_NOTIFICATIONS {
self.entries.pop_front();
}
self.entries.push_back((assigned_id, pane_id));
self.pending_tokens.retain(|(id, _)| *id != assigned_id);
if let Some(key) = osc_id {
let composite = (pane_id, key);
if self.replaces_ids.len() >= MAX_TRACKED_NOTIFICATIONS
&& !self.replaces_ids.contains_key(&composite)
{
self.replaces_ids.clear();
}
self.replaces_ids.insert(composite, assigned_id);
}
}
fn record_token(&mut self, id: u32, token: String) {
if token.is_empty() || !self.entries.iter().any(|(tracked_id, _)| *tracked_id == id) {
return;
}
self.pending_tokens
.retain(|(tracked_id, _)| *tracked_id != id);
if self.pending_tokens.len() >= MAX_TRACKED_NOTIFICATIONS {
self.pending_tokens.pop_front();
}
self.pending_tokens.push_back((id, token));
}
fn invoke_action(&mut self, id: u32, action_key: &str) -> Option<(PaneId, Option<String>)> {
if action_key != DEFAULT_ACTION_KEY {
return None;
}
let pane_id = self
.entries
.iter()
.rev()
.find_map(|(tracked_id, pane_id)| (*tracked_id == id).then_some(*pane_id))?;
let token = self
.pending_tokens
.iter()
.position(|(tracked_id, _)| *tracked_id == id)
.and_then(|idx| self.pending_tokens.remove(idx))
.map(|(_, token)| token);
Some((pane_id, token))
}
fn handle_closed(&mut self, id: u32) {
self.replaces_ids.retain(|_, tracked_id| *tracked_id != id);
}
}
pub(super) struct Notifier {
queue: Arc<Queue>,
}
impl Notifier {
pub(super) fn start(event_proxy: EventLoopProxy<Event>, app_id: String) -> io::Result<Self> {
let queue = Arc::new(Queue::default());
let worker_queue = Arc::clone(&queue);
thread::Builder::new()
.name("lune-notify".into())
.spawn(move || {
pollster::block_on(run(worker_queue, event_proxy, app_id));
})?;
Ok(Self { queue })
}
pub(super) fn send(&self, pane_id: PaneId, notification: DesktopNotification<'_>) {
let title: String = notification
.title
.chars()
.filter(|ch| !ch.is_control())
.collect();
let body: String = notification
.body
.chars()
.filter(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'))
.collect();
if title.is_empty() && body.is_empty() {
return;
}
self.queue.push(Message {
pane_id,
id: notification.id.map(str::to_owned),
title,
body,
urgency: notification.urgency,
});
}
}
impl Drop for Notifier {
fn drop(&mut self) {
self.queue.close();
}
}
async fn run(queue: Arc<Queue>, event_proxy: EventLoopProxy<Event>, app_id: String) {
let mut session: Option<(zbus::Proxy<'static>, SignalStream<'static>)> = None;
let mut tracker = NotificationTracker::default();
loop {
while let Some(message) = queue.pop() {
if session.is_none() {
match connect().await {
Ok(connected) => session = Some(connected),
Err(error) => {
log::debug!("Desktop notifications unavailable: {error}");
continue;
}
}
}
if let Some((proxy, _)) = &session
&& send_message(proxy, &app_id, &mut tracker, message)
.await
.is_err()
{
session = None;
}
}
if queue.is_closed() {
break;
}
let wake = queue.wake.listen();
if queue.has_pending() || queue.is_closed() {
continue;
}
if let Some((_, signals)) = &mut session {
enum Next {
Wake,
Signal(Option<zbus::Message>),
}
match future::race(
async {
wake.await;
Next::Wake
},
async { Next::Signal(signals.next().await) },
)
.await
{
Next::Wake => {}
Next::Signal(Some(signal)) => {
if let Some((pane_id, activation_token)) = handle_signal(&mut tracker, &signal)
&& event_proxy
.send_event(Event::NotificationActivated {
pane_id,
activation_token,
})
.is_err()
{
break;
}
}
Next::Signal(None) => session = None,
}
} else {
wake.await;
}
}
}
async fn send_message(
proxy: &zbus::Proxy<'static>,
app_id: &str,
tracker: &mut NotificationTracker,
message: Message,
) -> zbus::Result<()> {
let replaces_id = tracker.replaces_id(message.pane_id, message.id.as_deref());
let summary = if message.title.is_empty() {
"Lune"
} else {
message.title.as_str()
};
let urgency: u8 = match message.urgency {
NotificationUrgency::Low => 0,
NotificationUrgency::Normal => 1,
NotificationUrgency::Critical => 2,
};
let mut hints: HashMap<&str, Value<'_>> = HashMap::new();
hints.insert("urgency", Value::U8(urgency));
hints.insert("desktop-entry", Value::from(app_id));
let actions: &[&str] = &[DEFAULT_ACTION_KEY, DEFAULT_ACTION_LABEL];
match proxy
.call::<_, _, u32>(
"Notify",
&(
"Lune",
replaces_id,
"lune",
summary,
message.body.as_str(),
actions,
hints,
-1_i32,
),
)
.await
{
Ok(assigned) => {
tracker.record_sent(assigned, message.pane_id, message.id);
Ok(())
}
Err(error) => {
log::debug!("Desktop notification failed: {error}");
Err(error)
}
}
}
fn handle_signal(
tracker: &mut NotificationTracker,
signal: &zbus::Message,
) -> Option<(PaneId, Option<String>)> {
match signal.header().member().map(|member| member.as_str()) {
Some("ActivationToken") => {
if let Ok((id, token)) = signal.body().deserialize::<(u32, String)>() {
tracker.record_token(id, token);
}
None
}
Some("ActionInvoked") => {
let (id, action_key) = signal.body().deserialize::<(u32, String)>().ok()?;
tracker.invoke_action(id, &action_key)
}
Some("NotificationClosed") => {
if let Ok((id, _reason)) = signal.body().deserialize::<(u32, u32)>() {
tracker.handle_closed(id);
}
None
}
_ => None,
}
}
async fn connect() -> zbus::Result<(zbus::Proxy<'static>, SignalStream<'static>)> {
let connection = zbus::connection::Builder::session()?
.method_timeout(Duration::from_secs(2))
.build()
.await?;
let proxy = zbus::Proxy::new(
&connection,
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
)
.await?;
let signals = proxy.receive_all_signals().await?;
Ok((proxy, signals))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn action_invoked_resolves_source_pane_and_consumes_activation_token() {
let mut tracker = NotificationTracker::default();
tracker.record_sent(10, 2, Some("build".into()));
tracker.record_sent(11, 5, Some("build".into()));
assert_eq!(tracker.replaces_id(2, Some("build")), 10);
assert_eq!(tracker.replaces_id(5, Some("build")), 11);
tracker.record_token(10, "token-pane-2".into());
assert_eq!(tracker.invoke_action(10, "dismiss"), None);
assert_eq!(
tracker.invoke_action(10, DEFAULT_ACTION_KEY),
Some((2, Some("token-pane-2".into())))
);
assert_eq!(
tracker.invoke_action(10, DEFAULT_ACTION_KEY),
Some((2, None))
);
}
#[test]
fn ignores_foreign_notifications_and_survives_closed_before_action() {
let mut tracker = NotificationTracker::default();
tracker.record_sent(21, 3, Some("job".into()));
tracker.record_token(99, "foreign-token".into());
assert_eq!(tracker.invoke_action(99, DEFAULT_ACTION_KEY), None);
tracker.record_token(21, "token-21".into());
tracker.handle_closed(21);
assert_eq!(tracker.replaces_id(3, Some("job")), 0);
assert_eq!(
tracker.invoke_action(21, DEFAULT_ACTION_KEY),
Some((3, Some("token-21".into())))
);
}
#[test]
fn replacement_clears_stale_token_and_respects_capacity_bound() {
let mut tracker = NotificationTracker::default();
tracker.record_sent(1, 1, None);
tracker.record_token(1, "stale-token".into());
tracker.record_sent(1, 1, None);
assert_eq!(
tracker.invoke_action(1, DEFAULT_ACTION_KEY),
Some((1, None))
);
for id in 2..=(MAX_TRACKED_NOTIFICATIONS as u32 + 5) {
tracker.record_sent(id, id, None);
tracker.record_token(id, format!("token-{id}"));
}
assert!(tracker.entries.len() <= MAX_TRACKED_NOTIFICATIONS);
assert!(tracker.pending_tokens.len() <= MAX_TRACKED_NOTIFICATIONS);
assert_eq!(tracker.invoke_action(2, DEFAULT_ACTION_KEY), None);
let latest = MAX_TRACKED_NOTIFICATIONS as u32 + 5;
assert_eq!(
tracker.invoke_action(latest, DEFAULT_ACTION_KEY),
Some((latest, Some(format!("token-{latest}"))))
);
}
}