1mod 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";
46const HANDOFF: &str = "dev.crabshell.Handoff";
49
50const HANDOFF_LIMIT: Duration = Duration::from_secs(2);
52
53const MAX_HELD: usize = 256;
56
57const MAX_HANDOFF: usize = 16 * 1024 * 1024;
60
61pub(crate) const POPUP_TIMEOUT: Duration = Duration::from_secs(5);
63
64const MAX_KEPT: usize = 256;
67
68const MAX_PIXELS_KEPT: usize = 8 * 1024 * 1024;
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum CloseReason {
75 Expired,
78 Dismissed,
81 CloseRequested,
83}
84
85impl CloseReason {
86 fn code(self) -> u32 {
88 match self {
89 CloseReason::Expired => 1,
90 CloseReason::Dismissed => 2,
91 CloseReason::CloseRequested => 3,
92 }
93 }
94}
95
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
98pub enum Urgency {
99 Low,
101 #[default]
103 Normal,
104 Critical,
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
111pub enum Timeout {
112 #[default]
114 Default,
115 Never,
117 After(Duration),
119}
120
121#[derive(Clone, Debug, PartialEq)]
123pub struct Notification {
124 pub id: u32,
128 pub app_name: String,
130 pub app_icon: String,
133 pub summary: String,
135 pub body: String,
140 pub actions: Vec<(String, String)>,
143 pub urgency: Urgency,
145 pub timeout: Timeout,
147 pub image: Option<IconSource>,
150 pub desktop_entry: String,
152 pub category: String,
154 pub resident: bool,
156 pub transient: bool,
159 pub received: SystemTime,
161}
162
163#[derive(Clone)]
166pub struct Notifications {
167 service: Option<Rc<Service>>,
169 list: ReadSignal<Vec<Notification>>,
170 popups: ReadSignal<Vec<Notification>>,
171 owner: Owner,
174}
175
176impl Notifications {
177 pub fn list(&self) -> ReadSignal<Vec<Notification>> {
181 self.list
182 }
183
184 pub fn popups(&self) -> ReadSignal<Vec<Notification>> {
189 self.popups
190 }
191
192 pub fn dismiss(&self, id: u32) {
195 if let Some(service) = &self.service {
196 service.close(&[id], CloseReason::Dismissed);
197 }
198 }
199
200 pub fn invoke(&self, id: u32, key: &str) {
204 if let Some(service) = &self.service {
205 service.invoke(id, key);
206 }
207 }
208
209 pub fn set_body_markup(&self, on: bool) {
214 if let Some(service) = &self.service {
215 service.body_markup.set(on);
216 }
217 }
218
219 pub fn clear(&self) {
221 if let Some(service) = &self.service {
222 let state = service.state.borrow();
223 let history = state.as_ref().map(|state| state.history.as_slice());
224 let ids: Vec<u32> = history.unwrap_or_default().iter().map(|n| n.id).collect();
225 drop(state);
226 service.close(&ids, CloseReason::Dismissed);
227 }
228 }
229
230 #[track_caller]
240 pub fn on_closed(&self, handler: impl Fn(&Notification, CloseReason) + 'static) {
241 let at = Location::caller();
242 if self.owner.is_disposed() {
243 return tracing::warn!(
244 "notifications on_closed (called at {at}) on a context that is gone does nothing"
245 );
246 }
247 if let Some(service) = &self.service {
248 let id = service.listen(Rc::new(handler), at);
249 self.owner.signal(Unlisten(Rc::clone(service), id));
251 }
252 }
253}
254
255type CloseHandler = Rc<dyn Fn(&Notification, CloseReason)>;
257
258#[derive(Clone)]
260struct Listener {
261 id: u64,
262 handler: CloseHandler,
263 at: &'static Location<'static>,
265}
266
267struct Unlisten(Rc<Service>, u64);
269
270impl Drop for Unlisten {
271 fn drop(&mut self) {
272 drop(self.0.unlisten(self.1));
274 }
275}
276
277pub(crate) fn notifications(cx: &Cx) -> Notifications {
279 let Some(service) = cx.service::<Service>() else {
280 static LOGGED: Once = Once::new();
281 LOGGED.call_once(|| {
282 tracing::warn!("cx.notifications() needs the services the shell provides; none arrive");
283 });
284 return Notifications {
285 service: None,
286 list: cx.signal(Vec::new()).read_only(),
287 popups: cx.signal(Vec::new()).read_only(),
288 owner: cx.owner(),
289 };
290 };
291 let (list, popups) = service.start();
292 Notifications {
293 service: Some(service),
294 list,
295 popups,
296 owner: cx.owner(),
297 }
298}
299
300pub(crate) struct Service {
302 shared: Rc<Shared>,
303 state: RefCell<Option<State>>,
304 body_markup: Cell<bool>,
306 saved: RefCell<Option<Saved>>,
308 held: Cell<bool>,
311 handing_off: Cell<bool>,
314 handed_over: Cell<bool>,
318 saved_since_lost: Cell<bool>,
321 taking_from: RefCell<Option<String>>,
324}
325
326#[derive(Serialize, Deserialize)]
329struct Saved {
330 next_id: u32,
331 history: Vec<Kept>,
332 showing: Vec<(u32, Option<u64>)>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
338 owner: Option<String>,
339}
340
341#[derive(Serialize, Deserialize)]
344struct Kept {
345 id: u32,
346 app_name: String,
347 app_icon: String,
348 summary: String,
349 body: String,
350 actions: Vec<(String, String)>,
351 urgency: Urgency,
352 timeout: Timeout,
353 image: Option<Image>,
354 desktop_entry: String,
355 category: String,
356 resident: bool,
357 transient: bool,
358 received: SystemTime,
359}
360
361#[derive(Serialize, Deserialize)]
363enum Image {
364 Name(String),
365 File(std::path::PathBuf),
366}
367
368impl Kept {
369 fn new(notification: &Notification) -> Kept {
370 let image = match ¬ification.image {
371 Some(IconSource::Name(name)) => Some(Image::Name(name.clone())),
372 Some(IconSource::File(path)) => Some(Image::File(path.clone())),
373 Some(IconSource::Pixels(_)) | None => None,
374 };
375 Kept {
376 id: notification.id,
377 app_name: notification.app_name.clone(),
378 app_icon: notification.app_icon.clone(),
379 summary: notification.summary.clone(),
380 body: notification.body.clone(),
381 actions: notification.actions.clone(),
382 urgency: notification.urgency,
383 timeout: notification.timeout,
384 image,
385 desktop_entry: notification.desktop_entry.clone(),
386 category: notification.category.clone(),
387 resident: notification.resident,
388 transient: notification.transient,
389 received: notification.received,
390 }
391 }
392
393 fn notification(self) -> Notification {
396 use server::{MAX_ACTIONS, MAX_BODY, MAX_SUMMARY, MAX_TEXT, cut, cut_markup};
397
398 let text = |text: &str| cut(text, MAX_TEXT);
399 let actions = self.actions.iter().take(MAX_ACTIONS);
400 let image = match self.image {
401 Some(Image::Name(name)) => Some(IconSource::Name(name)),
402 Some(Image::File(path)) => Some(IconSource::File(path)),
403 None => server::icon(&self.app_icon),
404 };
405 Notification {
406 id: self.id,
407 app_name: text(&self.app_name),
408 app_icon: text(&self.app_icon),
409 summary: cut(&self.summary, MAX_SUMMARY),
410 body: cut_markup(&self.body, MAX_BODY),
411 actions: actions
412 .map(|(key, label)| (text(key), text(label)))
413 .collect(),
414 urgency: self.urgency,
415 timeout: self.timeout,
416 image,
417 desktop_entry: text(&self.desktop_entry),
418 category: text(&self.category),
419 resident: self.resident,
420 transient: self.transient,
421 received: self.received,
422 }
423 }
424}
425
426struct State {
427 list: Signal<Vec<Notification>>,
428 popups: Signal<Vec<Notification>>,
429 connection: Option<Connection>,
431 serving: bool,
433 history: Vec<Notification>,
435 showing: Showing,
437 next_id: u32,
439 timer: Option<RegistrationToken>,
441 listeners: Vec<Listener>,
443 next_listener: u64,
445}
446
447impl State {
448 fn new_id(&mut self) -> u32 {
451 loop {
452 let id = self.next_id;
453 self.next_id = id.checked_add(1).unwrap_or(1);
454 if !self.history.iter().any(|kept| kept.id == id) {
455 return id;
456 }
457 }
458 }
459}
460
461type Showing = Vec<(u32, Option<Instant>)>;
464
465enum Event {
467 Closed(u32, CloseReason),
469 Invoked(u32, String),
471}
472
473impl Service {
474 pub(crate) fn new(shared: Rc<Shared>) -> Service {
475 Service {
476 shared,
477 state: RefCell::new(None),
478 body_markup: Cell::new(false),
479 saved: RefCell::new(None),
480 held: Cell::new(false),
481 handing_off: Cell::new(false),
482 handed_over: Cell::new(false),
483 saved_since_lost: Cell::new(false),
484 taking_from: RefCell::new(None),
485 }
486 }
487
488 fn release(self: &Rc<Self>) {
491 self.taking_from.take();
492 if self.held.replace(false) {
493 self.schedule();
494 }
495 }
496
497 pub(crate) fn taking_over(&self) -> bool {
500 self.taking_from.borrow().is_some()
501 }
502
503 pub(crate) fn save(&self) -> Option<serde_json::Value> {
507 let saved = self.kept()?;
508 self.handing_off.set(saved.owner.is_some());
509 self.saved_since_lost.set(true);
510 serde_json::to_value(saved)
511 .inspect_err(|error| tracing::warn!(%error, "the notifications couldn't be kept"))
512 .ok()
513 }
514
515 fn kept(&self) -> Option<Saved> {
518 let state = self.state.borrow();
519 let state = state.as_ref()?;
520 let now = Instant::now();
521 let showing = state.showing.iter().map(|(id, expires)| {
522 let left = expires.map(|at| at.saturating_duration_since(now).as_millis());
523 (
524 *id,
525 left.map(|left| u64::try_from(left).unwrap_or(u64::MAX)),
526 )
527 });
528 let owner = (state.connection.as_ref()).filter(|_| state.serving || self.handed_over.get());
529 let owner = owner.and_then(|connection| connection.unique_name());
530 Some(Saved {
531 next_id: state.next_id,
532 history: state.history.iter().map(Kept::new).collect(),
533 showing: showing.collect(),
534 owner: owner.map(|name| name.to_string()),
535 })
536 }
537
538 async fn hand_over(&self, connection: &Connection, caller: Option<&str>) -> Option<String> {
541 if !self.handing_off.get() {
542 return None;
543 }
544 let ask = connection.call_method(
545 Some(BUS),
546 BUS_PATH,
547 Some(BUS),
548 "GetNameOwner",
549 &NOTIFICATIONS,
550 );
551 let owner = self.shared.timeout(HANDOFF_LIMIT, ask).await.ok()?;
552 let owner = owner.body().deserialize::<String>().ok()?;
553 if caller != Some(owner.as_str()) || !self.handing_off.replace(false) {
554 return None;
555 }
556 tracing::info!("handing the notifications over to the new shell");
557 self.handed_over.set(true);
558 serde_json::to_string(&self.kept()?).ok()
559 }
560
561 async fn take_over(self: &Rc<Self>, connection: &Connection, from: &str) {
564 let ask = connection.call_method(Some(from), NOTIFICATIONS_PATH, Some(HANDOFF), "Take", &());
565 let answer = self.shared.timeout(HANDOFF_LIMIT, ask).await;
566 let text = match answer.and_then(|answer| answer.body().deserialize::<String>()) {
567 Ok(text) if text.len() <= MAX_HANDOFF => text,
568 Ok(text) => {
569 return tracing::warn!(
570 bytes = text.len(),
571 "the old shell's notifications are too big; keeping what it saved"
572 );
573 }
574 Err(error) => {
575 return tracing::warn!(%error, "the old shell didn't hand its notifications over; keeping what it saved");
576 }
577 };
578 let saved = match serde_json::from_str::<Saved>(&text) {
579 Ok(saved) => saved,
580 Err(error) => {
581 return tracing::warn!(%error, "the old shell's notifications don't fit; keeping what it saved");
582 }
583 };
584 let (history, showing, next_id) = restored(saved, Instant::now());
585 if let Some(state) = self.state.borrow_mut().as_mut() {
586 state.history = history;
587 state.showing = showing;
588 state.next_id = next_id;
589 }
590 tracing::info!("took the notifications over from the old shell");
591 self.changed();
592 }
593
594 pub(crate) fn restore(&self, saved: serde_json::Value) {
597 match serde_json::from_value::<Saved>(saved) {
598 Ok(saved) => *self.saved.borrow_mut() = Some(saved),
599 Err(error) => tracing::warn!(%error, "the notifications kept don't fit; starting empty"),
600 }
601 }
602
603 fn start(self: &Rc<Self>) -> (ReadSignal<Vec<Notification>>, ReadSignal<Vec<Notification>>) {
606 if let Some(state) = &*self.state.borrow() {
607 return (state.list.read_only(), state.popups.read_only());
608 }
609 let saved = self.saved.take();
610 let from = saved.as_ref().and_then(|saved| saved.owner.clone());
611 let (history, showing, next_id) = saved.map_or_else(
612 || (Vec::new(), Vec::new(), 1),
613 |saved| restored(saved, Instant::now()),
614 );
615 let popups_shown = showing.iter().filter_map(|(id, _)| {
616 history
617 .iter()
618 .find(|kept: &&Notification| kept.id == *id)
619 .cloned()
620 });
621 let list = self.shared.root.signal(history.clone());
622 let popups = self.shared.root.signal(popups_shown.collect());
623 *self.state.borrow_mut() = Some(State {
624 list,
625 popups,
626 connection: None,
627 serving: false,
628 history,
629 showing,
630 next_id,
631 timer: None,
632 listeners: Vec::new(),
633 next_listener: 0,
634 });
635 self.held.set(self.shared.config.session_bus.is_some());
636 if self.held.get() {
637 *self.taking_from.borrow_mut() = from;
638 }
639 self.schedule();
640 match self.shared.config.session_bus.clone() {
641 Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
642 None => tracing::info!("no session bus, so no notifications arrive"),
643 }
644 (list.read_only(), popups.read_only())
645 }
646
647 fn alive(&self) -> bool {
650 let state = self.state.borrow();
651 let alive = state.as_ref().and_then(|state| state.list.try_with(|_| ()));
652 alive.is_some()
653 }
654
655 fn serving(&self) -> bool {
656 let state = self.state.borrow();
657 state.as_ref().is_some_and(|state| state.serving)
658 }
659
660 fn notify(self: &Rc<Self>, replaces: u32, mut notification: Notification) -> u32 {
663 let now = Instant::now();
664 let expires = match (notification.urgency, notification.timeout) {
665 (Urgency::Critical, _) | (_, Timeout::Never) => None,
666 (_, Timeout::Default) => Some(now + self.shared.config.popup_timeout),
667 (_, Timeout::After(after)) => Some(now + after),
668 };
669 let (id, dropped) = {
670 let mut state = self.state.borrow_mut();
671 let Some(state) = state.as_mut() else {
672 return 0;
673 };
674 let id = match replaces {
677 0 => state.new_id(),
678 id => id,
679 };
680 notification.id = id;
681 match state.history.iter().position(|kept| kept.id == id) {
682 Some(at) => state.history[at] = notification,
683 None => state.history.push(notification),
684 }
685 match state.showing.iter_mut().find(|(shown, _)| *shown == id) {
686 Some(shown) => shown.1 = expires,
687 None => state.showing.insert(0, (id, expires)),
688 }
689 let excess = state.history.len().saturating_sub(MAX_KEPT);
690 let dropped: Vec<Notification> = state.history.drain(..excess).collect();
691 let history = &state.history;
692 state
693 .showing
694 .retain(|(id, _)| history.iter().any(|kept| kept.id == *id));
695 keep_pixels_within(&mut state.history, MAX_PIXELS_KEPT);
696 (id, dropped)
697 };
698 self.closed(Vec::new(), dropped, CloseReason::Expired);
699 id
700 }
701
702 fn close(self: &Rc<Self>, ids: &[u32], reason: CloseReason) -> bool {
705 let taken = self.take(ids);
706 if taken.is_empty() {
707 return false;
708 }
709 self.closed(Vec::new(), taken, reason);
710 true
711 }
712
713 fn invoke(self: &Rc<Self>, id: u32, key: &str) {
716 let resident = self.state.borrow().as_ref().and_then(|state| {
717 let kept = state.history.iter().find(|kept| kept.id == id)?;
718 let offered = kept.actions.iter().any(|(action, _)| action == key);
719 offered.then_some(kept.resident)
720 });
721 let Some(resident) = resident else {
722 return tracing::warn!(id, key, "no such notification action");
723 };
724 let events = vec![Event::Invoked(id, key.to_owned())];
725 let taken = if resident {
726 Vec::new()
727 } else {
728 self.take(&[id])
729 };
730 self.closed(events, taken, CloseReason::Dismissed);
731 }
732
733 fn take(&self, ids: &[u32]) -> Vec<Notification> {
736 let mut state = self.state.borrow_mut();
737 let Some(state) = state.as_mut() else {
738 return Vec::new();
739 };
740 let (taken, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut state.history)
741 .into_iter()
742 .partition(|kept| ids.contains(&kept.id));
743 state.history = kept;
744 state.showing.retain(|(id, _)| !ids.contains(id));
745 taken
746 }
747
748 fn closed(
751 self: &Rc<Self>,
752 mut events: Vec<Event>,
753 closed: Vec<Notification>,
754 reason: CloseReason,
755 ) {
756 events.extend(closed.iter().map(|gone| Event::Closed(gone.id, reason)));
757 self.emit(events);
758 self.changed();
759 self.deliver(&closed, reason);
760 }
761
762 fn listen(&self, handler: CloseHandler, at: &'static Location<'static>) -> u64 {
764 let mut state = self.state.borrow_mut();
765 let state = state
766 .as_mut()
767 .expect("invariant: started by cx.notifications()");
768 state.next_listener += 1;
769 let id = state.next_listener;
770 state.listeners.push(Listener { id, handler, at });
771 id
772 }
773
774 fn unlisten(&self, id: u64) -> Option<Listener> {
776 let mut state = self.state.borrow_mut();
777 let listeners = &mut state.as_mut()?.listeners;
778 let index = listeners.iter().position(|listener| listener.id == id)?;
779 Some(listeners.remove(index))
780 }
781
782 fn listening(&self, id: u64) -> bool {
783 let state = self.state.borrow();
784 let mut listeners = state.iter().flat_map(|state| &state.listeners);
785 listeners.any(|listener| listener.id == id)
786 }
787
788 fn deliver(&self, closed: &[Notification], reason: CloseReason) {
794 let listeners = match self.state.borrow().as_ref() {
795 Some(state) if !closed.is_empty() => state.listeners.clone(),
796 _ => return,
797 };
798 for gone in closed {
799 for Listener { id, handler, at } in &listeners {
800 if !self.listening(*id) {
802 continue;
803 }
804 let run = AssertUnwindSafe(|| untrack(|| handler(gone, reason)));
805 if let Err(payload) = panic::catch_unwind(run) {
806 let message = panic_message(payload.as_ref());
807 tracing::error!("notifications on_closed (called at {at}) panicked: {message}");
808 drop(self.unlisten(*id));
809 }
810 }
811 }
812 }
813
814 fn expire(self: &Rc<Self>) -> TimeoutAction {
817 if let Some(state) = self.state.borrow_mut().as_mut() {
818 state.timer = None;
820 }
821 if !self.alive() {
822 return TimeoutAction::Drop;
823 }
824 let now = Instant::now();
825 let transient = {
826 let mut state = self.state.borrow_mut();
827 let Some(state) = state.as_mut() else {
828 return TimeoutAction::Drop;
829 };
830 let (expired, showing) = std::mem::take(&mut state.showing)
831 .into_iter()
832 .partition::<Vec<_>, _>(|(_, expires)| expires.is_some_and(|at| at <= now));
833 state.showing = showing;
834 let history = state.history.iter();
835 let transient = history.filter(|kept| kept.transient);
836 transient
837 .map(|kept| kept.id)
838 .filter(|id| expired.iter().any(|(gone, _)| gone == id))
839 .collect::<Vec<_>>()
840 };
841 let taken = self.take(&transient);
842 self.closed(Vec::new(), taken, CloseReason::Expired);
843 TimeoutAction::Drop
844 }
845
846 fn changed(self: &Rc<Self>) {
849 let shown = self.state.borrow().as_ref().map(|state| {
851 let popups = state.showing.iter().filter_map(|(id, _)| {
852 let kept = state.history.iter().find(|kept| kept.id == *id);
853 kept.cloned()
854 });
855 let popups = popups.collect::<Vec<_>>();
856 (state.list, state.history.clone(), state.popups, popups)
857 });
858 if let Some((list_signal, list, popups_signal, popups)) = shown {
859 set_changed(list_signal, list);
860 set_changed(popups_signal, popups);
861 }
862 self.schedule();
863 }
864
865 fn schedule(self: &Rc<Self>) {
868 if self.held.get() {
869 return;
870 }
871 let Some(event_loop) = self.shared.event_loop() else {
872 return;
873 };
874 let mut state = self.state.borrow_mut();
875 let Some(state) = state.as_mut() else {
876 return;
877 };
878 if let Some(token) = state.timer.take() {
879 event_loop.remove(token);
880 }
881 let Some(next) = state.showing.iter().filter_map(|(_, at)| *at).min() else {
882 return;
883 };
884 let service = Rc::clone(self);
885 let tick = Box::new(move || service.expire());
886 state.timer = event_loop.insert_timer(next, tick);
887 }
888
889 fn emit(&self, events: Vec<Event>) {
891 let connection = {
892 let state = self.state.borrow();
893 let serving = state.as_ref().filter(|state| state.serving);
894 serving.and_then(|state| state.connection.clone())
895 };
896 let Some(connection) = connection.filter(|_| !events.is_empty()) else {
897 return;
898 };
899 self.shared.spawn(async move {
900 for event in events {
901 let (path, interface) = (NOTIFICATIONS_PATH, NOTIFICATIONS);
902 let sent = match &event {
903 Event::Closed(id, reason) => {
904 let body = (*id, reason.code());
905 let signal = "NotificationClosed";
906 let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
907 emit.await
908 }
909 Event::Invoked(id, key) => {
910 let body = (*id, key.as_str());
911 let signal = "ActionInvoked";
912 let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
913 emit.await
914 }
915 };
916 if let Err(error) = sent {
917 tracing::warn!(%error, "a notification signal wasn't sent");
918 }
919 }
920 });
921 }
922
923 async fn on_message(self: &Rc<Self>, connection: &Connection, message: &Message) {
925 match message.header().message_type() {
926 Kind::MethodCall => server::answer(self, connection, message).await,
927 Kind::Signal => self.on_signal(message),
928 _ => {}
929 }
930 }
931
932 fn on_signal(&self, message: &Message) {
934 let header = message.header();
935 let from_bus = header.sender().is_some_and(|sender| sender.as_str() == BUS);
936 let ours = message.body().deserialize::<&str>().ok() == Some(NOTIFICATIONS);
937 if !from_bus || !ours {
938 return;
939 }
940 let serving = match header.member().map(|member| member.as_str()) {
941 Some("NameAcquired") => {
942 tracing::info!("serving notifications");
943 if !self.saved_since_lost.get() {
946 self.handing_off.set(false);
947 }
948 self.handed_over.set(false);
949 true
950 }
951 Some("NameLost") => {
952 tracing::info!("another program took over notifications; waiting for it to leave");
953 self.handed_over.set(false);
954 self.saved_since_lost.set(false);
955 false
956 }
957 _ => return,
958 };
959 if let Some(state) = self.state.borrow_mut().as_mut() {
960 state.serving = serving;
961 }
962 }
963}
964
965async fn run(service: Rc<Service>, address: zbus::Address) {
968 let builder = zbus::connection::Builder::address(address);
969 let connection = match builder.build().await {
970 Ok(connection) => connection,
971 Err(error) => {
972 service.release();
973 return tracing::info!(%error, "can't reach the session bus, so no notifications arrive");
974 }
975 };
976 let mut messages = MessageStream::from(&connection);
978 if let Some(state) = service.state.borrow_mut().as_mut() {
979 state.connection = Some(connection.clone());
980 }
981 let from = service.taking_from.borrow().clone();
985 let mut flags = RequestNameFlags::ALLOW_REPLACEMENT;
986 if from.is_some() {
987 flags |= RequestNameFlags::REPLACE_EXISTING;
988 }
989 let requested = connection
990 .request_name_with_flags(NOTIFICATIONS, flags)
991 .await;
992 let owner = matches!(
993 requested,
994 Ok(RequestNameReply::PrimaryOwner | RequestNameReply::AlreadyOwner)
995 );
996 if owner && let Some(state) = service.state.borrow_mut().as_mut() {
997 state.serving = true;
999 }
1000 let mut held = Vec::new();
1004 if owner && let Some(from) = from {
1005 let mut take = pin!(service.take_over(&connection, &from));
1006 poll_fn(|cx| {
1007 while held.len() < MAX_HELD
1008 && let Poll::Ready(Some(message)) = Pin::new(&mut messages).poll_next(cx)
1009 {
1010 held.push(message);
1011 }
1012 take.as_mut().poll(cx)
1013 })
1014 .await;
1015 }
1016 service.release();
1017 for message in held {
1018 match message {
1019 Ok(message) => service.on_message(&connection, &message).await,
1020 Err(error) => tracing::warn!(%error, "a bad message on the session bus"),
1021 }
1022 }
1023 match requested {
1024 Ok(RequestNameReply::InQueue) => {
1025 tracing::info!("another program serves notifications; waiting for it to leave");
1026 }
1027 Ok(_) => {}
1028 Err(error) => return tracing::warn!(%error, "couldn't ask for the notifications name"),
1029 }
1030 loop {
1031 let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
1032 if !service.alive() {
1033 return;
1034 }
1035 match next {
1036 Some(Ok(message)) => service.on_message(&connection, &message).await,
1037 Some(Err(error)) => tracing::warn!(%error, "a bad message on the session bus"),
1038 None => break,
1039 }
1040 }
1041 tracing::warn!("the session bus closed, so no more notifications arrive");
1042 if let Some(state) = service.state.borrow_mut().as_mut() {
1043 state.serving = false;
1044 state.connection = None;
1045 }
1046}
1047
1048fn restored(saved: Saved, now: Instant) -> (Vec<Notification>, Showing, u32) {
1051 let mut history: Vec<Notification> = Vec::new();
1052 for kept in saved.history {
1053 if kept.id != 0 && !history.iter().any(|seen| seen.id == kept.id) {
1054 history.push(kept.notification());
1055 }
1056 }
1057 let excess = history.len().saturating_sub(MAX_KEPT);
1058 history.drain(..excess);
1059 let mut showing = Showing::new();
1060 for (id, left) in saved.showing {
1061 let known = history.iter().any(|kept| kept.id == id);
1062 if known && !showing.iter().any(|(shown, _)| *shown == id) {
1063 let left = left.map(Duration::from_millis);
1064 showing.push((id, left.map(|left| now.checked_add(left).unwrap_or(now))));
1065 }
1066 }
1067 (history, showing, saved.next_id.max(1))
1068}
1069
1070fn keep_pixels_within(history: &mut [Notification], budget: usize) {
1073 let mut total = 0;
1074 for kept in history.iter_mut().rev() {
1075 let Some(IconSource::Pixels(pixels)) = &kept.image else {
1076 continue;
1077 };
1078 let bytes = pixels.data.len();
1079 if total + bytes <= budget {
1080 total += bytes;
1081 } else {
1082 tracing::debug!(
1083 id = kept.id,
1084 "past the pictures' budget; showing the app icon"
1085 );
1086 kept.image = server::icon(&kept.app_icon);
1087 }
1088 }
1089}