Skip to main content

egui_pop_api/bus/
notices.rs

1//! Notices on the bus (`docs/notices.md`).
2//!
3//! A notice ([`egui_pop_model::notice::Notice`]: an error, a warning, a
4//! success, a piece of information, a question) is raised once, as
5//! `pop.notice.raised` ([`NoticeRaised`]); a condition that ends is said
6//! as `pop.notice.resolved` ([`NoticeResolved`]), notices read as
7//! `pop.notice.seen` ([`NoticeSeen`]), notices the user put away as
8//! `pop.notice.dismissed` ([`NoticeDismissed`]), each naming its notices
9//! (a [`NoticeIds`]). [`AppHandle::report`], [`AppHandle::resolve_notice`],
10//! [`AppHandle::see_notice`] and [`AppHandle::dismiss_notice`] say them;
11//! whoever holds the bus (a background thread, a service without egui)
12//! may publish them by the same names.
13//!
14//! egui-pop's one listener, [`NOTICE_STORE`], keeps the last notices
15//! raised ([`AppHandle::notices`]), bounded, marked seen or resolved,
16//! dismissed ones dropped. It runs on any thread.
17//!
18//! Its second, [`NOTICE_ROUTE`], hears each notice once the store kept
19//! it and shows it where the application's policy says
20//! ([`AppHandle::route_notices`], egui-pop's
21//! [`default_route`](egui_pop_model::notice::route::default_route)
22//! otherwise): inline at a notice site ([`crate::notices::notice_site`]),
23//! a toast, the status bar's badge ([`AppHandle::notice_badge`]), the
24//! history, the Decisions surface ([`NoticeRouting::ask`]).
25
26use std::collections::{HashMap, VecDeque};
27use std::sync::{Arc, Mutex, RwLock};
28
29use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
30use egui_pop_core::lock;
31use egui_pop_model::commands::CommandError;
32use egui_pop_model::ids::CommandId;
33use egui_pop_model::notice::route::{DefaultRouting, NoticeRouting, Route, RouteCx, Surface};
34use egui_pop_model::notice::{
35    Kept, Notice, NoticeId, NoticeIds, NoticeStore, NoticesDoc, Severity, notices_schema, points,
36};
37use serde_json::Value as Json;
38
39use super::{OWNER, emit_with};
40use crate::app::AppHandle;
41
42/// A notice is raised (`pop.notice.raised`).
43#[derive(Debug)]
44pub struct NoticeRaised;
45impl Point for NoticeRaised {
46    const KIND: PointKind = PointKind::Event;
47    const ID: PointId = PointId::new(points::RAISED);
48    type Input = Notice;
49    type Value = ();
50}
51
52/// A condition ended (`pop.notice.resolved`).
53#[derive(Debug)]
54pub struct NoticeResolved;
55impl Point for NoticeResolved {
56    const KIND: PointKind = PointKind::Event;
57    const ID: PointId = PointId::new(points::RESOLVED);
58    type Input = NoticeIds;
59    type Value = ();
60}
61
62/// Notices were read (`pop.notice.seen`).
63#[derive(Debug)]
64pub struct NoticeSeen;
65impl Point for NoticeSeen {
66    const KIND: PointKind = PointKind::Event;
67    const ID: PointId = PointId::new(points::SEEN);
68    type Input = NoticeIds;
69    type Value = ();
70}
71
72/// Notices were put away by the user (`pop.notice.dismissed`).
73#[derive(Debug)]
74pub struct NoticeDismissed;
75impl Point for NoticeDismissed {
76    const KIND: PointKind = PointKind::Event;
77    const ID: PointId = PointId::new(points::DISMISSED);
78    type Input = NoticeIds;
79    type Value = ();
80}
81
82/// The notice points, in the order [`super::order_dump`] prints them.
83pub const NOTICE_POINTS: [&str; 4] = [
84    NoticeRaised::ID.as_str(),
85    NoticeResolved::ID.as_str(),
86    NoticeSeen::ID.as_str(),
87    NoticeDismissed::ID.as_str(),
88];
89
90/// egui-pop's listener of the notice points: keeps the last notices
91/// raised ([`AppHandle::notices`]).
92pub const NOTICE_STORE: &str = "pop.notices.store";
93
94/// egui-pop's listener of `pop.notice.raised` after the store: routes
95/// each notice to its views ([`AppHandle::route_notices`]).
96pub const NOTICE_ROUTE: &str = "pop.notices.route";
97
98/// A command run from a place, whose failure is reported there
99/// ([`AppHandle::run_reported`]).
100#[derive(Debug)]
101struct Reported {
102    command: CommandId,
103    args: Json,
104    place: String,
105}
106
107/// The notices' state, shared by the listeners (any thread) and the
108/// interface: the store, the policy, the routes given, the notice sites
109/// drawn, the toasts to show notices in.
110pub(crate) struct Hub {
111    pub(crate) store: Mutex<NoticeStore>,
112    policy: RwLock<Arc<dyn NoticeRouting>>,
113    /// The route each kept notice was given.
114    routes: Mutex<HashMap<NoticeId, Route>>,
115    /// Notices kept, waiting for the route listener, with their route.
116    routed: Mutex<VecDeque<(Notice, Route)>>,
117    /// The notice sites, by place: the window and pass each was last
118    /// drawn in.
119    sites: Mutex<HashMap<String, (egui::ViewportId, u64)>>,
120    /// The toasts, while the toasts plugin is connected.
121    pub(crate) toasts: Mutex<Option<crate::toasts::Toasts>>,
122    /// The interface, once it has one.
123    ctx: Arc<Mutex<Option<egui::Context>>>,
124    /// Runs whose failure is reported at a place, oldest first.
125    reported: Mutex<Vec<Reported>>,
126    /// Failures handlers told in full (`Call::fail`), by command.
127    failures: Mutex<Vec<(CommandId, CommandError)>>,
128    /// The last failure of each command, once its result is in, until
129    /// taken ([`AppHandle::take_failure`]).
130    settled: Mutex<HashMap<CommandId, CommandError>>,
131}
132
133impl std::fmt::Debug for Hub {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.debug_struct("Hub")
136            .field("store", &lock(&self.store).len())
137            .finish_non_exhaustive()
138    }
139}
140
141impl Hub {
142    pub(crate) fn new(ctx: Arc<Mutex<Option<egui::Context>>>) -> Self {
143        Self {
144            store: Mutex::default(),
145            policy: RwLock::new(Arc::new(DefaultRouting)),
146            routes: Mutex::default(),
147            routed: Mutex::default(),
148            sites: Mutex::default(),
149            toasts: Mutex::default(),
150            ctx,
151            reported: Mutex::default(),
152            failures: Mutex::default(),
153            settled: Mutex::default(),
154        }
155    }
156
157    fn policy(&self) -> Arc<dyn NoticeRouting> {
158        self.policy
159            .read()
160            .unwrap_or_else(std::sync::PoisonError::into_inner)
161            .clone()
162    }
163
164    /// The places a notice site shows now: drawn in its window's last
165    /// pass or this one.
166    fn route_cx(&self) -> RouteCx {
167        let ctx = lock(&self.ctx).clone();
168        let sites = lock(&self.sites);
169        RouteCx::new(
170            sites
171                .iter()
172                .filter(|(_, (viewport, pass))| {
173                    ctx.as_ref()
174                        .is_none_or(|c| c.cumulative_pass_nr_for(*viewport) <= pass + 1)
175                })
176                .map(|(place, _)| place.clone()),
177        )
178    }
179
180    /// Keeps a notice raised and gives it its route.
181    fn keep(&self, mut n: Notice) {
182        {
183            let mut store = lock(&self.store);
184            if n.id.is_empty() {
185                n.id = store.next_id();
186            }
187            store.add(n.clone());
188            store.prune(now_ms());
189        }
190        let route = self.policy().route(&n, &self.route_cx());
191        {
192            let mut routes = lock(&self.routes);
193            routes.insert(n.id.clone(), route.clone());
194            let store = lock(&self.store);
195            if routes.len() > store.len() {
196                routes.retain(|id, _| store.get(id).is_some());
197            }
198        }
199        lock(&self.routed).push_back((n, route));
200    }
201
202    /// Shows the next notice kept on its route's views.
203    fn show_next(&self) {
204        let Some((n, route)) = lock(&self.routed).pop_front() else {
205            return;
206        };
207        if route.has(&Surface::Toast) {
208            let toasts = lock(&self.toasts).clone();
209            if let Some(t) = toasts {
210                t.notify_notice(&n);
211            }
212        }
213        if route.has(&Surface::Decisions) {
214            self.policy().ask(&n);
215        }
216        if let Some(ctx) = lock(&self.ctx).as_ref() {
217            ctx.request_repaint();
218        }
219    }
220
221    pub(crate) fn route_of(&self, id: &NoticeId) -> Option<Route> {
222        lock(&self.routes).get(id).cloned()
223    }
224
225    /// What it keeps, as the `notices` document's text, with each
226    /// notice's route.
227    pub(crate) fn doc_text(&self) -> Option<String> {
228        let mut doc = lock(&self.store).to_doc();
229        let routes = lock(&self.routes);
230        doc.routes = doc
231            .notices
232            .iter()
233            .filter_map(|k| Some((k.notice.id.clone(), routes.get(&k.notice.id)?.clone())))
234            .collect();
235        notices_schema().save(&doc).ok()
236    }
237
238    /// The store's revision (it moves whenever what it keeps changes).
239    pub(crate) fn rev(&self) -> u64 {
240        lock(&self.store).rev()
241    }
242
243    /// Takes back the notices saved by an earlier session, with their
244    /// routes (a notice saved without one is given one by the policy;
245    /// none is shown again).
246    pub(crate) fn restore(&self, doc: &NoticesDoc) {
247        lock(&self.store).restore(doc, now_ms());
248        let kept: Vec<Notice> = lock(&self.store).list().map(|k| k.notice.clone()).collect();
249        let policy = self.policy();
250        let cx = RouteCx::new(std::iter::empty::<String>());
251        let mut routes = lock(&self.routes);
252        for n in kept {
253            if routes.contains_key(&n.id) {
254                continue;
255            }
256            let route = doc
257                .routes
258                .get(&n.id)
259                .cloned()
260                .unwrap_or_else(|| policy.route(&n, &cx));
261            routes.insert(n.id.clone(), route);
262        }
263    }
264
265    /// Notes a notice site drawn.
266    pub(crate) fn site_drawn(&self, place: &str, viewport: egui::ViewportId, pass: u64) {
267        lock(&self.sites).insert(place.to_string(), (viewport, pass));
268    }
269
270    /// The notices kept whose route is inline at `place`, oldest first.
271    pub(crate) fn at(&self, place: &str) -> Vec<Kept> {
272        let routes = lock(&self.routes);
273        lock(&self.store)
274            .list()
275            .filter(|k| {
276                routes
277                    .get(&k.notice.id)
278                    .is_some_and(|r| r.inline_place() == Some(place))
279            })
280            .cloned()
281            .collect()
282    }
283}
284
285/// The notices' shared state.
286pub(crate) type Store = Arc<Hub>;
287
288/// Registers [`NOTICE_STORE`] on the notice points, and [`NOTICE_ROUTE`]
289/// after it on `pop.notice.raised`.
290pub(super) fn install(kernel: &dyn Bus, hub: &Store) {
291    let mine = || ListenOpts::new().owner(OWNER);
292    let listened = [
293        {
294            let hub = hub.clone();
295            kernel.listen::<NoticeRaised>(NOTICE_STORE, mine(), move |n, _| {
296                hub.keep(n.clone());
297                Ok(())
298            })
299        },
300        {
301            let hub = hub.clone();
302            kernel.listen::<NoticeRaised>(NOTICE_ROUTE, mine().after(NOTICE_STORE), move |_, _| {
303                hub.show_next();
304                Ok(())
305            })
306        },
307        {
308            let hub = hub.clone();
309            kernel.listen::<NoticeResolved>(NOTICE_STORE, mine(), move |m, _| {
310                lock(&hub.store).resolve(&m.ids);
311                Ok(())
312            })
313        },
314        {
315            let hub = hub.clone();
316            kernel.listen::<NoticeSeen>(NOTICE_STORE, mine(), move |m, _| {
317                lock(&hub.store).see(&m.ids);
318                Ok(())
319            })
320        },
321        {
322            let hub = hub.clone();
323            kernel.listen::<NoticeDismissed>(NOTICE_STORE, mine(), move |m, _| {
324                lock(&hub.store).dismiss(&m.ids);
325                Ok(())
326            })
327        },
328    ];
329    for l in listened {
330        debug_assert!(l.is_ok(), "{l:?}");
331    }
332}
333
334/// Now, in milliseconds since 1970.
335pub(crate) fn now_ms() -> u64 {
336    use web_time::{SystemTime, UNIX_EPOCH};
337    SystemTime::now()
338        .duration_since(UNIX_EPOCH)
339        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
340}
341
342/// What the status bar's badge counts: the notices routed to it
343/// ([`Surface::StatusBadge`]) not seen yet, and for a condition not
344/// resolved yet.
345#[derive(Clone, Debug, Default, PartialEq)]
346#[non_exhaustive]
347pub struct NoticeBadge {
348    /// How many of them are errors.
349    pub errors: usize,
350    /// How many of them are warnings.
351    pub warnings: usize,
352    /// Them, oldest first.
353    pub unseen: Vec<Kept>,
354}
355
356impl NoticeBadge {
357    /// How many notices it counts.
358    pub fn count(&self) -> usize {
359        self.unseen.len()
360    }
361}
362
363impl AppHandle {
364    /// Raises a notice (`pop.notice.raised`): the one call for a message
365    /// to the user. Given no id, it gets the next of the application's
366    /// (`n<seq>`); given no time, now. Its id. The routing policy
367    /// ([`AppHandle::route_notices`]) picks the views that show it.
368    ///
369    /// <div class="warning">Experimental: may change in any release
370    /// (docs/stability.md).</div>
371    pub fn report(&self, mut notice: Notice) -> NoticeId {
372        if notice.id.is_empty() {
373            notice.id = lock(&self.0.bus.notices.store).next_id();
374        }
375        if notice.at_ms == 0 {
376            notice.at_ms = now_ms();
377        }
378        let id = notice.id.clone();
379        emit_with::<NoticeRaised>(self, notice, ());
380        id
381    }
382
383    /// Says a condition ended (`pop.notice.resolved`).
384    ///
385    /// <div class="warning">Experimental: may change in any release
386    /// (docs/stability.md).</div>
387    pub fn resolve_notice(&self, id: impl Into<NoticeId>) {
388        emit_with::<NoticeResolved>(self, NoticeIds::one(id), ());
389    }
390
391    /// Says a notice was read (`pop.notice.seen`).
392    ///
393    /// <div class="warning">Experimental: may change in any release
394    /// (docs/stability.md).</div>
395    pub fn see_notice(&self, id: impl Into<NoticeId>) {
396        emit_with::<NoticeSeen>(self, NoticeIds::one(id), ());
397    }
398
399    /// Says the user put a notice away (`pop.notice.dismissed`).
400    ///
401    /// <div class="warning">Experimental: may change in any release
402    /// (docs/stability.md).</div>
403    pub fn dismiss_notice(&self, id: impl Into<NoticeId>) {
404        emit_with::<NoticeDismissed>(self, NoticeIds::one(id), ());
405    }
406
407    /// Says notices were read (`pop.notice.seen`), in one message.
408    ///
409    /// <div class="warning">Experimental: may change in any release
410    /// (docs/stability.md).</div>
411    pub fn see_notices(&self, ids: impl IntoIterator<Item = NoticeId>) {
412        let ids = NoticeIds::new(ids);
413        if !ids.ids.is_empty() {
414            emit_with::<NoticeSeen>(self, ids, ());
415        }
416    }
417
418    /// Says the user put notices away (`pop.notice.dismissed`), in one
419    /// message.
420    ///
421    /// <div class="warning">Experimental: may change in any release
422    /// (docs/stability.md).</div>
423    pub fn dismiss_notices(&self, ids: impl IntoIterator<Item = NoticeId>) {
424        let ids = NoticeIds::new(ids);
425        if !ids.ids.is_empty() {
426            emit_with::<NoticeDismissed>(self, ids, ());
427        }
428    }
429
430    /// The last notices raised, oldest first, as [`NOTICE_STORE`] keeps
431    /// them (at most [`NoticeStore::DEFAULT_BOUND`], none older than
432    /// [`NoticeStore::DEFAULT_MAX_AGE_MS`] but errors not seen yet).
433    ///
434    /// <div class="warning">Experimental: may change in any release
435    /// (docs/stability.md).</div>
436    pub fn notices(&self) -> Vec<Kept> {
437        lock(&self.0.bus.notices.store).list().cloned().collect()
438    }
439
440    /// How many notices the store keeps (500 by default) and for how long,
441    /// in milliseconds (30 days by default); an error not seen yet stays
442    /// until it is seen.
443    ///
444    /// <div class="warning">Experimental: may change in any release
445    /// (docs/stability.md).</div>
446    pub fn set_notice_limits(&self, bound: usize, max_age_ms: u64) {
447        lock(&self.0.bus.notices.store).set_limits(bound, max_age_ms);
448    }
449
450    /// Installs the application's routing policy in place of egui-pop's
451    /// ([`default_route`](egui_pop_model::notice::route::default_route)):
452    /// it picks the views of each notice raised from now on. A closure
453    /// `Fn(&Notice, &RouteCx) -> Route` is one.
454    ///
455    /// <div class="warning">Experimental: may change in any release
456    /// (docs/stability.md).</div>
457    pub fn route_notices(&self, policy: impl NoticeRouting + 'static) {
458        *self
459            .0
460            .bus
461            .notices
462            .policy
463            .write()
464            .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(policy);
465    }
466
467    /// The route a kept notice was given.
468    ///
469    /// <div class="warning">Experimental: may change in any release
470    /// (docs/stability.md).</div>
471    pub fn notice_route(&self, id: &NoticeId) -> Option<Route> {
472        self.0.bus.notices.route_of(id)
473    }
474
475    /// What the status bar's badge counts now.
476    ///
477    /// <div class="warning">Experimental: may change in any release
478    /// (docs/stability.md).</div>
479    pub fn notice_badge(&self) -> NoticeBadge {
480        let hub = &self.0.bus.notices;
481        let routes = lock(&hub.routes);
482        let unseen: Vec<Kept> = lock(&hub.store)
483            .list()
484            .filter(|k| !k.seen && !k.resolved)
485            .filter(|k| {
486                routes
487                    .get(&k.notice.id)
488                    .is_some_and(|r| r.has(&Surface::StatusBadge))
489            })
490            .cloned()
491            .collect();
492        let of = |s: Severity| unseen.iter().filter(|k| k.notice.severity == s).count();
493        NoticeBadge {
494            errors: of(Severity::Error),
495            warnings: of(Severity::Warning),
496            unseen,
497        }
498    }
499
500    /// Runs a command for the user, as [`AppHandle::run`] does; if it
501    /// fails, its failure is reported (a [`CommandError`] made a notice,
502    /// origin user) at `place`, where the routing policy shows it (by
503    /// default, a note in the notice site of `place` if one is drawn,
504    /// else a toast). A failure is never silent.
505    ///
506    /// <div class="warning">Experimental: may change in any release
507    /// (docs/stability.md).</div>
508    pub fn run_reported(&self, command: CommandId, args: Json, place: impl Into<String>) {
509        lock(&self.0.bus.notices.reported).push(Reported {
510            command: command.clone(),
511            args: args.clone(),
512            place: place.into(),
513        });
514        self.run(command, args);
515    }
516
517    /// Keeps the failure a handler told in full, for its command's
518    /// result (`Call::fail`).
519    pub(crate) fn keep_failure(&self, command: CommandId, err: CommandError) {
520        let mut f = lock(&self.0.bus.notices.failures);
521        f.retain(|(c, _)| *c != command);
522        f.push((command, err));
523    }
524
525    /// The failure of `command`'s last run, structured, once its result
526    /// is in: the [`CommandError`] its handler told with `Call::fail`
527    /// (headline, reason, hint, details), or one made from the text of
528    /// any other failure (`user` off). Taken: a second call returns
529    /// `None`, and a run that succeeds clears it.
530    ///
531    /// [`App::run`](crate::App::run) and [`AppHandle::run`] give a
532    /// failure's text only (`Result<Json, String>`); this gives the rest,
533    /// for an application that reports the failure itself:
534    ///
535    /// ```
536    /// # use egui_pop_api::{App, AppHandle};
537    /// # use egui_pop_model::commands::Origin;
538    /// # use egui_pop_model::ids::CommandId;
539    /// # use egui_pop_model::notice::Notice;
540    /// fn restore(app: &mut App, command: &CommandId) {
541    ///     let reply = app.run(command, serde_json::json!({}), Origin::User);
542    ///     if let Some(Err(_)) = reply.now()
543    ///         && let Some(err) = app.handle().take_failure(command)
544    ///     {
545    ///         app.handle().report(err.to_notice("The restore did not work"));
546    ///     }
547    /// }
548    /// ```
549    ///
550    /// <div class="warning">Experimental: may change in any release
551    /// (docs/stability.md).</div>
552    pub fn take_failure(&self, command: &CommandId) -> Option<CommandError> {
553        lock(&self.0.bus.notices.settled).remove(command)
554    }
555
556    /// A command's result is in: its failure told in full is taken and
557    /// kept as its last failure ([`AppHandle::take_failure`]), and for a
558    /// run asked by [`AppHandle::run_reported`], a failure is reported at
559    /// its place.
560    pub(crate) fn settle_reported(
561        &self,
562        command: &CommandId,
563        args: &Json,
564        result: &Result<Json, String>,
565    ) {
566        let hub = &self.0.bus.notices;
567        let told = {
568            let mut f = lock(&hub.failures);
569            let at = f.iter().position(|(c, _)| c == command);
570            at.map(|i| f.remove(i).1)
571        };
572        let place = {
573            let mut r = lock(&hub.reported);
574            let at = r
575                .iter()
576                .position(|x| &x.command == command && &x.args == args);
577            at.map(|i| r.remove(i).place)
578        };
579        let Err(text) = result else {
580            lock(&hub.settled).remove(command);
581            return;
582        };
583        let err = told
584            .filter(|e| e.to_string() == *text)
585            .unwrap_or_else(|| CommandError::from(text.as_str()));
586        lock(&hub.settled).insert(command.clone(), err.clone());
587        let Some(place) = place else {
588            return;
589        };
590        let title = self
591            .command(command)
592            .map_or_else(|| command.to_string(), |c| self.command_title(&c));
593        let generic = egui_pop_core::strings::tr_args(
594            &self.egui(),
595            &crate::strings::COMMAND_FAILED,
596            &[("command", title.as_str())],
597        );
598        let mut notice = err.to_notice(generic).place(place);
599        notice = notice.subject(format!("command:{command}"));
600        self.report(notice);
601    }
602}