refcount ids and delete unused
This commit is contained in:
@@ -6,6 +6,7 @@ use crate::{
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
ops::{Index, IndexMut},
|
||||
sync::mpsc::{Receiver, Sender, channel},
|
||||
};
|
||||
|
||||
pub struct Ui<Ctx> {
|
||||
@@ -13,6 +14,8 @@ pub struct Ui<Ctx> {
|
||||
base: Option<WidgetId>,
|
||||
widgets: Widgets<Ctx>,
|
||||
updates: Vec<WidgetId>,
|
||||
del_recv: Receiver<Id>,
|
||||
del_send: Sender<Id>,
|
||||
pub(super) active_sensors: ActiveSensors,
|
||||
pub(super) sensor_map: SensorMap<Ctx>,
|
||||
primitives: Primitives,
|
||||
@@ -35,9 +38,9 @@ impl<Ctx> Ui<Ctx> {
|
||||
}
|
||||
|
||||
pub fn push<W: Widget<Ctx>>(&mut self, w: W) -> WidgetId<W> {
|
||||
let id = self.ids.next();
|
||||
self.widgets.insert(id.duplicate(), w);
|
||||
WidgetId::new(id, TypeId::of::<W>())
|
||||
let id = self.id();
|
||||
self.widgets.insert(id.id.duplicate(), w);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn set<W: Widget<Ctx>>(&mut self, i: &WidgetId<W>, w: W) {
|
||||
@@ -65,7 +68,7 @@ impl<Ctx> Ui<Ctx> {
|
||||
}
|
||||
|
||||
pub fn id<W: Widget<Ctx>>(&mut self) -> WidgetId<W> {
|
||||
WidgetId::new(self.ids.next(), TypeId::of::<W>())
|
||||
WidgetId::new(self.ids.next(), TypeId::of::<W>(), self.del_send.clone())
|
||||
}
|
||||
|
||||
pub fn redraw_all(&mut self, ctx: &mut Ctx)
|
||||
@@ -89,6 +92,10 @@ impl<Ctx> Ui<Ctx> {
|
||||
where
|
||||
Ctx: 'static,
|
||||
{
|
||||
while let Ok(id) = self.del_recv.try_recv() {
|
||||
self.widgets.delete(id);
|
||||
}
|
||||
|
||||
if self.full_redraw {
|
||||
self.redraw_all(ctx);
|
||||
self.full_redraw = false;
|
||||
@@ -105,6 +112,10 @@ impl<Ctx> Ui<Ctx> {
|
||||
pub fn needs_redraw(&self) -> bool {
|
||||
self.full_redraw || !self.updates.is_empty()
|
||||
}
|
||||
|
||||
pub fn num_widgets(&self) -> usize {
|
||||
self.widgets.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Widget<Ctx>, Ctx> Index<&WidgetId<W>> for Ui<Ctx> {
|
||||
@@ -146,6 +157,18 @@ impl<Ctx> Widgets<Ctx> {
|
||||
pub fn insert_any(&mut self, id: Id, widget: Box<dyn Widget<Ctx>>) {
|
||||
self.0.insert(id, widget);
|
||||
}
|
||||
|
||||
pub fn delete(&mut self, id: Id) {
|
||||
self.0.remove(&id);
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx> dyn Widget<Ctx> {
|
||||
@@ -160,6 +183,7 @@ impl<Ctx> dyn Widget<Ctx> {
|
||||
|
||||
impl<Ctx: 'static> Default for Ui<Ctx> {
|
||||
fn default() -> Self {
|
||||
let (del_send, del_recv) = channel();
|
||||
Self {
|
||||
ids: Default::default(),
|
||||
base: Default::default(),
|
||||
@@ -169,6 +193,8 @@ impl<Ctx: 'static> Default for Ui<Ctx> {
|
||||
full_redraw: false,
|
||||
active_sensors: Default::default(),
|
||||
sensor_map: Default::default(),
|
||||
del_send,
|
||||
del_recv,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user