use core::any::{Any, TypeId, type_name};
use core::cell::RefCell;
use core::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::fmt;
use super::FromView;
use crate::page::ViewContext;
#[derive(Default)]
pub(crate) struct TypeMap(RefCell<HashMap<TypeId, Option<Box<dyn Any>>>>);
impl TypeMap {
fn take<T: Default + 'static>(&self) -> Box<T> {
let mut map = self.0.borrow_mut();
let slot = map
.entry(TypeId::of::<T>())
.or_insert_with(|| Some(Box::new(T::default())));
let value = slot.take().unwrap_or_else(|| {
panic!(
"egui-kit: a view can only extract `{}` once",
type_name::<T>()
)
});
value.downcast().expect("stored by type")
}
fn put<T: 'static>(&self, value: Box<T>) {
self.0.borrow_mut().insert(TypeId::of::<T>(), Some(value));
}
pub(crate) fn take_all(&self) -> Self {
Self(RefCell::new(core::mem::take(&mut *self.0.borrow_mut())))
}
}
#[derive(Default)]
pub(crate) struct ViewStore {
pub(crate) page: TypeMap,
pub(crate) snapshot: TypeMap,
}
impl ViewStore {
pub(crate) fn restored(left: &Self) -> Self {
Self {
page: TypeMap::default(),
snapshot: left.snapshot.take_all(),
}
}
}
macro_rules! view_state {
($(#[$doc:meta])* $name:ident, $map:ident) => {
$(#[$doc])*
pub struct $name<'f, T: 'static> {
value: Option<Box<T>>,
map: &'f TypeMap,
}
impl<S: 'static, D, T: Default + 'static> FromView<S, D> for $name<'_, T> {
type Item<'f> = $name<'f, T>;
fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $name<'f, T> {
let map = &cx.store().$map;
$name {
value: Some(map.take()),
map,
}
}
}
impl<T> Deref for $name<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value.as_ref().expect("present until dropped")
}
}
impl<T> DerefMut for $name<'_, T> {
fn deref_mut(&mut self) -> &mut T {
self.value.as_mut().expect("present until dropped")
}
}
impl<T> Drop for $name<'_, T> {
fn drop(&mut self) {
if let Some(value) = self.value.take() {
self.map.put(value);
}
}
}
impl<T: fmt::Debug> fmt::Debug for $name<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple(stringify!($name)).field(&**self).finish()
}
}
};
}
view_state!(
PageState,
page
);
view_state!(
Snapshot,
snapshot
);