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: 'static>(&self, init: impl FnOnce() -> T) -> Box<T> {
let mut map = self.0.borrow_mut();
let slot = map
.entry(TypeId::of::<T>())
.or_insert_with(|| Some(Box::new(init())));
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));
}
fn contains<T: 'static>(&self) -> bool {
self.0.borrow().contains_key(&TypeId::of::<T>())
}
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(),
}
}
}
fn from_data<S, D: 'static, T: for<'d> From<&'d D>>(cx: &ViewContext<'_, S>) -> T {
cx.peek_data(|data| {
T::from(
data.downcast_ref::<D>()
.expect("egui-kit: the data does not match the view (this is a bug)"),
)
})
}
macro_rules! view_state {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
pub struct $name<'f, T: 'static> {
value: Option<Box<T>>,
map: &'f TypeMap,
}
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()
}
}
};
}
macro_rules! view_state_extractors {
($default:ident, $from:ident, $map:ident) => {
impl<S: 'static, D, T: Default + 'static> FromView<S, D> for $default<'_, T> {
type Item<'f> = $default<'f, T>;
fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $default<'f, T> {
let map = &cx.store().$map;
$default {
value: Some(map.take(T::default)),
map,
}
}
}
impl<S: 'static, D: 'static, T> FromView<S, D> for $from<'_, T>
where
T: for<'d> From<&'d D> + 'static,
{
type Item<'f> = $from<'f, T>;
fn prepare(cx: &ViewContext<'_, S>) {
let map = &cx.store().$map;
if !map.contains::<T>() {
map.put(Box::new(from_data::<S, D, T>(cx)));
}
}
fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> $from<'f, T> {
let map = &cx.store().$map;
$from {
value: Some(map.take(|| from_data::<S, D, T>(cx))),
map,
}
}
}
};
}
view_state!(
PageState
);
view_state!(
PageStateFrom
);
view_state!(
Snapshot
);
view_state!(
SnapshotFrom
);
view_state_extractors!(PageState, PageStateFrom, page);
view_state_extractors!(Snapshot, SnapshotFrom, snapshot);