remove modules and have single event manager (atomics feature parity + preparation for local state)

This commit is contained in:
2025-12-12 01:46:24 -05:00
parent a708813ce7
commit 37b1987aa8
17 changed files with 390 additions and 432 deletions

View File

@@ -1,26 +1,172 @@
use crate::{Ui, UiModule, Widget, WidgetId, WidgetRef, util::HashMap};
use crate::{
ActiveData, IdLike, LayerId, Ui, Widget, WidgetData, WidgetId, WidgetRef, util::HashMap,
};
use std::{
hash::Hash,
any::{Any, TypeId},
ops::{Index, IndexMut},
rc::Rc,
};
pub trait Event: Sized {
type Module<Ctx: 'static>: EventModule<Self, Ctx>;
type Data: Clone;
pub trait Event: Sized + 'static + Clone {
type Data<'a> = ();
type State: Default = ();
#[allow(unused_variables)]
fn should_run(&self, data: &mut Self::Data<'_>) -> bool {
true
}
}
pub trait EventLike {
type Event: Event;
fn into_event(self) -> Self::Event;
}
impl<E: Event> EventLike for E {
type Event = Self;
fn into_event(self) -> Self::Event {
self
}
}
pub struct EventCtx<'a, Ctx, Data> {
pub ui: &'a mut Ui,
pub state: &'a mut Ctx,
pub data: Data,
pub data: &'a mut Data,
}
pub struct EventIdCtx<'a, Ctx, Data, W: ?Sized> {
pub widget: WidgetRef<W>,
pub ui: &'a mut Ui,
pub state: &'a mut Ctx,
pub data: Data,
pub data: &'a mut Data,
}
#[derive(Default)]
pub struct EventManager {
types: HashMap<TypeId, Box<dyn EventManagerLike>>,
}
impl EventManager {
pub fn get_type<E: EventLike, Ctx: 'static>(&mut self) -> &mut TypeEventManager<E::Event, Ctx> {
self.types
.entry(Self::type_key::<E, Ctx>())
.or_insert(Box::new(TypeEventManager::<E::Event, Ctx>::default()))
.as_any()
.downcast_mut()
.unwrap()
}
pub fn register<I: IdLike, E: EventLike, Ctx: 'static>(
&mut self,
id: I,
event: E,
f: impl for<'a> EventFn<Ctx, <E::Event as Event>::Data<'a>>,
) {
self.get_type::<E, Ctx>().register(id, event, f);
}
pub fn type_key<E: EventLike, Ctx: 'static>() -> TypeId {
TypeId::of::<TypeEventManager<E::Event, Ctx>>()
}
pub fn remove(&mut self, id: WidgetId) {
for m in self.types.values_mut() {
m.remove(id);
}
}
pub fn draw(&mut self, data: &WidgetData, active: &ActiveData) {
for t in &data.event_mgrs {
self.types.get_mut(t).unwrap().draw(active);
}
}
pub fn undraw(&mut self, data: &WidgetData, active: &ActiveData) {
for t in &data.event_mgrs {
self.types.get_mut(t).unwrap().undraw(active);
}
}
}
pub trait EventManagerLike {
fn remove(&mut self, id: WidgetId);
fn draw(&mut self, data: &ActiveData);
fn undraw(&mut self, data: &ActiveData);
fn as_any(&mut self) -> &mut dyn Any;
}
type EventData<E, Ctx> = (E, Rc<dyn for<'a> EventFn<Ctx, <E as Event>::Data<'a>>>);
pub struct TypeEventManager<E: Event, Ctx> {
// TODO: reduce visiblity!!
pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>,
map: HashMap<WidgetId, Vec<EventData<E, Ctx>>>,
}
impl<E: Event, Ctx: 'static> EventManagerLike for TypeEventManager<E, Ctx> {
fn remove(&mut self, id: WidgetId) {
self.map.remove(&id);
for layer in self.active.values_mut() {
layer.remove(&id);
}
}
fn draw(&mut self, data: &ActiveData) {
self.active
.entry(data.layer)
.or_default()
.entry(data.id)
.or_default();
}
fn undraw(&mut self, data: &ActiveData) {
if let Some(layer) = self.active.get_mut(&data.layer) {
layer.remove(&data.id);
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
impl<E: Event, Ctx> Default for TypeEventManager<E, Ctx> {
fn default() -> Self {
Self {
active: Default::default(),
map: Default::default(),
}
}
}
impl<E: Event, Ctx: 'static> TypeEventManager<E, Ctx> {
fn register(
&mut self,
id: impl IdLike,
event: impl EventLike<Event = E>,
f: impl for<'a> EventFn<Ctx, E::Data<'a>>,
) {
let event = event.into_event();
self.map
.entry(id.id())
.or_default()
.push((event, Rc::new(f)));
}
fn run_fn<'a>(
&mut self,
id: impl IdLike,
) -> impl for<'b> FnOnce(EventCtx<Ctx, E::Data<'b>>) + 'a {
let fs = self.map.get(&id.id()).cloned().unwrap_or_default();
move |ctx| {
for (e, f) in fs {
if e.should_run(ctx.data) {
f(EventCtx {
ui: ctx.ui,
state: ctx.state,
data: ctx.data,
})
}
}
}
}
}
impl<'a, Ctx, Data, W2, W: Widget> Index<WidgetRef<W>> for EventIdCtx<'a, Ctx, Data, W2> {
@@ -52,120 +198,18 @@ impl<F: Fn(EventIdCtx<Ctx, Data, W>) + 'static, Ctx, Data, W: ?Sized> WidgetEven
{
}
pub trait DefaultEvent: Hash + Eq + 'static {
type Data: Clone = ();
}
impl<E: DefaultEvent> Event for E {
type Module<Ctx: 'static> = DefaultEventModule<E, Ctx>;
type Data = E::Data;
}
pub trait EventModule<E: Event, Ctx>: UiModule + Default {
fn register(&mut self, id: WidgetId, event: E, f: impl EventFn<Ctx, E::Data>);
fn run<'a>(
&self,
id: WidgetId,
event: E,
) -> Option<impl Fn(EventCtx<Ctx, E::Data>) + use<'a, Self, E, Ctx>>;
}
type EventFnMap<Ctx, Data> = HashMap<WidgetId, Vec<Rc<dyn EventFn<Ctx, Data>>>>;
pub struct DefaultEventModule<E: Event, Ctx> {
map: HashMap<E, EventFnMap<Ctx, <E as Event>::Data>>,
}
impl<E: Event + 'static, Ctx: 'static> UiModule for DefaultEventModule<E, Ctx> {
fn on_remove(&mut self, id: WidgetId) {
for map in self.map.values_mut() {
map.remove(&id);
}
}
}
pub trait HashableEvent: Event + Hash + Eq + 'static {}
impl<E: Event + Hash + Eq + 'static> HashableEvent for E {}
impl<E: HashableEvent, Ctx: 'static> EventModule<E, Ctx> for DefaultEventModule<E, Ctx> {
fn register(&mut self, id: WidgetId, event: E, f: impl EventFn<Ctx, <E as Event>::Data>) {
self.map
.entry(event)
.or_default()
.entry(id)
.or_default()
.push(Rc::new(f));
}
fn run<'a>(
&self,
id: WidgetId,
event: E,
) -> Option<impl Fn(EventCtx<Ctx, E::Data>) + use<'a, E, Ctx>> {
if let Some(map) = self.map.get(&event)
&& let Some(fs) = map.get(&id)
{
let fs = fs.clone();
Some(move |ctx: EventCtx<Ctx, <E as Event>::Data>| {
for f in &fs {
f(EventCtx {
ui: ctx.ui,
state: ctx.state,
data: ctx.data.clone(),
})
}
})
} else {
None
}
}
}
impl<E: HashableEvent, Ctx: 'static> DefaultEventModule<E, Ctx> {
pub fn run_all(&self, event: E, ctx: EventCtx<Ctx, E::Data>)
where
E::Data: Clone,
{
if let Some(map) = self.map.get(&event) {
for fs in map.values() {
for f in fs {
f(EventCtx {
ui: ctx.ui,
state: ctx.state,
data: ctx.data.clone(),
})
}
}
}
}
}
impl<E: Event + 'static, Ctx: 'static> Default for DefaultEventModule<E, Ctx> {
fn default() -> Self {
Self {
map: Default::default(),
}
}
}
impl Ui {
pub fn run_event<E: Event, Ctx: 'static, W>(
pub fn run_event<E: EventLike, Ctx: 'static>(
&mut self,
ctx: &mut Ctx,
id: WidgetRef<W>,
event: E,
data: E::Data,
id: impl IdLike,
data: &mut <E::Event as Event>::Data<'_>,
) {
if let Some(f) = self
.data
.modules
.get_mut::<E::Module<Ctx>>()
.run(id.id(), event)
{
f(EventCtx {
ui: self,
state: ctx,
data,
});
}
let f = self.data.events.get_type::<E, Ctx>().run_fn(id);
f(EventCtx {
ui: self,
state: ctx,
data,
})
}
}

