refcount ids and delete unused

This commit is contained in:
2025-08-16 19:15:21 -04:00
parent b2acbcc189
commit 368826fe05
8 changed files with 253 additions and 173 deletions

147
src/layout/id.rs Normal file
View File

@@ -0,0 +1,147 @@
use std::{
any::TypeId,
marker::PhantomData,
sync::{
Arc,
atomic::{AtomicU32, Ordering},
mpsc::Sender,
},
};
use crate::{FnTag, Ui, Widget, WidgetLike, WidgetTag, util::Id};
pub struct AnyWidget;
/// An identifier for a widget that can index a UI to get the associated widget.
/// It should always remain valid; it keeps a ref count and removes the widget from the UI if all
/// references are dropped.
///
/// W does not need to implement widget so that AnyWidget is valid;
/// Instead, add generic bounds on methods that take an ID if they need specific data.
#[repr(C)]
pub struct WidgetId<W = AnyWidget> {
pub(super) ty: TypeId,
pub(super) id: Id,
pub(super) refcount: Arc<AtomicU32>,
pub(super) send: Sender<Id>,
_pd: PhantomData<W>,
}
impl<W> std::fmt::Debug for WidgetId<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.id.fmt(f)
}
}
impl<W> Clone for WidgetId<W> {
fn clone(&self) -> Self {
self.refcount.fetch_add(1, Ordering::Release);
Self {
id: self.id.duplicate(),
ty: self.ty,
refcount: self.refcount.clone(),
send: self.send.clone(),
_pd: PhantomData,
}
}
}
impl<W> WidgetId<W> {
pub(super) fn new(id: Id, ty: TypeId, send: Sender<Id>) -> Self {
Self {
ty,
id,
refcount: AtomicU32::new(0).into(),
send,
_pd: PhantomData,
}
}
pub fn erase_type(self) -> WidgetId<AnyWidget> {
self.cast_type()
}
pub fn as_any(&self) -> &WidgetId<AnyWidget> {
// safety: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) }
}
pub(super) fn cast_type<W2>(self) -> WidgetId<W2> {
unsafe { std::mem::transmute(self) }
}
pub fn refs(&self) -> u32 {
self.refcount.load(Ordering::Acquire)
}
}
impl<W> Drop for WidgetId<W> {
fn drop(&mut self) {
let refs = self.refcount.fetch_sub(1, Ordering::Release);
if refs == 0 {
let _ = self.send.send(self.id.duplicate());
}
}
}
pub struct IdTag;
// pub trait WidgetIdFn<W, Ctx> = FnOnce(&mut Ui<Ctx>) -> WidgetId<W>;
macro_rules! WidgetIdFnRet {
($W:ty, $Ctx:ty) => {
impl FnOnce(&mut $crate::Ui<$Ctx>) -> $crate::WidgetId<$W>
};
($W:ty, $Ctx:ty, $($use:tt)*) => {
impl FnOnce(&mut $crate::Ui<$Ctx>) -> $crate::WidgetId<$W> + use<$($use)*>
};
}
pub(crate) use WidgetIdFnRet;
pub trait Idable<Ctx, Tag> {
type Widget: Widget<Ctx>;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>);
fn id<'a>(
self,
id: &WidgetId<Self::Widget>,
) -> WidgetIdFnRet!(Self::Widget, Ctx, 'a, Self, Ctx, Tag)
where
Self: Sized,
{
let id = id.clone();
move |ui| {
self.set(ui, &id);
id
}
}
}
impl<W: Widget<Ctx>, Ctx> Idable<Ctx, WidgetTag> for W {
type Widget = W;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>) {
ui.set(id, self);
}
}
impl<F: FnOnce(&mut Ui<Ctx>) -> W, W: Widget<Ctx>, Ctx> Idable<Ctx, FnTag> for F {
type Widget = W;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>) {
let w = self(ui);
ui.set(id, w);
}
}
impl<W: 'static, Ctx> WidgetLike<Ctx, FnTag> for WidgetId<W> {
type Widget = W;
fn add(self, _: &mut Ui<Ctx>) -> WidgetId<W> {
self
}
}
impl<W: 'static, F: FnOnce(&mut Ui<Ctx>) -> WidgetId<W>, Ctx> WidgetLike<Ctx, IdTag> for F {
type Widget = W;
fn add(self, ui: &mut Ui<Ctx>) -> WidgetId<W> {
self(ui)
}
}

