RE ADD CONTEXT

This commit is contained in:
2025-12-15 21:50:53 -05:00
parent dc2be7f688
commit 0b8a93c5ce
39 changed files with 925 additions and 713 deletions

View File

@@ -1,16 +1,19 @@
use crate::{Ui, WidgetIdFn, WidgetLike, WidgetRef}; use crate::{Ui, WidgetIdFn, WidgetLike, WidgetRef};
pub trait WidgetAttr<W: ?Sized> { pub trait WidgetAttr<State, W: ?Sized> {
type Input; type Input;
fn run(ui: &mut Ui, id: WidgetRef<W>, input: Self::Input); fn run(ui: &mut Ui<State>, id: WidgetRef<State, W>, input: Self::Input);
} }
pub trait Attrable<W: ?Sized, Tag> { pub trait Attrable<State, W: ?Sized, Tag> {
fn attr<A: WidgetAttr<W>>(self, input: A::Input) -> impl WidgetIdFn<W>; fn attr<A: WidgetAttr<State, W>>(self, input: A::Input) -> impl WidgetIdFn<State, W>;
} }
impl<WL: WidgetLike<Tag>, Tag> Attrable<WL::Widget, Tag> for WL { impl<State, WL: WidgetLike<State, Tag>, Tag> Attrable<State, WL::Widget, Tag> for WL {
fn attr<A: WidgetAttr<WL::Widget>>(self, input: A::Input) -> impl WidgetIdFn<WL::Widget> { fn attr<A: WidgetAttr<State, WL::Widget>>(
self,
input: A::Input,
) -> impl WidgetIdFn<State, WL::Widget> {
|ui| { |ui| {
let id = self.add(ui); let id = self.add(ui);
A::run(ui, id.weak(), input); A::run(ui, id.weak(), input);

View File

@@ -1,36 +1,34 @@
use std::ops::{Index, IndexMut}; use std::ops::{Deref, DerefMut};
use crate::{Ui, Widget, WidgetRef}; use crate::{HasUi, Ui, Widget, WidgetRef};
pub struct EventCtx<'a, Ctx, Data> { pub struct EventCtx<'a, State, Data> {
pub ui: &'a mut Ui, pub state: &'a mut State,
pub state: &'a mut Ctx,
pub data: &'a mut Data, pub data: &'a mut Data,
} }
pub struct EventIdCtx<'a, Ctx, Data, W: ?Sized> { pub struct EventIdCtx<'a, State, Data, W: ?Sized> {
pub widget: WidgetRef<W>, pub widget: WidgetRef<State, W>,
pub ui: &'a mut Ui, pub state: &'a mut State,
pub state: &'a mut Ctx,
pub data: &'a mut Data, pub data: &'a mut Data,
} }
impl<'a, Ctx, Data, W2, W: Widget> Index<WidgetRef<W>> for EventIdCtx<'a, Ctx, Data, W2> { impl<State: HasUi, Data, W: ?Sized> Deref for EventIdCtx<'_, State, Data, W> {
type Output = W; type Target = Ui<State>;
fn index(&self, index: WidgetRef<W>) -> &Self::Output { fn deref(&self) -> &Self::Target {
&self.ui[index] self.state.ui_ref()
} }
} }
impl<'a, Ctx, Data, W2, W: Widget> IndexMut<WidgetRef<W>> for EventIdCtx<'a, Ctx, Data, W2> { impl<State: HasUi, Data, W: ?Sized> DerefMut for EventIdCtx<'_, State, Data, W> {
fn index_mut(&mut self, index: WidgetRef<W>) -> &mut Self::Output { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.ui[index] self.state.ui()
} }
} }
impl<'a, Ctx, Data, W: Widget> EventIdCtx<'a, Ctx, Data, W> { impl<'a, State: HasUi + 'static, Data, W: Widget<State>> EventIdCtx<'a, State, Data, W> {
pub fn widget(&mut self) -> &mut W { pub fn widget(&mut self) -> &mut W {
&mut self.ui[self.widget] &mut self.state.ui()[self.widget]
} }
} }

View File

