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 restart_popup(&self, id: u32) {
224 if let Some(service) = &self.service {
225 service.restart(id);
226 }
227 }
228
229 pub fn hide_popup(&self, id: u32) {
235 if let Some(service) = &self.service {
236 service.hide(&[id]);
237 }
238 }
239
240 pub fn popup_time_left(&self, id: u32) -> Option<(Duration, Duration)> {
274 self.service.as_ref()?.time_left(id)
275 }
276
277 pub fn dismiss(&self, id: u32) {
280 if let Some(service) = &self.service {
281 service.close(&[id], CloseReason::Dismissed);
282 }
283 }
284
285 pub fn invoke(&self, id: u32, key: &str) {
289 if let Some(service) = &self.service {
290 service.invoke(id, key);
291 }
292 }
293
294 pub fn set_body_markup(&self, on: bool) {
299 if let Some(service) = &self.service {
300 service.body_markup.set(on);
301 }
302 }
303
304 pub fn clear(&self) {
306 if let Some(service) = &self.service {
307 let state = service.state.borrow();
308 let history = state.as_ref().map(|state| state.history.as_slice());
309 let ids: Vec<u32> = history.unwrap_or_default().iter().map(|n| n.id).collect();
310 drop(state);
311 service.close(&ids, CloseReason::Dismissed);
312 }
313 }
314
315 #[track_caller]
325 pub fn on_closed(&self, handler: impl Fn(&Notification, CloseReason) + 'static) {
326 self.listen(Handler::Closed(Rc::new(handler)), Location::caller());
327 }
328
329 #[track_caller]
340 pub fn on_notification(&self, handler: impl Fn(&Notification) + 'static) {
341 self.listen(Handler::Arrived(Rc::new(handler)), Location::caller());
342 }
343
344 fn listen(&self, handler: Handler, at: &'static Location<'static>) {
346 if self.owner.is_disposed() {
347 let name = handler.name();
348 return tracing::warn!(
349 "notifications {name} (called at {at}) on a context that is gone does nothing"
350 );
351 }
352 if let Some(service) = &self.service {
353 let id = service.listen(handler, at);
354 self.owner.signal(Unlisten(Rc::clone(service), id));
356 }
357 }
358}
359
360type CloseHandler = Rc<dyn Fn(&Notification, CloseReason)>;
362
363#[derive(Clone)]
365enum Handler {
366 Closed(CloseHandler),
367 Arrived(Rc<dyn Fn(&Notification)>),
368}
369
370impl Handler {
371 fn name(&self) -> &'static str {
373 match self {
374 Handler::Closed(_) => "on_closed",
375 Handler::Arrived(_) => "on_notification",
376 }
377 }
378}
379
380#[derive(Clone)]
382struct Listener {
383 id: u64,
384 handler: Handler,
385 at: &'static Location<'static>,
387}
388
389struct Unlisten(Rc<Service>, u64);
391
392impl Drop for Unlisten {
393 fn drop(&mut self) {
394 drop(self.0.unlisten(self.1));
396 }
397}
398
399pub(crate) fn notifications(cx: &Cx) -> Notifications {
401 let Some(service) = cx.service::<Service>() else {
402 static LOGGED: Once = Once::new();
403 LOGGED.call_once(|| {
404 tracing::warn!("cx.notifications() needs the services the shell provides; none arrive");
405 });
406 return Notifications {
407 service: None,
408 list: cx.signal(Vec::new()).read_only(),
409 popups: cx.signal(Vec::new()).read_only(),
410 owner: cx.owner(),
411 };
412 };
413 let (list, popups) = service.start();
414 Notifications {
415 service: Some(service),
416 list,
417 popups,
418 owner: cx.owner(),
419 }
420}
421
422pub(crate) struct Service {
424 shared: Rc<Shared>,
425 state: RefCell<Option<State>>,
426 body_markup: Cell<bool>,
428 default_timeout: Cell<Duration>,
430 saved: RefCell<Option<Saved>>,
432 held: Cell<bool>,
435 handing_off: Cell<bool>,
438 handed_over: Cell<bool>,
442 saved_since_lost: Cell<bool>,
445 taking_from: RefCell<Option<String>>,
448}
449
450#[derive(Serialize, Deserialize)]
453struct Saved {
454 next_id: u32,
455 history: Vec<Kept>,
456 showing: Vec<(u32, Option<u64>)>,
459 #[serde(default, skip_serializing_if = "Vec::is_empty")]
463 whole: Vec<(u32, u64)>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
467 owner: Option<String>,
468}
469
470#[derive(Serialize, Deserialize)]
473struct Kept {
474 id: u32,
475 app_name: String,
476 app_icon: String,
477 summary: String,
478 body: String,
479 actions: Vec<(String, String)>,
480 urgency: Urgency,
481 timeout: Timeout,
482 image: Option<Image>,
483 desktop_entry: String,
484 category: String,
485 resident: bool,
486 transient: bool,
487 received: SystemTime,
488}
489
490#[derive(Serialize, Deserialize)]
492enum Image {
493 Name(String),
494 File(std::path::PathBuf),
495}
496
497impl Kept {
498 fn new(notification: &Notification) -> Kept {
499 let image = match ¬ification.image {
500 Some(IconSource::Name(name)) => Some(Image::Name(name.clone())),
501 Some(IconSource::File(path)) => Some(Image::File(path.clone())),
502 Some(IconSource::Pixels(_)) | None => None,
503 };
504 Kept {
505 id: notification.id,
506 app_name: notification.app_name.clone(),
507 app_icon: notification.app_icon.clone(),
508 summary: notification.summary.clone(),
509 body: notification.body.clone(),
510 actions: notification.actions.clone(),
511 urgency: notification.urgency,
512 timeout: notification.timeout,
513 image,
514 desktop_entry: notification.desktop_entry.clone(),
515 category: notification.category.clone(),
516 resident: notification.resident,
517 transient: notification.transient,
518 received: notification.received,
519 }
520 }
521
522 fn notification(self) -> Notification {
525 use server::{MAX_ACTIONS, MAX_BODY, MAX_SUMMARY, MAX_TEXT, cut, cut_markup};
526
527 let text = |text: &str| cut(text, MAX_TEXT);
528 let actions = self.actions.iter().take(MAX_ACTIONS);
529 let image = match self.image {
530 Some(Image::Name(name)) => Some(IconSource::Name(name)),
531 Some(Image::File(path)) => Some(IconSource::File(path)),
532 None => server::icon(&self.app_icon),
533 };
534 Notification {
535 id: self.id,
536 app_name: text(&self.app_name),
537 app_icon: text(&self.app_icon),
538 summary: cut(&self.summary, MAX_SUMMARY),
539 body: cut_markup(&self.body, MAX_BODY),
540 actions: actions
541 .map(|(key, label)| (text(key), text(label)))
542 .collect(),
543 urgency: self.urgency,
544 timeout: self.timeout,
545 image,
546 desktop_entry: text(&self.desktop_entry),
547 category: text(&self.category),
548 resident: self.resident,
549 transient: self.transient,
550 received: self.received,
551 }
552 }
553}
554
555struct State {
556 list: Signal<Vec<Notification>>,
557 popups: Signal<Vec<Notification>>,
558 connection: Option<Connection>,
560 serving: bool,
562 history: Vec<Notification>,
564 showing: Showing,
566 next_id: u32,
568 timer: Option<RegistrationToken>,
570 listeners: Vec<Listener>,
572 next_listener: u64,
574}
575
576impl State {
577 fn new_id(&mut self) -> u32 {
580 loop {
581 let id = self.next_id;
582 self.next_id = id.checked_add(1).unwrap_or(1);
583 if !self.history.iter().any(|kept| kept.id == id) {
584 return id;
585 }
586 }
587 }
588}
589
590type Showing = Vec<Popup>;
592
593#[derive(Clone, Copy)]
595struct Popup {
596 id: u32,
597 timeout: Option<Duration>,
599 left: Duration,
601 since: Instant,
603 held: bool,
605}
606
607impl Popup {
608 fn new(id: u32, timeout: Option<Duration>, now: Instant) -> Popup {
609 Popup {
610 id,
611 timeout,
612 left: timeout.unwrap_or_default(),
613 since: now,
614 held: false,
615 }
616 }
617
618 fn left(&self, now: Instant) -> Option<Duration> {
620 self.timeout?;
621 match self.held {
622 true => Some(self.left),
623 false => Some(
624 self
625 .left
626 .saturating_sub(now.saturating_duration_since(self.since)),
627 ),
628 }
629 }
630
631 fn expires(&self) -> Option<Instant> {
633 self.timeout.filter(|_| !self.held)?;
634 self.since.checked_add(self.left)
635 }
636
637 fn hold(&mut self, held: bool, now: Instant) {
638 if held != self.held {
639 self.left = self.left(now).unwrap_or(self.left);
640 self.since = now;
641 self.held = held;
642 }
643 }
644}
645
646enum Event {
648 Closed(u32, CloseReason),
650 Invoked(u32, String),
652}
653
654impl Service {
655 pub(crate) fn new(shared: Rc<Shared>) -> Service {
656 Service {
657 default_timeout: Cell::new(shared.config.popup_timeout),
658 shared,
659 state: RefCell::new(None),
660 body_markup: Cell::new(false),
661 saved: RefCell::new(None),
662 held: Cell::new(false),
663 handing_off: Cell::new(false),
664 handed_over: Cell::new(false),
665 saved_since_lost: Cell::new(false),
666 taking_from: RefCell::new(None),
667 }
668 }
669
670 fn release(self: &Rc<Self>) {
673 self.taking_from.take();
674 if self.held.replace(false) {
675 self.schedule();
676 }
677 }
678
679 pub(crate) fn taking_over(&self) -> bool {
682 self.taking_from.borrow().is_some()
683 }
684
685 pub(crate) fn save(&self) -> Option<serde_json::Value> {
689 let saved = self.kept()?;
690 self.handing_off.set(saved.owner.is_some());
691 self.saved_since_lost.set(true);
692 serde_json::to_value(saved)
693 .inspect_err(|error| tracing::warn!(%error, "the notifications couldn't be kept"))
694 .ok()
695 }
696
697 fn kept(&self) -> Option<Saved> {
700 let state = self.state.borrow();
701 let state = state.as_ref()?;
702 let now = Instant::now();
703 let ms = |time: Duration| u64::try_from(time.as_millis()).unwrap_or(u64::MAX);
704 let showing = (state.showing.iter()).map(|popup| (popup.id, popup.left(now).map(ms)));
705 let whole = (state.showing.iter()).filter_map(|popup| Some((popup.id, ms(popup.timeout?))));
706 let owner = (state.connection.as_ref()).filter(|_| state.serving || self.handed_over.get());
707 let owner = owner.and_then(|connection| connection.unique_name());
708 Some(Saved {
709 next_id: state.next_id,
710 history: state.history.iter().map(Kept::new).collect(),
711 showing: showing.collect(),
712 whole: whole.collect(),
713 owner: owner.map(|name| name.to_string()),
714 })
715 }
716
717 async fn hand_over(&self, connection: &Connection, caller: Option<&str>) -> Option<String> {
720 if !self.handing_off.get() {
721 return None;
722 }
723 let ask = connection.call_method(
724 Some(BUS),
725 BUS_PATH,
726 Some(BUS),
727 "GetNameOwner",
728 &NOTIFICATIONS,
729 );
730 let owner = self.shared.timeout(HANDOFF_LIMIT, ask).await.ok()?;
731 let owner = owner.body().deserialize::<String>().ok()?;
732 if caller != Some(owner.as_str()) || !self.handing_off.replace(false) {
733 return None;
734 }
735 tracing::info!("handing the notifications over to the new shell");
736 self.handed_over.set(true);
737 serde_json::to_string(&self.kept()?).ok()
738 }
739
740 async fn take_over(self: &Rc<Self>, connection: &Connection, from: &str) {
743 let ask = connection.call_method(Some(from), NOTIFICATIONS_PATH, Some(HANDOFF), "Take", &());
744 let answer = self.shared.timeout(HANDOFF_LIMIT, ask).await;
745 let text = match answer.and_then(|answer| answer.body().deserialize::<String>()) {
746 Ok(text) if text.len() <= MAX_HANDOFF => text,
747 Ok(text) => {
748 return tracing::warn!(
749 bytes = text.len(),
750 "the old shell's notifications are too big; keeping what it saved"
751 );
752 }
753 Err(error) => {
754 return tracing::warn!(%error, "the old shell didn't hand its notifications over; keeping what it saved");
755 }
756 };
757 let saved = match serde_json::from_str::<Saved>(&text) {
758 Ok(saved) => saved,
759 Err(error) => {
760 return tracing::warn!(%error, "the old shell's notifications don't fit; keeping what it saved");
761 }
762 };
763 let (history, showing, next_id) = restored(saved, Instant::now());
764 if let Some(state) = self.state.borrow_mut().as_mut() {
765 state.history = history;
766 state.showing = showing;
767 state.next_id = next_id;
768 }
769 tracing::info!("took the notifications over from the old shell");
770 self.changed();
771 }
772
773 pub(crate) fn restore(&self, saved: serde_json::Value) {
776 match serde_json::from_value::<Saved>(saved) {
777 Ok(saved) => *self.saved.borrow_mut() = Some(saved),
778 Err(error) => tracing::warn!(%error, "the notifications kept don't fit; starting empty"),
779 }
780 }
781
782 fn start(self: &Rc<Self>) -> (ReadSignal<Vec<Notification>>, ReadSignal<Vec<Notification>>) {
785 if let Some(state) = &*self.state.borrow() {
786 return (state.list.read_only(), state.popups.read_only());
787 }
788 let saved = self.saved.take();
789 let from = saved.as_ref().and_then(|saved| saved.owner.clone());
790 let (history, showing, next_id) = saved.map_or_else(
791 || (Vec::new(), Vec::new(), 1),
792 |saved| restored(saved, Instant::now()),
793 );
794 let popups_shown = showing.iter().filter_map(|popup| {
795 history
796 .iter()
797 .find(|kept: &&Notification| kept.id == popup.id)
798 .cloned()
799 });
800 let list = self.shared.root.signal(history.clone());
801 let popups = self.shared.root.signal(popups_shown.collect());
802 *self.state.borrow_mut() = Some(State {
803 list,
804 popups,
805 connection: None,
806 serving: false,
807 history,
808 showing,
809 next_id,
810 timer: None,
811 listeners: Vec::new(),
812 next_listener: 0,
813 });
814 self.held.set(self.shared.config.session_bus.is_some());
815 if self.held.get() {
816 *self.taking_from.borrow_mut() = from;
817 }
818 self.schedule();
819 match self.shared.config.session_bus.clone() {
820 Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
821 None => tracing::info!("no session bus, so no notifications arrive"),
822 }
823 (list.read_only(), popups.read_only())
824 }
825
826 fn alive(&self) -> bool {
829 let state = self.state.borrow();
830 let alive = state.as_ref().and_then(|state| state.list.try_with(|_| ()));
831 alive.is_some()
832 }
833
834 fn serving(&self) -> bool {
835 let state = self.state.borrow();
836 state.as_ref().is_some_and(|state| state.serving)
837 }
838
839 fn notify(self: &Rc<Self>, replaces: u32, mut notification: Notification) -> u32 {
842 let now = Instant::now();
843 let timeout = match (notification.urgency, notification.timeout) {
844 (Urgency::Critical, _) | (_, Timeout::Never) => None,
845 (_, Timeout::Default) => Some(self.default_timeout.get()),
846 (_, Timeout::After(after)) => Some(after),
847 };
848 let timeout = timeout.filter(|timeout| now.checked_add(*timeout).is_some());
849 let (id, arrived, dropped) = {
850 let mut state = self.state.borrow_mut();
851 let Some(state) = state.as_mut() else {
852 return 0;
853 };
854 let id = match replaces {
857 0 => state.new_id(),
858 id => id,
859 };
860 notification.id = id;
861 let arrived = notification.clone();
862 match state.history.iter().position(|kept| kept.id == id) {
863 Some(at) => state.history[at] = notification,
864 None => state.history.push(notification),
865 }
866 let popup = Popup::new(id, timeout, now);
867 match state.showing.iter_mut().find(|shown| shown.id == id) {
868 Some(shown) => {
869 *shown = Popup {
870 held: shown.held,
871 ..popup
872 }
873 }
874 None => state.showing.insert(0, popup),
875 }
876 let excess = state.history.len().saturating_sub(MAX_KEPT);
877 let dropped: Vec<Notification> = state.history.drain(..excess).collect();
878 let history = &state.history;
879 state
880 .showing
881 .retain(|popup| history.iter().any(|kept| kept.id == popup.id));
882 keep_pixels_within(&mut state.history, MAX_PIXELS_KEPT);
883 (id, arrived, dropped)
884 };
885 self.each_handler(|handler| {
887 if let Handler::Arrived(handler) = handler {
888 handler(&arrived);
889 }
890 });
891 self.closed(Vec::new(), dropped, CloseReason::Expired);
892 id
893 }
894
895 fn hold(self: &Rc<Self>, id: u32, held: bool) {
898 if let Some(state) = self.state.borrow_mut().as_mut()
899 && let Some(popup) = state.showing.iter_mut().find(|popup| popup.id == id)
900 {
901 popup.hold(held, Instant::now());
902 }
903 self.schedule();
904 }
905
906 fn restart(self: &Rc<Self>, id: u32) {
909 if let Some(state) = self.state.borrow_mut().as_mut()
910 && let Some(popup) = state.showing.iter_mut().find(|popup| popup.id == id)
911 {
912 *popup = Popup {
913 held: popup.held,
914 ..Popup::new(id, popup.timeout, Instant::now())
915 };
916 }
917 self.schedule();
918 }
919
920 fn time_left(&self, id: u32) -> Option<(Duration, Duration)> {
923 let state = self.state.borrow();
924 let popup = state
925 .as_ref()?
926 .showing
927 .iter()
928 .find(|popup| popup.id == id)?;
929 let whole = popup.timeout.filter(|whole| !whole.is_zero())?;
931 Some((popup.left(Instant::now())?, whole))
932 }
933
934 fn hide(self: &Rc<Self>, ids: &[u32]) {
937 let transient = {
938 let mut state = self.state.borrow_mut();
939 let Some(state) = state.as_mut() else {
940 return;
941 };
942 state.showing.retain(|popup| !ids.contains(&popup.id));
943 let history = state.history.iter();
944 let transient = history.filter(|kept| kept.transient && ids.contains(&kept.id));
945 transient.map(|kept| kept.id).collect::<Vec<_>>()
946 };
947 let taken = self.take(&transient);
948 self.closed(Vec::new(), taken, CloseReason::Expired);
949 }
950
951 fn close(self: &Rc<Self>, ids: &[u32], reason: CloseReason) -> bool {
954 let taken = self.take(ids);
955 if taken.is_empty() {
956 return false;
957 }
958 self.closed(Vec::new(), taken, reason);
959 true
960 }
961
962 fn invoke(self: &Rc<Self>, id: u32, key: &str) {
965 let resident = self.state.borrow().as_ref().and_then(|state| {
966 let kept = state.history.iter().find(|kept| kept.id == id)?;
967 let offered = kept.actions.iter().any(|(action, _)| action == key);
968 offered.then_some(kept.resident)
969 });
970 let Some(resident) = resident else {
971 return tracing::warn!(id, key, "no such notification action");
972 };
973 let events = vec![Event::Invoked(id, key.to_owned())];
974 let taken = if resident {
975 Vec::new()
976 } else {
977 self.take(&[id])
978 };
979 self.closed(events, taken, CloseReason::Dismissed);
980 }
981
982 fn take(&self, ids: &[u32]) -> Vec<Notification> {
985 let mut state = self.state.borrow_mut();
986 let Some(state) = state.as_mut() else {
987 return Vec::new();
988 };
989 let (taken, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut state.history)
990 .into_iter()
991 .partition(|kept| ids.contains(&kept.id));
992 state.history = kept;
993 state.showing.retain(|popup| !ids.contains(&popup.id));
994 taken
995 }
996
997 fn closed(
1000 self: &Rc<Self>,
1001 mut events: Vec<Event>,
1002 closed: Vec<Notification>,
1003 reason: CloseReason,
1004 ) {
1005 events.extend(closed.iter().map(|gone| Event::Closed(gone.id, reason)));
1006 self.emit(events);
1007 self.changed();
1008 self.deliver(&closed, reason);
1009 }
1010
1011 fn listen(&self, handler: Handler, at: &'static Location<'static>) -> u64 {
1013 let mut state = self.state.borrow_mut();
1014 let state = state
1015 .as_mut()
1016 .expect("invariant: started by cx.notifications()");
1017 state.next_listener += 1;
1018 let id = state.next_listener;
1019 state.listeners.push(Listener { id, handler, at });
1020 id
1021 }
1022
1023 fn unlisten(&self, id: u64) -> Option<Listener> {
1025 let mut state = self.state.borrow_mut();
1026 let listeners = &mut state.as_mut()?.listeners;
1027 let index = listeners.iter().position(|listener| listener.id == id)?;
1028 Some(listeners.remove(index))
1029 }
1030
1031 fn listening(&self, id: u64) -> bool {
1032 let state = self.state.borrow();
1033 let mut listeners = state.iter().flat_map(|state| &state.listeners);
1034 listeners.any(|listener| listener.id == id)
1035 }
1036
1037 fn deliver(&self, closed: &[Notification], reason: CloseReason) {
1039 for gone in closed {
1040 self.each_handler(|handler| {
1041 if let Handler::Closed(handler) = handler {
1042 handler(gone, reason);
1043 }
1044 });
1045 }
1046 }
1047
1048 fn each_handler(&self, call: impl Fn(&Handler)) {
1054 let listeners = match self.state.borrow().as_ref() {
1055 Some(state) => state.listeners.clone(),
1056 None => return,
1057 };
1058 for Listener { id, handler, at } in &listeners {
1059 if !self.listening(*id) {
1061 continue;
1062 }
1063 let run = AssertUnwindSafe(|| untrack(|| call(handler)));
1064 if let Err(payload) = panic::catch_unwind(run) {
1065 let (name, message) = (handler.name(), panic_message(payload.as_ref()));
1066 tracing::error!("notifications {name} (called at {at}) panicked: {message}");
1067 drop(self.unlisten(*id));
1068 }
1069 }
1070 }
1071
1072 fn expire(self: &Rc<Self>) -> TimeoutAction {
1074 if let Some(state) = self.state.borrow_mut().as_mut() {
1075 state.timer = None;
1077 }
1078 if !self.alive() {
1079 return TimeoutAction::Drop;
1080 }
1081 let now = Instant::now();
1082 let expired = self.state.borrow().as_ref().map(|state| {
1083 let showing = state.showing.iter();
1084 let expired = showing.filter(|popup| popup.expires().is_some_and(|at| at <= now));
1085 expired.map(|popup| popup.id).collect::<Vec<_>>()
1086 });
1087 if let Some(expired) = expired {
1088 self.hide(&expired);
1089 }
1090 TimeoutAction::Drop
1091 }
1092
1093 fn changed(self: &Rc<Self>) {
1096 let shown = self.state.borrow().as_ref().map(|state| {
1098 let popups = state.showing.iter().filter_map(|popup| {
1099 let kept = state.history.iter().find(|kept| kept.id == popup.id);
1100 kept.cloned()
1101 });
1102 let popups = popups.collect::<Vec<_>>();
1103 (state.list, state.history.clone(), state.popups, popups)
1104 });
1105 if let Some((list_signal, list, popups_signal, popups)) = shown {
1106 set_changed(list_signal, list);
1107 set_changed(popups_signal, popups);
1108 }
1109 self.schedule();
1110 }
1111
1112 fn schedule(self: &Rc<Self>) {
1115 if self.held.get() {
1116 return;
1117 }
1118 let Some(event_loop) = self.shared.event_loop() else {
1119 return;
1120 };
1121 let mut state = self.state.borrow_mut();
1122 let Some(state) = state.as_mut() else {
1123 return;
1124 };
1125 if let Some(token) = state.timer.take() {
1126 event_loop.remove(token);
1127 }
1128 let Some(next) = state.showing.iter().filter_map(Popup::expires).min() else {
1129 return;
1130 };
1131 let service = Rc::clone(self);
1132 let tick = Box::new(move || service.expire());
1133 state.timer = event_loop.insert_timer(next, tick);
1134 }
1135
1136 fn emit(&self, events: Vec<Event>) {
1138 let connection = {
1139 let state = self.state.borrow();
1140 let serving = state.as_ref().filter(|state| state.serving);
1141 serving.and_then(|state| state.connection.clone())
1142 };
1143 let Some(connection) = connection.filter(|_| !events.is_empty()) else {
1144 return;
1145 };
1146 self.shared.spawn(async move {
1147 for event in events {
1148 let (path, interface) = (NOTIFICATIONS_PATH, NOTIFICATIONS);
1149 let sent = match &event {
1150 Event::Closed(id, reason) => {
1151 let body = (*id, reason.code());
1152 let signal = "NotificationClosed";
1153 let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
1154 emit.await
1155 }
1156 Event::Invoked(id, key) => {
1157 let body = (*id, key.as_str());
1158 let signal = "ActionInvoked";
1159 let emit = connection.emit_signal(None::<&str>, path, interface, signal, &body);
1160 emit.await
1161 }
1162 };
1163 if let Err(error) = sent {
1164 tracing::warn!(%error, "a notification signal wasn't sent");
1165 }
1166 }
1167 });
1168 }
1169
1170 async fn on_message(self: &Rc<Self>, connection: &Connection, message: &Message) {
1172 match message.header().message_type() {
1173 Kind::MethodCall => server::answer(self, connection, message).await,
1174 Kind::Signal => self.on_signal(message),
1175 _ => {}
1176 }
1177 }
1178
1179 fn on_signal(&self, message: &Message) {
1181 let header = message.header();
1182 let from_bus = header.sender().is_some_and(|sender| sender.as_str() == BUS);
1183 let ours = message.body().deserialize::<&str>().ok() == Some(NOTIFICATIONS);
1184 if !from_bus || !ours {
1185 return;
1186 }
1187 let serving = match header.member().map(|member| member.as_str()) {
1188 Some("NameAcquired") => {
1189 tracing::info!("serving notifications");
1190 if !self.saved_since_lost.get() {
1193 self.handing_off.set(false);
1194 }
1195 self.handed_over.set(false);
1196 true
1197 }
1198 Some("NameLost") => {
1199 tracing::info!("another program took over notifications; waiting for it to leave");
1200 self.handed_over.set(false);
1201 self.saved_since_lost.set(false);
1202 false
1203 }
1204 _ => return,
1205 };
1206 if let Some(state) = self.state.borrow_mut().as_mut() {
1207 state.serving = serving;
1208 }
1209 }
1210}
1211
1212async fn run(service: Rc<Service>, address: zbus::Address) {
1215 let builder = zbus::connection::Builder::address(address);
1216 let connection = match builder.build().await {
1217 Ok(connection) => connection,
1218 Err(error) => {
1219 service.release();
1220 return tracing::info!(%error, "can't reach the session bus, so no notifications arrive");
1221 }
1222 };
1223 let mut messages = MessageStream::from(&connection);
1225 if let Some(state) = service.state.borrow_mut().as_mut() {
1226 state.connection = Some(connection.clone());
1227 }
1228 let from = service.taking_from.borrow().clone();
1232 let mut flags = RequestNameFlags::ALLOW_REPLACEMENT;
1233 if from.is_some() {
1234 flags |= RequestNameFlags::REPLACE_EXISTING;
1235 }
1236 let requested = connection
1237 .request_name_with_flags(NOTIFICATIONS, flags)
1238 .await;
1239 let owner = matches!(
1240 requested,
1241 Ok(RequestNameReply::PrimaryOwner | RequestNameReply::AlreadyOwner)
1242 );
1243 if owner && let Some(state) = service.state.borrow_mut().as_mut() {
1244 state.serving = true;
1246 }
1247 let mut held = Vec::new();
1251 if owner && let Some(from) = from {
1252 let mut take = pin!(service.take_over(&connection, &from));
1253 poll_fn(|cx| {
1254 while held.len() < MAX_HELD
1255 && let Poll::Ready(Some(message)) = Pin::new(&mut messages).poll_next(cx)
1256 {
1257 held.push(message);
1258 }
1259 take.as_mut().poll(cx)
1260 })
1261 .await;
1262 }
1263 service.release();
1264 for message in held {
1265 match message {
1266 Ok(message) => service.on_message(&connection, &message).await,
1267 Err(error) => tracing::warn!(%error, "a bad message on the session bus"),
1268 }
1269 }
1270 match requested {
1271 Ok(RequestNameReply::InQueue) => {
1272 tracing::info!("another program serves notifications; waiting for it to leave");
1273 }
1274 Ok(_) => {}
1275 Err(error) => return tracing::warn!(%error, "couldn't ask for the notifications name"),
1276 }
1277 loop {
1278 let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
1279 if !service.alive() {
1280 return;
1281 }
1282 match next {
1283 Some(Ok(message)) => service.on_message(&connection, &message).await,
1284 Some(Err(error)) => tracing::warn!(%error, "a bad message on the session bus"),
1285 None => break,
1286 }
1287 }
1288 tracing::warn!("the session bus closed, so no more notifications arrive");
1289 if let Some(state) = service.state.borrow_mut().as_mut() {
1290 state.serving = false;
1291 state.connection = None;
1292 }
1293}
1294
1295fn restored(saved: Saved, now: Instant) -> (Vec<Notification>, Showing, u32) {
1298 let mut history: Vec<Notification> = Vec::new();
1299 for kept in saved.history {
1300 if kept.id != 0 && !history.iter().any(|seen| seen.id == kept.id) {
1301 history.push(kept.notification());
1302 }
1303 }
1304 let excess = history.len().saturating_sub(MAX_KEPT);
1305 history.drain(..excess);
1306 let mut showing = Showing::new();
1307 for (id, left) in saved.showing {
1308 let known = history.iter().any(|kept| kept.id == id);
1309 if known && !showing.iter().any(|shown| shown.id == id) {
1310 let left = left.map(Duration::from_millis);
1312 let left = left.map(|left| match now.checked_add(left) {
1313 Some(_) => left,
1314 None => Duration::ZERO,
1315 });
1316 let whole = saved.whole.iter().find(|(whole, _)| *whole == id);
1317 let whole = whole.map(|(_, ms)| Duration::from_millis(*ms));
1318 let timeout = left.map(|left| whole.unwrap_or(left).max(left));
1319 showing.push(Popup {
1320 left: left.unwrap_or_default(),
1321 ..Popup::new(id, timeout, now)
1322 });
1323 }
1324 }
1325 (history, showing, saved.next_id.max(1))
1326}
1327
1328fn keep_pixels_within(history: &mut [Notification], budget: usize) {
1331 let mut total = 0;
1332 for kept in history.iter_mut().rev() {
1333 let Some(IconSource::Pixels(pixels)) = &kept.image else {
1334 continue;
1335 };
1336 let bytes = pixels.data.len();
1337 if total + bytes <= budget {
1338 total += bytes;
1339 } else {
1340 tracing::debug!(
1341 id = kept.id,
1342 "past the pictures' budget; showing the app icon"
1343 );
1344 kept.image = server::icon(&kept.app_icon);
1345 }
1346 }
1347}