remove state generic from a lot of things

This commit is contained in:
2025-12-17 21:37:55 -05:00
parent 7e6369029f
commit 30bc55c78e
45 changed files with 740 additions and 856 deletions

View File

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

View File

@@ -8,13 +8,13 @@ pub struct EventCtx<'a, State, Data> {
} }
pub struct EventIdCtx<'a, State, Data, W: ?Sized> { pub struct EventIdCtx<'a, State, Data, W: ?Sized> {
pub widget: WidgetRef<State, W>, pub widget: WidgetRef<W>,
pub state: &'a mut State, pub state: &'a mut State,
pub data: &'a mut Data, pub data: &'a mut Data,
} }
impl<State: HasUi, Data, W: ?Sized> Deref for EventIdCtx<'_, State, Data, W> { impl<State: HasUi, Data, W: ?Sized> Deref for EventIdCtx<'_, State, Data, W> {
type Target = Ui<State>; type Target = Ui;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
self.state.ui_ref() self.state.ui_ref()
@@ -27,7 +27,7 @@ impl<State: HasUi, Data, W: ?Sized> DerefMut for EventIdCtx<'_, State, Data, W>
} }
} }
impl<'a, State: HasUi + 'static, Data, W: Widget<State>> EventIdCtx<'a, State, Data, W> { impl<'a, State: HasUi + 'static, Data, W: Widget> EventIdCtx<'a, State, Data, W> {
pub fn widget(&mut self) -> &mut W { pub fn widget(&mut self) -> &mut W {
&mut self.state.ui()[self.widget] &mut self.state.ui()[self.widget]
} }

View File

@@ -1,5 +1,6 @@
use crate::{ use crate::{
ActiveData, Event, EventCtx, EventFn, EventLike, HasUi, IdLike, LayerId, WidgetData, WidgetId, ActiveData, Event, EventCtx, EventFn, EventLike, HasRsc, HasUi, IdLike, LayerId, WidgetData,
WidgetId,
util::{HashMap, TypeMap}, util::{HashMap, TypeMap},
}; };
use std::{any::TypeId, rc::Rc}; use std::{any::TypeId, rc::Rc};
@@ -21,7 +22,7 @@ impl<State: 'static> EventManager<State> {
self.types.type_or_default() self.types.type_or_default()
} }
pub fn register<I: IdLike<State>, E: EventLike>( pub fn register<I: IdLike, E: EventLike>(
&mut self, &mut self,
id: I, id: I,
event: E, event: E,
@@ -33,20 +34,28 @@ impl<State: 'static> EventManager<State> {
pub fn type_key<E: EventLike>() -> TypeId { pub fn type_key<E: EventLike>() -> TypeId {
TypeId::of::<TypeEventManager<State, E::Event>>() TypeId::of::<TypeEventManager<State, E::Event>>()
} }
}
pub fn remove(&mut self, id: WidgetId) { pub trait EventsLike {
fn remove(&mut self, id: WidgetId);
fn draw(&mut self, data: &WidgetData, active: &ActiveData);
fn undraw(&mut self, data: &WidgetData, active: &ActiveData);
}
impl<State: 'static> EventsLike for EventManager<State> {
fn remove(&mut self, id: WidgetId) {
for m in self.types.values_mut() { for m in self.types.values_mut() {
m.remove(id); m.remove(id);
} }
} }
pub fn draw(&mut self, data: &WidgetData<State>, active: &ActiveData) { fn draw(&mut self, data: &WidgetData, 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<State>, active: &ActiveData) { fn undraw(&mut self, data: &WidgetData, 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);
} }
@@ -99,7 +108,7 @@ impl<State, E: Event> Default for TypeEventManager<State, E> {
impl<State: 'static, E: Event> TypeEventManager<State, E> { impl<State: 'static, E: Event> TypeEventManager<State, E> {
fn register( fn register(
&mut self, &mut self,
id: impl IdLike<State>, id: impl IdLike,
event: impl EventLike<Event = E>, event: impl EventLike<Event = E>,
f: impl for<'a> EventFn<State, E::Data<'a>>, f: impl for<'a> EventFn<State, E::Data<'a>>,
) { ) {
@@ -112,7 +121,7 @@ impl<State: 'static, E: Event> TypeEventManager<State, E> {
pub fn run_fn<'a>( pub fn run_fn<'a>(
&mut self, &mut self,
id: impl IdLike<State>, id: impl IdLike,
) -> impl for<'b> FnOnce(EventCtx<State, 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| {
@@ -128,21 +137,26 @@ impl<State: 'static, E: Event> TypeEventManager<State, E> {
} }
} }
pub trait HasEvents: Sized + HasUi { pub trait HasEvents: Sized {
fn run_event<E: EventLike>( type State: HasRsc<Rsc = Self>;
&mut self,
id: impl IdLike<Self>,
data: &mut <E::Event as Event>::Data<'_>,
);
}
impl<State: HasUi + 'static> HasEvents for State { fn events(&mut self) -> &mut EventManager<Self::State>;
fn run_event<E: EventLike>(
fn register_event<I: IdLike, E: EventLike>(
&mut self, &mut self,
id: impl IdLike<Self>, id: I,
data: &mut <E::Event as Event>::Data<'_>, event: E,
) { f: impl for<'a> EventFn<Self::State, <E::Event as Event>::Data<'a>>,
let f = self.ui().events.get_type::<E>().run_fn(id); ) where
f(EventCtx { state: self, data }) Self: HasUi,
{
let id = id.id();
self.events().register(id, event, f);
self.ui()
.widgets
.data_mut(id)
.unwrap()
.event_mgrs
.insert(EventManager::<Self::State>::type_key::<E>());
} }
} }

View File

@@ -1,8 +1,10 @@
mod ctx; mod ctx;
mod manager; mod manager;
mod rsc;
pub use ctx::*; pub use ctx::*;
pub use manager::*; pub use manager::*;
pub use rsc::*;
pub trait Event: Sized + 'static + Clone { pub trait Event: Sized + 'static + Clone {
type Data<'a> = (); type Data<'a> = ();

29
core/src/event/rsc.rs Normal file
View File

@@ -0,0 +1,29 @@
use crate::{Event, EventCtx, EventLike, EventManager, HasEvents, HasUi, IdLike};
pub trait HasRsc: Sized + 'static {
type Rsc: HasEvents<State = Self> + HasUi;
fn rsc(&self) -> &Self::Rsc;
fn rsc_mut(&mut self) -> &mut Self::Rsc;
fn run_event<E: EventLike>(&mut self, id: impl IdLike, data: &mut <E::Event as Event>::Data<'_>)
where
Self: 'static,
{
let f = self.rsc_mut().events().get_type::<E>().run_fn(id);
f(EventCtx { state: self, data })
}
fn events(&mut self) -> &mut EventManager<Self> {
self.rsc_mut().events()
}
}
impl<R: HasRsc> HasUi for R {
fn ui_ref(&self) -> &crate::Ui {
self.rsc().ui_ref()
}
fn ui(&mut self) -> &mut crate::Ui {
self.rsc_mut().ui()
}
}

View File

@@ -18,7 +18,6 @@ mod num;
mod orientation; mod orientation;
mod primitive; mod primitive;
mod render; mod render;
mod typed;
mod ui; mod ui;
mod widget; mod widget;

View File

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

View File

@@ -1,9 +0,0 @@
#[macro_export]
macro_rules! core_state {
($vis: vis $state: ty) => {
$vis type WidgetHandle<W = dyn Widget<$state>> = $crate::WidgetHandle<$state, W>;
$vis type WidgetHandles<W = dyn Widget<$state>> = $crate::WidgetHandles<$state, W>;
$vis type WidgetRef<W = dyn Widget<$state>> = $crate::WidgetRef<$state, W>;
$vis type Ui = $crate::Ui<$state>;
};
}

View File

@@ -1,20 +1,22 @@
use crate::{ use crate::{
ActiveData, Axis, Painter, SizeCtx, Ui, UiRegion, UiVec2, WidgetId, ActiveData, Axis, EventsLike, Painter, SizeCtx, Ui, UiRegion, UiVec2, WidgetId,
render::MaskIdx, render::MaskIdx,
util::{HashSet, forget_ref}, util::{HashSet, forget_ref},
}; };
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
/// state maintained between widgets during painting /// state maintained between widgets during painting
pub struct DrawState<'a, State> { pub struct DrawState<'a> {
pub(super) ui: &'a mut Ui<State>, pub(super) ui: &'a mut Ui,
pub(super) events: &'a mut dyn EventsLike,
draw_started: HashSet<WidgetId>, draw_started: HashSet<WidgetId>,
} }
impl<'a, State: 'static> DrawState<'a, State> { impl<'a> DrawState<'a> {
pub fn new(ui: &'a mut Ui<State>) -> Self { pub fn new(ui: &'a mut Ui, events: &'a mut dyn EventsLike) -> Self {
Self { Self {
ui, ui,
events,
draw_started: Default::default(), draw_started: Default::default(),
} }
} }
@@ -23,12 +25,10 @@ impl<'a, State: 'static> DrawState<'a, State> {
while let Some(&id) = self.widgets.needs_redraw.iter().next() { while let Some(&id) = self.widgets.needs_redraw.iter().next() {
self.redraw(id); self.redraw(id);
} }
self.free(); self.ui.free(self.events);
} }
/// 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,
/// will just return if so
pub fn redraw(&mut self, id: WidgetId) { pub fn redraw(&mut self, id: WidgetId) {
self.widgets.needs_redraw.remove(&id); self.widgets.needs_redraw.remove(&id);
self.draw_started.remove(&id); self.draw_started.remove(&id);
@@ -65,11 +65,7 @@ impl<'a, State: 'static> DrawState<'a, State> {
); );
} }
pub(super) fn size_ctx<'b>( pub(super) fn size_ctx<'b>(&'b mut self, source: WidgetId, outer: UiVec2) -> SizeCtx<'b> {
&'b mut self,
source: WidgetId,
outer: UiVec2,
) -> SizeCtx<'b, State> {
SizeCtx { SizeCtx {
source, source,
cache: &mut self.ui.cache, cache: &mut self.ui.cache,
@@ -86,10 +82,10 @@ impl<'a, State: 'static> DrawState<'a, State> {
// free all resources & cache // free all resources & cache
for (id, active) in self.ui.active.drain() { for (id, active) in self.ui.active.drain() {
let data = self.ui.widgets.data(id).unwrap(); let data = self.ui.widgets.data(id).unwrap();
self.ui.events.undraw(data, &active); self.events.undraw(data, &active);
} }
self.ui.cache.clear(); self.ui.cache.clear();
self.free(); self.ui.free(self.events);
self.layers.clear(); self.layers.clear();
self.widgets.needs_redraw.clear(); self.widgets.needs_redraw.clear();
@@ -107,26 +103,11 @@ impl<'a, State: 'static> DrawState<'a, State> {
mask: MaskIdx, mask: MaskIdx,
old_children: Option<Vec<WidgetId>>, old_children: Option<Vec<WidgetId>>,
) { ) {
// I have no idea if these checks work lol
// the idea is u can't redraw stuff u already drew,
// and if parent is different then there's another copy with a different parent
// but this has a very weird issue where you can't move widgets unless u remove first
// so swapping is impossible rn I think?
// there's definitely better solutions like a counter (>1 = panic) but don't care rn
// if self.draw_started.contains(&id) {
// panic!(
// "Cannot draw the same widget ({}) twice (1)",
// self.widgets.data(&id).unwrap().label
// );
// }
let mut old_children = old_children.unwrap_or_default(); let mut old_children = old_children.unwrap_or_default();
if let Some(active) = self.ui.active.get_mut(&id) if let Some(active) = self.ui.active.get_mut(&id)
&& !self.ui.widgets.needs_redraw.contains(&id) && !self.ui.widgets.needs_redraw.contains(&id)
{ {
// check to see if we can skip drawing first // check to see if we can skip drawing first
if active.parent != parent {
panic!("Cannot draw the same widget twice (2)");
}
if active.region == region { if active.region == region {
return; return;
} else if active.region.size() == region.size() { } else if active.region.size() == region.size() {
@@ -190,7 +171,7 @@ impl<'a, State: 'static> DrawState<'a, State> {
// update modules // update modules
let data = self.ui.widgets.data(id).unwrap(); let data = self.ui.widgets.data(id).unwrap();
self.ui.events.draw(data, &active); self.events.draw(data, &active);
self.active.insert(id, active); self.active.insert(id, active);
} }
@@ -222,7 +203,7 @@ impl<'a, State: 'static> DrawState<'a, State> {
self.textures.free(); self.textures.free();
if undraw { if undraw {
let data = self.ui.widgets.data(id).unwrap(); let data = self.ui.widgets.data(id).unwrap();
self.ui.events.undraw(data, active); self.events.undraw(data, active);
} }
} }
active active
@@ -240,14 +221,14 @@ impl<'a, State: 'static> DrawState<'a, State> {
} }
} }
impl<State> Deref for DrawState<'_, State> { impl Deref for DrawState<'_> {
type Target = Ui<State>; type Target = Ui;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
self.ui self.ui
} }
} }
impl<State> DerefMut for DrawState<'_, State> { impl DerefMut for DrawState<'_> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
self.ui self.ui
} }