@@ -1,30 +1,37 @@
use crate::{ use crate::{
ActiveData, Event, EventCtx, EventFn, EventLike, IdLike, LayerId, Ui, WidgetData, WidgetId, ActiveData, Event, EventCtx, EventFn, EventLike, HasUi, IdLike, LayerId, WidgetData, WidgetId,
util::{HashMap, TypeMap}, util::{HashMap, TypeMap},
}; };
use std::{any::TypeId, rc::Rc}; use std::{any::TypeId, rc::Rc};
#[derive(Default)] pub struct EventManager<State> {
pub struct EventManager { types: TypeMap<dyn EventManagerLike<State>>,
types: TypeMap<dyn EventManagerLike>,
} }
impl EventManager { impl<State> Default for EventManager<State> {
pub fn get_type<E: EventLike, Ctx: 'static>(&mut self) -> &mut TypeEventManager<E::Event, Ctx> { fn default() -> Self {
Self {
types: Default::default(),
}
}
}
impl<State: 'static> EventManager<State> {
pub fn get_type<E: EventLike>(&mut self) -> &mut TypeEventManager<State, E::Event> {
self.types.type_or_default() self.types.type_or_default()
} }
pub fn register<I: IdLike, E: EventLike, Ctx: 'static>( pub fn register<I: IdLike<State>, E: EventLike>(
&mut self, &mut self,
id: I, id: I,
event: E, event: E,
f: impl for<'a> EventFn<Ctx, <E::Event as Event>::Data<'a>>, f: impl for<'a> EventFn<State, <E::Event as Event>::Data<'a>>,
) { ) {
self.get_type::<E, Ctx>().register(id, event, f); self.get_type::<E>().register(id, event, f);
} }
pub fn type_key<E: EventLike, Ctx: 'static>() -> TypeId { pub fn type_key<E: EventLike>() -> TypeId {
TypeId::of::<TypeEventManager<E::Event, Ctx>>() TypeId::of::<TypeEventManager<State, E::Event>>()
} }
pub fn remove(&mut self, id: WidgetId) { pub fn remove(&mut self, id: WidgetId) {
@@ -33,33 +40,33 @@ impl EventManager {
} }
} }
pub fn draw(&mut self, data: &WidgetData, active: &ActiveData) { pub fn draw(&mut self, data: &WidgetData<State>, active: &ActiveData) {
for t in &data.event_mgrs { for t in &data.event_mgrs {
self.types.get_mut(t).unwrap().draw(active); self.types.get_mut(t).unwrap().draw(active);
} }
} }
pub fn undraw(&mut self, data: &WidgetData, active: &ActiveData) { pub fn undraw(&mut self, data: &WidgetData<State>, active: &ActiveData) {
for t in &data.event_mgrs { for t in &data.event_mgrs {
self.types.get_mut(t).unwrap().undraw(active); self.types.get_mut(t).unwrap().undraw(active);
} }
} }
} }
pub trait EventManagerLike { pub trait EventManagerLike<State> {
fn remove(&mut self, id: WidgetId); fn remove(&mut self, id: WidgetId);
fn draw(&mut self, data: &ActiveData); fn draw(&mut self, data: &ActiveData);
fn undraw(&mut self, data: &ActiveData); fn undraw(&mut self, data: &ActiveData);
} }
type EventData<E, Ctx> = (E, Rc<dyn for<'a> EventFn<Ctx, <E as Event>::Data<'a>>>); type EventData<State, E> = (E, Rc<dyn for<'a> EventFn<State, <E as Event>::Data<'a>>>);
pub struct TypeEventManager<E: Event, Ctx> { pub struct TypeEventManager<State, E: Event> {
// TODO: reduce visiblity!! // TODO: reduce visiblity!!
pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>, pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>,
map: HashMap<WidgetId, Vec<EventData<E, Ctx>>>, map: HashMap<WidgetId, Vec<EventData<State, E>>>,
} }
impl<E: Event, Ctx: 'static> EventManagerLike for TypeEventManager<E, Ctx> { impl<State, E: Event> EventManagerLike<State> for TypeEventManager<State, E> {
fn remove(&mut self, id: WidgetId) { fn remove(&mut self, id: WidgetId) {
self.map.remove(&id); self.map.remove(&id);
for layer in self.active.values_mut() { for layer in self.active.values_mut() {
@@ -80,7 +87,7 @@ impl<E: Event, Ctx: 'static> EventManagerLike for TypeEventManager<E, Ctx> {
} }
} }
impl<E: Event, Ctx> Default for TypeEventManager<E, Ctx> { impl<State, E: Event> Default for TypeEventManager<State, E> {
fn default() -> Self { fn default() -> Self {
Self { Self {
active: Default::default(), active: Default::default(),
@@ -89,12 +96,12 @@ impl<E: Event, Ctx> Default for TypeEventManager<E, Ctx> {
} }
} }
impl<E: Event, Ctx: 'static> TypeEventManager<E, Ctx> { impl<State: 'static, E: Event> TypeEventManager<State, E> {
fn register( fn register(
&mut self, &mut self,
id: impl IdLike, id: impl IdLike<State>,
event: impl EventLike<Event = E>, event: impl EventLike<Event = E>,
f: impl for<'a> EventFn<Ctx, E::Data<'a>>, f: impl for<'a> EventFn<State, E::Data<'a>>,
) { ) {
let event = event.into_event(); let event = event.into_event();
self.map self.map
@@ -105,14 +112,13 @@ impl<E: Event, Ctx: 'static> TypeEventManager<E, Ctx> {
pub fn run_fn<'a>( pub fn run_fn<'a>(
&mut self, &mut self,
id: impl IdLike, id: impl IdLike<State>,
) -> impl for<'b> FnOnce(EventCtx<Ctx, E::Data<'b>>) + 'a { ) -> impl for<'b> FnOnce(EventCtx<State, E::Data<'b>>) + 'a {
let fs = self.map.get(&id.id()).cloned().unwrap_or_default(); let fs = self.map.get(&id.id()).cloned().unwrap_or_default();
move |ctx| { move |ctx| {
for (e, f) in fs { for (e, f) in fs {
if e.should_run(ctx.data) { if e.should_run(ctx.data) {
f(EventCtx { f(EventCtx {
ui: ctx.ui,
state: ctx.state, state: ctx.state,
data: ctx.data, data: ctx.data,
}) })
@@ -122,18 +128,21 @@ impl<E: Event, Ctx: 'static> TypeEventManager<E, Ctx> {
} }
} }
impl Ui { pub trait HasEvents: Sized + HasUi {
pub fn run_event<E: EventLike, Ctx: 'static>( fn run_event<E: EventLike>(
&mut self, &mut self,
ctx: &mut Ctx, id: impl IdLike<Self>,
id: impl IdLike, data: &mut <E::Event as Event>::Data<'_>,
);
}
impl<State: HasUi + 'static> HasEvents for State {
fn run_event<E: EventLike>(
&mut self,
id: impl IdLike<Self>,
data: &mut <E::Event as Event>::Data<'_>, data: &mut <E::Event as Event>::Data<'_>,
) { ) {
let f = self.data.events.get_type::<E, Ctx>().run_fn(id); let f = self.ui().data.events.get_type::<E>().run_fn(id);
f(EventCtx { f(EventCtx { state: self, data })
ui: self,
state: ctx,
data,
})
} }
} }

View File

@@ -26,11 +26,11 @@ impl<E: Event> EventLike for E {
} }
} }
pub trait EventFn<Ctx, Data>: Fn(EventCtx<Ctx, Data>) + 'static {} pub trait EventFn<State, Data>: Fn(EventCtx<State, Data>) + 'static {}
impl<F: Fn(EventCtx<Ctx, Data>) + 'static, Ctx, Data> EventFn<Ctx, Data> for F {} impl<State, F: Fn(EventCtx<State, Data>) + 'static, Data> EventFn<State, Data> for F {}
pub trait WidgetEventFn<Ctx, Data, W: ?Sized>: Fn(EventIdCtx<Ctx, Data, W>) + 'static {} pub trait WidgetEventFn<State, Data, W: ?Sized>: Fn(EventIdCtx<State, Data, W>) + 'static {}
impl<F: Fn(EventIdCtx<Ctx, Data, W>) + 'static, Ctx, Data, W: ?Sized> WidgetEventFn<Ctx, Data, W> impl<State, F: Fn(EventIdCtx<State, Data, W>) + 'static, Data, W: ?Sized>
for F WidgetEventFn<State, Data, W> for F
{ {
} }

View File

@@ -6,8 +6,8 @@ use crate::{
}; };
/// makes your surfaces look pretty /// makes your surfaces look pretty
pub struct Painter<'a, 'c> { pub struct Painter<'a, 'c, State> {
ctx: &'a mut PainterCtx<'c>, ctx: &'a mut PainterCtx<'c, State>,
region: UiRegion, region: UiRegion,
mask: MaskIdx, mask: MaskIdx,
textures: Vec<TextureHandle>, textures: Vec<TextureHandle>,
@@ -20,15 +20,15 @@ pub struct Painter<'a, 'c> {
} }
/// context for a painter; lets you draw and redraw widgets /// context for a painter; lets you draw and redraw widgets
struct PainterCtx<'a> { struct PainterCtx<'a, State> {
pub widgets: &'a Widgets, pub widgets: &'a Widgets<State>,
pub active: &'a mut HashMap<WidgetId, ActiveData>, pub active: &'a mut HashMap<WidgetId, ActiveData>,
pub layers: &'a mut PrimitiveLayers, pub layers: &'a mut PrimitiveLayers,
pub textures: &'a mut Textures, pub textures: &'a mut Textures,
pub masks: &'a mut TrackedArena<Mask, u32>, pub masks: &'a mut TrackedArena<Mask, u32>,
pub text: &'a mut TextData, pub text: &'a mut TextData,
pub output_size: Vec2, pub output_size: Vec2,
pub events: &'a mut EventManager, pub events: &'a mut EventManager<State>,
pub cache_width: HashMap<WidgetId, (UiVec2, Len)>, pub cache_width: HashMap<WidgetId, (UiVec2, Len)>,
pub cache_height: HashMap<WidgetId, (UiVec2, Len)>, pub cache_height: HashMap<WidgetId, (UiVec2, Len)>,
pub needs_redraw: &'a mut HashSet<WidgetId>, pub needs_redraw: &'a mut HashSet<WidgetId>,
@@ -58,20 +58,35 @@ pub struct ActiveData {
} }
/// data to be stored in Ui to create PainterCtxs easily /// data to be stored in Ui to create PainterCtxs easily
#[derive(Default)] pub struct PainterData<State> {
pub struct PainterData { pub widgets: Widgets<State>,
pub widgets: Widgets,
pub active: HashMap<WidgetId, ActiveData>, pub active: HashMap<WidgetId, ActiveData>,
pub layers: PrimitiveLayers, pub layers: PrimitiveLayers,
pub textures: Textures, pub textures: Textures,
pub text: TextData, pub text: TextData,
pub output_size: Vec2, pub output_size: Vec2,
pub events: EventManager, pub events: EventManager<State>,
pub px_dependent: HashSet<WidgetId>, pub px_dependent: HashSet<WidgetId>,
pub masks: TrackedArena<Mask, u32>, pub masks: TrackedArena<Mask, u32>,
} }
impl<'a> PainterCtx<'a> { impl<State> Default for PainterData<State> {
fn default() -> Self {
Self {
widgets: Default::default(),
active: Default::default(),
layers: Default::default(),
textures: Default::default(),
text: Default::default(),
output_size: Default::default(),
events: Default::default(),
px_dependent: Default::default(),
masks: Default::default(),
}
}
}
impl<'a, State: 'static> PainterCtx<'a, State> {
/// redraws a widget that's currently active (drawn) /// redraws a widget that's currently active (drawn)
/// can be called on something already drawn or removed, /// can be called on something already drawn or removed,
/// will just return if so /// will just return if so
@@ -317,8 +332,8 @@ impl<'a> PainterCtx<'a> {
} }
} }
impl PainterData { impl<State: 'static> PainterData<State> {
fn ctx<'a>(&'a mut self, needs_redraw: &'a mut HashSet<WidgetId>) -> PainterCtx<'a> { fn ctx<'a>(&'a mut self, needs_redraw: &'a mut HashSet<WidgetId>) -> PainterCtx<'a, State> {
PainterCtx { PainterCtx {
widgets: &self.widgets, widgets: &self.widgets,
active: &mut self.active, active: &mut self.active,
@@ -351,7 +366,7 @@ impl PainterData {
} }
} }
impl<'a, 'c> Painter<'a, 'c> { impl<'a, 'c, State: 'static> Painter<'a, 'c, State> {
fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) { fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
let h = self.ctx.layers.write( let h = self.ctx.layers.write(
self.layer, self.layer,
@@ -384,17 +399,17 @@ impl<'a, 'c> Painter<'a, 'c> {
} }
/// Draws a widget within this widget's region. /// Draws a widget within this widget's region.
pub fn widget<W: ?Sized>(&mut self, id: &WidgetHandle<W>) { pub fn widget<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>) {
self.widget_at(id, self.region); self.widget_at(id, self.region);
} }
/// Draws a widget somewhere within this one. /// Draws a widget somewhere within this one.
/// Useful for drawing child widgets in select areas. /// Useful for drawing child widgets in select areas.
pub fn widget_within<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) { pub fn widget_within<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>, region: UiRegion) {
self.widget_at(id, region.within(&self.region)); self.widget_at(id, region.within(&self.region));
} }
fn widget_at<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) { fn widget_at<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>, region: UiRegion) {
self.children.push(id.id()); self.children.push(id.id());
self.ctx self.ctx
.draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None); .draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None);
@@ -424,18 +439,18 @@ impl<'a, 'c> Painter<'a, 'c> {
self.region self.region
} }
pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size { pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>) -> Size {
self.size_ctx().size(id) self.size_ctx().size(id)
} }
pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len { pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>, axis: Axis) -> Len {
match axis { match axis {
Axis::X => self.size_ctx().width(id), Axis::X => self.size_ctx().width(id),
Axis::Y => self.size_ctx().height(id), Axis::Y => self.size_ctx().height(id),
} }
} }
pub fn size_ctx(&mut self) -> SizeCtx<'_> { pub fn size_ctx(&mut self) -> SizeCtx<'_, State> {
SizeCtx { SizeCtx {
text: self.ctx.text, text: self.ctx.text,
textures: self.ctx.textures, textures: self.ctx.textures,
@@ -480,11 +495,11 @@ impl<'a, 'c> Painter<'a, 'c> {
} }
} }
pub struct SizeCtx<'a> { pub struct SizeCtx<'a, State> {
pub text: &'a mut TextData, pub text: &'a mut TextData,
pub textures: &'a mut Textures, pub textures: &'a mut Textures,
source: WidgetId, source: WidgetId,
widgets: &'a Widgets, widgets: &'a Widgets<State>,
cache_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>, cache_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
cache_height: &'a mut HashMap<WidgetId, (UiVec2, Len)>, cache_height: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
checked_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>, checked_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
@@ -495,7 +510,7 @@ pub struct SizeCtx<'a> {
id: WidgetId, id: WidgetId,
} }
impl SizeCtx<'_> { impl<State: 'static> SizeCtx<'_, State> {
pub fn id(&self) -> &WidgetId { pub fn id(&self) -> &WidgetId {
&self.id &self.id
} }
@@ -547,22 +562,22 @@ impl SizeCtx<'_> {
len len
} }
pub fn width<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Len { pub fn width<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>) -> Len {
self.width_inner(id.id()) self.width_inner(id.id())
} }
pub fn height<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Len { pub fn height<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>) -> Len {
self.height_inner(id.id()) self.height_inner(id.id())
} }
pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len { pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>, axis: Axis) -> Len {
match axis { match axis {
Axis::X => self.width(id), Axis::X => self.width(id),
Axis::Y => self.height(id), Axis::Y => self.height(id),
} }
} }
pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size { pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<State, W>) -> Size {
Size { Size {
x: self.width(id), x: self.width(id),
y: self.height(id), y: self.height(id),

View File

@@ -59,7 +59,7 @@ impl UiRenderNode {
} }
} }
pub fn update(&mut self, device: &Device, queue: &Queue, ui: &mut Ui) { pub fn update<State>(&mut self, device: &Device, queue: &Queue, ui: &mut Ui<State>) {
self.active.clear(); self.active.clear();
for (i, primitives) in ui.data.layers.iter_mut() { for (i, primitives) in ui.data.layers.iter_mut() {
self.active.push(i); self.active.push(i);

View File

@@ -8,35 +8,43 @@ use std::{
sync::mpsc::{Receiver, Sender, channel}, sync::mpsc::{Receiver, Sender, channel},
}; };
pub struct Ui { pub struct Ui<State> {
// TODO: make this at least pub(super) // TODO: make this at least pub(super)
pub data: PainterData, pub data: PainterData<State>,
root: Option<WidgetHandle>, root: Option<WidgetHandle<State>>,
recv: Receiver<WidgetId>, recv: Receiver<WidgetId>,
pub(super) send: Sender<WidgetId>, pub(super) send: Sender<WidgetId>,
full_redraw: bool, full_redraw: bool,
resized: bool, resized: bool,
} }
impl Ui { pub trait HasUi: Sized {
pub fn add<W: Widget, Tag>(&mut self, w: impl WidgetLike<Tag, Widget = W>) -> WidgetHandle<W> { fn ui_ref(&self) -> &Ui<Self>;
fn ui(&mut self) -> &mut Ui<Self>;
}
impl<State: 'static> Ui<State> {
pub fn add<W: Widget<State>, Tag>(
&mut self,
w: impl WidgetLike<State, Tag, Widget = W>,
) -> WidgetHandle<State, W> {
w.add(self) w.add(self)
} }
/// useful for debugging /// useful for debugging
pub fn set_label(&mut self, id: impl IdLike, label: String) { pub fn set_label(&mut self, id: impl IdLike<State>, label: String) {
self.data.widgets.data_mut(id.id()).unwrap().label = label; self.data.widgets.data_mut(id.id()).unwrap().label = label;
} }
pub fn label(&self, id: impl IdLike) -> &String { pub fn label(&self, id: impl IdLike<State>) -> &String {
&self.data.widgets.data(id.id()).unwrap().label &self.data.widgets.data(id.id()).unwrap().label
} }
pub fn add_widget<W: Widget>(&mut self, w: W) -> WidgetHandle<W> { pub fn add_widget<W: Widget<State>>(&mut self, w: W) -> WidgetHandle<State, W> {
WidgetHandle::new(self.data.widgets.add(w), self.send.clone()) WidgetHandle::new(self.data.widgets.add(w), self.send.clone())
} }
pub fn set_root<Tag>(&mut self, w: impl WidgetLike<Tag>) { pub fn set_root<Tag>(&mut self, w: impl WidgetLike<State, Tag>) {
self.root = Some(w.add(self)); self.root = Some(w.add(self));
self.full_redraw = true; self.full_redraw = true;
} }
@@ -45,14 +53,14 @@ impl Ui {
Self::default() Self::default()
} }
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget> pub fn get<I: IdLike<State>>(&self, id: &I) -> Option<&I::Widget>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
self.data.widgets.get(id) self.data.widgets.get(id)
} }
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget> pub fn get_mut<I: IdLike<State>>(&mut self, id: &I) -> Option<&mut I::Widget>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -63,11 +71,11 @@ impl Ui {
self.data.textures.add(image) self.data.textures.add(image)
} }
pub fn register_event<E: EventLike, Ctx: 'static>( pub fn register_event<E: EventLike>(
&mut self, &mut self,
id: impl IdLike, id: impl IdLike<State>,
event: E, event: E,
f: impl for<'a> EventFn<Ctx, <E::Event as Event>::Data<'a>>, f: impl for<'a> EventFn<State, <E::Event as Event>::Data<'a>>,
) { ) {
self.data.events.register(id.id(), event, f); self.data.events.register(id.id(), event, f);
self.data self.data
@@ -75,7 +83,7 @@ impl Ui {
.data_mut(id) .data_mut(id)
.unwrap() .unwrap()
.event_mgrs .event_mgrs
.insert(EventManager::type_key::<E, Ctx>()); .insert(EventManager::<State>::type_key::<E>());
} }
pub fn resize(&mut self, size: impl Into<Vec2>) { pub fn resize(&mut self, size: impl Into<Vec2>) {
@@ -148,7 +156,7 @@ impl Ui {
} }
} }
pub fn window_region(&self, id: &impl IdLike) -> Option<PixelRegion> { pub fn window_region(&self, id: &impl IdLike<State>) -> Option<PixelRegion> {
let region = self.data.active.get(&id.id())?.region; let region = self.data.active.get(&id.id())?.region;
Some(region.to_px(self.data.output_size)) Some(region.to_px(self.data.output_size))
} }
@@ -161,7 +169,7 @@ impl Ui {
} }
} }
impl<I: IdLike> Index<I> for Ui impl<State: 'static, I: IdLike<State>> Index<I> for Ui<State>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -172,7 +180,7 @@ where
} }
} }
impl<I: IdLike> IndexMut<I> for Ui impl<State: 'static, I: IdLike<State>> IndexMut<I> for Ui<State>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -181,7 +189,7 @@ where
} }
} }
impl Default for Ui { impl<State: 'static> Default for Ui<State> {
fn default() -> Self { fn default() -> Self {
let (send, recv) = channel(); let (send, recv) = channel();
Self { Self {

View File

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

View File

@@ -1,4 +1,9 @@
use std::{marker::Unsize, mem::MaybeUninit, ops::CoerceUnsized, sync::mpsc::Sender}; use std::{
marker::{PhantomData, Unsize},
mem::MaybeUninit,
ops::CoerceUnsized,
sync::mpsc::Sender,
};
use crate::{ use crate::{
Ui, Widget, Ui, Widget,
@@ -12,43 +17,46 @@ pub type WidgetId = SlotId;
/// a signal is sent to the owning UI to clean up the resources. /// a signal is sent to the owning UI to clean up the resources.
/// ///
/// TODO: ergonomic clones when they get put in rust-analyzer & don't cause ICEs? /// TODO: ergonomic clones when they get put in rust-analyzer & don't cause ICEs?
pub struct WidgetHandle<W: ?Sized = dyn Widget> { pub struct WidgetHandle<State, W: ?Sized = dyn Widget<State>> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
counter: RefCounter, counter: RefCounter,
send: Sender<WidgetId>, send: Sender<WidgetId>,
ty: *const W, ty: *const W,
state: PhantomData<State>,
} }
/// A weak handle to a widget. /// A weak handle to a widget.
/// Will not keep it alive, but can still be used for indexing like WidgetHandle. /// Will not keep it alive, but can still be used for indexing like WidgetHandle.
pub struct WidgetRef<W: ?Sized = dyn Widget> { pub struct WidgetRef<State, W: ?Sized = dyn Widget<State>> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
#[allow(unused)] #[allow(unused)]
ty: *const W, ty: *const W,
state: PhantomData<State>,
} }
pub struct WidgetHandles<W: ?Sized = dyn Widget> { pub struct WidgetHandles<State, W: ?Sized = dyn Widget<State>> {
pub h: WidgetHandle<W>, pub h: WidgetHandle<State, W>,
pub r: WidgetRef<W>, pub r: WidgetRef<State, W>,
} }
impl<W: Widget + ?Sized + Unsize<dyn Widget>> WidgetHandle<W> { impl<State, W: Widget<State> + ?Sized + Unsize<dyn Widget<State>>> WidgetHandle<State, W> {
pub fn any(self) -> WidgetHandle<dyn Widget> { pub fn any(self) -> WidgetHandle<State, dyn Widget<State>> {
self self
} }
} }
impl<W: ?Sized> WidgetHandle<W> { impl<State, W: ?Sized> WidgetHandle<State, W> {
pub(crate) fn new(id: WidgetId, send: Sender<WidgetId>) -> Self { pub(crate) fn new(id: WidgetId, send: Sender<WidgetId>) -> Self {
Self { Self {
id, id,
counter: RefCounter::new(), counter: RefCounter::new(),
send, send,
ty: unsafe { MaybeUninit::zeroed().assume_init() }, ty: unsafe { MaybeUninit::zeroed().assume_init() },
state: PhantomData,
} }
} }
pub fn as_any(&self) -> &WidgetHandle<dyn Widget> { pub fn as_any(&self) -> &WidgetHandle<State, dyn Widget<State>> {
// SAFETY: self is repr(C) and generic only used for phantom data // SAFETY: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) } unsafe { std::mem::transmute(self) }
} }
@@ -61,24 +69,28 @@ impl<W: ?Sized> WidgetHandle<W> {
self.counter.refs() self.counter.refs()
} }
pub fn weak(&self) -> WidgetRef<W> { pub fn weak(&self) -> WidgetRef<State, W> {
let Self { ty, id, .. } = *self; let Self { ty, id, .. } = *self;
WidgetRef { ty, id } WidgetRef {
ty,
id,
state: PhantomData,
}
} }
pub fn handles(self) -> WidgetHandles<W> { pub fn handles(self) -> WidgetHandles<State, W> {
let r = self.weak(); let r = self.weak();
WidgetHandles { h: self, r } WidgetHandles { h: self, r }
} }
} }
impl<W: ?Sized> WidgetRef<W> { impl<State, W: ?Sized> WidgetRef<State, W> {
pub fn id(&self) -> WidgetId { pub fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<W: ?Sized> Drop for WidgetHandle<W> { impl<State, W: ?Sized> Drop for WidgetHandle<State, W> {
fn drop(&mut self) { fn drop(&mut self) {
if self.counter.drop() { if self.counter.drop() {
let _ = self.send.send(self.id); let _ = self.send.send(self.id);
@@ -86,52 +98,64 @@ impl<W: ?Sized> Drop for WidgetHandle<W> {
} }
} }
pub trait WidgetIdFn<W: ?Sized = dyn Widget>: FnOnce(&mut Ui) -> WidgetHandle<W> {} pub trait WidgetIdFn<State, W: ?Sized = dyn Widget<State>>:
impl<W: ?Sized, F: FnOnce(&mut Ui) -> WidgetHandle<W>> WidgetIdFn<W> for F {} FnOnce(&mut Ui<State>) -> WidgetHandle<State, W>
{
}
impl<State, W: ?Sized, F: FnOnce(&mut Ui<State>) -> WidgetHandle<State, W>> WidgetIdFn<State, W>
for F
{
}
pub trait IdLike { pub trait IdLike<State> {
type Widget: Widget + ?Sized + 'static; type Widget: Widget<State> + ?Sized + 'static;
fn id(&self) -> WidgetId; fn id(&self) -> WidgetId;
} }
impl<W: Widget + ?Sized> IdLike for &WidgetHandle<W> { impl<State, W: Widget<State> + ?Sized> IdLike<State> for &WidgetHandle<State, W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<W: Widget + ?Sized> IdLike for WidgetHandle<W> { impl<State, W: Widget<State> + ?Sized> IdLike<State> for WidgetHandle<State, W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<W: Widget + ?Sized> IdLike for WidgetRef<W> { impl<State, W: Widget<State> + ?Sized> IdLike<State> for WidgetRef<State, W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl IdLike for WidgetId { impl<State: 'static> IdLike<State> for WidgetId {
type Widget = dyn Widget; type Widget = dyn Widget<State>;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
*self *self
} }
} }
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {} impl<T: ?Sized + Unsize<U>, U: ?Sized, State> CoerceUnsized<WidgetHandle<State, U>>
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<U>> for WidgetRef<T> {} for WidgetHandle<State, T>
{
}
impl<State, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<State, U>>
for WidgetRef<State, T>
{
}
impl<W: ?Sized> Clone for WidgetRef<W> { impl<State, W: ?Sized> Clone for WidgetRef<State, W> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
*self *self
} }
} }
impl<W: ?Sized> Copy for WidgetRef<W> {} impl<State, W: ?Sized> Copy for WidgetRef<State, W> {}
impl<W: ?Sized> PartialEq for WidgetRef<W> { impl<State, W: ?Sized> PartialEq for WidgetRef<State, W> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.id == other.id self.id == other.id
} }

View File

@@ -1,48 +1,48 @@
use super::*; use super::*;
use std::marker::Unsize; use std::marker::Unsize;
pub trait WidgetLike<Tag>: Sized { pub trait WidgetLike<State: 'static, Tag>: Sized {
type Widget: Widget + ?Sized + Unsize<dyn Widget> + 'static; type Widget: Widget<State> + ?Sized + Unsize<dyn Widget<State>> + 'static;
fn add(self, ui: &mut Ui) -> WidgetHandle<Self::Widget>; fn add(self, ui: &mut Ui<State>) -> WidgetHandle<State, Self::Widget>;
fn with_id<W2>( fn with_id<W2>(
self, self,
f: impl FnOnce(&mut Ui, WidgetHandle<Self::Widget>) -> WidgetHandle<W2>, f: impl FnOnce(&mut Ui<State>, WidgetHandle<State, Self::Widget>) -> WidgetHandle<State, W2>,
) -> impl WidgetIdFn<W2> { ) -> impl WidgetIdFn<State, W2> {
move |ui| { move |ui| {
let id = self.add(ui); let id = self.add(ui);
f(ui, id) f(ui, id)
} }
} }
fn set_root(self, ui: &mut Ui) { fn set_root(self, ui: &mut Ui<State>) {
ui.set_root(self); ui.set_root(self);
} }
fn handles(self, ui: &mut Ui) -> WidgetHandles<Self::Widget> { fn handles(self, ui: &mut Ui<State>) -> WidgetHandles<State, Self::Widget> {
self.add(ui).handles() self.add(ui).handles()
} }
} }
pub trait WidgetArrLike<const LEN: usize, Tag> { pub trait WidgetArrLike<State, const LEN: usize, Tag> {
fn ui(self, ui: &mut Ui) -> WidgetArr<LEN>; fn ui(self, ui: &mut Ui<State>) -> WidgetArr<State, LEN>;
} }
impl<const LEN: usize> WidgetArrLike<LEN, ArrTag> for WidgetArr<LEN> { impl<State, const LEN: usize> WidgetArrLike<State, LEN, ArrTag> for WidgetArr<State, LEN> {
fn ui(self, _: &mut Ui) -> WidgetArr<LEN> { fn ui(self, _: &mut Ui<State>) -> WidgetArr<State, LEN> {
self self
} }
} }
// I hate this language it's so bad why do I even use it // variadic generics please save us
macro_rules! impl_widget_arr { macro_rules! impl_widget_arr {
($n:expr;$($W:ident)*) => { ($n:expr;$($W:ident)*) => {
impl_widget_arr!($n;$($W)*;$(${concat($W,Tag)})*); impl_widget_arr!($n;$($W)*;$(${concat($W,Tag)})*);
}; };
($n:expr;$($W:ident)*;$($Tag:ident)*) => { ($n:expr;$($W:ident)*;$($Tag:ident)*) => {
impl<$($W: WidgetLike<$Tag>,$Tag,)*> WidgetArrLike<$n, ($($Tag,)*)> for ($($W,)*) { impl<State: 'static, $($W: WidgetLike<State, $Tag>,$Tag,)*> WidgetArrLike<State, $n, ($($Tag,)*)> for ($($W,)*) {
fn ui(self, ui: &mut Ui) -> WidgetArr<$n> { fn ui(self, ui: &mut Ui<State>) -> WidgetArr<State, $n> {
#[allow(non_snake_case)] #[allow(non_snake_case)]
let ($($W,)*) = self; let ($($W,)*) = self;
WidgetArr::new( WidgetArr::new(

View File

@@ -13,23 +13,23 @@ pub use like::*;
pub use tag::*; pub use tag::*;
pub use widgets::*; pub use widgets::*;
pub trait Widget: Any { pub trait Widget<State>: Any {
fn draw(&mut self, painter: &mut Painter); fn draw(&mut self, painter: &mut Painter<State>);
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len; fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len;
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len; fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len;
} }
impl Widget for () { impl<State> Widget<State> for () {
fn draw(&mut self, _: &mut Painter) {} fn draw(&mut self, _: &mut Painter<State>) {}
fn desired_width(&mut self, _: &mut SizeCtx) -> Len { fn desired_width(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::ZERO Len::ZERO
} }
fn desired_height(&mut self, _: &mut SizeCtx) -> Len { fn desired_height(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::ZERO Len::ZERO
} }
} }
impl dyn Widget { impl<State> dyn Widget<State> {
pub fn as_any(&self) -> &dyn Any { pub fn as_any(&self) -> &dyn Any {
self self
} }
@@ -42,31 +42,31 @@ impl dyn Widget {
/// A function that returns a widget given a UI. /// 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 /// Useful for defining trait functions on widgets that create a parent widget so that the children
/// don't need to be IDs yet /// don't need to be IDs yet
pub trait WidgetFn<W: Widget + ?Sized>: FnOnce(&mut Ui) -> W {} pub trait WidgetFn<State, W: Widget<State> + ?Sized>: FnOnce(&mut Ui<State>) -> W {}
impl<W: Widget + ?Sized, F: FnOnce(&mut Ui) -> W> WidgetFn<W> for F {} impl<State, W: Widget<State> + ?Sized, F: FnOnce(&mut Ui<State>) -> W> WidgetFn<State, W> for F {}
pub struct WidgetArr<const LEN: usize> { pub struct WidgetArr<State, const LEN: usize> {
pub arr: [WidgetHandle; LEN], pub arr: [WidgetHandle<State>; LEN],
} }
impl<const LEN: usize> WidgetArr<LEN> { impl<State, const LEN: usize> WidgetArr<State, LEN> {
pub fn new(arr: [WidgetHandle; LEN]) -> Self { pub fn new(arr: [WidgetHandle<State>; LEN]) -> Self {
Self { arr } Self { arr }
} }
} }
pub trait WidgetOption { pub trait WidgetOption<State> {
fn get(self, ui: &mut Ui) -> Option<WidgetHandle>; fn get(self, ui: &mut Ui<State>) -> Option<WidgetHandle<State>>;
} }
impl WidgetOption for () { impl<State> WidgetOption<State> for () {
fn get(self, _: &mut Ui) -> Option<WidgetHandle> { fn get(self, _: &mut Ui<State>) -> Option<WidgetHandle<State>> {
None None
} }
} }
impl<F: FnOnce(&mut Ui) -> Option<WidgetHandle>> WidgetOption for F { impl<State, F: FnOnce(&mut Ui<State>) -> Option<WidgetHandle<State>>> WidgetOption<State> for F {
fn get(self, ui: &mut Ui) -> Option<WidgetHandle> { fn get(self, ui: &mut Ui<State>) -> Option<WidgetHandle<State>> {
self(ui) self(ui)
} }
} }

View File

@@ -5,35 +5,42 @@ use super::*;
pub struct ArrTag; pub struct ArrTag;
pub struct WidgetTag; pub struct WidgetTag;
impl<W: Widget> WidgetLike<WidgetTag> for W { impl<State: 'static, W: Widget<State>> WidgetLike<State, WidgetTag> for W {
type Widget = W; type Widget = W;
fn add(self, ui: &mut Ui) -> WidgetHandle<W> { fn add(self, ui: &mut Ui<State>) -> WidgetHandle<State, W> {
ui.add_widget(self) ui.add_widget(self)
} }
} }
pub struct FnTag; pub struct FnTag;
impl<W: Widget, F: FnOnce(&mut Ui) -> W> WidgetLike<FnTag> for F { impl<State: 'static, W: Widget<State>, F: FnOnce(&mut Ui<State>) -> W> WidgetLike<State, FnTag>
for F
{
type Widget = W; type Widget = W;
fn add(self, ui: &mut Ui) -> WidgetHandle<W> { fn add(self, ui: &mut Ui<State>) -> WidgetHandle<State, W> {
self(ui).add(ui) self(ui).add(ui)
} }
} }
pub struct IdTag; pub struct IdTag;
impl<W: ?Sized + Widget + Unsize<dyn Widget> + 'static> WidgetLike<IdTag> for WidgetHandle<W> { impl<State: 'static, W: ?Sized + Widget<State> + Unsize<dyn Widget<State>> + 'static>
WidgetLike<State, IdTag> for WidgetHandle<State, W>
{
type Widget = W; type Widget = W;
fn add(self, _: &mut Ui) -> WidgetHandle<W> { fn add(self, _: &mut Ui<State>) -> WidgetHandle<State, W> {
self self
} }
} }
pub struct IdFnTag; pub struct IdFnTag;
impl<W: ?Sized + Widget + Unsize<dyn Widget> + 'static, F: FnOnce(&mut Ui) -> WidgetHandle<W>> impl<
WidgetLike<IdFnTag> for F State: 'static,
W: ?Sized + Widget<State> + Unsize<dyn Widget<State>> + 'static,
F: FnOnce(&mut Ui<State>) -> WidgetHandle<State, W>,
> WidgetLike<State, IdFnTag> for F
{ {
type Widget = W; type Widget = W;
fn add(self, ui: &mut Ui) -> WidgetHandle<W> { fn add(self, ui: &mut Ui<State>) -> WidgetHandle<State, W> {
self(ui) self(ui)
} }
} }

View File

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

View File

@@ -1,14 +1,22 @@
use iris::prelude::*; use iris::prelude::*;
use winit::event_loop::ActiveEventLoop;
fn main() { fn main() {
DefaultApp::<State>::run(); App::<State>::run();
} }
struct State; #[derive(HasUi, HasUiState)]
struct State {
ui: Ui<Self>,
ui_state: UiState<Self>,
}
impl DefaultAppState for State { impl DefaultAppState for State {
fn new(ui: &mut Ui, _state: &UiState, _proxy: Proxy<Self::Event>) -> Self { fn new(event_loop: &ActiveEventLoop, _proxy: Proxy<Self::Event>) -> Self {
rect(Color::RED).set_root(ui); let mut ui = Ui::new();
Self let window = event_loop.create_window(Default::default()).unwrap();
let ui_state = UiState::new(window);
rect(Color::RED).set_root(&mut ui);
Self { ui, ui_state }
} }
} }

View File

@@ -2,15 +2,19 @@ extern crate proc_macro;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use syn::{ use syn::{
Attribute, Block, Ident, ItemTrait, Signature, Token, Visibility, Attribute, Block, Error, GenericParam, Generics, Ident, ItemStruct, ItemTrait, Meta, Signature,
Token, Visibility,
parse::{Parse, ParseStream, Result}, parse::{Parse, ParseStream, Result},
parse_macro_input, parse_quote, parse_macro_input, parse_quote,
punctuated::Punctuated,
spanned::Spanned,
}; };
struct Input { struct Input {
attrs: Vec<Attribute>, attrs: Vec<Attribute>,
vis: Visibility, vis: Visibility,
name: Ident, name: Ident,
generics: Generics,
fns: Vec<InputFn>, fns: Vec<InputFn>,
} }
@@ -25,6 +29,7 @@ impl Parse for Input {
let vis = input.parse()?; let vis = input.parse()?;
input.parse::<Token![trait]>()?; input.parse::<Token![trait]>()?;
let name = input.parse()?; let name = input.parse()?;
let generics = input.parse::<Generics>()?;
input.parse::<Token![;]>()?; input.parse::<Token![;]>()?;
let mut fns = Vec::new(); let mut fns = Vec::new();
while !input.is_empty() { while !input.is_empty() {
@@ -39,6 +44,7 @@ impl Parse for Input {
attrs, attrs,
vis, vis,
name, name,
generics,
fns, fns,
}) })
} }
@@ -50,6 +56,7 @@ pub fn widget_trait(input: TokenStream) -> TokenStream {
attrs, attrs,
vis, vis,
name, name,
mut generics,
fns, fns,
} = parse_macro_input!(input as Input); } = parse_macro_input!(input as Input);
@@ -59,19 +66,130 @@ pub fn widget_trait(input: TokenStream) -> TokenStream {
.map(|InputFn { sig, body }| quote! { #sig #body }) .map(|InputFn { sig, body }| quote! { #sig #body })
.collect(); .collect();
let Some(GenericParam::Type(state)) = generics.params.first() else {
return Error::new(name.span(), "expected state generic parameter")
.into_compile_error()
.into();
};
let state = &state.ident;
generics
.params
.push(parse_quote!(WL: WidgetLike<#state, Tag>));
generics.params.push(parse_quote!(Tag));
let mut trai: ItemTrait = parse_quote!( let mut trai: ItemTrait = parse_quote!(
#vis trait #name<WL: WidgetLike<Tag>, Tag> { #vis trait #name #generics {
#(#sigs;)* #(#sigs;)*
} }
); );
trai.attrs = attrs; trai.attrs = attrs;
TokenStream::from(quote! { quote! {
#trai #trai
impl<WL: WidgetLike<Tag>, Tag> #name<WL, Tag> for WL { impl #generics #name<State, WL, Tag> for WL {
#(#impls)* #(#impls)*
} }
}) }
.into()
}
#[proc_macro_derive(GlobalState, attributes(has))]
pub fn derive_global_state(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemStruct);
let name = input.ident;
let mut impls = TokenStream::new();
for field in input.fields {
let Some(attr) = field.attrs.iter().find(|a| a.path().is_ident("has")) else {
continue;
};
let error: TokenStream = Error::new(
attr.span(),
"invalid attribute format; usage: #[has(HasTrait, trait_fn)]",
)
.into_compile_error()
.into();
let Meta::List(list) = &attr.meta else {
return error;
};
match list.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated) {
Ok(list) => {
if list.len() != 2 {
return error;
}
let traitt = &list[0];
let fn_name = &list[1];
let field_name = field.ident;
let ty = field.ty;
impls.extend::<TokenStream>(
quote! {
impl #traitt for #name {
fn #fn_name(&mut self) -> &mut #ty {
&mut self.#field_name
}
}
}
.into(),
);
}
Err(..) => {
return error;
}
}
}
impls
}
#[proc_macro_derive(HasUi)]
pub fn derive_has_ui(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemStruct);
let name = input.ident;
let Some(field) = input.fields.iter().find(|f| f.ty == parse_quote!(Ui<Self>)) else {
return Error::new(name.span(), "could not find a Ui<Self> field for HasUi")
.into_compile_error()
.into();
};
let field = &field.ident;
quote! {
impl HasUi for #name {
fn ui_ref(&self) -> &Ui<Self> {
&self.#field
}
fn ui(&mut self) -> &mut Ui<Self> {
&mut self.#field
}
}
}
.into()
}
#[proc_macro_derive(HasUiState)]
pub fn derive_has_ui_state(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemStruct);
let name = input.ident;
let Some(field) = input
.fields
.iter()
.find(|f| f.ty == parse_quote!(UiState<Self>))
else {
return Error::new(
name.span(),
"could not find a UiState<Self> field for HasUiState",
)
.into_compile_error()
.into();
};
let field = &field.ident;
quote! {
impl HasUiState for #name {
fn ui_state(&mut self) -> &mut UiState<Self> {
&mut self.#field
}
}
}
.into()
} }

View File

@@ -3,20 +3,30 @@ use std::{cell::RefCell, rc::Rc};
use cosmic_text::Family; use cosmic_text::Family;
use iris::prelude::*; use iris::prelude::*;
use len_fns::*; use len_fns::*;
use winit::event::WindowEvent; use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::WindowAttributes};
fn main() { fn main() {
DefaultApp::<Client>::run(); App::<Client>::run();
} }
#[derive(HasUi, HasUiState)]
pub struct Client { pub struct Client {
info: WidgetRef<Text>, ui: Ui<Self>,
ui_state: UiState<Self>,
info: WidgetRef<Self, Text<Self>>,
} }
event_ctx!(Client); event_ctx!(Client);
impl DefaultAppState for Client { impl DefaultAppState for Client {
fn new(ui: &mut Ui, _state: &UiState, _proxy: Proxy<Self::Event>) -> Self { fn new(event_loop: &ActiveEventLoop, _proxy: Proxy<Self::Event>) -> Self {
let mut ui = Ui::new();
let window = event_loop
.create_window(WindowAttributes::default())
.unwrap();
let info;
{
let ui = &mut ui;
let rrect = rect(Color::WHITE).radius(20); let rrect = rect(Color::WHITE).radius(20);
let pad_test = ( let pad_test = (
rrect.color(Color::BLUE), rrect.color(Color::BLUE),
@@ -57,9 +67,7 @@ impl DefaultAppState for Client {
let add_button = rect(Color::LIME) let add_button = rect(Color::LIME)
.radius(30) .radius(30)
.on(CursorSense::click(), move |mut ctx| { .on(CursorSense::click(), move |mut ctx| {
let child = ctx let child = ctx.add(image(include_bytes!("assets/sungals.png")).center());
.ui
.add(image(include_bytes!("assets/sungals.png")).center());
ctx[span_add.r].children.push(child); ctx[span_add.r].children.push(child);
}) })
.sized((150, 150)) .sized((150, 150))
@@ -105,16 +113,18 @@ impl DefaultAppState for Client {
.text_align(Align::LEFT) .text_align(Align::LEFT)
.size(30) .size(30)
.attr::<Selectable>(()) .attr::<Selectable>(())
.on(Submit, move |ctx| { .on(Submit, move |mut ctx| {
let content = ctx.widget.edit(ctx.ui).take(); let content = ctx.widget.edit(ctx.state.ui()).take();
let text = wtext(content) let text = wtext(content)
.editable(false) .editable(false)
.size(30) .size(30)
.text_align(Align::LEFT) .text_align(Align::LEFT)
.wrap(true) .wrap(true)
.attr::<Selectable>(()); .attr::<Selectable>(());
let msg_box = text.background(rect(Color::WHITE.darker(0.5))).add(ctx.ui); let msg_box = text
ctx.ui[texts.r].children.push(msg_box); .background(rect(Color::WHITE.darker(0.5)))
.add(&mut ctx);
ctx[texts.r].children.push(msg_box);
}) })
.handles(ui); .handles(ui);
let text_edit_scroll = ( let text_edit_scroll = (
@@ -125,8 +135,7 @@ impl DefaultAppState for Client {
add_text.h.width(rest(1)), add_text.h.width(rest(1)),
Rect::new(Color::GREEN) Rect::new(Color::GREEN)
.on(CursorSense::click(), move |ctx| { .on(CursorSense::click(), move |ctx| {
ctx.ui ctx.state.run_event::<Submit>(add_text.r, &mut ());
.run_event::<Submit, _>(ctx.state, add_text.r, &mut ());
}) })
.sized((40, 40)), .sized((40, 40)),
) )
@@ -144,7 +153,7 @@ impl DefaultAppState for Client {
let main = WidgetPtr::new().handles(ui); let main = WidgetPtr::new().handles(ui);
let vals = Rc::new(RefCell::new((0, Vec::new()))); let vals = Rc::new(RefCell::new((0, Vec::new())));
let mut switch_button = |color, to: WidgetHandle, label| { let mut switch_button = |color, to: WidgetHandle<Self>, label| {
let vec = &mut vals.borrow_mut().1; let vec = &mut vals.borrow_mut().1;
let i = vec.len(); let i = vec.len();
if vec.is_empty() { if vec.is_empty() {
@@ -188,28 +197,33 @@ impl DefaultAppState for Client {
) )
.span(Dir::RIGHT); .span(Dir::RIGHT);
let info = wtext("").handles(ui); info = wtext("").handles(ui);
let info_sect = info.h.pad(10).align(Align::RIGHT); let info_sect = info.h.pad(10).align(Align::RIGHT);
((tabs.height(40), main.h.pad(10)).span(Dir::DOWN), info_sect) ((tabs.height(40), main.h.pad(10)).span(Dir::DOWN), info_sect)
.stack() .stack()
.set_root(ui); .set_root(ui);
Self { info: info.r }
} }
fn window_event(&mut self, _: WindowEvent, ui: &mut Ui, state: &UiState) { Self {
ui,
ui_state: UiState::new(window),
info: info.r,
}
}
fn window_event(&mut self, _: WindowEvent) {
let new = format!( let new = format!(
"widgets: {}\nactive:{}\nviews: {}", "widgets: {}\nactive:{}\nviews: {}",
ui.num_widgets(), self.ui.num_widgets(),
ui.active_widgets(), self.ui.active_widgets(),
state.renderer.ui.view_count() self.ui_state.renderer.ui.view_count()
); );
if new != *ui[self.info].content { if new != *self.ui[self.info].content {
*ui[self.info].content = new; *self.ui[self.info].content = new;
} }
if ui.needs_redraw() { if self.ui.needs_redraw() {
state.window.request_redraw(); self.ui_state.window.request_redraw();
} }
} }
} }

View File

@@ -1,42 +1,34 @@
use crate::{default::UiState, prelude::*}; use crate::prelude::*;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use winit::dpi::{LogicalPosition, LogicalSize}; use winit::dpi::{LogicalPosition, LogicalSize};
pub struct Selector; pub struct Selector;
impl<W: Widget + 'static> WidgetAttr<W> for Selector { impl<State: HasUiState, W: Widget<State> + 'static> WidgetAttr<State, W> for Selector {
type Input = WidgetRef<TextEdit>; type Input = WidgetRef<State, TextEdit<State>>;
fn run(ui: &mut Ui, container: WidgetRef<W>, id: Self::Input) { fn run(ui: &mut Ui<State>, container: WidgetRef<State, W>, id: Self::Input) {
ui.register_event(container, CursorSense::click_or_drag(), move |ctx| { ui.register_event(container, CursorSense::click_or_drag(), move |ctx| {
let region = ctx.ui.window_region(&id).unwrap(); let region = ctx.state.ui().window_region(&id).unwrap();
let id_pos = region.top_left; let id_pos = region.top_left;
let container_pos = ctx.ui.window_region(&container).unwrap().top_left; let container_pos = ctx.state.ui().window_region(&container).unwrap().top_left;
let pos = ctx.data.pos + container_pos - id_pos; let pos = ctx.data.pos + container_pos - id_pos;
let size = region.size(); let size = region.size();
select( select(ctx.state, id, pos, size, ctx.data.sense.is_dragging());
ctx.ui,
id,
ctx.state,
pos,
size,
ctx.data.sense.is_dragging(),
);
}); });
} }
} }
pub struct Selectable; pub struct Selectable;
impl WidgetAttr<TextEdit> for Selectable { impl<State: HasUiState> WidgetAttr<State, TextEdit<State>> for Selectable {
type Input = (); type Input = ();
fn run(ui: &mut Ui, id: WidgetRef<TextEdit>, _: Self::Input) { fn run(ui: &mut Ui<State>, id: WidgetRef<State, TextEdit<State>>, _: Self::Input) {
ui.register_event(id, CursorSense::click_or_drag(), move |ctx| { ui.register_event(id, CursorSense::click_or_drag(), move |ctx| {
select( select(
ctx.ui,
id,
ctx.state, ctx.state,
id,
ctx.data.pos, ctx.data.pos,
ctx.data.size, ctx.data.size,
ctx.data.sense.is_dragging(), ctx.data.sense.is_dragging(),
@@ -45,24 +37,23 @@ impl WidgetAttr<TextEdit> for Selectable {
} }
} }
fn select( fn select<State: 'static + HasUiState>(
ui: &mut Ui, state: &mut State,
id: WidgetRef<TextEdit>, id: WidgetRef<State, TextEdit<State>>,
state: &mut UiState,
pos: Vec2, pos: Vec2,
size: Vec2, size: Vec2,
dragging: bool, dragging: bool,
) { ) {
let now = Instant::now(); let now = Instant::now();
let recent = (now - state.last_click) < Duration::from_millis(300); let recent = (now - state.ui_state().last_click) < Duration::from_millis(300);
state.last_click = now; state.ui_state().last_click = now;
id.edit(ui).select(pos, size, dragging, recent); id.edit(state.ui()).select(pos, size, dragging, recent);
if let Some(region) = ui.window_region(&id) { if let Some(region) = state.ui().window_region(&id) {
state.window.set_ime_allowed(true); state.ui_state().window.set_ime_allowed(true);
state.window.set_ime_cursor_area( state.ui_state().window.set_ime_cursor_area(
LogicalPosition::<f32>::from(region.top_left.tuple()), LogicalPosition::<f32>::from(region.top_left.tuple()),
LogicalSize::<f32>::from(region.size().tuple()), LogicalSize::<f32>::from(region.size().tuple()),
); );
} }
state.focus = Some(id); state.ui_state().focus = Some(id);
} }

View File

@@ -66,7 +66,7 @@ impl Input {
} }
} }
impl UiState { impl<State> UiState<State> {
pub fn window_size(&self) -> Vec2 { pub fn window_size(&self) -> Vec2 {
let size = self.renderer.window().inner_size(); let size = self.renderer.window().inner_size();
(size.width, size.height).into() (size.width, size.height).into()

View File

@@ -1,10 +1,11 @@
use crate::prelude::*; use crate::prelude::*;
use arboard::Clipboard; use arboard::Clipboard;
use std::sync::Arc; use std::{marker::Sized, sync::Arc, time::Instant};
use std::time::Instant; use winit::{
use winit::event::{Ime, WindowEvent}; event::{Ime, WindowEvent},
use winit::event_loop::{ActiveEventLoop, EventLoopProxy}; event_loop::{ActiveEventLoop, EventLoopProxy},
use winit::window::{Window, WindowAttributes}; window::Window,
};
mod app; mod app;
mod attr; mod attr;
@@ -21,49 +22,21 @@ pub use render::*;
pub use sense::*; pub use sense::*;
pub type Proxy<Event> = EventLoopProxy<Event>; pub type Proxy<Event> = EventLoopProxy<Event>;
pub type DefaultApp<Data> = App<DefaultState<Data>>;
pub struct DefaultState<AppState> { pub struct UiState<State> {
ui: Ui,
ui_state: UiState,
app_state: AppState,
}
pub struct UiState {
pub renderer: UiRenderer, pub renderer: UiRenderer,
pub input: Input, pub input: Input,
pub focus: Option<WidgetRef<TextEdit>>, pub focus: Option<WidgetRef<State, TextEdit<State>>>,
pub clipboard: Clipboard, pub clipboard: Clipboard,
pub window: Arc<Window>, pub window: Arc<Window>,
pub ime: usize, pub ime: usize,
pub last_click: Instant, pub last_click: Instant,
} }
pub trait DefaultAppState: 'static { impl<State> UiState<State> {
type Event: 'static = (); pub fn new(window: impl Into<Arc<Window>>) -> Self {
fn new(ui: &mut Ui, state: &UiState, proxy: Proxy<Self::Event>) -> Self; let window = window.into();
#[allow(unused_variables)] Self {
fn event(&mut self, event: Self::Event, ui: &mut Ui, state: &UiState) {}
#[allow(unused_variables)]
fn exit(&mut self, ui: &mut Ui, state: &UiState) {}
#[allow(unused_variables)]
fn window_event(&mut self, event: WindowEvent, ui: &mut Ui, state: &UiState) {}
fn window_attrs() -> WindowAttributes {
WindowAttributes::default()
}
}
impl<State: DefaultAppState> AppState for DefaultState<State> {
type Event = State::Event;
fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Self::Event>) -> Self {
let window = Arc::new(
event_loop
.create_window(State::window_attrs())
.expect("failed to create window "),
);
let mut ui = Ui::new();
let ui_state = UiState {
renderer: UiRenderer::new(window.clone()), renderer: UiRenderer::new(window.clone()),
window, window,
input: Input::default(), input: Input::default(),
@@ -71,26 +44,42 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
ime: 0, ime: 0,
last_click: Instant::now(), last_click: Instant::now(),
focus: None, focus: None,
};
let app_state = State::new(&mut ui, &ui_state, proxy);
Self {
ui,
ui_state,
app_state,
} }
} }
}
pub trait HasUiState: Sized + 'static + HasUi {
fn ui_state(&mut self) -> &mut UiState<Self>;
fn ui_with_ui_state(&mut self) -> (&mut Ui<Self>, &mut UiState<Self>) {
// as long as you're not doing anything actually unhinged this should always work safely
(unsafe { std::mem::transmute(self.ui()) }, self.ui_state())
}
}
pub trait DefaultAppState: Sized + 'static + HasUi + HasUiState {
type Event: 'static = ();
fn new(event_loop: &ActiveEventLoop, proxy: Proxy<Self::Event>) -> Self;
#[allow(unused_variables)]
fn event(&mut self, event: Self::Event) {}
#[allow(unused_variables)]
fn exit(&mut self) {}
#[allow(unused_variables)]
fn window_event(&mut self, event: WindowEvent) {}
}
impl<State: DefaultAppState> AppState for State {
type Event = State::Event;
fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Self::Event>) -> Self {
Self::new(event_loop, proxy)
}
fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) { fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) {
self.app_state.event(event, &mut self.ui, &self.ui_state); self.event(event);
} }
fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) { fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) {
let Self { let ui_state = self.ui_state();
ui,
ui_state,
app_state,
} = self;
let input_changed = ui_state.input.event(&event); let input_changed = ui_state.input.event(&event);
let cursor_state = ui_state.cursor_state().clone(); let cursor_state = ui_state.cursor_state().clone();
let old = ui_state.focus; let old = ui_state.focus;
@@ -99,13 +88,9 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
} }
if input_changed { if input_changed {
let window_size = ui_state.window_size(); let window_size = ui_state.window_size();
// call sensors with all 3 important contexts self.run_sensors(&cursor_state, window_size);
// TODO: allow user to specify custom contexts?
// and give them both states in case they need both
ui.run_sensors(&mut (), &cursor_state, window_size);
ui.run_sensors(ui_state, &cursor_state, window_size);
ui.run_sensors(app_state, &cursor_state, window_size);
} }
let (mut ui, mut ui_state) = self.ui_with_ui_state();
if old != ui_state.focus if old != ui_state.focus
&& let Some(old) = old && let Some(old) = old
{ {
@@ -133,13 +118,13 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
ui_state.window.set_ime_allowed(false); ui_state.window.set_ime_allowed(false);
} }
TextInputResult::Submit => { TextInputResult::Submit => {
ui.run_event::<Submit, _>(app_state, sel, &mut ()); self.run_event::<Submit>(sel, &mut ());
} }
TextInputResult::Paste => { TextInputResult::Paste => {
if let Ok(t) = ui_state.clipboard.get_text() { if let Ok(t) = ui_state.clipboard.get_text() {
text.insert(&t); text.insert(&t);
} }
ui.run_event::<Edited, _>(app_state, sel, &mut ()); self.run_event::<Edited>(sel, &mut ());
} }
TextInputResult::Copy(text) => { TextInputResult::Copy(text) => {
if let Err(err) = ui_state.clipboard.set_text(text) { if let Err(err) = ui_state.clipboard.set_text(text) {
@@ -147,14 +132,14 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
} }
} }
TextInputResult::Used => { TextInputResult::Used => {
ui.run_event::<Edited, _>(app_state, sel, &mut ()); self.run_event::<Edited>(sel, &mut ());
} }
TextInputResult::Unused => {} TextInputResult::Unused => {}
} }
} }
} }
WindowEvent::Ime(ime) => { WindowEvent::Ime(ime) => {
if let Some(sel) = &ui_state.focus { if let Some(sel) = ui_state.focus {
let mut text = sel.edit(ui); let mut text = sel.edit(ui);
match ime { match ime {
Ime::Enabled | Ime::Disabled => (), Ime::Enabled | Ime::Disabled => (),
@@ -171,7 +156,8 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
} }
_ => (), _ => (),
} }
app_state.window_event(event, ui, ui_state); self.window_event(event);
(ui, ui_state) = self.ui_with_ui_state();
if ui.needs_redraw() { if ui.needs_redraw() {
ui_state.renderer.window().request_redraw(); ui_state.renderer.window().request_redraw();
} }
@@ -179,6 +165,6 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
} }
fn exit(&mut self) { fn exit(&mut self) {
self.app_state.exit(&mut self.ui, &self.ui_state); self.exit();
} }
} }

