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