finished moving out render_state

This commit is contained in:
2026-01-19 18:00:24 -05:00
parent 79813db3ba
commit 06dd015092
26 changed files with 497 additions and 221 deletions

View File

@@ -13,6 +13,6 @@ pub struct EventIdCtx<'a, Rsc: HasEvents, Data, W: ?Sized> {
impl<Rsc: HasEvents, Data, W: Widget> EventIdCtx<'_, Rsc, Data, W> { impl<Rsc: HasEvents, Data, W: Widget> EventIdCtx<'_, Rsc, Data, W> {
pub fn widget<'a>(&self, rsc: &'a mut Rsc) -> &'a mut W { pub fn widget<'a>(&self, rsc: &'a mut Rsc) -> &'a mut W {
&mut rsc.widgets_mut()[self.widget] &mut rsc.ui_mut().widgets[self.widget]
} }
} }

View File

@@ -1,6 +1,6 @@
use crate::{ use crate::{
ActiveData, Event, EventCtx, EventFn, EventIdCtx, EventLike, HasEvents, IdLike, LayerId, ActiveData, Event, EventCtx, EventFn, EventIdCtx, EventLike, HasEvents, IdLike, LayerId,
Widget, WidgetEventFn, WidgetId, WeakWidget, WeakWidget, Widget, WidgetEventFn, WidgetId,
util::{HashMap, HashSet, TypeMap}, util::{HashMap, HashSet, TypeMap},
}; };
use std::{any::TypeId, rc::Rc}; use std::{any::TypeId, rc::Rc};
@@ -28,7 +28,7 @@ impl<Rsc: HasEvents + 'static> EventManager<Rsc> {
&mut self, &mut self,
id: WeakWidget<W>, id: WeakWidget<W>,
event: E, event: E,
f: impl WidgetEventFn<Rsc, <E::Event as Event>::Data, W>, f: impl for<'a> WidgetEventFn<Rsc, <E::Event as Event>::Data<'a>, W>,
) { ) {
self.get_type::<E>().register(id, event, f); self.get_type::<E>().register(id, event, f);
self.widget_to_types self.widget_to_types
@@ -74,7 +74,7 @@ pub trait EventManagerLike<State> {
fn undraw(&mut self, data: &ActiveData); fn undraw(&mut self, data: &ActiveData);
} }
type EventData<Rsc, E> = (E, Rc<dyn EventFn<Rsc, <E as Event>::Data>>); type EventData<Rsc, E> = (E, Rc<dyn for<'a> EventFn<Rsc, <E as Event>::Data<'a>>>);
pub struct TypeEventManager<Rsc: HasEvents, E: Event> { pub struct TypeEventManager<Rsc: HasEvents, E: Event> {
// TODO: reduce visiblity!! // TODO: reduce visiblity!!
pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>, pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>,
@@ -116,7 +116,7 @@ impl<Rsc: HasEvents + 'static, E: Event> TypeEventManager<Rsc, E> {
&mut self, &mut self,
widget: WeakWidget<W>, widget: WeakWidget<W>,
event: impl EventLike<Event = E>, event: impl EventLike<Event = E>,
f: impl WidgetEventFn<Rsc, E::Data, W>, f: impl for<'a> WidgetEventFn<Rsc, E::Data<'a>, W>,
) { ) {
let event = event.into_event(); let event = event.into_event();
self.map.entry(widget.id()).or_default().push(( self.map.entry(widget.id()).or_default().push((
@@ -137,7 +137,7 @@ impl<Rsc: HasEvents + 'static, E: Event> TypeEventManager<Rsc, E> {
pub fn run_fn<'a>( pub fn run_fn<'a>(
&mut self, &mut self,
id: impl IdLike, id: impl IdLike,
) -> impl FnOnce(EventCtx<'_, Rsc, E::Data>, &mut Rsc) + 'a { ) -> impl for<'b> FnOnce(EventCtx<'_, Rsc, E::Data<'b>>, &mut Rsc) + '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, rsc| { move |ctx, rsc| {
for (e, f) in fs { for (e, f) in fs {

View File

@@ -7,10 +7,10 @@ pub use manager::*;
pub use rsc::*; pub use rsc::*;
pub trait Event: Sized + 'static + Clone { pub trait Event: Sized + 'static + Clone {
type Data: Clone = (); type Data<'a>: Clone = ();
type State: Default = (); type State: Default = ();
#[allow(unused_variables)] #[allow(unused_variables)]
fn should_run(&self, data: &Self::Data) -> Option<Self::Data> { fn should_run<'a>(&self, data: &Self::Data<'a>) -> Option<Self::Data<'a>> {
Some(data.clone()) Some(data.clone())
} }
} }

View File

@@ -1,5 +1,5 @@
use crate::{ use crate::{
Event, EventCtx, EventLike, EventManager, IdLike, UiRsc, Widget, WidgetEventFn, WeakWidget, Event, EventCtx, EventLike, EventManager, IdLike, UiRsc, WeakWidget, Widget, WidgetEventFn,
}; };
pub trait HasState: 'static { pub trait HasState: 'static {
@@ -14,7 +14,7 @@ pub trait HasEvents: Sized + UiRsc + HasState {
&mut self, &mut self,
id: WeakWidget<W>, id: WeakWidget<W>,
event: E, event: E,
f: impl WidgetEventFn<Self, <E::Event as Event>::Data, W>, f: impl for<'a> WidgetEventFn<Self, <E::Event as Event>::Data<'a>, W>,
) { ) {
self.events_mut().register(id, event, f); self.events_mut().register(id, event, f);
} }
@@ -24,7 +24,7 @@ pub trait RunEvents: HasEvents {
fn run_event<E: EventLike>( fn run_event<E: EventLike>(
&mut self, &mut self,
id: impl IdLike, id: impl IdLike,
data: <E::Event as Event>::Data, data: <E::Event as Event>::Data<'_>,
state: &mut Self::State, state: &mut Self::State,
) { ) {
let f = self.events_mut().get_type::<E>().run_fn(id); let f = self.events_mut().get_type::<E>().run_fn(id);

View File

@@ -7,12 +7,3 @@ pub use color::*;
pub use layer::*; pub use layer::*;
pub use text::*; pub use text::*;
pub use texture::*; pub use texture::*;
use crate::{Mask, util::TrackedArena};
#[derive(Default)]
pub struct PainterData {
pub textures: Textures,
pub text: TextData,
pub masks: TrackedArena<Mask, u32>,
}

View File

@@ -1,7 +1,7 @@
use std::num::NonZero; use std::num::NonZero;
use crate::{ use crate::{
Textures, UiRenderState, UiData, UiRenderState,
render::{data::PrimitiveInstance, texture::GpuTextures, util::ArrBuf}, render::{data::PrimitiveInstance, texture::GpuTextures, util::ArrBuf},
util::HashMap, util::HashMap,
}; };
@@ -63,14 +63,14 @@ impl UiRenderNode {
&mut self, &mut self,
device: &Device, device: &Device,
queue: &Queue, queue: &Queue,
ui: &mut UiRenderState, ui: &mut UiData,
textures: &mut Textures, ui_render: &mut UiRenderState,
) { ) {
self.active.clear(); self.active.clear();
for (i, primitives) in ui.layers.iter_mut() { for (i, primitives) in ui_render.layers.iter_mut() {
self.active.push(i); self.active.push(i);
for change in primitives.apply_free() { for change in primitives.apply_free() {
if let Some(inst) = ui.active.get_mut(&change.id) { if let Some(inst) = ui_render.active.get_mut(&change.id) {
for h in &mut inst.primitives { for h in &mut inst.primitives {
if h.layer == i && h.inst_idx == change.old { if h.layer == i && h.inst_idx == change.old {
h.inst_idx = change.new; h.inst_idx = change.new;
@@ -107,7 +107,7 @@ impl UiRenderNode {
} }
} }
let mut changed = false; let mut changed = false;
changed |= self.textures.update(textures); changed |= self.textures.update(&mut ui.textures);
if ui.masks.changed { if ui.masks.changed {
ui.masks.changed = false; ui.masks.changed = false;
self.masks.update(device, queue, &ui.masks[..]); self.masks.update(device, queue, &ui.masks[..]);

View File

@@ -1,6 +1,6 @@
use crate::{ use crate::{
ActiveData, Axis, EventsLike, Painter, PainterData, SizeCtx, StrongWidget, UiRegion, ActiveData, Axis, EventsLike, Painter, SizeCtx, StrongWidget, UiRegion, UiRenderState, UiVec2,
UiRenderState, UiVec2, WidgetId, Widgets, WidgetId, Widgets,
render::MaskIdx, render::MaskIdx,
util::{HashSet, forget_ref}, util::{HashSet, forget_ref},
}; };
@@ -16,30 +16,6 @@ pub struct Drawer<'a> {
} }
impl<'a> Drawer<'a> { impl<'a> Drawer<'a> {
pub fn new(
widgets: &'a mut Widgets,
data: &'a mut PainterData,
render: &'a mut UiRenderState,
events: &'a mut dyn EventsLike,
root: Option<&'a StrongWidget>,
) -> Self {
Self {
widgets,
data,
events,
render,
root,
draw_started: Default::default(),
}
}
pub fn redraw_updates(&mut self) {
while let Some(&id) = self.widgets.needs_redraw.iter().next() {
self.redraw(id);
}
self.ui.free(self.events);
}
/// redraws a widget that's currently active (drawn) /// redraws a widget that's currently active (drawn)
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);
@@ -94,21 +70,6 @@ impl<'a> Drawer<'a> {
} }
} }
pub fn redraw_all(&mut self) {
// free all resources & cache
for (_, active) in self.render.active.drain() {
self.events.undraw(&active);
}
self.render.cache.clear();
self.ui.free(self.events);
self.render.layers.clear();
self.widgets.needs_redraw.clear();
if let Some(id) = self.root {
self.draw_inner(0, id.id(), UiRegion::FULL, None, MaskIdx::NONE, None);
}
}
pub(super) fn draw_inner( pub(super) fn draw_inner(
&mut self, &mut self,
layer: usize, layer: usize,

View File

@@ -1,8 +1,8 @@
use crate::{WeakWidget, Widget, Widgets}; use crate::{Mask, TextData, Textures, WeakWidget, WidgetId, Widgets, util::TrackedArena};
mod active; mod active;
mod cache; mod cache;
mod draw_state; // mod draw_state;
mod painter; mod painter;
mod render_state; mod render_state;
mod size; mod size;
@@ -13,10 +13,37 @@ pub use painter::Painter;
pub use render_state::*; pub use render_state::*;
pub use size::*; pub use size::*;
pub struct Ui {} #[derive(Default)]
pub struct UiData {
pub trait UiRsc: Sized { pub widgets: Widgets,
fn add_widget<W: Widget>(&mut self, widget: W) -> WeakWidget<W>; pub textures: Textures,
fn widgets(&self) -> &Widgets; pub text: TextData,
fn widgets_mut(&mut self) -> &mut Widgets; pub masks: TrackedArena<Mask, u32>,
}
pub trait UiRsc {
fn ui(&self) -> &UiData;
fn ui_mut(&mut self) -> &mut UiData;
#[allow(unused_variables)]
fn on_add(&mut self, id: WeakWidget) {}
#[allow(unused_variables)]
fn on_remove(&mut self, id: WidgetId) {}
#[allow(unused_variables)]
fn on_draw(&mut self, active: &ActiveData) {}
#[allow(unused_variables)]
fn on_undraw(&mut self, active: &ActiveData) {}
fn widgets(&self) -> &Widgets {
&self.ui().widgets
}
fn widgets_mut(&mut self) -> &mut Widgets {
&mut self.ui_mut().widgets
}
fn free(&mut self) {
while let Some(id) = self.widgets_mut().free_next() {
self.on_remove(id);
}
self.ui_mut().textures.free();
}
} }

View File

@@ -1,14 +1,14 @@
use crate::{ use crate::{
Axis, Len, RenderedText, Size, SizeCtx, StrongWidget, TextAttrs, TextBuffer, TextData, Axis, Len, RenderedText, Size, SizeCtx, StrongWidget, TextAttrs, TextBuffer, TextData,
TextureHandle, UiRegion, Widget, WidgetId, TextureHandle, UiRegion, UiRenderState, UiRsc, Widget, WidgetId,
render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst}, render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst},
ui::draw_state::Drawer,
util::Vec2, util::Vec2,
}; };
/// makes your surfaces look pretty /// makes your surfaces look pretty
pub struct Painter<'a, 'b> { pub struct Painter<'a> {
pub(super) drawer: &'a mut Drawer<'b>, pub(super) state: &'a mut UiRenderState,
pub(super) rsc: &'a mut dyn UiRsc,
pub(super) region: UiRegion, pub(super) region: UiRegion,
pub(super) mask: MaskIdx, pub(super) mask: MaskIdx,
@@ -19,9 +19,9 @@ pub struct Painter<'a, 'b> {
pub(super) id: WidgetId, pub(super) id: WidgetId,
} }
impl<'a, 'c> Painter<'a, 'c> { impl<'a> Painter<'a> {
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.drawer.layers.write( let h = self.state.layers.write(
self.layer, self.layer,
PrimitiveInst { PrimitiveInst {
id: self.id, id: self.id,
@@ -32,7 +32,7 @@ impl<'a, 'c> Painter<'a, 'c> {
); );
if self.mask != MaskIdx::NONE { if self.mask != MaskIdx::NONE {
// TODO: I have no clue if this works at all :joy: // TODO: I have no clue if this works at all :joy:
self.drawer.masks.push_ref(self.mask); self.rsc.ui_mut().masks.push_ref(self.mask);
} }
self.primitives.push(h); self.primitives.push(h);
} }
@@ -48,7 +48,7 @@ impl<'a, 'c> Painter<'a, 'c> {
pub fn set_mask(&mut self, region: UiRegion) { pub fn set_mask(&mut self, region: UiRegion) {
assert!(self.mask == MaskIdx::NONE); assert!(self.mask == MaskIdx::NONE);
self.mask = self.drawer.masks.push(Mask { region }); self.mask = self.rsc.ui_mut().masks.push(Mask { region });
} }
/// Draws a widget within this widget's region. /// Draws a widget within this widget's region.
@@ -64,8 +64,15 @@ impl<'a, 'c> Painter<'a, 'c> {
fn widget_at<W: ?Sized>(&mut self, id: &StrongWidget<W>, region: UiRegion) { fn widget_at<W: ?Sized>(&mut self, id: &StrongWidget<W>, region: UiRegion) {
self.children.push(id.id()); self.children.push(id.id());
self.drawer self.state.draw_inner(
.draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None); self.layer,
id.id(),
region,
Some(self.id),
self.mask,
None,
self.rsc,
);
} }
pub fn texture_within(&mut self, handle: &TextureHandle, region: UiRegion) { pub fn texture_within(&mut self, handle: &TextureHandle, region: UiRegion) {
@@ -85,10 +92,8 @@ impl<'a, 'c> Painter<'a, 'c> {
/// returns (handle, offset from top left) /// returns (handle, offset from top left)
pub fn render_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText { pub fn render_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
self.drawer let ui = self.rsc.ui_mut();
.ui ui.text.draw(buffer, attrs, &mut ui.textures)
.text
.draw(buffer, attrs, &mut self.drawer.ui.textures)
} }
pub fn region(&self) -> UiRegion { pub fn region(&self) -> UiRegion {
@@ -107,27 +112,27 @@ impl<'a, 'c> Painter<'a, 'c> {
} }
pub fn output_size(&self) -> Vec2 { pub fn output_size(&self) -> Vec2 {
self.drawer.output_size self.state.output_size
} }
pub fn px_size(&mut self) -> Vec2 { pub fn px_size(&mut self) -> Vec2 {
self.region.size().to_abs(self.drawer.output_size) self.region.size().to_abs(self.state.output_size)
} }
pub fn text_data(&mut self) -> &mut TextData { pub fn text_data(&mut self) -> &mut TextData {
&mut self.drawer.text &mut self.rsc.ui_mut().text
} }
pub fn child_layer(&mut self) { pub fn child_layer(&mut self) {
self.layer = self.drawer.layers.child(self.layer); self.layer = self.state.layers.child(self.layer);
} }
pub fn next_layer(&mut self) { pub fn next_layer(&mut self) {
self.layer = self.drawer.layers.next(self.layer); self.layer = self.state.layers.next(self.layer);
} }
pub fn label(&self) -> &str { pub fn label(&self) -> &str {
&self.drawer.widgets.data(self.id).unwrap().label &self.rsc.widgets().data(self.id).unwrap().label
} }
pub fn id(&self) -> &WidgetId { pub fn id(&self) -> &WidgetId {
@@ -135,6 +140,6 @@ impl<'a, 'c> Painter<'a, 'c> {
} }
pub fn size_ctx(&mut self) -> SizeCtx<'_> { pub fn size_ctx(&mut self) -> SizeCtx<'_> {
self.drawer.size_ctx(self.id, self.region.size()) self.state.size_ctx(self.id, self.region.size(), self.rsc)
} }
} }

View File

@@ -1,7 +1,8 @@
use crate::{ use crate::{
ActiveData, EventsLike, IdLike, PixelRegion, PrimitiveLayers, StrongWidget, WidgetId, Widgets, ActiveData, Axis, IdLike, MaskIdx, Painter, PixelRegion, PrimitiveLayers, SizeCtx,
ui::{cache::Cache, draw_state::Drawer}, StrongWidget, UiRegion, UiRsc, UiVec2, WidgetId, Widgets,
util::{HashMap, Vec2}, ui::cache::Cache,
util::{HashMap, HashSet, Vec2, forget_ref},
}; };
pub struct UiRenderState { pub struct UiRenderState {
@@ -12,6 +13,7 @@ pub struct UiRenderState {
old_root: Option<WidgetId>, old_root: Option<WidgetId>,
resized: bool, resized: bool,
draw_started: HashSet<WidgetId>,
} }
impl UiRenderState { impl UiRenderState {
@@ -23,6 +25,7 @@ impl UiRenderState {
output_size: Vec2::ZERO, output_size: Vec2::ZERO,
old_root: None, old_root: None,
resized: false, resized: false,
draw_started: Default::default(),
} }
} }
@@ -31,15 +34,11 @@ impl UiRenderState {
self.resized = true; self.resized = true;
} }
pub fn update<'a>( pub fn update<'a>(&mut self, root: impl Into<Option<&'a StrongWidget>>, rsc: &mut dyn UiRsc) {
&mut self,
root: impl Into<Option<&'a StrongWidget>>,
widgets: &mut Widgets,
events: &mut dyn EventsLike,
) {
// safety mechanism for memory leaks; might wanna return a result instead so user can // safety mechanism for memory leaks; might wanna return a result instead so user can
// decide whether to panic or not // decide whether to panic or not
if !widgets.waiting.is_empty() { if !rsc.widgets().waiting.is_empty() {
let widgets = rsc.widgets();
let len = widgets.waiting.len(); let len = widgets.waiting.len();
let all: Vec<_> = widgets let all: Vec<_> = widgets
.waiting .waiting
@@ -52,18 +51,169 @@ impl UiRenderState {
weak widgets: {all:#?}" weak widgets: {all:#?}"
); );
} }
if self.root_changed(root) { let root = root.into();
Drawer::new(self, events).redraw_all(); if self.root_changed(root) || self.resized {
self.old_root = root.into().map(|r| r.id()); self.redraw_all(root, rsc);
} else if widgets.has_updates() { self.old_root = root.map(|r| r.id());
Drawer::new(self, events).redraw_updates();
}
if self.resized {
self.resized = false; self.resized = false;
Drawer::new(self, events).redraw_all(); } else if rsc.widgets().has_updates() {
self.redraw_updates(rsc);
} }
} }
fn redraw_all(&mut self, root: Option<&StrongWidget>, rsc: &mut dyn UiRsc) {
self.clear(rsc);
// free all resources & cache
if let Some(id) = root {
self.draw_inner(0, id.id(), UiRegion::FULL, None, MaskIdx::NONE, None, rsc);
}
}
// TODO: should prolly make a DrawInfo struct or smth for everything other than rsc
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_inner(
&mut self,
layer: usize,
id: WidgetId,
region: UiRegion,
parent: Option<WidgetId>,
mask: MaskIdx,
old_children: Option<Vec<WidgetId>>,
rsc: &mut dyn UiRsc,
) {
let mut old_children = old_children.unwrap_or_default();
if let Some(active) = self.active.get_mut(&id)
&& !rsc.widgets().needs_redraw.contains(&id)
{
// check to see if we can skip drawing first
if active.region == region {
return;
} else if active.region.size() == region.size() {
// TODO: epsilon?
let from = active.region;
self.mov(id, from, region);
return;
}
// if not, then maintain resize and track old children to remove unneeded
let active = self.remove(id, false, rsc).unwrap();
old_children = active.children;
}
// draw widget
self.draw_started.insert(id);
let mut painter = Painter {
state: self,
region,
mask,
layer,
id,
textures: Vec::new(),
primitives: Vec::new(),
children: Vec::new(),
rsc,
};
let mut widget = painter.rsc.widgets().get_dyn_dynamic(id);
widget.draw(&mut painter);
drop(widget);
let Painter {
state: _,
rsc: _,
region,
mask,
textures,
primitives,
children,
layer,
id,
} = painter;
// add to active
let active = ActiveData {
id,
region,
parent,
textures,
primitives,
children,
mask,
layer,
};
// remove old children that weren't kept
for c in &old_children {
if !active.children.contains(c) {
self.remove_rec(*c, rsc);
}
}
rsc.on_draw(&active);
self.active.insert(id, active);
}
fn mov(&mut self, id: WidgetId, from: UiRegion, to: UiRegion) {
let active = self.active.get_mut(&id).unwrap();
for h in &active.primitives {
let region = self.layers[h.layer].region_mut(h);
*region = region.outside(&from).within(&to);
}
active.region = active.region.outside(&from).within(&to);
// SAFETY: children cannot be recursive
let children = unsafe { forget_ref(&active.children) };
for child in children {
self.mov(*child, from, to);
}
}
/// NOTE: instance textures are cleared and self.textures freed
fn remove(&mut self, id: WidgetId, undraw: bool, rsc: &mut dyn UiRsc) -> Option<ActiveData> {
let mut active = self.active.remove(&id);
if let Some(active) = &mut active {
for h in &active.primitives {
let mask = self.layers.free(h);
if mask != MaskIdx::NONE {
rsc.ui_mut().masks.remove(mask);
}
}
active.textures.clear();
rsc.ui_mut().textures.free();
if undraw {
rsc.on_undraw(active);
}
}
active
}
fn remove_rec(&mut self, id: WidgetId, rsc: &mut dyn UiRsc) -> Option<ActiveData> {
self.cache.remove(id);
let inst = self.remove(id, true, rsc);
if let Some(inst) = &inst {
for c in &inst.children {
self.remove_rec(*c, rsc);
}
}
inst
}
fn clear(&mut self, rsc: &mut dyn UiRsc) {
for (_, active) in self.active.drain() {
rsc.on_undraw(&active);
}
self.cache.clear();
self.layers.clear();
rsc.widgets_mut().needs_redraw.clear();
rsc.free();
}
pub fn redraw_updates(&mut self, rsc: &mut dyn UiRsc) {
while let Some(&id) = rsc.widgets().needs_redraw.iter().next() {
self.redraw(id, rsc);
}
rsc.free();
}
pub fn root_changed<'a>(&self, root: impl Into<Option<&'a StrongWidget>>) -> bool { pub fn root_changed<'a>(&self, root: impl Into<Option<&'a StrongWidget>>) -> bool {
root.into().map(|r| r.id()) != self.old_root root.into().map(|r| r.id()) != self.old_root
} }
@@ -103,10 +253,63 @@ impl UiRenderState {
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))
} }
}
pub trait HasRoot { /// redraws a widget that's currently active (drawn)
fn set_root(&mut self, root: StrongWidget); pub fn redraw(&mut self, id: WidgetId, rsc: &mut dyn UiRsc) {
rsc.widgets_mut().needs_redraw.remove(&id);
self.draw_started.remove(&id);
// check if parent depends on the desired size of this, if so then redraw it first
for axis in [Axis::X, Axis::Y] {
if let Some(&(outer, old)) = self.cache.size.axis_dyn(axis).get(&id)
&& let Some(current) = self.active.get(&id)
&& let Some(pid) = current.parent
{
self.cache.size.axis_dyn(axis).remove(&id);
let new = self.size_ctx(id, outer, rsc).len_axis(id, axis);
self.cache.size.axis_dyn(axis).insert(id, (outer, new));
if new != old {
self.redraw(pid, rsc);
}
}
}
if self.draw_started.contains(&id) {
return;
}
let Some(active) = self.remove(id, false, rsc) else {
return;
};
self.draw_inner(
active.layer,
id,
active.region,
active.parent,
active.mask,
Some(active.children),
rsc,
);
}
pub(super) fn size_ctx<'b>(
&'b mut self,
source: WidgetId,
outer: UiVec2,
rsc: &'b mut dyn UiRsc,
) -> SizeCtx<'b> {
let ui = rsc.ui_mut();
SizeCtx {
source,
cache: &mut self.cache,
text: &mut ui.text,
textures: &mut ui.textures,
widgets: &ui.widgets,
outer,
output_size: self.output_size,
id: source,
}
}
} }
impl Default for UiRenderState { impl Default for UiRenderState {

View File

@@ -1,4 +1,4 @@
use crate::{HasRoot, UiRsc}; use crate::UiRsc;
use super::*; use super::*;
use std::marker::Unsize; use std::marker::Unsize;
@@ -22,15 +22,16 @@ pub trait WidgetLike<Rsc: UiRsc, Tag>: Sized {
} }
} }
fn set_root(self, rsc: &mut Rsc) fn set_root(self, rsc: &mut Rsc, root: &mut impl HasRoot) {
where
Rsc: HasRoot,
{
let id = self.add_strong(rsc); let id = self.add_strong(rsc);
rsc.set_root(id); root.set_root(id);
} }
} }
pub trait HasRoot {
fn set_root(&mut self, root: StrongWidget);
}
pub trait WidgetArrLike<Rsc, const LEN: usize, Tag> { pub trait WidgetArrLike<Rsc, const LEN: usize, Tag> {
#[track_caller] #[track_caller]
fn add(self, state: &mut Rsc) -> WidgetArr<LEN>; fn add(self, state: &mut Rsc) -> WidgetArr<LEN>;

View File

@@ -6,7 +6,9 @@ pub struct WidgetTag;
impl<Rsc: UiRsc, W: Widget> WidgetLike<Rsc, WidgetTag> for W { impl<Rsc: UiRsc, W: Widget> WidgetLike<Rsc, WidgetTag> for W {
type Widget = W; type Widget = W;
fn add(self, rsc: &mut Rsc) -> WeakWidget<W> { fn add(self, rsc: &mut Rsc) -> WeakWidget<W> {
rsc.add_widget(self) let w = rsc.ui_mut().widgets.add_weak(self);
rsc.on_add(w);
w
} }
} }

View File

@@ -104,10 +104,10 @@ impl Widgets {
self.vec.get_mut(id.id()) self.vec.get_mut(id.id())
} }
pub fn free(&mut self) { pub fn free_next(&mut self) -> Option<WidgetId> {
for id in self.recv.try_iter() { let next = self.recv.try_recv().ok()?;
self.vec.free(id.id()); self.vec.free(next);
} Some(next)
} }
#[allow(clippy::len_without_is_empty)] #[allow(clippy::len_without_is_empty)]

View File

@@ -10,8 +10,12 @@ struct State {
} }
impl DefaultAppState for State { impl DefaultAppState for State {
fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, _: Proxy<Self::Event>) -> Self { fn new(
rect(Color::RED).set_root(rsc); mut ui_state: DefaultUiState,
rsc: &mut DefaultRsc<Self>,
_: Proxy<Self::Event>,
) -> Self {
rect(Color::RED).set_root(rsc, &mut ui_state);
Self { ui_state } Self { ui_state }
} }
} }

View File

@@ -16,7 +16,11 @@ pub struct Client {
} }
impl DefaultAppState for Client { impl DefaultAppState for Client {
fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, _: Proxy<Self::Event>) -> Self { fn new(
mut ui_state: DefaultUiState,
rsc: &mut DefaultRsc<Self>,
_: Proxy<Self::Event>,
) -> Self {
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),
@@ -197,20 +201,25 @@ impl DefaultAppState for Client {
((tabs.height(40), main.pad(10)).span(Dir::DOWN), info_sect) ((tabs.height(40), main.pad(10)).span(Dir::DOWN), info_sect)
.stack() .stack()
.set_root(rsc); .set_root(rsc, &mut ui_state);
Self { ui_state, info } Self { ui_state, info }
} }
fn window_event(&mut self, _: WindowEvent, rsc: &mut DefaultRsc<Self>) { fn window_event(
&mut self,
_: WindowEvent,
rsc: &mut DefaultRsc<Self>,
render: &mut UiRenderState,
) {
let new = format!( let new = format!(
"widgets: {}\nactive: {}\nviews: {}", "widgets: {}\nactive: {}\nviews: {}",
rsc.ui.num_widgets(), rsc.widgets().len(),
rsc.ui.active_widgets(), render.active_widgets(),
self.ui_state.renderer.ui.view_count() self.ui_state.renderer.ui.view_count(),
); );
if new != *rsc.ui[self.info].content { if new != *rsc.widgets()[self.info].content {
*rsc.ui[self.info].content = new; *rsc.widgets_mut()[self.info].content = new;
} }
} }
} }

View File

@@ -11,11 +11,15 @@ struct State {
} }
impl DefaultAppState for State { impl DefaultAppState for State {
fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, _: Proxy<Self::Event>) -> Self { fn new(
mut ui_state: DefaultUiState,
rsc: &mut DefaultRsc<Self>,
_: Proxy<Self::Event>,
) -> Self {
let rect = rect(Color::RED).add(rsc); let rect = rect(Color::RED).add(rsc);
rect.task_on(CursorSense::click(), async move |mut ctx| { rect.task_on(CursorSense::click(), async move |mut ctx| {
tokio::time::sleep(Duration::from_secs(1)).await; tokio::time::sleep(Duration::from_secs(1)).await;
ctx.task.update(move |_, rsc| { ctx.update(move |_, rsc| {
let rect = rect(rsc); let rect = rect(rsc);
if rect.color == Color::RED { if rect.color == Color::RED {
rect.color = Color::BLUE; rect.color = Color::BLUE;
@@ -24,7 +28,7 @@ impl DefaultAppState for State {
} }
}); });
}) })
.set_root(rsc); .set_root(rsc, &mut ui_state);
Self { ui_state } Self { ui_state }
} }
} }

View File

@@ -33,13 +33,17 @@ impl Test {
} }
impl DefaultAppState for State { impl DefaultAppState for State {
fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, _: Proxy<Self::Event>) -> Self { fn new(
mut ui_state: DefaultUiState,
rsc: &mut DefaultRsc<Self>,
_: Proxy<Self::Event>,
) -> Self {
let test = Test::new(rsc); let test = Test::new(rsc);
test.on(CursorSense::click(), move |_, rsc| { test.on(CursorSense::click(), move |_, rsc| {
test.toggle(rsc); test.toggle(rsc);
}) })
.set_root(rsc); .set_root(rsc, &mut ui_state);
Self { ui_state } Self { ui_state }
} }

View File

@@ -12,12 +12,20 @@ where
fn run(rsc: &mut Rsc, container: WeakWidget<W>, id: Self::Input) { fn run(rsc: &mut Rsc, container: WeakWidget<W>, id: Self::Input) {
rsc.register_event(container, CursorSense::click_or_drag(), move |ctx, rsc| { rsc.register_event(container, CursorSense::click_or_drag(), move |ctx, rsc| {
let region = rsc.ui().window_region(&id).unwrap(); let region = ctx.data.render.window_region(&id).unwrap();
let id_pos = region.top_left; let id_pos = region.top_left;
let container_pos = rsc.ui().window_region(&container).unwrap().top_left; let container_pos = ctx.data.render.window_region(&container).unwrap().top_left;
let pos = ctx.data.pos + container_pos - id_pos; let pos = ctx.data.pos + container_pos - id_pos;
let size = region.size(); let size = region.size();
select(rsc, ctx.state, id, pos, size, ctx.data.sense.is_dragging()); select(
rsc,
ctx.data.render,
ctx.state,
id,
pos,
size,
ctx.data.sense.is_dragging(),
);
}); });
} }
} }
@@ -34,6 +42,7 @@ where
rsc.register_event(id, CursorSense::click_or_drag(), move |ctx, rsc| { rsc.register_event(id, CursorSense::click_or_drag(), move |ctx, rsc| {
select( select(
rsc, rsc,
ctx.data.render,
ctx.state, ctx.state,
id, id,
ctx.data.pos, ctx.data.pos,
@@ -45,7 +54,8 @@ where
} }
fn select( fn select(
rsc: &mut impl HasUi, rsc: &mut impl UiRsc,
render: &UiRenderState,
state: &mut impl HasDefaultUiState, state: &mut impl HasDefaultUiState,
id: WeakWidget<TextEdit>, id: WeakWidget<TextEdit>,
pos: Vec2, pos: Vec2,
@@ -57,7 +67,7 @@ fn select(
let recent = (now - state.last_click) < Duration::from_millis(300); let recent = (now - state.last_click) < Duration::from_millis(300);
state.last_click = now; state.last_click = now;
id.edit(rsc).select(pos, size, dragging, recent); id.edit(rsc).select(pos, size, dragging, recent);
if let Some(region) = rsc.ui().window_region(&id) { if let Some(region) = render.window_region(&id) {
state.window.set_ime_allowed(true); state.window.set_ime_allowed(true);
state.window.set_ime_cursor_area( state.window.set_ime_cursor_area(
LogicalPosition::<f32>::from(region.top_left.tuple()), LogicalPosition::<f32>::from(region.top_left.tuple()),

View File

@@ -30,6 +30,7 @@ pub use task::*;
pub type Proxy<Event> = EventLoopProxy<Event>; pub type Proxy<Event> = EventLoopProxy<Event>;
pub struct DefaultUiState { pub struct DefaultUiState {
pub root: Option<StrongWidget>,
pub renderer: UiRenderer, pub renderer: UiRenderer,
pub input: Input, pub input: Input,
pub focus: Option<WeakWidget<TextEdit>>, pub focus: Option<WeakWidget<TextEdit>>,
@@ -39,10 +40,17 @@ pub struct DefaultUiState {
pub last_click: Instant, pub last_click: Instant,
} }
impl HasRoot for DefaultUiState {
fn set_root(&mut self, root: StrongWidget) {
self.root = Some(root);
}
}
impl DefaultUiState { impl DefaultUiState {
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 {
root: None,
renderer: UiRenderer::new(window.clone()), renderer: UiRenderer::new(window.clone()),
window, window,
input: Input::default(), input: Input::default(),
@@ -64,18 +72,30 @@ pub trait DefaultAppState: HasDefaultUiState {
fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, proxy: Proxy<Self::Event>) fn new(ui_state: DefaultUiState, rsc: &mut DefaultRsc<Self>, proxy: Proxy<Self::Event>)
-> Self; -> Self;
#[allow(unused_variables)] #[allow(unused_variables)]
fn event(&mut self, event: Self::Event, rsc: &mut DefaultRsc<Self>) {} fn event(
&mut self,
event: Self::Event,
rsc: &mut DefaultRsc<Self>,
render: &mut UiRenderState,
) {
}
#[allow(unused_variables)] #[allow(unused_variables)]
fn exit(&mut self, rsc: &mut DefaultRsc<Self>) {} fn exit(&mut self, rsc: &mut DefaultRsc<Self>, render: &mut UiRenderState) {}
#[allow(unused_variables)] #[allow(unused_variables)]
fn window_event(&mut self, event: WindowEvent, rsc: &mut DefaultRsc<Self>) {} fn window_event(
&mut self,
event: WindowEvent,
rsc: &mut DefaultRsc<Self>,
render: &mut UiRenderState,
) {
}
fn window_attributes() -> WindowAttributes { fn window_attributes() -> WindowAttributes {
Default::default() Default::default()
} }
} }
pub struct DefaultRsc<State: 'static> { pub struct DefaultRsc<State: 'static> {
pub ui: Ui, pub ui: UiData,
pub events: EventManager<Self>, pub events: EventManager<Self>,
pub tasks: Tasks<Self>, pub tasks: Tasks<Self>,
_state: PhantomData<State>, _state: PhantomData<State>,
@@ -96,14 +116,26 @@ impl<State> DefaultRsc<State> {
} }
} }
impl<State> HasUi for DefaultRsc<State> { impl<State> UiRsc for DefaultRsc<State> {
fn ui(&self) -> &Ui { fn ui(&self) -> &UiData {
&self.ui &self.ui
} }
fn ui_mut(&mut self) -> &mut Ui { fn ui_mut(&mut self) -> &mut UiData {
&mut self.ui &mut self.ui
} }
fn on_draw(&mut self, active: &ActiveData) {
self.events.draw(active);
}
fn on_undraw(&mut self, active: &ActiveData) {
self.events.undraw(active);
}
fn on_remove(&mut self, id: WidgetId) {
self.events.remove(id);
}
} }
impl<State: 'static> HasState for DefaultRsc<State> { impl<State: 'static> HasState for DefaultRsc<State> {
@@ -128,6 +160,7 @@ impl<State: 'static> HasTasks for DefaultRsc<State> {
pub struct DefaultApp<State: DefaultAppState> { pub struct DefaultApp<State: DefaultAppState> {
rsc: DefaultRsc<State>, rsc: DefaultRsc<State>,
render: UiRenderState,
state: State, state: State,
task_recv: TaskMsgReceiver<DefaultRsc<State>>, task_recv: TaskMsgReceiver<DefaultRsc<State>>,
} }
@@ -142,23 +175,32 @@ impl<State: DefaultAppState> AppState for DefaultApp<State> {
let default_state = DefaultUiState::new(window); let default_state = DefaultUiState::new(window);
let (mut rsc, task_recv) = DefaultRsc::init(default_state.window.clone()); let (mut rsc, task_recv) = DefaultRsc::init(default_state.window.clone());
let state = State::new(default_state, &mut rsc, proxy); let state = State::new(default_state, &mut rsc, proxy);
let render = UiRenderState::new();
Self { Self {
rsc, rsc,
state, state,
render,
task_recv, task_recv,
} }
} }
fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) { fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) {
self.state.event(event, &mut self.rsc); self.state.event(event, &mut self.rsc, &mut self.render);
} }
fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) { fn window_event(&mut self, event: WindowEvent, event_loop: &ActiveEventLoop) {
for update in self.task_recv.try_iter() { let Self {
update(&mut self.state, &mut self.rsc); rsc,
render,
state,
task_recv,
} = self;
for update in task_recv.try_iter() {
update(state, rsc);
} }
let ui_state = self.state.default_state_mut(); let ui_state = state.default_state_mut();
let input_changed = ui_state.input.event(&event); let input_changed = ui_state.input.event(&event);
let cursor_state = ui_state.cursor_state().clone(); let cursor_state = ui_state.cursor_state().clone();
let old = ui_state.focus; let old = ui_state.focus;
@@ -167,45 +209,43 @@ impl<State: DefaultAppState> AppState for DefaultApp<State> {
} }
if input_changed { if input_changed {
let window_size = ui_state.window_size(); let window_size = ui_state.window_size();
self.rsc render.run_sensors(rsc, state, cursor_state, window_size);
.run_sensors(&mut self.state, cursor_state, window_size);
} }
let ui = &mut self.rsc.ui; let ui_state = state.default_state_mut();
let ui_state = self.state.default_state_mut();
if old != ui_state.focus if old != ui_state.focus
&& let Some(old) = old && let Some(old) = old
{ {
old.edit(ui).deselect(); old.edit(rsc).deselect();
} }
match &event { match &event {
WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => {
ui.update(&mut self.rsc.events); render.update(&ui_state.root, rsc);
ui_state.renderer.update(ui); ui_state.renderer.update(&mut rsc.ui, render);
ui_state.renderer.draw(); ui_state.renderer.draw();
} }
WindowEvent::Resized(size) => { WindowEvent::Resized(size) => {
ui.resize((size.width, size.height)); render.resize((size.width, size.height));
ui_state.renderer.resize(size) ui_state.renderer.resize(size)
} }
WindowEvent::KeyboardInput { event, .. } => { WindowEvent::KeyboardInput { event, .. } => {
if let Some(sel) = ui_state.focus if let Some(sel) = ui_state.focus
&& event.state.is_pressed() && event.state.is_pressed()
{ {
let mut text = sel.edit(ui); let mut text = sel.edit(rsc);
match text.apply_event(event, &ui_state.input.modifiers) { match text.apply_event(event, &ui_state.input.modifiers) {
TextInputResult::Unfocus => { TextInputResult::Unfocus => {
ui_state.focus = None; ui_state.focus = None;
ui_state.window.set_ime_allowed(false); ui_state.window.set_ime_allowed(false);
} }
TextInputResult::Submit => { TextInputResult::Submit => {
self.rsc.run_event::<Submit>(sel, (), &mut self.state); rsc.run_event::<Submit>(sel, (), state);
} }
TextInputResult::Paste => { TextInputResult::Paste => {
if let Ok(t) = ui_state.clipboard.get_text() { if let Ok(t) = ui_state.clipboard.get_text() {
text.insert(&t); text.insert(&t);
} }
self.rsc.run_event::<Edited>(sel, (), &mut self.state); rsc.run_event::<Edited>(sel, (), state);
} }
TextInputResult::Copy(text) => { TextInputResult::Copy(text) => {
if let Err(err) = ui_state.clipboard.set_text(text) { if let Err(err) = ui_state.clipboard.set_text(text) {
@@ -213,7 +253,7 @@ impl<State: DefaultAppState> AppState for DefaultApp<State> {
} }
} }
TextInputResult::Used => { TextInputResult::Used => {
self.rsc.run_event::<Edited>(sel, (), &mut self.state); rsc.run_event::<Edited>(sel, (), state);
} }
TextInputResult::Unused => {} TextInputResult::Unused => {}
} }
@@ -221,7 +261,7 @@ impl<State: DefaultAppState> AppState for DefaultApp<State> {
} }
WindowEvent::Ime(ime) => { WindowEvent::Ime(ime) => {
if let Some(sel) = ui_state.focus { if let Some(sel) = ui_state.focus {
let mut text = sel.edit(ui); let mut text = sel.edit(rsc);
match ime { match ime {
Ime::Enabled | Ime::Disabled => (), Ime::Enabled | Ime::Disabled => (),
Ime::Preedit(content, _pos) => { Ime::Preedit(content, _pos) => {
@@ -237,15 +277,15 @@ impl<State: DefaultAppState> AppState for DefaultApp<State> {
} }
_ => (), _ => (),
} }
self.state.window_event(event, &mut self.rsc); state.window_event(event, rsc, render);
let ui_state = self.state.default_state_mut(); let ui_state = self.state.default_state_mut();
if self.rsc.ui.needs_redraw() { if render.needs_redraw(&ui_state.root, rsc.widgets()) {
ui_state.renderer.window().request_redraw(); ui_state.renderer.window().request_redraw();
} }
ui_state.input.end_frame(); ui_state.input.end_frame();
} }
fn exit(&mut self) { fn exit(&mut self) {
self.state.exit(&mut self.rsc); self.state.exit(&mut self.rsc, &mut self.render);
} }
} }

View File

@@ -1,4 +1,4 @@
use iris_core::{Ui, UiLimits, UiRenderNode}; use iris_core::{UiData, UiLimits, UiRenderNode, UiRenderState};
use pollster::FutureExt; use pollster::FutureExt;
use std::sync::Arc; use std::sync::Arc;
use wgpu::*; use wgpu::*;
@@ -17,8 +17,8 @@ pub struct UiRenderer {
} }
impl UiRenderer { impl UiRenderer {
pub fn update(&mut self, ui: &mut Ui) { pub fn update(&mut self, ui: &mut UiData, render: &mut UiRenderState) {
self.ui.update(&self.device, &self.queue, ui); self.ui.update(&self.device, &self.queue, ui, render);
} }
pub fn draw(&mut self) { pub fn draw(&mut self) {

View File

@@ -26,9 +26,9 @@ pub enum CursorSense {
pub struct CursorSenses(Vec<CursorSense>); pub struct CursorSenses(Vec<CursorSense>);
impl Event for CursorSenses { impl Event for CursorSenses {
type Data = CursorData; type Data<'a> = CursorData<'a>;
type State = SensorState; type State = SensorState;
fn should_run(&self, data: &Self::Data) -> Option<Self::Data> { fn should_run<'a>(&self, data: &Self::Data<'a>) -> Option<Self::Data<'a>> {
if let Some(sense) = should_run(self, &data.cursor, data.hover) { if let Some(sense) = should_run(self, &data.cursor, data.hover) {
let mut data = data.clone(); let mut data = data.clone();
data.sense = sense; data.sense = sense;
@@ -129,7 +129,7 @@ pub struct SensorState {
} }
#[derive(Clone)] #[derive(Clone)]
pub struct CursorData { pub struct CursorData<'a> {
/// where this widget was hit /// where this widget was hit
pub pos: Vec2, pub pos: Vec2,
pub size: Vec2, pub size: Vec2,
@@ -138,20 +138,36 @@ pub struct CursorData {
pub cursor: CursorState, pub cursor: CursorState,
/// the first sense that triggered this /// the first sense that triggered this
pub sense: CursorSense, pub sense: CursorSense,
pub render: &'a UiRenderState,
} }
pub trait SensorUi<Rsc: HasEvents> { pub trait SensorUi {
fn run_sensors(&mut self, state: &mut Rsc::State, cursor: CursorState, window_size: Vec2); fn run_sensors<Rsc: HasEvents>(
&self,
rsc: &mut Rsc,
state: &mut Rsc::State,
cursor: CursorState,
window_size: Vec2,
);
} }
impl<Rsc: HasEvents> SensorUi<Rsc> for Rsc { impl SensorUi for UiRenderState {
fn run_sensors(&mut self, state: &mut Rsc::State, cursor: CursorState, window_size: Vec2) { fn run_sensors<Rsc: HasEvents>(
let layers = std::mem::take(&mut self.ui_mut().layers); &self,
let mut active = std::mem::take(&mut self.events_mut().get_type::<CursorSense>().active); rsc: &mut Rsc,
for layer in layers.indices().rev() { state: &mut Rsc::State,
cursor: CursorState,
window_size: Vec2,
) {
// in order to remove this take, need to store active list in UiRenderState somehow
// this would probably be done through a generic parameter that adds yet another rsc /
// state like thing, but local to render state, and is passed to UiRsc events so you can
// update it there?
let mut active = std::mem::take(&mut rsc.events_mut().get_type::<CursorSense>().active);
for layer in self.layers.indices().rev() {
let mut sensed = false; let mut sensed = false;
for (id, sensor) in active.get_mut(&layer).into_flat_iter() { for (id, sensor) in active.get_mut(&layer).into_flat_iter() {
let shape = self.ui().active.get(id).unwrap().region; let shape = self.active.get(id).unwrap().region;
let region = shape.to_px(window_size); let region = shape.to_px(window_size);
let in_shape = cursor.exists && region.contains(cursor.pos); let in_shape = cursor.exists && region.contains(cursor.pos);
sensor.hover.update(in_shape); sensor.hover.update(in_shape);
@@ -171,15 +187,15 @@ impl<Rsc: HasEvents> SensorUi<Rsc> for Rsc {
// this does not have any meaning; // this does not have any meaning;
// might wanna set up Event to have a prepare stage // might wanna set up Event to have a prepare stage
sense: CursorSense::Hovering, sense: CursorSense::Hovering,
render: self,
}; };
self.run_event::<CursorSense>(*id, data, state); rsc.run_event::<CursorSense>(*id, data, state);
} }
if sensed { if sensed {
break; break;
} }
} }
self.events_mut().get_type::<CursorSense>().active = active; rsc.events_mut().get_type::<CursorSense>().active = active;
self.ui_mut().layers = layers;
} }
} }

View File

@@ -2,13 +2,13 @@ use iris_core::*;
use iris_macro::*; use iris_macro::*;
use std::sync::Arc; use std::sync::Arc;
use crate::default::{TaskCtx, Tasks}; use crate::default::{TaskCtx, TaskUpdate, Tasks};
pub trait Eventable<Rsc: HasEvents, Tag>: WidgetLike<Rsc, Tag> { pub trait Eventable<Rsc: HasEvents, Tag>: WidgetLike<Rsc, Tag> {
fn on<E: EventLike>( fn on<E: EventLike>(
self, self,
event: E, event: E,
f: impl WidgetEventFn<Rsc, <E::Event as Event>::Data, Self::Widget>, f: impl for<'a> WidgetEventFn<Rsc, <E::Event as Event>::Data<'a>, Self::Widget>,
) -> impl WidgetIdFn<Rsc, Self::Widget> { ) -> impl WidgetIdFn<Rsc, Self::Widget> {
move |rsc| { move |rsc| {
let id = self.add(rsc); let id = self.add(rsc);
@@ -30,24 +30,22 @@ impl<WL: WidgetLike<Rsc, Tag>, Rsc: HasEvents, Tag> Eventable<Rsc, Tag> for WL {
widget_trait! { widget_trait! {
pub trait TaskEventable<Rsc: HasEvents + HasTasks>; pub trait TaskEventable<Rsc: HasEvents + HasTasks>;
fn task_on<E: EventLike, F: AsyncWidgetEventFn<Rsc, <E::Event as Event>::Data, WL::Widget>>( fn task_on<'a, E: EventLike, F: AsyncWidgetEventFn<Rsc, WL::Widget>>(
self, self,
event: E, event: E,
f: F, f: F,
) -> impl WidgetIdFn<Rsc, WL::Widget> ) -> impl WidgetIdFn<Rsc, WL::Widget>
where <E::Event as Event>::Data: Send, where <E::Event as Event>::Data<'a>: Send,
for<'a> F::CallRefFuture<'a>: Send, for<'b> F::CallRefFuture<'b>: Send,
{ {
let f = Arc::new(f); let f = Arc::new(f);
move |rsc| { move |rsc| {
let id = self.add(rsc); let id = self.add(rsc);
rsc.register_event(id, event.into_event(), move |ctx, rsc| { rsc.register_event(id, event.into_event(), move |_, rsc| {
let data = ctx.data;
let f = f.clone(); let f = f.clone();
rsc.tasks_mut().spawn(async move |task| { rsc.tasks_mut().spawn(async move |task| {
f(AsyncEventIdCtx { f(AsyncEventIdCtx {
widget: id, widget: id,
data,
task, task,
}).await; }).await;
}); });
@@ -61,21 +59,22 @@ pub trait HasTasks: Sized + HasState + HasEvents {
fn tasks_mut(&mut self) -> &mut Tasks<Self>; fn tasks_mut(&mut self) -> &mut Tasks<Self>;
} }
pub trait AsyncWidgetEventFn<Rsc: HasEvents, Data, W: ?Sized>: pub trait AsyncWidgetEventFn<Rsc: HasEvents, W: ?Sized>:
AsyncFn(AsyncEventIdCtx<Rsc, Data, W>) + Send + Sync + 'static AsyncFn(AsyncEventIdCtx<Rsc, W>) + Send + Sync + 'static
{ {
} }
impl< impl<Rsc: HasEvents, F: AsyncFn(AsyncEventIdCtx<Rsc, W>) + Send + Sync + 'static, W: ?Sized>
Rsc: HasEvents, AsyncWidgetEventFn<Rsc, W> for F
F: AsyncFn(AsyncEventIdCtx<Rsc, Data, W>) + Send + Sync + 'static,
Data,
W: ?Sized,
> AsyncWidgetEventFn<Rsc, Data, W> for F
{ {
} }
pub struct AsyncEventIdCtx<Rsc: HasEvents, Data, W: ?Sized> { pub struct AsyncEventIdCtx<Rsc: HasEvents, W: ?Sized> {
pub widget: WeakWidget<W>, pub widget: WeakWidget<W>,
pub data: Data, task: TaskCtx<Rsc>,
pub task: TaskCtx<Rsc>, }
impl<Rsc: HasEvents, W: ?Sized> AsyncEventIdCtx<Rsc, W> {
pub fn update(&mut self, f: impl TaskUpdate<Rsc> + 'static) {
self.task.update(f);
}
} }

View File

@@ -19,10 +19,10 @@ impl Widget for Image {
} }
} }
pub fn image<State: HasUi>(image: impl LoadableImage) -> impl WidgetFn<State, Image> { pub fn image<State: UiRsc>(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 |state| Image { move |state| Image {
handle: state.ui_mut().add_texture(image), handle: state.ui_mut().textures.add(image),
} }
} }

View File

@@ -51,7 +51,7 @@ impl<State, O, H: WidgetOption<State>> TextBuilder<State, O, H> {
} }
} }
impl<Rsc: HasUi, O> TextBuilder<Rsc, O> { impl<Rsc: UiRsc, O> TextBuilder<Rsc, O> {
pub fn hint<W: WidgetLike<Rsc, Tag>, Tag>( pub fn hint<W: WidgetLike<Rsc, Tag>, Tag>(
self, self,
hint: W, hint: W,
@@ -75,7 +75,7 @@ pub trait TextBuilderOutput<State>: Sized {
} }
pub struct TextOutput; pub struct TextOutput;
impl<Rsc: HasUi> TextBuilderOutput<Rsc> for TextOutput { impl<Rsc: UiRsc> TextBuilderOutput<Rsc> for TextOutput {
type Output = Text; type Output = Text;
fn run<H: WidgetOption<Rsc>>( fn run<H: WidgetOption<Rsc>>(
@@ -103,7 +103,7 @@ pub struct TextEditOutput {
mode: EditMode, mode: EditMode,
} }
impl<State: HasUi> TextBuilderOutput<State> for TextEditOutput { impl<State: UiRsc> TextBuilderOutput<State> for TextEditOutput {
type Output = TextEdit; type Output = TextEdit;
fn run<H: WidgetOption<State>>( fn run<H: WidgetOption<State>>(

View File

@@ -617,11 +617,11 @@ impl DerefMut for TextEdit {
} }
pub trait TextEditable { pub trait TextEditable {
fn edit<'a>(&self, ui: &'a mut impl HasUi) -> TextEditCtx<'a>; fn edit<'a>(&self, ui: &'a mut impl UiRsc) -> TextEditCtx<'a>;
} }
impl<I: IdLike<Widget = TextEdit>> TextEditable for I { impl<I: IdLike<Widget = TextEdit>> TextEditable for I {
fn edit<'a>(&self, ui: &'a mut impl HasUi) -> TextEditCtx<'a> { fn edit<'a>(&self, ui: &'a mut impl UiRsc) -> TextEditCtx<'a> {
let ui = ui.ui_mut(); let ui = ui.ui_mut();
TextEditCtx { TextEditCtx {
text: ui.widgets.get_mut(self).unwrap(), text: ui.widgets.get_mut(self).unwrap(),

View File

@@ -3,7 +3,7 @@ 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<Rsc: HasUi + 'static>; pub trait CoreWidget<Rsc: UiRsc + 'static>;
fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<Rsc, Pad> { fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<Rsc, Pad> {
|state| Pad { |state| Pad {
@@ -26,7 +26,7 @@ widget_trait! {
fn label(self, label: impl Into<String>) -> impl WidgetIdFn<Rsc, WL::Widget> { fn label(self, label: impl Into<String>) -> impl WidgetIdFn<Rsc, WL::Widget> {
|state| { |state| {
let id = self.add(state); let id = self.add(state);
state.ui_mut().set_label(id, label.into()); state.ui_mut().widgets.set_label(id, label.into());
id id
} }
} }
@@ -127,7 +127,7 @@ widget_trait! {
fn set_ptr(self, ptr: WeakWidget<WidgetPtr>, state: &mut Rsc) { fn set_ptr(self, ptr: WeakWidget<WidgetPtr>, state: &mut Rsc) {
let id = self.add_strong(state); let id = self.add_strong(state);
state.ui_mut()[ptr].inner = Some(id); state.ui_mut().widgets[ptr].inner = Some(id);
} }
} }