use std::any::TypeId;
use std::fmt::Debug;
use crate::core::{FromDynWidget, MutateCtx, Property, Widget, WidgetId};
use crate::kurbo::Affine;
use crate::properties::core_property_changed;
#[non_exhaustive]
pub struct WidgetMut<'a, W: Widget + ?Sized> {
pub widget: &'a mut W,
pub ctx: MutateCtx<'a>,
}
impl<W: Widget + ?Sized> Drop for WidgetMut<'_, W> {
fn drop(&mut self) {
if let Some(parent_widget_state) = self.ctx.parent_widget_state.take() {
parent_widget_state.merge_up(self.ctx.widget_state);
}
}
}
impl<W: Widget + ?Sized> Debug for WidgetMut<'_, W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WidgetMut")
.field("widget", &self.widget.short_type_name())
.field("id", &self.ctx.widget_state.id)
.finish_non_exhaustive()
}
}
impl<W: Widget + ?Sized> WidgetMut<'_, W> {
pub fn id(&self) -> WidgetId {
self.ctx.widget_state.id
}
pub fn reborrow_mut(&mut self) -> WidgetMut<'_, W> {
let widget = &mut self.widget;
WidgetMut {
widget,
ctx: self.ctx.reborrow_mut(),
}
}
pub fn contains_prop<T: Property>(&self) -> bool {
self.ctx.properties.contains::<T>()
}
pub fn get_prop<T: Property>(&mut self) -> &T {
self.ctx
.properties
.get::<T>(&mut self.ctx.widget_state.property_cache)
}
pub fn insert_prop<P: Property>(&mut self, value: P) -> Option<P> {
let value = self.ctx.properties.insert(value);
let mut ctx = self.ctx.update_mut();
let property_type = TypeId::of::<P>();
core_property_changed(&mut ctx, property_type);
self.widget.property_changed(&mut ctx, property_type);
value
}
pub fn remove_prop<P: Property>(&mut self) -> Option<P> {
let value = self.ctx.properties.remove::<P>();
let mut ctx = self.ctx.update_mut();
let property_type = TypeId::of::<P>();
core_property_changed(&mut ctx, property_type);
self.widget.property_changed(&mut ctx, property_type);
value
}
pub fn set_transform(&mut self, transform: Affine) {
self.ctx.set_transform(transform);
}
pub fn try_downcast<W2: Widget + FromDynWidget + ?Sized>(
&mut self,
) -> Option<WidgetMut<'_, W2>> {
Some(WidgetMut {
ctx: self.ctx.reborrow_mut(),
widget: W2::from_dyn_mut(self.widget.as_mut_dyn())?,
})
}
pub fn downcast<W2: Widget + FromDynWidget + ?Sized>(&mut self) -> WidgetMut<'_, W2> {
let w1_name = self.widget.type_name();
match W2::from_dyn_mut(self.widget.as_mut_dyn()) {
Some(widget) => WidgetMut {
widget,
ctx: self.ctx.reborrow_mut(),
},
None => {
panic!(
"failed to downcast widget: expected widget of type `{}`, found `{}`",
std::any::type_name::<W2>(),
w1_name,
);
}
}
}
}