View File

@@ -1,6 +1,6 @@
use crate::{ use crate::{
Event, EventFn, EventLike, EventManager, IdLike, Mask, PixelRegion, PrimitiveLayers, TextData, EventsLike, IdLike, Mask, PixelRegion, PrimitiveLayers, TextData, TextureHandle, Textures,
TextureHandle, Textures, Widget, WidgetHandle, WidgetId, WidgetLike, Widgets, Widget, WidgetHandle, WidgetId, Widgets,
ui::draw_state::DrawState, ui::draw_state::DrawState,
util::{HashMap, TrackedArena, Vec2}, util::{HashMap, TrackedArena, Vec2},
}; };
@@ -22,10 +22,9 @@ use cache::*;
pub use painter::Painter; pub use painter::Painter;
pub use size::*; pub use size::*;
pub struct Ui<State> { pub struct Ui {
// TODO: edit visibilities // TODO: edit visibilities
pub widgets: Widgets<State>, pub widgets: Widgets,
pub events: EventManager<State>,
// retained painter state // retained painter state
pub active: HashMap<WidgetId, ActiveData>, pub active: HashMap<WidgetId, ActiveData>,
@@ -36,56 +35,44 @@ pub struct Ui<State> {
pub masks: TrackedArena<Mask, u32>, pub masks: TrackedArena<Mask, u32>,
pub cache: Cache, pub cache: Cache,
root: Option<WidgetHandle<State>>, pub root: Option<WidgetHandle>,
old_root: Option<WidgetId>,
recv: Receiver<WidgetId>, recv: Receiver<WidgetId>,
send: Sender<WidgetId>, send: Sender<WidgetId>,
full_redraw: bool,
resized: bool, resized: bool,
} }
pub trait HasUi: Sized { pub trait HasUi: Sized + 'static {
fn ui_ref(&self) -> &Ui<Self>; fn ui_ref(&self) -> &Ui;
fn ui(&mut self) -> &mut Ui<Self>; fn ui(&mut self) -> &mut Ui;
}
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)
} }
impl Ui {
/// useful for debugging /// useful for debugging
pub fn set_label(&mut self, id: impl IdLike<State>, label: String) { pub fn set_label(&mut self, id: impl IdLike, label: String) {
self.widgets.data_mut(id.id()).unwrap().label = label; self.widgets.data_mut(id.id()).unwrap().label = label;
} }
pub fn label(&self, id: impl IdLike<State>) -> &String { pub fn label(&self, id: impl IdLike) -> &String {
&self.widgets.data(id.id()).unwrap().label &self.widgets.data(id.id()).unwrap().label
} }
pub fn add_widget<W: Widget<State>>(&mut self, w: W) -> WidgetHandle<State, W> { pub fn add_widget<W: Widget>(&mut self, w: W) -> WidgetHandle<W> {
WidgetHandle::new(self.widgets.add(w), self.send.clone()) WidgetHandle::new(self.widgets.add(w), self.send.clone())
} }
pub fn set_root<Tag>(&mut self, w: impl WidgetLike<State, Tag>) {
self.root = Some(w.add(self));
self.full_redraw = true;
}
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
} }
pub fn get<I: IdLike<State>>(&self, id: &I) -> Option<&I::Widget> pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
self.widgets.get(id) self.widgets.get(id)
} }
pub fn get_mut<I: IdLike<State>>(&mut self, id: &I) -> Option<&mut I::Widget> pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget>
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -96,49 +83,39 @@ impl<State: 'static> Ui<State> {
self.textures.add(image) self.textures.add(image)
} }
pub fn register_event<E: EventLike>(
&mut self,
id: impl IdLike<State>,
event: E,
f: impl for<'a> EventFn<State, <E::Event as Event>::Data<'a>>,
) {
self.events.register(id.id(), event, f);
self.widgets
.data_mut(id)
.unwrap()
.event_mgrs
.insert(EventManager::<State>::type_key::<E>());
}
pub fn resize(&mut self, size: impl Into<Vec2>) { pub fn resize(&mut self, size: impl Into<Vec2>) {
self.output_size = size.into(); self.output_size = size.into();
self.resized = true; self.resized = true;
} }
pub fn update(&mut self) { pub fn update(&mut self, events: &mut dyn EventsLike) {
if self.full_redraw { if self.root_changed() {
DrawState::new(self).redraw_all(); DrawState::new(self, events).redraw_all();
self.full_redraw = false; self.old_root = self.root.as_ref().map(|r| r.id());
} else if self.widgets.has_updates() { } else if self.widgets.has_updates() {
DrawState::new(self).redraw_updates(); DrawState::new(self, events).redraw_updates();
} }
if self.resized { if self.resized {
self.resized = false; self.resized = false;
DrawState::new(self).redraw_all(); DrawState::new(self, events).redraw_all();
} }
} }
/// free any resources that don't have references anymore /// free any resources that don't have references anymore
fn free(&mut self) { fn free(&mut self, events: &mut dyn EventsLike) {
for id in self.recv.try_iter() { for id in self.recv.try_iter() {
self.events.remove(id); events.remove(id);
self.widgets.delete(id); self.widgets.delete(id);
} }
self.textures.free(); self.textures.free();
} }
pub fn root_changed(&self) -> bool {
self.root.as_ref().map(|r| r.id()) != self.old_root
}
pub fn needs_redraw(&self) -> bool { pub fn needs_redraw(&self) -> bool {
self.full_redraw || self.widgets.has_updates() self.root_changed() || self.widgets.has_updates()
} }
pub fn num_widgets(&self) -> usize { pub fn num_widgets(&self) -> usize {
@@ -161,7 +138,7 @@ impl<State: 'static> Ui<State> {
} }
} }
pub fn window_region(&self, id: &impl IdLike<State>) -> Option<PixelRegion> { pub fn window_region(&self, id: &impl IdLike) -> Option<PixelRegion> {
let region = self.active.get(&id.id())?.region; let region = self.active.get(&id.id())?.region;
Some(region.to_px(self.output_size)) Some(region.to_px(self.output_size))
} }
@@ -174,7 +151,7 @@ impl<State: 'static> Ui<State> {
} }
} }
impl<State: 'static, I: IdLike<State>> Index<I> for Ui<State> impl<I: IdLike> Index<I> for Ui
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -185,7 +162,7 @@ where
} }
} }
impl<State: 'static, I: IdLike<State>> IndexMut<I> for Ui<State> impl<I: IdLike> IndexMut<I> for Ui
where where
I::Widget: Sized, I::Widget: Sized,
{ {
@@ -194,12 +171,11 @@ where
} }
} }
impl<State: 'static> Default for Ui<State> { impl Default for Ui {
fn default() -> Self { fn default() -> Self {
let (send, recv) = channel(); let (send, recv) = channel();
Self { Self {
widgets: Default::default(), widgets: Default::default(),
events: Default::default(),
active: Default::default(), active: Default::default(),
layers: Default::default(), layers: Default::default(),
masks: Default::default(), masks: Default::default(),
@@ -207,8 +183,8 @@ impl<State: 'static> Default for Ui<State> {
textures: Default::default(), textures: Default::default(),
cache: Default::default(), cache: Default::default(),
output_size: Vec2::ZERO, output_size: Vec2::ZERO,
root: Default::default(), root: None,
full_redraw: false, old_root: None,
send, send,
recv, recv,
resized: false, resized: false,

View File

@@ -7,8 +7,8 @@ use crate::{
}; };
/// makes your surfaces look pretty /// makes your surfaces look pretty
pub struct Painter<'a, 'b, State> { pub struct Painter<'a, 'b> {
pub(super) state: &'a mut DrawState<'b, State>, pub(super) state: &'a mut DrawState<'b>,
pub(super) region: UiRegion, pub(super) region: UiRegion,
pub(super) mask: MaskIdx, pub(super) mask: MaskIdx,
@@ -19,7 +19,7 @@ pub struct Painter<'a, 'b, State> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
} }
impl<'a, 'c, State: 'static> Painter<'a, 'c, State> { impl<'a, 'c> Painter<'a, 'c> {
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.state.layers.write( let h = self.state.layers.write(
self.layer, self.layer,
@@ -52,17 +52,17 @@ impl<'a, 'c, State: 'static> Painter<'a, 'c, State> {
} }
/// 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<State, W>) { pub fn widget<W: ?Sized>(&mut self, id: &WidgetHandle<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<State, W>, region: UiRegion) { pub fn widget_within<W: ?Sized>(&mut self, id: &WidgetHandle<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<State, W>, region: UiRegion) { fn widget_at<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
self.children.push(id.id()); self.children.push(id.id());
self.state self.state
.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);
@@ -95,15 +95,11 @@ impl<'a, 'c, State: 'static> Painter<'a, 'c, State> {
self.region self.region
} }
pub fn size<W: ?Sized + Widget<State>>(&mut self, id: &WidgetHandle<State, W>) -> Size { pub fn size<W: ?Sized + Widget>(&mut self, id: &WidgetHandle<W>) -> Size {
self.size_ctx().size(id) self.size_ctx().size(id)
} }
pub fn len_axis<W: ?Sized + Widget<State>>( pub fn len_axis<W: ?Sized + Widget>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
&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),
@@ -138,7 +134,7 @@ impl<'a, 'c, State: 'static> Painter<'a, 'c, State> {
&self.id &self.id
} }
pub fn size_ctx(&mut self) -> SizeCtx<'_, State> { pub fn size_ctx(&mut self) -> SizeCtx<'_> {
self.state.size_ctx(self.id, self.region.size()) self.state.size_ctx(self.id, self.region.size())
} }
} }