View File

@@ -14,7 +14,6 @@
mod attr;
mod event;
mod module;
mod num;
mod orientation;
mod painter;
@@ -27,7 +26,6 @@ pub mod util;
pub use attr::*;
pub use event::*;
pub use module::*;
pub use num::*;
pub use orientation::*;
pub use painter::*;

View File

@@ -1,32 +0,0 @@
use std::any::{Any, TypeId};
use crate::{ActiveData, WidgetId, util::HashMap};
#[allow(unused_variables)]
pub trait UiModule: Any {
fn on_draw(&mut self, inst: &ActiveData) {}
fn on_undraw(&mut self, inst: &ActiveData) {}
fn on_remove(&mut self, id: WidgetId) {}
fn on_move(&mut self, inst: &ActiveData) {}
}
#[derive(Default)]
pub struct Modules {
map: HashMap<TypeId, Box<dyn UiModule>>,
}
impl Modules {
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (dyn UiModule + 'static)> {
self.map.values_mut().map(|m| m.as_mut())
}
pub fn get_mut<M: UiModule + Default>(&mut self) -> &mut M {
let rf = self
.map
.entry(TypeId::of::<M>())
.or_insert_with(|| Box::new(M::default()))
.as_mut();
let any: &mut dyn Any = &mut *rf;
any.downcast_mut().unwrap()
}
}