View File

@@ -18,7 +18,7 @@ pub struct UiRenderer {
} }
impl UiRenderer { impl UiRenderer {
pub fn update(&mut self, updates: &mut Ui) { pub fn update<State>(&mut self, updates: &mut Ui<State>) {
self.ui.update(&self.device, &self.queue, updates); self.ui.update(&self.device, &self.queue, updates);
} }

View File

@@ -138,28 +138,23 @@ pub struct CursorData<'a> {
pub sense: CursorSense, pub sense: CursorSense,
} }
pub trait SensorUi { pub trait SensorUi<State> {
fn run_sensors<Ctx: 'static>(&mut self, ctx: &mut Ctx, cursor: &CursorState, window_size: Vec2); fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2);
} }
impl SensorUi for Ui { impl<State: 'static + HasUi> SensorUi<State> for State {
fn run_sensors<Ctx: 'static>( fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2) {
&mut self, let layers = std::mem::take(&mut self.ui().data.layers);
ctx: &mut Ctx,
cursor: &CursorState,
window_size: Vec2,
) {
let layers = std::mem::take(&mut self.data.layers);
let mut active = let mut active =
std::mem::take(&mut self.data.events.get_type::<CursorSense, Ctx>().active); std::mem::take(&mut self.ui().data.events.get_type::<CursorSense>().active);
for layer in layers.indices().rev() { for layer in layers.indices().rev() {
let mut sensed = false; let mut sensed = false;
for (id, state) in active.get_mut(&layer).into_iter().flatten() { for (id, sensor) in active.get_mut(&layer).into_iter().flatten() {
let shape = self.data.active.get(id).unwrap().region; let shape = self.ui().data.active.get(id).unwrap().region;
let region = shape.to_px(window_size); let region = shape.to_px(window_size);
let in_shape = cursor.exists && region.contains(cursor.pos); let in_shape = cursor.exists && region.contains(cursor.pos);
state.hover.update(in_shape); sensor.hover.update(in_shape);
if state.hover == ActivationState::Off { if sensor.hover == ActivationState::Off {
continue; continue;
} }
sensed = true; sensed = true;
@@ -168,20 +163,20 @@ impl SensorUi for Ui {
pos: cursor.pos - region.top_left, pos: cursor.pos - region.top_left,
size: region.bot_right - region.top_left, size: region.bot_right - region.top_left,
scroll_delta: cursor.scroll_delta, scroll_delta: cursor.scroll_delta,
hover: state.hover, hover: sensor.hover,
cursor, cursor,
// this does not have any meaning; // this does not have any meaning;
// might wanna set up Event to have a prepare stage // might wanna set up Event to have a prepare stage
sense: CursorSense::Hovering, sense: CursorSense::Hovering,
}; };
self.run_event::<CursorSense, Ctx>(ctx, *id, &mut data); self.run_event::<CursorSense>(*id, &mut data);
} }
if sensed { if sensed {
break; break;
} }
} }
self.data.events.get_type::<CursorSense, Ctx>().active = active; self.ui().data.events.get_type::<CursorSense>().active = active;
self.data.layers = layers; self.ui().data.layers = layers;
} }
} }

