1use std::collections::{BTreeMap, VecDeque};
54use std::sync::mpsc::{Receiver, Sender, channel};
55use std::sync::{Arc, Mutex};
56
57use egui_pop_api::hooks::On;
58use egui_pop_api::services::ServiceToken;
59use egui_pop_api::steps::{Outcome, StepSpec};
60use egui_pop_api::toasts::{self, TOASTS, Toast};
61use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
62use egui_pop_core::lock;
63use egui_pop_model::commands::{CommandSpec, Origin};
64use egui_pop_model::ids::{CommandId, PluginId, SettingId, StepId};
65use egui_pop_model::values::Descriptor;
66use serde::{Deserialize, Serialize};
67use serde_json::{Value as Json, json};
68
69pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.notify");
71pub const STEP_SHOW: StepId = StepId::from_static("notify.show");
73pub const STEP_ACTION: StepId = StepId::from_static("notify.action");
75pub const SETTING_DESKTOP: SettingId = SettingId::from_static("notifications.desktop");
78pub const CMD_ACT: CommandId = CommandId::from_static("notify.act");
81pub const NOTIFIER: ServiceToken<Notifier> = ServiceToken::new("platform.notify");
83pub const FAILED: &str = "notify.failed";
85pub const HISTORY: usize = 32;
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "lowercase")]
92pub enum Level {
93 #[default]
94 Info,
95 Success,
96 Warning,
97 Error,
98}
99
100impl Level {
101 fn toast(self) -> toasts::Level {
102 match self {
103 Level::Info => toasts::Level::Info,
104 Level::Success => toasts::Level::Success,
105 Level::Warning => toasts::Level::Warning,
106 Level::Error => toasts::Level::Error,
107 }
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
113pub struct Action {
114 pub id: String,
116 pub label: String,
117 pub command: CommandId,
118 #[serde(default)]
119 pub args: Json,
120}
121
122#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
124pub struct Notification {
125 pub title: String,
126 #[serde(default)]
127 pub body: String,
128 #[serde(default)]
129 pub level: Level,
130 #[serde(default)]
131 pub actions: Vec<Action>,
132 #[serde(default)]
135 pub default: Option<(CommandId, Json)>,
136 #[serde(default)]
138 pub icon: Option<String>,
139}
140
141impl Notification {
142 pub fn new(title: &str, body: &str) -> Self {
143 Self {
144 title: title.into(),
145 body: body.into(),
146 ..Self::default()
147 }
148 }
149
150 pub fn level(mut self, level: Level) -> Self {
151 self.level = level;
152 self
153 }
154
155 pub fn action(mut self, id: &str, label: &str, command: CommandId, args: Json) -> Self {
157 self.actions.push(Action {
158 id: id.into(),
159 label: label.into(),
160 command,
161 args,
162 });
163 self
164 }
165
166 pub fn on_click(mut self, command: CommandId, args: Json) -> Self {
168 self.default = Some((command, args));
169 self
170 }
171
172 pub fn icon(mut self, icon: &str) -> Self {
173 self.icon = Some(icon.into());
174 self
175 }
176}
177
178pub trait Backend: Send + Sync + 'static {
181 fn name(&self) -> String;
183
184 fn probe(&self) -> Result<String, String>;
187
188 fn known(&self) -> Option<Result<String, String>> {
191 None
192 }
193
194 fn show(
198 &self,
199 id: u64,
200 n: &Notification,
201 respond: Box<dyn FnOnce(String) + Send>,
202 ) -> Result<(), String>;
203}
204
205#[derive(Clone, Debug)]
207pub struct Desktop {
208 #[cfg_attr(
209 target_arch = "wasm32",
210 allow(
211 dead_code,
212 reason = "notify-rust is not built for the web, so nothing reads it there"
213 )
214 )]
215 app_name: String,
216 app_id: Option<String>,
217}
218
219impl Desktop {
220 pub fn new(app_name: &str) -> Self {
222 Self {
223 app_name: app_name.into(),
224 app_id: None,
225 }
226 }
227
228 pub fn app_id(mut self, id: &str) -> Self {
235 self.app_id = Some(id.into());
236 self
237 }
238}
239
240impl Backend for Desktop {
241 fn name(&self) -> String {
242 if cfg!(windows) {
243 "windows"
244 } else if cfg!(target_os = "macos") {
245 "macos"
246 } else if cfg!(target_arch = "wasm32") {
247 "none"
248 } else {
249 "xdg"
250 }
251 .into()
252 }
253
254 #[cfg(not(target_arch = "wasm32"))]
255 fn probe(&self) -> Result<String, String> {
256 #[cfg(all(unix, not(target_os = "macos")))]
257 {
258 notify_rust::get_server_information()
259 .map(|s| format!("{} {}", s.name, s.version))
260 .map_err(|e| format!("no notification server: {e}"))
261 }
262 #[cfg(not(all(unix, not(target_os = "macos"))))]
263 {
264 Ok(self.name())
265 }
266 }
267
268 #[cfg(target_arch = "wasm32")]
269 fn probe(&self) -> Result<String, String> {
270 Err("no desktop notifications on the web".into())
271 }
272
273 #[cfg(not(target_arch = "wasm32"))]
274 fn show(
275 &self,
276 _id: u64,
277 n: &Notification,
278 respond: Box<dyn FnOnce(String) + Send>,
279 ) -> Result<(), String> {
280 let mut out = notify_rust::Notification::new();
281 out.appname(&self.app_name).summary(&n.title).body(&n.body);
282 if let Some(id) = &self.app_id {
283 #[cfg(all(unix, not(target_os = "macos")))]
284 out.hint(notify_rust::Hint::DesktopEntry(id.clone()));
285 #[cfg(windows)]
286 out.app_id(id);
287 #[cfg(target_os = "macos")]
288 {
289 static SET: std::sync::Once = std::sync::Once::new();
290 SET.call_once(|| {
291 let _ = notify_rust::set_application(id);
292 });
293 }
294 }
295 if let Some(icon) = &n.icon {
296 out.icon(icon);
297 }
298 #[cfg(all(unix, not(target_os = "macos")))]
299 out.urgency(match n.level {
300 Level::Error => notify_rust::Urgency::Critical,
301 Level::Warning => notify_rust::Urgency::Normal,
302 Level::Info | Level::Success => notify_rust::Urgency::Low,
303 });
304 if n.default.is_some() {
305 out.action("default", &n.title);
306 }
307 for a in &n.actions {
308 out.action(&a.id, &a.label);
309 }
310 let handle = out.show().map_err(|e| e.to_string())?;
311 let waits = n.default.is_some() || !n.actions.is_empty();
312 if waits {
313 std::thread::Builder::new()
316 .name("egui-pop notification".into())
317 .spawn(move || {
318 handle.wait_for_action(|action| {
319 if action != "__closed" {
320 respond(action.to_string());
321 }
322 });
323 })
324 .map_err(|e| e.to_string())?;
325 }
326 Ok(())
327 }
328
329 #[cfg(target_arch = "wasm32")]
330 fn show(
331 &self,
332 _: u64,
333 _: &Notification,
334 _: Box<dyn FnOnce(String) + Send>,
335 ) -> Result<(), String> {
336 Err("no desktop notifications on the web".into())
337 }
338}
339
340type Respond = Box<dyn FnOnce(String) + Send>;
341
342#[derive(Default)]
343struct SimState {
344 shown: Vec<(u64, Notification)>,
345 responders: BTreeMap<u64, Respond>,
346}
347
348#[derive(Clone)]
351pub struct Simulated {
352 available: Result<String, String>,
353 state: Arc<Mutex<SimState>>,
354}
355
356impl std::fmt::Debug for Simulated {
357 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358 f.debug_struct("Simulated")
359 .field("available", &self.available)
360 .finish_non_exhaustive()
361 }
362}
363
364impl Default for Simulated {
365 fn default() -> Self {
366 Self {
367 available: Ok("simulated".into()),
368 state: Arc::default(),
369 }
370 }
371}
372
373impl Simulated {
374 pub fn unavailable(reason: &str) -> Self {
376 Self {
377 available: Err(reason.into()),
378 state: Arc::default(),
379 }
380 }
381
382 pub fn shown(&self) -> Vec<(u64, Notification)> {
384 lock(&self.state).shown.clone()
385 }
386
387 pub fn click(&self, id: u64, action: &str) -> bool {
390 let respond = lock(&self.state).responders.remove(&id);
391 match respond {
392 Some(r) => {
393 r(action.into());
394 true
395 }
396 None => false,
397 }
398 }
399}
400
401impl Backend for Simulated {
402 fn name(&self) -> String {
403 "simulated".into()
404 }
405
406 fn probe(&self) -> Result<String, String> {
407 self.available.clone()
408 }
409
410 fn known(&self) -> Option<Result<String, String>> {
411 Some(self.available.clone())
412 }
413
414 fn show(&self, id: u64, n: &Notification, respond: Respond) -> Result<(), String> {
415 self.available.as_ref().map_err(Clone::clone)?;
416 let mut s = lock(&self.state);
417 s.shown.push((id, n.clone()));
418 s.responders.insert(id, respond);
419 Ok(())
420 }
421}
422
423#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
425#[serde(rename_all = "lowercase")]
426pub enum Via {
427 Desktop,
428 Toast,
429 Nowhere,
431}
432
433#[derive(Clone, Debug, PartialEq, Serialize)]
435pub struct Shown {
436 pub id: u64,
437 pub notification: Notification,
438 pub via: Via,
439 pub picked: Vec<String>,
441}
442
443enum Event {
445 Probed(Result<String, String>),
446 Failed(u64, String),
447 Picked(u64, String),
448}
449
450#[derive(Default)]
451struct State {
452 next: u64,
453 posted: VecDeque<Notification>,
454 history: VecDeque<Shown>,
455 desktop: Option<Result<String, String>>,
456 waker: Option<egui::Context>,
457}
458
459#[derive(Clone, Default)]
462pub struct Notifier(Arc<Mutex<State>>);
463
464impl std::fmt::Debug for Notifier {
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 f.debug_struct("Notifier").finish_non_exhaustive()
467 }
468}
469
470impl Notifier {
471 pub fn post(&self, n: Notification) {
473 let waker = {
474 let mut s = lock(&self.0);
475 s.posted.push_back(n);
476 s.waker.clone()
477 };
478 if let Some(ctx) = waker {
479 ctx.request_repaint();
480 }
481 }
482
483 pub fn history(&self) -> Vec<Shown> {
485 lock(&self.0).history.iter().cloned().collect()
486 }
487
488 pub fn desktop(&self) -> Option<Result<String, String>> {
491 lock(&self.0).desktop.clone()
492 }
493
494 fn next_id(&self) -> u64 {
495 let mut s = lock(&self.0);
496 s.next += 1;
497 s.next
498 }
499
500 fn record(&self, shown: Shown) {
501 let mut s = lock(&self.0);
502 s.history.retain(|h| h.id != shown.id);
503 s.history.push_back(shown);
504 while s.history.len() > HISTORY {
505 s.history.pop_front();
506 }
507 }
508
509 fn find(&self, id: u64) -> Option<Shown> {
510 lock(&self.0).history.iter().find(|h| h.id == id).cloned()
511 }
512
513 fn update(&self, id: u64, f: impl FnOnce(&mut Shown)) {
514 if let Some(h) = lock(&self.0).history.iter_mut().find(|h| h.id == id) {
515 f(h);
516 }
517 }
518}
519
520struct Shared {
522 notifier: Notifier,
523 jobs: Mutex<Option<Sender<(u64, Notification)>>>,
524}
525
526pub fn show(app: &AppHandle, n: Notification) -> Outcome {
530 let Some(notifier) = app.service(&NOTIFIER) else {
531 return Outcome::Done(Err("the notifications plugin is not connected".into()));
532 };
533 let id = notifier.next_id();
534 run_show(app, ¬ifier, id, n)
535}
536
537fn args_of(id: u64, n: &Notification) -> Json {
538 let mut args = serde_json::to_value(n).unwrap_or_default();
539 args["id"] = json!(id);
540 args
541}
542
543fn run_show(app: &AppHandle, notifier: &Notifier, id: u64, n: Notification) -> Outcome {
544 let args = args_of(id, &n);
545 let n_default = n.clone();
546 let out = app.step(&STEP_SHOW, args, move |app, args| {
547 let n: Notification = serde_json::from_value(args.clone()).unwrap_or(n_default);
548 let shared = app
549 .service(&SHARED)
550 .ok_or("the notifications plugin is not connected")?;
551 let wanted = desktop_wanted(app);
552 let desktop = lock(&shared.notifier.0).desktop.clone();
553 let reason = match (&wanted, &desktop) {
554 (Err(why), _) => why.clone(),
555 (Ok(()), Some(Err(why))) => why.clone(),
556 (Ok(()), _) => {
557 let sent = lock(&shared.jobs)
558 .as_ref()
559 .is_some_and(|tx| tx.send((id, n.clone())).is_ok());
560 if sent {
561 shared.notifier.record(Shown {
562 id,
563 notification: n,
564 via: Via::Desktop,
565 picked: Vec::new(),
566 });
567 return Ok(json!({ "id": id, "via": "desktop" }));
568 }
569 "the notification thread is gone".into()
570 }
571 };
572 toast(app, &shared.notifier, id, &n)?;
573 Ok(json!({ "id": id, "via": "toast", "reason": reason }))
574 });
575 if out.vetoed().is_some() {
576 notifier.record(Shown {
577 id,
578 notification: n,
579 via: Via::Nowhere,
580 picked: Vec::new(),
581 });
582 }
583 out
584}
585
586fn desktop_wanted(app: &AppHandle) -> Result<(), String> {
588 let setting = lock(&app.store())
589 .get(&format!("settings/{SETTING_DESKTOP}"))
590 .and_then(|e| e.value.as_choice().map(str::to_string))
591 .unwrap_or_else(|| "always".into());
592 match setting.as_str() {
593 "never" => Err("notifications show in the window (setting)".into()),
594 "unfocused" => {
595 let focused = app.egui().input(|i| i.viewport().focused.unwrap_or(true));
596 if focused {
597 Err("the window has the focus (setting)".into())
598 } else {
599 Ok(())
600 }
601 }
602 _ => Ok(()),
603 }
604}
605
606fn toast(app: &AppHandle, notifier: &Notifier, id: u64, n: &Notification) -> Result<(), String> {
608 let toasts = app
609 .service(&TOASTS)
610 .ok_or("no desktop notifications and no toasts")?;
611 let text = if n.body.is_empty() {
612 n.title.clone()
613 } else {
614 format!("{}: {}", n.title, n.body)
615 };
616 let mut t = Toast::new(n.level.toast(), &text);
617 if let Some(a) = n.actions.first() {
618 t = t.action(&a.label, CMD_ACT, json!({ "id": id, "action": a.id }));
619 }
620 toasts.notify(t);
621 notifier.record(Shown {
622 id,
623 notification: n.clone(),
624 via: Via::Toast,
625 picked: Vec::new(),
626 });
627 Ok(())
628}
629
630fn picked(app: &AppHandle, notifier: &Notifier, id: u64, action: &str) -> Outcome {
632 let Some(shown) = notifier.find(id) else {
633 return Outcome::Done(Err(format!("no notification {id}")));
634 };
635 notifier.update(id, |h| h.picked.push(action.into()));
636 let n = &shown.notification;
637 let (command, args) = if action == "default" {
638 match &n.default {
639 Some((c, a)) => (Some(c.clone()), a.clone()),
640 None => (None, Json::Null),
641 }
642 } else {
643 match n.actions.iter().find(|a| a.id == action) {
644 Some(a) => (Some(a.command.clone()), a.args.clone()),
645 None => return Outcome::Done(Err(format!("no action `{action}` on {id}"))),
646 }
647 };
648 app.step(
649 &STEP_ACTION,
650 json!({ "id": id, "action": action, "command": command, "args": args }),
651 |app, args| {
652 if args["action"] == "default" {
653 crate::window::raise_app(app);
654 }
655 let Some(command) = args["command"]
656 .as_str()
657 .and_then(|c| CommandId::new(c).ok())
658 else {
659 return Ok(json!({ "ran": null }));
660 };
661 app.run_as(command.clone(), args["args"].clone(), Origin::User);
662 Ok(json!({ "ran": command }))
663 },
664 )
665}
666
667const SHARED: ServiceToken<Shared> = ServiceToken::new("platform.notify.shared");
668
669pub struct NotifyPlugin {
671 backend: Arc<dyn Backend>,
672}
673
674impl std::fmt::Debug for NotifyPlugin {
675 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
676 f.debug_struct("NotifyPlugin")
677 .field("backend", &self.backend.name())
678 .finish_non_exhaustive()
679 }
680}
681
682impl NotifyPlugin {
683 pub fn new(app_name: &str) -> Self {
687 Self {
688 backend: Arc::new(Desktop::new(app_name)),
689 }
690 }
691
692 pub fn backend(mut self, backend: impl Backend) -> Self {
694 self.backend = Arc::new(backend);
695 self
696 }
697}
698
699impl Plugin for NotifyPlugin {
700 fn id(&self) -> PluginId {
701 PLUGIN
702 }
703
704 fn title(&self) -> String {
705 "Notifications".into()
706 }
707
708 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
709 ctx.setting(
710 SETTING_DESKTOP,
711 Descriptor::choice(
712 "Desktop notifications",
713 &["always", "unfocused", "never"],
714 "always",
715 )
716 .description(
717 "Where notifications show: on the desktop, on the desktop only while the window does not have the focus, or in the window.",
718 ),
719 )?;
720 ctx.step(
721 StepSpec::new(
722 STEP_SHOW,
723 "A notification is shown (`id`, `title`, `body`, `level`, `actions`, `default`); the result says where (`via`: desktop or toast).",
724 )
725 .args(json!({ "id": 1, "title": "Export done", "body": "3 images", "level": "success", "actions": [] })),
726 )?
727 .step(
728 StepSpec::new(
729 STEP_ACTION,
730 "The user picked a notification's action (`id`, `action`, `command`, `args`); by default its command runs.",
731 )
732 .args(json!({ "id": 1, "action": "show", "command": "files.reveal", "args": {} })),
733 )?;
734 ctx.command(
735 CommandSpec::new(CMD_ACT, "Act on a notification", "Notifications")
736 .description(
737 "Runs a notification's action (`id`, `action`), as a click on it does.",
738 )
739 .args(json!({ "id": 1, "action": "show" }))
740 .hidden(),
741 |call| {
742 let id = call.args["id"].as_u64().ok_or("`id` is missing")?;
743 let action = call.args["action"].as_str().ok_or("`action` is missing")?;
744 let notifier = call.app.service(&NOTIFIER).ok_or("no notifier")?;
745 match picked(call.app, ¬ifier, id, action) {
746 Outcome::Done(r) => r,
747 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
748 }
749 },
750 )?;
751 let notifier = Notifier::default();
752 let known = self.backend.known();
753 {
754 let mut s = lock(¬ifier.0);
755 s.waker = Some(ctx.app().egui());
756 s.desktop = known.clone();
757 }
758 let (events_tx, events_rx) = channel::<Event>();
759 let events_rx: Mutex<Receiver<Event>> = Mutex::new(events_rx);
760 let (jobs_tx, jobs_rx) = channel::<(u64, Notification)>();
763 let backend = self.backend.clone();
764 let waker = ctx.app().egui();
765 let tx = events_tx;
766 let spawned = std::thread::Builder::new()
767 .name("egui-pop notifications".into())
768 .spawn(move || {
769 let wake = |tx: &Sender<Event>, e: Event| {
770 let _ = tx.send(e);
771 waker.request_repaint();
772 };
773 if known.is_none() {
774 wake(&tx, Event::Probed(backend.probe()));
775 }
776 for (id, n) in jobs_rx {
777 let (rtx, rwaker) = (tx.clone(), waker.clone());
778 let respond: Respond = Box::new(move |action| {
779 let _ = rtx.send(Event::Picked(id, action));
780 rwaker.request_repaint();
781 });
782 if let Err(e) = backend.show(id, &n, respond) {
783 wake(&tx, Event::Failed(id, e));
784 }
785 }
786 });
787 let jobs = match spawned {
789 Ok(_) => Some(jobs_tx),
790 Err(e) => {
791 lock(¬ifier.0).desktop =
792 Some(Err(format!("no thread to show desktop notifications: {e}")));
793 None
794 }
795 };
796 let shared = Shared {
797 notifier: notifier.clone(),
798 jobs: Mutex::new(jobs),
799 };
800 ctx.service(&SHARED, shared)?;
801 ctx.service(&NOTIFIER, notifier.clone())?;
802 ctx.on(On::Pass, move |app, _| {
803 let events: Vec<Event> = lock(&events_rx).try_iter().collect();
804 for e in events {
805 match e {
806 Event::Probed(r) => lock(¬ifier.0).desktop = Some(r),
807 Event::Failed(id, error) => {
808 app.publish(
809 "egui_pop",
810 None,
811 FAILED,
812 json!({ "id": id, "error": error }),
813 );
814 if let Some(shown) = notifier.find(id) {
815 let _ = toast(app, ¬ifier, id, &shown.notification);
816 }
817 }
818 Event::Picked(id, action) => {
819 picked(app, ¬ifier, id, &action);
820 }
821 }
822 }
823 let posted: Vec<Notification> = lock(¬ifier.0).posted.drain(..).collect();
824 for n in posted {
825 let id = notifier.next_id();
826 run_show(app, ¬ifier, id, n);
827 }
828 });
829 Ok(())
830 }
831
832 fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
833 if let Some(shared) = ctx.app().service(&SHARED) {
834 lock(&shared.jobs).take();
836 lock(&shared.notifier.0).waker = None;
837 }
838 }
839}