Skip to main content

egui_pop_platform/
notify.rs

1//! Desktop notifications with actions, routed to commands, falling back
2//! to an in-app toast.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! A [`Notification`] has a title, a body, a level, actions (each a
8//! label and a command with its arguments) and a command for a click on
9//! its body. [`show`] shows one now (on the interface thread);
10//! [`Notifier::post`] queues one from any thread, shown at the next
11//! pass. Both go through the steps (ADR 0011):
12//!
13//! - `notify.show`: the notification, as JSON (its fields and `id`). By
14//!   default it goes to the desktop (notify-rust: the XDG notification
15//!   server on Linux and BSD, the notification centre on macOS, toasts
16//!   on Windows) as the `notifications.desktop` setting says (`always`,
17//!   `unfocused`: only while the window does not have the focus,
18//!   `never`), else, and whenever the desktop has no notification
19//!   server or fails, to a toast (`TOASTS`, its first action as the
20//!   toast's). The result says where: `{ "id", "via": "desktop" |
21//!   "toast" }`. Replace it to send notifications elsewhere; veto it to
22//!   keep quiet (do-not-disturb).
23//! - `notify.action`: the user picked an action, on the desktop or on
24//!   the toast: `{ "id", "action", "command", "args" }` (`action`:
25//!   the action's id, or `default` for a click on the body). By default
26//!   its command runs through the host; `default` also brings the window
27//!   to the front.
28//!
29//! Desktop notifications are shown from a thread of their own (a D-Bus
30//! call can block), so a failure arrives at a later pass: it shows the
31//! toast then and publishes `notify.failed` (`{ "id", "error" }`).
32//!
33//! ```
34//! use egui_pop_api::App;
35//! use egui_pop_api::toasts::{TOASTS, ToastsPlugin};
36//! use egui_pop_model::ids::CommandId;
37//! use egui_pop_platform::notify::{self, Notification, NotifyPlugin, Simulated};
38//!
39//! let ctx = egui::Context::default();
40//! let desktop = Simulated::unavailable("no notification server");
41//! let app = App::builder()
42//!     .plugin(ToastsPlugin)
43//!     .plugin(NotifyPlugin::new("Demo").backend(desktop))
44//!     .build(&ctx)
45//!     .unwrap();
46//! let n = Notification::new("Export done", "3 images in ~/Pictures")
47//!     .action("show", "Show", CommandId::from_static("files.reveal"), serde_json::json!({}));
48//! let out = notify::show(app.handle(), n);
49//! assert_eq!(out.result().unwrap().as_ref().unwrap()["via"], "toast");
50//! assert_eq!(app.handle().service(&TOASTS).unwrap().shown().len(), 1);
51//! ```
52
53use 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
69/// The plugin's id.
70pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.notify");
71/// A notification to show: its fields and `id`.
72pub const STEP_SHOW: StepId = StepId::from_static("notify.show");
73/// An action picked: `{ "id", "action", "command", "args" }`.
74pub const STEP_ACTION: StepId = StepId::from_static("notify.action");
75/// Where notifications show: `always` on the desktop, `unfocused` (while
76/// the window does not have the focus), `never` (toasts only).
77pub const SETTING_DESKTOP: SettingId = SettingId::from_static("notifications.desktop");
78/// The command a toast's action runs, to go through `notify.action`
79/// (`{ "id", "action" }`).
80pub const CMD_ACT: CommandId = CommandId::from_static("notify.act");
81/// The notifier, as a service.
82pub const NOTIFIER: ServiceToken<Notifier> = ServiceToken::new("platform.notify");
83/// The signal published when the desktop failed to show one.
84pub const FAILED: &str = "notify.failed";
85/// How many notifications [`Notifier::history`] keeps.
86pub const HISTORY: usize = 32;
87
88/// How much a notification matters: its toast's level, its urgency on
89/// the desktop.
90#[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/// An action offered with a notification: a button on the desktop.
112#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
113pub struct Action {
114    /// Stable, never shown: `show`, `retry`.
115    pub id: String,
116    pub label: String,
117    pub command: CommandId,
118    #[serde(default)]
119    pub args: Json,
120}
121
122/// A notification.
123#[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    /// What a click on its body runs (besides bringing the window to the
133    /// front).
134    #[serde(default)]
135    pub default: Option<(CommandId, Json)>,
136    /// A themed icon's name or a file path (desktop only).
137    #[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    /// Offers an action, running `command` with `args` when picked.
156    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    /// Runs `command` with `args` when its body is clicked.
167    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
178/// What shows notifications on the desktop. [`Desktop`] is the real
179/// one; [`Simulated`] records them, for tests and the gallery.
180pub trait Backend: Send + Sync + 'static {
181    /// A short name: `xdg`, `windows`, `macos`, `simulated`.
182    fn name(&self) -> String;
183
184    /// Whether the desktop can show notifications, and through what
185    /// (the server's name), or why not. May block: called from a thread.
186    fn probe(&self) -> Result<String, String>;
187
188    /// [`Backend::probe`]'s answer when it is known without asking
189    /// (taken at connect, and the thread asks nothing).
190    fn known(&self) -> Option<Result<String, String>> {
191        None
192    }
193
194    /// Shows one. `respond` gets the action the user picks (an action's
195    /// id, or `default` for its body), at most once. May block: called
196    /// from a thread.
197    fn show(
198        &self,
199        id: u64,
200        n: &Notification,
201        respond: Box<dyn FnOnce(String) + Send>,
202    ) -> Result<(), String>;
203}
204
205/// The desktop's notifications, through notify-rust.
206#[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    /// `app_name`: the application as the notification server shows it.
221    pub fn new(app_name: &str) -> Self {
222        Self {
223            app_name: app_name.into(),
224            app_id: None,
225        }
226    }
227
228    /// The application's id, as the desktop knows it: its desktop file's
229    /// name on Linux (`org.example.Viewer`, the `desktop-entry` hint),
230    /// its AppUserModelID on Windows (set on its Start menu shortcut by
231    /// the installer; without one, notifications show as PowerShell's),
232    /// its bundle identifier on macOS (without one, as another
233    /// application's). See `docs/packaging.md`.
234    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            // Each notification waiting for an answer holds a thread
314            // until it is closed (notify-rust's way).
315            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/// A desktop that records what it shows; [`Simulated::click`] answers
349/// as the user would. For tests and the gallery.
350#[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    /// A desktop without notifications, saying why.
375    pub fn unavailable(reason: &str) -> Self {
376        Self {
377            available: Err(reason.into()),
378            state: Arc::default(),
379        }
380    }
381
382    /// What it showed: id and notification, oldest first.
383    pub fn shown(&self) -> Vec<(u64, Notification)> {
384        lock(&self.state).shown.clone()
385    }
386
387    /// The user picks `action` (an action's id, or `default`) on the
388    /// notification `id`; false when it waits for no answer.
389    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/// Where a notification went.
424#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
425#[serde(rename_all = "lowercase")]
426pub enum Via {
427    Desktop,
428    Toast,
429    /// Not shown: its step was vetoed.
430    Nowhere,
431}
432
433/// A notification shown, as kept.
434#[derive(Clone, Debug, PartialEq, Serialize)]
435pub struct Shown {
436    pub id: u64,
437    pub notification: Notification,
438    pub via: Via,
439    /// The actions picked, in order.
440    pub picked: Vec<String>,
441}
442
443/// What the desktop said back, from its threads.
444enum 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/// The notifications, as a service: post from any thread, read what was
460/// shown and where. Cheap to clone (shared).
461#[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    /// Queues a notification, shown at the next pass (from any thread).
472    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    /// The notifications shown, oldest first.
484    pub fn history(&self) -> Vec<Shown> {
485        lock(&self.0).history.iter().cloned().collect()
486    }
487
488    /// Whether the desktop shows notifications (and through what), or
489    /// why not; none while it is being asked.
490    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
520/// What the plugin keeps between its closures.
521struct Shared {
522    notifier: Notifier,
523    jobs: Mutex<Option<Sender<(u64, Notification)>>>,
524}
525
526/// Shows a notification now, through `notify.show` (on the interface
527/// thread; [`Notifier::post`] from others). Without the plugin, the
528/// step runs nowhere and says so.
529pub 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, &notifier, 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
586/// Whether the setting sends this one to the desktop, or why not.
587fn 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
606/// Shows it as a toast, its first action as the toast's.
607fn 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
630/// Runs `notify.action` for an action picked.
631fn 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
669/// Desktop notifications, as a plugin (see the module).
670pub 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    /// With the desktop's notifications ([`Desktop`]), the application
684    /// named `app_name` (give its id with
685    /// `.backend(Desktop::new(name).app_id(id))`).
686    pub fn new(app_name: &str) -> Self {
687        Self {
688            backend: Arc::new(Desktop::new(app_name)),
689        }
690    }
691
692    /// Another backend ([`Simulated`] in tests).
693    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, &notifier, 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(&notifier.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        // The desktop's thread: asks once whether it shows notifications,
761        // then shows them in order.
762        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        // Without a thread (the web), toasts only.
788        let jobs = match spawned {
789            Ok(_) => Some(jobs_tx),
790            Err(e) => {
791                lock(&notifier.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(&notifier.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, &notifier, id, &shown.notification);
816                        }
817                    }
818                    Event::Picked(id, action) => {
819                        picked(app, &notifier, id, &action);
820                    }
821                }
822            }
823            let posted: Vec<Notification> = lock(&notifier.0).posted.drain(..).collect();
824            for n in posted {
825                let id = notifier.next_id();
826                run_show(app, &notifier, 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            // The desktop's thread ends with its queue.
835            lock(&shared.jobs).take();
836            lock(&shared.notifier.0).waker = None;
837        }
838    }
839}