use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use waft_foundation::{App, Handle};
use super::element::{
AnyElement, BuildContext, Element, ElementData, ElementLifecycle, Slot,
debug_check_owner_build_target_exists,
};
use super::elements::{ComponentElement, ComponentElementData, ProxyElement};
use super::widget::{
InheritedWidget, IntoWidget, KeyRef, Widget, WidgetKind, WidgetRef, downcast_widget,
};
pub trait InheritedModel: InheritedWidget {
type Aspect: Clone + Eq + Hash + 'static;
fn update_should_notify_dependent(
&self,
old_widget: &Self,
dependencies: &HashSet<Self::Aspect>,
) -> bool;
fn is_supported_aspect(&self, aspect: &Self::Aspect) -> bool {
let _ = aspect;
true
}
fn inherit_from(
app: &mut App,
context: BuildContext,
aspect: Option<Self::Aspect>,
) -> Option<&Self>
where
Self: Sized,
{
let Some(aspect) = aspect else {
return context.depend_on_inherited_widget_of_exact_type::<Self>(app);
};
let mut models = Vec::new();
find_models::<Self>(app, context, &aspect, &mut models);
let last_model = *models.last()?;
for model in models {
let erased: Rc<dyn Any> = Rc::new(aspect.clone());
context.depend_on_inherited_element(app, model, Some(erased));
if model == last_model {
let widget: &WidgetRef = model.widget(app);
return downcast_widget::<Self>(&**widget);
}
}
unreachable!("the last model is in the list");
}
}
fn find_models<T: InheritedModel>(
app: &App,
context: BuildContext,
aspect: &T::Aspect,
results: &mut Vec<AnyElement>,
) {
let Some(model) = context.get_element_for_inherited_widget_of_exact_type::<T>(app) else {
return;
};
results.push(model);
let model_widget: &T = downcast_widget::<T>(&**model.widget(app))
.expect("an InheritedModel element holds its InheritedModel");
if model_widget.is_supported_aspect(aspect) {
return;
}
let mut model_parent = None;
model.visit_ancestor_elements(app, &mut |ancestor| {
model_parent = Some(ancestor);
false
});
let Some(model_parent) = model_parent else {
return;
};
find_models::<T>(app, model_parent, aspect, results);
}
pub struct InheritedModelKind;
pub struct InheritedModelWrapper<W: InheritedModel>(pub W);
impl<W: InheritedModel> IntoWidget<InheritedModelKind> for W {
fn into_widget(self) -> WidgetRef {
Rc::new(InheritedModelWrapper(self))
}
}
impl<W: InheritedModel> Widget for InheritedModelWrapper<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
InheritedModelElement::<W>::create(app, this)
}
fn as_any(&self) -> &dyn Any {
&self.0
}
fn widget_type(&self) -> TypeId {
TypeId::of::<W>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
}
impl<W: InheritedModel> Debug for InheritedModelWrapper<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub struct InheritedModelElement<W: InheritedModel> {
element: ElementData,
component: ComponentElementData,
dependents: HashMap<AnyElement, HashSet<W::Aspect>>,
marker: PhantomData<fn() -> W>,
}
impl<W: InheritedModel> InheritedModelElement<W> {
pub fn create(app: &mut App, widget: WidgetRef) -> AnyElement {
debug_assert!(downcast_widget::<W>(&*widget).is_some());
app.create(InheritedModelElement::<W> {
element: ElementData::new(widget),
component: ComponentElementData::default(),
dependents: HashMap::new(),
marker: PhantomData,
})
.as_element()
}
pub fn widget(self: Handle<Self>, app: &App) -> &W {
downcast_widget::<W>(&**self.as_element().widget(app))
.expect("an InheritedModelElement holds its InheritedModel")
}
pub fn get_dependencies(
self: Handle<Self>,
app: &App,
dependent: AnyElement,
) -> Option<&HashSet<W::Aspect>> {
app.get(self).dependents.get(&dependent)
}
pub fn set_dependencies(
self: Handle<Self>,
app: &mut App,
dependent: AnyElement,
value: HashSet<W::Aspect>,
) {
app.get_mut(self).dependents.insert(dependent, value);
}
pub fn notify_dependent(
self: Handle<Self>,
app: &mut App,
old_widget: &WidgetRef,
dependent: AnyElement,
) {
let Some(dependencies) = self.get_dependencies(app, dependent) else {
return;
};
let should_notify = dependencies.is_empty() || {
let old =
downcast_widget::<W>(&**old_widget).expect("the old widget has the same type");
self.widget(app)
.update_should_notify_dependent(old, dependencies)
};
if should_notify {
dependent.did_change_dependencies(app);
}
}
}
impl<W: InheritedModel> ComponentElement for InheritedModelElement<W> {
fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
&app.get(self).component
}
fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
&mut app.get_mut(self).component
}
fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
self.proxied_child(app)
}
}
impl<W: InheritedModel> ProxyElement for InheritedModelElement<W> {
fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
self.widget(app).child().clone()
}
fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
let should_notify = {
let old =
&downcast_widget::<W>(&*old_widget).expect("the old widget has the same type");
self.widget(app).update_should_notify(old)
};
if should_notify {
self.notify_clients(app, old_widget);
}
}
fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
debug_assert!(debug_check_owner_build_target_exists(
self.as_element(),
app,
"notifyClients"
));
let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
for dependent in dependents {
if cfg!(debug_assertions) {
let mut ancestor = dependent.parent(app);
while let Some(current) = ancestor
&& current != self.as_element()
{
ancestor = current.parent(app);
}
debug_assert!(ancestor == Some(self.as_element()));
debug_assert!(dependent.does_depend_on_inherited_element(app, self.as_element()));
}
self.notify_dependent(app, &old_widget, dependent);
}
}
}
impl<W: InheritedModel> Element for InheritedModelElement<W> {
crate::element_accessors!();
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
ComponentElement::visit_children_component(self, app, visitor);
}
fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
ComponentElement::child(self, app)
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
ComponentElement::forget_child(self, app, child);
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
ComponentElement::mount(self, app, parent, new_slot);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
ProxyElement::update(self, app, new_widget);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
ComponentElement::perform_rebuild(self, app);
}
fn update_inheritance(self: Handle<Self>, app: &mut App) {
debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
let incoming = self
.as_element()
.parent(app)
.and_then(|parent| parent.inherited_elements(app));
let mut widgets: HashMap<TypeId, AnyElement> = incoming
.map(|incoming| (*incoming).clone())
.unwrap_or_default();
widgets.insert(TypeId::of::<W>(), self.as_element());
self.as_element()
.set_inherited_elements(app, Some(Rc::new(widgets)));
}
fn debug_deactivated(self: Handle<Self>, app: &mut App) {
debug_assert!(app.get(self).dependents.is_empty());
debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
}
const IS_INHERITED_ELEMENT: bool = true;
fn update_dependencies(
self: Handle<Self>,
app: &mut App,
dependent: AnyElement,
aspect: Option<Rc<dyn Any>>,
) {
if self
.get_dependencies(app, dependent)
.is_some_and(HashSet::is_empty)
{
return;
}
match aspect {
None => self.set_dependencies(app, dependent, HashSet::new()),
Some(aspect) => {
let aspect = (*aspect)
.downcast_ref::<W::Aspect>()
.expect("an InheritedModel dependency names one of the model's aspects")
.clone();
app.get_mut(self)
.dependents
.entry(dependent)
.or_default()
.insert(aspect);
}
}
}
fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
app.get_mut(self).dependents.remove(&dependent);
}
}