use std::{
any::TypeId,
collections::HashMap,
hash::{BuildHasher, Hash},
};
use collections::FxBuildHasher;
use gpui_util::TypeIdHashBuilder;
use crate::{App, EntityId, Subscription};
pub(crate) type EntityNotices = Pending<EntityId, FxBuildHasher>;
pub(crate) type GlobalNotices = Pending<TypeId, TypeIdHashBuilder>;
pub(crate) struct Pending<K, S> {
notices: HashMap<K, u64, S>,
changes: u64,
}
impl<K, S: Default> Default for Pending<K, S> {
fn default() -> Self {
Self {
notices: HashMap::default(),
changes: 0,
}
}
}
impl<K: Hash + Eq, S: BuildHasher> Pending<K, S> {
fn note_change(&mut self, key: K) -> bool {
self.changes += 1;
self.notices.insert(key, self.changes).is_none()
}
fn take_notice(&mut self, key: &K) -> u64 {
self.notices.remove(key).unwrap_or(self.changes)
}
}
pub(crate) struct Observer {
began_after: u64,
handler: Box<dyn FnMut(&mut App) -> bool + 'static>,
}
pub(crate) fn note_entity_change(cx: &mut App, entity: EntityId) -> bool {
cx.pending_notifications.note_change(entity)
}
pub(crate) fn note_global_change(cx: &mut App, global: TypeId) -> bool {
cx.pending_global_notifications.note_change(global)
}
pub(crate) fn take_entity_notice(cx: &mut App, entity: EntityId) -> u64 {
cx.pending_notifications.take_notice(&entity)
}
pub(crate) fn take_global_notice(cx: &mut App, global: TypeId) -> u64 {
cx.pending_global_notifications.take_notice(&global)
}
pub(crate) fn tell(observer: &mut Observer, told: u64, cx: &mut App) -> bool {
observer.began_after >= told || (observer.handler)(cx)
}
pub(crate) fn observe_entity(
cx: &App,
entity: EntityId,
handler: Box<dyn FnMut(&mut App) -> bool + 'static>,
) -> Subscription {
let observer = Observer {
began_after: cx.pending_notifications.changes,
handler,
};
cx.observers.insert(entity, observer)
}
pub(crate) fn observe_global(
cx: &App,
global: TypeId,
handler: Box<dyn FnMut(&mut App) -> bool + 'static>,
) -> Subscription {
let observer = Observer {
began_after: cx.pending_global_notifications.changes,
handler,
};
cx.global_observers.insert(global, observer)
}