This commit is contained in:
2025-08-15 15:48:00 -04:00
parent c5aa0a02e2
commit 78ea738b8e
8 changed files with 222 additions and 52 deletions

View File

@@ -1,5 +1,5 @@
use crate::{
HashMap, Painter, Widget, WidgetId, WidgetLike,
HashMap, Painter, SenseCtx, UiRegion, Widget, WidgetId, WidgetLike,
primitive::Primitives,
util::{IDTracker, Id},
};
@@ -13,6 +13,7 @@ pub struct Ui<Ctx> {
base: Option<WidgetId>,
widgets: Widgets<Ctx>,
updates: Vec<WidgetId>,
sensors: Sensors<Ctx>,
primitives: Primitives,
full_redraw: bool,
}
@@ -20,6 +21,27 @@ pub struct Ui<Ctx> {
#[derive(Default)]
pub struct Widgets<Ctx>(HashMap<Id, Box<dyn Widget<Ctx>>>);
#[derive(Clone, Copy)]
pub enum Sense {
Click,
Hover,
}
pub type Sensors<Ctx> = Vec<(SenseTrigger, Box<dyn SenseFn<Ctx>>)>;
pub trait SenseFn_<Ctx> = Fn(&mut Ui<Ctx>, &mut Ctx) + 'static;
pub type SenseShape = UiRegion;
pub struct SenseTrigger {
pub shape: SenseShape,
pub sense: Sense,
}
pub trait SenseFn<Ctx>: SenseFn_<Ctx> {
fn box_clone(&self) -> Box<dyn SenseFn<Ctx>>;
}
impl<F: SenseFn_<Ctx> + Clone, Ctx> SenseFn<Ctx> for F {
fn box_clone(&self) -> Box<dyn SenseFn<Ctx>> {
Box::new(self.clone())
}
}
impl<Ctx> Ui<Ctx> {
pub fn add<W: Widget<Ctx>, Tag>(
&mut self,
@@ -67,13 +89,27 @@ impl<Ctx> Ui<Ctx> {
where
Ctx: 'static,
{
let mut painter = Painter::new(&self.widgets, ctx);
self.sensors.clear();
let mut painter = Painter::new(&self.widgets, ctx, &mut self.sensors);
if let Some(base) = &self.base {
painter.draw(base);
}
self.primitives = painter.finish();
}
pub fn run_sensors(&mut self, ctx: &mut Ctx)
where
Ctx: SenseCtx,
{
for (t, f) in self.sensors.iter().rev() {
if ctx.active(t) {
let f = f.as_ref().box_clone();
f(self, ctx);
return;
}
}
}
pub fn update(&mut self, ctx: &mut Ctx) -> Option<&Primitives>
where
Ctx: 'static,
@@ -94,8 +130,6 @@ impl<Ctx> Ui<Ctx> {
pub fn needs_redraw(&self) -> bool {
self.full_redraw || !self.updates.is_empty()
}
pub fn set_mouse_pos(&mut self) {}
}
impl<W: Widget<Ctx>, Ctx> Index<&WidgetId<W>> for Ui<Ctx> {
@@ -157,7 +191,8 @@ impl<Ctx> Default for Ui<Ctx> {
widgets: Widgets::new(),
updates: Default::default(),
primitives: Default::default(),
full_redraw: Default::default(),
full_redraw: false,
sensors: Default::default(),
}
}
}