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