View File

@@ -3,11 +3,11 @@ use crate::{
UiVec2, WidgetAxisFns, WidgetId, Widgets, XAxis, YAxis, ui::cache::Cache, util::Vec2, UiVec2, WidgetAxisFns, WidgetId, Widgets, XAxis, YAxis, ui::cache::Cache, util::Vec2,
}; };
pub struct SizeCtx<'a, State> { pub struct SizeCtx<'a> {
pub text: &'a mut TextData, pub text: &'a mut TextData,
pub textures: &'a mut Textures, pub textures: &'a mut Textures,
pub(super) source: WidgetId, pub(super) source: WidgetId,
pub(super) widgets: &'a Widgets<State>, pub(super) widgets: &'a Widgets,
pub(super) cache: &'a mut Cache, pub(super) cache: &'a mut Cache,
/// TODO: should this be pub? rn used for sized /// TODO: should this be pub? rn used for sized
pub outer: UiVec2, pub outer: UiVec2,
@@ -15,7 +15,7 @@ pub struct SizeCtx<'a, State> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
} }
impl<State: 'static> SizeCtx<'_, State> { impl SizeCtx<'_> {
pub fn id(&self) -> &WidgetId { pub fn id(&self) -> &WidgetId {
&self.id &self.id
} }
@@ -45,22 +45,22 @@ impl<State: 'static> SizeCtx<'_, State> {
len len
} }
pub fn width(&mut self, id: impl IdLike<State>) -> Len { pub fn width(&mut self, id: impl IdLike) -> Len {
self.len_inner::<XAxis>(id.id()) self.len_inner::<XAxis>(id.id())
} }
pub fn height(&mut self, id: impl IdLike<State>) -> Len { pub fn height(&mut self, id: impl IdLike) -> Len {
self.len_inner::<YAxis>(id.id()) self.len_inner::<YAxis>(id.id())
} }
pub fn len_axis(&mut self, id: impl IdLike<State>, axis: Axis) -> Len { pub fn len_axis(&mut self, id: impl IdLike, 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(&mut self, id: impl IdLike<State>) -> Size { pub fn size(&mut self, id: impl IdLike) -> Size {
let id = id.id(); let id = id.id();
Size { Size {
x: self.width(id), x: self.width(id),

View File

@@ -2,16 +2,16 @@ use std::any::TypeId;
use crate::{Widget, util::HashSet}; use crate::{Widget, util::HashSet};
pub struct WidgetData<State> { pub struct WidgetData {
pub widget: Box<dyn Widget<State>>, pub widget: Box<dyn Widget>,
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<State> WidgetData<State> { impl WidgetData {
pub fn new<W: Widget<State>>(widget: W) -> Self { pub fn new<W: Widget>(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,12 +1,7 @@
use std::{ use std::{marker::Unsize, mem::MaybeUninit, ops::CoerceUnsized, sync::mpsc::Sender};
marker::{PhantomData, Unsize},
mem::MaybeUninit,
ops::CoerceUnsized,
sync::mpsc::Sender,
};
use crate::{ use crate::{
Ui, Widget, Widget,
util::{RefCounter, SlotId}, util::{RefCounter, SlotId},
}; };
@@ -17,42 +12,39 @@ 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<State, W: ?Sized = dyn Widget<State>> { pub struct WidgetHandle<W: ?Sized = dyn Widget> {
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<State, W: ?Sized = dyn Widget<State>> { pub struct WidgetRef<W: ?Sized = dyn Widget> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
#[allow(unused)] #[allow(unused)]
ty: *const W, ty: *const W,
state: PhantomData<State>,
} }
pub struct WidgetHandles<State, W: ?Sized = dyn Widget<State>> { pub struct WidgetHandles<W: ?Sized = dyn Widget> {
pub h: WidgetHandle<State, W>, pub h: WidgetHandle<W>,
pub r: WidgetRef<State, W>, pub r: WidgetRef<W>,
} }
impl<State, W: Widget<State> + ?Sized + Unsize<dyn Widget<State>>> WidgetHandle<State, W> { impl<W: Widget + ?Sized + Unsize<dyn Widget>> WidgetHandle<W> {
pub fn any(self) -> WidgetHandle<State, dyn Widget<State>> { pub fn any(self) -> WidgetHandle<dyn Widget> {
self self
} }
} }
impl<State, W: ?Sized> WidgetHandle<State, W> { impl<W: ?Sized> WidgetHandle<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,
} }
} }
@@ -64,28 +56,24 @@ impl<State, W: ?Sized> WidgetHandle<State, W> {
self.counter.refs() self.counter.refs()
} }
pub fn weak(&self) -> WidgetRef<State, W> { pub fn weak(&self) -> WidgetRef<W> {
let Self { ty, id, .. } = *self; let Self { ty, id, .. } = *self;
WidgetRef { WidgetRef { ty, id }
ty,
id,
state: PhantomData,
}
} }
pub fn handles(self) -> WidgetHandles<State, W> { pub fn handles(self) -> WidgetHandles<W> {
let r = self.weak(); let r = self.weak();
WidgetHandles { h: self, r } WidgetHandles { h: self, r }
} }
} }
impl<State, W: ?Sized> WidgetRef<State, W> { impl<W: ?Sized> WidgetRef<W> {
pub fn id(&self) -> WidgetId { pub fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<State, W: ?Sized> Drop for WidgetHandle<State, W> { impl<W: ?Sized> Drop for WidgetHandle<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);
@@ -93,64 +81,52 @@ impl<State, W: ?Sized> Drop for WidgetHandle<State, W> {
} }
} }
pub trait WidgetIdFn<State, W: ?Sized = dyn Widget<State>>: pub trait WidgetIdFn<State, W: ?Sized = dyn Widget>: FnOnce(&mut State) -> WidgetHandle<W> {}
FnOnce(&mut Ui<State>) -> WidgetHandle<State, W> impl<State, W: ?Sized, F: FnOnce(&mut State) -> WidgetHandle<W>> WidgetIdFn<State, W> for F {}
{
}
impl<State, W: ?Sized, F: FnOnce(&mut Ui<State>) -> WidgetHandle<State, W>> WidgetIdFn<State, W>
for F
{
}
pub trait IdLike<State> { pub trait IdLike {
type Widget: Widget<State> + ?Sized + 'static; type Widget: Widget + ?Sized + 'static;
fn id(&self) -> WidgetId; fn id(&self) -> WidgetId;
} }
impl<State, W: Widget<State> + ?Sized> IdLike<State> for &WidgetHandle<State, W> { impl<W: Widget + ?Sized> IdLike for &WidgetHandle<W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<State, W: Widget<State> + ?Sized> IdLike<State> for WidgetHandle<State, W> { impl<W: Widget + ?Sized> IdLike for WidgetHandle<W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<State, W: Widget<State> + ?Sized> IdLike<State> for WidgetRef<State, W> { impl<W: Widget + ?Sized> IdLike for WidgetRef<W> {
type Widget = W; type Widget = W;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
self.id self.id
} }
} }
impl<State: 'static> IdLike<State> for WidgetId { impl IdLike for WidgetId {
type Widget = dyn Widget<State>; type Widget = dyn Widget;
fn id(&self) -> WidgetId { fn id(&self) -> WidgetId {
*self *self
} }
} }
impl<T: ?Sized + Unsize<U>, U: ?Sized, State> CoerceUnsized<WidgetHandle<State, U>> impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {}
for WidgetHandle<State, T> impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<U>> for WidgetRef<T> {}
{
}
impl<State, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<State, U>>
for WidgetRef<State, T>
{
}
impl<State, W: ?Sized> Clone for WidgetRef<State, W> { impl<W: ?Sized> Clone for WidgetRef<W> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
*self *self
} }
} }
impl<State, W: ?Sized> Copy for WidgetRef<State, W> {} impl<W: ?Sized> Copy for WidgetRef<W> {}
impl<State, W: ?Sized> PartialEq for WidgetRef<State, W> { impl<W: ?Sized> PartialEq for WidgetRef<W> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.id == other.id self.id == other.id
} }

View File

@@ -1,36 +1,38 @@
use crate::HasUi;
use super::*; use super::*;
use std::marker::Unsize; use std::marker::Unsize;
pub trait WidgetLike<State: 'static, Tag>: Sized { pub trait WidgetLike<State: 'static + HasUi, Tag>: Sized {
type Widget: Widget<State> + ?Sized + Unsize<dyn Widget<State>> + 'static; type Widget: Widget + ?Sized + Unsize<dyn Widget> + 'static;
fn add(self, ui: &mut Ui<State>) -> WidgetHandle<State, Self::Widget>; fn add(self, state: &mut State) -> WidgetHandle<Self::Widget>;
fn with_id<W2>( fn with_id<W2>(
self, self,
f: impl FnOnce(&mut Ui<State>, WidgetHandle<State, Self::Widget>) -> WidgetHandle<State, W2>, f: impl FnOnce(&mut State, WidgetHandle<Self::Widget>) -> WidgetHandle<W2>,
) -> impl WidgetIdFn<State, W2> { ) -> impl WidgetIdFn<State, W2> {
move |ui| { move |state| {
let id = self.add(ui); let id = self.add(state);
f(ui, id) f(state, id)
} }
} }
fn set_root(self, ui: &mut Ui<State>) { fn set_root(self, state: &mut State) {
ui.set_root(self); state.ui().root = Some(self.add(state));
} }
fn handles(self, ui: &mut Ui<State>) -> WidgetHandles<State, Self::Widget> { fn handles(self, state: &mut State) -> WidgetHandles<Self::Widget> {
self.add(ui).handles() self.add(state).handles()
} }
} }
pub trait WidgetArrLike<State, const LEN: usize, Tag> { pub trait WidgetArrLike<State, const LEN: usize, Tag> {
fn ui(self, ui: &mut Ui<State>) -> WidgetArr<State, LEN>; fn add(self, state: &mut State) -> WidgetArr<LEN>;
} }
impl<State, const LEN: usize> WidgetArrLike<State, LEN, ArrTag> for WidgetArr<State, LEN> { impl<State, const LEN: usize> WidgetArrLike<State, LEN, ArrTag> for WidgetArr<LEN> {
fn ui(self, _: &mut Ui<State>) -> WidgetArr<State, LEN> { fn add(self, _: &mut State) -> WidgetArr<LEN> {
self self
} }
} }
@@ -41,12 +43,12 @@ macro_rules! impl_widget_arr {
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<State: 'static, $($W: WidgetLike<State, $Tag>,$Tag,)*> WidgetArrLike<State, $n, ($($Tag,)*)> for ($($W,)*) { impl<State: 'static + HasUi, $($W: WidgetLike<State, $Tag>,$Tag,)*> WidgetArrLike<State, $n, ($($Tag,)*)> for ($($W,)*) {
fn ui(self, ui: &mut Ui<State>) -> WidgetArr<State, $n> { fn add(self, state: &mut State) -> WidgetArr<$n> {
#[allow(non_snake_case)] #[allow(non_snake_case)]
let ($($W,)*) = self; let ($($W,)*) = self;
WidgetArr::new( WidgetArr::new(
[$($W.add(ui),)*], [$($W.add(state),)*],
) )
} }
} }

