1use 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#[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#[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#[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#[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
82pub 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
90pub const NOTICE_STORE: &str = "pop.notices.store";
93
94pub const NOTICE_ROUTE: &str = "pop.notices.route";
97
98#[derive(Debug)]
101struct Reported {
102 command: CommandId,
103 args: Json,
104 place: String,
105}
106
107pub(crate) struct Hub {
111 pub(crate) store: Mutex<NoticeStore>,
112 policy: RwLock<Arc<dyn NoticeRouting>>,
113 routes: Mutex<HashMap<NoticeId, Route>>,
115 routed: Mutex<VecDeque<(Notice, Route)>>,
117 sites: Mutex<HashMap<String, (egui::ViewportId, u64)>>,
120 pub(crate) toasts: Mutex<Option<crate::toasts::Toasts>>,
122 ctx: Arc<Mutex<Option<egui::Context>>>,
124 reported: Mutex<Vec<Reported>>,
126 failures: Mutex<Vec<(CommandId, CommandError)>>,
128 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 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 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 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 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 pub(crate) fn rev(&self) -> u64 {
240 lock(&self.store).rev()
241 }
242
243 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 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 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
285pub(crate) type Store = Arc<Hub>;
287
288pub(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
334pub(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#[derive(Clone, Debug, Default, PartialEq)]
346#[non_exhaustive]
347pub struct NoticeBadge {
348 pub errors: usize,
350 pub warnings: usize,
352 pub unseen: Vec<Kept>,
354}
355
356impl NoticeBadge {
357 pub fn count(&self) -> usize {
359 self.unseen.len()
360 }
361}
362
363impl AppHandle {
364 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 pub fn resolve_notice(&self, id: impl Into<NoticeId>) {
388 emit_with::<NoticeResolved>(self, NoticeIds::one(id), ());
389 }
390
391 pub fn see_notice(&self, id: impl Into<NoticeId>) {
396 emit_with::<NoticeSeen>(self, NoticeIds::one(id), ());
397 }
398
399 pub fn dismiss_notice(&self, id: impl Into<NoticeId>) {
404 emit_with::<NoticeDismissed>(self, NoticeIds::one(id), ());
405 }
406
407 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 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 pub fn notices(&self) -> Vec<Kept> {
437 lock(&self.0.bus.notices.store).list().cloned().collect()
438 }
439
440 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 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 pub fn notice_route(&self, id: &NoticeId) -> Option<Route> {
472 self.0.bus.notices.route_of(id)
473 }
474
475 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 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 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 pub fn take_failure(&self, command: &CommandId) -> Option<CommandError> {
553 lock(&self.0.bus.notices.settled).remove(command)
554 }
555
556 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}