View File

@@ -5,6 +5,7 @@ mod sense;
mod ui;
mod vec2;
mod widget;
mod id;
pub use color::*;
pub use painter::*;
@@ -13,5 +14,6 @@ pub use sense::*;
pub use ui::*;
pub use vec2::*;
pub use widget::*;
pub use id::*;
pub type UiColor = Color<u8>;

View File

@@ -12,27 +12,19 @@ pub struct UiPos {
}
impl UiPos {
pub const fn anchor_offset(anchor_x: f32, anchor_y: f32, offset_x: f32, offset_y: f32) -> Self {
Self {
anchor: vec2(anchor_x, anchor_y),
offset: vec2(offset_x, offset_y),
}
}
pub const fn center() -> Self {
Self::anchor_offset(0.5, 0.5, 0.0, 0.0)
Self::anchor(vec2(0.5, 0.5))
}
pub const fn anchor(anchor: Vec2) -> Self {
Self::anchor_offset(anchor.x, anchor.y, 0.0, 0.0)
Self {
anchor,
offset: Vec2::ZERO,
}
}
pub const fn top_left() -> Self {
Self::anchor_offset(0.0, 0.0, 0.0, 0.0)
}
pub const fn bottom_right() -> Self {
Self::anchor_offset(1.0, 1.0, 0.0, 0.0)
pub const fn corner(corner: Corner) -> Self {
Self::anchor(corner.anchor())
}
pub const fn shift(&mut self, offset: Vec2) {
@@ -126,8 +118,8 @@ pub struct UiRegion {
impl UiRegion {
pub const fn full() -> Self {
Self {
top_left: UiPos::top_left(),
bot_right: UiPos::bottom_right(),
top_left: UiPos::corner(Corner::TopLeft),
bot_right: UiPos::corner(Corner::BotRight),
}
}
pub fn center() -> Self {
@@ -178,17 +170,10 @@ impl UiRegion {
self
}
pub fn top_left() -> Self {
pub fn corner(corner: Corner) -> Self {
Self {
top_left: UiPos::top_left(),
bot_right: UiPos::top_left(),
}
}
pub fn bottom_right() -> Self {
Self {
top_left: UiPos::bottom_right(),
bot_right: UiPos::bottom_right(),
top_left: UiPos::corner(corner),
bot_right: UiPos::corner(corner),
}
}
@@ -236,3 +221,22 @@ impl UIScalarView<'_> {
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum Corner {
TopLeft,
TopRight,
BotLeft,
BotRight,
}
impl Corner {
pub const fn anchor(&self) -> Vec2 {
match self {
Corner::TopLeft => vec2(0.0, 0.0),
Corner::TopRight => vec2(1.0, 0.0),
Corner::BotLeft => vec2(0.0, 1.0),
Corner::BotRight => vec2(1.0, 1.0),
}
}
}

View File

@@ -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,
}
}
}

View File

@@ -1,72 +1,12 @@
use std::{
any::{Any, TypeId},
marker::PhantomData,
};
use crate::{Painter, Ui, util::Id};
use crate::{Painter, Ui, WidgetId, WidgetIdFnRet};
use std::{any::Any, marker::PhantomData};
pub trait Widget<Ctx>: Any {
fn draw(&self, painter: &mut Painter<Ctx>);
}
pub struct AnyWidget;
/// An identifier for a widget.
/// Can index a UI to get the associated widget.
///
/// W does not need to implement widget so that AnyWidget is valid;
/// Instead, add generic bounds on methods that take an ID if they need specific data.
#[repr(C)]
#[derive(Eq, Hash, PartialEq)]
pub struct WidgetId<W = AnyWidget> {
pub(super) ty: TypeId,
pub(super) id: Id,
_pd: PhantomData<W>,
}
impl<W> std::fmt::Debug for WidgetId<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.id.fmt(f)
}
}
// TODO: temp
impl<W> Clone for WidgetId<W> {
fn clone(&self) -> Self {
Self::new(self.id.duplicate(), self.ty)
}
}
impl<W> WidgetId<W> {
pub(super) fn new(id: Id, ty: TypeId) -> Self {
Self {
ty,
id,
_pd: PhantomData,
}
}
pub fn erase_type(self) -> WidgetId<AnyWidget> {
self.cast_type()
}
pub fn as_any(&self) -> &WidgetId<AnyWidget> {
// safety: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) }
}
fn cast_type<W2>(self) -> WidgetId<W2> {
WidgetId {
ty: self.ty,
id: self.id,
_pd: PhantomData,
}
}
}
pub struct WidgetTag;
pub struct FnTag;
pub struct IdTag;
pub trait WidgetLike<Ctx, Tag> {
type Widget: 'static;
@@ -85,63 +25,18 @@ pub trait WidgetLike<Ctx, Tag> {
}
}
// A function that returns a widget given a UI.
// Useful for defining trait functions on widgets that create a parent widget so that the children
// don't need to be IDs yet
// pub trait WidgetFn<W: Widget<Ctx>, Ctx> = FnOnce(&mut Ui<Ctx>) -> W;
// pub trait WidgetIdFn<W, Ctx> = FnOnce(&mut Ui<Ctx>) -> WidgetId<W>;
// copium for rust analyzer
/// A function that returns a widget given a UI.
/// Useful for defining trait functions on widgets that create a parent widget so that the children
/// don't need to be IDs yet
/// currently a macro for rust analyzer (doesn't support trait aliases atm)
macro_rules! WidgetFnRet {
($W:ty, $Ctx:ty) => {
impl FnOnce(&mut $crate::Ui<$Ctx>) -> $W
};
}
pub(crate) use WidgetFnRet;
macro_rules! WidgetIdFnRet {
($W:ty, $Ctx:ty) => {
impl FnOnce(&mut $crate::Ui<$Ctx>) -> $crate::WidgetId<$W>
};
($W:ty, $Ctx:ty, $($use:tt)*) => {
impl FnOnce(&mut $crate::Ui<$Ctx>) -> $crate::WidgetId<$W> + use<$($use)*>
};
}
pub(crate) use WidgetIdFnRet;
pub trait Idable<Ctx, Tag> {
type Widget: Widget<Ctx>;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>);
fn id<'a>(
self,
id: &WidgetId<Self::Widget>,
) -> WidgetIdFnRet!(Self::Widget, Ctx, 'a, Self, Ctx, Tag)
where
Self: Sized,
{
let id = id.clone();
move |ui| {
self.set(ui, &id);
id
}
}
}
impl<W: Widget<Ctx>, Ctx> Idable<Ctx, WidgetTag> for W {
type Widget = W;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>) {
ui.set(id, self);
}
}
impl<F: FnOnce(&mut Ui<Ctx>) -> W, W: Widget<Ctx>, Ctx> Idable<Ctx, FnTag> for F {
type Widget = W;
fn set(self, ui: &mut Ui<Ctx>, id: &WidgetId<Self::Widget>) {
let w = self(ui);
ui.set(id, w);
}
}
impl<W: Widget<Ctx>, Ctx, F: FnOnce(&mut Ui<Ctx>) -> W> WidgetLike<Ctx, FnTag> for F {
type Widget = W;
@@ -151,13 +46,6 @@ impl<W: Widget<Ctx>, Ctx, F: FnOnce(&mut Ui<Ctx>) -> W> WidgetLike<Ctx, FnTag> f
}
}
impl<W: 'static, F: FnOnce(&mut Ui<Ctx>) -> WidgetId<W>, Ctx> WidgetLike<Ctx, IdTag> for F {
type Widget = W;
fn add(self, ui: &mut Ui<Ctx>) -> WidgetId<W> {
self(ui)
}
}
impl<W: Widget<Ctx>, Ctx> WidgetLike<Ctx, WidgetTag> for W {
type Widget = W;
fn add(self, ui: &mut Ui<Ctx>) -> WidgetId<W> {
@@ -165,13 +53,6 @@ impl<W: Widget<Ctx>, Ctx> WidgetLike<Ctx, WidgetTag> for W {
}
}
impl<W: 'static, Ctx> WidgetLike<Ctx, FnTag> for WidgetId<W> {
type Widget = W;
fn add(self, _: &mut Ui<Ctx>) -> WidgetId<W> {
self
}
}
pub struct WidgetArr<const LEN: usize, Ws> {
pub arr: [WidgetId; LEN],
_pd: PhantomData<Ws>,