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);
64
65const MAX_KEPT: usize = 256;
68
69const MAX_PIXELS_KEPT: usize = 8 * 1024 * 1024;
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum CloseReason {
76 Expired,
79 Dismissed,
82 CloseRequested,
84}
85
86impl CloseReason {
87 fn code(self) -> u32 {
89 match self {
90 CloseReason::Expired => 1,
91 CloseReason::Dismissed => 2,
92 CloseReason::CloseRequested => 3,
93 }
94 }
95}
96
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99pub enum Urgency {
100 Low,
102 #[default]
104 Normal,
105 Critical,
108}
109
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
112pub enum Timeout {
113 #[default]
116 Default,
117 Never,
119 After(Duration),
121}
122
123#[derive(Clone, Debug, PartialEq)]
125pub struct Notification {
126 pub id: u32,
130 pub app_name: String,
132 pub app_icon: String,
135 pub summary: String,
137 pub body: String,
142 pub actions: Vec<(String, String)>,
145 pub urgency: Urgency,
147 pub timeout: Timeout,
149 pub image: Option<IconSource>,
152 pub desktop_entry: String,
154 pub category: String,
156 pub resident: bool,
158 pub transient: bool,
161 pub received: SystemTime,
163}
164
165#[derive(Clone)]
168pub struct Notifications {
169 service: Option<Rc<Service>>,
171 list: ReadSignal<Vec<Notification>>,
172 popups: ReadSignal<Vec<Notification>>,
173 owner: Owner,
176}
177
178impl Notifications {
179 pub fn list(&self) -> ReadSignal<Vec<Notification>> {
183 self.list
184 }
185
186 pub fn popups(&self) -> ReadSignal<Vec<Notification>> {
192 self.popups
193 }
194
195 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 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 pub fn hide_popup(&self, id: u32) {
222 if let Some(service) = &self.service {
223 service.hide(&[id]);
224 }
225 }
226
227 pub fn popup_time_left(&self, id: u32) -> Option<(Duration, Duration)> {
261 self.service.as_ref()?.time_left(id)
262 }
263
264 pub fn dismiss(&self, id: u32) {
267 if let Some(service) = &self.service {
268 service.close(&[id], CloseReason::Dismissed);
269 }
270 }
271
272 pub fn invoke(&self, id: u32, key: &str) {
276 if let Some(service) = &self.service {
277 service.invoke(id, key);
278 }
279 }
280
281 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 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 #[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 #[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 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 self.owner.signal(Unlisten(Rc::clone(service), id));
343 }
344 }
345}
346
347type CloseHandler = Rc<dyn Fn(&Notification, CloseReason)>;
349
350#[derive(Clone)]
352enum Handler {
353 Closed(CloseHandler),
354 Arrived(Rc<dyn Fn(&Notification)>),
355}
356
357impl Handler {
358 fn name(&self) -> &'static str {
360 match self {
361 Handler::Closed(_) => "on_closed",
362 Handler::Arrived(_) => "on_notification",
363 }
364 }
365}
366
367#[derive(Clone)]
369struct Listener {
370 id: u64,
371 handler: Handler,
372 at: &'static Location<'static>,
374}
375
376struct Unlisten(Rc<Service>, u64);
378
379impl Drop for Unlisten {
380 fn drop(&mut self) {
381 drop(self.0.unlisten(self.1));
383 }
384}
385
386pub(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
409pub(crate) struct Service {
411 shared: Rc<Shared>,
412 state: RefCell<Option<State>>,
413 body_markup: Cell<bool>,
415 default_timeout: Cell<Duration>,
417 saved: RefCell<Option<Saved>>,
419 held: Cell<bool>,
422 handing_off: Cell<bool>,
425 handed_over: Cell<bool>,
429 saved_since_lost: Cell<bool>,
432 taking_from: RefCell<Option<String>>,
435}
436
437#[derive(Serialize, Deserialize)]
440struct Saved {
441 next_id: u32,
442 history: Vec<Kept>,
443 showing: Vec<(u32, Option<u64>)>,
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
450 whole: Vec<(u32, u64)>,
451 #[serde(default, skip_serializing_if = "Option::is_none")]
454 owner: Option<String>,
455}
456
457#[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#[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 ¬ification.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 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 connection: Option<Connection>,
547 serving: bool,
549 history: Vec<Notification>,
551 showing: Showing,
553 next_id: u32,
555 timer: Option<RegistrationToken>,
557 listeners: Vec<Listener>,
559 next_listener: u64,
561}
562
563impl State {
564 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
577type Showing = Vec<Popup>;
579
580#[derive(Clone, Copy)]
582struct Popup {
583 id: u32,
584 timeout: Option<Duration>,
586 left: Duration,
588 since: Instant,
590 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 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 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
633enum Event {
635 Closed(u32, CloseReason),
637 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 fn release(self: &Rc<Self>) {
660 self.taking_from.take();
661 if self.held.replace(false) {
662 self.schedule();
663 }
664 }
665
666 pub(crate) fn taking_over(&self) -> bool {
669 self.taking_from.borrow().is_some()
670 }
671
672 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 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 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 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 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 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 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 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 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 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 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 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 let whole = popup.timeout.filter(|whole| !whole.is_zero())?;
904 Some((popup.left(Instant::now())?, whole))
905 }
906
907 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 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 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 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 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 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 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 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 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 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 fn expire(self: &Rc<Self>) -> TimeoutAction {
1047 if let Some(state) = self.state.borrow_mut().as_mut() {
1048 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 fn changed(self: &Rc<Self>) {
1069 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 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 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 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 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 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
1185async 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 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 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 state.serving = true;
1219 }
1220 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
1268fn 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 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
1301fn 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}