View File

@@ -1,4 +1,4 @@
use crate::{Axis, AxisT, Len, Painter, SizeCtx, Ui}; use crate::{Axis, AxisT, Len, Painter, SizeCtx};
use std::any::Any; use std::any::Any;
mod data; mod data;
@@ -13,18 +13,18 @@ pub use like::*;
pub use tag::*; pub use tag::*;
pub use widgets::*; pub use widgets::*;
pub trait Widget<State>: Any { pub trait Widget: Any {
fn draw(&mut self, painter: &mut Painter<State>); fn draw(&mut self, painter: &mut Painter);
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len; fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len;
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len; fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len;
} }
pub trait WidgetAxisFns<State> { pub trait WidgetAxisFns {
fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx<State>) -> Len; fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx) -> Len;
} }
impl<State, W: Widget<State> + ?Sized> WidgetAxisFns<State> for W { impl<W: Widget + ?Sized> WidgetAxisFns for W {
fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx) -> Len {
match A::get() { match A::get() {
Axis::X => self.desired_width(ctx), Axis::X => self.desired_width(ctx),
Axis::Y => self.desired_height(ctx), Axis::Y => self.desired_height(ctx),
@@ -32,17 +32,17 @@ impl<State, W: Widget<State> + ?Sized> WidgetAxisFns<State> for W {
} }
} }
impl<State> Widget<State> for () { impl Widget for () {
fn draw(&mut self, _: &mut Painter<State>) {} fn draw(&mut self, _: &mut Painter) {}
fn desired_width(&mut self, _: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, _: &mut SizeCtx) -> Len {
Len::ZERO Len::ZERO
} }
fn desired_height(&mut self, _: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, _: &mut SizeCtx) -> Len {
Len::ZERO Len::ZERO
} }
} }
impl<State> dyn Widget<State> { impl dyn Widget {
pub fn as_any(&self) -> &dyn Any { pub fn as_any(&self) -> &dyn Any {
self self
} }
@@ -55,31 +55,31 @@ impl<State> dyn Widget<State> {
/// 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<State, W: Widget<State> + ?Sized>: FnOnce(&mut Ui<State>) -> W {} pub trait WidgetFn<State, W: Widget + ?Sized>: FnOnce(&mut State) -> W {}
impl<State, W: Widget<State> + ?Sized, F: FnOnce(&mut Ui<State>) -> W> WidgetFn<State, W> for F {} impl<State, W: Widget + ?Sized, F: FnOnce(&mut State) -> W> WidgetFn<State, W> for F {}
pub struct WidgetArr<State, const LEN: usize> { pub struct WidgetArr<const LEN: usize> {
pub arr: [WidgetHandle<State>; LEN], pub arr: [WidgetHandle; LEN],
} }
impl<State, const LEN: usize> WidgetArr<State, LEN> { impl<const LEN: usize> WidgetArr<LEN> {
pub fn new(arr: [WidgetHandle<State>; LEN]) -> Self { pub fn new(arr: [WidgetHandle; LEN]) -> Self {
Self { arr } Self { arr }
} }
} }
pub trait WidgetOption<State> { pub trait WidgetOption<State> {
fn get(self, ui: &mut Ui<State>) -> Option<WidgetHandle<State>>; fn get(self, state: &mut State) -> Option<WidgetHandle>;
} }
impl<State> WidgetOption<State> for () { impl<State> WidgetOption<State> for () {
fn get(self, _: &mut Ui<State>) -> Option<WidgetHandle<State>> { fn get(self, _: &mut State) -> Option<WidgetHandle> {
None None
} }
} }
impl<State, F: FnOnce(&mut Ui<State>) -> Option<WidgetHandle<State>>> WidgetOption<State> for F { impl<State, F: FnOnce(&mut State) -> Option<WidgetHandle>> WidgetOption<State> for F {
fn get(self, ui: &mut Ui<State>) -> Option<WidgetHandle<State>> { fn get(self, state: &mut State) -> Option<WidgetHandle> {
self(ui) self(state)
} }
} }

View File

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

View File

@@ -3,12 +3,12 @@ use crate::{
util::{DynBorrower, HashSet, SlotVec, forget_mut, to_mut}, util::{DynBorrower, HashSet, SlotVec, forget_mut, to_mut},
}; };
pub struct Widgets<State> { pub struct Widgets {
pub needs_redraw: HashSet<WidgetId>, pub needs_redraw: HashSet<WidgetId>,
vec: SlotVec<WidgetData<State>>, vec: SlotVec<WidgetData>,
} }
impl<State> Default for Widgets<State> { impl Default for Widgets {
fn default() -> Self { fn default() -> Self {
Self { Self {
needs_redraw: Default::default(), needs_redraw: Default::default(),
@@ -17,23 +17,23 @@ impl<State> Default for Widgets<State> {
} }
} }
impl<State: 'static> Widgets<State> { impl Widgets {
pub fn has_updates(&self) -> bool { pub fn has_updates(&self) -> bool {
!self.needs_redraw.is_empty() !self.needs_redraw.is_empty()
} }
pub fn get_dyn(&self, id: WidgetId) -> Option<&dyn Widget<State>> { pub fn get_dyn(&self, id: WidgetId) -> Option<&dyn Widget> {
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<State>> { pub fn get_dyn_mut(&mut self, id: WidgetId) -> Option<&mut dyn Widget> {
self.needs_redraw.insert(id); self.needs_redraw.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<'a>(&self, id: WidgetId) -> WidgetWrapper<'a, State> { pub(crate) fn get_dyn_dynamic<'a>(&self, id: WidgetId) -> WidgetWrapper<'a> {
// 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
let data = unsafe { forget_mut(to_mut(self.vec.get(id).unwrap())) }; let data = unsafe { forget_mut(to_mut(self.vec.get(id).unwrap())) };
@@ -43,37 +43,37 @@ impl<State: 'static> Widgets<State> {
WidgetWrapper::new(data.widget.as_mut(), &mut data.borrowed) WidgetWrapper::new(data.widget.as_mut(), &mut data.borrowed)
} }
pub fn get<I: IdLike<State>>(&self, id: &I) -> Option<&I::Widget> pub fn get<I: IdLike>(&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<State>>(&mut self, id: &I) -> Option<&mut I::Widget> pub fn get_mut<I: IdLike>(&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<State>>(&mut self, widget: W) -> WidgetId { pub fn add<W: Widget>(&mut self, widget: W) -> WidgetId {
self.vec.add(WidgetData::new(widget)) self.vec.add(WidgetData::new(widget))
} }
pub fn data(&self, id: impl IdLike<State>) -> Option<&WidgetData<State>> { pub fn data(&self, id: impl IdLike) -> Option<&WidgetData> {
self.vec.get(id.id()) self.vec.get(id.id())
} }
pub fn label(&self, id: impl IdLike<State>) -> &String { pub fn label(&self, id: impl IdLike) -> &String {
&self.data(id.id()).unwrap().label &self.data(id.id()).unwrap().label
} }
pub fn data_mut(&mut self, id: impl IdLike<State>) -> Option<&mut WidgetData<State>> { pub fn data_mut(&mut self, id: impl IdLike) -> Option<&mut WidgetData> {
self.vec.get_mut(id.id()) self.vec.get_mut(id.id())
} }
pub fn delete(&mut self, id: impl IdLike<State>) { pub fn delete(&mut self, id: impl IdLike) {
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);
@@ -85,4 +85,4 @@ impl<State: 'static> Widgets<State> {
} }
} }
pub type WidgetWrapper<'a, State> = DynBorrower<'a, dyn Widget<State>>; pub type WidgetWrapper<'a> = DynBorrower<'a, dyn Widget>;

View File

@@ -2,12 +2,10 @@ extern crate proc_macro;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use syn::{ use syn::{
Attribute, Block, Error, GenericParam, Generics, Ident, ItemStruct, ItemTrait, Meta, Signature, Attribute, Block, Error, GenericParam, Generics, Ident, ItemTrait, Signature, Token,
Token, Visibility, 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 {
@@ -96,111 +94,3 @@ pub fn widget_trait(input: TokenStream) -> TokenStream {
} }
.into() .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 {
has_ui(&parse_macro_input!(input))
}
fn has_ui(input: &ItemStruct) -> TokenStream {
let name = &input.ident;
let Some(field) = input
.fields
.iter()
.find(|f| f.ty == parse_quote!(Ui<Self>) || f.ty == parse_quote!(Ui))
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) -> &iris::iris_core::Ui<Self> {
&self.#field
}
fn ui(&mut self) -> &mut iris::iris_core::Ui<Self> {
&mut self.#field
}
}
}
.into()
}
#[proc_macro_derive(DefaultUiState)]
pub fn derive_default_ui_state(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemStruct);
let mut output = has_ui(&input);
let name = input.ident;
let Some(field) = input
.fields
.iter()
.find(|f| f.ty == parse_quote!(UiState<Self>) || f.ty == parse_quote!(UiState))
else {
return Error::new(
name.span(),
"could not find a UiState<Self> field for HasUiState",
)
.into_compile_error()
.into();
};
let field = &field.ident;
output.extend::<TokenStream>(
quote! {
impl HasUiState for #name {
fn ui_state(&mut self) -> &mut iris::default::UiState<Self> {
&mut self.#field
}
}
}
.into(),
);
output
}

View File

@@ -2,28 +2,36 @@ use cosmic_text::Family;
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::WindowAttributes}; use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::WindowAttributes};
iris::state_prelude!(Client); iris::state_prelude!(DefaultUiRsc<Client>);
fn main() { fn main() {
App::<Client>::run(); App::<Client>::run();
} }
#[derive(DefaultUiState)]
pub struct Client { pub struct Client {
ui: Ui, rsc: DefaultUiRsc<Self>,
ui_state: UiState,
info: WidgetRef<Text>, info: WidgetRef<Text>,
} }
impl HasRsc for Client {
type Rsc = DefaultUiRsc<Self>;
fn rsc(&self) -> &Self::Rsc {
&self.rsc
}
fn rsc_mut(&mut self) -> &mut Self::Rsc {
&mut self.rsc
}
}
impl DefaultAppState for Client { impl DefaultAppState for Client {
fn new(event_loop: &ActiveEventLoop, _proxy: Proxy<Self::Event>) -> Self { fn new(event_loop: &ActiveEventLoop, _proxy: Proxy<Self::Event>) -> Self {
let mut ui = Ui::new();
let window = event_loop let window = event_loop
.create_window(WindowAttributes::default()) .create_window(WindowAttributes::default())
.unwrap(); .unwrap();
let mut rsc = DefaultUiRsc::new(window);
let info; 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),
@@ -46,7 +54,7 @@ impl DefaultAppState for Client {
.width(rest(3)), .width(rest(3)),
) )
.span(Dir::RIGHT) .span(Dir::RIGHT)
.handles(ui); .handles(&mut rsc);
let span_test = ( let span_test = (
rrect.color(Color::GREEN).width(100), rrect.color(Color::GREEN).width(100),
@@ -57,14 +65,16 @@ impl DefaultAppState for Client {
rrect.color(Color::RED).width(100), rrect.color(Color::RED).width(100),
) )
.span(Dir::LEFT) .span(Dir::LEFT)
.add(ui); .add(&mut rsc);
let span_add = Span::empty(Dir::RIGHT).handles(ui); let span_add = Span::empty(Dir::RIGHT).handles(&mut rsc);
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.add(image(include_bytes!("assets/sungals.png")).center()); let child = image(include_bytes!("assets/sungals.png"))
.center()
.add(&mut ctx.state.rsc);
ctx[span_add.r].children.push(child); ctx[span_add.r].children.push(child);
}) })
.sized((150, 150)) .sized((150, 150))
@@ -78,7 +88,7 @@ impl DefaultAppState for Client {
.sized((150, 150)) .sized((150, 150))
.align(Align::BOT_LEFT); .align(Align::BOT_LEFT);
let span_add_test = (span_add.h, add_button, del_button).stack().add(ui); let span_add_test = (span_add.h, add_button, del_button).stack().add(&mut rsc);
let btext = |content| wtext(content).size(30); let btext = |content| wtext(content).size(30);
@@ -101,9 +111,9 @@ impl DefaultAppState for Client {
wtext("pretty cool right?").size(50), wtext("pretty cool right?").size(50),
) )
.span(Dir::DOWN) .span(Dir::DOWN)
.add(ui); .add(&mut rsc);
let texts = Span::empty(Dir::DOWN).gap(10).handles(ui); let texts = Span::empty(Dir::DOWN).gap(10).handles(&mut rsc);
let msg_area = texts.h.scrollable().masked().background(rect(Color::SKY)); let msg_area = texts.h.scrollable().masked().background(rect(Color::SKY));
let add_text = wtext("add") let add_text = wtext("add")
.editable(EditMode::MultiLine) .editable(EditMode::MultiLine)
@@ -120,10 +130,10 @@ impl DefaultAppState for Client {
.attr::<Selectable>(()); .attr::<Selectable>(());
let msg_box = text let msg_box = text
.background(rect(Color::WHITE.darker(0.5))) .background(rect(Color::WHITE.darker(0.5)))
.add(&mut ctx); .add(&mut ctx.state.rsc);
ctx[texts.r].children.push(msg_box); ctx[texts.r].children.push(msg_box);
}) })
.handles(ui); .handles(&mut rsc);
let text_edit_scroll = ( let text_edit_scroll = (
msg_area.height(rest(1)), msg_area.height(rest(1)),
( (
@@ -145,9 +155,9 @@ impl DefaultAppState for Client {
.align(Align::BOT), .align(Align::BOT),
) )
.span(Dir::DOWN) .span(Dir::DOWN)
.add(ui); .add(&mut rsc);
let main = WidgetPtr::new().handles(ui); let main = WidgetPtr::new().handles(&mut rsc);
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, label| {
@@ -155,7 +165,7 @@ impl DefaultAppState for Client {
let i = vec.len(); let i = vec.len();
if vec.is_empty() { if vec.is_empty() {
vec.push(None); vec.push(None);
ui[main.r].set(to); rsc.ui[main.r].set(to);
} else { } else {
vec.push(Some(to)); vec.push(Some(to));
} }
@@ -194,33 +204,28 @@ impl DefaultAppState for Client {
) )
.span(Dir::RIGHT); .span(Dir::RIGHT);
info = wtext("").handles(ui); info = wtext("").handles(&mut rsc);
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(&mut rsc);
}
Self { Self { rsc, info: info.r }
ui,
ui_state: UiState::new(window),
info: info.r,
}
} }
fn window_event(&mut self, _: WindowEvent) { fn window_event(&mut self, _: WindowEvent) {
let new = format!( let new = format!(
"widgets: {}\nactive:{}\nviews: {}", "widgets: {}\nactive:{}\nviews: {}",
self.ui.num_widgets(), self.ui().num_widgets(),
self.ui.active_widgets(), self.ui().active_widgets(),
self.ui_state.renderer.ui.view_count() self.ui_state().renderer.ui.view_count()
); );
if new != *self.ui[self.info].content { if new != *self.rsc.ui[self.info].content {
*self.ui[self.info].content = new; *self.rsc.ui[self.info].content = new;
} }
if self.ui.needs_redraw() { if self.ui().needs_redraw() {
self.ui_state.window.request_redraw(); self.ui_state().window.request_redraw();
} }
} }
} }

