use std::{
any::{Any, TypeId},
collections::HashMap,
fmt,
sync::Arc,
};
use gpui::{App, Global};
use super::QueryError;
type ServiceMap = HashMap<TypeId, Arc<dyn Any + Send + Sync>>;
#[derive(Clone, Default)]
pub struct TaskCx {
services: Arc<ServiceMap>,
}
impl TaskCx {
#[must_use]
pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
self.services.get(&TypeId::of::<T>())?.downcast_ref::<T>()
}
pub fn require<T: Any + Send + Sync>(&self) -> Result<&T, QueryError> {
self.get::<T>().ok_or_else(|| {
QueryError::msg(format!(
"no {} was provided; call rok_ui::query::provide at startup",
std::any::type_name::<T>()
))
})
}
}
impl fmt::Debug for TaskCx {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TaskCx")
.field("services", &self.services.len())
.finish()
}
}
#[derive(Default)]
struct Services(TaskCx);
impl Global for Services {}
pub fn provide<T: Any + Send + Sync>(cx: &mut App, value: T) {
let services = &mut cx.default_global::<Services>().0.services;
Arc::make_mut(services).insert(TypeId::of::<T>(), Arc::new(value));
}
pub fn unprovide<T: Any + Send + Sync>(cx: &mut App) {
let services = &mut cx.default_global::<Services>().0.services;
Arc::make_mut(services).remove(&TypeId::of::<T>());
}
#[must_use]
pub fn task_cx(cx: &App) -> TaskCx {
cx.try_global::<Services>()
.map(|services| services.0.clone())
.unwrap_or_default()
}