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