View File

@@ -4,11 +4,11 @@ use winit::dpi::{LogicalPosition, LogicalSize};
pub struct Selector; pub struct Selector;
impl<State: HasUiState, W: Widget<State> + 'static> WidgetAttr<State, W> for Selector { impl<State: HasUiState + HasEvents, W: Widget + 'static> WidgetAttr<State, W> for Selector {
type Input = WidgetRef<State, TextEdit<State>>; type Input = WidgetRef<TextEdit>;
fn run(ui: &mut Ui<State>, container: WidgetRef<State, W>, id: Self::Input) { fn run(state: &mut State, container: WidgetRef<W>, id: Self::Input) {
ui.register_event(container, CursorSense::click_or_drag(), move |ctx| { state.register_event(container, CursorSense::click_or_drag(), move |ctx| {
let region = ctx.state.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.state.ui().window_region(&container).unwrap().top_left; let container_pos = ctx.state.ui().window_region(&container).unwrap().top_left;
@@ -21,11 +21,11 @@ impl<State: HasUiState, W: Widget<State> + 'static> WidgetAttr<State, W> for Sel
pub struct Selectable; pub struct Selectable;
impl<State: HasUiState> WidgetAttr<State, TextEdit<State>> for Selectable { impl<State: HasUiState + HasEvents> WidgetAttr<State, TextEdit> for Selectable {
type Input = (); type Input = ();
fn run(ui: &mut Ui<State>, id: WidgetRef<State, TextEdit<State>>, _: Self::Input) { fn run(state: &mut State, id: WidgetRef<TextEdit>, _: Self::Input) {
ui.register_event(id, CursorSense::click_or_drag(), move |ctx| { state.register_event(id, CursorSense::click_or_drag(), move |ctx| {
select( select(
ctx.state, ctx.state,
id, id,
@@ -37,9 +37,9 @@ impl<State: HasUiState> WidgetAttr<State, TextEdit<State>> for Selectable {
} }
} }
fn select<State: 'static + HasUiState>( fn select(
state: &mut State, state: &mut impl HasUiState,
id: WidgetRef<State, TextEdit<State>>, id: WidgetRef<TextEdit>,
pos: Vec2, pos: Vec2,
size: Vec2, size: Vec2,
dragging: bool, dragging: bool,

View File

@@ -66,7 +66,7 @@ impl Input {
} }
} }
impl<State> UiState<State> { impl UiState {
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

@@ -24,17 +24,57 @@ pub use sense::*;
pub type Proxy<Event> = EventLoopProxy<Event>; pub type Proxy<Event> = EventLoopProxy<Event>;
pub struct UiState<State> { pub struct DefaultUiRsc<State> {
pub ui: Ui,
pub ui_state: UiState,
pub events: EventManager<State>,
}
impl<State> DefaultUiRsc<State> {
pub fn new(window: impl Into<Arc<Window>>) -> Self {
Self {
ui: Ui::new(),
ui_state: UiState::new(window),
events: EventManager::default(),
}
}
}
impl<State: 'static> HasUi for DefaultUiRsc<State> {
fn ui_ref(&self) -> &Ui {
&self.ui
}
fn ui(&mut self) -> &mut Ui {
&mut self.ui
}
}
impl<State: 'static + HasRsc<Rsc = Self>> HasEvents for DefaultUiRsc<State> {
type State = State;
fn events(&mut self) -> &mut EventManager<State> {
&mut self.events
}
}
impl<State: 'static> HasUiState for DefaultUiRsc<State> {
fn ui_state(&mut self) -> &mut UiState {
&mut self.ui_state
}
}
pub struct UiState {
pub renderer: UiRenderer, pub renderer: UiRenderer,
pub input: Input, pub input: Input,
pub focus: Option<WidgetRef<State, TextEdit<State>>>, pub focus: Option<WidgetRef<TextEdit>>,
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,
} }
impl<State> UiState<State> { impl UiState {
pub fn new(window: impl Into<Arc<Window>>) -> Self { pub fn new(window: impl Into<Arc<Window>>) -> Self {
let window = window.into(); let window = window.into();
Self { Self {
@@ -50,14 +90,23 @@ impl<State> UiState<State> {
} }
pub trait HasUiState: Sized + 'static + HasUi { pub trait HasUiState: Sized + 'static + HasUi {
fn ui_state(&mut self) -> &mut UiState<Self>; fn ui_state(&mut self) -> &mut UiState;
fn ui_with_ui_state(&mut self) -> (&mut Ui<Self>, &mut UiState<Self>) { fn ui_with_ui_state(&mut self) -> (&mut Ui, &mut UiState) {
// as long as you're not doing anything actually unhinged this should always work safely // as long as you're not doing anything actually unhinged this should always work safely
(unsafe { forget_mut(self.ui()) }, self.ui_state()) (unsafe { forget_mut(self.ui()) }, self.ui_state())
} }
} }
pub trait DefaultAppState: Sized + 'static + HasUi + HasUiState { impl<R: HasRsc> HasUiState for R
where
R::Rsc: HasUiState,
{
fn ui_state(&mut self) -> &mut UiState {
self.rsc_mut().ui_state()
}
}
pub trait DefaultAppState: Sized + 'static + HasRsc + HasUi + HasUiState {
type Event: 'static = (); type Event: 'static = ();
fn new(event_loop: &ActiveEventLoop, proxy: Proxy<Self::Event>) -> Self; fn new(event_loop: &ActiveEventLoop, proxy: Proxy<Self::Event>) -> Self;
#[allow(unused_variables)] #[allow(unused_variables)]
@@ -80,6 +129,7 @@ impl<State: DefaultAppState> AppState for State {
} }
fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) { fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) {
let events = unsafe { forget_mut(self.events()) };
let ui_state = self.ui_state(); let ui_state = self.ui_state();
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();
@@ -100,7 +150,7 @@ impl<State: DefaultAppState> AppState for State {
match &event { match &event {
WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => {
ui.update(); ui.update(events);
ui_state.renderer.update(ui); ui_state.renderer.update(ui);
ui_state.renderer.draw(); ui_state.renderer.draw();
} }

View File

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

View File

@@ -142,11 +142,10 @@ pub trait SensorUi<State> {
fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2); fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2);
} }
impl<State: 'static + HasUi> SensorUi<State> for State { impl<State: 'static + HasRsc> SensorUi<State> for State {
fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2) { fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2) {
let layers = std::mem::take(&mut self.ui().layers); let layers = std::mem::take(&mut self.ui().layers);
let mut active = let mut active = std::mem::take(&mut self.events().get_type::<CursorSense>().active);
std::mem::take(&mut self.ui().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, sensor) in active.get_mut(&layer).into_iter().flatten() { for (id, sensor) in active.get_mut(&layer).into_iter().flatten() {
@@ -175,7 +174,7 @@ impl<State: 'static + HasUi> SensorUi<State> for State {
break; break;
} }
} }
self.ui().events.get_type::<CursorSense>().active = active; self.events().get_type::<CursorSense>().active = active;
self.ui().layers = layers; self.ui().layers = layers;
} }
} }

View File

@@ -3,15 +3,15 @@ use crate::prelude::*;
pub mod eventable { pub mod eventable {
use super::*; use super::*;
widget_trait! { widget_trait! {
pub trait Eventable<State: 'static>; pub trait Eventable<State: HasUi + HasEvents>;
fn on<E: EventLike>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl for<'a> WidgetEventFn<State, <E::Event as Event>::Data<'a>, WL::Widget>, f: impl for<'a> WidgetEventFn<State::State, <E::Event as Event>::Data<'a>, WL::Widget>,
) -> impl WidgetIdFn<State, WL::Widget> { ) -> impl WidgetIdFn<State, WL::Widget> {
move |ui| { move |state| {
let id = self.handles(ui); let id = self.handles(state);
ui.register_event(id.r, event.into_event(), move |ctx| { state.register_event(id.r, event.into_event(), move |ctx| {
f(EventIdCtx { f(EventIdCtx {
widget: id.r, widget: id.r,
state: ctx.state, state: ctx.state,

View File

@@ -9,20 +9,17 @@ pub mod event;
pub mod typed; pub mod typed;
pub mod widget; pub mod widget;
pub use iris_core; pub use iris_core as core;
pub use iris_macro; pub use iris_macro as macros;
#[macro_export] #[macro_export]
macro_rules! state_prelude { macro_rules! state_prelude {
($vis:vis $state:ty) => { ($vis:vis $state:ty) => {
iris::event_state!($vis $state); iris::event_state!($vis $state);
iris::iris_core::core_state!($vis $state);
iris::default_state!($vis $state);
iris::widget_state!($vis $state);
$vis use iris::{ $vis use iris::{
default::*, default::*,
iris_core::{len_fns::*, util::Vec2, *}, core::{len_fns::*, util::Vec2, *},
iris_macro::*, macros::*,
widget::*, widget::*,
}; };
}; };

View File

@@ -1,35 +1,3 @@
#[macro_export]
macro_rules! default_state {
($vis:vis $state:ty) => {
$vis type UiState = $crate::default::UiState<$state>;
};
}
#[macro_export]
macro_rules! widget_state {
($vis:vis $state:ty) => {
$crate::widget_state!(
$vis $state;
Aligned,
LayerOffset,
MaxSize,
Offset,
Scroll,
Sized,
Span,
Stack,
Text,
TextEdit,
Masked,
WidgetPtr,
);
$vis type TextBuilder<O = TextOutput, H: WidgetOption<$state> = ()> = $crate::widget::TextBuilder<$state, O, H>;
};
($vis:vis $state:ty; $($ty:ident,)*) => {
$($vis type $ty = $crate::widget::$ty<$state>;)*
}
}
#[macro_export] #[macro_export]
macro_rules! event_state { macro_rules! event_state {
($vis:vis $state:ty) => { ($vis:vis $state:ty) => {
@@ -37,24 +5,32 @@ macro_rules! event_state {
use super::*; use super::*;
#[allow(unused_imports)] #[allow(unused_imports)]
use $crate::prelude::*; use $crate::prelude::*;
pub trait EventableCtx<WL: WidgetLike<$state, Tag>, Tag> { pub trait EventableCtx<WL: WidgetLike<$state, Tag>, Tag> {
fn on<E: EventLike>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl for<'a> WidgetEventFn<$state, <E::Event as Event>::Data<'a>, WL::Widget>, f: impl for<'a> WidgetEventFn<
<$state as HasEvents>::State,
<E::Event as Event>::Data<'a>,
WL::Widget
>,
) -> impl WidgetIdFn<$state, WL::Widget>; ) -> impl WidgetIdFn<$state, WL::Widget>;
} }
impl<WL: WidgetLike<$state, Tag>, Tag> EventableCtx<WL, Tag> for WL { impl<WL: WidgetLike<$state, Tag>, Tag> EventableCtx<WL, Tag> for WL {
fn on<E: EventLike>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl for<'a> WidgetEventFn<Client, <E::Event as Event>::Data<'a>, WL::Widget>, f: impl for<'a> WidgetEventFn<
) -> impl WidgetIdFn<Client, WL::Widget> { <$state as HasEvents>::State,
<E::Event as Event>::Data<'a>,
WL::Widget
>,
) -> impl WidgetIdFn<$state, WL::Widget> {
eventable::Eventable::on(self, event, f) eventable::Eventable::on(self, event, f)
} }
} }
} }
$vis type EventManager = $crate::prelude::EventManager<$state>;
$vis use local_event_trait::*; $vis use local_event_trait::*;
}; };
} }

View File

@@ -5,24 +5,24 @@ pub struct Image {
handle: TextureHandle, handle: TextureHandle,
} }
impl<State: 'static> Widget<State> for Image { impl Widget for Image {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
painter.texture(&self.handle); painter.texture(&self.handle);
} }
fn desired_width(&mut self, _: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, _: &mut SizeCtx) -> Len {
Len::abs(self.handle.size().x) Len::abs(self.handle.size().x)
} }
fn desired_height(&mut self, _: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, _: &mut SizeCtx) -> Len {
Len::abs(self.handle.size().y) Len::abs(self.handle.size().y)
} }
} }
pub fn image<State: 'static>(image: impl LoadableImage) -> impl WidgetFn<State, Image> { pub fn image<State: HasUi>(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 |state| Image {
handle: ui.add_texture(image), handle: state.ui().add_texture(image),
} }
} }

View File

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

View File

@@ -1,12 +1,12 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Aligned<State> { pub struct Aligned {
pub inner: WidgetHandle<State>, pub inner: WidgetHandle,
pub align: Align, pub align: Align,
} }
impl<State: 'static> Widget<State> for Aligned<State> { impl Widget for Aligned {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State: 'static> Widget<State> for Aligned<State> {
painter.widget_within(&self.inner, region); painter.widget_within(&self.inner, region);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

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

View File

@@ -1,13 +1,13 @@
use crate::prelude::*; use crate::prelude::*;
pub struct MaxSize<State> { pub struct MaxSize {
pub inner: WidgetHandle<State>, pub inner: WidgetHandle,
pub x: Option<Len>, pub x: Option<Len>,
pub y: Option<Len>, pub y: Option<Len>,
} }
impl<State: 'static> MaxSize<State> { impl MaxSize {
fn apply_to_outer(&self, ctx: &mut SizeCtx<State>) { fn apply_to_outer(&self, ctx: &mut SizeCtx) {
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<State: 'static> MaxSize<State> {
} }
} }
impl<State: 'static> Widget<State> for MaxSize<State> { impl Widget for MaxSize {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> Widget<State> for MaxSize<State> {
} }
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State> { pub struct Offset {
pub inner: WidgetHandle<State>, pub inner: WidgetHandle,
pub amt: UiVec2, pub amt: UiVec2,
} }
impl<State: 'static> Widget<State> for Offset<State> { impl Widget for Offset {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }

View File

@@ -1,16 +1,16 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Pad<State> { pub struct Pad {
pub padding: Padding, pub padding: Padding,
pub inner: WidgetHandle<State>, pub inner: WidgetHandle,
} }
impl<State: 'static> Widget<State> for Pad<State> { impl Widget for Pad {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
painter.widget_within(&self.inner, self.padding.region()); painter.widget_within(&self.inner, self.padding.region());
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> Widget<State> for Pad<State> {
size size
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State> { pub struct Scroll {
inner: WidgetHandle<State>, inner: WidgetHandle,
axis: Axis, axis: Axis,
amt: f32, amt: f32,
snap_end: bool, snap_end: bool,
@@ -9,8 +9,8 @@ pub struct Scroll<State> {
content_len: f32, content_len: f32,
} }
impl<State: 'static> Widget<State> for Scroll<State> { impl Widget for Scroll {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State: 'static> Widget<State> for Scroll<State> {
painter.widget_within(&self.inner, region); painter.widget_within(&self.inner, region);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.width(&self.inner) ctx.width(&self.inner)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len {
ctx.height(&self.inner) ctx.height(&self.inner)
} }
} }
impl<State> Scroll<State> { impl Scroll {
pub fn new(inner: WidgetHandle<State>, axis: Axis) -> Self { pub fn new(inner: WidgetHandle, axis: Axis) -> Self {
Self { Self {
inner, inner,
axis, axis,

View File

@@ -1,13 +1,13 @@
use crate::prelude::*; use crate::prelude::*;
pub struct Sized<State> { pub struct Sized {
pub inner: WidgetHandle<State>, pub inner: WidgetHandle,
pub x: Option<Len>, pub x: Option<Len>,
pub y: Option<Len>, pub y: Option<Len>,
} }
impl<State: 'static> Sized<State> { impl Sized {
fn apply_to_outer(&self, ctx: &mut SizeCtx<State>) { fn apply_to_outer(&self, ctx: &mut SizeCtx) {
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<State: 'static> Sized<State> {
} }
} }
impl<State: 'static> Widget<State> for Sized<State> { impl Widget for Sized {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
painter.widget(&self.inner); painter.widget(&self.inner);
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State> { pub struct Span {
pub children: Vec<WidgetHandle<State>>, pub children: Vec<WidgetHandle>,
pub dir: Dir, pub dir: Dir,
pub gap: f32, pub gap: f32,
} }
impl<State: 'static> Widget<State> for Span<State> { impl Widget for Span {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State: 'static> Widget<State> for Span<State> {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> Widget<State> for Span<State> {
} }
} }
impl<State: 'static> Span<State> { impl Span {
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<State: 'static> Span<State> {
self self
} }
fn len_sum(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn len_sum(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> Span<State> {
}) })
} }
fn desired_len(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_len(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> Span<State> {
} }
} }
fn desired_ortho(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_ortho(&mut self, ctx: &mut SizeCtx) -> 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,
@@ -151,14 +151,14 @@ pub struct SpanBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Ta
_pd: PhantomData<(State, Tag)>, _pd: PhantomData<(State, Tag)>,
} }
impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut Ui<State>,)> impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut State,)>
for SpanBuilder<State, LEN, Wa, Tag> for SpanBuilder<State, LEN, Wa, Tag>
{ {
type Output = Span<State>; type Output = Span;
extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut State,)) -> Self::Output {
Span { Span {
children: self.children.ui(args.0).arr.into_iter().collect(), children: self.children.add(args.0).arr.into_iter().collect(),
dir: self.dir, dir: self.dir,
gap: self.gap, gap: self.gap,
} }
@@ -183,15 +183,15 @@ impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
} }
} }
impl<State> std::ops::Deref for Span<State> { impl std::ops::Deref for Span {
type Target = Vec<WidgetHandle<State>>; type Target = Vec<WidgetHandle>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.children &self.children
} }
} }
impl<State> std::ops::DerefMut for Span<State> { impl std::ops::DerefMut for Span {
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<State> { pub struct Stack {
pub children: Vec<WidgetHandle<State>>, pub children: Vec<WidgetHandle>,
pub size: StackSize, pub size: StackSize,
} }
impl<State: 'static> Widget<State> for Stack<State> { impl Widget for Stack {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State: 'static> Widget<State> for Stack<State> {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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]),
@@ -48,14 +48,14 @@ pub struct StackBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, T
_pd: PhantomData<(State, Tag)>, _pd: PhantomData<(State, Tag)>,
} }
impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut Ui<State>,)> impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut State,)>
for StackBuilder<State, LEN, Wa, Tag> for StackBuilder<State, LEN, Wa, Tag>
{ {
type Output = Stack<State>; type Output = Stack;
extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut State,)) -> Self::Output {
Stack { Stack {
children: self.children.ui(args.0).arr.into_iter().collect(), children: self.children.add(args.0).arr.into_iter().collect(),
size: self.size, size: self.size,
} }
} }

