Skip to main content

egui_pop_api/
services.rs

1//! Services plugins share, by typed token.
2//!
3//! ```
4//! use egui_pop_api::services::ServiceToken;
5//!
6//! pub struct Clock { pub ticks: u64 }
7//! pub const CLOCK: ServiceToken<Clock> = ServiceToken::new("demo.clock");
8//! assert_eq!(CLOCK.id().as_str(), "demo.clock");
9//! ```
10
11use std::any::Any;
12use std::collections::BTreeMap;
13use std::fmt;
14use std::marker::PhantomData;
15use std::sync::Arc;
16
17use egui_pop_model::ids::{OwnerId, ServiceId};
18
19/// A service's id and type: `ctx.service(&TOKEN, value)` provides it,
20/// `app.service(&TOKEN)` gets it back typed.
21pub struct ServiceToken<T: ?Sized> {
22    id: ServiceId,
23    _type: PhantomData<fn() -> Arc<T>>,
24}
25
26impl<T: ?Sized> ServiceToken<T> {
27    pub const fn new(id: &'static str) -> Self {
28        Self {
29            id: ServiceId::from_static(id),
30            _type: PhantomData,
31        }
32    }
33
34    pub fn id(&self) -> &ServiceId {
35        &self.id
36    }
37}
38
39impl<T: ?Sized> fmt::Debug for ServiceToken<T> {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(
42            f,
43            "ServiceToken({}: {})",
44            self.id,
45            std::any::type_name::<T>()
46        )
47    }
48}
49
50#[derive(Default)]
51pub(crate) struct Services {
52    map: BTreeMap<ServiceId, (OwnerId, Arc<dyn Any + Send + Sync>, &'static str)>,
53}
54
55impl fmt::Debug for Services {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_map()
58            .entries(self.map.iter().map(|(k, (o, _, t))| (k, (o, t))))
59            .finish()
60    }
61}
62
63impl Services {
64    pub fn provide<T: Send + Sync + 'static>(
65        &mut self,
66        owner: &OwnerId,
67        token: &ServiceToken<T>,
68        value: Arc<T>,
69    ) -> Result<(), OwnerId> {
70        if let Some((by, _, _)) = self.map.get(&token.id) {
71            return Err(by.clone());
72        }
73        self.map.insert(
74            token.id.clone(),
75            (owner.clone(), value, std::any::type_name::<T>()),
76        );
77        Ok(())
78    }
79
80    pub fn get<T: Send + Sync + 'static>(&self, token: &ServiceToken<T>) -> Option<Arc<T>> {
81        self.map
82            .get(&token.id)
83            .and_then(|(_, v, _)| v.clone().downcast::<T>().ok())
84    }
85
86    pub fn remove_owner(&mut self, owner: &OwnerId) {
87        self.map.retain(|_, (o, _, _)| o != owner);
88    }
89
90    /// Id, owner and type name of each service.
91    pub fn list(&self) -> Vec<(ServiceId, OwnerId, &'static str)> {
92        self.map
93            .iter()
94            .map(|(k, (o, _, t))| (k.clone(), o.clone(), *t))
95            .collect()
96    }
97}