View File

@@ -2,14 +2,13 @@ use crate::prelude::*;
pub mod eventable { pub mod eventable {
use super::*; use super::*;
widget_trait! { widget_trait! {
pub trait Eventable; pub trait Eventable<State: 'static>;
fn on<E: EventLike, Ctx: 'static>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl for<'a> WidgetEventFn<Ctx, <E::Event as Event>::Data<'a>, WL::Widget>, f: impl for<'a> WidgetEventFn<State, <E::Event as Event>::Data<'a>, WL::Widget>,
) -> impl WidgetIdFn<WL::Widget> { ) -> impl WidgetIdFn<State, WL::Widget> {
move |ui| { move |ui| {
let id = self.handles(ui); let id = self.handles(ui);
ui.register_event(id.r, event.into_event(), move |ctx| { ui.register_event(id.r, event.into_event(), move |ctx| {
@@ -17,7 +16,6 @@ pub mod eventable {
widget: id.r, widget: id.r,
state: ctx.state, state: ctx.state,
data: ctx.data, data: ctx.data,
ui: ctx.ui,
}); });
}); });
id.h id.h
@@ -35,25 +33,20 @@ macro_rules! event_ctx {
#[allow(unused_imports)] #[allow(unused_imports)]
use $crate::prelude::*; use $crate::prelude::*;
widget_trait! { pub trait EventableCtx<WL: WidgetLike<$ty, Tag>, Tag> {
pub trait EventableCtx;
fn on<E: EventLike>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl for<'a> WidgetEventFn<$ty, <E::Event as Event>::Data<'a>, WL::Widget>, f: impl for<'a> WidgetEventFn<$ty, <E::Event as Event>::Data<'a>, WL::Widget>,
) -> impl WidgetIdFn<WL::Widget> { ) -> impl WidgetIdFn<$ty, WL::Widget>;
move |ui| {
let id = self.handles(ui);
ui.register_event(id.r, event.into_event(), move |ctx| {
f(EventIdCtx {
widget: id.r,
state: ctx.state,
data: ctx.data,
ui: ctx.ui,
});
});
id.h
} }
impl<WL: WidgetLike<$ty, Tag>, Tag> EventableCtx<WL, Tag> for WL {
fn on<E: EventLike>(
self,
event: E,
f: impl for<'a> WidgetEventFn<Client, <E::Event as Event>::Data<'a>, WL::Widget>,
) -> impl WidgetIdFn<Client, WL::Widget> {
eventable::Eventable::on(self, event, f)
} }
} }
} }

