Skip to main content

crabshell_services/
notifications.rs

1//! A notification server, as the Desktop Notifications spec 1.2 has it:
2//! apps call `org.freedesktop.Notifications` on the session bus, and the
3//! shell keeps what they send.
4//!
5//! The shell queues for the name, so it serves while no other daemon,
6//! such as mako or dunst, does, and takes over when that one leaves.
7//! zbus has no object server here, so the calls are answered by hand on
8//! the main thread, in [`server`]. One stream reads every message the bus
9//! sends this connection, and one loop timer runs only while a popup
10//! waits to expire, so a quiet bus leaves the shell asleep.
11
12mod server;
13
14#[cfg(test)]
15mod tests;
16
17use std::cell::{Cell, RefCell};
18use std::future::poll_fn;
19use std::panic::{self, AssertUnwindSafe, Location};
20use std::pin::Pin;
21use std::rc::Rc;
22use std::sync::Once;
23use std::time::{Duration, Instant, SystemTime};
24
25use calloop::RegistrationToken;
26use calloop::timer::TimeoutAction;
27use crabshell_reactive::{Owner, ReadSignal, Signal, untrack};
28use crabshell_ui::{Cx, IconSource};
29use serde::{Deserialize, Serialize};
30use zbus::export::futures_core::Stream;
31use zbus::fdo::{RequestNameFlags, RequestNameReply};
32use zbus::message::Type as Kind;
33use zbus::{Connection, Message, MessageStream};
34
35use crate::Shared;
36use crate::dbus::BUS;
37use crate::dbus::set_changed;
38use crate::lines::panic_message;
39
40const NOTIFICATIONS: &str = "org.freedesktop.Notifications";
41const NOTIFICATIONS_PATH: &str = "/org/freedesktop/Notifications";
42
43/// How long a popup shows when its app leaves that to the server.
44pub(crate) const POPUP_TIMEOUT: Duration = Duration::from_secs(5);
45
46/// The most notifications kept. Past it the oldest goes, as if it
47/// expired.
48const MAX_KEPT: usize = 256;
49
50/// The most pixel bytes the history keeps: 128 pictures of 128 px.
51const MAX_PIXELS_KEPT: usize = 8 * 1024 * 1024;
52
53/// Why a notification closed, from [`Notifications::on_closed`]. Its app
54/// hears the same in `NotificationClosed`.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum CloseReason {
57  /// It went by itself: a transient one's popup timed out, or it was the
58  /// oldest when the history was full.
59  Expired,
60  /// The user dismissed it, cleared them all, or picked one of its
61  /// actions.
62  Dismissed,
63  /// Its app took it back.
64  CloseRequested,
65}
66
67impl CloseReason {
68  /// Its number in `NotificationClosed`.
69  fn code(self) -> u32 {
70    match self {
71      CloseReason::Expired => 1,
72      CloseReason::Dismissed => 2,
73      CloseReason::CloseRequested => 3,
74    }
75  }
76}
77
78/// How urgent a notification is, from its `urgency` hint.
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
80pub enum Urgency {
81  /// It can wait, such as a finished download.
82  Low,
83  /// The usual.
84  #[default]
85  Normal,
86  /// It needs the user now, such as a battery about to run out. Its
87  /// popup stays until dismissed.
88  Critical,
89}
90
91/// How long a notification's popup shows, as its app asks.
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
93pub enum Timeout {
94  /// As long as the server likes: 5 s.
95  #[default]
96  Default,
97  /// Until dismissed.
98  Never,
99  /// This long.
100  After(Duration),
101}
102
103/// One notification an app sent.
104#[derive(Clone, Debug, PartialEq)]
105pub struct Notification {
106  /// Never 0, and unique among those kept. The key to give
107  /// `children_keyed`, and what [`Notifications::dismiss`] and
108  /// [`Notifications::invoke`] take.
109  pub id: u32,
110  /// The app's name for itself, such as `Firefox`, or empty.
111  pub app_name: String,
112  /// The app's icon as it sent it: an icon name, a `file://` URI, or
113  /// empty.
114  pub app_icon: String,
115  /// One line about it, at most 1 KiB.
116  pub summary: String,
117  /// The text under that, at most 4 KiB, as plain text: tags an app sent
118  /// are taken out and entities decoded. While
119  /// [`set_body_markup`](Notifications::set_body_markup) is on, it is the
120  /// markup as sent, for `parse_markup`.
121  pub body: String,
122  /// The actions the user can pick, as (key, label), at most 16. The
123  /// app means `default` for a click on the notification itself.
124  pub actions: Vec<(String, String)>,
125  /// How urgent it is.
126  pub urgency: Urgency,
127  /// How long its popup shows.
128  pub timeout: Timeout,
129  /// The picture to show: the app's pixels, an image file, or else its
130  /// icon. `None` when it has none.
131  pub image: Option<IconSource>,
132  /// The app's desktop entry, such as `org.mozilla.firefox`, or empty.
133  pub desktop_entry: String,
134  /// What kind it is, such as `email.arrived`, or empty.
135  pub category: String,
136  /// Whether it stays after one of its actions is picked.
137  pub resident: bool,
138  /// Whether it goes once its popup expires, instead of staying in the
139  /// history.
140  pub transient: bool,
141  /// When it arrived, or was last replaced.
142  pub received: SystemTime,
143}
144
145/// The notifications, from `cx.notifications()`. A clone is cheap and
146/// shares the one server.
147#[derive(Clone)]
148pub struct Notifications {
149  /// `None` when the shell provided no services.
150  service: Option<Rc<Service>>,
151  list: ReadSignal<Vec<Notification>>,
152  popups: ReadSignal<Vec<Notification>>,
153  /// The asking context's owner, which [`on_closed`](Self::on_closed)'s
154  /// handlers live under.
155  owner: Owner,
156}
157
158impl Notifications {
159  /// Every notification kept, oldest first: the history, from arrival
160  /// until it is dismissed, picked or closed by its app. A replaced one
161  /// keeps its place.
162  pub fn list(&self) -> ReadSignal<Vec<Notification>> {
163    self.list
164  }
165
166  /// The notifications still showing as popups, newest first. Each stays
167  /// for its timeout, and until dismissed when that is
168  /// [`Timeout::Never`] or it is [`Urgency::Critical`]. An expired one
169  /// stays in [`list`](Self::list), unless it is transient.
170  pub fn popups(&self) -> ReadSignal<Vec<Notification>> {
171    self.popups
172  }
173
174  /// Takes notification `id` away, as the user's close button does, and
175  /// tells its app. An unknown `id` is ignored.
176  pub fn dismiss(&self, id: u32) {
177    if let Some(service) = &self.service {
178      service.close(&[id], CloseReason::Dismissed);
179    }
180  }
181
182  /// Tells notification `id`'s app that the user picked its action
183  /// `key`, then takes it away unless it is resident. An unknown `id` or
184  /// `key` is logged.
185  pub fn invoke(&self, id: u32, key: &str) {
186    if let Some(service) = &self.service {
187      service.invoke(id, key);
188    }
189  }
190
191  /// When on, the server tells apps it shows `body-markup` and
192  /// `body-hyperlinks`, so they send the spec's markup, and keeps each body
193  /// as sent, for `Text::rich(parse_markup(&body))`. Off by default, when
194  /// tags are taken out. Notifications already kept stay as they came.
195  pub fn set_body_markup(&self, on: bool) {
196    if let Some(service) = &self.service {
197      service.body_markup.set(on);
198    }
199  }
200
201  /// Dismisses every notification.
202  pub fn clear(&self) {
203    if let Some(service) = &self.service {
204      let state = service.state.borrow();
205      let history = state.as_ref().map(|state| state.history.as_slice());
206      let ids: Vec<u32> = history.unwrap_or_default().iter().map(|n| n.id).collect();
207      drop(state);
208      service.close(&ids, CloseReason::Dismissed);
209    }
210  }
211
212  /// Calls `handler` with each notification that leaves the history and
213  /// why, as Quickshell's `Notification.closed`, for as long as the
214  /// context `cx.notifications()` was called on lives. It runs on the
215  /// main thread once the lists no longer show it. A popup that times out
216  /// stays in the history, so it hasn't closed, unless it is transient.
217  ///
218  /// If it panics, that is logged with where `on_closed` was called, and
219  /// it isn't called again. Called on a handle whose context went, it
220  /// logs that and does nothing.
221  #[track_caller]
222  pub fn on_closed(&self, handler: impl Fn(&Notification, CloseReason) + 'static) {
223    let at = Location::caller();
224    if self.owner.is_disposed() {
225      return tracing::warn!(
226        "notifications on_closed (called at {at}) on a context that is gone does nothing"
227      );
228    }
229    if let Some(service) = &self.service {
230      let id = service.listen(Rc::new(handler), at);
231      // Dropped with the asking context's owner, which takes the handler away.
232      self.owner.signal(Unlisten(Rc::clone(service), id));
233    }
234  }
235}
236
237/// What `on_closed` calls.
238type CloseHandler = Rc<dyn Fn(&Notification, CloseReason)>;
239
240/// A config's handler of closed notifications, from `on_closed`.
241#[derive(Clone)]
242struct Listener {
243  id: u64,
244  handler: CloseHandler,
245  /// Where `on_closed` was called, for the log if it panics.
246  at: &'static Location<'static>,
247}
248
249/// Takes a listener away when its context's owner drops this.
250struct Unlisten(Rc<Service>, u64);
251
252impl Drop for Unlisten {
253  fn drop(&mut self) {
254    // Dropped outside the borrow: the handler may hold a `Notifications`.
255    drop(self.0.unlisten(self.1));
256  }
257}
258
259/// `cx.notifications()`.
260pub(crate) fn notifications(cx: &Cx) -> Notifications {
261  let Some(service) = cx.service::<Service>() else {
262    static LOGGED: Once = Once::new();
263    LOGGED.call_once(|| {
264      tracing::warn!("cx.notifications() needs the services the shell provides; none arrive");
265    });
266    return Notifications {
267      service: None,
268      list: cx.signal(Vec::new()).read_only(),
269      popups: cx.signal(Vec::new()).read_only(),
270      owner: cx.owner(),
271    };
272  };
273  let (list, popups) = service.start();
274  Notifications {
275    service: Some(service),
276    list,
277    popups,
278    owner: cx.owner(),
279  }
280}
281
282/// The notification server of one shell, started on first use.
283pub(crate) struct Service {
284  shared: Rc<Shared>,
285  state: RefCell<Option<State>>,
286  /// Whether bodies are kept as markup, from `set_body_markup`.
287  body_markup: Cell<bool>,
288  /// What the shell before a reload kept, until the server starts.
289  saved: RefCell<Option<Saved>>,
290  /// Whether expiries wait for the bus to answer the name request, so a
291  /// popup that expired during a reload is told to its app.
292  held: Cell<bool>,
293}
294
295/// What a reload keeps of the server: the history, the popups showing and
296/// the next id, so apps' ids go on.
297#[derive(Serialize, Deserialize)]
298struct Saved {
299  next_id: u32,
300  history: Vec<Kept>,
301  /// The ids showing as popups, newest first, each with the milliseconds
302  /// left until it expires, `None` for never.
303  showing: Vec<(u32, Option<u64>)>,
304}
305
306/// A notification as a reload keeps it: all but pixels, which fall back
307/// to the app's icon.
308#[derive(Serialize, Deserialize)]
309struct Kept {
310  id: u32,
311  app_name: String,
312  app_icon: String,
313  summary: String,
314  body: String,
315  actions: Vec<(String, String)>,
316  urgency: Urgency,
317  timeout: Timeout,
318  image: Option<Image>,
319  desktop_entry: String,
320  category: String,
321  resident: bool,
322  transient: bool,
323  received: SystemTime,
324}
325
326/// A picture a reload keeps.
327#[derive(Serialize, Deserialize)]
328enum Image {
329  Name(String),
330  File(std::path::PathBuf),
331}
332
333impl Kept {
334  fn new(notification: &Notification) -> Kept {
335    let image = match &notification.image {
336      Some(IconSource::Name(name)) => Some(Image::Name(name.clone())),
337      Some(IconSource::File(path)) => Some(Image::File(path.clone())),
338      Some(IconSource::Pixels(_)) | None => None,
339    };
340    Kept {
341      id: notification.id,
342      app_name: notification.app_name.clone(),
343      app_icon: notification.app_icon.clone(),
344      summary: notification.summary.clone(),
345      body: notification.body.clone(),
346      actions: notification.actions.clone(),
347      urgency: notification.urgency,
348      timeout: notification.timeout,
349      image,
350      desktop_entry: notification.desktop_entry.clone(),
351      category: notification.category.clone(),
352      resident: notification.resident,
353      transient: notification.transient,
354      received: notification.received,
355    }
356  }
357
358  /// The notification, within the caps of one that arrives, since the
359  /// file it came from is outside data.
360  fn notification(self) -> Notification {
361    use server::{MAX_ACTIONS, MAX_BODY, MAX_SUMMARY, MAX_TEXT, cut, cut_markup};
362
363    let text = |text: &str| cut(text, MAX_TEXT);
364    let actions = self.actions.iter().take(MAX_ACTIONS);
365    let image = match self.image {
366      Some(Image::Name(name)) => Some(IconSource::Name(name)),
367      Some(Image::File(path)) => Some(IconSource::File(path)),
368      None => server::icon(&self.app_icon),
369    };
370    Notification {
371      id: self.id,
372      app_name: text(&self.app_name),
373      app_icon: text(&self.app_icon),
374      summary: cut(&self.summary, MAX_SUMMARY),
375      body: cut_markup(&self.body, MAX_BODY),
376      actions: actions
377        .map(|(key, label)| (text(key), text(label)))
378        .collect(),
379      urgency: self.urgency,
380      timeout: self.timeout,
381      image,
382      desktop_entry: text(&self.desktop_entry),
383      category: text(&self.category),
384      resident: self.resident,
385      transient: self.transient,
386      received: self.received,
387    }
388  }
389}
390
391struct State {
392  list: Signal<Vec<Notification>>,
393  popups: Signal<Vec<Notification>>,
394  /// The session bus, once connected.
395  connection: Option<Connection>,
396  /// Whether this shell owns the name now, so it answers and signals.
397  serving: bool,
398  /// Every notification kept, oldest first.
399  history: Vec<Notification>,
400  /// The ids showing as popups.
401  showing: Showing,
402  /// The id the next notification gets, unless one kept has it.
403  next_id: u32,
404  /// The expiry timer, while a popup waits to expire.
405  timer: Option<RegistrationToken>,
406  /// The config's close handlers, in the order given.
407  listeners: Vec<Listener>,
408  /// The id the next listener gets.
409  next_listener: u64,
410}
411
412impl State {
413  /// A new id: the count goes on from the last, skipping 0 when it wraps
414  /// and any id still kept.
415  fn new_id(&mut self) -> u32 {
416    loop {
417      let id = self.next_id;
418      self.next_id = id.checked_add(1).unwrap_or(1);
419      if !self.history.iter().any(|kept| kept.id == id) {
420        return id;
421      }
422    }
423  }
424}
425
426/// The ids showing as popups, newest first, each with when it expires,
427/// `None` for never.
428type Showing = Vec<(u32, Option<Instant>)>;
429
430/// A signal for the apps, sent in order.
431enum Event {
432  /// `NotificationClosed`: the id and why.
433  Closed(u32, CloseReason),
434  /// `ActionInvoked`: the id and the action's key.
435  Invoked(u32, String),
436}
437
438impl Service {
439  pub(crate) fn new(shared: Rc<Shared>) -> Service {
440    Service {
441      shared,
442      state: RefCell::new(None),
443      body_markup: Cell::new(false),
444      saved: RefCell::new(None),
445      held: Cell::new(false),
446    }
447  }
448
449  /// Lets expiries run, now that the name request was answered or never
450  /// will be.
451  fn release(self: &Rc<Self>) {
452    if self.held.replace(false) {
453      self.schedule();
454    }
455  }
456
457  /// What a reload keeps, or `None` when the server never started.
458  pub(crate) fn save(&self) -> Option<serde_json::Value> {
459    let state = self.state.borrow();
460    let state = state.as_ref()?;
461    let now = Instant::now();
462    let showing = state.showing.iter().map(|(id, expires)| {
463      let left = expires.map(|at| at.saturating_duration_since(now).as_millis());
464      (
465        *id,
466        left.map(|left| u64::try_from(left).unwrap_or(u64::MAX)),
467      )
468    });
469    let saved = Saved {
470      next_id: state.next_id,
471      history: state.history.iter().map(Kept::new).collect(),
472      showing: showing.collect(),
473    };
474    serde_json::to_value(saved)
475      .inspect_err(|error| tracing::warn!(%error, "the notifications couldn't be kept"))
476      .ok()
477  }
478
479  /// Starts from what the shell before a reload kept, once a config asks
480  /// for the notifications. One that doesn't fit is logged and dropped.
481  pub(crate) fn restore(&self, saved: serde_json::Value) {
482    match serde_json::from_value::<Saved>(saved) {
483      Ok(saved) => *self.saved.borrow_mut() = Some(saved),
484      Err(error) => tracing::warn!(%error, "the notifications kept don't fit; starting empty"),
485    }
486  }
487
488  /// The history and the popups, joining the bus if this is the first
489  /// ask.
490  fn start(self: &Rc<Self>) -> (ReadSignal<Vec<Notification>>, ReadSignal<Vec<Notification>>) {
491    if let Some(state) = &*self.state.borrow() {
492      return (state.list.read_only(), state.popups.read_only());
493    }
494    let (history, showing, next_id) = self.saved.take().map_or_else(
495      || (Vec::new(), Vec::new(), 1),
496      |saved| restored(saved, Instant::now()),
497    );
498    let popups_shown = showing.iter().filter_map(|(id, _)| {
499      history
500        .iter()
501        .find(|kept: &&Notification| kept.id == *id)
502        .cloned()
503    });
504    let list = self.shared.root.signal(history.clone());
505    let popups = self.shared.root.signal(popups_shown.collect());
506    *self.state.borrow_mut() = Some(State {
507      list,
508      popups,
509      connection: None,
510      serving: false,
511      history,
512      showing,
513      next_id,
514      timer: None,
515      listeners: Vec::new(),
516      next_listener: 0,
517    });
518    self.held.set(self.shared.config.session_bus.is_some());
519    self.schedule();
520    match self.shared.config.session_bus.clone() {
521      Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
522      None => tracing::info!("no session bus, so no notifications arrive"),
523    }
524    (list.read_only(), popups.read_only())
525  }
526
527  /// Whether the history is still there: its owner, the root, isn't
528  /// disposed.
529  fn alive(&self) -> bool {
530    let state = self.state.borrow();
531    let alive = state.as_ref().and_then(|state| state.list.try_with(|_| ()));
532    alive.is_some()
533  }
534
535  fn serving(&self) -> bool {
536    let state = self.state.borrow();
537    state.as_ref().is_some_and(|state| state.serving)
538  }
539
540  /// Keeps `notification`, in place of `replaces` if that one is kept,
541  /// and shows it as a popup. Returns its id.
542  fn notify(self: &Rc<Self>, replaces: u32, mut notification: Notification) -> u32 {
543    let now = Instant::now();
544    let expires = match (notification.urgency, notification.timeout) {
545      (Urgency::Critical, _) | (_, Timeout::Never) => None,
546      (_, Timeout::Default) => Some(now + self.shared.config.popup_timeout),
547      (_, Timeout::After(after)) => Some(now + after),
548    };
549    let (id, dropped) = {
550      let mut state = self.state.borrow_mut();
551      let Some(state) = state.as_mut() else {
552        return 0;
553      };
554      // The spec returns `replaces` even when it is gone, so it names
555      // the new one then.
556      let id = match replaces {
557        0 => state.new_id(),
558        id => id,
559      };
560      notification.id = id;
561      match state.history.iter().position(|kept| kept.id == id) {
562        Some(at) => state.history[at] = notification,
563        None => state.history.push(notification),
564      }
565      match state.showing.iter_mut().find(|(shown, _)| *shown == id) {
566        Some(shown) => shown.1 = expires,
567        None => state.showing.insert(0, (id, expires)),
568      }
569      let excess = state.history.len().saturating_sub(MAX_KEPT);
570      let dropped: Vec<Notification> = state.history.drain(..excess).collect();
571      let history = &state.history;
572      state
573        .showing
574        .retain(|(id, _)| history.iter().any(|kept| kept.id == *id));
575      keep_pixels_within(&mut state.history, MAX_PIXELS_KEPT);
576      (id, dropped)
577    };
578    self.closed(Vec::new(), dropped, CloseReason::Expired);
579    id
580  }
581
582  /// Takes `ids` away and tells their apps `reason`. Returns whether any
583  /// was kept.
584  fn close(self: &Rc<Self>, ids: &[u32], reason: CloseReason) -> bool {
585    let taken = self.take(ids);
586    if taken.is_empty() {
587      return false;
588    }
589    self.closed(Vec::new(), taken, reason);
590    true
591  }
592
593  /// Picks action `key` of notification `id`, as [`Notifications::invoke`]
594  /// does.
595  fn invoke(self: &Rc<Self>, id: u32, key: &str) {
596    let resident = self.state.borrow().as_ref().and_then(|state| {
597      let kept = state.history.iter().find(|kept| kept.id == id)?;
598      let offered = kept.actions.iter().any(|(action, _)| action == key);
599      offered.then_some(kept.resident)
600    });
601    let Some(resident) = resident else {
602      return tracing::warn!(id, key, "no such notification action");
603    };
604    let events = vec![Event::Invoked(id, key.to_owned())];
605    let taken = if resident {
606      Vec::new()
607    } else {
608      self.take(&[id])
609    };
610    self.closed(events, taken, CloseReason::Dismissed);
611  }
612
613  /// Takes `ids` out of the history and the popups, and returns those
614  /// that were kept, oldest first.
615  fn take(&self, ids: &[u32]) -> Vec<Notification> {
616    let mut state = self.state.borrow_mut();
617    let Some(state) = state.as_mut() else {
618      return Vec::new();
619    };
620    let (taken, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut state.history)
621      .into_iter()
622      .partition(|kept| ids.contains(&kept.id));
623    state.history = kept;
624    state.showing.retain(|(id, _)| !ids.contains(id));
625    taken
626  }
627
628  /// Tells the apps `events`, then that `closed` went for `reason`, shows
629  /// the lists without them, and then calls the config's handlers.
630  fn closed(
631    self: &Rc<Self>,
632    mut events: Vec<Event>,
633    closed: Vec<Notification>,
634    reason: CloseReason,
635  ) {
636    events.extend(closed.iter().map(|gone| Event::Closed(gone.id, reason)));
637    self.emit(events);
638    self.changed();
639    self.deliver(&closed, reason);
640  }
641
642  /// Adds a config's close handler. Its id.
643  fn listen(&self, handler: CloseHandler, at: &'static Location<'static>) -> u64 {
644    let mut state = self.state.borrow_mut();
645    let state = state
646      .as_mut()
647      .expect("invariant: started by cx.notifications()");
648    state.next_listener += 1;
649    let id = state.next_listener;
650    state.listeners.push(Listener { id, handler, at });
651    id
652  }
653
654  /// Takes a handler away, handing it back to drop outside the borrow.
655  fn unlisten(&self, id: u64) -> Option<Listener> {
656    let mut state = self.state.borrow_mut();
657    let listeners = &mut state.as_mut()?.listeners;
658    let index = listeners.iter().position(|listener| listener.id == id)?;
659    Some(listeners.remove(index))
660  }
661
662  fn listening(&self, id: u64) -> bool {
663    let state = self.state.borrow();
664    let mut listeners = state.iter().flat_map(|state| &state.listeners);
665    listeners.any(|listener| listener.id == id)
666  }
667
668  /// Hands each of `closed` to the config's handlers, with nothing
669  /// borrowed, since a handler may call the service, and untracked, so
670  /// what one reads never reruns an effect that closed a notification. A
671  /// handler that panics is logged with where `on_closed` was called, and
672  /// taken away.
673  fn deliver(&self, closed: &[Notification], reason: CloseReason) {
674    let listeners = match self.state.borrow().as_ref() {
675      Some(state) if !closed.is_empty() => state.listeners.clone(),
676      _ => return,
677    };
678    for gone in closed {
679      for Listener { id, handler, at } in &listeners {
680        // A handler before this one may have taken this one's context.
681        if !self.listening(*id) {
682          continue;
683        }
684        let run = AssertUnwindSafe(|| untrack(|| handler(gone, reason)));
685        if let Err(payload) = panic::catch_unwind(run) {
686          let message = panic_message(payload.as_ref());
687          tracing::error!("notifications on_closed (called at {at}) panicked: {message}");
688          drop(self.unlisten(*id));
689        }
690      }
691    }
692  }
693
694  /// The timer's tick: takes the expired popups away, and the transient
695  /// ones out of the history too.
696  fn expire(self: &Rc<Self>) -> TimeoutAction {
697    if let Some(state) = self.state.borrow_mut().as_mut() {
698      // This timer goes once the tick returns.
699      state.timer = None;
700    }
701    if !self.alive() {
702      return TimeoutAction::Drop;
703    }
704    let now = Instant::now();
705    let transient = {
706      let mut state = self.state.borrow_mut();
707      let Some(state) = state.as_mut() else {
708        return TimeoutAction::Drop;
709      };
710      let (expired, showing) = std::mem::take(&mut state.showing)
711        .into_iter()
712        .partition::<Vec<_>, _>(|(_, expires)| expires.is_some_and(|at| at <= now));
713      state.showing = showing;
714      let history = state.history.iter();
715      let transient = history.filter(|kept| kept.transient);
716      transient
717        .map(|kept| kept.id)
718        .filter(|id| expired.iter().any(|(gone, _)| gone == id))
719        .collect::<Vec<_>>()
720    };
721    let taken = self.take(&transient);
722    self.closed(Vec::new(), taken, CloseReason::Expired);
723    TimeoutAction::Drop
724  }
725
726  /// Shows the history and popups as they are now, and sets the timer
727  /// for the next popup to expire.
728  fn changed(self: &Rc<Self>) {
729    // Set apart from the borrow, since effects may ask for more.
730    let shown = self.state.borrow().as_ref().map(|state| {
731      let popups = state.showing.iter().filter_map(|(id, _)| {
732        let kept = state.history.iter().find(|kept| kept.id == *id);
733        kept.cloned()
734      });
735      let popups = popups.collect::<Vec<_>>();
736      (state.list, state.history.clone(), state.popups, popups)
737    });
738    if let Some((list_signal, list, popups_signal, popups)) = shown {
739      set_changed(list_signal, list);
740      set_changed(popups_signal, popups);
741    }
742    self.schedule();
743  }
744
745  /// Sets the one timer afresh, at the soonest expiry, or none while no
746  /// popup expires.
747  fn schedule(self: &Rc<Self>) {
748    if self.held.get() {
749      return;
750    }
751    let Some(event_loop) = self.shared.event_loop() else {
752      return;
753    };
754    let mut state = self.state.borrow_mut();
755    let Some(state) = state.as_mut() else {
756      return;
757    };
758    if let Some(token) = state.timer.take() {
759      event_loop.remove(token);
760    }
761    let Some(next) = state.showing.iter().filter_map(|(_, at)| *at).min() else {
762      return;
763    };
764    let service = Rc::clone(self);
765    let tick = Box::new(move || service.expire());
766    state.timer = event_loop.insert_timer(next, tick);
767  }
768
769  /// Sends `events` in order, while this shell serves.
770  fn emit(&self, events: Vec<Event>) {
771    let connection = {
772      let state = self.state.borrow();
773      let serving = state.as_ref().filter(|state| state.serving);
774      serving.and_then(|state| state.connection.clone())
775    };
776    let Some(connection) = connection.filter(|_| !events.is_empty()) else {
777      return;
778    };
779    self.shared.spawn(async move {
780      for event in events {
781        let (path, interface) = (NOTIFICATIONS_PATH, NOTIFICATIONS);
782        let sent = match &event {
783          Event::Closed(id, reason) => {
784            let body = (*id, reason.code());
785            let signal = "NotificationClosed";
786            let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
787            emit.await
788          }
789          Event::Invoked(id, key) => {
790            let body = (*id, key.as_str());
791            let signal = "ActionInvoked";
792            let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
793            emit.await
794          }
795        };
796        if let Err(error) = sent {
797          tracing::warn!(%error, "a notification signal wasn't sent");
798        }
799      }
800    });
801  }
802
803  /// Acts on one message from the bus.
804  async fn on_message(self: &Rc<Self>, connection: &Connection, message: &Message) {
805    match message.header().message_type() {
806      Kind::MethodCall => server::answer(self, connection, message).await,
807      Kind::Signal => self.on_signal(message),
808      _ => {}
809    }
810  }
811
812  /// The bus handing this shell the name, or taking it away.
813  fn on_signal(&self, message: &Message) {
814    let header = message.header();
815    let from_bus = header.sender().is_some_and(|sender| sender.as_str() == BUS);
816    let ours = message.body().deserialize::<&str>().ok() == Some(NOTIFICATIONS);
817    if !from_bus || !ours {
818      return;
819    }
820    let serving = match header.member().map(|member| member.as_str()) {
821      Some("NameAcquired") => {
822        tracing::info!("serving notifications");
823        true
824      }
825      Some("NameLost") => {
826        tracing::info!("another program took over notifications; waiting for it to leave");
827        false
828      }
829      _ => return,
830    };
831    if let Some(state) = self.state.borrow_mut().as_mut() {
832      state.serving = serving;
833    }
834  }
835}
836
837/// Joins the session bus at `address`, queues for the name, and acts on
838/// what arrives, until the bus closes or the history is disposed.
839async fn run(service: Rc<Service>, address: zbus::Address) {
840  let builder = zbus::connection::Builder::address(address);
841  let connection = match builder.build().await {
842    Ok(connection) => connection,
843    Err(error) => {
844      service.release();
845      return tracing::info!(%error, "can't reach the session bus, so no notifications arrive");
846    }
847  };
848  // Made before anything is asked, so no call or NameAcquired is missed.
849  let mut messages = MessageStream::from(&connection);
850  if let Some(state) = service.state.borrow_mut().as_mut() {
851    state.connection = Some(connection.clone());
852  }
853  // Queued rather than refused, so the bus hands the name over when the
854  // daemon that has it leaves. NameAcquired says so, in `on_signal`.
855  let flags = RequestNameFlags::ALLOW_REPLACEMENT;
856  let requested = connection
857    .request_name_with_flags(NOTIFICATIONS, flags)
858    .await;
859  if let Ok(RequestNameReply::PrimaryOwner | RequestNameReply::AlreadyOwner) = requested
860    && let Some(state) = service.state.borrow_mut().as_mut()
861  {
862    // As NameAcquired says too, so expiries held till now reach the apps.
863    state.serving = true;
864  }
865  service.release();
866  match requested {
867    Ok(RequestNameReply::InQueue) => {
868      tracing::info!("another program serves notifications; waiting for it to leave");
869    }
870    Ok(_) => {}
871    Err(error) => return tracing::warn!(%error, "couldn't ask for the notifications name"),
872  }
873  loop {
874    let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
875    if !service.alive() {
876      return;
877    }
878    match next {
879      Some(Ok(message)) => service.on_message(&connection, &message).await,
880      Some(Err(error)) => tracing::warn!(%error, "a bad message on the session bus"),
881      None => break,
882    }
883  }
884  tracing::warn!("the session bus closed, so no more notifications arrive");
885  if let Some(state) = service.state.borrow_mut().as_mut() {
886    state.serving = false;
887    state.connection = None;
888  }
889}
890
891/// The history, popups and next id `saved` holds, as of `now`, within the
892/// caps: ids unique and never 0, and popups only of those kept.
893fn restored(saved: Saved, now: Instant) -> (Vec<Notification>, Showing, u32) {
894  let mut history: Vec<Notification> = Vec::new();
895  for kept in saved.history {
896    if kept.id != 0 && !history.iter().any(|seen| seen.id == kept.id) {
897      history.push(kept.notification());
898    }
899  }
900  let excess = history.len().saturating_sub(MAX_KEPT);
901  history.drain(..excess);
902  let mut showing = Showing::new();
903  for (id, left) in saved.showing {
904    let known = history.iter().any(|kept| kept.id == id);
905    if known && !showing.iter().any(|(shown, _)| *shown == id) {
906      let left = left.map(Duration::from_millis);
907      showing.push((id, left.map(|left| now.checked_add(left).unwrap_or(now))));
908    }
909  }
910  (history, showing, saved.next_id.max(1))
911}
912
913/// Drops the pixels of the oldest notifications past `budget` bytes in
914/// all, each falling back to its app's icon.
915fn keep_pixels_within(history: &mut [Notification], budget: usize) {
916  let mut total = 0;
917  for kept in history.iter_mut().rev() {
918    let Some(IconSource::Pixels(pixels)) = &kept.image else {
919      continue;
920    };
921    let bytes = pixels.data.len();
922    if total + bytes <= budget {
923      total += bytes;
924    } else {
925      tracing::debug!(
926        id = kept.id,
927        "past the pictures' budget; showing the app icon"
928      );
929      kept.image = server::icon(&kept.app_icon);
930    }
931  }
932}