strong & weak widgets

This commit is contained in:
2025-12-11 07:16:06 -05:00
parent a85e129026
commit 36668c82f4
19 changed files with 293 additions and 294 deletions

View File

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

View File

@@ -1,9 +1,8 @@
use std::{hash::Hash, rc::Rc};
use crate::{
Ui, UiModule, WidgetHandle, WidgetView,
Ui, UiModule, WidgetView,
util::{HashMap, Id},
};
use std::{hash::Hash, rc::Rc};
pub trait Event: Sized {
type Module<Ctx: 'static>: EventModule<Self, Ctx>;
@@ -16,9 +15,8 @@ pub struct EventCtx<'a, Ctx, Data> {
pub data: Data,
}
pub type ECtx<'a, Ctx, Data, W> = EventIdCtx<'a, Ctx, Data, W>;
pub struct EventIdCtx<'a, Ctx, Data, W> {
pub id: &'a WidgetView<W>,
pub struct EventIdCtx<'a, Ctx, Data, W: ?Sized> {
pub id: WidgetView<W>,
pub ui: &'a mut Ui,
pub state: &'a mut Ctx,
pub data: Data,
@@ -27,8 +25,11 @@ pub struct EventIdCtx<'a, Ctx, Data, W> {
pub trait EventFn<Ctx, Data>: Fn(EventCtx<Ctx, Data>) + 'static {}
impl<F: Fn(EventCtx<Ctx, Data>) + 'static, Ctx, Data> EventFn<Ctx, Data> for F {}
pub trait WidgetEventFn<Ctx, Data, W>: Fn(EventIdCtx<Ctx, Data, W>) + 'static {}
impl<F: Fn(EventIdCtx<Ctx, Data, W>) + 'static, Ctx, Data, W> WidgetEventFn<Ctx, Data, W> for F {}
pub trait WidgetEventFn<Ctx, Data, W: ?Sized>: Fn(EventIdCtx<Ctx, Data, W>) + 'static {}
impl<F: Fn(EventIdCtx<Ctx, Data, W>) + 'static, Ctx, Data, W: ?Sized> WidgetEventFn<Ctx, Data, W>
for F
{
}
pub trait DefaultEvent: Hash + Eq + 'static {
type Data: Clone = ();
@@ -129,7 +130,7 @@ impl Ui {
pub fn run_event<E: Event, Ctx: 'static, W>(
&mut self,
ctx: &mut Ctx,
id: &WidgetHandle<W>,
id: WidgetView<W>,
event: E,
data: E::Data,
) {

View File

@@ -387,17 +387,17 @@ impl<'a, 'c> Painter<'a, 'c> {
}
/// Draws a widget within this widget's region.
pub fn widget<W>(&mut self, id: &WidgetHandle<W>) {
pub fn widget<W: ?Sized>(&mut self, id: &WidgetHandle<W>) {
self.widget_at(id, self.region);
}
/// Draws a widget somewhere within this one.
/// Useful for drawing child widgets in select areas.
pub fn widget_within<W>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
pub fn widget_within<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
self.widget_at(id, region.within(&self.region));
}
fn widget_at<W>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
fn widget_at<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
self.children.push(id.id());
self.ctx
.draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None);
@@ -427,11 +427,11 @@ impl<'a, 'c> Painter<'a, 'c> {
self.region
}
pub fn size<W>(&mut self, id: &WidgetHandle<W>) -> Size {
pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size {
self.size_ctx().size(id)
}
pub fn len_axis<W>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
match axis {
Axis::X => self.size_ctx().width(id),
Axis::Y => self.size_ctx().height(id),
@@ -550,22 +550,22 @@ impl SizeCtx<'_> {
len
}
pub fn width<W>(&mut self, id: &WidgetHandle<W>) -> Len {
pub fn width<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Len {
self.width_inner(id.id())
}
pub fn height<W>(&mut self, id: &WidgetHandle<W>) -> Len {
pub fn height<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Len {
self.height_inner(id.id())
}
pub fn len_axis<W>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
pub fn len_axis<W: ?Sized>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
match axis {
Axis::X => self.width(id),
Axis::Y => self.height(id),
}
}
pub fn size<W>(&mut self, id: &WidgetHandle<W>) -> Size {
pub fn size<W: ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size {
Size {
x: self.width(id),
y: self.height(id),

View File

@@ -5,7 +5,7 @@ use crate::{
};
use image::DynamicImage;
use std::{
any::{Any, TypeId},
any::Any,
ops::{Index, IndexMut},
sync::mpsc::{Receiver, Sender, channel},
};
@@ -26,26 +26,22 @@ impl Ui {
}
/// useful for debugging
pub fn set_label<W>(&mut self, id: &WidgetHandle<W>, label: String) {
pub fn set_label<W: ?Sized>(&mut self, id: &WidgetHandle<W>, label: String) {
self.data.widgets.data_mut(&id.id()).unwrap().label = label;
}
pub fn label<W>(&self, id: &WidgetHandle<W>) -> &String {
pub fn label<W: ?Sized>(&self, id: &WidgetHandle<W>) -> &String {
&self.data.widgets.data(&id.id()).unwrap().label
}
pub fn add_widget<W: Widget>(&mut self, w: W) -> WidgetHandle<W> {
self.push(w)
}
pub fn push<W: Widget>(&mut self, w: W) -> WidgetHandle<W> {
let id = self.new_id();
self.data.widgets.insert(id.id(), w);
id
}
pub fn set_root<Tag>(&mut self, w: impl WidgetLike<Tag>) {
self.root = Some(w.add(self).any());
self.root = Some(w.add(self));
self.full_redraw = true;
}
@@ -53,29 +49,31 @@ impl Ui {
Self::default()
}
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget> {
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget>
where
I::Widget: Sized,
{
self.data.widgets.get(id)
}
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget> {
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget>
where
I::Widget: Sized,
{
self.data.widgets.get_mut(id)
}
fn new_id<W: Widget>(&mut self) -> WidgetHandle<W> {
WidgetHandle::new(
self.data.widgets.reserve(),
TypeId::of::<W>(),
self.send.clone(),
)
WidgetHandle::new(self.data.widgets.reserve(), self.send.clone())
}
pub fn add_texture(&mut self, image: DynamicImage) -> TextureHandle {
self.data.textures.add(image)
}
pub fn register_event<W, E: Event, Ctx: 'static>(
pub fn register_event<I: IdLike, E: Event, Ctx: 'static>(
&mut self,
id: &WidgetHandle<W>,
id: &I,
event: E,
f: impl EventFn<Ctx, E::Data>,
) {
@@ -171,17 +169,23 @@ impl Ui {
}
}
impl<I: IdLike> Index<&I> for Ui {
impl<I: IdLike> Index<I> for Ui
where
I::Widget: Sized,
{
type Output = I::Widget;
fn index(&self, id: &I) -> &Self::Output {
self.get(id).unwrap()
fn index(&self, id: I) -> &Self::Output {
self.get(&id).unwrap()
}
}
impl<I: IdLike> IndexMut<&I> for Ui {
fn index_mut(&mut self, id: &I) -> &mut Self::Output {
self.get_mut(id).unwrap()
impl<I: IdLike> IndexMut<I> for Ui
where
I::Widget: Sized,
{
fn index_mut(&mut self, id: I) -> &mut Self::Output {
self.get_mut(&id).unwrap()
}
}

130
core/src/widget/handle.rs Normal file
View File

@@ -0,0 +1,130 @@
use std::{marker::Unsize, mem::MaybeUninit, ops::CoerceUnsized, sync::mpsc::Sender};
use crate::{
Ui, Widget,
util::{Id, RefCounter},
};
/// An identifier for a widget that can index a UI to get the associated widget.
/// It should always remain valid; it keeps a ref count and removes the widget from the UI if all
/// references are dropped.
///
/// W does not need to implement widget so that AnyWidget is valid;
/// Instead, add generic bounds on methods that take an ID if they need specific data.
///
/// TODO: ergonomic clones when they get put in rust-analyzer & don't cause ICEs?
pub struct WidgetHandle<W: ?Sized = dyn Widget> {
pub(super) id: Id,
counter: RefCounter,
send: Sender<Id>,
ty: *const W,
}
pub struct WidgetView<W: ?Sized = dyn Widget> {
pub(super) id: Id,
#[allow(unused)]
ty: *const W,
}
impl<W: Widget + ?Sized + Unsize<dyn Widget>> WidgetHandle<W> {
pub fn any(self) -> WidgetHandle<dyn Widget> {
self
}
}
impl<W: ?Sized> WidgetHandle<W> {
pub(crate) fn new(id: Id, send: Sender<Id>) -> Self {
Self {
id,
counter: RefCounter::new(),
send,
ty: unsafe { MaybeUninit::zeroed().assume_init() },
}
}
pub fn as_any(&self) -> &WidgetHandle<dyn Widget> {
// SAFETY: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) }
}
pub fn id(&self) -> Id {
self.id
}
pub fn refs(&self) -> u32 {
self.counter.refs()
}
pub fn weak(&self) -> WidgetView<W> {
let Self { ty, id, .. } = *self;
WidgetView { ty, id }
}
pub fn handles(self) -> (Self, WidgetView<W>) {
let weak = self.weak();
(self, weak)
}
}
impl<W: ?Sized> WidgetView<W> {
pub fn id(&self) -> Id {
self.id
}
}
impl<W: ?Sized> Drop for WidgetHandle<W> {
fn drop(&mut self) {
if self.counter.drop() {
let _ = self.send.send(self.id);
}
}
}
pub trait WidgetIdFn<W: ?Sized = dyn Widget>: FnOnce(&mut Ui) -> WidgetHandle<W> {}
impl<W: ?Sized, F: FnOnce(&mut Ui) -> WidgetHandle<W>> WidgetIdFn<W> for F {}
pub trait IdLike {
type Widget: Widget + ?Sized + 'static;
fn id(&self) -> Id;
}
impl<W: Widget + ?Sized> IdLike for WidgetHandle<W> {
type Widget = W;
fn id(&self) -> Id {
self.id
}
}
impl<W: Widget + ?Sized> IdLike for WidgetView<W> {
type Widget = W;
fn id(&self) -> Id {
self.id
}
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetView<U>> for WidgetView<T> {}
impl<W: ?Sized> Clone for WidgetView<W> {
fn clone(&self) -> Self {
*self
}
}
impl<W: ?Sized> Copy for WidgetView<W> {}
impl<W: ?Sized> PartialEq for WidgetView<W> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<W> PartialEq for WidgetHandle<W> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<W> std::fmt::Debug for WidgetHandle<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.id.fmt(f)
}
}

View File

@@ -1,152 +0,0 @@
use std::{any::TypeId, marker::PhantomData, sync::mpsc::Sender};
use crate::{
Ui, Widget,
util::{Id, RefCounter},
};
pub struct AnyWidget;
/// An identifier for a widget that can index a UI to get the associated widget.
/// It should always remain valid; it keeps a ref count and removes the widget from the UI if all
/// references are dropped.
///
/// W does not need to implement widget so that AnyWidget is valid;
/// Instead, add generic bounds on methods that take an ID if they need specific data.
///
/// TODO: ergonomic clones when they get put in rust-analyzer & don't cause ICEs?
#[repr(C)]
pub struct WidgetHandle<W = AnyWidget> {
pub(super) ty: TypeId,
pub(super) id: Id,
counter: RefCounter,
send: Sender<Id>,
_pd: PhantomData<W>,
}
#[repr(C)]
pub struct WidgetView<W = AnyWidget> {
pub(super) ty: TypeId,
pub(super) id: Id,
counter: RefCounter,
send: Sender<Id>,
_pd: PhantomData<W>,
}
impl<W> PartialEq for WidgetHandle<W> {
fn eq(&self, other: &Self) -> bool {
self.ty == other.ty && self.id == other.id
}
}
impl<W> std::fmt::Debug for WidgetHandle<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.id.fmt(f)
}
}
impl<W> Clone for WidgetHandle<W> {
fn clone(&self) -> Self {
Self {
id: self.id,
ty: self.ty,
counter: self.counter.clone(),
send: self.send.clone(),
_pd: PhantomData,
}
}
}
impl<W> WidgetHandle<W> {
pub(crate) fn new(id: Id, ty: TypeId, send: Sender<Id>) -> Self {
Self {
ty,
id,
counter: RefCounter::new(),
send,
_pd: PhantomData,
}
}
pub fn any(self) -> WidgetHandle<AnyWidget> {
self.cast_type()
}
pub fn as_any(&self) -> &WidgetHandle<AnyWidget> {
// SAFETY: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) }
}
pub fn id(&self) -> Id {
self.id
}
pub(super) fn cast_type<W2>(self) -> WidgetHandle<W2> {
// SAFETY: self is repr(C) and generic only used for phantom data
unsafe { std::mem::transmute(self) }
}
pub fn refs(&self) -> u32 {
self.counter.refs()
}
pub fn weak(&self) -> WidgetView<W> {
let Self {
ty,
id,
ref counter,
ref send,
_pd,
} = *self;
WidgetView {
ty,
id,
counter: counter.quiet_clone(),
send: send.clone(),
_pd,
}
}
}
impl<W> Drop for WidgetHandle<W> {
fn drop(&mut self) {
if self.counter.drop() {
let _ = self.send.send(self.id);
}
}
}
pub trait WidgetIdFn<W>: FnOnce(&mut Ui) -> WidgetHandle<W> {}
impl<W, F: FnOnce(&mut Ui) -> WidgetHandle<W>> WidgetIdFn<W> for F {}
pub trait WidgetRet: FnOnce(&mut Ui) -> WidgetHandle<AnyWidget> {}
impl<F: FnOnce(&mut Ui) -> WidgetHandle<AnyWidget>> WidgetRet for F {}
pub trait WidgetIdLike<W> {
fn id(self, send: &Sender<Id>) -> WidgetHandle<W>;
}
impl<W> WidgetIdLike<W> for &WidgetHandle<W> {
fn id(self, _: &Sender<Id>) -> WidgetHandle<W> {
self.clone()
}
}
pub trait IdLike {
type Widget: Widget + 'static;
fn id(&self) -> Id;
}
impl<W: Widget> IdLike for WidgetHandle<W> {
type Widget = W;
fn id(&self) -> Id {
self.id
}
}
impl<W: Widget> IdLike for WidgetView<W> {
type Widget = W;
fn id(&self) -> Id {
self.id
}
}

View File

@@ -1,7 +1,8 @@
use super::*;
use std::marker::Unsize;
pub trait WidgetLike<Tag> {
type Widget: 'static;
type Widget: Widget + ?Sized + Unsize<dyn Widget> + 'static;
fn add(self, ui: &mut Ui) -> WidgetHandle<Self::Widget>;
@@ -27,24 +28,15 @@ pub trait WidgetLike<Tag> {
}
pub trait WidgetArrLike<const LEN: usize, Tag> {
type Ws;
fn ui(self, ui: &mut Ui) -> WidgetArr<LEN, Self::Ws>;
fn ui(self, ui: &mut Ui) -> WidgetArr<LEN>;
}
impl<const LEN: usize, Ws> WidgetArrLike<LEN, ArrTag> for WidgetArr<LEN, Ws> {
type Ws = Ws;
fn ui(self, _: &mut Ui) -> WidgetArr<LEN, Ws> {
impl<const LEN: usize> WidgetArrLike<LEN, ArrTag> for WidgetArr<LEN> {
fn ui(self, _: &mut Ui) -> WidgetArr<LEN> {
self
}
}
impl<W: WidgetLike<WidgetTag>> WidgetArrLike<1, WidgetTag> for W {
type Ws = (W::Widget,);
fn ui(self, ui: &mut Ui) -> WidgetArr<1, (W::Widget,)> {
WidgetArr::new([self.add(ui).any()])
}
}
// I hate this language it's so bad why do I even use it
macro_rules! impl_widget_arr {
($n:expr;$($W:ident)*) => {
@@ -52,12 +44,11 @@ macro_rules! impl_widget_arr {
};
($n:expr;$($W:ident)*;$($Tag:ident)*) => {
impl<$($W: WidgetLike<$Tag>,$Tag,)*> WidgetArrLike<$n, ($($Tag,)*)> for ($($W,)*) {
type Ws = ($($W::Widget,)*);
fn ui(self, ui: &mut Ui) -> WidgetArr<$n, ($($W::Widget,)*)> {
fn ui(self, ui: &mut Ui) -> WidgetArr<$n> {
#[allow(non_snake_case)]
let ($($W,)*) = self;
WidgetArr::new(
[$($W.add(ui).cast_type(),)*],
[$($W.add(ui),)*],
)
}
}

View File

@@ -1,12 +1,12 @@
use crate::{Len, Painter, SizeCtx, Ui};
use std::{any::Any, marker::PhantomData};
use std::any::Any;
mod id;
mod handle;
mod like;
mod tag;
mod widgets;
pub use id::*;
pub use handle::*;
pub use like::*;
pub use tag::*;
pub use widgets::*;
@@ -30,20 +30,16 @@ impl Widget for () {
/// 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
/// don't need to be IDs yet
pub trait WidgetFn<W: Widget>: FnOnce(&mut Ui) -> W {}
impl<W: Widget, F: FnOnce(&mut Ui) -> W> WidgetFn<W> for F {}
pub trait WidgetFn<W: Widget + ?Sized>: FnOnce(&mut Ui) -> W {}
impl<W: Widget + ?Sized, F: FnOnce(&mut Ui) -> W> WidgetFn<W> for F {}
pub struct WidgetArr<const LEN: usize, Ws> {
pub struct WidgetArr<const LEN: usize> {
pub arr: [WidgetHandle; LEN],
_pd: PhantomData<Ws>,
}
impl<const LEN: usize, Ws> WidgetArr<LEN, Ws> {
impl<const LEN: usize> WidgetArr<LEN> {
pub fn new(arr: [WidgetHandle; LEN]) -> Self {
Self {
arr,
_pd: PhantomData,
}
Self { arr }
}
}

View File

@@ -1,3 +1,5 @@
use std::marker::Unsize;
use super::*;
pub struct ArrTag;
@@ -19,7 +21,7 @@ impl<W: Widget, F: FnOnce(&mut Ui) -> W> WidgetLike<FnTag> for F {
}
pub struct IdTag;
impl<W: 'static> WidgetLike<IdTag> for WidgetHandle<W> {
impl<W: ?Sized + Widget + Unsize<dyn Widget> + 'static> WidgetLike<IdTag> for WidgetHandle<W> {
type Widget = W;
fn add(self, _: &mut Ui) -> WidgetHandle<W> {
self
@@ -27,10 +29,11 @@ impl<W: 'static> WidgetLike<IdTag> for WidgetHandle<W> {
}
pub struct IdFnTag;
impl<W: 'static, F: FnOnce(&mut Ui) -> WidgetHandle<W>> WidgetLike<IdFnTag> for F {
impl<W: ?Sized + Widget + Unsize<dyn Widget> + 'static, F: FnOnce(&mut Ui) -> WidgetHandle<W>>
WidgetLike<IdFnTag> for F
{
type Widget = W;
fn add(self, ui: &mut Ui) -> WidgetHandle<W> {
self(ui)
}
}

View File

@@ -46,11 +46,11 @@ impl Widgets {
WidgetWrapper::new(data.widget.as_mut(), &mut data.borrowed)
}
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget> {
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget> where I::Widget: Sized {
self.get_dyn(id.id())?.as_any().downcast_ref()
}
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget> {
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget> where I::Widget: Sized {
self.get_dyn_mut(id.id())?.as_any_mut().downcast_mut()
}

View File

@@ -1,3 +1,5 @@
use std::{cell::RefCell, rc::Rc};
use cosmic_text::Family;
use iris::prelude::*;
use len_fns::*;
@@ -8,7 +10,7 @@ fn main() {
}
pub struct Client {
info: WidgetHandle<Text>,
info: WidgetView<Text>,
}
event_ctx!(Client);
@@ -37,7 +39,8 @@ impl DefaultAppState for Client {
.width(rest(3)),
)
.span(Dir::RIGHT)
.add(ui);
.add(ui)
.handles();
let span_test = (
rrect.color(Color::GREEN).width(100),
@@ -50,8 +53,7 @@ impl DefaultAppState for Client {
.span(Dir::LEFT)
.add(ui);
let span_add = Span::empty(Dir::RIGHT).add(ui);
let span_add_ = span_add.clone();
let span_add = Span::empty(Dir::RIGHT).add(ui).handles();
let add_button = rect(Color::LIME)
.radius(30)
@@ -60,21 +62,20 @@ impl DefaultAppState for Client {
.ui
.add(image(include_bytes!("assets/sungals.png")).center())
.any();
ctx.ui[&span_add_].children.push(child);
ctx.ui[span_add.1].children.push(child);
})
.sized((150, 150))
.align(Align::BOT_RIGHT);
let span_add_ = span_add.clone();
let del_button = rect(Color::RED)
.radius(30)
.on(CursorSense::click(), move |ctx| {
ctx.ui[&span_add_].children.pop();
ctx.ui[span_add.1].children.pop();
})
.sized((150, 150))
.align(Align::BOT_LEFT);
let span_add_test = (span_add, add_button, del_button).stack().add(ui);
let span_add_test = (span_add.0, add_button, del_button).stack().add(ui);
let btext = |content| wtext(content).size(30);
@@ -99,8 +100,8 @@ impl DefaultAppState for Client {
.span(Dir::DOWN)
.add(ui);
let texts = Span::empty(Dir::DOWN).gap(10).add(ui);
let msg_area = texts.clone().scroll().masked().background(rect(Color::SKY));
let texts = Span::empty(Dir::DOWN).gap(10).add(ui).handles();
let msg_area = texts.0.scroll().masked().background(rect(Color::SKY));
let add_text = wtext("add")
.editable(false)
.text_align(Align::LEFT)
@@ -115,18 +116,19 @@ impl DefaultAppState for Client {
.wrap(true)
.attr::<Selectable>(());
let msg_box = text.background(rect(Color::WHITE.darker(0.5))).add(ctx.ui);
ctx.ui[&texts].children.push(msg_box.any());
ctx.ui[texts.1].children.push(msg_box.any());
})
.add(ui);
.add(ui)
.handles();
let text_edit_scroll = (
msg_area.height(rest(1)),
(
Rect::new(Color::WHITE.darker(0.9)),
(
add_text.clone().width(rest(1)),
add_text.0.width(rest(1)),
Rect::new(Color::GREEN)
.on(CursorSense::click(), move |ctx| {
ctx.ui.run_event(ctx.state, &add_text, Submit, ());
ctx.ui.run_event(ctx.state, add_text.1, Submit, ());
})
.sized((40, 40)),
)
@@ -141,13 +143,26 @@ impl DefaultAppState for Client {
.span(Dir::DOWN)
.add(ui);
let main = pad_test.clone().pad(10).add(ui);
let main = WidgetPtr::new().add(ui).handles();
let switch_button = |color, to: WidgetHandle, label| {
let main_ = main.clone();
let vals = Rc::new(RefCell::new((0, Vec::new())));
let mut switch_button = |color, to: WidgetHandle, label| {
let vec = &mut vals.borrow_mut().1;
let i = vec.len();
if vec.is_empty() {
vec.push(None);
ui[main.1].set(to);
} else {
vec.push(Some(to));
}
let vals = vals.clone();
let rect = rect(color)
.on(CursorSense::click(), move |ctx| {
ctx.ui[&main_.clone()].inner = to.clone();
let (prev, vec) = &mut *vals.borrow_mut();
if let Some(h) = vec[i].take() {
vec[*prev] = ctx.ui[main.1].replace(h);
*prev = i;
}
ctx.ui[ctx.id].color = color.darker(0.3);
})
.on(
@@ -163,26 +178,26 @@ impl DefaultAppState for Client {
};
let tabs = (
switch_button(Color::RED, pad_test.any(), "pad"),
switch_button(Color::GREEN, span_test.any(), "span"),
switch_button(Color::BLUE, span_add_test.any(), "image span"),
switch_button(Color::MAGENTA, text_test.any(), "text layout"),
switch_button(Color::RED, pad_test.0, "pad"),
switch_button(Color::GREEN, span_test, "span"),
switch_button(Color::BLUE, span_add_test, "image span"),
switch_button(Color::MAGENTA, text_test, "text layout"),
switch_button(
Color::YELLOW.mul_rgb(0.5),
text_edit_scroll.any(),
text_edit_scroll,
"text edit scroll",
),
)
.span(Dir::RIGHT);
let info = wtext("").add(ui);
let info_sect = info.clone().pad(10).align(Align::RIGHT);
let info = wtext("").add(ui).handles();
let info_sect = info.0.pad(10).align(Align::RIGHT);
((tabs.height(40), main).span(Dir::DOWN), info_sect)
((tabs.height(40), main.0.pad(10)).span(Dir::DOWN), info_sect)
.stack()
.set_root(ui);
Self { info }
Self { info: info.1 }
}
fn window_event(&mut self, _: WindowEvent, ui: &mut Ui, state: &UiState) {
@@ -192,8 +207,8 @@ impl DefaultAppState for Client {
ui.active_widgets(),
state.renderer.ui.view_count()
);
if new != *ui[&self.info].content {
*ui[&self.info].content = new;
if new != *ui[self.info].content {
*ui[self.info].content = new;
}
if ui.needs_redraw() {
state.window.request_redraw();

View File

@@ -5,23 +5,18 @@ use winit::dpi::{LogicalPosition, LogicalSize};
pub struct Selector;
impl<W: 'static + Widget> WidgetAttr<W> for Selector {
type Input = WidgetHandle<TextEdit>;
type Input = WidgetView<TextEdit>;
fn run(ui: &mut Ui, container: &WidgetHandle<W>, id: Self::Input) {
let container = container.clone();
ui.register_event(
&container.clone(),
CursorSense::click_or_drag(),
move |mut ctx| {
fn run(ui: &mut Ui, container: WidgetView<W>, id: Self::Input) {
ui.register_event(&container, CursorSense::click_or_drag(), move |mut ctx| {
let ui = ctx.ui;
let region = ui.window_region(&id).unwrap();
let id_pos = region.top_left;
let container_pos = ui.window_region(&container).unwrap().top_left;
ctx.data.cursor += container_pos - id_pos;
ctx.data.size = region.size();
select(ui, id.clone(), ctx.state, ctx.data);
},
);
select(ui, id, ctx.state, ctx.data);
});
}
}
@@ -30,15 +25,14 @@ pub struct Selectable;
impl WidgetAttr<TextEdit> for Selectable {
type Input = ();
fn run(ui: &mut Ui, id: &WidgetHandle<TextEdit>, _: Self::Input) {
let id = id.clone();
ui.register_event(&id.clone(), CursorSense::click_or_drag(), move |ctx| {
select(ctx.ui, id.clone(), ctx.state, ctx.data);
fn run(ui: &mut Ui, id: WidgetView<TextEdit>, _: Self::Input) {
ui.register_event(&id, CursorSense::click_or_drag(), move |ctx| {
select(ctx.ui, id, ctx.state, ctx.data);
});
}
}
fn select(ui: &mut Ui, id: WidgetHandle<TextEdit>, state: &mut UiState, data: CursorData) {
fn select(ui: &mut Ui, id: WidgetView<TextEdit>, state: &mut UiState, data: CursorData) {
let now = Instant::now();
let recent = (now - state.last_click) < Duration::from_millis(300);
state.last_click = now;

View File

@@ -30,7 +30,7 @@ pub struct DefaultState<AppState> {
pub struct UiState {
pub renderer: UiRenderer,
pub input: Input,
pub focus: Option<WidgetHandle<TextEdit>>,
pub focus: Option<WidgetView<TextEdit>>,
pub clipboard: Clipboard,
pub window: Arc<Window>,
pub ime: usize,
@@ -91,7 +91,7 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
let input_changed = ui_state.input.event(&event);
let cursor_state = ui_state.cursor_state().clone();
let old = ui_state.focus.clone();
let old = ui_state.focus;
if cursor_state.buttons.left.is_start() {
ui_state.focus = None;
}
@@ -121,10 +121,9 @@ impl<State: DefaultAppState> AppState for DefaultState<State> {
ui_state.renderer.resize(size)
}
WindowEvent::KeyboardInput { event, .. } => {
if let Some(sel) = &ui_state.focus
if let Some(sel) = ui_state.focus
&& event.state.is_pressed()
{
let sel = &sel.clone();
let mut text = sel.edit(ui);
match text.apply_event(event, &ui_state.input.modifiers) {
TextInputResult::Unfocus => {

View File

@@ -9,20 +9,20 @@ macro_rules! event_ctx {
#[allow(unused_imports)]
use $crate::prelude::*;
pub trait EventableCtx<W, Tag, Ctx: 'static> {
pub trait EventableCtx<WL: WidgetLike<Tag>, Tag, Ctx: 'static> {
fn on<E: Event>(
self,
event: E,
f: impl WidgetEventFn<Ctx, E::Data, W>,
) -> impl WidgetIdFn<W> + EventableCtx<W, IdFnTag, Ctx>;
f: impl WidgetEventFn<Ctx, E::Data, WL::Widget>,
) -> impl WidgetIdFn<WL::Widget>;
}
impl<WL: WidgetLike<Tag>, Tag> EventableCtx<WL::Widget, Tag, $ty> for WL {
impl<WL: WidgetLike<Tag>, Tag> EventableCtx<WL, Tag, $ty> for WL {
fn on<E: Event>(
self,
event: E,
f: impl WidgetEventFn<$ty, E::Data, WL::Widget>,
) -> impl WidgetIdFn<WL::Widget> + EventableCtx<WL::Widget, IdFnTag, $ty> {
) -> impl WidgetIdFn<WL::Widget> {
eventable::Eventable::on(self, event, f)
}
}
@@ -47,7 +47,7 @@ pub mod eventable {
let id_ = id.weak();
ui.register_event(&id, event, move |ctx| {
f(EventIdCtx {
id: &id_,
id: id_,
state: ctx.state,
data: ctx.data,
ui: ctx.ui,

View File

@@ -2,6 +2,7 @@
#![feature(fn_traits)]
#![feature(gen_blocks)]
#![feature(associated_type_defaults)]
#![feature(unsize)]
mod default;
mod event;

View File

@@ -158,7 +158,7 @@ impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
Span {
children: self.children.ui(args.0).arr.to_vec(),
children: self.children.ui(args.0).arr.into_iter().collect(),
dir: self.dir,
gap: self.gap,
}

View File

@@ -55,7 +55,7 @@ impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
Stack {
children: self.children.ui(args.0).arr.to_vec(),
children: self.children.ui(args.0).arr.into_iter().collect(),
size: self.size,
}
}

View File

@@ -1,4 +1,5 @@
use crate::prelude::*;
use std::marker::{Sized, Unsize};
#[derive(Default)]
pub struct WidgetPtr {
@@ -28,3 +29,19 @@ impl Widget for WidgetPtr {
}
}
}
impl WidgetPtr {
pub fn new() -> Self {
Self::default()
}
pub fn set<W: ?Sized + Unsize<dyn Widget>>(&mut self, to: WidgetHandle<W>) {
self.inner = Some(to)
}
pub fn replace<W: ?Sized + Unsize<dyn Widget>>(
&mut self,
to: WidgetHandle<W>,
) -> Option<WidgetHandle> {
self.inner.replace(to)
}
}

View File

@@ -123,7 +123,7 @@ widget_trait! {
}
}
fn to_any(self) -> impl WidgetRet {
fn to_any(self) -> impl WidgetIdFn {
|ui| self.add(ui).any()
}
}