View File

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

View File

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

View File

@@ -51,7 +51,7 @@ impl<State, O, H: WidgetOption<State>> TextBuilder<State, O, H> {
} }
} }
impl<State: 'static, O> TextBuilder<State, O> { impl<State: HasUi, O> TextBuilder<State, O> {
pub fn hint<W: WidgetLike<State, Tag>, Tag>( pub fn hint<W: WidgetLike<State, Tag>, Tag>(
self, self,
hint: W, hint: W,
@@ -59,7 +59,7 @@ impl<State: 'static, O> TextBuilder<State, O> {
TextBuilder { TextBuilder {
content: self.content, content: self.content,
attrs: self.attrs, attrs: self.attrs,
hint: move |ui: &mut Ui<State>| Some(hint.add(ui).any()), hint: move |ui: &mut State| Some(hint.add(ui).any()),
output: self.output, output: self.output,
state: PhantomData, state: PhantomData,
} }
@@ -69,25 +69,25 @@ impl<State: 'static, O> TextBuilder<State, O> {
pub trait TextBuilderOutput<State>: Sized { pub trait TextBuilderOutput<State>: Sized {
type Output; type Output;
fn run<H: WidgetOption<State>>( fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>, state: &mut State,
builder: TextBuilder<State, Self, H>, builder: TextBuilder<State, Self, H>,
) -> Self::Output; ) -> Self::Output;
} }
pub struct TextOutput; pub struct TextOutput;
impl<State: 'static> TextBuilderOutput<State> for TextOutput { impl<State: HasUi> TextBuilderOutput<State> for TextOutput {
type Output = Text<State>; type Output = Text;
fn run<H: WidgetOption<State>>( fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>, state: &mut State,
builder: TextBuilder<State, Self, H>, builder: TextBuilder<State, Self, H>,
) -> Self::Output { ) -> 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,
)); ));
let hint = builder.hint.get(ui); let hint = builder.hint.get(state);
let font_system = &mut ui.text.font_system; let font_system = &mut state.ui().text.font_system;
buf.set_text(font_system, &builder.content, &Attrs::new(), SHAPING, None); buf.set_text(font_system, &builder.content, &Attrs::new(), SHAPING, None);
let mut text = Text { let mut text = Text {
content: builder.content.into(), content: builder.content.into(),
@@ -102,11 +102,12 @@ impl<State: 'static> TextBuilderOutput<State> for TextOutput {
pub struct TextEditOutput { pub struct TextEditOutput {
mode: EditMode, mode: EditMode,
} }
impl<State: 'static> TextBuilderOutput<State> for TextEditOutput {
type Output = TextEdit<State>; impl<State: HasUi> TextBuilderOutput<State> for TextEditOutput {
type Output = TextEdit;
fn run<H: WidgetOption<State>>( fn run<H: WidgetOption<State>>(
ui: &mut Ui<State>, state: &mut State,
builder: TextBuilder<State, Self, H>, builder: TextBuilder<State, Self, H>,
) -> Self::Output { ) -> Self::Output {
let buf = TextBuffer::new_empty(Metrics::new( let buf = TextBuffer::new_empty(Metrics::new(
@@ -114,10 +115,10 @@ impl<State: 'static> TextBuilderOutput<State> for TextEditOutput {
builder.attrs.line_height, builder.attrs.line_height,
)); ));
let mut text = TextEdit::new( let mut text = TextEdit::new(
TextView::new(buf, builder.attrs, builder.hint.get(ui)), TextView::new(buf, builder.attrs, builder.hint.get(state)),
builder.output.mode, builder.output.mode,
); );
let font_system = &mut ui.text.font_system; let font_system = &mut state.ui().text.font_system;
text.buf text.buf
.set_text(font_system, &builder.content, &Attrs::new(), SHAPING, None); .set_text(font_system, &builder.content, &Attrs::new(), SHAPING, None);
builder.attrs.apply(font_system, &mut text.buf, None); builder.attrs.apply(font_system, &mut text.buf, None);
@@ -125,12 +126,12 @@ impl<State: 'static> TextBuilderOutput<State> for TextEditOutput {
} }
} }
impl<State, O: TextBuilderOutput<State>, H: WidgetOption<State>> FnOnce<(&mut Ui<State>,)> impl<State, O: TextBuilderOutput<State>, H: WidgetOption<State>> FnOnce<(&mut State,)>
for TextBuilder<State, O, H> for TextBuilder<State, O, H>
{ {
type Output = O::Output; type Output = O::Output;
extern "rust-call" fn call_once(self, args: (&mut Ui<State>,)) -> Self::Output { extern "rust-call" fn call_once(self, args: (&mut State,)) -> Self::Output {
O::run(args.0, self) O::run(args.0, self)
} }
} }

View File

@@ -7,8 +7,8 @@ use winit::{
keyboard::{Key, NamedKey}, keyboard::{Key, NamedKey},
}; };
pub struct TextEdit<State> { pub struct TextEdit {
view: TextView<State>, view: TextView,
selection: TextSelection, selection: TextSelection,
history: Vec<(String, TextSelection)>, history: Vec<(String, TextSelection)>,
double_hit: Option<Cursor>, double_hit: Option<Cursor>,
@@ -21,8 +21,8 @@ pub enum EditMode {
MultiLine, MultiLine,
} }
impl<State: 'static> TextEdit<State> { impl TextEdit {
pub fn new(view: TextView<State>, mode: EditMode) -> Self { pub fn new(view: TextView, mode: EditMode) -> Self {
Self { Self {
view, view,
selection: Default::default(), selection: Default::default(),
@@ -49,8 +49,8 @@ impl<State: 'static> TextEdit<State> {
} }
} }
impl<State: 'static> Widget<State> for TextEdit<State> { impl Widget for TextEdit {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
let base = painter.layer; let base = painter.layer;
painter.child_layer(); painter.child_layer();
self.view.draw(painter); self.view.draw(painter);
@@ -92,11 +92,11 @@ impl<State: 'static> Widget<State> for TextEdit<State> {
} }
} }
fn desired_width(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len {
self.view.desired_width(ctx) self.view.desired_width(ctx)
} }
fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len {
self.view.desired_height(ctx) self.view.desired_height(ctx)
} }
} }
@@ -180,12 +180,12 @@ fn cursor_pos(cursor: Cursor, buf: &TextBuffer) -> Option<Vec2> {
prev prev
} }
pub struct TextEditCtx<'a, State> { pub struct TextEditCtx<'a> {
pub text: &'a mut TextEdit<State>, pub text: &'a mut TextEdit,
pub font_system: &'a mut FontSystem, pub font_system: &'a mut FontSystem,
} }
impl<'a, State: 'static> TextEditCtx<'a, State> { impl<'a> TextEditCtx<'a> {
pub fn take(&mut self) -> String { pub fn take(&mut self) -> String {
let text = self let text = self
.text .text
@@ -602,26 +602,26 @@ impl TextInputResult {
} }
} }
impl<State> Deref for TextEdit<State> { impl Deref for TextEdit {
type Target = TextView<State>; type Target = TextView;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.view &self.view
} }
} }
impl<State> DerefMut for TextEdit<State> { impl DerefMut for TextEdit {
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<State> { pub trait TextEditable {
fn edit<'a>(&self, ui: &'a mut Ui<State>) -> TextEditCtx<'a, State>; fn edit<'a>(&self, ui: &'a mut Ui) -> TextEditCtx<'a>;
} }
impl<State: 'static, I: IdLike<State, Widget = TextEdit<State>>> TextEditable<State> for I { impl<I: IdLike<Widget = TextEdit>> TextEditable for I {
fn edit<'a>(&self, ui: &'a mut Ui<State>) -> TextEditCtx<'a, State> { fn edit<'a>(&self, ui: &'a mut Ui) -> TextEditCtx<'a> {
TextEditCtx { TextEditCtx {
text: ui.widgets.get_mut(self).unwrap(), text: ui.widgets.get_mut(self).unwrap(),
font_system: &mut ui.text.font_system, font_system: &mut ui.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<State> { pub struct Text {
pub content: MutDetect<String>, pub content: MutDetect<String>,
view: TextView<State>, view: TextView,
} }
pub struct TextView<State> { pub struct TextView {
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<State>>, pub hint: Option<WidgetHandle>,
} }
impl<State: 'static> TextView<State> { impl TextView {
pub fn new(buf: TextBuffer, attrs: TextAttrs, hint: Option<WidgetHandle<State>>) -> Self { pub fn new(buf: TextBuffer, attrs: TextAttrs, hint: Option<WidgetHandle>) -> Self {
Self { Self {
attrs: attrs.into(), attrs: attrs.into(),
buf: buf.into(), buf: buf.into(),
@@ -54,7 +54,7 @@ impl<State: 'static> TextView<State> {
region region
} }
fn render(&mut self, ctx: &mut SizeCtx<State>) -> RenderedText { fn render(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> TextView<State> {
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<State>) -> Len { pub fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> TextView<State> {
Len::abs(self.render(ctx).size.x) Len::abs(self.render(ctx).size.x)
} }
} }
pub fn desired_height(&mut self, ctx: &mut SizeCtx<State>) -> Len { pub fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State: 'static> TextView<State> {
Len::abs(self.render(ctx).size.y) Len::abs(self.render(ctx).size.y)
} }
} }
pub fn draw(&mut self, painter: &mut Painter<State>) -> UiRegion { pub fn draw(&mut self, painter: &mut Painter) -> 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<State: 'static> TextView<State> {
} }
} }
impl<State: 'static> Text<State> { impl Text {
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<State: 'static> Text<State> {
view: TextView::new(buf, attrs, None), view: TextView::new(buf, attrs, None),
} }
} }
fn update_buf(&mut self, ctx: &mut SizeCtx<State>) { fn update_buf(&mut self, ctx: &mut SizeCtx) {
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<State: 'static> Text<State> {
} }
} }
impl<State: 'static> Widget<State> for Text<State> { impl Widget for Text {
fn draw(&mut self, painter: &mut Painter<State>) { fn draw(&mut self, painter: &mut Painter) {
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<State>) -> Len { fn desired_width(&mut self, ctx: &mut SizeCtx) -> 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<State>) -> Len { fn desired_height(&mut self, ctx: &mut SizeCtx) -> 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<State> Deref for Text<State> { impl Deref for Text {
type Target = TextAttrs; type Target = TextAttrs;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -182,13 +182,13 @@ impl<State> Deref for Text<State> {
} }
} }
impl<State> DerefMut for Text<State> { impl DerefMut for Text {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.view &mut self.view
} }
} }
impl<State> Deref for TextView<State> { impl Deref for TextView {
type Target = TextAttrs; type Target = TextAttrs;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -196,7 +196,7 @@ impl<State> Deref for TextView<State> {
} }
} }
impl<State> DerefMut for TextView<State> { impl DerefMut for TextView {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.attrs &mut self.attrs
} }

