94 lines
2.7 KiB
Rust
94 lines
2.7 KiB
Rust
use crate::{
|
|
IdLike, Widget, WidgetData, WidgetId,
|
|
util::{DynBorrower, HashSet, SlotVec},
|
|
};
|
|
|
|
pub struct Widgets<State> {
|
|
pub needs_redraw: HashSet<WidgetId>,
|
|
vec: SlotVec<WidgetData<State>>,
|
|
}
|
|
|
|
impl<State> Default for Widgets<State> {
|
|
fn default() -> Self {
|
|
Self {
|
|
needs_redraw: Default::default(),
|
|
vec: Default::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<State: 'static> Widgets<State> {
|
|
pub fn has_updates(&self) -> bool {
|
|
!self.needs_redraw.is_empty()
|
|
}
|
|
|
|
pub fn get_dyn(&self, id: WidgetId) -> Option<&dyn Widget<State>> {
|
|
Some(self.vec.get(id)?.widget.as_ref())
|
|
}
|
|
|
|
pub fn get_dyn_mut(&mut self, id: WidgetId) -> Option<&mut dyn Widget<State>> {
|
|
self.needs_redraw.insert(id);
|
|
Some(self.vec.get_mut(id)?.widget.as_mut())
|
|
}
|
|
|
|
/// get_dyn but dynamic borrow checking of widgets
|
|
/// lets you do recursive (tree) operations, like the painter does
|
|
pub(crate) fn get_dyn_dynamic<'a>(&self, id: WidgetId) -> WidgetWrapper<'a, State> {
|
|
// SAFETY: must guarantee no other mutable references to this widget exist
|
|
// done through the borrow variable
|
|
#[allow(mutable_transmutes)]
|
|
let data = unsafe {
|
|
std::mem::transmute::<&WidgetData<State>, &mut WidgetData<State>>(
|
|
self.vec.get(id).unwrap(),
|
|
)
|
|
};
|
|
if data.borrowed {
|
|
panic!("tried to mutably borrow the same widget twice");
|
|
}
|
|
WidgetWrapper::new(data.widget.as_mut(), &mut data.borrowed)
|
|
}
|
|
|
|
pub fn get<I: IdLike<State>>(&self, id: &I) -> Option<&I::Widget>
|
|
where
|
|
I::Widget: Sized,
|
|
{
|
|
self.get_dyn(id.id())?.as_any().downcast_ref()
|
|
}
|
|
|
|
pub fn get_mut<I: IdLike<State>>(&mut self, id: &I) -> Option<&mut I::Widget>
|
|
where
|
|
I::Widget: Sized,
|
|
{
|
|
self.get_dyn_mut(id.id())?.as_any_mut().downcast_mut()
|
|
}
|
|
|
|
pub fn add<W: Widget<State>>(&mut self, widget: W) -> WidgetId {
|
|
self.vec.add(WidgetData::new(widget))
|
|
}
|
|
|
|
pub fn data(&self, id: impl IdLike<State>) -> Option<&WidgetData<State>> {
|
|
self.vec.get(id.id())
|
|
}
|
|
|
|
pub fn label(&self, id: impl IdLike<State>) -> &String {
|
|
&self.data(id.id()).unwrap().label
|
|
}
|
|
|
|
pub fn data_mut(&mut self, id: impl IdLike<State>) -> Option<&mut WidgetData<State>> {
|
|
self.vec.get_mut(id.id())
|
|
}
|
|
|
|
pub fn delete(&mut self, id: impl IdLike<State>) {
|
|
self.vec.free(id.id());
|
|
// not sure if there's any point in this
|
|
// self.updates.remove(&id);
|
|
}
|
|
|
|
#[allow(clippy::len_without_is_empty)]
|
|
pub fn len(&self) -> usize {
|
|
self.vec.len()
|
|
}
|
|
}
|
|
|
|
pub type WidgetWrapper<'a, State> = DynBorrower<'a, dyn Widget<State>>;
|