View File

@@ -1,5 +1,5 @@
use crate::{
Axis, Len, Modules, PrimitiveLayers, RenderedText, Size, TextAttrs, TextBuffer, TextData,
Axis, EventManager, Len, PrimitiveLayers, RenderedText, Size, TextAttrs, TextBuffer, TextData,
TextureHandle, Textures, UiRegion, UiVec2, WidgetHandle, WidgetId, Widgets,
render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst},
util::{HashMap, HashSet, TrackedArena, Vec2},
@@ -28,7 +28,7 @@ struct PainterCtx<'a> {
pub masks: &'a mut TrackedArena<Mask, u32>,
pub text: &'a mut TextData,
pub output_size: Vec2,
pub modules: &'a mut Modules,
pub events: &'a mut EventManager,
pub cache_width: HashMap<WidgetId, (UiVec2, Len)>,
pub cache_height: HashMap<WidgetId, (UiVec2, Len)>,
pub needs_redraw: &'a mut HashSet<WidgetId>,
@@ -66,7 +66,7 @@ pub struct PainterData {
pub textures: Textures,
pub text: TextData,
pub output_size: Vec2,
pub modules: Modules,
pub events: EventManager,
pub px_dependent: HashSet<WidgetId>,
pub masks: TrackedArena<Mask, u32>,
}
@@ -150,7 +150,7 @@ impl<'a> PainterCtx<'a> {
return finish(self, resize);
}
let Some(active) = self.remove(id) else {
let Some(active) = self.remove(id, false) else {
return;
};
@@ -204,7 +204,7 @@ impl<'a> PainterCtx<'a> {
return;
}
// if not, then maintain resize and track old children to remove unneeded
let active = self.remove(id).unwrap();
let active = self.remove(id, false).unwrap();
old_children = active.children;
resize = active.resize;
}
@@ -231,7 +231,7 @@ impl<'a> PainterCtx<'a> {
let children_height = painter.children_height;
// add to active
let instance = ActiveData {
let active = ActiveData {
id,
region,
parent,
@@ -260,16 +260,15 @@ impl<'a> PainterCtx<'a> {
// remove old children that weren't kept
for c in &old_children {
if !instance.children.contains(c) {
if !active.children.contains(c) {
self.remove_rec(*c);
}
}
// update modules
for m in self.modules.iter_mut() {
m.on_draw(&instance);
}
self.active.insert(id, instance);
let data = self.widgets.data(id).unwrap();
self.events.draw(data, &active);
self.active.insert(id, active);
}
fn mov(&mut self, id: WidgetId, from: UiRegion, to: UiRegion) {
@@ -279,9 +278,6 @@ impl<'a> PainterCtx<'a> {
*region = region.outside(&from).within(&to);
}
active.region = active.region.outside(&from).within(&to);
for m in self.modules.iter_mut() {
m.on_move(active);
}
// children will not be changed, so this technically should not be needed
// probably need unsafe
let children = active.children.clone();
@@ -291,26 +287,27 @@ impl<'a> PainterCtx<'a> {
}
/// NOTE: instance textures are cleared and self.textures freed
fn remove(&mut self, id: WidgetId) -> Option<ActiveData> {
let mut inst = self.active.remove(&id);
if let Some(inst) = &mut inst {
for h in &inst.primitives {
fn remove(&mut self, id: WidgetId, undraw: bool) -> Option<ActiveData> {
let mut active = self.active.remove(&id);
if let Some(active) = &mut active {
for h in &active.primitives {
let mask = self.layers.free(h);
if mask != MaskIdx::NONE {
self.masks.remove(mask);
}
}
inst.textures.clear();
active.textures.clear();
self.textures.free();
for m in self.modules.iter_mut() {
m.on_undraw(inst);
if undraw {
let data = self.widgets.data(id).unwrap();
self.events.undraw(data, active);
}
}
inst
active
}
fn remove_rec(&mut self, id: WidgetId) -> Option<ActiveData> {
let inst = self.remove(id);
let inst = self.remove(id, true);
if let Some(inst) = &inst {
for c in &inst.children {
self.remove_rec(*c);
@@ -329,7 +326,7 @@ impl PainterData {
textures: &mut self.textures,
text: &mut self.text,
output_size: self.output_size,
modules: &mut self.modules,
events: &mut self.events,
masks: &mut self.masks,
cache_width: Default::default(),
cache_height: Default::default(),

View File

@@ -2,6 +2,8 @@ use std::ops::{Index, IndexMut};
use crate::render::{MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst, Primitives};
pub type LayerId = usize;
struct LayerNode<T> {
next: Ptr,
prev: Ptr,
@@ -49,13 +51,13 @@ impl<T: Default> Layers<T> {
self.vec.push(LayerNode::head());
}
fn push(&mut self, node: LayerNode<T>) -> usize {
fn push(&mut self, node: LayerNode<T>) -> LayerId {
let i = self.vec.len();
self.vec.push(node);
i
}
pub fn next(&mut self, i: usize) -> usize {
pub fn next(&mut self, i: LayerId) -> LayerId {
if let Ptr::Next(i) = self.vec[i].next {
return i;
}
@@ -75,7 +77,7 @@ impl<T: Default> Layers<T> {
i_new
}
pub fn child(&mut self, i: usize) -> usize {
pub fn child(&mut self, i: LayerId) -> LayerId {
if let Some(c) = self.vec[i].child {
return c.head;
}
@@ -100,11 +102,11 @@ impl<T: Default> Layers<T> {
self.vec.iter_mut().map(|n| &mut n.data).enumerate()
}
pub fn iter(&self) -> impl Iterator<Item = (usize, &T)> {
pub fn iter(&self) -> impl Iterator<Item = (LayerId, &T)> {
self.indices().map(|i| (i, &self.vec[i].data))
}
pub fn iter_depth(&self) -> impl Iterator<Item = ((usize, usize), &T)> {
pub fn iter_depth(&self) -> impl Iterator<Item = ((LayerId, usize), &T)> {
self.indices()
.map(|i| ((i, self.vec[i].depth), &self.vec[i].data))
}
@@ -115,7 +117,11 @@ impl<T: Default> Layers<T> {
}
impl PrimitiveLayers {
pub fn write<P: Primitive>(&mut self, layer: usize, info: PrimitiveInst<P>) -> PrimitiveHandle {
pub fn write<P: Primitive>(
&mut self,
layer: LayerId,
info: PrimitiveInst<P>,
) -> PrimitiveHandle {
self[layer].write(layer, info)
}
@@ -130,16 +136,16 @@ impl<T: Default> Default for Layers<T> {
}
}
impl<T> Index<usize> for Layers<T> {
impl<T> Index<LayerId> for Layers<T> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
fn index(&self, index: LayerId) -> &Self::Output {
&self.vec[index].data
}
}
impl<T> IndexMut<usize> for Layers<T> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
impl<T> IndexMut<LayerId> for Layers<T> {
fn index_mut(&mut self, index: LayerId) -> &mut Self::Output {
&mut self.vec[index].data
}
}

View File

@@ -1,6 +1,6 @@
use crate::{
ActiveData, Event, EventFn, EventModule, IdLike, PainterData, PixelRegion, TextureHandle,
Widget, WidgetHandle, WidgetId, WidgetLike, util::Vec2,
ActiveData, Event, EventFn, EventLike, EventManager, IdLike, PainterData, PixelRegion,
TextureHandle, Widget, WidgetHandle, WidgetId, WidgetLike, util::Vec2,
};
use image::DynamicImage;
use std::{
@@ -24,11 +24,11 @@ impl Ui {
}
/// useful for debugging
pub fn set_label<W: ?Sized>(&mut self, id: &WidgetHandle<W>, label: String) {
pub fn set_label(&mut self, id: impl IdLike, label: String) {
self.data.widgets.data_mut(id.id()).unwrap().label = label;
}
pub fn label<W: ?Sized>(&self, id: &WidgetHandle<W>) -> &String {
pub fn label(&self, id: impl IdLike) -> &String {
&self.data.widgets.data(id.id()).unwrap().label
}
@@ -63,16 +63,19 @@ impl Ui {
self.data.textures.add(image)
}
pub fn register_event<I: IdLike, E: Event, Ctx: 'static>(
pub fn register_event<E: EventLike, Ctx: 'static>(
&mut self,
id: &I,
id: impl IdLike,
event: E,
f: impl EventFn<Ctx, E::Data>,
f: impl for<'a> EventFn<Ctx, <E::Event as Event>::Data<'a>>,
) {
self.data.events.register(id.id(), event, f);
self.data
.modules
.get_mut::<E::Module<Ctx>>()
.register(id.id(), event, f);
.widgets
.data_mut(id)
.unwrap()
.event_mgrs
.insert(EventManager::type_key::<E, Ctx>());
}
pub fn resize(&mut self, size: impl Into<Vec2>) {
@@ -81,10 +84,9 @@ impl Ui {
}
pub fn redraw_all(&mut self) {
for (_, inst) in self.data.active.drain() {
for m in self.data.modules.iter_mut() {
m.on_undraw(&inst);
}
for (id, active) in self.data.active.drain() {
let data = self.data.widgets.data(id).unwrap();
self.data.events.undraw(data, &active);
}
// free before bc nothing should exist
self.free();
@@ -116,9 +118,7 @@ impl Ui {
/// free any resources that don't have references anymore
fn free(&mut self) {
for id in self.recv.try_iter() {
for m in self.data.modules.iter_mut() {
m.on_remove(id);
}
self.data.events.remove(id);
self.data.widgets.delete(id);
}
self.data.textures.free();

26
core/src/widget/data.rs Normal file
View File

@@ -0,0 +1,26 @@
use std::any::TypeId;
use crate::{Widget, util::HashSet};
pub struct WidgetData {
pub widget: Box<dyn Widget>,
pub label: String,
pub event_mgrs: HashSet<TypeId>,
/// dynamic borrow checking
pub borrowed: bool,
}
impl WidgetData {
pub fn new<W: Widget>(widget: W) -> Self {
let mut label = std::any::type_name::<W>().to_string();
if let (Some(first), Some(last)) = (label.find(":"), label.rfind(":")) {
label = label.split_at(first).0.to_string() + "::" + label.split_at(last + 1).1;
}
Self {
widget: Box::new(widget),
label,
borrowed: false,
event_mgrs: Default::default(),
}
}
}

View File

@@ -94,6 +94,13 @@ pub trait IdLike {
fn id(&self) -> WidgetId;
}
impl<W: Widget + ?Sized> IdLike for &WidgetHandle<W> {
type Widget = W;
fn id(&self) -> WidgetId {
self.id
}
}
impl<W: Widget + ?Sized> IdLike for WidgetHandle<W> {
type Widget = W;
fn id(&self) -> WidgetId {
@@ -108,6 +115,13 @@ impl<W: Widget + ?Sized> IdLike for WidgetRef<W> {
}
}
impl IdLike for WidgetId {
type Widget = dyn Widget;
fn id(&self) -> WidgetId {
*self
}
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<U>> for WidgetRef<T> {}

View File

@@ -1,11 +1,13 @@
use crate::{Len, Painter, SizeCtx, Ui};
use std::any::Any;
mod data;
mod handle;
mod like;
mod tag;
mod widgets;
pub use data::*;
pub use handle::*;
pub use like::*;
pub use tag::*;

View File

@@ -1,5 +1,5 @@
use crate::{
IdLike, Widget, WidgetId,
IdLike, Widget, WidgetData, WidgetId,
util::{DynBorrower, HashSet, SlotVec},
};
@@ -9,13 +9,6 @@ pub struct Widgets {
vec: SlotVec<WidgetData>,
}
pub struct WidgetData {
pub widget: Box<dyn Widget>,
pub label: String,
/// dynamic borrow checking
pub borrowed: bool,
}
impl Widgets {
pub fn has_updates(&self) -> bool {
!self.updates.is_empty()
@@ -60,35 +53,23 @@ impl Widgets {
}
pub fn add<W: Widget>(&mut self, widget: W) -> WidgetId {
let mut label = std::any::type_name::<W>().to_string();
if let (Some(first), Some(last)) = (label.find(":"), label.rfind(":")) {
label = label.split_at(first).0.to_string() + "::" + label.split_at(last + 1).1;
}
self.insert_any(Box::new(widget), label)
self.vec.add(WidgetData::new(widget))
}
pub fn data(&self, id: WidgetId) -> Option<&WidgetData> {
self.vec.get(id)
pub fn data(&self, id: impl IdLike) -> Option<&WidgetData> {
self.vec.get(id.id())
}
pub fn label(&self, id: WidgetId) -> &String {
&self.data(id).unwrap().label
pub fn label(&self, id: impl IdLike) -> &String {
&self.data(id.id()).unwrap().label
}
pub fn data_mut(&mut self, id: WidgetId) -> Option<&mut WidgetData> {
self.vec.get_mut(id)
pub fn data_mut(&mut self, id: impl IdLike) -> Option<&mut WidgetData> {
self.vec.get_mut(id.id())
}
pub fn insert_any(&mut self, widget: Box<dyn Widget>, label: String) -> WidgetId {
self.vec.add(WidgetData {
widget,
label,
borrowed: false,
})
}
pub fn delete(&mut self, id: WidgetId) {
self.vec.free(id);
pub fn delete(&mut self, id: impl IdLike) {
self.vec.free(id.id());
// not sure if there's any point in this
// self.updates.remove(&id);
}