View File

@@ -3,132 +3,132 @@ 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
widget_trait! { widget_trait! {
pub trait CoreWidget<State: HasUi + 'static>; pub trait CoreWidget<State: HasUi>;
fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<State, Pad<State>> { fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<State, Pad> {
|ui| Pad { |state| Pad {
padding: padding.into(), padding: padding.into(),
inner: self.add(ui), inner: self.add(state),
} }
} }
fn align(self, align: impl Into<Align>) -> impl WidgetFn<State, Aligned<State>> { fn align(self, align: impl Into<Align>) -> impl WidgetFn<State, Aligned> {
move |ui| Aligned { move |state| Aligned {
inner: self.add(ui), inner: self.add(state),
align: align.into(), align: align.into(),
} }
} }
fn center(self) -> impl WidgetFn<State, Aligned<State>> { fn center(self) -> impl WidgetFn<State, Aligned> {
self.align(Align::CENTER) self.align(Align::CENTER)
} }
fn label(self, label: impl Into<String>) -> impl WidgetIdFn<State, WL::Widget> { fn label(self, label: impl Into<String>) -> impl WidgetIdFn<State, WL::Widget> {
|ui| { |state| {
let id = self.add(ui); let id = self.add(state);
ui.set_label(&id, label.into()); state.ui().set_label(&id, label.into());
id id
} }
} }
fn sized(self, size: impl Into<Size>) -> impl WidgetFn<State, Sized<State>> { fn sized(self, size: impl Into<Size>) -> impl WidgetFn<State, Sized> {
let size = size.into(); let size = size.into();
move |ui| Sized { move |state| Sized {
inner: self.add(ui), inner: self.add(state),
x: Some(size.x), x: Some(size.x),
y: Some(size.y), y: Some(size.y),
} }
} }
fn max_width(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize<State>> { fn max_width(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize> {
let len = len.into(); let len = len.into();
move |ui| MaxSize { move |state| MaxSize {
inner: self.add(ui), inner: self.add(state),
x: Some(len), x: Some(len),
y: None, y: None,
} }
} }
fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize<State>> { fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize> {
let len = len.into(); let len = len.into();
move |ui| MaxSize { move |state| MaxSize {
inner: self.add(ui), inner: self.add(state),
x: None, x: None,
y: Some(len), y: Some(len),
} }
} }
fn width(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized<State>> { fn width(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized> {
let len = len.into(); let len = len.into();
move |ui| Sized { move |state| Sized {
inner: self.add(ui), inner: self.add(state),
x: Some(len), x: Some(len),
y: None, y: None,
} }
} }
fn height(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized<State>> { fn height(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized> {
let len = len.into(); let len = len.into();
move |ui| Sized { move |state| Sized {
inner: self.add(ui), inner: self.add(state),
x: None, x: None,
y: Some(len), y: Some(len),
} }
} }
fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<State, Offset<State>> { fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<State, Offset> {
move |ui| Offset { move |state| Offset {
inner: self.add(ui), inner: self.add(state),
amt: amt.into(), amt: amt.into(),
} }
} }
fn scrollable(self) -> impl WidgetIdFn<State, Scroll<State>> { fn scrollable(self) -> impl WidgetIdFn<State, Scroll> where State: HasEvents {
use eventable::*; use eventable::*;
move |ui| { move |state| {
Scroll::new(self.add(ui), Axis::Y) Scroll::new(self.add(state), Axis::Y)
.on(CursorSense::Scroll, |mut ctx| { .on(CursorSense::Scroll, |mut ctx| {
let delta = ctx.data.scroll_delta.y * 50.0; let delta = ctx.data.scroll_delta.y * 50.0;
ctx.widget().scroll(delta); ctx.widget().scroll(delta);
}) })
.add(ui) .add(state)
} }
} }
fn masked(self) -> impl WidgetFn<State, Masked<State>> { fn masked(self) -> impl WidgetFn<State, Masked> {
move |ui| Masked { move |state| Masked {
inner: self.add(ui), inner: self.add(state),
} }
} }
fn background<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack<State>> { fn background<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack> {
move |ui| Stack { move |state| Stack {
children: vec![w.add(ui), self.add(ui)], children: vec![w.add(state), self.add(state)],
size: StackSize::Child(1), size: StackSize::Child(1),
} }
} }
fn foreground<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack<State>> { fn foreground<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack> {
move |ui| Stack { move |state| Stack {
children: vec![self.add(ui), w.add(ui)], children: vec![self.add(state), w.add(state)],
size: StackSize::Child(0), size: StackSize::Child(0),
} }
} }
fn layer_offset(self, offset: usize) -> impl WidgetFn<State, LayerOffset<State>> { fn layer_offset(self, offset: usize) -> impl WidgetFn<State, LayerOffset> {
move |ui| LayerOffset { move |state| LayerOffset {
inner: self.add(ui), inner: self.add(state),
offset, offset,
} }
} }
fn to_any(self) -> impl WidgetIdFn<State> { fn to_any(self) -> impl WidgetIdFn<State> {
|ui| self.add(ui) |state| self.add(state)
} }
fn set_ptr(self, ptr: WidgetRef<State, WidgetPtr<State>>, ui: &mut Ui<State>) { fn set_ptr(self, ptr: WidgetRef<WidgetPtr>, state: &mut State) {
let id = self.add(ui); let id = self.add(state);
ui[ptr].inner = Some(id); state.ui()[ptr].inner = Some(id);
} }
} }