1use std::collections::HashMap;
24use std::sync::mpsc as std_mpsc;
25
26use futures_util::StreamExt;
27use tokio::sync::mpsc;
28use zbus::zvariant::Value;
29
30use super::{Notification, Presenter, UserAction};
31
32const DEST: &str = "org.freedesktop.Notifications";
33const PATH: &str = "/org/freedesktop/Notifications";
34const IFACE: &str = "org.freedesktop.Notifications";
35
36enum Cmd {
37 Show(Notification),
38 Retract(String),
39 ClearAll(std_mpsc::Sender<()>),
40}
41
42pub struct LinuxPresenter {
43 tx: mpsc::UnboundedSender<Cmd>,
44}
45
46impl LinuxPresenter {
47 pub fn spawn(actions: mpsc::UnboundedSender<UserAction>) -> Self {
48 let (tx, rx) = mpsc::unbounded_channel();
49 tokio::spawn(run(rx, actions));
50 Self { tx }
51 }
52}
53
54impl Presenter for LinuxPresenter {
55 fn show(&self, n: &Notification) {
56 let _ = self.tx.send(Cmd::Show(n.clone()));
57 }
58 fn retract(&self, tag: &str) {
59 let _ = self.tx.send(Cmd::Retract(tag.to_string()));
60 }
61 fn clear_all(&self) {
62 let (done_tx, done_rx) = std_mpsc::channel();
63 if self.tx.send(Cmd::ClearAll(done_tx)).is_ok() {
64 let _ = done_rx.recv_timeout(std::time::Duration::from_secs(2));
65 }
66 }
67}
68
69pub fn escape_markup(s: &str) -> String {
71 s.replace('&', "&").replace('<', "<").replace('>', ">")
72}
73
74pub fn texts(n: &Notification, body_markup: bool) -> (String, String) {
79 let body = [n.body.as_deref(), n.summary.as_deref()].into_iter().flatten().collect::<Vec<_>>().join("\n");
80 (n.title.clone(), if body_markup { escape_markup(&body) } else { body })
81}
82
83pub fn delivery(n: &Notification) -> (u8, i32, bool) {
92 if n.is_attention() {
93 (1, 0, true)
94 } else {
95 (1, -1, false)
96 }
97}
98
99pub fn action_args(n: &Notification, server_has_actions: bool) -> Vec<String> {
103 let mut out = vec!["default".to_string(), "Open".to_string()];
104 if server_has_actions {
105 for (id, label) in n.buttons() {
106 out.push(id.to_string());
107 out.push(label.to_string());
108 }
109 }
110 out
111}
112
113pub fn pressed(offered: &[String], action: &str, id: &str) -> Option<UserAction> {
116 match action {
117 "default" => Some(UserAction::Clicked(id.to_string())),
118 "keep" if offered.iter().any(|a| a == "keep") => Some(UserAction::Keep(id.to_string())),
119 "now" if offered.iter().any(|a| a == "now") => Some(UserAction::Now(id.to_string())),
120 _ => None,
121 }
122}
123
124pub fn closed_is_user_dismissal(reason: u32) -> bool {
127 reason == 2
128}
129
130async fn run(mut rx: mpsc::UnboundedReceiver<Cmd>, actions: mpsc::UnboundedSender<UserAction>) {
131 let conn = match zbus::Connection::session().await {
132 Ok(c) => c,
133 Err(e) => {
134 crate::logging::log(&format!("notify: no D-Bus session bus ({e}); notifications disabled"));
135 while let Some(cmd) = rx.recv().await {
137 if let Cmd::ClearAll(done) = cmd {
138 let _ = done.send(());
139 }
140 }
141 return;
142 }
143 };
144
145 let (body_markup, has_actions) = match conn.call_method(Some(DEST), PATH, Some(IFACE), "GetCapabilities", &()).await {
146 Ok(reply) => {
147 let caps = reply.body().deserialize::<Vec<String>>().unwrap_or_default();
148 (caps.iter().any(|x| x == "body-markup"), caps.iter().any(|x| x == "actions"))
149 }
150 Err(e) => {
151 crate::logging::log(&format!("notify: no notification server ({e})"));
152 (false, false)
153 }
154 };
155
156 let rule = zbus::MatchRule::builder()
161 .msg_type(zbus::message::Type::Signal)
162 .sender(DEST)
163 .and_then(|b| b.path(PATH))
164 .and_then(|b| b.interface(IFACE))
165 .map(|b| b.build());
166 let mut signals = match rule {
167 Ok(rule) => zbus::MessageStream::for_match_rule(rule, &conn, None).await.ok(),
168 Err(_) => None,
169 };
170
171 let mut by_tag: HashMap<String, (u32, String)> = HashMap::new();
173 let mut by_server: HashMap<u32, String> = HashMap::new();
174 let mut offered: HashMap<u32, Vec<String>> = HashMap::new();
176
177 loop {
178 tokio::select! {
179 cmd = rx.recv() => {
180 let Some(cmd) = cmd else { return };
181 match cmd {
182 Cmd::Show(n) => {
183 let replaces = by_tag.get(&n.tag).map(|(sid, _)| *sid).unwrap_or(0);
184 let (summary, body) = texts(&n, body_markup);
185 let mut hints: HashMap<&str, Value<'_>> = HashMap::new();
186 hints.insert("desktop-entry", Value::from("agentmux"));
187 let (urgency, timeout, resident) = delivery(&n);
188 hints.insert("urgency", Value::from(urgency));
189 if resident {
190 hints.insert("resident", Value::from(true));
191 }
192 let action_list = action_args(&n, has_actions);
193 let args = (
194 "AgentMux",
195 replaces,
196 "agentmux",
197 summary.as_str(),
198 body.as_str(),
199 action_list.clone(),
200 hints,
201 timeout,
202 );
203 match conn.call_method(Some(DEST), PATH, Some(IFACE), "Notify", &args).await {
204 Ok(reply) => {
205 if let Ok(sid) = reply.body().deserialize::<u32>() {
206 if let Some((old, _)) = by_tag.insert(n.tag.clone(), (sid, n.id.clone())) {
207 by_server.remove(&old);
208 offered.remove(&old);
209 }
210 by_server.insert(sid, n.id.clone());
211 offered.insert(sid, action_list);
212 }
213 }
214 Err(e) => crate::logging::log(&format!("notify: Notify failed: {e}")),
215 }
216 }
217 Cmd::Retract(tag) => {
218 if let Some((sid, _)) = by_tag.remove(&tag) {
219 by_server.remove(&sid);
220 offered.remove(&sid);
221 let _ = conn.call_method(Some(DEST), PATH, Some(IFACE), "CloseNotification", &(sid,)).await;
222 }
223 }
224 Cmd::ClearAll(done) => {
225 for (_, (sid, _)) in by_tag.drain() {
226 let _ = conn.call_method(Some(DEST), PATH, Some(IFACE), "CloseNotification", &(sid,)).await;
227 }
228 by_server.clear();
229 offered.clear();
230 let _ = done.send(());
231 }
232 }
233 }
234 msg = async {
235 match signals.as_mut() {
236 Some(s) => s.next().await,
237 None => std::future::pending().await,
238 }
239 } => {
240 let Some(Ok(msg)) = msg else { continue };
241 let header = msg.header();
242 let member = header.member().map(|m| m.as_str().to_string()).unwrap_or_default();
243 match member.as_str() {
244 "ActionInvoked" => {
245 if let Ok((sid, action)) = msg.body().deserialize::<(u32, String)>() {
246 if let Some(id) = by_server.get(&sid) {
247 let list = offered.get(&sid).map(Vec::as_slice).unwrap_or_default();
248 if let Some(press) = pressed(list, &action, id) {
249 let _ = actions.send(press);
250 }
251 }
252 }
253 }
254 "NotificationClosed" => {
255 if let Ok((sid, reason)) = msg.body().deserialize::<(u32, u32)>() {
256 if let Some(id) = by_server.remove(&sid) {
257 offered.remove(&sid);
258 by_tag.retain(|_, (s, _)| *s != sid);
259 if closed_is_user_dismissal(reason) {
260 let _ = actions.send(UserAction::Dismissed(id));
261 }
262 }
263 }
264 }
265 _ => {}
266 }
267 }
268 }
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 fn n(body: Option<&str>) -> Notification {
277 Notification {
278 id: "n1".into(),
279 kind: "input_waiting".into(),
280 priority: "attention".into(),
281 title: "lark has a question".into(),
282 body: body.map(Into::into),
283 summary: None,
284 actions: vec![],
285 countdown: None,
286 tag: "t1".into(),
287 }
288 }
289
290 #[test]
291 fn body_is_escaped_only_for_markup_servers() {
292 let evil = "<a href='x'>click</a> & more";
293 assert_eq!(texts(&n(Some(evil)), true).1, "<a href='x'>click</a> & more");
294 assert_eq!(texts(&n(Some(evil)), false).1, evil);
295 assert_eq!(texts(&n(None), true), ("lark has a question".to_string(), String::new()));
296 }
297
298 #[test]
299 fn summary_is_the_last_body_line_and_escaped_with_it() {
300 let with = |body: Option<&str>, summary: &str| Notification { summary: Some(summary.into()), ..n(body) };
301 assert_eq!(texts(&with(Some("Which branch?"), "Fix repaint"), false).1, "Which branch?\nFix repaint");
302 assert_eq!(texts(&with(None, "Fix repaint"), false).1, "Fix repaint");
303 assert_eq!(texts(&with(Some("a"), "<b>x</b>"), true).1, "a\n<b>x</b>");
304 }
305
306 #[test]
307 fn attention_never_expires_but_never_goes_critical() {
308 let mut a = n(None);
309 a.priority = "attention".into();
310 assert_eq!(delivery(&a), (1, 0, true));
311 let mut normal = n(None);
312 normal.priority = "normal".into();
313 assert_eq!(delivery(&normal), (1, -1, false));
314 }
315
316 #[test]
317 fn only_user_dismissal_is_feedback() {
318 assert!(closed_is_user_dismissal(2));
319 assert!(!closed_is_user_dismissal(1)); assert!(!closed_is_user_dismissal(3)); assert!(!closed_is_user_dismissal(4));
322 }
323
324 fn closing() -> Notification {
325 Notification {
326 actions: vec![
327 super::super::NotifyAction { id: "keep".into(), label: "Keep running".into() },
328 super::super::NotifyAction { id: "now".into(), label: "Close now".into() },
329 ],
330 ..n(Some("AgentY asked to close it."))
331 }
332 }
333
334 #[test]
337 fn the_buttons_are_actions_only_where_the_server_supports_actions() {
338 assert_eq!(action_args(&closing(), true), vec!["default", "Open", "keep", "Keep running", "now", "Close now"]);
339 assert_eq!(action_args(&closing(), false), vec!["default", "Open"]);
340 assert_eq!(action_args(&n(None), true), vec!["default", "Open"], "no button for any other notification");
341 }
342
343 #[test]
346 fn a_press_is_only_what_we_offered() {
347 let offered = action_args(&closing(), true);
348 assert_eq!(pressed(&offered, "keep", "n1"), Some(UserAction::Keep("n1".into())));
349 assert_eq!(pressed(&offered, "now", "n1"), Some(UserAction::Now("n1".into())));
350 assert_eq!(pressed(&offered, "default", "n1"), Some(UserAction::Clicked("n1".into())));
351 assert_eq!(pressed(&offered, "something-else", "n1"), None);
352 let plain = action_args(&n(None), true);
353 assert_eq!(pressed(&plain, "keep", "n2"), None);
354 assert_eq!(pressed(&plain, "now", "n2"), None);
355 }
356}