View File

@@ -5,21 +5,21 @@ pub struct Image {
handle: TextureHandle, handle: TextureHandle,
} }
impl Widget for Image { impl<State: 'static> Widget<State> for Image {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.texture(&self.handle); painter.texture(&self.handle);
} }
fn desired_width(&mut self, _: &mut SizeCtx) -> Len { fn desired_width(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::abs(self.handle.size().x) Len::abs(self.handle.size().x)
} }
fn desired_height(&mut self, _: &mut SizeCtx) -> Len { fn desired_height(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::abs(self.handle.size().y) Len::abs(self.handle.size().y)
} }
} }
pub fn image(image: impl LoadableImage) -> impl WidgetFn<Image> { pub fn image<State: 'static>(image: impl LoadableImage) -> impl WidgetFn<State, Image> {
let image = image.get_image().expect("Failed to load image"); let image = image.get_image().expect("Failed to load image");
move |ui| Image { move |ui| Image {
handle: ui.add_texture(image), handle: ui.add_texture(image),

View File

@@ -1,20 +1,20 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Masked { pub struct Masked<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
} }
impl Widget for Masked { impl<State: 'static> Widget<State> for Masked<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.set_mask(painter.region()); painter.set_mask(painter.region());
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

@@ -1,12 +1,12 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Aligned { pub struct Aligned<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
pub align: Align, pub align: Align,
} }
impl Widget for Aligned { impl<State: 'static> Widget<State> for Aligned<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let region = match self.align.tuple() { let region = match self.align.tuple() {
(Some(x), Some(y)) => painter (Some(x), Some(y)) => painter
.size(&self.inner) .size(&self.inner)
@@ -25,11 +25,11 @@ impl Widget for Aligned {
painter.widget_within(&self.inner, region); painter.widget_within(&self.inner, region);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

@@ -1,23 +1,23 @@
use crate::prelude::*; use crate::prelude::*;
pub struct LayerOffset { pub struct LayerOffset<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
pub offset: usize, pub offset: usize,
} }
impl Widget for LayerOffset { impl<State: 'static> Widget<State> for LayerOffset<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
for _ in 0..self.offset { for _ in 0..self.offset {
painter.next_layer(); painter.next_layer();
} }
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

@@ -1,13 +1,13 @@
use crate::prelude::*; use crate::prelude::*;
pub struct MaxSize { pub struct MaxSize<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
pub x: Option<Len>, pub x: Option<Len>,
pub y: Option<Len>, pub y: Option<Len>,
} }
impl MaxSize { impl<State: 'static> MaxSize<State> {
fn apply_to_outer(&self, ctx: &mut SizeCtx) { fn apply_to_outer(&self, ctx: &mut SizeCtx<State>) {
if let Some(x) = self.x { if let Some(x) = self.x {
ctx.outer.x.select_len(x.apply_rest()); ctx.outer.x.select_len(x.apply_rest());
} }
@@ -17,12 +17,12 @@ impl MaxSize {
} }
} }
impl Widget for MaxSize { impl<State: 'static> Widget<State> for MaxSize<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.apply_to_outer(ctx); self.apply_to_outer(ctx);
let width = ctx.width(&self.inner); let width = ctx.width(&self.inner);
if let Some(x) = self.x { if let Some(x) = self.x {
@@ -34,7 +34,7 @@ impl Widget for MaxSize {
} }
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.apply_to_outer(ctx); self.apply_to_outer(ctx);
let height = ctx.height(&self.inner); let height = ctx.height(&self.inner);
if let Some(y) = self.y { if let Some(y) = self.y {

View File

@@ -1,21 +1,21 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Offset { pub struct Offset<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
pub amt: UiVec2, pub amt: UiVec2,
} }
impl Widget for Offset { impl<State: 'static> Widget<State> for Offset<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let region = UiRegion::FULL.offset(self.amt); let region = UiRegion::FULL.offset(self.amt);
painter.widget_within(&self.inner, region); painter.widget_within(&self.inner, region);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

@@ -1,16 +1,16 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Pad { pub struct Pad<State> {
pub padding: Padding, pub padding: Padding,
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
} }
impl Widget for Pad { impl<State: 'static> Widget<State> for Pad<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.widget_within(&self.inner, self.padding.region()); painter.widget_within(&self.inner, self.padding.region());
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
let width = self.padding.left + self.padding.right; let width = self.padding.left + self.padding.right;
let height = self.padding.top + self.padding.bottom; let height = self.padding.top + self.padding.bottom;
ctx.outer.x.abs -= width; ctx.outer.x.abs -= width;
@@ -20,7 +20,7 @@ impl Widget for Pad {
size size
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
let width = self.padding.left + self.padding.right; let width = self.padding.left + self.padding.right;
let height = self.padding.top + self.padding.bottom; let height = self.padding.top + self.padding.bottom;
ctx.outer.x.abs -= width; ctx.outer.x.abs -= width;

View File

@@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Scroll { pub struct Scroll<State> {
inner: WidgetHandle, inner: WidgetHandle<State>,
axis: Axis, axis: Axis,
amt: f32, amt: f32,
snap_end: bool, snap_end: bool,
@@ -9,8 +9,8 @@ pub struct Scroll {
content_len: f32, content_len: f32,
} }
impl Widget for Scroll { impl<State: 'static> Widget<State> for Scroll<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let output_len = painter.output_size().axis(self.axis); let output_len = painter.output_size().axis(self.axis);
let container_len = painter.region().axis(self.axis).len(); let container_len = painter.region().axis(self.axis).len();
let content_len = painter let content_len = painter
@@ -31,17 +31,17 @@ impl Widget for Scroll {
painter.widget_within(&self.inner, region); painter.widget_within(&self.inner, region);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }
impl Scroll { impl<State> Scroll<State> {
pub fn new(inner: WidgetHandle, axis: Axis) -> Self { pub fn new(inner: WidgetHandle<State>, axis: Axis) -> Self {
Self { Self {
inner, inner,
axis, axis,

View File

@@ -1,13 +1,13 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Sized { pub struct Sized<State> {
pub inner: WidgetHandle, pub inner: WidgetHandle<State>,
pub x: Option<Len>, pub x: Option<Len>,
pub y: Option<Len>, pub y: Option<Len>,
} }
impl Sized { impl<State: 'static> Sized<State> {
fn apply_to_outer(&self, ctx: &mut SizeCtx) { fn apply_to_outer(&self, ctx: &mut SizeCtx<State>) {
if let Some(x) = self.x { if let Some(x) = self.x {
ctx.outer.x.select_len(x.apply_rest()); ctx.outer.x.select_len(x.apply_rest());
} }
@@ -17,17 +17,17 @@ impl Sized {
} }
} }
impl Widget for Sized { impl<State: 'static> Widget<State> for Sized<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.apply_to_outer(ctx); self.apply_to_outer(ctx);
self.x.unwrap_or_else(|| ctx.width(&self.inner)) self.x.unwrap_or_else(|| ctx.width(&self.inner))
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.apply_to_outer(ctx); self.apply_to_outer(ctx);
self.y.unwrap_or_else(|| ctx.height(&self.inner)) self.y.unwrap_or_else(|| ctx.height(&self.inner))
} }

View File

@@ -1,14 +1,14 @@
use crate::prelude::*; use crate::prelude::*;
use std::marker::PhantomData; use std::marker::PhantomData;
pub struct Span { pub struct Span<State> {
pub children: Vec<WidgetHandle>, pub children: Vec<WidgetHandle<State>>,
pub dir: Dir, pub dir: Dir,
pub gap: f32, pub gap: f32,
} }
impl Widget for Span { impl<State: 'static> Widget<State> for Span<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let total = self.len_sum(&mut painter.size_ctx()); let total = self.len_sum(&mut painter.size_ctx());
let mut start = UiScalar::rel_min(); let mut start = UiScalar::rel_min();
for child in &self.children { for child in &self.children {
@@ -33,14 +33,14 @@ impl Widget for Span {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
match self.dir.axis { match self.dir.axis {
Axis::X => self.desired_len(ctx), Axis::X => self.desired_len(ctx),
Axis::Y => self.desired_ortho(ctx), Axis::Y => self.desired_ortho(ctx),
} }
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
match self.dir.axis { match self.dir.axis {
Axis::X => self.desired_ortho(ctx), Axis::X => self.desired_ortho(ctx),
Axis::Y => self.desired_len(ctx), Axis::Y => self.desired_len(ctx),
@@ -48,7 +48,7 @@ impl Widget for Span {
} }
} }
impl Span { impl<State: 'static> Span<State> {
pub fn empty(dir: Dir) -> Self { pub fn empty(dir: Dir) -> Self {
Self { Self {
children: Vec::new(), children: Vec::new(),
@@ -62,7 +62,7 @@ impl Span {
self self
} }
fn len_sum(&mut self, ctx: &mut SizeCtx) -> Len { fn len_sum(&mut self, ctx: &mut SizeCtx<State>) -> Len {
let gap = self.gap * self.children.len().saturating_sub(1) as f32; let gap = self.gap * self.children.len().saturating_sub(1) as f32;
self.children.iter().fold(Len::abs(gap), |mut s, id| { self.children.iter().fold(Len::abs(gap), |mut s, id| {
// it's tempting to subtract the abs & rel from the ctx outer, // it's tempting to subtract the abs & rel from the ctx outer,
@@ -78,7 +78,7 @@ impl Span {
}) })
} }
fn desired_len(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_len(&mut self, ctx: &mut SizeCtx<State>) -> Len {
let len = self.len_sum(ctx); let len = self.len_sum(ctx);
if len.rest == 0.0 && len.rel == 0.0 { if len.rest == 0.0 && len.rel == 0.0 {
len len
@@ -87,7 +87,7 @@ impl Span {
} }
} }
fn desired_ortho(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_ortho(&mut self, ctx: &mut SizeCtx<State>) -> Len {
// this is a weird hack to get text wrapping to work properly when in a downward span // this is a weird hack to get text wrapping to work properly when in a downward span
// the correct solution here is to add a function to widget that lets them // the correct solution here is to add a function to widget that lets them
// request that ctx.outer has an axis "resolved" before checking the other, // request that ctx.outer has an axis "resolved" before checking the other,
@@ -144,19 +144,19 @@ impl Span {
} }
} }
pub struct SpanBuilder<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> { pub struct SpanBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
pub children: Wa, pub children: Wa,
pub dir: Dir, pub dir: Dir,
pub gap: f32, pub gap: f32,
_pd: PhantomData<Tag>, _pd: PhantomData<(State, Tag)>,
} }
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)> impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut Ui<State>,)>
for SpanBuilder<LEN, Wa, Tag> for SpanBuilder<State, LEN, Wa, Tag>
{ {
type Output = Span; type Output = Span<State>;
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output {
Span { Span {
children: self.children.ui(args.0).arr.into_iter().collect(), children: self.children.ui(args.0).arr.into_iter().collect(),
dir: self.dir, dir: self.dir,
@@ -165,7 +165,9 @@ impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
} }
} }
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> SpanBuilder<LEN, Wa, Tag> { impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
SpanBuilder<State, LEN, Wa, Tag>
{
pub fn new(children: Wa, dir: Dir) -> Self { pub fn new(children: Wa, dir: Dir) -> Self {
Self { Self {
children, children,
@@ -181,15 +183,15 @@ impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> SpanBuilder<LEN, Wa, Ta
} }
} }
impl std::ops::Deref for Span { impl<State> std::ops::Deref for Span<State> {
type Target = Vec<WidgetHandle>; type Target = Vec<WidgetHandle<State>>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.children &self.children
} }
} }
impl std::ops::DerefMut for Span { impl<State> std::ops::DerefMut for Span<State> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.children &mut self.children
} }

View File

@@ -2,13 +2,13 @@ use std::marker::PhantomData;
use crate::prelude::*; use crate::prelude::*;
pub struct Stack { pub struct Stack<State> {
pub children: Vec<WidgetHandle>, pub children: Vec<WidgetHandle<State>>,
pub size: StackSize, pub size: StackSize,
} }
impl Widget for Stack { impl<State: 'static> Widget<State> for Stack<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let mut iter = self.children.iter(); let mut iter = self.children.iter();
if let Some(child) = iter.next() { if let Some(child) = iter.next() {
painter.child_layer(); painter.child_layer();
@@ -20,14 +20,14 @@ impl Widget for Stack {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
match self.size { match self.size {
StackSize::Default => Len::default(), StackSize::Default => Len::default(),
StackSize::Child(i) => ctx.width(&self.children[i]), StackSize::Child(i) => ctx.width(&self.children[i]),
} }
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
match self.size { match self.size {
StackSize::Default => Len::default(), StackSize::Default => Len::default(),
StackSize::Child(i) => ctx.height(&self.children[i]), StackSize::Child(i) => ctx.height(&self.children[i]),
@@ -42,18 +42,18 @@ pub enum StackSize {
Child(usize), Child(usize),
} }
pub struct StackBuilder<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> { pub struct StackBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
pub children: Wa, pub children: Wa,
pub size: StackSize, pub size: StackSize,
_pd: PhantomData<Tag>, _pd: PhantomData<(State, Tag)>,
} }
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)> impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut Ui<State>,)>
for StackBuilder<LEN, Wa, Tag> for StackBuilder<State, LEN, Wa, Tag>
{ {
type Output = Stack; type Output = Stack<State>;
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output {
Stack { Stack {
children: self.children.ui(args.0).arr.into_iter().collect(), children: self.children.ui(args.0).arr.into_iter().collect(),
size: self.size, size: self.size,
@@ -61,7 +61,9 @@ impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
} }
} }
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> StackBuilder<LEN, Wa, Tag> { impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
StackBuilder<State, LEN, Wa, Tag>
{
pub fn new(children: Wa) -> Self { pub fn new(children: Wa) -> Self {
Self { Self {
children, children,

View File

@@ -1,19 +1,18 @@
use crate::prelude::*; use crate::prelude::*;
use std::marker::{Sized, Unsize}; use std::marker::{Sized, Unsize};
#[derive(Default)] pub struct WidgetPtr<State> {
pub struct WidgetPtr { pub inner: Option<WidgetHandle<State>>,
pub inner: Option<WidgetHandle>,
} }
impl Widget for WidgetPtr { impl<State: 'static> Widget<State> for WidgetPtr<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
if let Some(id) = &self.inner { if let Some(id) = &self.inner {
painter.widget(id); painter.widget(id);
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
if let Some(id) = &self.inner { if let Some(id) = &self.inner {
ctx.width(id) ctx.width(id)
} else { } else {
@@ -21,7 +20,7 @@ impl Widget for WidgetPtr {
} }
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
if let Some(id) = &self.inner { if let Some(id) = &self.inner {
ctx.height(id) ctx.height(id)
} else { } else {
@@ -30,18 +29,29 @@ impl Widget for WidgetPtr {
} }
} }
impl WidgetPtr { impl<State> WidgetPtr<State> {
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
} }
pub fn set<W: ?Sized + Unsize<dyn Widget>>(&mut self, to: WidgetHandle<W>) { pub fn empty() -> Self {
Self {
inner: Default::default(),
}
}
pub fn set<W: ?Sized + Unsize<dyn Widget<State>>>(&mut self, to: WidgetHandle<State, W>) {
self.inner = Some(to) self.inner = Some(to)
} }
pub fn replace<W: ?Sized + Unsize<dyn Widget>>( pub fn replace<W: ?Sized + Unsize<dyn Widget<State>>>(
&mut self, &mut self,
to: WidgetHandle<W>, to: WidgetHandle<State, W>,
) -> Option<WidgetHandle> { ) -> Option<WidgetHandle<State>> {
self.inner.replace(to) self.inner.replace(to)
} }
} }
impl<State> Default for WidgetPtr<State> {
fn default() -> Self {
Self::empty()
}
}

View File

@@ -27,8 +27,8 @@ impl Rect {
} }
} }
impl Widget for Rect { impl<State: 'static> Widget<State> for Rect {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
painter.primitive(RectPrimitive { painter.primitive(RectPrimitive {
color: self.color, color: self.color,
radius: self.radius, radius: self.radius,
@@ -37,11 +37,11 @@ impl Widget for Rect {
}); });
} }
fn desired_width(&mut self, _: &mut SizeCtx) -> Len { fn desired_width(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::rest(1) Len::rest(1)
} }
fn desired_height(&mut self, _: &mut SizeCtx) -> Len { fn desired_height(&mut self, _: &mut SizeCtx<State>) -> Len {
Len::rest(1) Len::rest(1)
} }
} }

View File

@@ -1,15 +1,16 @@
use crate::prelude::*; use crate::prelude::*;
use cosmic_text::{Attrs, Family, Metrics}; use cosmic_text::{Attrs, Family, Metrics};
use std::marker::Sized; use std::marker::{PhantomData, Sized};
pub struct TextBuilder<O = TextOutput, H: WidgetOption = ()> { pub struct TextBuilder<State, O = TextOutput, H: WidgetOption<State> = ()> {
pub content: String, pub content: String,
pub attrs: TextAttrs, pub attrs: TextAttrs,
pub hint: H, pub hint: H,
pub output: O, pub output: O,
state: PhantomData<State>,
} }
impl<O, H: WidgetOption> TextBuilder<O, H> { impl<State, O, H: WidgetOption<State>> TextBuilder<State, O, H> {
pub fn size(mut self, size: impl UiNum) -> Self { pub fn size(mut self, size: impl UiNum) -> Self {
self.attrs.font_size = size.to_f32(); self.attrs.font_size = size.to_f32();
self.attrs.line_height = self.attrs.font_size * LINE_HEIGHT_MULT; self.attrs.line_height = self.attrs.font_size * LINE_HEIGHT_MULT;
@@ -39,37 +40,48 @@ impl<O, H: WidgetOption> TextBuilder<O, H> {
self.attrs.wrap = wrap; self.attrs.wrap = wrap;
self self
} }
pub fn editable(self, single_line: bool) -> TextBuilder<TextEditOutput, H> { pub fn editable(self, single_line: bool) -> TextBuilder<State, TextEditOutput, H> {
TextBuilder { TextBuilder {
content: self.content, content: self.content,
attrs: self.attrs, attrs: self.attrs,
hint: self.hint, hint: self.hint,
output: TextEditOutput { single_line }, output: TextEditOutput { single_line },
state: PhantomData,
} }
} }
} }
impl<O> TextBuilder<O> { impl<State: 'static, O> TextBuilder<State, O> {
pub fn hint<W: WidgetLike<Tag>, Tag>(self, hint: W) -> TextBuilder<O, impl WidgetOption> { pub fn hint<W: WidgetLike<State, Tag>, Tag>(
self,
hint: W,
) -> TextBuilder<State, O, impl WidgetOption<State>> {
TextBuilder { TextBuilder {
content: self.content, content: self.content,
attrs: self.attrs, attrs: self.attrs,
hint: move |ui: &mut Ui| Some(hint.add(ui).any()), hint: move |ui: &mut Ui<State>| Some(hint.add(ui).any()),
output: self.output, output: self.output,
state: PhantomData,
} }
} }
} }
pub trait TextBuilderOutput: Sized { pub trait TextBuilderOutput<State>: Sized {
type Output; type Output;
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output; fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>,
builder: TextBuilder<State, Self, H>,
) -> Self::Output;
} }
pub struct TextOutput; pub struct TextOutput;
impl TextBuilderOutput for TextOutput { impl<State: 'static> TextBuilderOutput<State> for TextOutput {
type Output = Text; type Output = Text<State>;
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output { fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>,
builder: TextBuilder<State, Self, H>,
) -> Self::Output {
let mut buf = TextBuffer::new_empty(Metrics::new( let mut buf = TextBuffer::new_empty(Metrics::new(
builder.attrs.font_size, builder.attrs.font_size,
builder.attrs.line_height, builder.attrs.line_height,
@@ -90,10 +102,13 @@ impl TextBuilderOutput for TextOutput {
pub struct TextEditOutput { pub struct TextEditOutput {
single_line: bool, single_line: bool,
} }
impl TextBuilderOutput for TextEditOutput { impl<State: 'static> TextBuilderOutput<State> for TextEditOutput {
type Output = TextEdit; type Output = TextEdit<State>;
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output { fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>,
builder: TextBuilder<State, Self, H>,
) -> Self::Output {
let buf = TextBuffer::new_empty(Metrics::new( let buf = TextBuffer::new_empty(Metrics::new(
builder.attrs.font_size, builder.attrs.font_size,
builder.attrs.line_height, builder.attrs.line_height,
@@ -110,19 +125,22 @@ impl TextBuilderOutput for TextEditOutput {
} }
} }
impl<O: TextBuilderOutput, H: WidgetOption> FnOnce<(&mut Ui,)> for TextBuilder<O, H> { impl<State, O: TextBuilderOutput<State>, H: WidgetOption<State>> FnOnce<(&mut Ui<State>,)>
for TextBuilder<State, O, H>
{
type Output = O::Output; type Output = O::Output;
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output {
O::run(args.0, self) O::run(args.0, self)
} }
} }
pub fn wtext(content: impl Into<String>) -> TextBuilder { pub fn wtext<State>(content: impl Into<String>) -> TextBuilder<State> {
TextBuilder { TextBuilder {
content: content.into(), content: content.into(),
attrs: TextAttrs::default(), attrs: TextAttrs::default(),
hint: (), hint: (),
output: TextOutput, output: TextOutput,
state: PhantomData,
} }
} }

View File

@@ -7,16 +7,16 @@ use winit::{
keyboard::{Key, NamedKey}, keyboard::{Key, NamedKey},
}; };
pub struct TextEdit { pub struct TextEdit<State> {
view: TextView, view: TextView<State>,
selection: TextSelection, selection: TextSelection,
history: Vec<(String, TextSelection)>, history: Vec<(String, TextSelection)>,
double_hit: Option<Cursor>, double_hit: Option<Cursor>,
pub single_line: bool, pub single_line: bool,
} }
impl TextEdit { impl<State: 'static> TextEdit<State> {
pub fn new(view: TextView, single_line: bool) -> Self { pub fn new(view: TextView<State>, single_line: bool) -> Self {
Self { Self {
view, view,
selection: Default::default(), selection: Default::default(),
@@ -43,8 +43,8 @@ impl TextEdit {
} }
} }
impl Widget for TextEdit { impl<State: 'static> Widget<State> for TextEdit<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
let base = painter.layer; let base = painter.layer;
painter.child_layer(); painter.child_layer();
self.view.draw(painter); self.view.draw(painter);
@@ -86,11 +86,11 @@ impl Widget for TextEdit {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.view.desired_width(ctx) self.view.desired_width(ctx)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.view.desired_height(ctx) self.view.desired_height(ctx)
} }
} }
@@ -174,12 +174,12 @@ fn cursor_pos(cursor: Cursor, buf: &TextBuffer) -> Option<Vec2> {
prev prev
} }
pub struct TextEditCtx<'a> { pub struct TextEditCtx<'a, State> {
pub text: &'a mut TextEdit, pub text: &'a mut TextEdit<State>,
pub font_system: &'a mut FontSystem, pub font_system: &'a mut FontSystem,
} }
impl<'a> TextEditCtx<'a> { impl<'a, State: 'static> TextEditCtx<'a, State> {
pub fn take(&mut self) -> String { pub fn take(&mut self) -> String {
let text = self let text = self
.text .text
@@ -596,26 +596,26 @@ impl TextInputResult {
} }
} }
impl Deref for TextEdit { impl<State> Deref for TextEdit<State> {
type Target = TextView; type Target = TextView<State>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.view &self.view
} }
} }
impl DerefMut for TextEdit { impl<State> DerefMut for TextEdit<State> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.view &mut self.view
} }
} }
pub trait TextEditable { pub trait TextEditable<State> {
fn edit<'a>(&self, ui: &'a mut Ui) -> TextEditCtx<'a>; fn edit<'a>(&self, ui: &'a mut Ui<State>) -> TextEditCtx<'a, State>;
} }
impl<I: IdLike<Widget = TextEdit>> TextEditable for I { impl<State: 'static, I: IdLike<State, Widget = TextEdit<State>>> TextEditable<State> for I {
fn edit<'a>(&self, ui: &'a mut Ui) -> TextEditCtx<'a> { fn edit<'a>(&self, ui: &'a mut Ui<State>) -> TextEditCtx<'a, State> {
TextEditCtx { TextEditCtx {
text: ui.data.widgets.get_mut(self).unwrap(), text: ui.data.widgets.get_mut(self).unwrap(),
font_system: &mut ui.data.text.font_system, font_system: &mut ui.data.text.font_system,

View File

@@ -11,22 +11,22 @@ use std::ops::{Deref, DerefMut};
pub const SHAPING: Shaping = Shaping::Advanced; pub const SHAPING: Shaping = Shaping::Advanced;
pub struct Text { pub struct Text<State> {
pub content: MutDetect<String>, pub content: MutDetect<String>,
view: TextView, view: TextView<State>,
} }
pub struct TextView { pub struct TextView<State> {
pub attrs: MutDetect<TextAttrs>, pub attrs: MutDetect<TextAttrs>,
pub buf: MutDetect<TextBuffer>, pub buf: MutDetect<TextBuffer>,
// cache // cache
tex: Option<RenderedText>, tex: Option<RenderedText>,
width: Option<f32>, width: Option<f32>,
pub hint: Option<WidgetHandle>, pub hint: Option<WidgetHandle<State>>,
} }
impl TextView { impl<State: 'static> TextView<State> {
pub fn new(buf: TextBuffer, attrs: TextAttrs, hint: Option<WidgetHandle>) -> Self { pub fn new(buf: TextBuffer, attrs: TextAttrs, hint: Option<WidgetHandle<State>>) -> Self {
Self { Self {
attrs: attrs.into(), attrs: attrs.into(),
buf: buf.into(), buf: buf.into(),
@@ -54,7 +54,7 @@ impl TextView {
region region
} }
fn render(&mut self, ctx: &mut SizeCtx) -> RenderedText { fn render(&mut self, ctx: &mut SizeCtx<State>) -> RenderedText {
let width = if self.attrs.wrap { let width = if self.attrs.wrap {
Some(ctx.px_size().x) Some(ctx.px_size().x)
} else { } else {
@@ -80,7 +80,7 @@ impl TextView {
pub fn tex(&self) -> Option<&RenderedText> { pub fn tex(&self) -> Option<&RenderedText> {
self.tex.as_ref() self.tex.as_ref()
} }
pub fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { pub fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
if let Some(hint) = &self.hint if let Some(hint) = &self.hint
&& let [line] = &self.buf.lines[..] && let [line] = &self.buf.lines[..]
&& line.text().is_empty() && line.text().is_empty()
@@ -90,7 +90,7 @@ impl TextView {
Len::abs(self.render(ctx).size.x) Len::abs(self.render(ctx).size.x)
} }
} }
pub fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { pub fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
if let Some(hint) = &self.hint if let Some(hint) = &self.hint
&& let [line] = &self.buf.lines[..] && let [line] = &self.buf.lines[..]
&& line.text().is_empty() && line.text().is_empty()
@@ -100,7 +100,7 @@ impl TextView {
Len::abs(self.render(ctx).size.y) Len::abs(self.render(ctx).size.y)
} }
} }
pub fn draw(&mut self, painter: &mut Painter) -> UiRegion { pub fn draw(&mut self, painter: &mut Painter<State>) -> UiRegion {
let tex = self.render(&mut painter.size_ctx()); let tex = self.render(&mut painter.size_ctx());
let region = self.tex_region(&tex); let region = self.tex_region(&tex);
if let Some(hint) = &self.hint if let Some(hint) = &self.hint
@@ -124,7 +124,7 @@ impl TextView {
} }
} }
impl Text { impl<State: 'static> Text<State> {
pub fn new(content: impl Into<String>) -> Self { pub fn new(content: impl Into<String>) -> Self {
let attrs = TextAttrs::default(); let attrs = TextAttrs::default();
let buf = TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height)); let buf = TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height));
@@ -133,7 +133,7 @@ impl Text {
view: TextView::new(buf, attrs, None), view: TextView::new(buf, attrs, None),
} }
} }
fn update_buf(&mut self, ctx: &mut SizeCtx) { fn update_buf(&mut self, ctx: &mut SizeCtx<State>) {
if self.content.changed { if self.content.changed {
self.content.changed = false; self.content.changed = false;
self.view.buf.set_text( self.view.buf.set_text(
@@ -147,18 +147,18 @@ impl Text {
} }
} }
impl Widget for Text { impl<State: 'static> Widget<State> for Text<State> {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter<State>) {
self.update_buf(&mut painter.size_ctx()); self.update_buf(&mut painter.size_ctx());
self.view.draw(painter); self.view.draw(painter);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.update_buf(ctx); self.update_buf(ctx);
self.view.desired_width(ctx) self.view.desired_width(ctx)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len {
self.update_buf(ctx); self.update_buf(ctx);
self.view.desired_height(ctx) self.view.desired_height(ctx)
} }
@@ -174,7 +174,7 @@ pub fn edit_line(line: &mut BufferLine, text: String) {
line.set_text(text, line.ending(), line.attrs_list().clone()); line.set_text(text, line.ending(), line.attrs_list().clone());
} }
impl Deref for Text { impl<State> Deref for Text<State> {
type Target = TextAttrs; type Target = TextAttrs;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -182,13 +182,13 @@ impl Deref for Text {
} }
} }
impl DerefMut for Text { impl<State> DerefMut for Text<State> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.view &mut self.view
} }
} }
impl Deref for TextView { impl<State> Deref for TextView<State> {
type Target = TextAttrs; type Target = TextAttrs;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -196,7 +196,7 @@ impl Deref for TextView {
} }
} }
impl DerefMut for TextView { impl<State> DerefMut for TextView<State> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.attrs &mut self.attrs
} }

View File

@@ -2,30 +2,28 @@ use super::*;
use crate::prelude::*; use crate::prelude::*;
// these methods should "not require any context" (require unit) because they're in core // these methods should "not require any context" (require unit) because they're in core
event_ctx!(());
widget_trait! { widget_trait! {
pub trait CoreWidget; pub trait CoreWidget<State: HasUi + 'static>;
fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<Pad> { fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<State, Pad<State>> {
|ui| Pad { |ui| Pad {
padding: padding.into(), padding: padding.into(),
inner: self.add(ui), inner: self.add(ui),
} }
} }
fn align(self, align: impl Into<Align>) -> impl WidgetFn<Aligned> { fn align(self, align: impl Into<Align>) -> impl WidgetFn<State, Aligned<State>> {
move |ui| Aligned { move |ui| Aligned {
inner: self.add(ui), inner: self.add(ui),
align: align.into(), align: align.into(),
} }
} }
fn center(self) -> impl WidgetFn<Aligned> { fn center(self) -> impl WidgetFn<State, Aligned<State>> {
self.align(Align::CENTER) self.align(Align::CENTER)
} }
fn label(self, label: impl Into<String>) -> impl WidgetIdFn<WL::Widget> { fn label(self, label: impl Into<String>) -> impl WidgetIdFn<State, WL::Widget> {
|ui| { |ui| {
let id = self.add(ui); let id = self.add(ui);
ui.set_label(&id, label.into()); ui.set_label(&id, label.into());
@@ -33,7 +31,7 @@ widget_trait! {
} }
} }
fn sized(self, size: impl Into<Size>) -> impl WidgetFn<Sized> { fn sized(self, size: impl Into<Size>) -> impl WidgetFn<State, Sized<State>> {
let size = size.into(); let size = size.into();
move |ui| Sized { move |ui| Sized {
inner: self.add(ui), inner: self.add(ui),
@@ -42,7 +40,7 @@ widget_trait! {
} }
} }
fn max_width(self, len: impl Into<Len>) -> impl WidgetFn<MaxSize> { fn max_width(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize<State>> {
let len = len.into(); let len = len.into();
move |ui| MaxSize { move |ui| MaxSize {
inner: self.add(ui), inner: self.add(ui),
@@ -51,7 +49,7 @@ widget_trait! {
} }
} }
fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<MaxSize> { fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize<State>> {
let len = len.into(); let len = len.into();
move |ui| MaxSize { move |ui| MaxSize {
inner: self.add(ui), inner: self.add(ui),
@@ -60,7 +58,7 @@ widget_trait! {
} }
} }
fn width(self, len: impl Into<Len>) -> impl WidgetFn<Sized> { fn width(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized<State>> {
let len = len.into(); let len = len.into();
move |ui| Sized { move |ui| Sized {
inner: self.add(ui), inner: self.add(ui),
@@ -69,7 +67,7 @@ widget_trait! {
} }
} }
fn height(self, len: impl Into<Len>) -> impl WidgetFn<Sized> { fn height(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized<State>> {
let len = len.into(); let len = len.into();
move |ui| Sized { move |ui| Sized {
inner: self.add(ui), inner: self.add(ui),
@@ -78,66 +76,69 @@ widget_trait! {
} }
} }
fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<Offset> { fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<State, Offset<State>> {
move |ui| Offset { move |ui| Offset {
inner: self.add(ui), inner: self.add(ui),
amt: amt.into(), amt: amt.into(),
} }
} }
fn scroll(self) -> impl WidgetIdFn<Scroll> { fn scroll(self) -> impl WidgetIdFn<State, Scroll<State>> {
use eventable::*;
move |ui| { move |ui| {
Scroll::new(self.add(ui), Axis::Y) Scroll::new(self.add(ui), Axis::Y)
.on(CursorSense::Scroll, |ctx| { .on(CursorSense::Scroll, |ctx| {
let s = &mut ctx.ui[ctx.widget]; let s = &mut ctx.state.ui()[ctx.widget];
s.scroll(ctx.data.scroll_delta.y * 50.0); s.scroll(ctx.data.scroll_delta.y * 50.0);
}) })
.add(ui) .add(ui)
} }
} }
fn masked(self) -> impl WidgetFn<Masked> { fn masked(self) -> impl WidgetFn<State, Masked<State>> {
move |ui| Masked { move |ui| Masked {
inner: self.add(ui), inner: self.add(ui),
} }
} }
fn background<T>(self, w: impl WidgetLike<T>) -> impl WidgetFn<Stack> { fn background<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack<State>> {
move |ui| Stack { move |ui| Stack {
children: vec![w.add(ui), self.add(ui)], children: vec![w.add(ui), self.add(ui)],
size: StackSize::Child(1), size: StackSize::Child(1),
} }
} }
fn foreground<T>(self, w: impl WidgetLike<T>) -> impl WidgetFn<Stack> { fn foreground<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack<State>> {
move |ui| Stack { move |ui| Stack {
children: vec![self.add(ui), w.add(ui)], children: vec![self.add(ui), w.add(ui)],
size: StackSize::Child(0), size: StackSize::Child(0),
} }
} }
fn layer_offset(self, offset: usize) -> impl WidgetFn<LayerOffset> { fn layer_offset(self, offset: usize) -> impl WidgetFn<State, LayerOffset<State>> {
move |ui| LayerOffset { move |ui| LayerOffset {
inner: self.add(ui), inner: self.add(ui),
offset, offset,
} }
} }
fn to_any(self) -> impl WidgetIdFn { fn to_any(self) -> impl WidgetIdFn<State> {
|ui| self.add(ui) |ui| self.add(ui)
} }
} }
pub trait CoreWidgetArr<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> { pub trait CoreWidgetArr<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
fn span(self, dir: Dir) -> SpanBuilder<LEN, Wa, Tag>; fn span(self, dir: Dir) -> SpanBuilder<State, LEN, Wa, Tag>;
fn stack(self) -> StackBuilder<LEN, Wa, Tag>; fn stack(self) -> StackBuilder<State, LEN, Wa, Tag>;
} }
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> CoreWidgetArr<LEN, Wa, Tag> for Wa { impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
fn span(self, dir: Dir) -> SpanBuilder<LEN, Wa, Tag> { CoreWidgetArr<State, LEN, Wa, Tag> for Wa
{
fn span(self, dir: Dir) -> SpanBuilder<State, LEN, Wa, Tag> {
SpanBuilder::new(self, dir) SpanBuilder::new(self, dir)
} }
fn stack(self) -> StackBuilder<LEN, Wa, Tag> { fn stack(self) -> StackBuilder<State, LEN, Wa, Tag> {
StackBuilder::new(self) StackBuilder::new(self)
} }
} }