use std::{
cell::{Cell, RefCell},
rc::Weak,
};
use smallvec::SmallVec;
use super::Subscribers;
use crate::{
RecomposeScope, RecomposeScopeInner, RuntimeHandle, ScopeId, StateId,
collections::map::HashMap, debug_trace::debug_record_scope_invalidation, runtime::StateArena,
with_current_composer_opt,
};
const INLINE_READERS: usize = 4;
pub(super) struct StateWatchers {
pub(super) scopes: RefCell<HashMap<ScopeId, Weak<RecomposeScopeInner>>>,
pub(super) runtime: RuntimeHandle,
pub(super) state_id: Cell<Option<StateId>>,
}
fn shrink_watchers_if_sparse(watchers: &mut HashMap<ScopeId, Weak<RecomposeScopeInner>>) {
let len = watchers.len();
let capacity = watchers.capacity();
if capacity > len.saturating_mul(4).max(32) {
watchers.shrink_to_fit();
}
}
impl StateWatchers {
pub(super) fn register_scope(
&self,
subscribers: &Subscribers,
scope: &RecomposeScope,
) -> (bool, bool) {
let mut watchers = self.scopes.borrow_mut();
let id = scope.id();
match watchers.get(&id) {
Some(existing) if existing.strong_count() > 0 => return (false, false),
Some(_) => {
watchers.remove(&id);
subscribers.remove_scope_observers(1);
}
None => {}
}
let any_live = watchers.values().any(|watcher| watcher.strong_count() > 0);
if !any_live || watchers.len() >= watchers.capacity() {
let before = watchers.len();
watchers.retain(|_, watcher| watcher.strong_count() > 0);
subscribers.remove_scope_observers(before - watchers.len());
}
watchers.insert(id, scope.downgrade());
drop(watchers);
(true, subscribers.add_scope_observer())
}
pub(super) fn has_subscribers(&self, subscribers: &Subscribers) -> bool {
let mut watchers = self.scopes.borrow_mut();
let before = watchers.len();
watchers.retain(|_, existing| existing.upgrade().is_some());
subscribers.remove_scope_observers(before - watchers.len());
subscribers.has_subscribers()
}
pub(super) fn forget_scope(&self, subscribers: &Subscribers, scope_id: ScopeId) {
let mut watchers = self.scopes.borrow_mut();
let removed = watchers.remove(&scope_id).is_some();
if removed {
shrink_watchers_if_sparse(&mut watchers);
}
drop(watchers);
subscribers.remove_scope_observers(usize::from(removed));
}
pub(super) fn unregister_scope(&self, subscribers: &Subscribers, scope_id: ScopeId) {
let mut watchers = self.scopes.borrow_mut();
let removed = if watchers
.get(&scope_id)
.is_some_and(|weak| weak.upgrade().is_none())
{
watchers.remove(&scope_id);
shrink_watchers_if_sparse(&mut watchers);
true
} else {
false
};
drop(watchers);
subscribers.remove_scope_observers(usize::from(removed));
}
pub(super) fn invalidate(&self, subscribers: &Subscribers, type_name: &'static str) {
if self.scopes.borrow().len() <= INLINE_READERS {
let mut live = SmallVec::<[RecomposeScope; INLINE_READERS]>::new();
self.copy_live(subscribers, &mut live);
self.invalidate_each(&live, type_name);
return;
}
let mut live = self
.runtime
.try_with_state_arena(StateArena::take_reader_list)
.unwrap_or_default();
self.copy_live(subscribers, &mut live);
self.invalidate_each(&live, type_name);
self.runtime
.try_with_state_arena(|arena| arena.recycle_reader_list(live));
}
fn copy_live(&self, subscribers: &Subscribers, live: &mut impl Extend<RecomposeScope>) {
let removed_count = {
let mut watchers = self.scopes.borrow_mut();
let before = watchers.len();
watchers.retain(|_, scope| {
if let Some(inner) = scope.upgrade() {
live.extend([RecomposeScope { inner }]);
true
} else {
false
}
});
let removed_count = before - watchers.len();
shrink_watchers_if_sparse(&mut watchers);
removed_count
};
subscribers.remove_scope_observers(removed_count);
}
fn invalidate_each(&self, live: &[RecomposeScope], type_name: &'static str) {
for watcher in live {
debug_record_scope_invalidation(watcher.id(), self.state_id.get(), type_name);
if let Some(state_id) = self.state_id.get() {
watcher.invalidate_from_state(state_id);
} else {
watcher.invalidate();
}
}
}
}
#[inline(never)]
pub(super) fn register_current_state_scope(watchers: &StateWatchers, subscribers: &Subscribers) {
let state_id = watchers.state_id.get();
let Some(Some((scope, read))) =
with_current_composer_opt(|composer| composer.note_state_read(state_id))
else {
return;
};
let (registered, became_subscribed) = watchers.register_scope(subscribers, &scope);
if let (crate::ScopeRead::NotReading, true, Some(state_id)) = (read, registered, state_id) {
scope.record_state_subscription(state_id);
}
if became_subscribed {
subscribers.notify_subscribers();
}
}